1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of Railt package. |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Railt\SDL; |
13
|
|
|
|
14
|
|
|
use Phplrt\Source\File; |
15
|
|
|
use Psr\SimpleCache\CacheInterface; |
16
|
|
|
use Phplrt\Contracts\Source\FileInterface; |
17
|
|
|
use Cache\Adapter\PHPArray\ArrayCachePool; |
18
|
|
|
use Phplrt\Contracts\Parser\ParserInterface; |
19
|
|
|
use Railt\SDL\Frontend\Parser as ParserRuntime; |
20
|
|
|
use Psr\SimpleCache\InvalidArgumentException; |
21
|
|
|
use Phplrt\Contracts\Source\ReadableInterface; |
22
|
|
|
use Phplrt\Source\Exception\NotAccessibleException; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Class Frontend |
26
|
|
|
*/ |
27
|
|
|
class Frontend implements ParserInterface |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* @var ParserInterface|ParserRuntime |
31
|
|
|
*/ |
32
|
|
|
private ParserInterface $parser; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var CacheInterface|null |
36
|
|
|
*/ |
37
|
|
|
private CacheInterface $cache; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Parser constructor. |
41
|
|
|
* |
42
|
|
|
* @param CacheInterface|null $cache |
43
|
|
|
*/ |
44
|
|
|
public function __construct(CacheInterface $cache = null) |
45
|
|
|
{ |
46
|
|
|
$this->parser = new ParserRuntime(); |
47
|
|
|
$this->cache = $cache ?? new ArrayCachePool(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritDoc} |
52
|
|
|
* @throws NotAccessibleException |
53
|
|
|
* @throws \RuntimeException |
54
|
|
|
* @throws \Throwable |
55
|
|
|
* @throws InvalidArgumentException |
56
|
|
|
*/ |
57
|
|
|
public function parse($source): iterable |
58
|
|
|
{ |
59
|
|
|
$hash = $this->hash($source = File::new($source)); |
60
|
|
|
|
61
|
|
|
if (! $this->cache->has($hash)) { |
62
|
|
|
$this->cache->set($hash, $this->parser->parse($source)); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $this->cache->get($hash); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param ReadableInterface $source |
70
|
|
|
* @return string |
71
|
|
|
*/ |
72
|
|
|
private function hash(ReadableInterface $source): string |
73
|
|
|
{ |
74
|
|
|
if ($source instanceof FileInterface) { |
75
|
|
|
return \md5_file($source->getPathname()); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return \md5($source->getContents()); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
|
82
|
|
|
} |
83
|
|
|
|