Specification pattern - performance optimization

This commit is contained in:
vuurball
2017-04-12 18:01:43 +03:00
parent c3116c9e91
commit eb847fbfb2
2 changed files with 14 additions and 9 deletions

View File

@@ -17,14 +17,17 @@ class AndSpecification implements SpecificationInterface
$this->specifications = $specifications; $this->specifications = $specifications;
} }
/**
* if at least one specification is false, return false, else return true.
*/
public function isSatisfiedBy(Item $item): bool public function isSatisfiedBy(Item $item): bool
{ {
$satisfied = [];
foreach ($this->specifications as $specification) { foreach ($this->specifications as $specification) {
$satisfied[] = $specification->isSatisfiedBy($item); if (!$specification->isSatisfiedBy($item)) {
return false;
}
} }
return !in_array(false, $satisfied); return true;
} }
} }

View File

@@ -17,14 +17,16 @@ class OrSpecification implements SpecificationInterface
$this->specifications = $specifications; $this->specifications = $specifications;
} }
/**
* if at least one specification is true, return true, else return false
*/
public function isSatisfiedBy(Item $item): bool public function isSatisfiedBy(Item $item): bool
{ {
$satisfied = [];
foreach ($this->specifications as $specification) { foreach ($this->specifications as $specification) {
$satisfied[] = $specification->isSatisfiedBy($item); if ($specification->isSatisfiedBy($item)) {
return true;
}
} }
return false;
return in_array(true, $satisfied);
} }
} }