Completed
Pull Request — master (#38)
by Boris
04:23 queued 02:11
created

Code::writeTo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4285
nc 3
cc 3
eloc 7
nop 1
crap 3
1
<?php
2
3
/*
4
 * This file is part of CacheTool.
5
 *
6
 * (c) Samuel Gordalina <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CacheTool;
13
14
class Code
15
{
16
    /**
17
     * @var array
18
     */
19
    protected $code = array();
20
21
    /**
22
     * @param  string $statement
23
     * @return Code
24
     */
25 11
    public static function fromString($statement)
26
    {
27 11
        $code = new static();
28 11
        $code->addStatement($statement);
29
30 11
        return $code;
31
    }
32
33
    /**
34
     * @param string $statement
35
     */
36 18
    public function addStatement($statement)
37
    {
38 18
        $this->code[] = $statement;
39 18
    }
40
41
    /**
42
     * @return string
43
     */
44 18
    public function getCode()
45
    {
46 18
        return implode(PHP_EOL, $this->code);
47
    }
48
49
    /**
50
     * @param  string $file
51
     * @return null
52
     */
53 5
    public function writeTo($file)
54
    {
55 5
        $code = '<?php' . PHP_EOL . $this->getCodeExecutable();
56 5
        $chksum = md5($code);
57
58 5
        if (false === @file_put_contents($file, $code)) {
59 1
            throw new \RuntimeException("Could not write to `{$file}`: No such file or directory.");
60
        }
61
62 4
        if ($chksum !== md5_file($file)) {
63 1
            throw new \RuntimeException("Aborted due to security constraints: After writing to `{$file}` the contents were not the same.");
64
        }
65 3
    }
66
67
    /**
68
     * @return string
69
     */
70 10
    public function getCodeExecutable()
71
    {
72
        $template =<<<'EOF'
73
$errors = array();
74
75
$cachetool_error_handler_%s = function($errno, $errstr, $errfile, $errline) use (&$errors) {
76
    $errors[] = array(
77
        'no' => $errno,
78
        'str' => $errstr,
79
    );
80
};
81
82
$cachetool_exec_%s = function() use (&$errors) {
83
    try {
84
        %s
85
    } catch (\Exception $e) {
86
        $errors[] = array(
87
            'no' => $e->getCode(),
88
            'str' => $e->getMessage(),
89
        );
90
    }
91
};
92
93
set_error_handler($cachetool_error_handler_%s);
94
95
$result = $cachetool_exec_%s();
96
97
echo serialize(array(
98
    'result' => $result,
99
    'errors' => $errors
100
));
101 10
EOF;
102
103 10
        $uniq = uniqid();
104
105 10
        return sprintf($template, $uniq, $uniq, $this->getCode(), $uniq, $uniq);
106
    }
107
}
108