PHP code example of oofbar / craft-twig-toolbox

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

    

oofbar / craft-twig-toolbox example snippets


 return [
    'filters' => [],
    'functions' => [],
    'globals' => [],
    'tests' => [],
];

 return [
    'filters' => [
        'salePrice' => function(float $price): float {
            return $price * 0.9;
        },
    ],
];

 return [
    'functions' => [
        'getDeals' => function(): array {
            return Entry::find()
                ->section('products')
                ->onSale(true)
                ->all();
        },
        'log' => function(mixed $message): void {
            Craft::getLogger()->log($message);
        },
    ],
];

 return [
    'globals' => [
        'cutoffTime' => (new \DateTime)->modify('midnight'),
    ],
];



use craft\elements\User;

return [
    'tests' => [
        'expensive' => function(float $value): bool {
            return $value > 10.0;
        },
        'member' => function(User $user): bool {
            return $user->isInGroup('members');
        },
    ],
];

use craft\helpers\Number;

return [
    'filters' => [
        // Built-in PHP functions:
        'chunk' => 'array_chunk',
        // Craft helper proxy:
        'roman' => [Number::class, 'upperRoman'],
    ],
];



use craft\elements\Entry;

return [
    'tests' => [
        'expensive' => function(float|Entry $value): bool {
            // Normalize an Entry into a scalar field value:
            if ($value instanceof Entry) {
                $value = $value->price;
            }

            return $value > 10.0;
        },
    ],
];

 return [
    'functions' => [
        'bem' => function(string $base, array $flags): string {
            $classNames = [$base];

            // Create BEM-style class names, ignoring empty flags:
            foreach (array_filter($flags) as $flag) {
                $classNames[] = "{$base}--{$flag}";
            }

            return join(' ', array_unique($classNames));
        },
    ],
];
twig
<div class="{{ bem('product', [
    product is expensive ? 'expensive' : null,
    currentUser is member ? 'member-pricing' : null,
]) }}">
    {{ product.title }}
</div>