Packagist::getLatestVersion()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 1
1
<?php
2
3
/**
4
 * This file is part of Packy.
5
 *
6
 * (c) Peter Nijssen
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace AppBundle\PackageManager;
13
14
use AppBundle\Entity\Package;
15
use GuzzleHttp\Client as GuzzleClient;
16
17
class Packagist implements PackageManager
18
{
19
    /**
20
     * @var string
21
     */
22
    private $packageVendor = 'https://packagist.org/packages/';
23
24
    /**
25
     * @param Package $package
26
     *
27
     * @return Package
28
     */
29
    public function analyzePackage(Package $package)
30
    {
31
        $client = new GuzzleClient();
32
        $response = $client->get(
33
            $this->packageVendor . $package->getName() . '.json',
34
            [
35
                'exceptions' => false,
36
            ]
37
        );
38
39
        if ($response->getStatusCode() == 200) {
40
            $data = $this->parseJson((string) $response->getBody());
41
42
            $newestVersion = $this->getLatestVersion(array_keys($data['package']['versions']));
43
            $package->setLatestVersion($newestVersion);
44
            $package->setLastCheckAt(new \DateTime());
45
        }
46
47
        return $package;
48
    }
49
50
    /**
51
     * Parse JSON data.
52
     *
53
     * @param string $data
54
     *
55
     * @return mixed
56
     */
57
    private function parseJson($data)
58
    {
59
        $parsedData = json_decode($data, true);
60
        if ($parsedData === false) {
61
            throw new \RuntimeException('Unable to parse json file');
62
        }
63
64
        return $parsedData;
65
    }
66
67
    /**
68
     * Find latest version.
69
     *
70
     * @param array $versions
71
     *
72
     * @return string
73
     */
74
    private function getLatestVersion($versions = [])
75
    {
76
        $latestVersion = '0.0.0';
77
        foreach ($versions as $version) {
78
            $version = ltrim($version, 'v');
79
            if (preg_match('/^[0-9.]+$/', $version)) {
80
                if (version_compare($latestVersion, $version) >= 0) {
81
                    continue;
82
                }
83
                $latestVersion = $version;
84
            }
85
        }
86
87
        return $latestVersion;
88
    }
89
}
90