PHP code example of koba / filter-builder-core

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

    

koba / filter-builder-core example snippets




use Koba\FilterBuilder\Core\Configuration\Configuration;
use Koba\FilterBuilder\Core\Enums\ConstraintType;
use Koba\FilterBuilder\Core\Enums\Operation;
use Koba\FilterBuilder\Core\ObjectStrategy\ObjectStrategy;

// Define your class
class Product
{
    public function __construct(
        public string $name,
        public float $price,
        public string $category,
    ) {}
}

// Create a product instance
$product = new Product("Laptop", 999.99, "Electronics");

// Define filter criteria (typically from API request)
$filterArray = [
    'type' => 'group',
    'operation' => 'and',
    'children' => [
        ['name' => 'name', 'operation' => 'starts_with', 'value' => 'Lap'],
        ['name' => 'price', 'operation' => 'less_than', 'value' => 1000],
    ]
];

// Configure filterable fields
$strategy = new ObjectStrategy(Product::class);
$configuration = (new Configuration($strategy))
    ->addRuleEntry(
        'name',
        ConstraintType::STRING,
        [Operation::EQUALS, Operation::STARTS_WITH],
        fn($factory) => $factory->makeRule(fn($obj) => $obj->name)
    )
    ->addRuleEntry(
        'price',
        ConstraintType::NUMBER,
        [Operation::LESS_THAN, Operation::GREATER_THAN, Operation::EQUALS],
        fn($factory) => $factory->makeRule(fn($obj) => $obj->price)
    )
    ->addRuleEntry(
        'category',
        ConstraintType::DROPDOWN,
        [Operation::EQUALS, Operation::ONE_OF],
        fn($factory) => $factory->makeRule(fn($obj) => $obj->category)
    );

// Get the filter and check if object adheres
$filter = $configuration->getFilter($filterArray);

if ($filter->adheres($product)) {
    echo "Product matches the filter!";
}

$configuration = new Configuration($strategy);

use Koba\FilterBuilder\Core\Translation\Dutch;

$configuration = new Configuration(
    $strategy,
    new Dutch(), // Translation
    null // Custom BoundFilterFactory (optional)
);

$configuration->addRuleEntry(
    'fieldName',                    // Field identifier
    ConstraintType::STRING,         // Data type
    [Operation::EQUALS],            // Supported operations
    fn($factory) => $factory->makeRule(
        fn($obj) => $obj->fieldName // Property accessor
    )
);

$configuration->addRuleEntry(
    'status',
    ConstraintType::DROPDOWN,
    [Operation::EQUALS, Operation::ONE_OF],
    fn($factory) => $factory->makeRule(fn($obj) => $obj->status),
    extraValidation: function($value, $addError) {
        $validStatuses = ['active', 'inactive', 'pending'];
        $values = is_array($value) ? $value : [$value];

        foreach ($values as $v) {
            if (!in_array($v, $validStatuses)) {
                $addError("Invalid status: $v");
            }
        }
    }
);

class Order
{
    public function __construct(
        public int $id,
        public Customer $customer,
    ) {}
}

class Customer
{
    public function __construct(
        public string $name,
        public string $email,
    ) {}
}

// Configure customer filters
$customerStrategy = new ObjectStrategy(Customer::class);
$customerConfig = (new Configuration($customerStrategy))
    ->addRuleEntry(
        'name',
        ConstraintType::STRING,
        [Operation::EQUALS, Operation::STARTS_WITH],
        fn($factory) => $factory->makeRule(fn($customer) => $customer->name)
    );

// Configure order filters with customer relation
$orderStrategy = new ObjectStrategy(Order::class);
$orderConfig = (new Configuration($orderStrategy))
    ->addRuleEntry(
        'id',
        ConstraintType::NUMBER,
        [Operation::EQUALS],
        fn($factory) => $factory->makeRule(fn($order) => $order->id)
    )
    ->addRelationEntry(
        'customer',
        fn($factory) => $factory->makeRelation(
            fn($order) => $order->customer
        ),
        $customerConfig
    );

// Filter by customer name
$filterArray = [
    'type' => 'group',
    'operation' => 'and',
    'children' => [
        [
            'name' => 'customer',
            'operation' => 'and',
            'children' => [
                ['name' => 'name', 'operation' => 'equals', 'value' => 'John Doe']
            ]
        ]
    ]
];

$filter = $orderConfig->getFilter($filterArray);

[
    'type' => 'group',
    'operation' => 'and', // or 'or'
    'children' => [
        // Child filters (rules or nested groups)
    ]
]

[
    'name' => 'fieldName',
    'operation' => 'equals', // or other operations
    'value' => 'someValue'
]

[
    'name' => 'category',
    'operation' => 'one_of',
    'value' => ['Electronics', 'Books', 'Clothing']
]

[
    'name' => 'relationName',
    'operation' => 'and', // or 'or'
    'children' => [
        // Filters for related object
    ]
]

$filterArray = [
    'type' => 'group',
    'operation' => 'and',
    'children' => [
        [
            'type' => 'group',
            'operation' => 'or',
            'children' => [
                ['name' => 'category', 'operation' => 'equals', 'value' => 'Electronics'],
                ['name' => 'category', 'operation' => 'equals', 'value' => 'Books'],
            ]
        ],
        ['name' => 'price', 'operation' => 'less_than', 'value' => 100],
        ['name' => 'inStock', 'operation' => 'equals', 'value' => true],
    ]
];

use Koba\FilterBuilder\Core\Exceptions\ValidationException;

try {
    $filter = $configuration->getFilter($invalidFilterArray);
} catch (ValidationException $e) {
    // Get all error messages
    $errors = $e->getMessages();

    foreach ($errors as $error) {
        echo $error . "\n";
    }
}

use Koba\FilterBuilder\Core\Translation\English;
use Koba\FilterBuilder\Core\Translation\Dutch;

// English (default)
$configuration = new Configuration($strategy, new English());

// Dutch
$configuration = new Configuration($strategy, new Dutch());

use Koba\FilterBuilder\Core\Contracts\Translationinterface;
use Koba\FilterBuilder\Core\Enums\ErrorMessage;
use Koba\FilterBuilder\Core\Enums\ErrorFieldMessage;

class Spanish implements Translationinterface
{
    public function translateError(ErrorMessage $message): string
    {
        return match($message) {
            ErrorMessage::INVALID_CONFIGURATION => 'Configuración inválida',
            // ... other translations
        };
    }

    public function translateErrorWithField(
        ErrorFieldMessage $message,
        string $field
    ): string {
        return match($message) {
            ErrorFieldMessage::MISSING_CONFIGURATION_ENTRY =>
                "Falta la entrada de configuración: $field",
            // ... other translations
        };
    }
}

$configuration = new Configuration($strategy, new Spanish());

$products = [
    new Product("Laptop", 999.99, "Electronics"),
    new Product("Book", 19.99, "Books"),
    new Product("Phone", 599.99, "Electronics"),
];

$filter = $configuration->getFilter($filterArray);

$filtered = array_filter($products, fn($product) => $filter->adheres($product));

use Koba\FilterBuilder\Core\Contracts\BoundFilterFactoryInterface;
use Koba\FilterBuilder\Core\Factories\BoundFilterFactory;

class CustomBoundFilterFactory extends BoundFilterFactory
{
    // Override methods as needed
}

$configuration = new Configuration(
    $strategy,
    null,
    new CustomBoundFilterFactory($configuration)
);

use Koba\FilterBuilder\Core\Contracts\StrategyInterface;
use Koba\FilterBuilder\Core\Contracts\BoundFilterInterface;

class DatabaseQueryStrategy implements StrategyInterface
{
    // Implement strategy for building database queries
}