Completed
Push — feature/ss4-upgrade ( f41a3f )
by
unknown
10:12
created

AddonBuilder::buildScreenshots()   C

Complexity

Conditions 12
Paths 54

Size

Total Lines 70
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

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

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\Addons\Services;
4
5
use Composer\Package\Package;
6
use Composer\Package\PackageInterface;
7
use dflydev\markdown\MarkdownParser;
8
use SilverStripe\Addons\Model\Addon;
9
use SilverStripe\Assets\Upload;
10
use HTMLPurifier;
11
use Exception;
12
/**
13
 * Downloads an add-on and builds more details information about it.
14
 */
15
class AddonBuilder 
16
{
17
18
	const ADDONS_DIR = 'add-ons';
19
20
	const SCREENSHOTS_DIR = 'screenshots';
21
22
	private $packagist;
23
24
	public function __construct(PackagistService $packagist) 
25
	{
26
		$this->packagist = $packagist;
27
	}
28
29
	public function build(Addon $addon) 
30
	{
31
		$composer = $this->packagist->getComposer();
32
		$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...
33
		$packageVersions = $this->packagist->getPackageVersions($addon->Name);
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<SilverStripe\Addons\Model\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...
34
		$time = time();
35
36
		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...
37
			throw new Exception('Could not find corresponding Packagist versions');
38
		}
39
40
		// Get the latest local and packagist version pair.
41
		$version = $addon->Versions()->filter('Development', true)->first();
0 ignored issues
show
Bug introduced by
The method Versions() does not exist on SilverStripe\Addons\Model\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...
42
		foreach ($packageVersions as $packageVersion) {
43
			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...
44
				continue;
45
			}
46
47
			$path = implode('/', array(
48
				TEMP_FOLDER, self::ADDONS_DIR, $addon->Name
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<SilverStripe\Addons\Model\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...
49
			));
50
51
			// Convert PackagistAPI result into class compatible with Composer logic
52
			$package = new Package(
53
				$addon->Name, 
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<SilverStripe\Addons\Model\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...
54
				$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...
55
				$packageVersion->getVersion()
56
			);
57
			$package->setExtra($packageVersion->getExtra());
58
			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...
59
				$package->setSourceUrl($source->getUrl());
60
				$package->setSourceType($source->getType());
61
				$package->setSourceReference($source->getReference());
62
			}
63
			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...
64
				$package->setDistUrl($dist->getUrl());
65
				$package->setDistType($dist->getType());
66
				$package->setDistReference($dist->getReference());
67
			}
68
69
			$this->download($package, $path);
70
			$this->buildReadme($addon, $path);
71
			$this->buildScreenshots($addon, $package, $path);
72
		}
73
74
		$addon->LastBuilt = $time;
0 ignored issues
show
Documentation introduced by
The property LastBuilt does not exist on object<SilverStripe\Addons\Model\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...
75
		$addon->write();
76
	}
77
78
	protected function download(PackageInterface $package, $path) {
79
		$this->packagist
80
			->getComposer()
81
			->getDownloadManager()
82
			->download($package, $path);
83
	}
84
85
	private function buildReadme(Addon $addon, $path) {
86
		$candidates = array(
87
			'README.md',
88
			'README.markdown',
89
			'README.mdown',
90
			'docs/en/index.md'
91
		);
92
93
		foreach ($candidates as $candidate) {
94
			$lower = strtolower($candidate);
95
			$paths = array("$path/$candidate", "$path/$lower");
96
97
			foreach ($paths as $path) {
98
				if (!file_exists($path)) {
99
					return;
100
				}
101
102
				$parser = new MarkdownParser();
103
				$readme = $parser->transformMarkdown(file_get_contents($path));
104
105
				$purifier = new HTMLPurifier();
106
				$readme = $purifier->purify($readme, array(
107
					'Cache.SerializerPath' => TEMP_FOLDER
108
				));
109
110
				$addon->Readme = $readme;
0 ignored issues
show
Documentation introduced by
The property Readme does not exist on object<SilverStripe\Addons\Model\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...
111
				return;
112
			}
113
		}
114
	}
115
116
	private function buildScreenshots(Addon $addon, PackageInterface $package, $path) {
117
		$extra = $package->getExtra();
118
		$screenshots = array();
119
		$target = self::SCREENSHOTS_DIR . '/' . $addon->Name;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<SilverStripe\Addons\Model\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...
120
121
		if (isset($extra['screenshots'])) {
122
			$screenshots = (array) $extra['screenshots'];
123
		} elseif (isset($extra['screenshot'])) {
124
			$screenshots = (array) $extra['screenshot'];
125
		}
126
127
		// Delete existing screenshots.
128
		foreach ($addon->Screenshots() as $screenshot) {
0 ignored issues
show
Documentation Bug introduced by
The method Screenshots does not exist on object<SilverStripe\Addons\Model\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...
129
			$screenshot->delete();
130
		}
131
132
		$addon->Screenshots()->removeAll();
0 ignored issues
show
Documentation Bug introduced by
The method Screenshots does not exist on object<SilverStripe\Addons\Model\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...
133
134
		foreach ($screenshots as $screenshot) {
135
			if (!is_string($screenshot)) {
136
				continue;
137
			}
138
139
			$scheme = parse_url($screenshot, PHP_URL_SCHEME);
140
141
			// Handle absolute image URLs.
142
			if ($scheme == 'http' || $scheme == 'https') {
143
				$temp = TEMP_FOLDER . '/' . md5($screenshot);
144
145
				if (!copy($screenshot, $temp)) {
146
					continue;
147
				}
148
149
				$data = array(
150
					'name' => basename($screenshot),
151
					'size' => filesize($temp),
152
					'tmp_name' => $temp,
153
					'error' => 0
154
				);
155
			}
156
			// Handle images that are included in the repository.
157
			else {
158
				$source = $path . '/' . ltrim($screenshot, '/');
159
160
				// Prevent directory traversal.
161
				if ($source != realpath($source)) {
162
					continue;
163
				}
164
165
				if (!file_exists($source)) {
166
					continue;
167
				}
168
169
				$data = array(
170
					'name' => basename($source),
171
					'size' => filesize($source),
172
					'tmp_name' => $source,
173
					'error' => 0
174
				);
175
			}
176
177
			$upload = new Upload();
178
			$upload->setValidator(new AddonBuilderScreenshotValidator());
179
			$upload->load($data, $target);
180
181
			if($file = $upload->getFile()) {
182
				$addon->Screenshots()->add($file);
0 ignored issues
show
Documentation Bug introduced by
The method Screenshots does not exist on object<SilverStripe\Addons\Model\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...
183
			}
184
		}
185
	}
186
187
}
188