Skip to content

Instantly share code, notes, and snippets.

@WinterSilence
Created May 25, 2014 19:31
Show Gist options
  • Save WinterSilence/604e1cd86e242e592795 to your computer and use it in GitHub Desktop.
Save WinterSilence/604e1cd86e242e592795 to your computer and use it in GitHub Desktop.
Class Enso\Closure: used to create serializable anonymous function
<?php
/**
* Used to create serializable anonymous function, based on PHP function
* [create_function](http://php.net/create-function).
*
* @package Enso
* @category Base
* @license http://ensophp.github.io/license
*/
namespace Enso;
class Closure implements \Serializable
{
/**
* @var \Closure Created function
*/
protected $funct;
/**
* @var string Function code (eg: 'return $a + $b;')
*/
protected $code;
/**
* @var string Function arguments (eg: '$a,$b', 'Route $route, $params = array()')
*/
protected $args = '';
/**
* Create instance of Enso\Closure.
*
* @param string $code
* @param string $arguments
* @return void
*/
public function __construct($code, $arguments = '')
{
$this->code = (string) $code;
$this->args = (string) $arguments;
$this->funct = $this->create($this->args, $this->code);
}
/**
* Called when the script tries to perform as a feature, return function result.
*
* @param string $arguments
* @param string $code
* @return \Closure
* @throws \InvalidArgumentException
*/
public function create($arguments, $code)
{
$funct = create_function($arguments, $code);
if ($funct === false) {
throw new \InvalidArgumentException(
'Error at create function in Enso\Closure: unvalid values of arguments.'
);
}
return $funct;
}
/**
* Called when the script tries to perform as a feature, return function result.
*
* @param mixed $arg,$arg2,.. Function arguments values
* @return mixed
*/
public function __invoke()
{
$arguments = func_get_args();
return call_user_func_array($this->funct, $arguments);
}
/**
* Return serialized properties of object.
*
* @return string
*/
public function serialize()
{
return serialize($this->code, $this->args);
}
/**
* Unserialize object properties.
*
* @param string $properties Serialized properties
* @return void
*/
public function unserialize($properties)
{
list($this->args, $this->code) = unserialize($properties);
$this->funct = $this->create($this->args, $this->code);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment