3.8. Specification

    You can also find this code on

    SpecificationInterface.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\Specification;
    4.  
    5. interface SpecificationInterface
    6. {
    7. public function isSatisfiedBy(Item $item): bool;
    8. }

    OrSpecification.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\Specification;
    4.  
    5. class PriceSpecification implements SpecificationInterface
    6. {
    7. /**
    8. * @var float|null
    9. */
    10. private $maxPrice;
    11. /**
    12. * @var float|null
    13. */
    14. private $minPrice;
    15.  
    16. /**
    17. * @param float $minPrice
    18. * @param float $maxPrice
    19. */
    20. public function __construct($minPrice, $maxPrice)
    21. {
    22. $this->minPrice = $minPrice;
    23. $this->maxPrice = $maxPrice;
    24. }
    25.  
    26. public function isSatisfiedBy(Item $item): bool
    27. {
    28. if ($this->maxPrice !== null && $item->getPrice() > $this->maxPrice) {
    29. return false;
    30. }
    31.  
    32. if ($this->minPrice !== null && $item->getPrice() < $this->minPrice) {
    33. return false;
    34. }
    35. return true;
    36. }
    37. }

    AndSpecification.php

    NotSpecification.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\Specification;
    4.  
    5. class NotSpecification implements SpecificationInterface
    6. {
    7. /**
    8. * @var SpecificationInterface
    9. */
    10. private $specification;
    11.  
    12. public function __construct(SpecificationInterface $specification)
    13. {
    14. $this->specification = $specification;
    15. }
    16.  
    17. public function isSatisfiedBy(Item $item): bool
    18. {
    19. return !$this->specification->isSatisfiedBy($item);
    20. }
    21. }