anonymous//src/Util/OpcachePrimer.php$0   A
last analyzed

Complexity

Total Complexity 1

Size/Duplication

Total Lines 4
Duplicated Lines 0 %

Importance

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