Completed
Push — master ( 088a71...2ad8eb )
by Théo
01:24
created

src/Strategy/GithubStrategy.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Humbug
4
 *
5
 * @category   Humbug
6
 * @package    Humbug
7
 * @copyright  Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com)
8
 * @license    https://github.com/padraic/phar-updater/blob/master/LICENSE New BSD License
9
 *
10
 * This class is partially patterned after Composer's self-update.
11
 */
12
13
namespace Humbug\SelfUpdate\Strategy;
14
15
use Humbug\SelfUpdate\Updater;
16
use Humbug\SelfUpdate\VersionParser;
17
use Humbug\SelfUpdate\Exception\HttpRequestException;
18
use Humbug\SelfUpdate\Exception\InvalidArgumentException;
19
use Humbug\SelfUpdate\Exception\JsonParsingException;
20
use function Humbug\get_contents;
21
22
class GithubStrategy implements StrategyInterface
23
{
24
    const API_URL = 'https://packagist.org/packages/%s.json';
25
26
    const STABLE = 'stable';
27
28
    const UNSTABLE = 'unstable';
29
30
    const ANY = 'any';
31
32
    /**
33
     * @var string
34
     */
35
    private $localVersion;
36
37
    /**
38
     * @var string
39
     */
40
    private $remoteVersion;
41
42
    /**
43
     * @var string
44
     */
45
    private $remoteUrl;
46
47
    /**
48
     * @var string
49
     */
50
    private $pharName;
51
52
    /**
53
     * @var string
54
     */
55
    private $packageName;
56
57
    /**
58
     * @var string
59
     */
60
    private $stability = self::STABLE;
61
62
    /**
63
     * Download the remote Phar file.
64
     *
65
     * @param Updater $updater
66
     * @return void
67
     */
68 View Code Duplication
    public function download(Updater $updater)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69
    {
70
        /** Switch remote request errors to HttpRequestExceptions */
71
        set_error_handler(array($updater, 'throwHttpRequestException'));
72
        $result = get_contents($this->remoteUrl);
73
        restore_error_handler();
74
        if (false === $result) {
75
            throw new HttpRequestException(sprintf(
76
                'Request to URL failed: %s', $this->remoteUrl
77
            ));
78
        }
79
80
        file_put_contents($updater->getTempPharFile(), $result);
81
    }
82
83
    /**
84
     * Retrieve the current version available remotely.
85
     *
86
     * @param Updater $updater
87
     * @return string|bool
88
     */
89
    public function getCurrentRemoteVersion(Updater $updater)
90
    {
91
        /** Switch remote request errors to HttpRequestExceptions */
92
        set_error_handler(array($updater, 'throwHttpRequestException'));
93
        $packageUrl = $this->getApiUrl();
94
        $package = json_decode(get_contents($packageUrl), true);
95
        restore_error_handler();
96
97
        if (null === $package || json_last_error() !== JSON_ERROR_NONE) {
98
            throw new JsonParsingException(
99
                'Error parsing JSON package data'
100
                . (function_exists('json_last_error_msg') ? ': ' . json_last_error_msg() : '')
101
            );
102
        }
103
104
        $versions = array_keys($package['package']['versions']);
105
        $versionParser = new VersionParser($versions);
106
        if ($this->getStability() === self::STABLE) {
107
            $this->remoteVersion = $versionParser->getMostRecentStable();
108
        } elseif ($this->getStability() === self::UNSTABLE) {
109
            $this->remoteVersion = $versionParser->getMostRecentUnstable();
110
        } else {
111
            $this->remoteVersion = $versionParser->getMostRecentAll();
112
        }
113
114
        /**
115
         * Setup remote URL if there's an actual version to download
116
         */
117
        if (!empty($this->remoteVersion)) {
118
            $this->remoteUrl = $this->getDownloadUrl($package);
119
        }
120
121
        return $this->remoteVersion;
122
    }
123
124
    /**
125
     * Retrieve the current version of the local phar file.
126
     *
127
     * @param Updater $updater
128
     * @return string
129
     */
130
    public function getCurrentLocalVersion(Updater $updater)
131
    {
132
        return $this->localVersion;
133
    }
134
135
    /**
136
     * Set version string of the local phar
137
     *
138
     * @param string $version
139
     */
140
    public function setCurrentLocalVersion($version)
141
    {
142
        $this->localVersion = $version;
143
    }
144
145
    /**
146
     * Set Package name
147
     *
148
     * @param string $name
149
     */
150
    public function setPackageName($name)
151
    {
152
        $this->packageName = $name;
153
    }
154
155
    /**
156
     * Get Package name
157
     *
158
     * @return string
159
     */
160
    public function getPackageName()
161
    {
162
        return $this->packageName;
163
    }
164
165
    /**
166
     * Set phar file's name
167
     *
168
     * @param string $name
169
     */
170
    public function setPharName($name)
171
    {
172
        $this->pharName = $name;
173
    }
174
175
    /**
176
     * Get phar file's name
177
     *
178
     * @return string
179
     */
180
    public function getPharName()
181
    {
182
        return $this->pharName;
183
    }
184
185
    /**
186
     * Set target stability
187
     *
188
     * @param string $stability
189
     */
190
    public function setStability($stability)
191
    {
192
        if ($stability !== self::STABLE && $stability !== self::UNSTABLE && $stability !== self::ANY) {
193
            throw new InvalidArgumentException(
194
                'Invalid stability value. Must be one of "stable", "unstable" or "any".'
195
            );
196
        }
197
        $this->stability = $stability;
198
    }
199
200
    /**
201
     * Get target stability
202
     *
203
     * @return string
204
     */
205
    public function getStability()
206
    {
207
        return $this->stability;
208
    }
209
210
    protected function getApiUrl()
211
    {
212
        return sprintf(self::API_URL, $this->getPackageName());
213
    }
214
215
    protected function getDownloadUrl(array $package)
216
    {
217
        $baseUrl = preg_replace(
218
            '{\.git$}',
219
            '',
220
            $package['package']['versions'][$this->remoteVersion]['source']['url']
221
        );
222
        $downloadUrl = sprintf(
223
            '%s/releases/download/%s/%s',
224
            $baseUrl,
225
            $this->remoteVersion,
226
            $this->getPharName()
227
        );
228
        return $downloadUrl;
229
    }
230
}
231