• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 9366456936

04 Jun 2024 11:44AM UTC coverage: 84.448% (+0.006%) from 84.442%
9366456936

Pull #8908

github

web-flow
Merge 737312559 into 8c459cf12
Pull Request #8908: feat: Controller.php Add custom Config\Validation class

5 of 6 new or added lines in 1 file covered. (83.33%)

85 existing lines in 5 files now uncovered.

20357 of 24106 relevant lines covered (84.45%)

188.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.83
/system/Controller.php
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
     * Config Validation file
77
     *
78
     * @var Validation
79
     */
80
    protected $configValidation;
81

82
    /**
83
     * Constructor.
84
     *
85
     * @return void
86
     *
87
     * @throws HTTPException
88
     */
89
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
90
    {
91
        $this->request          = $request;
73✔
92
        $this->response         = $response;
73✔
93
        $this->logger           = $logger;
73✔
94
        $this->configValidation = config(Validation::class);
73✔
95

96
        if ($this->forceHTTPS > 0) {
73✔
97
            $this->forceHTTPS($this->forceHTTPS);
1✔
98
        }
99

100
        // Autoload helper files.
101
        helper($this->helpers);
72✔
102
    }
103

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

123
    /**
124
     * How long to cache the current page for.
125
     *
126
     * @params int $time time to live in seconds.
127
     *
128
     * @return void
129
     */
130
    protected function cachePage(int $time)
131
    {
132
        service('responsecache')->setTtl($time);
1✔
133
    }
134

135
    /**
136
     * A shortcut to performing validation on Request data.
137
     *
138
     * @param array|string $rules
139
     * @param array        $messages An array of custom error messages
140
     */
141
    protected function validate($rules, array $messages = []): bool
142
    {
143
        $this->setValidator($rules, $messages);
4✔
144

145
        return $this->validator->withRequest($this->request)->run();
3✔
146
    }
147

148
    /**
149
     * A shortcut to performing validation on any input data.
150
     *
151
     * @param array        $data     The data to validate
152
     * @param array|string $rules
153
     * @param array        $messages An array of custom error messages
154
     * @param string|null  $dbGroup  The database group to use
155
     */
156
    protected function validateData(array $data, $rules, array $messages = [], ?string $dbGroup = null): bool
157
    {
158
        $this->setValidator($rules, $messages);
1✔
159

160
        return $this->validator->run($data, null, $dbGroup);
1✔
161
    }
162

163
    protected function setConfigValidator(Validation $config): void
164
    {
NEW
165
        $this->configValidation = $config;
×
166
    }
167

168
    /**
169
     * @param array|string $rules
170
     * @param array        $messages An array of custom error messages
171
     */
172
    private function setValidator($rules, array $messages): void
173
    {
174
        $this->validator = service('validation');
5✔
175

176
        // If you replace the $rules array with the name of the group
177
        if (is_string($rules)) {
5✔
178
            $validation = $this->configValidation;
3✔
179

180
            // If the rule wasn't found in the \Config\Validation, we
181
            // should throw an exception so the developer can find it.
182
            if (! isset($validation->{$rules})) {
3✔
183
                throw ValidationException::forRuleNotFound($rules);
1✔
184
            }
185

186
            // If no error message is defined, use the error message in the Config\Validation file
187
            if ($messages === []) {
2✔
188
                $errorName = $rules . '_errors';
1✔
189
                $messages  = $validation->{$errorName} ?? [];
1✔
190
            }
191

192
            $rules = $validation->{$rules};
2✔
193
        }
194

195
        $this->validator->setRules($rules, $messages);
4✔
196
    }
197
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc