Completed
Pull Request — master (#143)
by Robbie
01:49
created

AddonBuilder::replaceRelativeLinks()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 8.439
c 0
b 0
f 0
cc 6
eloc 19
nc 8
nop 2
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
                $readme = $parser->toHtml(file_get_contents($path));
101
102
                $purifier = new HTMLPurifier();
103
                $readme = $purifier->purify($readme, array(
104
                    'Cache.SerializerPath' => TEMP_FOLDER
105
                ));
106
107
                $readme = $this->replaceRelativeLinks($addon, $readme);
108
109
                $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...
110
                return;
111
            }
112
        }
113
    }
114
115
    /**
116
     * Given an addon and a parsed HTML readme string, find and replace relative links with absolute
117
     * repository path links. This method applies to GitHub repositories only.
118
     *
119
     * @param  Addon  $addon
120
     * @param  string $readme
121
     * @return string
122
     */
123
    public function replaceRelativeLinks(Addon $addon, $readme)
124
    {
125
        if (!$this->hasGitHubRepository($addon)) {
126
            return $this;
127
        }
128
129
        $dom = new DOMDocument;
130
        // LibXML needs a wrapper element...
131
        $dom->loadHTML('<div>' . $readme . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
132
        $xpath = new DOMXPath($dom);
133
134
        // Select all anchors and images in the readme document
135
        $query = $xpath->query('//*[self::a or self::img]');
136
137
        foreach ($query as $element) { /** @var DOMElement $element */
138
            $attribute = ($element->nodeName === 'a') ? 'href' : 'src';
139
            $path = $element->getAttribute($attribute);
140
            if (!$this->isRelativeUri($path)) {
141
                continue;
142
            }
143
144
            // See GitHub readmes for example
145
            $folder = ($attribute === 'href') ? 'blob' : 'raw';
146
            $defaultBranch = 'master'; // Is this safe to assume?
147
148
            $element->setAttribute(
149
                $attribute,
150
                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...
151
            );
152
        }
153
154
        // Return the inner HTML of the wrapper div... Reference: stackoverflow.com/a/39193507/2812842
155
        $node = $dom->getElementsByTagName('div')->item(0);
156
        return implode(array_map([$node->ownerDocument, 'saveHTML'], iterator_to_array($node->childNodes)));
157
    }
158
159
    /**
160
     * Decide whether a URI path is relative or not. The regex pattern matches prefixes that start with
161
     * a protocol, a slash or a hash. If they don't start with those things, then they are deemed to be
162
     * relative paths.
163
     *
164
     * @param  string $path
165
     * @return bool
166
     */
167
    public function isRelativeUri($path)
168
    {
169
        return !preg_match('/(^(?:https?:\/\/|\/|#).*$)/', $path);
170
    }
171
172
    /**
173
     * Determine whether an addon is hosted on GitHub
174
     *
175
     * @param  Addon $addon
176
     * @return bool
177
     */
178
    public function hasGitHubRepository(Addon $addon)
179
    {
180
        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...
181
    }
182
183
    private function buildScreenshots(Addon $addon, PackageInterface $package, $path) {
184
        $extra = $package->getExtra();
185
        $screenshots = array();
186
        $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...
187
188
        if (isset($extra['screenshots'])) {
189
            $screenshots = (array) $extra['screenshots'];
190
        } elseif (isset($extra['screenshot'])) {
191
            $screenshots = (array) $extra['screenshot'];
192
        }
193
194
        // Delete existing screenshots.
195
        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...
196
            $screenshot->delete();
197
        }
198
199
        $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...
200
201
        foreach ($screenshots as $screenshot) {
202
            if (!is_string($screenshot)) {
203
                continue;
204
            }
205
206
            $scheme = parse_url($screenshot, PHP_URL_SCHEME);
207
208
            // Handle absolute image URLs.
209
            if ($scheme == 'http' || $scheme == 'https') {
210
                $temp = TEMP_FOLDER . '/' . md5($screenshot);
211
212
                if (!copy($screenshot, $temp)) {
213
                    continue;
214
                }
215
216
                $data = array(
217
                    'name' => basename($screenshot),
218
                    'size' => filesize($temp),
219
                    'tmp_name' => $temp,
220
                    'error' => 0
221
                );
222
            }
223
            // Handle images that are included in the repository.
224
            else {
225
                $source = $path . '/' . ltrim($screenshot, '/');
226
227
                // Prevent directory traversal.
228
                if ($source != realpath($source)) {
229
                    continue;
230
                }
231
232
                if (!file_exists($source)) {
233
                    continue;
234
                }
235
236
                $data = array(
237
                    'name' => basename($source),
238
                    'size' => filesize($source),
239
                    'tmp_name' => $source,
240
                    'error' => 0
241
                );
242
            }
243
244
            $upload = new Upload();
245
            $upload->setValidator(new AddonBuilderScreenshotValidator());
246
            $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...
247
248
            if($file = $upload->getFile()) {
249
                $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...
250
            }
251
        }
252
    }
253
254
}
255