Definitions::loadSource()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 4
nc 3
nop 2
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 $selector): Crawler
29
    {
30
        return (new Crawler($this->loadSource('core')))->filter($selector);
31
    }
32
33
    protected function loadSource(string $sourceId, bool $fromCache = true): string
34
    {
35
        if (! isset($this->sources[$sourceId])) {
36
            throw new RuntimeError("Source `{$sourceId}` doesn't exist");
37
        }
38
39
        $cachePath = $this->tempDir.'/'.$sourceId.'.rdfa';
40
41
        if ($fromCache && file_exists($cachePath)) {
42
            return file_get_contents($cachePath);
43
        }
44
45
        $rdfa = file_get_contents($this->sources[$sourceId]);
46
47
        file_put_contents($cachePath, $rdfa);
48
49
        return $rdfa;
50
    }
51
}
52