Passed
Push — master ( c79df9...45a681 )
by Enjoys
49s queued 13s
created

OneFileStrategy   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Test Coverage

Coverage 83.67%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 46
c 2
b 0
f 1
dl 0
loc 129
ccs 41
cts 49
cp 0.8367
rs 10
wmc 13

7 Methods

Rating   Name   Duplication   Size   Complexity  
A generateFilename() 0 3 1
A isCacheValid() 0 6 2
A __construct() 0 26 1
A getFilePath() 0 3 1
A init() 0 11 2
A getFileUrl() 0 3 1
A getResult() 0 29 5
1
<?php
2
3
namespace Enjoys\AssetsCollector\CollectStrategy\Strategy;
4
5
use Enjoys\AssetsCollector\Asset;
6
use Enjoys\AssetsCollector\CollectStrategy\StrategyAbstract;
7
use Enjoys\AssetsCollector\Content\Reader;
8
use Enjoys\AssetsCollector\Environment;
9
use Enjoys\AssetsCollector\Helpers;
10
11
class OneFileStrategy extends StrategyAbstract
12
{
13
    private int $cacheTime;
14
    private string $filePath;
15
    private string $fileUrl;
16
    private bool $fileCreated = false;
17
18
    /**
19
     * @var Asset[]
20
     */
21
    private array $notCollect = [];
22
23
    /**
24
     * Build constructor.
25
     * @param Environment $environment
26
     * @param array<Asset> $assets
27
     * @param string $type
28
     * @throws \Exception
29
     */
30 4
    public function __construct(
31
        Environment $environment,
32
        array $assets,
33
        string $type
34
    ) {
35 4
        parent::__construct($environment, $assets, $type);
36
37 4
        $this->cacheTime = $environment->getCacheTime();
38
39 4
        $filename = $this->generateFilename($type);
40
41 4
        $this->filePath = $environment->getCompileDir() . DIRECTORY_SEPARATOR . $filename;
42 4
        $this->fileUrl = $environment->getBaseUrl() . '/' . str_replace(DIRECTORY_SEPARATOR, '/', $filename);
43
44 4
        $this->notCollect = array_filter($assets, function ($asset) {
45
            /** @var Asset $asset */
46 4
            return $asset->getOptions()->isNotCollect();
47 4
        });
48
49 4
        $this->assets = array_filter($assets, function ($asset) {
50
            /** @var Asset $asset */
51 4
            return !$asset->getOptions()->isNotCollect();
52 4
        });
53
54
55 4
        $this->init();
56
    }
57
58
    /**
59
     * @param string $type css|js
60
     * @return string
61
     */
62 4
    private function generateFilename(string $type): string
63
    {
64 4
        return '_' . $type . DIRECTORY_SEPARATOR . $this->getHashId() . '.' . $type;
65
    }
66
67
    /**
68
     * @throws \Exception
69
     */
70 4
    private function init(): void
71
    {
72 4
        Helpers::createDirectory(
73 4
            pathinfo($this->filePath, PATHINFO_DIRNAME),
0 ignored issues
show
Bug introduced by
It seems like pathinfo($this->filePath...ategy\PATHINFO_DIRNAME) can also be of type array; however, parameter $path of Enjoys\AssetsCollector\Helpers::createDirectory() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

73
            /** @scrutinizer ignore-type */ pathinfo($this->filePath, PATHINFO_DIRNAME),
Loading history...
74 4
            $this->environment->getDirectoryPermissions(),
75 4
            $this->logger
76 4
        );
77
78 4
        if (!file_exists($this->filePath)) {
79 4
            Helpers::createEmptyFile($this->filePath, $this->logger);
80 4
            $this->fileCreated = true;
81
        }
82
    }
83
84 3
    private function isCacheValid(): bool
85
    {
86 3
        if ($this->fileCreated) {
87 3
            return false;
88
        }
89
        return (filemtime($this->filePath) + $this->cacheTime) > time();
90
    }
91
92
    /**
93
     * @return array<string, array|null>
94
     */
95 3
    public function getResult(): array
96
    {
97 3
        $notCollectedResult = (new ManyFilesStrategy($this->environment, $this->notCollect, $this->type))->getResult();
98
99
        try {
100 3
            if ($this->isCacheValid()) {
101
                $this->logger->info(sprintf('Use cached file: %s', $this->filePath));
102
                $this->logger->info(sprintf('Return url: %s', $this->fileUrl));
103
                return array_merge([$this->fileUrl => null], $notCollectedResult);
104
            }
105
106 3
            $output = '';
107
108 3
            foreach ($this->assets as $asset) {
109 3
                $reader = new Reader($asset, $this->environment, $this->logger);
110 3
                $output .= $reader->replaceRelativeUrlsAndCreatedSymlinks()->minify()->getContents();
111
112
113 3
                foreach ($asset->getOptions()->getSymlinks() as $optLink => $optTarget) {
114 1
                    Helpers::createSymlink($optLink, $optTarget, $this->logger);
115
                }
116
            }
117 3
            Helpers::writeFile($this->filePath, $output, 'w', $this->logger);
118
        } catch (\Exception $e) {
119
            $this->logger->notice($e->getMessage());
120
        }
121
122 3
        $this->logger->info(sprintf('Return url: %s', $this->fileUrl));
123 3
        return array_merge([$this->fileUrl => null], $notCollectedResult);
124
    }
125
126
    /**
127
     * @return string
128
     */
129
    public function getFileUrl(): string
130
    {
131
        return $this->fileUrl;
132
    }
133
134
    /**
135
     * @return string
136
     */
137 2
    public function getFilePath(): string
138
    {
139 2
        return $this->filePath;
140
    }
141
}
142