Skip to content

Instantly share code, notes, and snippets.

@gggeek
Created March 7, 2013 17:53
Show Gist options
  • Save gggeek/5110151 to your computer and use it in GitHub Desktop.
Save gggeek/5110151 to your computer and use it in GitHub Desktop.
Converter for ez4 template-objects to twig templates
<?php
class ForwardAdapter
{
private $object;
private $properties;
private $staticproperties;
/**
* Constructor, takes as input an "eZ4 template object".
* Those had no interface defined, but have to implement 3 methods:
* hasAttribute, attriubute and attributes
*
* @todo check that $transferredObject implements the appropraite interface...
*/
public function __construct( $transferredObject )
{
$this->object = $transferredObject;
}
/**
* This is implemented to allow the Twig tpl engine to access the "properties"
* of the eZ4 object. Twig likes "__call()", but does know squat about "attribute()"
*/
public function __call( $name, $args )
{
// cache this for speed
if ( !is_array( $this->properties ) )
{
// list all of the existing attributes
$this->properties = array_flip( $this->object->attributes() );
// list of all attributes which do not needa closure
if ( is_callable( array( $this->object, 'definition' ) )
{
$def = $this->object->definition();
foreach( $def['fields'] as $attrname => $fielddesc )
{
$this->staticproperties[$attrname] = $fielddesc['name'];
}
}
}
if ( !array_key_exists( $name, $this->properties ) )
{
// eZ4 style: be tolerant! Shall we make it more strict?
return null;
}
// In case of dynamic attributes, we need to use the dreaded closure.
// We try to avoid this if possible
if ( array_key_exists( $name, $this->staticproperties ) )
{
$field = $this->staticproperties[$name];
$return = $this->object->$field;
}
else
{
$return = $this->object->attribute( $name );
$obj = $this->object;
$return = $this->getLegacyKernel()->runCallback(
function () use ( $obj, $name )
{
return $obj->attribute( $name );
}
);
}
return self::wrap( $return );
}
/**
* Recursive wrapping of eZ4 "template objects" into ForwardAdapter objects
*/
protected static wrap( $val )
{
if ( is_object( $val ) && is_callable( array( $val, 'attributes' ) ) && is_callable( array( $val, 'attribute' ) ) && is_callable( array( $val, 'hasAttribute' ) ) )
{
return new self( $val );
}
if ( is_array( $val ) )
{
foreach ( $val as $key => $value )
{
$val[$key] = self::wrap( $value );
}
}
/// @todo should we disallow objects which do not implement the proper 3 methods?
/// We should check how they behave in ez4, most likely as "empty" objects...
return $val;
}
}
?>
@lolautruche
Copy link

Interesting, even if I still hardly see a valid use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment