Completed
Push — develop ( 38da12...667cd2 )
by Vladimir
02:29
created

AssetEngineSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\EventSubscriber;
9
10
use __\__;
11
use allejo\stakx\AssetEngine\AssetEngineInterface;
12
use allejo\stakx\AssetEngine\AssetEngineManager;
13
use allejo\stakx\Configuration;
14
use allejo\stakx\Document\StaticPageView;
15
use allejo\stakx\Event\CompilerPostRenderStaticPageView;
16
use allejo\stakx\Event\ConfigurationParseComplete;
17
use allejo\stakx\Event\PageManagerPostProcess;
18
use allejo\stakx\Filesystem\FileExplorer;
19
use allejo\stakx\Filesystem\FilesystemLoader as fs;
20
use allejo\stakx\Filesystem\FilesystemPath;
21
use allejo\stakx\Filesystem\WritableFolder;
22
use allejo\stakx\RuntimeStatus;
23
use allejo\stakx\Service;
24
use Psr\Log\LoggerInterface;
25
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
26
27
class AssetEngineSubscriber implements EventSubscriberInterface
28
{
29
    private $assetEngineManager;
30
    private $assetPageViews;
31
    private $logger;
32
33 7
    public function __construct(AssetEngineManager $assetEngineManager, LoggerInterface $logger)
34
    {
35 7
        $this->assetEngineManager = $assetEngineManager;
36 7
        $this->assetPageViews = [];
37 7
        $this->logger = $logger;
38 7
    }
39
40 7
    public function processConfigurationSettings(ConfigurationParseComplete $event)
41
    {
42 7
        $configuration = $event->getConfiguration()->getConfiguration();
43
44
        /** @var AssetEngineInterface $engine */
45 7
        foreach ($this->assetEngineManager->getEngines() as $engine)
46
        {
47 7
            $defaults = __::get($configuration, $engine->getConfigurationNamespace(), []);
48 7
            $options = array_merge($engine->getDefaultConfiguration(), $defaults);
49
50 7
            $engine->setOptions($options);
51
        }
52 7
    }
53
54 1
    public function processAssetEnginePageView(PageManagerPostProcess $event)
55
    {
56
        /**
57
         * @var string               $folder
58
         * @var AssetEngineInterface $engine
59
         */
60 1
        foreach ($this->assetEngineManager->getFoldersToWatch() as $folder => $engine)
61
        {
62 1
            $assetFolder = fs::absolutePath($folder);
0 ignored issues
show
Documentation introduced by
$folder is of type integer|string, but the function expects a object<string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
63
64 1
            if (!fs::exists($assetFolder))
65
            {
66
                continue;
67
            }
68
69 1
            $engine->setPageManager($event->getPageManager());
70 1
            $extensions = [];
71
72 1
            foreach ($engine->getExtensions() as $extension)
73
            {
74 1
                $extensions[] = "/.{$extension}.twig$/";
75
            }
76
77 1
            $explorer = FileExplorer::create($assetFolder, $extensions, [], FileExplorer::INCLUDE_ONLY_FILES | FileExplorer::IGNORE_DIRECTORIES);
0 ignored issues
show
Deprecated Code introduced by
The method allejo\stakx\Filesystem\FileExplorer::create() has been deprecated with message: Use `FileExplorer::createFromDefinition()` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
78
79 1
            foreach ($explorer as $file)
80
            {
81 1
                $assetPageView = new StaticPageView($file);
0 ignored issues
show
Bug introduced by
It seems like $file defined by $file on line 79 can also be of type object<allejo\stakx\Filesystem\Folder>; however, allejo\stakx\Document\St...PageView::__construct() does only seem to accept object<allejo\stakx\Filesystem\File>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
82
83
                try
84
                {
85 1
                    $event->getPageManager()->trackNewPageView($assetPageView);
86 1
                    $this->assetPageViews[$assetPageView->getRelativeFilePath()] = [
87 1
                        'engine' => $engine,
88
                    ];
89
                }
90
                catch (\Exception $e)
91
                {
92
                    $this->logger->error('An exception occurred while creating a Static PageView for an AssetEngine');
93
                    $this->logger->error('  {message}', [
94
                        'message' => $e->getMessage(),
95
                    ]);
96
                }
97
            }
98
        }
99 1
    }
100
101 1
    public function compileAssetEnginePageViews(CompilerPostRenderStaticPageView $event)
102
    {
103 1
        $pageView = $event->getPageView();
104 1
        $filePath = $pageView->getRelativeFilePath();
105
106 1
        if (isset($this->assetPageViews[$filePath]))
107
        {
108
            /** @var AssetEngineInterface $engine */
109 1
            $engine = $this->assetPageViews[$filePath]['engine'];
110 1
            $cacheDir = $this->buildCacheFolder($engine);
111
112 1
            if (Service::hasRunTimeFlag(RuntimeStatus::USING_CACHE))
113
            {
114
                $engine->loadCache($cacheDir);
115
            }
116
117 1
            $output = $engine->parse($event->getCompiledOutput(), [
118 1
                'pageview' => $pageView,
119
            ]);
120
121 1
            $engine->saveCache($cacheDir);
122 1
            $event->setCompiledOutput($output);
123
        }
124 1
    }
125
126
    public static function getSubscribedEvents()
127
    {
128
        return [
129
            ConfigurationParseComplete::NAME => 'processConfigurationSettings',
130
            PageManagerPostProcess::NAME => 'processAssetEnginePageView',
131
            CompilerPostRenderStaticPageView::NAME => 'compileAssetEnginePageViews',
132
        ];
133
    }
134
135 1
    private function buildCacheFolder(AssetEngineInterface $engine)
136
    {
137 1
        $cacheDirPath = new FilesystemPath(Service::getWorkingDirectory() . '/');
138
        $cacheDirPath
139 1
            ->appendToPath(Configuration::CACHE_FOLDER . '/')
140 1
            ->appendToPath(__::slug(strtolower($engine->getName())) . '/')
141
        ;
142
143 1
        fs::mkdir($cacheDirPath);
144
145 1
        $cacheDir = new WritableFolder($cacheDirPath);
146 1
        $cacheDir->freeze();
147
148 1
        return $cacheDir;
149
    }
150
}
151