Passed
Branch 3.x (80fbf8)
by Enjoys
01:46
created

Defaults   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 14
eloc 63
dl 0
loc 136
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A createImage() 0 53 5
A getBase64Image() 0 7 1
A getCode() 0 3 1
A validate() 0 12 2
A __construct() 0 8 2
A generateCode() 0 14 2
A renderHtml() 0 19 1
1
<?php
2
3
/*
4
 * The MIT License
5
 *
6
 * Copyright 2020 Enjoys.
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated documentation files (the "Software"), to deal
10
 * in the Software without restriction, including without limitation the rights
11
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
 * copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
 * THE SOFTWARE.
25
 */
26
27
declare(strict_types=1);
28
29
namespace Enjoys\Forms\Captcha\Defaults;
30
31
use Enjoys\Session\Session as Session;
32
33
/**
34
 * Description of Defaults
35
 *
36
 *
37
 * @author Enjoys
38
 */
39
class Defaults extends \Enjoys\Forms\Captcha\CaptchaBase implements \Enjoys\Forms\Captcha\CaptchaInterface
40
{
41
42
    private $code = '';
43
    
44
45
    public function __construct($message = null)
46
    {
47
48
        $this->setName('captcha_defaults');
49
        if (is_null($message)) {
50
            $message = 'Не верно введен код';
51
        }
52
        $this->setRuleMessage($message);
53
    }
54
55
56
    public function validate(\Enjoys\Forms\Element $element): bool
57
    {
58
59
60
        $method = $this->getRequest()->getMethod();
61
        $value = \getValueByIndexPath($element->getName(), $this->getRequest()->$method());
62
63
        if (Session::get($element->getName()) !== $value) {
64
            $element->setRuleError($this->ruleMessage);
0 ignored issues
show
Bug introduced by
The method setRuleError() does not exist on Enjoys\Forms\Element. It seems like you code against a sub-type of said class. However, the method does not exist in Enjoys\Forms\Elements\Optgroup or Enjoys\Forms\Elements\Submit or Enjoys\Forms\Elements\Option or Enjoys\Forms\Elements\Button or Enjoys\Forms\Elements\Image or Enjoys\Forms\Elements\Reset or Enjoys\Forms\Elements\Header. Are you sure you never get one of those? ( Ignorable by Annotation )

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

64
            $element->/** @scrutinizer ignore-call */ 
65
                      setRuleError($this->ruleMessage);
Loading history...
65
            return false;
66
        }
67
        return true;
68
    }
69
70
    public function renderHtml(\Enjoys\Forms\Element $element): string
71
    {
72
        $element->setAttributes([
73
            'type' => 'text',
74
            'autocomplete' => 'off'
75
        ]);
76
77
        $this->generateCode($element);
78
        $img = $this->createImage($this->getCode(), $this->getOption('width', 150), $this->getOption('height', 50));
0 ignored issues
show
Bug introduced by
150 of type integer is incompatible with the type Enjoys\Traits\type expected by parameter $defaults of Enjoys\Forms\Captcha\CaptchaBase::getOption(). ( Ignorable by Annotation )

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

78
        $img = $this->createImage($this->getCode(), $this->getOption('width', /** @scrutinizer ignore-type */ 150), $this->getOption('height', 50));
Loading history...
79
80
        //dump(Session::get($this->getName()));
81
        $html = '';
82
83
//        if ($this->element->isRuleError()) {
84
//            $html .= "<p style=\"color: red\">{$this->element->getRuleErrorMessage()}</p>";
85
//        }
86
        $html .= '<img src="data:image/jpeg;base64,' . $this->getBase64Image($img) . '" /><br /><input' . $element->getAttributesString() . '>';
87
88
        return $html;
89
    }
90
91
    private function generateCode(\Enjoys\Forms\Element $element)
92
    {
93
        $max = $this->getOption('size', 6);
0 ignored issues
show
Bug introduced by
6 of type integer is incompatible with the type Enjoys\Traits\type expected by parameter $defaults of Enjoys\Forms\Captcha\CaptchaBase::getOption(). ( Ignorable by Annotation )

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

93
        $max = $this->getOption('size', /** @scrutinizer ignore-type */ 6);
Loading history...
94
        $chars = $this->getOption('chars', 'qwertyuiopasdfghjklzxcvbnm1234567890');
0 ignored issues
show
Bug introduced by
'qwertyuiopasdfghjklzxcvbnm1234567890' of type string is incompatible with the type Enjoys\Traits\type expected by parameter $defaults of Enjoys\Forms\Captcha\CaptchaBase::getOption(). ( Ignorable by Annotation )

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

94
        $chars = $this->getOption('chars', /** @scrutinizer ignore-type */ 'qwertyuiopasdfghjklzxcvbnm1234567890');
Loading history...
95
        $size = StrLen($chars) - 1;
96
        // Определяем пустую переменную, в которую и будем записывать символы.
97
        $code = null;
98
        // Создаём пароль.
99
        while ($max--) {
100
            $code .= $chars[rand(0, $size)];
101
        }
102
        $this->code = $code;
103
        Session::set([
104
            $element->getName() => $this->code
105
        ]);
106
    }
107
108
    public function getCode()
109
    {
110
        return $this->code;
111
    }
112
113
    private function createImage($code, $width = 150, $height = 50)
114
    {
115
        // Создаем пустое изображение
116
        $img = \imagecreatetruecolor($width, $height);
117
118
        $background_color = [\mt_rand(200, 255), \mt_rand(200, 255), \mt_rand(200, 255)];
119
        // Заливаем фон белым цветом
120
        $background = \imagecolorallocate($img, $background_color[0], $background_color[1], $background_color[2]);
0 ignored issues
show
Bug introduced by
It seems like $img 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

120
        $background = \imagecolorallocate(/** @scrutinizer ignore-type */ $img, $background_color[0], $background_color[1], $background_color[2]);
Loading history...
121
        \imagefill($img, 0, 0, $background);
0 ignored issues
show
Bug introduced by
It seems like $img can also be of type false; however, parameter $image of imagefill() 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

121
        \imagefill(/** @scrutinizer ignore-type */ $img, 0, 0, $background);
Loading history...
122
123
124
        // Накладываем защитный код
125
        $x = 0;
126
        $letters = \str_split($code);
127
        $figures = [50, 70, 90, 110, 130, 150, 170, 190, 210];
128
129
        foreach ($letters as $letter) {
130
            //Ориентир
131
            $h = 1;
132
            //Рисуем
133
            $color = \imagecolorallocatealpha(
134
                    $img,
0 ignored issues
show
Bug introduced by
It seems like $img can also be of type false; however, parameter $image of imagecolorallocatealpha() 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

134
                    /** @scrutinizer ignore-type */ $img,
Loading history...
135
                    $figures[\rand(0, \count($figures) - 1)],
136
                    $figures[\rand(0, \count($figures) - 1)],
137
                    $figures[\rand(0, \count($figures) - 1)],
138
                    rand(10, 30)
139
            );
140
141
142
            // Формируем координаты для вывода символа
143
            if (empty($x)) {
144
                $x = (int) ($width * 0.08);
145
            } else {
146
                $x = (int) ($x + ($width * 0.8) / \count($letters) + \rand(0, (int) ($width * 0.01)));
147
            }
148
149
            if ($h == rand(1, 2)) {
150
                $y = (int) ((($height * 1) / 4) + \rand(0, (int) ($height * 0.1)));
151
            } else {
152
                $y = (int) ((($height * 1) / 4) - \rand(0, (int) ($height * 0.1)));
153
            }
154
155
156
            // Изменяем регистр символа
157
            if ($h == \rand(0, 1)) {
158
                $letter = \strtoupper($letter);
159
            }
160
            // Выводим символ на изображение
161
            \imagestring($img, 6, $x, $y, $letter, $color);
0 ignored issues
show
Bug introduced by
It seems like $img can also be of type false; however, parameter $image of imagestring() 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

161
            \imagestring(/** @scrutinizer ignore-type */ $img, 6, $x, $y, $letter, $color);
Loading history...
162
            $x++;
163
        }
164
165
        return $img;
166
    }
167
168
    private function getBase64Image($img)
169
    {
170
        \ob_start();
171
        \imagejpeg($img, null, 80);
172
        $img_data = \ob_get_contents();
173
        \ob_end_clean();
174
        return \base64_encode($img_data);
175
    }
176
}
177