Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twig Php Functions Bundle Laravel Package

chebur/twig-php-functions-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chebur/twig-php-functions-bundle
    

    Add the bundle to config/bundles.php in Symfony:

    return [
        // ...
        Chebur\TwigPhpFunctionsBundle\CheburTwigPhpFunctionsBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Use native PHP functions directly in Twig templates. No need for custom filters or extensions.

    {{ dump(php_function('count', ['array' => [1, 2, 3]])) }}
    

    Outputs: 3

  3. Where to Look First:

    • Check config/packages/chebur_twig_php_functions.yaml for allowed functions (whitelist).
    • Review src/DependencyInjection/Configuration.php for default settings.
    • Test with php_function() in Twig to validate setup.

Implementation Patterns

Core Workflows

  1. Whitelisting Functions: Define allowed PHP functions in config/packages/chebur_twig_php_functions.yaml:

    chebur_twig_php_functions:
        allowed_functions:
            - 'count'
            - 'in_array'
            - 'array_key_exists'
    

    Restrict usage to approved functions for security.

  2. Dynamic Function Calls: Pass variables directly to PHP functions:

    {% set result = php_function('array_merge', {
        'array1': [1, 2],
        'array2': [3, 4]
    }) %}
    {{ dump(result) }}  {# Outputs: [1, 2, 3, 4] #}
    
  3. Integration with Laravel:

    • Use Symfony’s TwigBridge to integrate Twig with Laravel (e.g., via spatie/laravel-twig).
    • Override Twig’s environment in app/Providers/AppServiceProvider.php:
      public function register()
      {
          $this->app->singleton(\Twig\Environment::class, function () {
              $loader = new \Twig\Loader\FilesystemLoader(__DIR__.'/../resources/views');
              $twig = new \Twig\Environment($loader);
              $twig->addExtension(new \Chebur\TwigPhpFunctionsBundle\Twig\PhpFunctionsExtension());
              return $twig;
          });
      }
      
  4. Conditional Logic: Use PHP functions for complex logic in templates:

    {% if php_function('empty', {'haystack': user.input}) %}
        <p>Input is empty!</p>
    {% endif %}
    
  5. Performance Considerations: Cache Twig templates aggressively when using PHP functions, as they bypass Twig’s compile-time optimizations.


Gotchas and Tips

Pitfalls

  1. Security Risks:

    • Never allow arbitrary PHP functions in production. Always whitelist explicitly.
    • Avoid exposing sensitive functions like system(), exec(), or file_get_contents().
    • Validate all inputs passed to PHP functions to prevent injection (e.g., php_function('eval', {...})).
  2. Type Mismatches: PHP functions expect specific argument types. Twig converts variables to strings by default:

    {{ php_function('is_int', {'var': '123'}) }}  {# Returns false #}
    

    Fix: Pass variables as arrays with explicit types:

    {{ php_function('is_int', {'var': 123}) }}  {# Returns true #}
    
  3. Laravel-Specific Issues:

    • Blade vs. Twig: If using both, ensure Twig templates are rendered separately to avoid conflicts.
    • Service Container: The bundle assumes Symfony’s DI container. In Laravel, manually bind the Twig extension:
      $twig->addExtension(new \Chebur\TwigPhpFunctionsBundle\Twig\PhpFunctionsExtension());
      
  4. Debugging:

    • Use {{ dump(php_function('debug_backtrace')) }} to inspect the call stack in templates.
    • Check Twig’s error logs for Undefined function or Call to undefined function errors (common if functions aren’t whitelisted).

Tips

  1. Custom Extensions: Extend the bundle by creating a custom Twig extension that wraps php_function():

    class CustomPhpFunctionsExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new \Twig\TwigFunction('safe_count', [$this, 'safeCount']),
            ];
        }
    
        public function safeCount(array $array)
        {
            return \Chebur\TwigPhpFunctionsBundle\Twig\PhpFunctionsRuntime::callPhpFunction(
                'count',
                ['array' => $array]
            );
        }
    }
    
  2. Configuration Overrides: Dynamically override allowed functions in Laravel’s config/twig.php:

    'extensions' => [
        \Chebur\TwigPhpFunctionsBundle\Twig\PhpFunctionsExtension::class => [
            'allowed_functions' => ['count', 'array_filter'],
        ],
    ],
    
  3. Testing: Mock PHP functions in tests using the bundle’s runtime:

    $runtime = new \Chebur\TwigPhpFunctionsBundle\Twig\PhpFunctionsRuntime(['count']);
    $this->assertEquals(3, $runtime->callPhpFunction('count', ['array' => [1, 2, 3]]));
    
  4. Performance: For frequently used functions, consider pre-compiling Twig templates with PHP functions replaced by native Twig logic (e.g., {% for %} instead of php_function('array_map')).

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge