Completed
Push — master ( 0c7238...cc3d38 )
by Jitendra
02:55
created

OpcachePrimer::normalizePaths()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace PhalconExt\Util;
4
5
/**
6
 * Prime the opcache - so requests are fast from the first ever hit.
7
 *
8
 * @author  Jitendra Adhikari <[email protected]>
9
 * @license MIT
10
 *
11
 * @link    https://github.com/adhocore/phalcon-ext
12
 */
13
class OpcachePrimer
14
{
15
    public function __construct()
16
    {
17
        if (!\function_exists('opcache_compile_file')) {
18
            throw new \Exception('Opcache is not enabled');
19
        }
20
    }
21
22
    /**
23
     * Prime/Warm the cache for given paths.
24
     *
25
     * @param array $paths
26
     *
27
     * @return int The count of files whose opcache primed/warmed.
28
     */
29
    public function prime(array $paths): int
30
    {
31
        $cached = 0;
32
33
        foreach ($this->normalizePaths($paths) as $path) {
34
            $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
35
36
            foreach ($this->filter($iterator) as $file) {
37
                $cached += (int) \opcache_compile_file($file->getRealPath());
38
            }
39
        }
40
41
        return $cached;
42
    }
43
44
    /**
45
     * Normalize paths.
46
     *
47
     * @param array $paths
48
     *
49
     * @return array
50
     */
51
    protected function normalizePaths(array $paths): array
52
    {
53
        return \array_filter(\array_map('realpath', $paths));
54
    }
55
56
    /**
57
     * Filter php files.
58
     *
59
     * @param \RecursiveIteratorIterator $iterator
60
     *
61
     * @return \FilterIterator
62
     */
63
    protected function filter(\RecursiveIteratorIterator $iterator): \FilterIterator
64
    {
65
        return new class($iterator) extends \FilterIterator {
66
            public function accept(): bool
67
            {
68
                return $this->getInnerIterator()->current()->getExtension() === 'php';
69
            }
70
        };
71
    }
72
}
73