php-hotfix/src/Runner/PythonRunner.php

62 lines
1.5 KiB
PHP

<?php
namespace NoccyLabs\Hotfix\Runner;
use NoccyLabs\Hotfix\System\Facts;
use NoccyLabs\Hotfix\Hotfix\Hotfix;
use NoccyLabs\Hotfix\Exception\UnsupportedRunnerException;
/**
* Run hotfixes written in Python.
*
*
*/
class PythonRunner implements RunnerInterface
{
const PYTHON_STUB = "/../stubs/python.stub";
protected $hotfix;
protected $facts;
public function prepare(Hotfix $hotfix, Facts $facts)
{
$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");
}
}
public function apply()
{
$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);
}
}