AddonBuilder   B
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 279
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 10
dl 0
loc 279
rs 8.6
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B build() 0 48 6
A download() 0 7 1
B buildReadme() 0 41 6
A getGitHubContext() 0 15 3
B replaceRelativeLinks() 0 35 6
A isRelativeUri() 0 4 1
A hasGitHubRepository() 0 4 1
C buildScreenshots() 0 70 12
1
<?php
2
3
use Composer\Package\Package;
4
use Composer\Package\PackageInterface;
5
6
/**
7
 * Downloads an add-on and builds more details information about it.
8
 */
9
class AddonBuilder
10
{
11
12
    const ADDONS_DIR = 'add-ons';
13
14
    const SCREENSHOTS_DIR = 'screenshots';
15
16
    private $packagist;
17
18
    public function __construct(PackagistService $packagist)
19
    {
20
        $this->packagist = $packagist;
21
    }
22
23
    public function build(Addon $addon)
24
    {
25
        $composer = $this->packagist->getComposer();
26
        $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...
27
        $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...
28
        $time = time();
29
30
        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...
31
            throw new Exception('Could not find corresponding Packagist versions');
32
        }
33
34
        // Get the latest local and packagist version pair.
35
        $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...
36
        foreach ($packageVersions as $packageVersion) {
37
            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...
38
                continue;
39
            }
40
41
            $path = implode('/', array(
42
                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...
43
            ));
44
45
            // Convert PackagistAPI result into class compatible with Composer logic
46
            $package = new Package(
47
                $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
                $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...
49
                $packageVersion->getVersion()
50
            );
51
            $package->setExtra($packageVersion->getExtra());
52
            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...
53
                $package->setSourceUrl($source->getUrl());
54
                $package->setSourceType($source->getType());
55
                $package->setSourceReference($source->getReference());
56
            }
57
            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...
58
                $package->setDistUrl($dist->getUrl());
59
                $package->setDistType($dist->getType());
60
                $package->setDistReference($dist->getReference());
61
            }
62
63
            $this->download($package, $path);
64
            $this->buildReadme($addon, $path);
65
            $this->buildScreenshots($addon, $package, $path);
66
        }
67
68
        $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...
69
        $addon->write();
70
    }
71
72
    protected function download(PackageInterface $package, $path)
73
    {
74
        $this->packagist
75
            ->getComposer()
76
            ->getDownloadManager()
77
            ->download($package, $path);
78
    }
79
80
    /**
81
     * Parses a readme file from markdown to HTML, then purifies it
82
     * @param Addon  $addon
83
     * @param string $path
84
     */
85
    protected function buildReadme(Addon $addon, $path)
86
    {
87
        $candidates = array(
88
            'README.md',
89
            'README.markdown',
90
            'README.mdown',
91
            'docs/en/index.md'
92
        );
93
94
        foreach ($candidates as $candidate) {
95
            $lower = strtolower($candidate);
96
            $paths = array("$path/$candidate", "$path/$lower");
97
98
            foreach ($paths as $path) {
99
                if (!file_exists($path)) {
100
                    return;
101
                }
102
103
                $parser = GitHubMarkdownService::create();
104
                if ($context = $this->getGitHubContext($addon)) {
105
                    $parser->setContext($context);
106
                }
107
                $readme = $parser->toHtml(file_get_contents($path));
108
109
                if (empty($readme)) {
110
                    return;
111
                }
112
113
                $readme = $parser->toHtml(file_get_contents($path));
114
115
                $purifier = new HTMLPurifier();
116
                $readme = $purifier->purify($readme, array(
117
                    'Cache.SerializerPath' => TEMP_FOLDER
118
                ));
119
120
                $readme = $this->replaceRelativeLinks($addon, $readme);
121
                $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...
122
                return;
123
            }
124
        }
125
    }
126
127
    /**
128
     * Determine if the repository is from GitHub, and if so then return the "context" (vendor/module) from the path
129
     *
130
     * @param  Addon $addon
131
     * @return string|false
132
     */
133
    public function getGitHubContext(Addon $addon)
134
    {
135
        $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...
136
        if (stripos($repository, '://github.com/') === false) {
137
            return false;
138
        }
139
140
        preg_match('/^http(?:s?):\/\/github\.com\/(?<module>.*)(\.git)?$/U', $repository, $matches);
141
142
        if (isset($matches['module'])) {
143
            return $matches['module'];
144
        }
145
146
        return false;
147
    }
148
149
    /**
150
     * Given an addon and a parsed HTML readme string, find and replace relative links with absolute
151
     * repository path links. This method applies to GitHub repositories only.
152
     *
153
     * @param  Addon  $addon
154
     * @param  string $readme
155
     * @return string
156
     */
157
    public function replaceRelativeLinks(Addon $addon, $readme)
158
    {
159
        if (!$this->hasGitHubRepository($addon)) {
160
            return $readme;
161
        }
162
163
        $dom = new DOMDocument;
164
        // LibXML needs a wrapper element...
165
        $dom->loadHTML('<div>' . $readme . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
166
        $xpath = new DOMXPath($dom);
167
168
        // Select all anchors and images in the readme document
169
        $query = $xpath->query('//*[self::a or self::img]');
170
171
        foreach ($query as $element) { /** @var DOMElement $element */
172
            $attribute = ($element->nodeName === 'a') ? 'href' : 'src';
173
            $path = $element->getAttribute($attribute);
174
            if (!$this->isRelativeUri($path)) {
175
                continue;
176
            }
177
178
            // See GitHub readmes for example
179
            $folder = ($attribute === 'href') ? 'blob' : 'raw';
180
            $defaultBranch = 'master'; // Is this safe to assume?
181
182
            $element->setAttribute(
183
                $attribute,
184
                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...
185
            );
186
        }
187
188
        // Return the inner HTML of the wrapper div... Reference: stackoverflow.com/a/39193507/2812842
189
        $node = $dom->getElementsByTagName('div')->item(0);
190
        return implode(array_map([$node->ownerDocument, 'saveHTML'], iterator_to_array($node->childNodes)));
191
    }
192
193
    /**
194
     * Decide whether a URI path is relative or not. The regex pattern matches prefixes that start with
195
     * a protocol, a slash or a hash. If they don't start with those things, then they are deemed to be
196
     * relative paths.
197
     *
198
     * @param  string $path
199
     * @return bool
200
     */
201
    public function isRelativeUri($path)
202
    {
203
        return !preg_match('/(^(?:https?:\/\/|\/|#).*$)/', $path);
204
    }
205
206
    /**
207
     * Determine whether an addon is hosted on GitHub
208
     *
209
     * @param  Addon $addon
210
     * @return bool
211
     */
212
    public function hasGitHubRepository(Addon $addon)
213
    {
214
        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...
215
    }
216
217
    private function buildScreenshots(Addon $addon, PackageInterface $package, $path)
218
    {
219
        $extra = $package->getExtra();
220
        $screenshots = array();
221
        $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...
222
223
        if (isset($extra['screenshots'])) {
224
            $screenshots = (array) $extra['screenshots'];
225
        } elseif (isset($extra['screenshot'])) {
226
            $screenshots = (array) $extra['screenshot'];
227
        }
228
229
        // Delete existing screenshots.
230
        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...
231
            $screenshot->delete();
232
        }
233
234
        $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...
235
236
        foreach ($screenshots as $screenshot) {
237
            if (!is_string($screenshot)) {
238
                continue;
239
            }
240
241
            $scheme = parse_url($screenshot, PHP_URL_SCHEME);
242
243
            // Handle absolute image URLs.
244
            if ($scheme == 'http' || $scheme == 'https') {
245
                $temp = TEMP_FOLDER . '/' . md5($screenshot);
246
247
                if (!copy($screenshot, $temp)) {
248
                    continue;
249
                }
250
251
                $data = array(
252
                    'name' => basename($screenshot),
253
                    'size' => filesize($temp),
254
                    'tmp_name' => $temp,
255
                    'error' => 0
256
                );
257
            } // Handle images that are included in the repository.
258
            else {
259
                $source = $path . '/' . ltrim($screenshot, '/');
260
261
                // Prevent directory traversal.
262
                if ($source != realpath($source)) {
263
                    continue;
264
                }
265
266
                if (!file_exists($source)) {
267
                    continue;
268
                }
269
270
                $data = array(
271
                    'name' => basename($source),
272
                    'size' => filesize($source),
273
                    'tmp_name' => $source,
274
                    'error' => 0
275
                );
276
            }
277
278
            $upload = new Upload();
279
            $upload->setValidator(new AddonBuilderScreenshotValidator());
280
            $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...
281
282
            if ($file = $upload->getFile()) {
283
                $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...
284
            }
285
        }
286
    }
287
}
288