ArrayIntersector.php
58 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Pelago\Emogrifier\Utilities; |
| 6 | |
| 7 | /** |
| 8 | * When computing many array intersections using the same array, it is more efficient to use `array_flip()` first and |
| 9 | * then `array_intersect_key()`, than `array_intersect()`. See the discussion at |
| 10 | * {@link https://stackoverflow.com/questions/6329211/php-array-intersect-efficiency Stack Overflow} for more |
| 11 | * information. |
| 12 | * |
| 13 | * Of course, this is only possible if the arrays contain integer or string values, and either don't contain duplicates, |
| 14 | * or that fact that duplicates will be removed does not matter. |
| 15 | * |
| 16 | * This class takes care of the detail. |
| 17 | * |
| 18 | * @internal |
| 19 | */ |
| 20 | class ArrayIntersector |
| 21 | { |
| 22 | /** |
| 23 | * the array with which the object was constructed, with all its keys exchanged with their associated values |
| 24 | * |
| 25 | * @var array<array-key, array-key> |
| 26 | */ |
| 27 | private $invertedArray; |
| 28 | |
| 29 | /** |
| 30 | * Constructs the object with the array that will be reused for many intersection computations. |
| 31 | * |
| 32 | * @param array<array-key, array-key> $array |
| 33 | */ |
| 34 | public function __construct(array $array) |
| 35 | { |
| 36 | $this->invertedArray = \array_flip($array); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Computes the intersection of `$array` and the array with which this object was constructed. |
| 41 | * |
| 42 | * @param array<array-key, array-key> $array |
| 43 | * |
| 44 | * @return array<array-key, array-key> |
| 45 | * Returns an array containing all of the values in `$array` whose values exist in the array |
| 46 | * with which this object was constructed. Note that keys are preserved, order is maintained, but |
| 47 | * duplicates are removed. |
| 48 | */ |
| 49 | public function intersectWith(array $array): array |
| 50 | { |
| 51 | $invertedArray = \array_flip($array); |
| 52 | |
| 53 | $invertedIntersection = \array_intersect_key($invertedArray, $this->invertedArray); |
| 54 | |
| 55 | return \array_flip($invertedIntersection); |
| 56 | } |
| 57 | } |
| 58 |