[ Index ] |
PHP Cross Reference of phpBB-3.3.14-deutsch |
[Summary view] [Print] [Text view]
1 <?php declare(strict_types=1); 2 3 /** 4 * @package s9e\RegexpBuilder 5 * @copyright Copyright (c) 2016-2022 The s9e authors 6 * @license http://www.opensource.org/licenses/mit-license.php The MIT License 7 */ 8 namespace s9e\RegexpBuilder\Passes; 9 10 use const false, true; 11 use function array_slice, count; 12 13 /** 14 * Replaces (?:axx|ayy) with a(?:xx|yy) 15 */ 16 class MergePrefix extends AbstractPass 17 { 18 /** 19 * {@inheritdoc} 20 */ 21 protected function runPass(array $strings): array 22 { 23 $newStrings = []; 24 foreach ($this->getStringsByPrefix($strings) as $prefix => $strings) 25 { 26 $newStrings[] = (isset($strings[1])) ? $this->mergeStrings($strings) : $strings[0]; 27 } 28 29 return $newStrings; 30 } 31 32 /** 33 * Get the number of leading elements common to all given strings 34 * 35 * @param array[] $strings 36 * @return integer 37 */ 38 protected function getPrefixLength(array $strings): int 39 { 40 $len = 1; 41 $cnt = count($strings[0]); 42 while ($len < $cnt && $this->stringsMatch($strings, $len)) 43 { 44 ++$len; 45 } 46 47 return $len; 48 } 49 50 /** 51 * Return given strings grouped by their first element 52 * 53 * NOTE: assumes that this pass is run before the first element of any string could be replaced 54 * 55 * @param array[] $strings 56 * @return array[] 57 */ 58 protected function getStringsByPrefix(array $strings): array 59 { 60 $byPrefix = []; 61 foreach ($strings as $string) 62 { 63 $byPrefix[$string[0]][] = $string; 64 } 65 66 return $byPrefix; 67 } 68 69 /** 70 * Merge given strings into a new single string 71 * 72 * @param array[] $strings 73 * @return array 74 */ 75 protected function mergeStrings(array $strings): array 76 { 77 $len = $this->getPrefixLength($strings); 78 $newString = array_slice($strings[0], 0, $len); 79 foreach ($strings as $string) 80 { 81 $newString[$len][] = array_slice($string, $len); 82 } 83 84 return $newString; 85 } 86 87 /** 88 * Test whether all given strings' elements match at given position 89 * 90 * @param array[] $strings 91 * @param integer $pos 92 * @return bool 93 */ 94 protected function stringsMatch(array $strings, int $pos): bool 95 { 96 $value = $strings[0][$pos]; 97 foreach ($strings as $string) 98 { 99 if (!isset($string[$pos]) || $string[$pos] !== $value) 100 { 101 return false; 102 } 103 } 104 105 return true; 106 } 107 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Mon Nov 25 19:05:08 2024 | Cross-referenced by PHPXref 0.7.1 |