Completed
Push — feature-images-optim ( 953358...9d767f )
by Arnaud
02:06
created

OptimizeImages::init()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 3
nc 4
nop 1
1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Step;
10
11
use Spatie\ImageOptimizer\OptimizerChainFactory;
12
use Symfony\Component\Finder\Finder;
13
14
/**
15
 * Images Optimization.
16
 */
17
class OptimizeImages extends AbstractStep
18
{
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function init($options)
23
    {
24
        if (is_dir($this->builder->getConfig()->getOutputPath())) {
25
            $this->process = true;
26
        }
27
        if (false === $this->builder->getConfig()->get('optimize.images.enabled')) {
28
            $this->process = false;
29
        }
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function process()
36
    {
37
        call_user_func_array($this->builder->getMessageCb(), ['OPTIMIZE', 'Optimizing images']);
38
39
        $optimizerChain = OptimizerChainFactory::create();
40
41
        $data = Finder::create()
42
            ->files()
43
            ->in($this->builder->getConfig()->getOutputPath())
44
            ->name('/\.('.implode('|', $this->builder->getConfig()->get('optimize.images.ext')).')$/')
45
            ->sortByName(true);
46
47
        $count = 0;
48
        $max = count($data);
49
50
        if ($max <= 0) {
51
            $message = 'No images';
52
            call_user_func_array($this->builder->getMessageCb(), ['OPTIMIZE_PROGRESS', $message]);
53
54
            return;
55
        }
56
57
        /* @var $file \Symfony\Component\Finder\SplFileInfo */
58
        foreach ($data as $file) {
59
            $count++;
60
61
            $sizeBefore = $file->getSize();
62
            $optimizerChain->optimize($file->getPathname());
63
            $sizeAfter = $file->getSize();
64
            //$sizeAfter = filesize($file->getPathname());
65
66
            $message = sprintf(
67
                '"%s" processed (%s Ko -> %s Ko)',
68
                $file->getFilename(),
69
                $sizeBefore/1000,
70
                $sizeAfter/1000
71
            );
72
            call_user_func_array($this->builder->getMessageCb(), ['OPTIMIZE_PROGRESS', $message, $count, $max]);
73
        }
74
    }
75
}
76