Code   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 5
eloc 9
c 5
b 0
f 0
dl 0
loc 24
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A save() 0 13 4
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Aop;
6
7
use PhpParser\Node;
8
use PhpParser\PrettyPrinter\Standard;
9
use Ray\Aop\Exception\NotWritableException;
10
11
use function dirname;
12
use function file_put_contents;
13
use function is_string;
14
use function rename;
15
use function sprintf;
16
use function str_replace;
17
use function tempnam;
18
use function unlink;
19
20
use const PHP_EOL;
21
22
final class Code
23
{
24
    /** @var string */
25
    public $code;
26
27
    /** @param array<Node> $stmt */
28
    public function __construct(array $stmt)
29
    {
30
        $this->code = (new Standard(['shortArraySyntax' => true]))->prettyPrintFile($stmt) . PHP_EOL;
31
    }
32
33
    public function save(string $classDir, string $aopClassName): string
34
    {
35
        $flatName = str_replace('\\', '_', $aopClassName);
36
        $filename = sprintf('%s/%s.php', $classDir, $flatName);
37
        $tmpFile = tempnam(dirname($filename), 'swap');
38
        if (is_string($tmpFile) && file_put_contents($tmpFile, $this->code) && rename($tmpFile, $filename)) {
39
            return $filename;
40
        }
41
42
        // @codeCoverageIgnoreStart
43
        @unlink((string) $tmpFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

43
        /** @scrutinizer ignore-unhandled */ @unlink((string) $tmpFile);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
44
45
        throw new NotWritableException(sprintf('swap: %s, file: %s', $tmpFile, $filename));
46
47
        // @codeCoverageIgnoreEnd
48
    }
49
}
50