AddonBuilder::buildScreenshots()   C
last analyzed

Complexity

Conditions 12
Paths 54

Size

Total Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 70
rs 6.2278
c 0
b 0
f 0
cc 12
nc 54
nop 3

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
use Composer\Package\Package;
4
use Composer\Package\PackageInterface;
5
use Monolog\Formatter\LineFormatter;
6
use Monolog\Handler\SyslogHandler;
7
use SilverStripe\ModuleRatings\CheckSuite;
8
9
/**
10
 * Downloads an add-on and builds more details information about it.
11
 */
12
class AddonBuilder
13
{
14
15
    const ADDONS_DIR = 'addon-downloads';
16
17
    const SCREENSHOTS_DIR = 'screenshots';
18
19
    private $packagist;
20
21
    /**
22
     * @var CheckSuite
23
     */
24
    protected $checkSuite;
25
26
    public function __construct(PackagistService $packagist)
27
    {
28
        $this->packagist = $packagist;
29
    }
30
31
    public function build(Addon $addon)
32
    {
33
        putenv("GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no\"");
34
35
        $checkSuite = new CheckSuite();
36
        $this->setCheckSuite($checkSuite);
37
        // Provide the checksuite with a logger in case API calls fail
38
        $logger = new Monolog\Logger('module_ratings_logs', [
39
            new SyslogHandler('SilverStripe_log'),
40
        ]);
41
        $formatter = new LineFormatter("%level_name%: %message% %context% %extra%");
42
        $logger->setFormatter($formatter);
0 ignored issues
show
Bug introduced by
The method setFormatter() does not seem to exist on object<Monolog\Logger>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
43
        $checkSuite->setLogger($logger);
44
45
        $composer = $this->packagist->getComposer();
46
        $downloader = $composer->getDownloadManager();
0 ignored issues
show
Unused Code introduced by
$downloader is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
47
        $packageVersions = $this->packagist->getPackageVersions($addon->Name);
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
48
        $time = time();
49
50
        if (!$packageVersions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $packageVersions of type Composer\Package\PackageInterface[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
51
            throw new Exception('Could not find corresponding Packagist versions');
52
        }
53
54
        // Get the latest local and packagist version pair.
55
        $version = $addon->Versions()->filter('Development', true)->first();
0 ignored issues
show
Bug introduced by
The method Versions() does not exist on Addon. Did you maybe mean SortedVersions()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
56
        if (!$version) {
57
            echo "No versions found for " . $addon->Name . "; deleting orphan record.\n";
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
58
            $addon->delete();
59
            return;
60
        }
61
62
        foreach ($packageVersions as $packageVersion) {
63
            if ($packageVersion->getVersionNormalized() != $version->Version) {
0 ignored issues
show
Bug introduced by
The method getVersionNormalized() does not exist on Composer\Package\PackageInterface. Did you maybe mean getVersion()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
64
                continue;
65
            }
66
67
            if (defined('SS_ADDONS_DOWNLOAD_PATH')) {
68
                $path = SS_ADDONS_DOWNLOAD_PATH . '/' . $addon->Name;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
69
            } else {
70
                $path = implode('/', array(
71
                    TEMP_FOLDER, self::ADDONS_DIR, $addon->Name
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
72
                ));
73
            }
74
75
            // Convert PackagistAPI result into class compatible with Composer logic
76
            $package = new Package(
77
                $addon->Name,
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
78
                $packageVersion->getVersionNormalized(),
0 ignored issues
show
Bug introduced by
The method getVersionNormalized() does not exist on Composer\Package\PackageInterface. Did you maybe mean getVersion()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
79
                $packageVersion->getVersion()
80
            );
81
82
            if ($extra = $packageVersion->getExtra()) {
83
                $package->setExtra((array) $extra);
84
            }
85
            if ($source = $packageVersion->getSource()) {
0 ignored issues
show
Bug introduced by
The method getSource() does not exist on Composer\Package\PackageInterface. Did you maybe mean getSourceMirrors()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
86
                $package->setSourceUrl($source->getUrl());
87
                $package->setSourceType($source->getType());
88
                $package->setSourceReference($source->getReference());
89
            }
90
            if ($dist = $packageVersion->getDist()) {
0 ignored issues
show
Bug introduced by
The method getDist() does not exist on Composer\Package\PackageInterface. Did you maybe mean getDistMirrors()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
91
                $package->setDistUrl($dist->getUrl());
92
                $package->setDistType($dist->getType());
93
                $package->setDistReference($dist->getReference());
94
            }
95
96
            try {
97
                $this->download($package, $path);
98
99
            // If there's an error, mark this version as bad
100
            } catch (RuntimeException $e) {
101
                echo "Add-on " . $addon->Name . " couldn't be downloaded; deleting from database.\n";
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
102
                echo "Error message: " . $e->getMessage() . "\n";
103
                $addon->delete();
104
                return;
105
            }
106
107
            $this->buildReadme($addon, $path);
108
            $this->buildScreenshots($addon, $package, $path);
109
            $this->rateModule($addon, $path);
110
        }
111
112
        $addon->LastBuilt = $time;
0 ignored issues
show
Documentation introduced by
The property LastBuilt does not exist on object<Addon>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
113
        $addon->write();
114
    }
115
116
    protected function download(PackageInterface $package, $path)
117
    {
118
        $this->packagist
119
            ->getComposer()
120
            ->getDownloadManager()
121
            ->download($package, $path);
122
    }
123
124
    /**
125
     * Parses a readme file from markdown to HTML, then purifies it
126
     * @param Addon  $addon
127
     * @param string $path
128
     */
129
    protected function buildReadme(Addon $addon, $path)
130
    {
131
        $candidates = array(
132
            'README.md',
133
            'README.markdown',
134
            'README.mdown',
135
            'docs/en/index.md'
136
        );
137
138
        foreach ($candidates as $candidate) {
139
            $lower = strtolower($candidate);
140
            $paths = array("$path/$candidate", "$path/$lower");
141
142
            foreach ($paths as $path) {
143
                if (!file_exists($path)) {
144
                    return;
145
                }
146
147
                $parser = GitHubMarkdownService::create();
148
                if ($context = $this->getGitHubContext($addon)) {
149
                    $parser->setContext($context);
150
                }
151
                $readme = $parser->toHtml(file_get_contents($path));
152
153
                if (empty($readme)) {
154
                    return;
155
                }
156
157
                $readme = $parser->toHtml(file_get_contents($path));
158
159
                $purifier = new HTMLPurifier();
160
                $readme = $purifier->purify($readme, array(
161
                    'Cache.SerializerPath' => TEMP_FOLDER
162
                ));
163
164
                $readme = $this->replaceRelativeLinks($addon, $readme);
165
                $addon->Readme = $readme;
0 ignored issues
show
Documentation introduced by
The property Readme does not exist on object<Addon>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
166
                return;
167
            }
168
        }
169
    }
170
171
    /**
172
     * Determine if the repository is from GitHub, and if so then return the "context" (vendor/module) from the path
173
     *
174
     * @param  Addon $addon
175
     * @return string|false
176
     */
177
    public function getGitHubContext(Addon $addon)
178
    {
179
        $repository = $addon->Repository;
0 ignored issues
show
Documentation introduced by
The property Repository does not exist on object<Addon>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
180
        if (stripos($repository, '://github.com/') === false) {
181
            return false;
182
        }
183
184
        preg_match('/^http(?:s?):\/\/github\.com\/(?<module>.*)(\.git)?$/U', $repository, $matches);
185
186
        if (isset($matches['module'])) {
187
            return $matches['module'];
188
        }
189
190
        return false;
191
    }
192
193
    /**
194
     * Given an addon and a parsed HTML readme string, find and replace relative links with absolute
195
     * repository path links. This method applies to GitHub repositories only.
196
     *
197
     * @param  Addon  $addon
198
     * @param  string $readme
199
     * @return string
200
     */
201
    public function replaceRelativeLinks(Addon $addon, $readme)
202
    {
203
        if (!$this->hasGitHubRepository($addon)) {
204
            return $readme;
205
        }
206
207
        $dom = new DOMDocument;
208
        // LibXML needs a wrapper element...
209
        $dom->loadHTML('<div>' . $readme . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
210
        $xpath = new DOMXPath($dom);
211
212
        // Select all anchors and images in the readme document
213
        $query = $xpath->query('//*[self::a or self::img]');
214
215
        foreach ($query as $element) { /** @var DOMElement $element */
216
            $attribute = ($element->nodeName === 'a') ? 'href' : 'src';
217
            $path = $element->getAttribute($attribute);
218
            if (!$this->isRelativeUri($path)) {
219
                continue;
220
            }
221
222
            // See GitHub readmes for example
223
            $folder = ($attribute === 'href') ? 'blob' : 'raw';
224
            $defaultBranch = 'master'; // Is this safe to assume?
225
226
            $element->setAttribute(
227
                $attribute,
228
                implode('/', array($addon->Repository, $folder, $defaultBranch, $path))
0 ignored issues
show
Documentation introduced by
The property Repository does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
229
            );
230
        }
231
232
        // Return the inner HTML of the wrapper div... Reference: stackoverflow.com/a/39193507/2812842
233
        $node = $dom->getElementsByTagName('div')->item(0);
234
        return implode(array_map([$node->ownerDocument, 'saveHTML'], iterator_to_array($node->childNodes)));
235
    }
236
237
    /**
238
     * Decide whether a URI path is relative or not. The regex pattern matches prefixes that start with
239
     * a protocol, a slash or a hash. If they don't start with those things, then they are deemed to be
240
     * relative paths.
241
     *
242
     * @param  string $path
243
     * @return bool
244
     */
245
    public function isRelativeUri($path)
246
    {
247
        return !preg_match('/(^(?:https?:\/\/|\/|#).*$)/', $path);
248
    }
249
250
    /**
251
     * Determine whether an addon is hosted on GitHub
252
     *
253
     * @param  Addon $addon
254
     * @return bool
255
     */
256
    public function hasGitHubRepository(Addon $addon)
257
    {
258
        return (strpos($addon->Repository, 'github.com') !== false);
0 ignored issues
show
Documentation introduced by
The property Repository does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
259
    }
260
261
    private function buildScreenshots(Addon $addon, PackageInterface $package, $path)
262
    {
263
        $extra = $package->getExtra();
264
        $screenshots = array();
265
        $target = self::SCREENSHOTS_DIR . '/' . $addon->Name;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
266
267
        if (isset($extra['screenshots'])) {
268
            $screenshots = (array) $extra['screenshots'];
269
        } elseif (isset($extra['screenshot'])) {
270
            $screenshots = (array) $extra['screenshot'];
271
        }
272
273
        // Delete existing screenshots.
274
        foreach ($addon->Screenshots() as $screenshot) {
0 ignored issues
show
Documentation Bug introduced by
The method Screenshots does not exist on object<Addon>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
275
            $screenshot->delete();
276
        }
277
278
        $addon->Screenshots()->removeAll();
0 ignored issues
show
Documentation Bug introduced by
The method Screenshots does not exist on object<Addon>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
279
280
        foreach ($screenshots as $screenshot) {
281
            if (!is_string($screenshot)) {
282
                continue;
283
            }
284
285
            $scheme = parse_url($screenshot, PHP_URL_SCHEME);
286
287
            // Handle absolute image URLs.
288
            if ($scheme == 'http' || $scheme == 'https') {
289
                $temp = TEMP_FOLDER . '/' . md5($screenshot);
290
291
                if (!copy($screenshot, $temp)) {
292
                    continue;
293
                }
294
295
                $data = array(
296
                    'name' => basename($screenshot),
297
                    'size' => filesize($temp),
298
                    'tmp_name' => $temp,
299
                    'error' => 0
300
                );
301
            // Handle images that are included in the repository.
302
            } else {
303
                $source = $path . '/' . ltrim($screenshot, '/');
304
305
                // Prevent directory traversal.
306
                if ($source != realpath($source)) {
307
                    continue;
308
                }
309
310
                if (!file_exists($source)) {
311
                    continue;
312
                }
313
314
                $data = array(
315
                    'name' => basename($source),
316
                    'size' => filesize($source),
317
                    'tmp_name' => $source,
318
                    'error' => 0
319
                );
320
            }
321
322
            $upload = new Upload();
323
            $upload->setValidator(new AddonBuilderScreenshotValidator());
324
            $upload->load($data, $target);
0 ignored issues
show
Documentation introduced by
$target is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
325
326
            if ($file = $upload->getFile()) {
327
                $addon->Screenshots()->add($file);
0 ignored issues
show
Documentation Bug introduced by
The method Screenshots does not exist on object<Addon>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
328
            }
329
        }
330
    }
331
332
    /**
333
     * Use the Rating check runner to generate an automated rating for this module
334
     *
335
     * @param Addon $addon
336
     * @param string $modulePath
337
     */
338
    protected function rateModule(Addon $addon, $modulePath)
339
    {
340
        $suite = $this->getCheckSuite();
341
        $suite->setModuleRoot($modulePath);
342
        $repositoryUrl = $addon->Repository;
0 ignored issues
show
Documentation introduced by
The property Repository does not exist on object<Addon>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
343
        // Get repository slug from URL
344
        preg_match('~.*\/(.+\/.+)(?:\.git)?$~', $repositoryUrl, $matches);
345
        $suite->setRepositorySlug(!empty($matches[1]) ? $matches[1] : '');
346
347
        try {
348
            $suite->run();
349
        } catch (\Exception $e) {
350
            echo $e->getMessage();
351
            return;
352
        }
353
        /** @var array $checkDetails */
354
        $checkDetails = $suite->getCheckDetails();
355
356
        // Pull part of the check details out that we want (code and points)
357
        $details = array();
358
        foreach ($checkDetails as $checkCode => $metrics) {
359
            $details[$checkCode] = $metrics['points'];
360
        }
361
362
        // Total score for the check suite
363
        $addon->Rating = $suite->getScore();
0 ignored issues
show
Documentation introduced by
The property Rating does not exist on object<Addon>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
364
        // Individual checks and scores for each
365
        $addon->RatingDetails = Convert::raw2json($details);
0 ignored issues
show
Documentation introduced by
The property RatingDetails does not exist on object<Addon>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
366
    }
367
368
    /**
369
     * @return CheckSuite
370
     */
371
    public function getCheckSuite()
372
    {
373
        return $this->checkSuite;
374
    }
375
376
    /**
377
     * @param CheckSuite $checkSuite
378
     * @return $this
379
     */
380
    public function setCheckSuite($checkSuite)
381
    {
382
        $this->checkSuite = $checkSuite;
383
        return $this;
384
    }
385
}
386