bcit-ci / CodeIgniter

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
18.27k stars 7.6k forks source link

Error when parsing objects #1065

Closed qswks closed 12 years ago

qswks commented 12 years ago

When you pass an object as $data to the Tempalte Parser Class an error is thrown for each object that couldn't be converted to string.

This snipplet:

$data = array(
  'name' => 'John Doe',
  'details' => $stdClassObject,
  'created' => $dateTimeObject
);

$this->load->library('parser');
$salutation = $this->parser->parse_string('Hi {name}', $data, TRUE);

Throws these errors:

ERROR - (date) --> Severity: 4096  --> Object of class stdClass could not be converted to string /path/to/codeigniter/system/libraries/Parser.php 101
ERROR - (date) --> Severity: 4096  --> Object of class DateTime could not be converted to string /path/to/codeigniter/system/libraries/Parser.php 101

Suggested patch (system/libraries/Parser.php - Line 101)

--- Parser.php  2012-02-20 19:40:04.000000000 +0100
+++ Parser.php.orig     2012-02-20 19:39:56.000000000 +0100
@@ -96,7 +96,7 @@
                    {
                            $template = $this->_parse_pair($key, $val, $template);
                    }
-                       else if (!is_object($val))
+                       else
                    {
                            $template = $this->_parse_single($key, (string)$val, $template);
                    }
jamierumbelow commented 12 years ago

In my opinion, there are a couple of things we could do in this situation.

We could use the @ operator to surpress the error (thus giving us a blank string) or we could totally ignore the object, like above.

$template = $this->_parse_single($key, (string)$val, $template);

Alternatively, we could use http_build_query(), json_encode() or serialize() to provide a readable string representation of the object if we so desired. Or we could just add an error message to the class to prevent objects from being passed?

AkenRoberts commented 12 years ago

You shouldn't exclude objects entirely - the __toString() functionality would make them an acceptable replacement value for a parsed pseudo-variable. Personally, I think throwing the error is correct - an object should not be an acceptable replacement unless it has a __toString() capability.

The Parser class is designed to handle string replacements, and that's it. It doesn't tout any additional features. If someone needs something fancier, they should use one of the template libraries out there.

narfbg commented 12 years ago

@cryode is correct - this is only supposed to work with strings.

Myerden commented 7 years ago

Now, there is no suitable answer yet..Yeah?

AkenRoberts commented 7 years ago

@Myerden If you want to use objects in the parser, the objects must implement the __toString() magic method. That, or make sure to manually convert your object into a string when defining it as a replacement value.