ci4

Форк
0
/
Controller.php 
183 строки · 4.8 Кб
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter;
15

16
use CodeIgniter\HTTP\CLIRequest;
17
use CodeIgniter\HTTP\Exceptions\HTTPException;
18
use CodeIgniter\HTTP\IncomingRequest;
19
use CodeIgniter\HTTP\RequestInterface;
20
use CodeIgniter\HTTP\ResponseInterface;
21
use CodeIgniter\Validation\Exceptions\ValidationException;
22
use CodeIgniter\Validation\ValidationInterface;
23
use Config\Validation;
24
use Psr\Log\LoggerInterface;
25

26
/**
27
 * Class Controller
28
 *
29
 * @see \CodeIgniter\ControllerTest
30
 */
31
class Controller
32
{
33
    /**
34
     * Helpers that will be automatically loaded on class instantiation.
35
     *
36
     * @var list<string>
37
     */
38
    protected $helpers = [];
39

40
    /**
41
     * Instance of the main Request object.
42
     *
43
     * @var CLIRequest|IncomingRequest
44
     */
45
    protected $request;
46

47
    /**
48
     * Instance of the main response object.
49
     *
50
     * @var ResponseInterface
51
     */
52
    protected $response;
53

54
    /**
55
     * Instance of logger to use.
56
     *
57
     * @var LoggerInterface
58
     */
59
    protected $logger;
60

61
    /**
62
     * Should enforce HTTPS access for all methods in this controller.
63
     *
64
     * @var int Number of seconds to set HSTS header
65
     */
66
    protected $forceHTTPS = 0;
67

68
    /**
69
     * Once validation has been run, will hold the Validation instance.
70
     *
71
     * @var ValidationInterface|null
72
     */
73
    protected $validator;
74

75
    /**
76
     * Constructor.
77
     *
78
     * @return void
79
     *
80
     * @throws HTTPException
81
     */
82
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
83
    {
84
        $this->request  = $request;
85
        $this->response = $response;
86
        $this->logger   = $logger;
87

88
        if ($this->forceHTTPS > 0) {
89
            $this->forceHTTPS($this->forceHTTPS);
90
        }
91

92
        // Autoload helper files.
93
        helper($this->helpers);
94
    }
95

96
    /**
97
     * A convenience method to use when you need to ensure that a single
98
     * method is reached only via HTTPS. If it isn't, then a redirect
99
     * will happen back to this method and HSTS header will be sent
100
     * to have modern browsers transform requests automatically.
101
     *
102
     * @param int $duration The number of seconds this link should be
103
     *                      considered secure for. Only with HSTS header.
104
     *                      Default value is 1 year.
105
     *
106
     * @return void
107
     *
108
     * @throws HTTPException
109
     */
110
    protected function forceHTTPS(int $duration = 31_536_000)
111
    {
112
        force_https($duration, $this->request, $this->response);
113
    }
114

115
    /**
116
     * How long to cache the current page for.
117
     *
118
     * @params int $time time to live in seconds.
119
     *
120
     * @return void
121
     */
122
    protected function cachePage(int $time)
123
    {
124
        service('responsecache')->setTtl($time);
125
    }
126

127
    /**
128
     * A shortcut to performing validation on Request data.
129
     *
130
     * @param array|string $rules
131
     * @param array        $messages An array of custom error messages
132
     */
133
    protected function validate($rules, array $messages = []): bool
134
    {
135
        $this->setValidator($rules, $messages);
136

137
        return $this->validator->withRequest($this->request)->run();
138
    }
139

140
    /**
141
     * A shortcut to performing validation on any input data.
142
     *
143
     * @param array        $data     The data to validate
144
     * @param array|string $rules
145
     * @param array        $messages An array of custom error messages
146
     * @param string|null  $dbGroup  The database group to use
147
     */
148
    protected function validateData(array $data, $rules, array $messages = [], ?string $dbGroup = null): bool
149
    {
150
        $this->setValidator($rules, $messages);
151

152
        return $this->validator->run($data, null, $dbGroup);
153
    }
154

155
    /**
156
     * @param array|string $rules
157
     */
158
    private function setValidator($rules, array $messages): void
159
    {
160
        $this->validator = service('validation');
161

162
        // If you replace the $rules array with the name of the group
163
        if (is_string($rules)) {
164
            $validation = config(Validation::class);
165

166
            // If the rule wasn't found in the \Config\Validation, we
167
            // should throw an exception so the developer can find it.
168
            if (! isset($validation->{$rules})) {
169
                throw ValidationException::forRuleNotFound($rules);
170
            }
171

172
            // If no error message is defined, use the error message in the Config\Validation file
173
            if ($messages === []) {
174
                $errorName = $rules . '_errors';
175
                $messages  = $validation->{$errorName} ?? [];
176
            }
177

178
            $rules = $validation->{$rules};
179
        }
180

181
        $this->validator->setRules($rules, $messages);
182
    }
183
}
184

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.