Passed
Pull Request — assets (#722)
by Arnaud
07:45 queued 05:19
created

AbstractPostProcess::preparesHashFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Step;
12
13
use Cecil\Cache\Cache;
14
use Cecil\Exception\Exception;
15
use Cecil\Util;
16
use Symfony\Component\Finder\Finder;
17
18
/**
19
 * Post Processing.
20
 */
21
abstract class AbstractPostProcess extends AbstractStep
22
{
23
    /** @var string File type (ie: 'css') */
24
    protected $type = 'type';
25
    /** @var mixed File processor */
26
    protected $processor;
27
28
    const CACHE_FILES = 'postprocess/files';
29
    const CACHE_HASH = 'postprocess/hash';
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function init($options)
35
    {
36
        if ($options['dry-run']) {
37
            $this->process = false;
38
39
            return;
40
        }
41
        if (false === $this->builder->getConfig()->get(sprintf('postprocess.%s.enabled', $this->type))) {
42
            $this->process = false;
43
44
            return;
45
        }
46
        if (true === $this->builder->getConfig()->get('postprocess.enabled')) {
47
            $this->process = true;
48
        }
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function process()
55
    {
56
        $this->setProcessor();
57
58
        call_user_func_array(
59
            $this->builder->getMessageCb(),
60
            ['POSTPROCESS', sprintf('Post-processing %s', $this->type)]
61
        );
62
63
        $extensions = $this->builder->getConfig()->get(sprintf('postprocess.%s.ext', $this->type));
64
        if (empty($extensions)) {
65
            throw new Exception(sprintf('The config key "postprocess.%s.ext" is empty', $this->type));
66
        }
67
68
        $files = Finder::create()
69
            ->files()
70
            ->in($this->builder->getConfig()->getOutputPath())
71
            ->name('/\.('.implode('|', $extensions).')$/')
72
            ->notName('/\.min\.('.implode('|', $extensions).')$/')
73
            ->sortByName(true);
74
        $max = count($files);
75
76
        if ($max <= 0) {
77
            $message = 'No files';
78
            call_user_func_array($this->builder->getMessageCb(), ['POSTPROCESS_PROGRESS', $message]);
79
80
            return;
81
        }
82
83
        $count = 0;
84
        $postprocessed = 0;
85
86
        /** @var \Symfony\Component\Finder\SplFileInfo $file */
87
        foreach ($files as $file) {
88
            $count++;
89
            $sizeBefore = $file->getSize();
90
            $message = $file->getRelativePathname();
91
92
            $cache = new Cache($this->builder, 'postprocess', $this->config->getOutputPath());
93
            if (!$cache->isExists($file->getPathname())) {
94
                $hash = $cache->getHash($file->getPathname());
95
                $this->processFile($file);
96
                $postprocessed++;
97
                $sizeAfter = $file->getSize();
98
                if ($sizeAfter < $sizeBefore) {
99
                    $message = sprintf(
100
                        '%s (%s Ko -> %s Ko)',
101
                        $file->getRelativePathname(),
102
                        ceil($sizeBefore / 1000),
103
                        ceil($sizeAfter / 1000)
104
                    );
105
                }
106
                $cache->save($file->getPathname(), $hash);
107
            }
108
            call_user_func_array($this->builder->getMessageCb(), ['POSTPROCESS_PROGRESS', $message, $count, $max]);
109
        }
110
        if ($postprocessed == 0) {
0 ignored issues
show
introduced by
The condition $postprocessed == 0 is always true.
Loading history...
111
            $message = '> Nothing to do';
112
            call_user_func_array($this->builder->getMessageCb(), ['POSTPROCESS_PROGRESS', $message]);
113
        }
114
    }
115
116
    /**
117
     * @param string $path
118
     *
119
     * @return string
120
     */
121
    private function preparesHashFile(string $path): string
122
    {
123
        return str_replace(DIRECTORY_SEPARATOR, '-', $path).'_';
124
    }
125
126
    /**
127
     * @param string $path
128
     *
129
     * @return void
130
     */
131
    private function removesHashFile(string $path): void
132
    {
133
        $pattern = Util::joinFile($this->config->getCachePath(), self::CACHE_HASH, $this->preparesHashFile($path)).'*';
134
        foreach (glob($pattern) as $filename) {
135
            Util::getFS()->remove($filename);
136
        }
137
    }
138
139
    /**
140
     * Set file processor object.
141
     *
142
     * @return void
143
     */
144
    abstract public function setProcessor();
145
146
    /**
147
     * Process a file.
148
     *
149
     * @param \Symfony\Component\Finder\SplFileInfo $file
150
     *
151
     * @return void
152
     */
153
    abstract public function processFile(\Symfony\Component\Finder\SplFileInfo $file);
154
}
155