Passed
Pull Request — master (#22)
by Luis
24:40 queued 21:48
created

ImageProcessor   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 50
ccs 22
cts 22
cp 1
rs 10
c 1
b 0
f 0
wmc 7
1
<?php declare(strict_types=1);
2
/**
3
 * PHP version 8.1
4
 *
5
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
6
 */
7
8
namespace PhUml\Processors;
9
10
use Symfony\Component\Process\Process;
11
use Symplify\SmartFileSystem\SmartFileSystem;
12
13
/**
14
 * It generates a `png` class diagram from a digraph in DOT format
15
 *
16
 * It takes a digraph in DOT format, saves it to a temporary location and creates a `png` class
17
 * diagram out of it.
18
 * It uses either the `dot` or `neato` command to create the image
19
 */
20
final class ImageProcessor implements Processor
21
{
22 8
    public static function neato(SmartFileSystem $filesystem): ImageProcessor
23
    {
24 8
        return new ImageProcessor(new ImageProcessorName('neato'), $filesystem);
25
    }
26
27 4
    public static function dot(SmartFileSystem $filesystem): ImageProcessor
28
    {
29 4
        return new ImageProcessor(new ImageProcessorName('dot'), $filesystem);
30
    }
31
32 12
    private function __construct(private readonly ImageProcessorName $name, private readonly SmartFileSystem $fileSystem)
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 32 at column 50
Loading history...
33
    {
34
    }
35
36 9
    public function name(): string
37
    {
38 9
        return $this->name->value();
39
    }
40
41
    /**
42
     * It returns the contents of a `png` class diagram
43
     */
44 9
    public function process(OutputContent $digraphInDotFormat): OutputContent
45
    {
46 9
        $dotFile = $this->fileSystem->tempnam(sys_get_temp_dir(), 'phuml');
47 9
        $imageFile = $this->fileSystem->tempnam(sys_get_temp_dir(), 'phuml');
48
49 9
        $this->fileSystem->dumpFile($dotFile, $digraphInDotFormat->value());
50
51 9
        $this->execute($dotFile, $imageFile);
52
53 7
        $image = $this->fileSystem->readFile($imageFile);
54
55 7
        $this->fileSystem->remove($dotFile);
56 7
        $this->fileSystem->remove($imageFile);
57
58 7
        return new OutputContent($image);
59
    }
60
61
    /**
62
     * @throws ImageGenerationFailure If the Graphviz command failed
63
     */
64 9
    private function execute(string $inputFile, string $outputFile): void
65
    {
66 9
        $process = new Process([$this->name->command(), '-Tpng', '-o', $outputFile, $inputFile]);
67 9
        $process->run();
68 9
        if (! $process->isSuccessful()) {
69 2
            throw ImageGenerationFailure::withOutput($process->getErrorOutput());
70
        }
71
    }
72
}
73