PHP code example of emarref / spec

1. Go to this page and download the library: Download emarref/spec library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

emarref / spec example snippets




use Emarref\Spec\SpecificationInterface;
use Emarref\Spec\LogicalSpecificationTrait;

class MorningSpecification implements SpecificationInterface
{
    use LogicalSpecificationTrait;

    public function isSatisfiedBy($subject): bool
    {
        if (!$subject instanceof \DateTimeInterface) {
            throw new \InvalidArgumentException('Subject must be a date time object.');
        }

        $hour = (int) $subject->format('G');

        return $hour < 12;
    }
}

class AfternoonSpecification implements SpecificationInterface
{
    use LogicalSpecificationTrait;

    public function isSatisfiedBy($subject): bool
    {
        if (!$subject instanceof \DateTimeInterface) {
            throw new \InvalidArgumentException('Subject must be a date time object.');
        }

        $hour = (int) $subject->format('G');

        return $hour > 12 && $hour < 18;
    }
}

class NightSpecification implements SpecificationInterface
{
    use LogicalSpecificationTrait;

    public function isSatisfiedBy($subject): bool
    {
        if (!$subject instanceof \DateTimeInterface) {
            throw new \InvalidArgumentException('Subject must be a date time object.');
        }

        $hour = (int) $subject->format('G');

        return $hour > 17;
    }
}



$morning = new \DateTime('8am');
$isMorning = new MorningSpecification();

$isMorning->isSatisfiedBy($morning); // true



$isAfternoon = new AfternoonSpecification();
$isAfternoon->isSatisfiedBy($morning); // false



$night = new \DateTime('11pm');

$isMorning->or($isAfternoon)->isSatisfiedBy($morning); // true
$isMorning->or($isAfternoon)->isSatisfiedBy($night); // false



$isMorning->or($isAfternoon->andNot($isNight))->isSatisfiedBy($morning); // true



class StoreIsOpen implements SpecificationInterface
{
    use LogicalSpecificationTrait;

    public function isSatisfiedBy($subject): bool
    {
        if (!$subject instanceof \DateTimeInterface) {
            throw new \InvalidArgumentException('Subject must be a date time object.');
        }

        $isMorning = new MorningSpec();
        $isAfternoon = new AfternoonSpec();

        return $isMorning->or($isAfternoon)->isSatisfiedBy($subject);
    }
}

$storeIsOpen = new StoreIsOpen();
$storeIsOpen->isSatisfiedBy(new DateTime('10am')); // true
$storeIsOpen->isSatisfiedBy(new DateTime('11pm')); // false