Completed
Pull Request — master (#166)
by Marcel
09:53 queued 05:25
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
        return response('FAILED to get Domain', 500);
0 ignored issues
show
Bug Best Practice introduced by
The expression return response('FAILED to get Domain', 500) returns the type Illuminate\Http\Response which is incompatible with the documented return type App\Domain.
Loading history...
138
    }
139
140
    /**
141
     * Returns a valid URL for the given domain (hostname) that is reachable.
142
     *
143
     * @param string $domain Domain / Hostname to get the URL for.
144
     * @param Client $client Guzzle Client for PHPUnit testing only.
145
     *
146
     * @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...
147
     */
148
    public static function getDomainURL(string $domain, Client $client = null)
149
    {
150
        $testDomain = $domain;
151
152
        // Pings via guzzle
153
        $client = $client ?: new Client([
154
            'headers' => [
155
                'User-Agent' => config('app.userAgent'),
156
            ],
157
            'timeout' => 25,
158
            'verify'  => false,
159
        ]);
160
161
        $scheme = parse_url($testDomain, PHP_URL_SCHEME);
162
163
        // if user entered a URL -> test if available
164
        if ($scheme) {
165
            try {
166
                $testURL = $testDomain;
167
                $response = $client->request('GET', $testURL);
168
                if ($response->getStatusCode() === 200) {
169
                    return $testURL;
170
                }
171
            } catch (\Exception $e) {
172
                // if not available, remove scheme from domain
173
                // scheme = https; + 3 for ://
174
                $testDomain = substr($domain, strlen($scheme) + 3);
175
            }
176
        }
177
178
        // Domain is available via https://
179
        try {
180
            $testURL = 'https://'.$testDomain;
181
            $response = $client->request('GET', $testURL);
182
            if ($response->getStatusCode() === 200) {
183
                return $testURL;
184
            }
185
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
186
        }
187
188
        // Domain is available via http://
189
        try {
190
            $testURL = 'http://'.$testDomain;
191
            $response = $client->request('GET', $testURL);
192
            if ($response->getStatusCode() === 200) {
193
                return $testURL;
194
            }
195
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
196
        }
197
198
        // Domain is available with or without www
199
        // if www. is there, than remove it, otherwise add it
200
        $testDomain = substr($testDomain, 0, 4) === 'www.' ? substr($testDomain, 4) : 'www.'.$testDomain;
201
202
        try {
203
            $testURL = 'https://'.$testDomain;
204
            $response = $client->request('GET', $testURL);
205
            if ($response->getStatusCode() === 200) {
206
                return collect([
207
                    'notAvailable'         => $domain,
208
                    'alternativeAvailable' => $testDomain,
209
                ]);
210
            }
211
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
212
        }
213
214
        try {
215
            $testURL = 'http://'.$testDomain;
216
            $response = $client->request('GET', $testURL);
217
            if ($response->getStatusCode() === 200) {
218
                return collect([
219
                    'notAvailable'         => $domain,
220
                    'alternativeAvailable' => $testDomain,
221
                ]);
222
            }
223
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
224
        }
225
    }
226
}
227