Completed
Pull Request — master (#154)
by
unknown
04:41 queued 52s
created

Domain::getDomainURL()   F

Complexity

Conditions 14
Paths 1529

Size

Total Lines 76
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 44
nc 1529
nop 2
dl 0
loc 76
rs 2.1
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App;
4
5
use GuzzleHttp\Client;
6
use Illuminate\Database\Eloquent\Model;
7
use Keygen\Keygen;
8
use Log;
9
10
const METATAGNAME = 'siwecostoken';
11
12
/**
13
 * App\Domain.
14
 *
15
 * @property int $id
16
 * @property \Carbon\Carbon|null $created_at
17
 * @property \Carbon\Carbon|null $updated_at
18
 * @property string $domain
19
 * @property string $domain_token
20
 * @property int|null $token_id
21
 * @property int $verified
22
 * @property-read \App\Token|null $token
23
 *
24
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereCreatedAt( $value )
25
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereDomain( $value )
26
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereDomainToken( $value )
27
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereId( $value )
28
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereTokenId( $value )
29
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereUpdatedAt( $value )
30
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereVerified( $value )
31
 * @mixin \Eloquent
32
 *
33
 * @property \Carbon\Carbon|null $last_notification
34
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Scan[] $scans
35
 *
36
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereLastNotification( $value )
37
 */
38
class Domain extends Model
39
{
40
    protected $fillable = ['domain', 'token_id', 'verified', 'domain_token'];
41
42
    public function __construct(array $attributes = [])
43
    {
44
        parent::__construct($attributes);
45
46
        if (array_key_exists('domain', $attributes)) {
47
            $this->domain = $attributes['domain'];
48
        }
49
        if (array_key_exists('token', $attributes)) {
50
            $token = Token::getTokenByString($attributes['token']);
51
            $this->token_id = $token->id;
52
            $this->domain_token = Keygen::alphanum(64)->generate();
53
        }
54
    }
55
56
    /**
57
     * @return bool
58
     */
59
    public function checkMetatags()
60
    {
61
        try {
62
            ini_set('user_agent', config('app.userAgent'));
63
            $tags = get_meta_tags($this->domain);
64
            foreach ($tags as $tagkey => $tagvalue) {
65
                if ($tagkey == METATAGNAME) {
66
                    if ($tagvalue == $this->domain_token) {
67
                        /*Hooray site is activated*/
68
                        $this->verified = 1;
69
                        $this->save();
70
71
                        return true;
72
                    }
73
                }
74
            }
75
        } catch (\Exception $exception) {
76
            Log::warning($exception->getMessage());
77
        }
78
79
        return false;
80
    }
81
82
    public function token()
83
    {
84
        return $this->belongsTo(Token::class);
85
    }
86
87
    /**
88
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
89
     */
90
    public function scans()
91
    {
92
        return $this->hasMany(Scan::class, 'url', 'domain');
93
    }
94
95
    /**
96
     * @return bool
97
     */
98
    public function checkHtmlPage()
99
    {
100
        /*get the content of the page. there should be nothing, except the activationkey*/
101
        ini_set('user_agent', config('app.userAgent'));
102
        $url = $this->domain.'/'.$this->domain_token.'.html';
103
104
        try {
105
            $pageRequest = file_get_contents($url);
106
            if ($pageRequest == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $pageRequest of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
107
                return false;
108
            }
109
            if (strpos($pageRequest, $this->domain_token) !== false) {
110
                $this->verified = 1;
111
                $this->save();
112
113
                return true;
114
            }
115
        } catch (\Exception $exception) {
116
            Log::warning($exception->getMessage());
117
        }
118
119
        return false;
120
    }
121
122
    /**
123
     * @param string $domain
124
     * @param int    $tokenId
125
     *
126
     * @return Domain
127
     */
128
    public static function getDomainOrFail(string $domain, int $tokenId)
129
    {
130
        Log::warning('DOMAIN: '.$domain.' ID: '.$tokenId);
131
132
        $domain = self::where(['domain' => $domain, 'token_id' => $tokenId])->first();
133
        if ($domain instanceof self) {
134
            return $domain;
135
        }
136
    }
137
138
    /**
139
     * Returns a valid URL for the given domain (hostname) that is reachable.
140
     *
141
     * @param string $domain Domain / Hostname to get the URL for.
142
     * @param Client $client Guzzle Client for PHPUnit testing only.
143
     *
144
     * @return string|Collection|null A valid URL incl. schema if valid. Collection with alternative URL if the given one was not valid or or NULL if no URL is available.
0 ignored issues
show
Bug introduced by
The type App\Collection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
145
     */
146
    public static function getDomainURL(string $domain, Client $client = null)
147
    {
148
        $testDomain = $domain;
149
150
        // Pings via guzzle
151
        $client = $client ?: new Client([
152
            'headers' => [
153
                'User-Agent' => config('app.userAgent'),
154
            ],
155
            'timeout' => 25,
156
            'verify'  => false,
157
        ]);
158
159
        $scheme = parse_url($testDomain, PHP_URL_SCHEME);
160
161
        // if user entered a URL -> test if available
162
        if ($scheme) {
163
            try {
164
                $testURL = $testDomain;
165
                $response = $client->request('GET', $testURL);
166
                if ($response->getStatusCode() === 200) {
167
                    return $testURL;
168
                }
169
            } catch (\Exception $e) {
170
                // if not available, remove scheme from domain
171
                // scheme = https; + 3 for ://
172
                $testDomain = substr($domain, strlen($scheme) + 3);
173
            }
174
        }
175
176
        // Domain is available via https://
177
        try {
178
            $testURL = 'https://'.$testDomain;
179
            $response = $client->request('GET', $testURL);
180
            if ($response->getStatusCode() === 200) {
181
                return $testURL;
182
            }
183
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
184
        }
185
186
        // Domain is available via http://
187
        try {
188
            $testURL = 'http://'.$testDomain;
189
            $response = $client->request('GET', $testURL);
190
            if ($response->getStatusCode() === 200) {
191
                return $testURL;
192
            }
193
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
194
        }
195
196
        // Domain is available with or without www
197
        // if www. is there, than remove it, otherwise add it
198
        $testDomain = substr($testDomain, 0, 4) === 'www.' ? substr($testDomain, 4) : 'www.'.$testDomain;
199
200
        try {
201
            $testURL = 'https://'.$testDomain;
202
            $response = $client->request('GET', $testURL);
203
            if ($response->getStatusCode() === 200) {
204
                return collect([
205
                    'notAvailable'         => $domain,
206
                    'alternativeAvailable' => $testDomain,
207
                ]);
208
            }
209
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
210
        }
211
212
        try {
213
            $testURL = 'http://'.$testDomain;
214
            $response = $client->request('GET', $testURL);
215
            if ($response->getStatusCode() === 200) {
216
                return collect([
217
                    'notAvailable'         => $domain,
218
                    'alternativeAvailable' => $testDomain,
219
                ]);
220
            }
221
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
222
        }
223
    }
224
}
225