PHP code example of bakame / spec

1. Go to this page and download the library: Download bakame/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/ */

    

bakame / spec example snippets



$invoiceCollection = array_filter(
    fn (Invoice $invoice): bool => $sendToCollection->isSatisfiedBy($invoice),
    $respository->getInvoices()
);

foreach ($invoiceCollection as $invoice) {
    $invoice->sendToCollection();
}


$invoiceCollection = new CallbackFilterIterator(
    $respository->getInvoices(),
    fn (Invoice $invoice): bool => $sendToCollection->isSatisfiedBy($invoice),
);

foreach ($invoiceCollection as $invoice) {
    $invoice->sendToCollection();
}


$invoiceCollection = $respository->getInvoices()->filter(
    fn (Invoice $invoice): bool => $sendToCollection->isSatisfiedBy($invoice)
);

foreach ($invoiceCollection as $invoice) {
    $invoice->sendToCollection();
}



declare(strict_types=1);

use Bakame\Specification\Specification;
use Illuminate\Support\Collection;

Collection::macro('satisfies', fn (Specification $specification): Collection =>
    $this->filter(
        fn ($item): bool => $specification->isSatisfiedBy($item);
    )
);

$invoiceCollection = $invoices->all()->satifies($sendToCollection);
foreach ($invoiceCollection as $invoice) {
    $invoice->sendToCollection();
}


use Bakame\Specification\Specification;

final class OverDueSpecification implements Specification
{
    public function __construct(
        private DateTimeImmutable $date = new DateTimeImmutable('NOW', new DateTimeZone('UTC'))
    ) {
    }

    public function isSatisfiedBy(mixed $subject) : bool
    {
        return $subject instanceof Invoice
            && $subject->getDueDate() < $this->date;
    }


use Bakame\Specification\Chain;

$overDue = new OverDueSpecification();
$noticeSent = new NoticeSentSpecification();
$inCollection = new InCollectionSpecification();

$sendToCollection = Chain::one($overDue)
    ->and($noticeSent)
    ->andNot($inCollection);

foreach ($service->getInvoices() as $invoice) {
    if ($sendToCollection->isSatisfiedBy($invoice)) {
        $invoice->sendToCollection();
    }