Completed
Pull Request — master (#142)
by Robbie
10:23
created

AddonBuilder   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 199
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 10
dl 0
loc 199
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B build() 0 47 6
A download() 0 6 1
B buildReadme() 0 37 6
A getGitHubContext() 0 15 3
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
    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
    private function buildReadme(Addon $addon, $path) {
77
        $candidates = array(
78
            'README.md',
79
            'README.markdown',
80
            'README.mdown',
81
            'docs/en/index.md'
82
        );
83
84
        foreach ($candidates as $candidate) {
85
            $lower = strtolower($candidate);
86
            $paths = array("$path/$candidate", "$path/$lower");
87
88
            foreach ($paths as $path) {
89
                if (!file_exists($path)) {
90
                    return;
91
                }
92
93
                $parser = GitHubMarkdownService::create();
94
                if ($context = $this->getGitHubContext($addon)) {
95
                    $parser->setContext($context);
96
                }
97
                $readme = $parser->toHtml(file_get_contents($path));
98
99
                if (empty($readme)) {
100
                    return;
101
                }
102
103
                $purifier = new HTMLPurifier();
104
                $readme = $purifier->purify($readme, array(
105
                    'Cache.SerializerPath' => TEMP_FOLDER
106
                ));
107
108
                $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...
109
                return;
110
            }
111
        }
112
    }
113
114
    /**
115
     * Determine if the repository is from GitHub, and if so then return the "context" (vendor/module) from the path
116
     *
117
     * @param  Addon $addon
118
     * @return string|false
119
     */
120
    public function getGitHubContext(Addon $addon)
121
    {
122
        $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...
123
        if (stripos($repository, '://github.com/') === false) {
124
            return false;
125
        }
126
127
        preg_match('/^http(?:s?):\/\/github\.com\/(?<module>.*)(\.git)?$/U', $repository, $matches);
128
129
        if (isset($matches['module'])) {
130
            return $matches['module'];
131
        }
132
133
        return false;
134
    }
135
136
    private function buildScreenshots(Addon $addon, PackageInterface $package, $path) {
137
        $extra = $package->getExtra();
138
        $screenshots = array();
139
        $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...
140
141
        if (isset($extra['screenshots'])) {
142
            $screenshots = (array) $extra['screenshots'];
143
        } elseif (isset($extra['screenshot'])) {
144
            $screenshots = (array) $extra['screenshot'];
145
        }
146
147
        // Delete existing screenshots.
148
        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...
149
            $screenshot->delete();
150
        }
151
152
        $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...
153
154
        foreach ($screenshots as $screenshot) {
155
            if (!is_string($screenshot)) {
156
                continue;
157
            }
158
159
            $scheme = parse_url($screenshot, PHP_URL_SCHEME);
160
161
            // Handle absolute image URLs.
162
            if ($scheme == 'http' || $scheme == 'https') {
163
                $temp = TEMP_FOLDER . '/' . md5($screenshot);
164
165
                if (!copy($screenshot, $temp)) {
166
                    continue;
167
                }
168
169
                $data = array(
170
                    'name' => basename($screenshot),
171
                    'size' => filesize($temp),
172
                    'tmp_name' => $temp,
173
                    'error' => 0
174
                );
175
            }
176
            // Handle images that are included in the repository.
177
            else {
178
                $source = $path . '/' . ltrim($screenshot, '/');
179
180
                // Prevent directory traversal.
181
                if ($source != realpath($source)) {
182
                    continue;
183
                }
184
185
                if (!file_exists($source)) {
186
                    continue;
187
                }
188
189
                $data = array(
190
                    'name' => basename($source),
191
                    'size' => filesize($source),
192
                    'tmp_name' => $source,
193
                    'error' => 0
194
                );
195
            }
196
197
            $upload = new Upload();
198
            $upload->setValidator(new AddonBuilderScreenshotValidator());
199
            $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...
200
201
            if($file = $upload->getFile()) {
202
                $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...
203
            }
204
        }
205
    }
206
207
}
208