Passed
Branch dev (c2c9e6)
by Enjoys
02:26
created

OneFileStrategy::isCacheValid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
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> $assetsCollection
27
     * @param string $type
28
     * @throws \Exception
29
     */
30 3
    public function __construct(
31
        Environment $environment,
32
        array $assetsCollection,
33
        string $type
34
    ) {
35 3
        parent::__construct($environment, $assetsCollection, $type);
36
37 3
        $this->cacheTime = $environment->getCacheTime();
38
39 3
        $filename = $this->generateFilename($type);
40
41 3
        $this->filePath = $environment->getCompileDir() . DIRECTORY_SEPARATOR . $filename;
42 3
        $this->fileUrl = $environment->getBaseUrl() . '/' . str_replace(DIRECTORY_SEPARATOR, '/', $filename);
43
44 3
        $this->notCollect = array_filter($assetsCollection, function ($asset){
45
            /** @var Asset $asset */
46 3
            return $asset->isNotCollect();
47
        });
48
49 3
        $this->assetsCollection = array_filter($assetsCollection, function ($asset){
50
            /** @var Asset $asset */
51 3
            return !$asset->isNotCollect();
52
        });
53
54
55 3
        $this->init();
56
57
    }
58
59
    /**
60
     * @param string $type css|js
61
     * @return string
62
     */
63 3
    private function generateFilename(string $type): string
64
    {
65 3
        return '_' . $type . DIRECTORY_SEPARATOR . md5(serialize($this->assetsCollection)) . '.' . $type;
66
    }
67
68
    /**
69
     * @throws \Exception
70
     */
71 3
    private function init(): void
72
    {
73 3
        Helpers::createDirectory(pathinfo($this->filePath, PATHINFO_DIRNAME), $this->environment->getDirectoryPermissions(), $this->logger);
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
        Helpers::createDirectory(/** @scrutinizer ignore-type */ pathinfo($this->filePath, PATHINFO_DIRNAME), $this->environment->getDirectoryPermissions(), $this->logger);
Loading history...
74
75 3
        if (!file_exists($this->filePath)) {
76 3
            Helpers::createEmptyFile($this->filePath, $this->logger);
77 3
            $this->fileCreated = true;
78
        }
79
    }
80
81 2
    private function isCacheValid(): bool
82
    {
83 2
        if ($this->fileCreated) {
84 2
            return false;
85
        }
86
        return (filemtime($this->filePath) + $this->cacheTime) > time();
87
    }
88
89
    /**
90
     * @return array<string, array|null>
91
     */
92 2
    public function getResult(): array
93
    {
94 2
        $notCollectedResult = (new ManyFilesStrategy($this->environment, $this->notCollect, $this->type))->getResult();
95
96
        try {
97 2
            if ($this->isCacheValid()) {
98
                $this->logger->info(sprintf('Use cached file: %s', $this->filePath));
99
                $this->logger->info(sprintf('Return url: %s', $this->fileUrl));
100
                return array_merge([$this->fileUrl => null], $notCollectedResult);
101
            }
102
103 2
            $output = '';
104
105 2
            foreach ($this->assetsCollection as $asset) {
106 2
                $output .= (new Reader($asset, $this->environment, $this->logger))->getContents();
107
108 2
                $optSymlinks = (array)$asset->getOption(Asset::CREATE_SYMLINK, []);
109
110
                /** @var array<string, string> $optSymlinks */
111 2
                foreach ($optSymlinks as $optLink => $optTarget) {
112
                    Helpers::createSymlink($optLink, $optTarget, $this->logger);
113
                }
114
            }
115 2
            Helpers::writeFile($this->filePath, $output, 'w', $this->logger);
116
        } catch (\Exception $e) {
117
            $this->logger->notice($e->getMessage());
118
        }
119
120 2
        $this->logger->info(sprintf('Return url: %s', $this->fileUrl));
121 2
        return array_merge([$this->fileUrl => null], $notCollectedResult);
122
    }
123
124
    /**
125
     * @return string
126
     */
127
    public function getFileUrl(): string
128
    {
129
        return $this->fileUrl;
130
    }
131
132
    /**
133
     * @return string
134
     */
135 2
    public function getFilePath(): string
136
    {
137 2
        return $this->filePath;
138
    }
139
}
140