|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Inok\ruCalendar; |
|
4
|
|
|
|
|
5
|
|
|
use AppZz\Http\CurlClient; |
|
6
|
|
|
use AppZz\Http\CurlClient\Response; |
|
7
|
|
|
|
|
8
|
|
|
class Calendar |
|
9
|
|
|
{ |
|
10
|
|
|
private $calendarYear; |
|
11
|
|
|
private $calendarCacheDays; |
|
12
|
|
|
|
|
13
|
|
|
/** @var domCalendar */ |
|
14
|
|
|
private $calendar = null; |
|
15
|
|
|
|
|
16
|
|
|
private $minYear = 2013; |
|
17
|
|
|
const CALENDAR_URL = 'http://www.consultant.ru/law/ref/calendar/proizvodstvennye/%04d/'; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(int $year = null, int $calendarCacheDays = 7) { |
|
20
|
|
|
$this->calendarYear = $year; |
|
21
|
|
|
$this->calendarCacheDays = $calendarCacheDays; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function getCalendar(): array { |
|
25
|
|
|
if (is_null($this->calendar)) { |
|
26
|
|
|
$this->getCalendarContent(); |
|
27
|
|
|
} |
|
28
|
|
|
return (is_null($this->calendar)) ? [] : $this->calendar->getHolidays(); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
private function getCalendarContent() { |
|
32
|
|
|
if (is_null($this->calendarYear)) { |
|
33
|
|
|
$this->calendarYear = (int) date("Y"); |
|
34
|
|
|
} |
|
35
|
|
|
if ($this->calendarYear < $this->minYear) { |
|
36
|
|
|
return; |
|
37
|
|
|
} |
|
38
|
|
|
$content = $this->getCalendarDomContent(); |
|
39
|
|
|
if ($content) { |
|
40
|
|
|
$this->calendar = new domCalendar($content); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
private function getCacheDir(): string { |
|
45
|
|
|
$cacheDir = sys_get_temp_dir()."/iCalendar"; |
|
46
|
|
|
if (!file_exists($cacheDir)) { |
|
47
|
|
|
mkdir($cacheDir); |
|
48
|
|
|
} |
|
49
|
|
|
return $cacheDir; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
private function getCalendarDomContent() { |
|
53
|
|
|
$calendarCache = sprintf($this->getCacheDir()."/%04d", $this->calendarYear); |
|
54
|
|
|
if (file_exists($calendarCache) && ((time() - filemtime($calendarCache)) / 60 / 60 / 24) <= $this->calendarCacheDays) { |
|
55
|
|
|
return file_get_contents($calendarCache); |
|
56
|
|
|
} |
|
57
|
|
|
$calendarUrl = sprintf(Calendar::CALENDAR_URL, $this->calendarYear); |
|
58
|
|
|
$request = CurlClient::get($calendarUrl); |
|
59
|
|
|
$request->browser('chrome', 'mac'); |
|
60
|
|
|
$request->accept('html', 'gzip'); |
|
61
|
|
|
/** @var Response $response */ |
|
62
|
|
|
$response = $request->send(); |
|
63
|
|
|
if ($response->get_status() === 200) { |
|
64
|
|
|
file_put_contents($calendarCache, $response->get_body()); |
|
65
|
|
|
return $response->get_body(); |
|
66
|
|
|
} |
|
67
|
|
|
return false; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|