2016-12-11 15:15:36 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace NoccyLabs\Hotfix\Runner;
|
|
|
|
|
|
|
|
use NoccyLabs\Hotfix\System\Facts;
|
|
|
|
use NoccyLabs\Hotfix\Hotfix\Hotfix;
|
2016-12-11 22:45:21 +00:00
|
|
|
use NoccyLabs\Hotfix\Exception\UnsupportedRunnerException;
|
2016-12-11 15:15:36 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Run hotfixes written in Python.
|
|
|
|
*
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
class PythonRunner implements RunnerInterface
|
|
|
|
{
|
|
|
|
|
2016-12-11 22:45:21 +00:00
|
|
|
const PYTHON_STUB = "/../stubs/python.stub";
|
|
|
|
|
|
|
|
protected $hotfix;
|
|
|
|
|
|
|
|
protected $facts;
|
|
|
|
|
2016-12-11 15:15:36 +00:00
|
|
|
public function prepare(Hotfix $hotfix, Facts $facts)
|
|
|
|
{
|
2016-12-11 22:45:21 +00:00
|
|
|
$this->hotfix = $hotfix;
|
|
|
|
$this->facts = $facts;
|
|
|
|
|
|
|
|
$python = trim(exec("which python"));
|
|
|
|
if (!$python) {
|
|
|
|
throw new UnsupportedRunnerException("You need to install python to apply this hotfix");
|
|
|
|
}
|
2016-12-11 15:15:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public function apply()
|
|
|
|
{
|
2016-12-11 22:45:21 +00:00
|
|
|
$head = file(__DIR__.self::PYTHON_STUB, FILE_IGNORE_NEW_LINES);
|
|
|
|
$body = $this->hotfix->getBody();
|
|
|
|
$hash = $this->hotfix->getHash();
|
|
|
|
|
|
|
|
$facts = $this->facts->getFlat();
|
|
|
|
$head[] = "def fact(f):";
|
|
|
|
$head[] = " facts = {";
|
|
|
|
$tmp = [];
|
|
|
|
foreach ($facts as $key=>$fact) {
|
|
|
|
$tmp[] = sprintf(' "%s": "%s"', $key, $fact);
|
|
|
|
}
|
|
|
|
$head[] = join(",\n", $tmp)."\n";
|
|
|
|
$head[] = " }";
|
|
|
|
$head[] = " return facts[f]";
|
|
|
|
|
|
|
|
$head = join("\n", $head);
|
|
|
|
|
|
|
|
// Create temporary filename based on the hash of the hotfix
|
|
|
|
$tmpfile = sys_get_temp_dir()."/hotfix_".$hash;
|
|
|
|
file_put_contents($tmpfile, $head."\n".$body."\n");
|
|
|
|
|
|
|
|
// Execute the hotfix and clean up
|
|
|
|
passthru("python {$tmpfile}");
|
|
|
|
unlink($tmpfile);
|
2016-12-11 15:15:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|