1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace ReliqArts\StyleImporter\Util; |
6
|
|
|
|
7
|
|
|
use Illuminate\View\View; |
8
|
|
|
use ReliqArts\StyleImporter\ConfigProvider; |
9
|
|
|
use ReliqArts\StyleImporter\Exception\ActiveViewHtmlRetrievalFailed; |
10
|
|
|
use ReliqArts\StyleImporter\Exception\ActiveViewRetrievalFailed; |
11
|
|
|
use Throwable; |
12
|
|
|
|
13
|
|
|
class ViewAccessor |
14
|
|
|
{ |
15
|
|
|
private const ACTIVE_VIEW_POSITION = 2; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var ConfigProvider |
19
|
|
|
*/ |
20
|
|
|
private $configProvider; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var BacktraceAccessor |
24
|
|
|
*/ |
25
|
|
|
private $backtraceAccessor; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* ActiveViewRetriever constructor. |
29
|
|
|
* |
30
|
|
|
* @param ConfigProvider $configProvider |
31
|
|
|
* @param BacktraceAccessor $backtraceAccessor |
32
|
|
|
*/ |
33
|
|
|
public function __construct(ConfigProvider $configProvider, BacktraceAccessor $backtraceAccessor) |
34
|
|
|
{ |
35
|
|
|
$this->configProvider = $configProvider; |
36
|
|
|
$this->backtraceAccessor = $backtraceAccessor; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param null|View $view |
41
|
|
|
* |
42
|
|
|
* @throws ActiveViewHtmlRetrievalFailed |
43
|
|
|
* |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
|
|
public function getViewHTML(?View $view = null): string |
47
|
|
|
{ |
48
|
|
|
try { |
49
|
|
|
$view = $view ?? $this->deriveActiveViewFromBacktrace(); |
50
|
|
|
|
51
|
|
|
return $view |
|
|
|
|
52
|
|
|
->with([$this->configProvider->getSkipStyleImportVariableName() => true]) |
53
|
|
|
->render(); |
54
|
|
|
} catch (Throwable $exception) { |
55
|
|
|
throw new ActiveViewHtmlRetrievalFailed( |
56
|
|
|
sprintf('Could not retrieve HTML of active view; %s', $exception->getMessage()), |
57
|
|
|
$exception->getCode(), |
58
|
|
|
$exception |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @throws ActiveViewRetrievalFailed |
65
|
|
|
* |
66
|
|
|
* @return View |
67
|
|
|
*/ |
68
|
|
|
private function deriveActiveViewFromBacktrace(): View |
69
|
|
|
{ |
70
|
|
|
/** @var null|View $view */ |
71
|
|
|
$view = $this->backtraceAccessor->getNthObjectOfType(self::ACTIVE_VIEW_POSITION, View::class); |
72
|
|
|
|
73
|
|
|
if (!empty($view)) { |
74
|
|
|
return $view; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
throw new ActiveViewRetrievalFailed( |
78
|
|
|
'Could not retrieve active view from backtrace.' |
79
|
|
|
); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|