Last active
December 7, 2016 21:55
-
-
Save parweb/73867316c4bba6d718e8d1db6b751afd to your computer and use it in GitHub Desktop.
defer any code in PHP
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
{ | |
"require": { | |
"opis/closure": "^2.1.0" | |
} | |
} |
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 | |
require __DIR__ . '/vendor/autoload.php'; | |
use Opis\Closure\SerializableClosure; | |
function defer ( Closure $closure, $id = null ) { | |
$wrapper = new SerializableClosure( $closure ); | |
$serialized = serialize( $wrapper ); | |
// $serialized = str_replace( "\n", ' ', $serialized ); | |
$serialized = str_replace( '$', '\$', $serialized ); | |
// $serialized = addslashes( $serialized ); | |
// print_r($serialized);exit; | |
$autoload = __DIR__ . '/vendor/autoload.php'; | |
$raw = 'require \'' . $autoload . '\'; | |
$serialized = <<<EOD | |
'.$serialized.' | |
EOD; | |
$wrapper = unserialize( $serialized ); | |
call_user_func( | |
$wrapper->getClosure() | |
);'; | |
$encoded = base64_encode( $raw ); | |
$raw = base64_decode( $encoded ); | |
// echo($raw."\n---\n\n"); | |
$script = 'eval( base64_decode( \'' . $encoded . '\' ) );'; | |
// exec('php -r "' . $script . '"', $output); | |
// return $output; | |
if ( is_string( $id ) ) { | |
$script = '/* id:' . $id . ' */' . $script; | |
} | |
$shh = '> /dev/null 2> /dev/null &'; | |
// $shh = ''; | |
exec( | |
'php -r "' . $script . '" ' . $shh, | |
$output | |
); | |
return $output; | |
} | |
// begining of how to use it | |
// with very crazy syntax | |
$var = 'plop'; | |
$$var = function () use ( $var ) { | |
return [ "{$var}-( ".microtime().' ).txt', 'hey' ]; | |
}; | |
$output = defer( function () use ( $plop ) { | |
$files = glob( '*.txt'); | |
array_walk( $files, function ( $file ) { unlink("$file"); }); | |
file_put_contents( ...$plop() ); | |
}, 'yolo' ); | |
var_dump($output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment