|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Trims the common prefix from the full_path index of cached scripts |
| 4 | + * |
| 5 | + * PHP version 5.5 |
| 6 | + * |
| 7 | + * @category OpCacheGUI |
| 8 | + * @package Format |
| 9 | + * @author Pieter Hordijk <info@pieterhordijk.com> |
| 10 | + * @copyright Copyright (c) 2014 Pieter Hordijk <https://github.com/PeeHaa> |
| 11 | + * @license http://www.opensource.org/licenses/mit-license.html MIT License |
| 12 | + * @version 1.0.0 |
| 13 | + */ |
| 14 | +namespace OpCacheGUI\Format; |
| 15 | + |
| 16 | +/** |
| 17 | + * Trims the common prefix from the full_path index of cached scripts |
| 18 | + * |
| 19 | + * @category OpCacheGUI |
| 20 | + * @package Format |
| 21 | + * @author Pieter Hordijk <info@pieterhordijk.com> |
| 22 | + */ |
| 23 | +class Prefix implements Trimmer |
| 24 | +{ |
| 25 | + /** |
| 26 | + * Trims the common prefix from an array of strings |
| 27 | + * |
| 28 | + * @param array $scripts The list of scripts |
| 29 | + * |
| 30 | + * @return array The trimmed strings |
| 31 | + */ |
| 32 | + public function trim(array $scripts) |
| 33 | + { |
| 34 | + $length = $this->getPrefixLength($scripts); |
| 35 | + |
| 36 | + foreach ($scripts as $index => $script) { |
| 37 | + $scripts[$index]['full_path'] = mb_substr($script['full_path'], $length); |
| 38 | + } |
| 39 | + |
| 40 | + return $scripts; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Gets the length of the common prefix to trim |
| 45 | + * |
| 46 | + * @param array $scripts The list of scripts |
| 47 | + * |
| 48 | + * @return int The length of the common prefix |
| 49 | + */ |
| 50 | + private function getPrefixLength(array $scripts) |
| 51 | + { |
| 52 | + $prefix = $scripts[0]['full_path']; |
| 53 | + |
| 54 | + foreach ($scripts as $script) { |
| 55 | + if ($prefix === '') { |
| 56 | + return 0; |
| 57 | + } |
| 58 | + |
| 59 | + if (strpos($script['full_path'], $prefix) === 0) { |
| 60 | + continue; |
| 61 | + } |
| 62 | + |
| 63 | + $prefix = $this->findLongestPrefix($prefix, $script['full_path']); |
| 64 | + } |
| 65 | + |
| 66 | + return mb_strlen($prefix); |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Get the longest common prefix between two strings |
| 71 | + * |
| 72 | + * @param string $prefix The current common prefix |
| 73 | + * @param string $path The path to match against the common prefix |
| 74 | + * |
| 75 | + * @return string The common prefix |
| 76 | + */ |
| 77 | + private function findLongestPrefix($prefix, $path) |
| 78 | + { |
| 79 | + $prefixChars = str_split($prefix); |
| 80 | + $pathChars = str_split($path); |
| 81 | + |
| 82 | + foreach ($prefixChars as $index => $char) { |
| 83 | + if ($char !== $pathChars[$index]) { |
| 84 | + return mb_substr($prefix, 0, $index); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + return $prefix; |
| 89 | + } |
| 90 | +} |
0 commit comments