Completed
Push — master ( 265a2d...f9e310 )
by jerome
02:58
created

UpdateWatcherService::process()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
rs 8.8571
cc 5
eloc 9
nc 8
nop 0
1
<?php
2
3
/**
4
 * This file is part of Dedipanel project
5
 *
6
 * (c) 2010-2015 Dedipanel <http://www.dedicated-panel.net>
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 DP\Core\CoreBundle\Service;
13
14
class UpdateWatcherService
15
{
16
    private $currentVersion;
17
    private $updateAvailable = false;
18
    private $versionAvailable;
19
    private $versionFile;
20
21
    public function __construct($currentVersion, $watcherDir)
22
    {
23
        $this->currentVersion = $currentVersion;
24
        $this->versionFile = $watcherDir . '/version.json';
25
26
        $this->process();
27
    }
28
29
    public function getCurrentVersion()
30
    {
31
        return $this->currentVersion;
32
    }
33
34
    public function isUpdateAvailable()
35
    {
36
        return $this->updateAvailable;
37
    }
38
39
    public function getAvailableVersion()
40
    {
41
        return $this->versionAvailable;
42
    }
43
44
    private function process()
45
    {
46
        $version = '';
47
48
        if (!file_exists($this->versionFile)
49
        || filemtime($this->versionFile) <= mktime(0, 0, 0)) {
50
            $version = $this->fetchData();
51
        }
52
53
        if (empty($version)) {
54
            $version = @file_get_contents($this->versionFile);
55
        }
56
57
        if ($version !== false) {
58
            $this->processVersion($version);
59
        }
60
    }
61
    
62
    private function fetchData()
63
    {
64
        $context = stream_context_create(array(
65
            'http' => array(
66
                'method'  => 'GET',
67
                'timeout' => 1, 
68
            )
69
        ));
70
71
        $version = @file_get_contents('http://www.dedicated-panel.net/version.json', false, $context);
72
73
        if ($version !== false) {
74
            file_put_contents($this->versionFile, $version);
75
        }
76
77
        return $version;
78
    }
79
80
    private function processVersion($version)
81
    {
82
        $version = json_decode($version);
83
84
        $this->versionAvailable = $version->version;
85
        $this->updateAvailable  = false;
86
87
        if (version_compare($this->versionAvailable, $this->currentVersion) == 1) {
88
            $this->updateAvailable = true;
89
        }
90
    }
91
}
92