Exporter   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 124
Duplicated Lines 0 %

Importance

Changes 6
Bugs 2 Features 2
Metric Value
eloc 57
c 6
b 2
f 2
dl 0
loc 124
rs 10
wmc 20

7 Methods

Rating   Name   Duplication   Size   Complexity  
A colorCode() 0 16 2
A setOptions() 0 24 5
A export() 0 19 4
A estimateSize() 0 6 2
A doReset() 0 3 1
A __destruct() 0 4 2
A visit() 0 21 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the CLI-SYNTAX package.
7
 *
8
 * (c) Jitendra Adhikari <[email protected]>
9
 *     <https://github.com/adhocore>
10
 *
11
 * Licensed under MIT license.
12
 */
13
14
namespace Ahc\CliSyntax;
15
16
class Exporter extends Pretty
17
{
18
    /** @var int Font size */
19
    protected $size = 16;
20
21
    /** @var string Font path */
22
    protected $font = __DIR__ . '/../font/ubuntu.ttf';
23
24
    /** @var resource The image */
25
    protected $image;
26
27
    /** @var array */
28
    protected $imgSize = [];
29
30
    /** @var array Colors cached for each types. */
31
    protected $colors = [];
32
33
    public function __destruct()
34
    {
35
        if (\is_resource($this->image)) {
36
            \imagedestroy($this->image);
37
        }
38
    }
39
40
    public function export(string $output, array $options = [])
41
    {
42
        if (!\is_dir(\dirname($output))) {
43
            throw new \InvalidArgumentException('The output path doesnot exist.');
44
        }
45
46
        $this->setOptions($options);
47
48
        $this->imgSize   = $this->estimateSize($this->code);
49
        $this->lineCount = \substr_count($this->code, "\n") ?: 1;
50
51
        $padLineNo   = $this->withLineNo ? $this->estimateSize($this->formatLineNo())['x'] : 0;
52
        $this->image = \imagecreate($this->imgSize['x'] + $padLineNo + 50, $this->imgSize['y'] + 25);
0 ignored issues
show
Documentation Bug introduced by
It seems like imagecreate($this->imgSi...his->imgSize['y'] + 25) can also be of type false. However, the property $image is declared as type resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
53
54
        \imagecolorallocate($this->image, 0, 0, 0);
0 ignored issues
show
Bug introduced by
It seems like $this->image can also be of type false; however, parameter $image of imagecolorallocate() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

54
        \imagecolorallocate(/** @scrutinizer ignore-type */ $this->image, 0, 0, 0);
Loading history...
55
56
        $this->parse();
57
58
        \imagepng($this->image, $output);
0 ignored issues
show
Bug introduced by
It seems like $this->image can also be of type false; however, parameter $image of imagepng() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

58
        \imagepng(/** @scrutinizer ignore-type */ $this->image, $output);
Loading history...
59
    }
60
61
    protected function setOptions(array $options)
62
    {
63
        parent::setOptions($options);
64
65
        if (isset($options['size'])) {
66
            $this->size = $options['size'];
67
        }
68
69
        if (!isset($options['font'])) {
70
            return;
71
        }
72
73
        if (\is_file($options['font'])) {
74
            $this->font = $options['font'];
75
76
            return;
77
        }
78
79
        $base = \basename($options['font'], '.ttf');
80
        if (!\is_file($font = __DIR__ . "/../font/$base.ttf")) {
81
            throw new \InvalidArgumentException('The given font doesnot exist.');
82
        }
83
84
        $this->font = $font;
85
    }
86
87
    protected function estimateSize(string $for): array
88
    {
89
        $eol = \substr_count($for, "\n") ?: 1;
90
        $box = \imagettfbbox($this->size, 0, $this->font, $for);
91
92
        return ['x' => $box[2], 'y' => $box[1], 'y1' => \intval($box[1] / $eol)];
93
    }
94
95
    protected function doReset()
96
    {
97
        $this->colors = [];
98
    }
99
100
    protected function visit(\DOMNode $el)
101
    {
102
        $type   = $el instanceof \DOMElement ? $el->getAttribute('data-type') : 'raw';
103
        $color  = $this->colorCode($type);
104
        $ncolor = $this->colorCode('lineno');
105
        $text   = \str_replace(['&nbsp;', '&lt;', '&gt;'], [' ', '<', '>'], $el->textContent);
106
107
        foreach (\explode("\n", $text) as $line) {
108
            $xlen = $this->lengths[$this->lineNo] ?? 0;
109
            $ypos = 12 + $this->imgSize['y1'] * $this->lineNo;
110
111
            if ('' !== $lineNo = $this->formatLineNo()) {
112
                $xlen += $this->estimateSize($lineNo)['x'];
113
                \imagefttext($this->image, $this->size, 0, 12, $ypos, $ncolor, $this->font, $lineNo);
114
            }
115
116
            \imagefttext($this->image, $this->size, 0, 12 + $xlen, $ypos, $color, $this->font, $line);
117
118
            $this->lengths[$this->lineNo] = $xlen + $this->estimateSize($line)['x'];
119
120
            $this->lineNo++;
121
        }
122
    }
123
124
    protected function colorCode(string $type): int
125
    {
126
        if (isset($this->colors[$type])) {
127
            return $this->colors[$type];
128
        }
129
130
        $palette = [
131
            'comment' => [0, 96, 192],
132
            'default' => [0, 192, 0],
133
            'keyword' => [192, 0, 0],
134
            'string'  => [192, 192, 0],
135
            'raw'     => [128, 128, 128],
136
            'lineno'  => [128, 224, 224],
137
        ];
138
139
        return $this->colors[$type] = \imagecolorallocate($this->image, ...$palette[$type]);
140
    }
141
}
142