Completed
Push — master ( b6038c...004e03 )
by Daniel
01:58
created

AddonBuilder::isRelativeUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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