Completed
Push — master ( 6ffc3f...4609e3 )
by Antonio
51:14 queued 46:44
created

ImageTrait::writeString()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 54
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 0
cts 49
cp 0
rs 8.7449
c 0
b 0
f 0
cc 5
eloc 38
nc 12
nop 1
crap 30

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-qrcode-component project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\QrCode\Traits;
13
14
use BaconQrCode\Renderer\Image\Png;
15
use BaconQrCode\Writer;
16
use Da\QrCode\Contracts\LabelInterface;
17
use Da\QrCode\Contracts\QrCodeInterface;
18
use Da\QrCode\Exception\BadMethodCallException;
19
use Da\QrCode\Exception\ValidationException;
20
use Da\QrCode\Renderer\Jpg;
21
use QrReader;
22
23
trait ImageTrait
24
{
25
    protected $validate = false;
26
27
    /**
28
     * Whether to validate result or not.
29
     *
30
     * @param $validate
31
     *
32
     * @return $this
33
     */
34
    public function validateResult($validate)
35
    {
36
        $cloned = clone $this;
37
        $cloned->validate = $validate;
38
39
        return $cloned;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function writeString(QrCodeInterface $qrCode)
46
    {
47
        /** @var Png|Jpg $renderer */
48
        $renderer = $this->renderer;
0 ignored issues
show
Bug introduced by
The property renderer does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
49
50
        $renderer->setWidth($qrCode->getSize());
51
        $renderer->setHeight($qrCode->getSize());
52
        $renderer->setMargin(0);
53
        $renderer->setForegroundColor($this->convertColor($qrCode->getForegroundColor()));
0 ignored issues
show
Bug introduced by
It seems like convertColor() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
54
        $renderer->setBackgroundColor($this->convertColor($qrCode->getBackgroundColor()));
0 ignored issues
show
Bug introduced by
It seems like convertColor() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
55
        $writer = new Writer($renderer);
56
        $string = $writer->writeString(
57
            $qrCode->getText(),
58
            $qrCode->getEncoding(),
59
            $this->convertErrorCorrectionLevel($qrCode->getErrorCorrectionLevel())
0 ignored issues
show
Bug introduced by
It seems like convertErrorCorrectionLevel() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
60
        );
61
        $image = imagecreatefromstring($string);
62
        $image = $this->addMargin(
63
            $image,
64
            $qrCode->getMargin(),
65
            $qrCode->getSize(),
66
            $qrCode->getForegroundColor(),
67
            $qrCode->getBackgroundColor()
68
        );
69
70
        if ($qrCode->getLogoPath()) {
71
            $image = $this->addLogo($image, $qrCode->getLogoPath(), $qrCode->getLogoWidth());
72
        }
73
74
        if ($qrCode->getLabel()) {
75
            $image = $this->addLabel(
76
                $image,
77
                $qrCode->getLabel(),
78
                $qrCode->getForegroundColor(),
79
                $qrCode->getBackgroundColor()
80
            );
81
        }
82
        $string = $this->imageToString($image);
0 ignored issues
show
Bug introduced by
It seems like imageToString() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
83
        if ($this->validate) {
84
            $reader = new QrReader($string, QrReader::SOURCE_TYPE_BLOB);
85
            if ($reader->text() !== $qrCode->getText()) {
86
                throw new ValidationException(
87
                    sprintf(
88
                        'Built-in validation reader read "%s" instead of "%s"' .
89
                        'Adjust your parameters to increase readability or disable built-in validation.',
90
                        $reader->text(),
91
                        $qrCode->getText()
92
                    )
93
                );
94
            }
95
        }
96
97
        return $string;
98
    }
99
100
    /**
101
     * @param resource $sourceImage
102
     * @param int      $margin
103
     * @param int      $size
104
     * @param int[]    $foregroundColor
105
     * @param int[]    $backgroundColor
106
     *
107
     * @return resource
108
     */
109
    protected function addMargin($sourceImage, $margin, $size, array $foregroundColor, array $backgroundColor)
110
    {
111
        $additionalWhitespace = $this->calculateAdditionalWhiteSpace($sourceImage, $foregroundColor);
112
113
        if ($additionalWhitespace == 0 && $margin == 0) {
114
            return $sourceImage;
115
        }
116
117
        $targetImage = imagecreatetruecolor($size + $margin * 2, $size + $margin * 2);
118
        $backgroundColor = imagecolorallocate(
119
            $targetImage,
120
            $backgroundColor['r'],
121
            $backgroundColor['g'],
122
            $backgroundColor['b']
123
        );
124
        imagefill($targetImage, 0, 0, $backgroundColor);
125
        imagecopyresampled(
126
            $targetImage,
127
            $sourceImage,
128
            $margin,
129
            $margin,
130
            $additionalWhitespace,
131
            $additionalWhitespace,
132
            $size,
133
            $size,
134
            $size - 2 * $additionalWhitespace,
135
            $size - 2 * $additionalWhitespace
136
        );
137
138
        return $targetImage;
139
    }
140
141
    /**
142
     * @param resource $image
143
     * @param int[]    $foregroundColor
144
     *
145
     * @return int
146
     */
147
    protected function calculateAdditionalWhiteSpace($image, array $foregroundColor)
148
    {
149
        $width = imagesx($image);
150
        $height = imagesy($image);
151
        $foregroundColor = imagecolorallocate(
152
            $image,
153
            $foregroundColor['r'],
154
            $foregroundColor['g'],
155
            $foregroundColor['b']
156
        );
157
        $whitespace = $width;
158
        for ($y = 0; $y < $height; $y++) {
159
            for ($x = 0; $x < $width; $x++) {
160
                $color = imagecolorat($image, $x, $y);
161
                if ($color == $foregroundColor || $x == $whitespace) {
162
                    $whitespace = min($whitespace, $x);
163
                    break;
164
                }
165
            }
166
        }
167
168
        return $whitespace;
169
    }
170
171
    /**
172
     * @param resource $sourceImage
173
     * @param string   $logoPath
174
     * @param int      $logoWidth
175
     *
176
     * @return resource
177
     */
178
    protected function addLogo($sourceImage, $logoPath, $logoWidth = null)
179
    {
180
        $logoImage = imagecreatefromstring(file_get_contents($logoPath));
181
        $logoSourceWidth = imagesx($logoImage);
182
        $logoSourceHeight = imagesy($logoImage);
183
        $logoTargetWidth = $logoWidth;
184
185
        if ($logoTargetWidth === null) {
186
            $logoTargetWidth = $logoSourceWidth;
187
            $logoTargetHeight = $logoSourceHeight;
188
        } else {
189
            $scale = $logoTargetWidth / $logoSourceWidth;
190
            $logoTargetHeight = intval($scale * imagesy($logoImage));
191
        }
192
193
        $logoX = imagesx($sourceImage) / 2 - $logoTargetWidth / 2;
194
        $logoY = imagesy($sourceImage) / 2 - $logoTargetHeight / 2;
195
196
        imagecopyresampled(
197
            $sourceImage,
198
            $logoImage,
199
            $logoX,
200
            $logoY,
201
            0,
202
            0,
203
            $logoTargetWidth,
204
            $logoTargetHeight,
205
            $logoSourceWidth,
206
            $logoSourceHeight
207
        );
208
209
        return $sourceImage;
210
    }
211
212
    /**
213
     * @param resource       $sourceImage
214
     * @param LabelInterface $label
215
     * @param int[]          $foregroundColor
216
     * @param int[]          $backgroundColor
217
     *
218
     * @throws BadMethodCallException
219
     * @return resource
220
     */
221
    protected function addLabel(
222
        $sourceImage,
223
        LabelInterface $label,
224
        array $foregroundColor,
225
        array $backgroundColor
226
    ) {
227
        if (!function_exists('imagettfbbox')) {
228
            throw new BadMethodCallException('Missing function "imagettfbbox". Did you install the FreeType library?');
229
        }
230
        $labelText = $label->getText();
231
        $labelFontSize = $label->getFontSize();
232
        $labelFontPath = $label->getFont();
233
        $labelMargin = $label->getMargins();
234
        $labelAlignment = $label->getAlignment();
235
236
        $labelBox = imagettfbbox($labelFontSize, 0, $labelFontPath, $labelText);
237
        $labelBoxWidth = intval($labelBox[2] - $labelBox[0]);
238
        $labelBoxHeight = intval($labelBox[0] - $labelBox[7]);
239
        $sourceWidth = imagesx($sourceImage);
240
        $sourceHeight = imagesy($sourceImage);
241
        $targetWidth = $sourceWidth;
242
        $targetHeight = $sourceHeight + $labelBoxHeight + $labelMargin['t'] + $labelMargin['b'];
243
244
        // Create empty target image
245
        $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
246
        $foregroundColor = imagecolorallocate(
247
            $targetImage,
248
            $foregroundColor['r'],
249
            $foregroundColor['g'],
250
            $foregroundColor['b']
251
        );
252
        $backgroundColor = imagecolorallocate(
253
            $targetImage,
254
            $backgroundColor['r'],
255
            $backgroundColor['g'],
256
            $backgroundColor['b']
257
        );
258
        imagefill($targetImage, 0, 0, $backgroundColor);
259
        // Copy source image to target image
260
        imagecopyresampled(
261
            $targetImage,
262
            $sourceImage,
263
            0,
264
            0,
265
            0,
266
            0,
267
            $sourceWidth,
268
            $sourceHeight,
269
            $sourceWidth,
270
            $sourceHeight
271
        );
272
        switch ($labelAlignment) {
273
            case LabelInterface::ALIGN_LEFT:
274
                $labelX = $labelMargin['l'];
275
                break;
276
            case LabelInterface::ALIGN_RIGHT:
277
                $labelX = $targetWidth - $labelBoxWidth - $labelMargin['r'];
278
                break;
279
            default:
280
                $labelX = intval($targetWidth / 2 - $labelBoxWidth / 2);
281
                break;
282
        }
283
        $labelY = $targetHeight - $labelMargin['b'];
284
        imagettftext($targetImage, $labelFontSize, 0, $labelX, $labelY, $foregroundColor, $labelFontPath, $labelText);
285
286
        return $targetImage;
287
    }
288
}
289