Created
April 5, 2014 23:39
-
-
Save AMHOL/9999508 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace AMH; | |
use Exception; | |
use Jeremeamia\SuperClosure\SerializableClosure; | |
use Symfony\Component\Process\PhpProcess; | |
class PromiseValueException extends Exception {} | |
class Promise | |
{ | |
protected $_promises = array(); | |
protected $_resolvedPromises = array(); | |
public function __set($key, $callback) | |
{ | |
if ( !is_callable($callback) ) { | |
throw new PromiseValueException('You can only set callbacks as promise properties'); | |
} | |
$functionCode = serialize(new SerializableClosure($callback)); | |
$phpCode = | |
'<?php | |
include "../vendor/autoload.php"; | |
$callback = unserialize("'. str_replace('"', '\\"', $functionCode) .'"); | |
echo serialize($callback()); | |
?>'; | |
$promise = new PhpProcess($phpCode); | |
$promise->start(); | |
$this->_promises[$key] = $promise; | |
} | |
public function __get($key) | |
{ | |
if ( !isset($this->_resolvedPromises[$key]) ) { | |
$this->_promises[$key]->wait(); | |
$serializedOutput = $this->_promises[$key]->getOutput(); | |
if ( !$this->_isSerialized($serializedOutput) ) { | |
throw new Exception('Content "'. $serializedOutput .'" returned from Promise could not be unserialized'); | |
} | |
$this->_resolvedPromises[$key] = unserialize($serializedOutput); | |
unset($this->_promises[$key]); | |
} | |
return $this->_resolvedPromises[$key]; | |
} | |
public function _isSerialized($str) | |
{ | |
return ($str == serialize(false) || @unserialize($str) !== false); | |
} | |
public function __destruct() | |
{ | |
try { | |
foreach($this->_promises as $key => $promise) { | |
$this->_promises[$key]->stop(0); | |
} | |
} catch ( Exception $e ) {} | |
} | |
} |
Author
AMHOL
commented
Apr 5, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment