Completed
Push — master ( 4cf3c5...0c7238 )
by Jitendra
11s
created

OpcachePrimer::__construct()   A

Complexity

Conditions 2
Paths 2

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 2
eloc 2
nc 2
nop 0
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 ($paths as $path) {
34
            if (false === $path = \realpath($path)) {
35
                continue;
36
            }
37
38
            $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
39
40
            foreach ($this->filter($iterator) as $file) {
41
                \opcache_compile_file($file->getRealPath()) && $cached++;
42
            }
43
        }
44
45
        return $cached;
46
    }
47
48
    /**
49
     * Filter php files.
50
     *
51
     * @param \RecursiveIteratorIterator $iterator
52
     *
53
     * @return \FilterIterator
54
     */
55
    protected function filter(\RecursiveIteratorIterator $iterator): \FilterIterator
56
    {
57
        return new class($iterator) extends \FilterIterator {
58
            public function accept(): bool
59
            {
60
                return $this->getInnerIterator()->current()->getExtension() === 'php';
61
            }
62
        };
63
    }
64
}
65