1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace ReliqArts\StyleImporter\Importer; |
6
|
|
|
|
7
|
|
|
use ReliqArts\StyleImporter\CSS\Processor; |
8
|
|
|
use ReliqArts\StyleImporter\CSS\Ruleset; |
9
|
|
|
use ReliqArts\StyleImporter\Exception\ActiveViewHtmlRetrievalFailed; |
10
|
|
|
use ReliqArts\StyleImporter\HTML\Extractor; |
11
|
|
|
use ReliqArts\StyleImporter\Importer; |
12
|
|
|
use ReliqArts\StyleImporter\Util\FileAssistant; |
13
|
|
|
use ReliqArts\StyleImporter\Util\ViewAccessor; |
14
|
|
|
|
15
|
|
|
final class Agent implements Importer |
16
|
|
|
{ |
17
|
|
|
private const STYLE_TAG_TEMPLATE = '<style type="text/css">%s</style>'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var ViewAccessor |
21
|
|
|
*/ |
22
|
|
|
private $activeViewAccessor; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var Extractor |
26
|
|
|
*/ |
27
|
|
|
private $htmlExtractor; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var Processor |
31
|
|
|
*/ |
32
|
|
|
private $cssProcessor; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var FileAssistant |
36
|
|
|
*/ |
37
|
|
|
private $fileAssistant; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Importer constructor. |
41
|
|
|
* |
42
|
|
|
* @param ViewAccessor $activeViewAccessor |
43
|
|
|
* @param Extractor $htmlExtractor |
44
|
|
|
* @param Processor $cssProcessor |
45
|
|
|
* @param FileAssistant $fileAssistant |
46
|
|
|
*/ |
47
|
|
|
public function __construct( |
48
|
|
|
ViewAccessor $activeViewAccessor, |
49
|
|
|
Extractor $htmlExtractor, |
50
|
|
|
Processor $cssProcessor, |
51
|
|
|
FileAssistant $fileAssistant |
52
|
|
|
) { |
53
|
|
|
$this->activeViewAccessor = $activeViewAccessor; |
54
|
|
|
$this->htmlExtractor = $htmlExtractor; |
55
|
|
|
$this->cssProcessor = $cssProcessor; |
56
|
|
|
$this->fileAssistant = $fileAssistant; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param string $stylesheetUrl |
61
|
|
|
* @param string ...$initialHtmlElements |
62
|
|
|
* |
63
|
|
|
* @throws ActiveViewHtmlRetrievalFailed |
64
|
|
|
* |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
|
|
public function import(string $stylesheetUrl, string ...$initialHtmlElements): string |
68
|
|
|
{ |
69
|
|
|
$viewHtml = $this->activeViewAccessor->getViewHTML(); |
70
|
|
|
$elements = array_merge($initialHtmlElements, $this->htmlExtractor->extract($viewHtml)); |
71
|
|
|
$stylesheet = $this->fileAssistant->getFileContents($stylesheetUrl); |
72
|
|
|
$cssRules = $this->cssProcessor->getStyles($stylesheet, ...$elements); |
73
|
|
|
|
74
|
|
|
return $this->wrapImportedStyles($cssRules); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param Ruleset $styles |
79
|
|
|
* |
80
|
|
|
* @return string |
81
|
|
|
*/ |
82
|
|
|
private function wrapImportedStyles(Ruleset $styles): string |
83
|
|
|
{ |
84
|
|
|
return sprintf(self::STYLE_TAG_TEMPLATE, $styles); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|