From 98424559e7af5773f67e31e90cbbae8972df2f36 Mon Sep 17 00:00:00 2001 From: Andrii Kotiuk Date: Fri, 11 Apr 2025 16:12:40 +0200 Subject: [PATCH] FIN-28266 update Validator parseArrayAttribute to use array by reference instead of O(n^2) --- src/Attribute.php | 36 +++++++++++++++++++++++++++++++++++- src/Validation.php | 6 ++---- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/Attribute.php b/src/Attribute.php index ebd7a11..c7adb0e 100644 --- a/src/Attribute.php +++ b/src/Attribute.php @@ -29,6 +29,16 @@ class Attribute /** @var array */ protected $keyIndexes = []; + /** + * @var array + */ + private $attributesRef = []; + + /** + * @var string|int|null + */ + private $selfKey = null; + /** * Constructor * @@ -84,6 +94,19 @@ public function getPrimaryAttribute() return $this->primaryAttribute; } + /** + * Provide a reference to all attributes, so we can dynamically exclude self + * + * @param array $allAttributes + * @param string|int $selfKey + * @return void + */ + public function setAttributesReference(array &$allAttributes, $selfKey) + { + $this->attributesRef = &$allAttributes; + $this->selfKey = $selfKey; + } + /** * Set other attributes * @@ -116,7 +139,18 @@ public function addOtherAttribute(Attribute $otherAttribute) */ public function getOtherAttributes(): array { - return $this->otherAttributes; + if (!empty($this->attributesRef) && $this->selfKey !== null) { + return array_filter( + $this->attributesRef, + function ($_, $key) { + return $key !== $this->selfKey; + }, + ARRAY_FILTER_USE_BOTH + ); + } + + // fallback to legacy if not initialized + return $this->otherAttributes ?? []; } /** diff --git a/src/Validation.php b/src/Validation.php index d74786a..da059f5 100644 --- a/src/Validation.php +++ b/src/Validation.php @@ -218,10 +218,8 @@ protected function parseArrayAttribute(Attribute $attribute): array } // set other attributes to each attributes - foreach ($attributes as $i => $attr) { - $otherAttributes = $attributes; - unset($otherAttributes[$i]); - $attr->setOtherAttributes($otherAttributes); + foreach ($this->attributes as $i => $attr) { + $attr->setAttributesReference($this->attributes, $i); } return $attributes;