DocumentationWarmer::addFilter()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Knp\MegaMAN\Cache;
4
5
use Knp\MegaMAN\Filter;
6
use Symfony\Component\Finder\Finder;
7
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
8
9
class DocumentationWarmer implements CacheWarmerInterface
10
{
11
    /**
12
     * @var string
13
     */
14
    private $cache;
15
16
    /**
17
     * @var string
18
     */
19
    private $documentation;
20
21
    /**
22
     * @var string
23
     */
24
    private $vendor;
25
26
    /**
27
     * @var Finder
28
     */
29
    private $finder;
30
31
    /**
32
     * @var Filter[]
33
     */
34
    private $filters;
35
36
    /**
37
     * @param string      $cache
38
     * @param string      $documentation
39
     * @param string      $vendor
40
     * @param Finder|null $finder
41
     */
42
    public function __construct($cache, $documentation, $vendor, Finder $finder = null)
43
    {
44
        $this->cache         = $cache;
45
        $this->documentation = $documentation;
46
        $this->vendor        = $vendor;
47
        $this->finder        = null === $finder ? new Finder() : $finder;
48
        $this->filters       = [];
49
    }
50
51
    /**
52
     * @param Filter $filter
53
     */
54
    public function addFilter(Filter $filter)
55
    {
56
        $this->filters[] = $filter;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function warmUp($cacheDir)
63
    {
64
        $files = $this
65
            ->finder
66
            ->in($this->vendor)
67
            ->files()
68
            ->name($this->documentation)
69
        ;
70
71
        $definitions = [];
72
73
        foreach ($files as $file) {
74
            $definitions[] = ['readme' => $file->getRealpath()];
75
        }
76
77
        foreach ($this->filters as $filter) {
78
            $definitions = $filter($definitions);
79
        }
80
81
        $packages = array_map(function ($e) {
82
            return $e['package'];
83
        }, $definitions);
84
        $definitions = array_combine($packages, $definitions);
85
86
        ksort($definitions);
87
88
        $export = json_encode($definitions, JSON_PRETTY_PRINT);
89
90
        file_put_contents($this->cache, $export);
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    public function isOptional()
97
    {
98
        return false;
99
    }
100
}
101