3

I'm having trouble properly changing from the default compiler to a custom compiler. It looks like I may not be creating the class or object correctly.

From http://twig.sensiolabs.org/doc/internals.html "The default compiler (Twig_Compiler) can be changed by calling the setCompiler() method: $twig->setCompiler($compiler);"

Here's where I'm trying to change the compiler:

\Twig_Autoloader::register();
$loader = new \Twig_Loader_Filesystem($templateDirectory);
$twig = new \Twig_Environment($loader);

$compiler = new Config_Generator_Twig_Compiler($twig);
$twig->setCompiler($compiler);

But I get this error:

PHP Catchable fatal error: Argument 1 passed to Twig_Node_Module::compile() must be an instance of Twig_Compiler, instance of Config_Generator_Twig_Compiler given, called in /config_generator/Config_Generator_Twig_Compiler.php on line 87 and defined in /config_generator/lib/Twig/Node/Module.php on line 36


"Config_Generator_Twig_Compiler.php" is just a copy of the Twig file "Compiler.php" with a couple of lines at the top changed:

<?php
require_once $rootDirectory.'/lib/Twig/CompilerInterface.php'; <---- added this line

class Config_Generator_Twig_Compiler implements Twig_CompilerInterface <---- changed from "class Twig_Compiler implements Twig_CompilerInterface"

The rest of this file is currently the same as "Compiler.php":

{...
  public function compile(Twig_NodeInterface $node, $indentation = 0)
  {
      $this->lastLine = null;
      $this->source = '';
      $this->sourceOffset = 0;
      // source code starts at 1 (as we then increment it when we encounter                                     new lines)
      $this->sourceLine = 1;
      $this->indentation = $indentation;

      if ($node instanceof Twig_Node_Module) {
          $this->filename = $node->getAttribute('filename');
      }

      $node->compile($this); <---- here's line 87

      return $this;
  }
...}
d_edmonton
  • 31
  • 1
  • Change your class to extend the original `Twig_Compiler` class. – Maerlyn Mar 12 '15 at 06:01
  • Thank You, that was my problem. I changed my Config_Generator_Twig_Compiler class to this: `class Config_Generator_Twig_Compiler extends Twig_Compiler`. Because of the dependency, I also had to add these at the top of my script, in this order: `require_once $rootDirectory.'/lib/Twig/CompilerInterface.php'; require_once $rootDirectory.'/lib/Twig/Compiler.php';` – d_edmonton Mar 12 '15 at 14:26

1 Answers1

0

$twig->setCompiler($object) need that $object extends or is a Twig_Compiler.
So, your class must extends it.

class Config_Generator_Twig_Compiler extends Twig_Compiler 
{

    [... your code here ...]

}

Twig_Compiler already implements Twig_CompilerInterface.

Kevin Robatel
  • 8,025
  • 3
  • 44
  • 57