Passed
Push — fix-cache ( 8a09c1 )
by Arnaud
04:58
created

AbstractPostProcess::removesHashFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 5
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\Exception\Exception;
14
use Cecil\Util;
15
use Symfony\Component\Finder\Finder;
16
17
/**
18
 * Post Processing.
19
 */
20
abstract class AbstractPostProcess extends AbstractStep
21
{
22
    /** @var string File type (ie: 'css') */
23
    protected $type = 'type';
24
    /** @var mixed File processor */
25
    protected $processor;
26
27
    const CACHE_FILES = 'postprocess/files';
28
    const CACHE_HASH = 'postprocess/hash';
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function init($options)
34
    {
35
        if ($options['dry-run']) {
36
            $this->process = false;
37
38
            return;
39
        }
40
        if (false === $this->builder->getConfig()->get(sprintf('postprocess.%s.enabled', $this->type))) {
41
            $this->process = false;
42
43
            return;
44
        }
45
        if (true === $this->builder->getConfig()->get('postprocess.enabled')) {
46
            $this->process = true;
47
        }
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function process()
54
    {
55
        $this->setProcessor();
56
57
        call_user_func_array(
58
            $this->builder->getMessageCb(),
59
            ['POSTPROCESS', sprintf('Post-processing %s', $this->type)]
60
        );
61
62
        $extensions = $this->builder->getConfig()->get(sprintf('postprocess.%s.ext', $this->type));
63
        if (empty($extensions)) {
64
            throw new Exception(sprintf('The config key "postprocess.%s.ext" is empty', $this->type));
65
        }
66
67
        $files = Finder::create()
68
            ->files()
69
            ->in($this->builder->getConfig()->getOutputPath())
70
            ->name('/\.('.implode('|', $extensions).')$/')
71
            ->notName('/\.min\.('.implode('|', $extensions).')$/')
72
            ->sortByName(true);
73
        $max = count($files);
74
75
        if ($max <= 0) {
76
            $message = 'No files';
77
            call_user_func_array($this->builder->getMessageCb(), ['POSTPROCESS_PROGRESS', $message]);
78
79
            return;
80
        }
81
82
        $count = 0;
83
        $postprocessed = 0;
84
85
        /** @var \Symfony\Component\Finder\SplFileInfo $file */
86
        foreach ($files as $file) {
87
            $sizeBefore = $file->getSize();
88
89
            $processedFile = Util::joinFile(
90
                $this->config->getCachePath(),
91
                self::CACHE_FILES,
92
                $file->getRelativePathname()
93
            );
94
            $hash = hash_file('md5', $file->getPathname());
95
            $hashFile = Util::joinFile(
96
                $this->config->getCachePath(),
97
                self::CACHE_HASH,
98
                $this->preparesHashFile($file->getRelativePathname()).$hash
99
            );
100
101
            if (!Util::getFS()->exists($processedFile)
102
            || !Util::getFS()->exists($hashFile)
103
            ) {
104
                $count++;
105
106
                $this->processFile($file);
107
                $postprocessed++;
108
                $sizeAfter = $file->getSize();
109
110
                $this->removesHashFile($file->getRelativePathname());
111
                Util::getFS()->copy($file->getPathname(), $processedFile, true);
112
                Util::getFS()->mkdir(Util::joinFile($this->config->getCachePath(), self::CACHE_HASH));
113
                Util::getFS()->touch($hashFile);
114
115
                $message = $file->getRelativePathname();
116
                if ($sizeAfter < $sizeBefore) {
117
                    $message = sprintf(
118
                        '%s (%s Ko -> %s Ko)',
119
                        $file->getRelativePathname(),
120
                        ceil($sizeBefore / 1000),
121
                        ceil($sizeAfter / 1000)
122
                    );
123
                }
124
                call_user_func_array($this->builder->getMessageCb(), ['POSTPROCESS_PROGRESS', $message, $count, $max]);
125
            }
126
        }
127
        if ($postprocessed == 0) {
128
            $message = 'Nothing to do';
129
            call_user_func_array($this->builder->getMessageCb(), ['POSTPROCESS_PROGRESS', $message]);
130
        }
131
    }
132
133
    /**
134
     * @param string $path
135
     *
136
     * @return string
137
     */
138
    private function preparesHashFile(string $path)
139
    {
140
        return str_replace(DIRECTORY_SEPARATOR, '-', $path).'_';
141
    }
142
143
    /**
144
     * @param string $path
145
     *
146
     * @return string
147
     */
148
    private function removesHashFile(string $path)
149
    {
150
        $pattern = Util::joinFile($this->config->getCachePath(), self::CACHE_HASH, $this->preparesHashFile($path)).'*';
151
        foreach (glob($pattern) as $filename) {
152
            Util::getFS()->remove($filename);
153
        }
154
    }
155
156
    /**
157
     * Set file processor object.
158
     *
159
     * @return void
160
     */
161
    abstract public function setProcessor();
162
163
    /**
164
     * Process a file.
165
     *
166
     * @param \Symfony\Component\Finder\SplFileInfo $file
167
     *
168
     * @return void
169
     */
170
    abstract public function processFile(\Symfony\Component\Finder\SplFileInfo $file);
171
}
172