You are here

class TwigExtension in Twig VarDumper 8

Same name and namespace in other branches
  1. 8.2 src/TwigExtension.php \Drupal\twig_vardumper\TwigExtension
  2. 3.0.x src/TwigExtension.php \Drupal\twig_vardumper\TwigExtension

Twig extension with some useful functions and filters.

Hierarchy

  • class \Drupal\twig_vardumper\TwigExtension extends \Drupal\twig_vardumper\Twig_Extension

Expanded class hierarchy of TwigExtension

1 string reference to 'TwigExtension'
twig_vardumper.services.yml in ./twig_vardumper.services.yml
twig_vardumper.services.yml
1 service uses TwigExtension
twig_vardumper.twig_extension in ./twig_vardumper.services.yml
Drupal\twig_vardumper\TwigExtension

File

src/TwigExtension.php, line 8

Namespace

Drupal\twig_vardumper
View source
class TwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('dump', [
        $this,
        'drupalDump',
      ], [
        'needs_context' => TRUE,
        'needs_environment' => TRUE,
      ]),
      new \Twig_SimpleFunction('vardumper', [
        $this,
        'drupalDump',
      ], [
        'needs_context' => TRUE,
        'needs_environment' => TRUE,
      ]),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'twig_vardumper';
  }

  /**
   * Dumps information about variables.
   *
   * @param \Twig_Environment $env
   *   Enviroment values.
   * @param array $context
   *   Context values.
   */
  public function drupalDump(\Twig_Environment $env, array $context) {
    if (!$env
      ->isDebug()) {
      return;
    }
    $var_dumper = '\\Symfony\\Component\\VarDumper\\VarDumper';
    if (class_exists($var_dumper)) {
      $count = func_num_args();
      if (2 === $count) {
        $vars = [];
        foreach ($context as $key => $value) {
          if (!$value instanceof \Twig_Template) {
            $vars[$key] = $value;
          }
        }
        call_user_func($var_dumper . '::dump', $vars);
      }
      else {
        for ($i = 2; $i < $count; ++$i) {
          call_user_func($var_dumper . '::dump', func_get_arg($i));
        }
      }
    }
    else {
      trigger_error('Could not dump the variable because symfony/var-dumper component is not installed.', E_USER_WARNING);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
TwigExtension::drupalDump public function Dumps information about variables.
TwigExtension::getFunctions public function
TwigExtension::getName public function