Completed
Pull Request — master (#66)
by
unknown
03:28
created

Definitions::getSourceIds()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spatie\SchemaOrg\Generator;
4
5
use RuntimeError;
6
use Symfony\Component\DomCrawler\Crawler;
7
8
class Definitions
9
{
10
    /** @var array */
11
    protected $sources;
12
13
    /** @var string */
14
    protected $tempDir = __DIR__.'/temp';
15
16
    public function __construct(array $sources)
17
    {
18
        $this->sources = $sources;
19
    }
20
21
    public function preload()
22
    {
23
        foreach ($this->sources as $sourceId => $sourcePath) {
24
            $this->loadSource($sourceId, false);
25
        }
26
    }
27
28
    public function query(string $sourceId, string $selector): Crawler
29
    {
30
        return (new Crawler($this->loadSource($sourceId)))->filter($selector);
31
    }
32
33
    public function getSourceIds(): array
34
    {
35
        return array_keys($this->sources);
36
    }
37
38
    protected function loadSource(string $sourceId, bool $fromCache = true): string
39
    {
40
        if (! isset($this->sources[$sourceId])) {
41
            throw new RuntimeError("Source `{$sourceId}` doesn't exist");
42
        }
43
44
        $cachePath = $this->tempDir.'/'.$sourceId.'.rdfa';
45
46
        if ($fromCache && file_exists($cachePath)) {
47
            return file_get_contents($cachePath);
48
        }
49
50
        $rdfa = file_get_contents($this->sources[$sourceId]);
51
52
        file_put_contents($cachePath, $rdfa);
53
54
        return $rdfa;
55
    }
56
}
57