7e0da4327ad145b9a2e47cf93a27f3b545270130
[yaffs-website] / vendor / psy / psysh / src / VersionUpdater / IntervalChecker.php
1 <?php
2
3 /*
4  * This file is part of Psy Shell.
5  *
6  * (c) 2012-2018 Justin Hileman
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 Psy\VersionUpdater;
13
14 class IntervalChecker extends GitHubChecker
15 {
16     private $cacheFile;
17     private $interval;
18
19     public function __construct($cacheFile, $interval)
20     {
21         $this->cacheFile = $cacheFile;
22         $this->interval  = $interval;
23     }
24
25     public function fetchLatestRelease()
26     {
27         // Read the cached file
28         $cached = \json_decode(@\file_get_contents($this->cacheFile, false));
29         if ($cached && isset($cached->last_check) && isset($cached->release)) {
30             $now = new \DateTime();
31             $lastCheck = new \DateTime($cached->last_check);
32             if ($lastCheck >= $now->sub($this->getDateInterval())) {
33                 return $cached->release;
34             }
35         }
36
37         // Fall back to fetching from GitHub
38         $release = parent::fetchLatestRelease();
39         if ($release && isset($release->tag_name)) {
40             $this->updateCache($release);
41         }
42
43         return $release;
44     }
45
46     private function getDateInterval()
47     {
48         switch ($this->interval) {
49             case Checker::DAILY:
50                 return new \DateInterval('P1D');
51             case Checker::WEEKLY:
52                 return new \DateInterval('P1W');
53             case Checker::MONTHLY:
54                 return new \DateInterval('P1M');
55         }
56     }
57
58     private function updateCache($release)
59     {
60         $data = [
61             'last_check' => \date(DATE_ATOM),
62             'release'    => $release,
63         ];
64
65         \file_put_contents($this->cacheFile, \json_encode($data));
66     }
67 }