Passed
Push — cache ( 9a2fba...c787e1 )
by Arnaud
05:10
created

Save::clearCache()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Step\Assets;
15
16
use Cecil\Assets\Cache;
17
use Cecil\Exception\RuntimeException;
18
use Cecil\Step\AbstractStep;
19
use Cecil\Util;
20
21
/**
22
 * Assets saving.
23
 */
24
class Save extends AbstractStep
25
{
26
    protected Cache $cache;
27
    protected string $cacheKey;
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function getName(): string
33
    {
34
        return 'Saving assets';
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function init(array $options): void
41
    {
42
        // should clear cache?
43
        $this->clearCache();
44
45
        if ($options['dry-run']) {
46
            return;
47
        }
48
49
        $this->cache = new \Cecil\Assets\Cache($this->builder, (string) $this->config->get('cache.assets.dir'));
50
        $this->cacheKey = \sprintf('_list__%s', $this->builder->getVersion());
51
        if (empty($this->assets) && $this->cache->has($this->cacheKey)) {
52
            $this->builder->setAssets($this->cache->get($this->cacheKey));
53
        }
54
55
        $this->canProcess = true;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     * Note: a file from `static/` with the same name will NOT be overridden.
61
     *
62
     * @throws RuntimeException
63
     */
64
    public function process(): void
65
    {
66
        $total = \count($this->builder->getAssets());
67
        $count = 0;
68
        foreach ($this->builder->getAssets() as $path) {
69
            $count++;
70
            Util\File::getFS()->copy($this->cache->getContentFilePathname($path), Util::joinFile($this->config->getOutputPath(), $path), false);
71
            $message = \sprintf('Asset "%s" saved', $path);
72
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
73
        }
74
        $this->cache->set($this->cacheKey, $this->builder->getAssets());
75
    }
76
77
    /**
78
     * Deletes cache directory.
79
     */
80
    private function clearCache(): void
81
    {
82
        if ($this->config->get('cache.enabled') === false) {
83
            try {
84
                Util\File::getFS()->remove($this->config->getCachePath());
85
            } catch (\Exception) {
86
                throw new RuntimeException(\sprintf('Can\'t remove cache directory "%s".', $this->config->getCachePath()));
87
            }
88
        }
89
    }
90
}
91