Twig function not loaded - php

I use last version of Twig in Codeigniter project, I have an error I don't understand. I load my functions using Twig but I get this error :
Message: An exception has been thrown during the compilation of a
template ("Function () does not exist") in "base.twig".
To load my functions I use :
foreach(get_defined_functions() as $functions)
{
foreach($functions as $function)
{
$this->_twig->addFunction( new \Twig_Function($function) );
}
}
Then in template I try :
{{ base_url('test') }}
I made a var_dump of $twig->getFunctions(), and base_url() is listed.
I just migrated to the last version of Twig, and got this error.
Did I miss something ?

Ok I found the way in Twig 2.2.4 :
foreach(get_defined_functions() as $functions)
{
foreach($functions as $function)
{
$this->_twig->addFunction( new \Twig_SimpleFunction($function, $function) );
}
}
It works.

Related

Unknown "dump" function error using Twig 1 and Codeigniter 2

I added Twig template engine to CodeIgniter 2 using this library:
https://github.com/dilantha/codeigniter-twig
Everything works except dum() function. Using dump troughs this error:
Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'Unknown "dump" function. Did you mean "var_dump", "debug_zval_dump", "xdebug_var_dump", "mysqli_dump_debug_info", "xdebug_dump_superglobals", "xdebug_dump_aggr_profiling_data"?
This is my Twig Template:
{{ dump() }}
And this is my controller:
public function index()
{
$data = ['title' => 'Title' ];
$this->twig->display('dump.twig', $data);
}
CodeIgniter Version: 2.2.0
Twig Version: 1.35.4
This option is not enabled by default in version 1.and codeigniter-twig code missed this.
I added this code to Twig.php library and the problem solved:
if ($debug) {
$this->_twig->addExtension(new Twig_Extension_Debug());
}
I will report this to the author.

Twig_Error_Syntax for "Unknown filter" with a Twig filter in Timber

This has got to be simple, but I can't see what's wrong. I'm using the simple filter example at https://twig.symfony.com/doc/1.x/advanced.html#filters with Twig 1.34 in Timber, a WordPress plugin.
I added
// an anonymous function
$filter = new Twig_SimpleFilter('rot13', function ($string) {
return str_rot13($string);
});
and
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
to my theme's functions.php file.
But using {{ 'Twig'|rot13 }} in my view.twig file gives a fatal error
PHP Fatal error: Uncaught exception 'Twig_Error_Syntax'
with message 'Unknown "rot13" filter' in view.twig
and a notice
Undefined variable: loader in functions.php
Using a filter like {{ 'Twig'|lower }} works OK.
Do I need to add the functions to functions.php in a different way?
According to documentation here (title: Adding to Twig)
it should be done like this (in functions.php):
add_filter('timber/twig', function($twig) {
$twig->addExtension(new Twig_Extension_StringLoader());
// add Your filters here
$twig->addFilter(
new Twig_SimpleFilter(
'rot13',
function($string) {
return str_rot13($string);
}
)
);
// or simply:
// $twig->addFilter(new Twig_SimpleFilter('rot13', 'str_rot13'));
$twig->addFilter(
new Twig_SimpleFilter(
'hello',
function($name) {
return 'Hello, '.$name;
}
)
);
return $twig;
});

Trailing comma in array causing Parse Error

I'm currently working on some project on Symfony 2.8.
I've come across this weird PHP error.
I'm building a symfony command that allows using Kahlan test framework inside a Symfony project. Thus, I need the Symfony container to be available in Kahlan test suites, and so to be defined as global variable of said suites. Simple matter with the Container aware command.
But here comes the glitch. When I try to call a service that uses Symfony's security.authorization_checker service, the cli returns this error:
PHP Parse error: syntax error, unexpected ',' in /tmp/kahlan/data/www/project/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authorization/ExpressionLanguageProvider.php on line 55
The code of said file:
[...]
public function getFunctions()
{
return array(
new ExpressionFunction('is_anonymous', function () {
return '$trust_resolver->isAnonymous($token)';
}, function (array $variables) {
return $variables['trust_resolver']->isAnonymous($variables['token']);
}),
new ExpressionFunction('is_authenticated', function () {
return '$token && !$trust_resolver->isAnonymous($token)';
}, function (array $variables) {
return $variables['token'] && !$variables['trust_resolver']->isAnonymous($variables['token']);
}),
new ExpressionFunction('is_fully_authenticated', function () {
return '$trust_resolver->isFullFledged($token)';
}, function (array $variables) {
return $variables['trust_resolver']->isFullFledged($variables['token']);
}),
new ExpressionFunction('is_remember_me', function () {
return '$trust_resolver->isRememberMe($token)';
}, function (array $variables) {
return $variables['trust_resolver']->isRememberMe($variables['token']);
}),
new ExpressionFunction('has_role', function ($role) {
return sprintf('in_array(%s, $roles)', $role);
}, function (array $variables, $role) {
return in_array($role, $variables['roles']);
}),
);
}
[...]
Line 55 is the line of the last array element, thus said comma is the trailing comma.
The error is thrown only in cli.
An of course, I have tried removing the comma, everything works then perfectly. But obviously, I can't change Symfony's built-in classes.
So, How come PHP throws Parse Errors for a trailing comma in an array only in cli mode, and do you guys have any idea on how to fix this?
Thanks.
As seen in the kahlan-bundle repo, The problem was not in my code but seemed to be with kahlan.
Issue answered by Kahlan dev here.
Upgrading to the new kahlan version simply resolved the problem.

Can't load modules from libraries in CodeIgniter HMVC

I'm having a problem loading modules inside my template library in CodeIgniter HMVC. The reason I want to load a module in the template library is that I wish to use modules for sideboxes and other content boxes in my template.
PS: I am also using the Smarty template parsing system for CodeIgniter, but I doubt it has anything to do with the errors, but if you have reasons to believe otherwise, please, let me know.
What I tried to do
I tried to load the module in two different ways, and both presented with the same errors.
The errors
A PHP Error was encountered
Severity: Notice
Message: Undefined Property CI::$template
File: MX/Loader.php
Line Number: 141
-
A PHP Error was encountered
Severity: Notice
Message: Undefined Property CI::$template
Filename: MX/Controller.php
Line number: 57
-
Fatal error: Call to a member function load_content() on a non-object in E:\Xampp\htdocs\firecms\application\modules\sidebar_login_box\controllers\sidebar_login_box.php on line 7
The undefined "load_content()" function will be explained further down (in Sidebar Controller).
The Error lines
MX/Loader
/*Line 140*/if (isset($this->_ci_classes[$class]) AND $_alias = $this->_ci_classes[$class])
/*Line 141*/ return CI::$APP->$_alias;
MX/Controller
/*Line 56*/public function __get($class) {
/*Line 57*/ return CI::$APP->$class;
How I tried to load the modules
This was my first attempt (loading the file and instancing its class):
class Template {
//[...]
public function load_sidebars()
{
$sidebars = $this->CI->cms_model->get_sidebars();
foreach ($sidebars as $sidebar)
{
if (trim($sidebar["content"]) == "")
{
//An example of sidebar module name is "sidebar:login_box"
//The function below changes the name to "sidebar_login_box" (the
//module's folder and controller name.
$module = str_replace(':', '_', $sidebar["module"]);
$file_path = APPPATH.'modules/'.$module.'/controllers/'.$module.'.php';
require_once $file_path;
$class = ucfirst($module);
$object = new $class();
$module_data = $object->index();
$this->_section_data["sidebars"][]["content"] = $module_data;
}
else
{
$this->_section_data["sidebars"][]["content"] = $sidebar["content"];
}
}
}
//[...]
}
And this was my second attempt (using the loader function):
public function load_sidebars()
{
$sidebars = $this->CI->cms_model->get_sidebars();
foreach ($sidebars as $sidebar)
{
if (trim($sidebar["content"]) == "")
{
$module = str_replace(':', '_', $sidebar["module"]);
$this->CI->load->module($module);
$module_data = $this->CI->$module->index();
$this->_section_data["sidebars"][]["content"] = $module_data;
}
else
{
$this->_section_data["sidebars"][]["content"] = $sidebar["content"];
}
}
}
The sidebar controller
This is how the sidebar controller looks like:
class Sidebar_login_box extends Fire_Controller {
public function index()
{
$view_data = array();
//The load_content function in the template library is used to parse template files
//and return them as a string.
return $this->template->load_content("login_box", $view_data);
}
}
The Fire Controller
The Fire_Controller is my core controller. My core classes' prefix is Fire_ instead of MY_.
This is how the fire controller looks like:
class Fire_Controller extends MX_Controller {
public function __construct()
{
parent::__construct();
//Load configurations from the database.
$this->config->load_db_configs();
//Set the timezone.
date_default_timezone_set(config_item("timezone"));
//Loads the form validation library.
$this->load->library("form_validation");
//Reset the Form Validation CI Object (to fix problems with HMVC CI).
$this->form_validation->CI =& $this;
//To reduce load time, the template library will not be loaded in ajax
//requests.
if ( ! $this->input->is_ajax_request())
{
$this->load->library("template");
}
//Force access via SSL connection (HTTPS) if necessary.
if ((int)config_item('force_https') === 1)
{
force_https();
}
}
Note: This is a very recent project of mine, which means that the framework and all third party extensions are in the most recent stable version as of January 06, 2015.
Thank you for your time,
Best regards.
Fixed.
The sidebars were loaded from the set_defaults() method, which was called by the constructor method in my template library. And since it wasn't fully loaded, the template object was not saved in CI's super object, thus being inaccessible and throwing the errors in the sidebar module.
I have moved the set_defaults() call to the render_page() function of my template library (which are called by the modules' controllers), and now it's working perfectly.
Too bad I added bounty a few hours before finding the solution, hehe.
You need to load the library before you can use it in the sidebar controller. It isn't being passed from the parent. Try this:
class Sidebar_login_box extends Fire_Controller {
public function index()
{
$view_data = array();
$this->load->library('template');
//The load_content function in the template library is used to parse template files
//and return them as a string.
return $this->template->load_content("login_box", $view_data);
}
}
Cheers!

Fatal error: Class 'Zend_Log' not found

I'm getting the following error in magento administration
Fatal error: Class 'Zend_Log' not found in /home/website/public_html/app/code/community/Uni/Fileuploader/Block/Adminhtml/Fileuploader/Edit/Tab/Products.php on line 241
This is a community extension, which has been working fine on my website. The error makes no sense to me, because the line 241 contains just a closing "}" character.
class Uni_Fileuploader_Block_Adminhtml_Fileuploader_Edit_Tab_Products extends Mage_Adminhtml_Block_Widget_Grid {
...
...
...
public function getRowUrl() {
return '#';
}
public function getGridUrl() {
return $this->getUrl('*/*/productgrid', array('_current' => true));
}
protected function getFileuploaderData() {
return Mage::registry('fileuploader_data');
}
protected function _getSelectedProducts() {
$products = $this->getRequest()->getPost('selected_products');
if (is_null($products)) {
$products = explode(',', $this->getFileuploaderData()->getProductIds());
return (sizeof($products) > 0 ? $products : 0);
}
return $products;
}
} // line 241, where error occurs
I can post the rest of the code, if you need it.
I noticed that if I upgrade to PHP 5.4 version the error disappears, but since 5.4 version causes other errors on my website, I have to continue using 5.3.
Any ideas on how to solve this?
The problem could be the name of one of the methods in your custom class.
Take for example the method name is getData() ,
Try searching for generic method names in your script, such as getData, which might be reserved by some of Magento’s core classes. I figure that these methods have predefined functionality, which your module is missing support for, and Zend then tries to write an exception to Zend log.
Reference link: netismine
I got the same error when rewriting a payment method.
public function authorize($payment, $amount)
Solved rewriting exactly the same main method:
public function authorize(Varien_Object $payment, $amount)
Magento 1.9.1.0/PHP 5.5

Categories