Completed
Pull Request — master (#2751)
by Jeroen
06:20
created

VersionChecker   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 235
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 86.75%

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 7
dl 0
loc 235
ccs 72
cts 83
cp 0.8675
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A setClient() 0 4 1
A getLockPath() 0 7 1
B __construct() 0 27 6
A isEnabled() 0 4 1
A periodicallyCheck() 0 11 4
A check() 0 42 4
A getClient() 0 8 2
A getPackages() 0 24 5
A parseComposer() 0 15 3
1
<?php
2
3
namespace Kunstmaan\AdminBundle\Helper\VersionCheck;
4
5
use Doctrine\Common\Cache\Cache;
6
use Exception;
7
use GuzzleHttp\Client;
8
use Kunstmaan\AdminBundle\Helper\VersionCheck\Exception\ParseException;
9
use Symfony\Component\Cache\Adapter\AdapterInterface;
10
use Symfony\Component\Cache\Adapter\DoctrineAdapter;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
13
use Symfony\Contracts\Translation\TranslatorInterface;
14
15
/**
16
 * Version checker
17
 */
18
class VersionChecker
19
{
20
    public const CACHE_KEY = 'version_check';
21
22
    /**
23
     * @var ContainerInterface
24
     */
25
    private $container;
26
27
    /**
28
     * @var AdapterInterface
29
     */
30
    private $cache;
31
32
    /**
33
     * @var string
34
     */
35
    private $webserviceUrl;
36
37
    /**
38
     * @var int
39
     */
40
    private $cacheTimeframe;
41
42
    /**
43
     * @var bool
44
     */
45
    private $enabled;
46
47
    /**
48
     * @var Client
49
     */
50
    private $client;
51
52
    /**
53
     * @var TranslatorInterface|LegacyTranslatorInterface
54
     */
55
    private $translator;
56
57
    /**
58
     * @param Cache|AdapterInterface $cache
59
     */
60 10
    public function __construct(ContainerInterface $container, /* AdapterInterface */$cache, $translator)
61
    {
62 10
        $this->container = $container;
63
64 10
        if (!$cache instanceof Cache && !$cache instanceof AdapterInterface) {
65
            // NEXT_MAJOR Add AdapterInterface typehint for the $cache parameter
66 1
            throw new \InvalidArgumentException(sprintf('The "$cache" parameter should implement "%s" or "%s"', Cache::class, AdapterInterface::class));
67
        }
68
69 9
        $this->cache = $cache;
0 ignored issues
show
Documentation Bug introduced by
It seems like $cache can also be of type object<Doctrine\Common\Cache\Cache>. However, the property $cache is declared as type object<Symfony\Component...apter\AdapterInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
70 9
        if ($cache instanceof Cache) {
71 2
            @trigger_error(sprintf('Passing an instance of "%s" as the second argument in "%s" is deprecated since KunstmaanAdminBundle 5.7 and an instance of "%s" will be required in KunstmaanAdminBundle 6.0.', Cache::class, __METHOD__, AdapterInterface::class), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
72
73 2
            $this->cache = new DoctrineAdapter($cache);
0 ignored issues
show
Compatibility introduced by
$cache of type object<Doctrine\Common\Cache\Cache> is not a sub-type of object<Doctrine\Common\Cache\CacheProvider>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Cache\Cache to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
74
        }
75
76
        // NEXT_MAJOR Add "Symfony\Contracts\Translation\TranslatorInterface" typehint when sf <4.4 support is removed.
77 9
        if (!$translator instanceof TranslatorInterface && !$translator instanceof LegacyTranslatorInterface) {
78 1
            throw new \InvalidArgumentException(sprintf('The "$translator" parameter should be instance of "%s" or "%s"', TranslatorInterface::class, LegacyTranslatorInterface::class));
79
        }
80
81 8
        $this->translator = $translator;
82
83 8
        $this->webserviceUrl = $this->container->getParameter('version_checker.url');
84 8
        $this->cacheTimeframe = $this->container->getParameter('version_checker.timeframe');
85 8
        $this->enabled = $this->container->getParameter('version_checker.enabled');
86 8
    }
87
88
    /**
89
     * Check that the version check is enabled.
90
     *
91
     * @return bool
92
     */
93 7
    public function isEnabled()
94
    {
95 7
        return $this->enabled;
96
    }
97
98
    /**
99
     * Check if we recently did a version check, if not do one now.
100
     *
101
     * @throws ParseException
102
     */
103 1
    public function periodicallyCheck()
104
    {
105 1
        if (!$this->isEnabled()) {
106
            return;
107
        }
108
109 1
        $cacheItem = $this->cache->getItem(self::CACHE_KEY);
110 1
        if (!$cacheItem->isHit() || !\is_array($cacheItem->get())) {
111
            $this->check();
112
        }
113 1
    }
114
115
    /**
116
     * Get the version details via webservice.
117
     *
118
     * @return mixed a list of bundles if available
119
     *
120
     * @throws ParseException
121
     */
122 5
    public function check()
123
    {
124 5
        if (!$this->isEnabled()) {
125
            return;
126
        }
127
128 5
        $host = $this->container->get('request_stack')->getCurrentRequest()->getHttpHost();
129 5
        $console = realpath($this->container->get('kernel')->getProjectDir().'/bin/console');
130 5
        $installed = filectime($console);
131 5
        $bundles = $this->parseComposer();
132 2
        $title = $this->container->getParameter('kunstmaan_admin.website_title');
133
134 2
        $jsonData = json_encode(array(
135 2
            'host' => $host,
136 2
            'installed' => $installed,
137 2
            'bundles' => $bundles,
138 2
            'project' => $this->translator->trans($title),
139
        ));
140
141
        try {
142 2
            $client = $this->getClient();
143 2
            $response = $client->post($this->webserviceUrl, ['body' => $jsonData]);
144 1
            $contents = $response->getBody()->getContents();
145 1
            $data = json_decode($contents);
146
147 1
            if (null === $data) {
148
                return false;
149
            }
150
151
            // Save the result in the cache to make sure we don't do the check too often
152 1
            $cacheItem = $this->cache->getItem(self::CACHE_KEY);
153 1
            $cacheItem->expiresAfter($this->cacheTimeframe);
154 1
            $cacheItem->set($data);
155
156 1
            $this->cache->save($cacheItem);
157
158 1
            return $data;
159 1
        } catch (Exception $e) {
160
            // We did not receive valid json
161 1
            return false;
162
        }
163
    }
164
165
    /**
166
     * @return Client
167
     */
168 1
    public function getClient()
169
    {
170 1
        if (!$this->client) {
171 1
            $this->client = new Client(array('connect_timeout' => 3, 'timeout' => 1));
172
        }
173
174 1
        return $this->client;
175
    }
176
177
    /**
178
     * @param Client $client
179
     */
180
    public function setClient($client)
181
    {
182
        $this->client = $client;
183
    }
184
185
    /**
186
     * Returns the absolute path to the composer.lock file.
187
     *
188
     * @return string
189
     */
190
    protected function getLockPath()
191
    {
192
        $kernel = $this->container->get('kernel');
193
        $rootPath = $kernel->getProjectDir();
194
195
        return $rootPath.'/composer.lock';
196
    }
197
198
    /**
199
     * Returns a list of composer packages.
200
     *
201
     * @return array
202
     *
203
     * @throws ParseException
204
     */
205 4
    protected function getPackages()
206
    {
207 4
        $translator = $this->container->get('translator');
208 4
        $errorMessage = $translator->trans('settings.version.error_parsing_composer');
209
210 4
        $composerPath = $this->getLockPath();
211 4
        if (!file_exists($composerPath)) {
212 1
            throw new ParseException($translator->trans('settings.version.composer_lock_not_found'));
213
        }
214
215 3
        $json = file_get_contents($composerPath);
216 3
        $result = json_decode($json, true);
217
218 3
        if (json_last_error() !== JSON_ERROR_NONE) {
219 1
            throw new ParseException($errorMessage.' (#'.json_last_error().')');
220
        }
221
222 2
        if (\array_key_exists('packages', $result) && \is_array($result['packages'])) {
223 1
            return $result['packages'];
224
        }
225
226
        // No package list in JSON structure
227 1
        throw new ParseException($errorMessage);
228
    }
229
230
    /**
231
     * Parse the composer.lock file to get the currently used versions of the kunstmaan bundles.
232
     *
233
     * @return array
234
     *
235
     * @throws ParseException
236
     */
237 4
    protected function parseComposer()
238
    {
239 4
        $bundles = array();
240 4
        foreach ($this->getPackages() as $package) {
241 1
            if (!strncmp($package['name'], 'kunstmaan/', \strlen('kunstmaan/'))) {
242 1
                $bundles[] = array(
243 1
                    'name' => $package['name'],
244 1
                    'version' => $package['version'],
245 1
                    'reference' => $package['source']['reference'],
246
                );
247
            }
248
        }
249
250 1
        return $bundles;
251
    }
252
}
253