Passed
Pull Request — master (#1)
by Jitendra
01:39
created

Exporter::estimateSize()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 2
eloc 3
c 2
b 0
f 2
nc 1
nop 1
dl 0
loc 6
rs 10
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
    /** @var array Lengths of each line */
34
    protected $lengths = [];
35
36
    public function __destruct()
37
    {
38
        if (\is_resource($this->image)) {
39
            \imagedestroy($this->image);
40
        }
41
    }
42
43
    public function export(string $output, array $options = [])
44
    {
45
        $this->setOptions($options);
46
47
        $this->imgSize = $this->estimateSize($this->code);
48
        $this->image   = \imagecreate($this->imgSize['x'] + 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...
49
50
        \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

50
        \imagecolorallocate(/** @scrutinizer ignore-type */ $this->image, 0, 0, 0);
Loading history...
51
52
        $this->parse();
53
54
        \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

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