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

daycry / auth / 16343465380

17 Jul 2025 11:07AM UTC coverage: 59.224% (-0.6%) from 59.854%
16343465380

push

github

web-flow
Merge pull request #23 from daycry/development

Improvements

57 of 292 new or added lines in 16 files covered. (19.52%)

6 existing lines in 4 files now uncovered.

1939 of 3274 relevant lines covered (59.22%)

22.81 hits per line

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

40.0
/src/Traits/BaseControllerTrait.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of Daycry Auth.
7
 *
8
 * (c) Daycry <daycry9@proton.me>
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 Daycry\Auth\Traits;
15

16
use CodeIgniter\Exceptions\ExceptionInterface;
17
use CodeIgniter\Exceptions\PageNotFoundException;
18
use CodeIgniter\HTTP\RequestInterface;
19
use CodeIgniter\HTTP\ResponseInterface;
20
use Config\Mimes;
21
use Config\Services;
22
use Daycry\Auth\Libraries\Utils;
23
use Daycry\Auth\Services\AttemptHandler;
24
use Daycry\Auth\Services\ExceptionHandler;
25
use Daycry\Auth\Services\RequestLogger;
26
use Daycry\Encryption\Encryption;
27
use Psr\Log\LoggerInterface;
28

29
/**
30
 * BaseControllerTrait that delegates to specialized services
31
 *
32
 * This version follows Single Responsibility Principle by using dedicated services
33
 * for logging, attempt handling, and exception management.
34
 */
35
trait BaseControllerTrait
36
{
37
    use Validation;
38

39
    protected Encryption $encryption;
40
    protected RequestLogger $requestLogger;
41
    protected AttemptHandler $attemptHandler;
42
    protected ExceptionHandler $exceptionHandler;
43
    protected array $args;
44
    protected mixed $content = null;
45

46
    /**
47
     * Hook for early checks - can be overridden by implementing classes
48
     */
49
    protected function earlyChecks(): void
50
    {
51
        // Override in child classes if needed
52
    }
15✔
53

54
    /**
55
     * Initialize controller with services
56
     */
57
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger): void
58
    {
59
        // Load required helpers
60
        helper(['security', 'auth']);
15✔
61

62
        // Initialize services
63
        $this->encryption       = new Encryption();
15✔
64
        $this->requestLogger    = new RequestLogger();
15✔
65
        $this->attemptHandler   = new AttemptHandler();
15✔
66
        $this->exceptionHandler = new ExceptionHandler();
15✔
67

68
        // Call parent initialization
69
        parent::initController($request, $response, $logger);
15✔
70

71
        // Set response format if method exists (for API controllers)
72
        if (method_exists($this, 'setFormat')) {
15✔
73
            $output = $this->request->negotiate('media', setting('Format.supportedResponseFormats'));
×
74
            $output = Mimes::guessExtensionFromType($output);
×
75
            $this->setFormat($output);
×
76
        }
77

78
        // Extract request parameters
79
        $this->args    = Utils::getAllParams();
15✔
80
        $this->content = $this->args['body'] ?? null;
15✔
81

82
        // Run early checks
83
        $this->earlyChecks();
15✔
84
    }
85

86
    /**
87
     * Cleanup and logging on destruction
88
     */
89
    public function __destruct()
90
    {
91
        if (isset($this->request) && $this->request) {
6✔
92
            $this->requestLogger->logRequest($this->response);
6✔
93

94
            if (! $this->requestLogger->isRequestAuthorized()) {
6✔
NEW
95
                $this->attemptHandler->handleInvalidAttempt($this->request);
×
96
            }
97
        }
98

99
        if (isset($this->validator) && $this->validator) {
6✔
100
            $this->validator->reset();
×
101
        }
102
    }
103

104
    /**
105
     * Get CSRF token for forms
106
     */
107
    protected function getToken(): array
108
    {
109
        return ['name' => csrf_token(), 'hash' => csrf_hash()];
2✔
110
    }
111

112
    /**
113
     * Main request handler with exception management
114
     */
115
    public function _remap(string $method, ...$params)
116
    {
117
        try {
118
            if (! method_exists($this, $method)) {
×
119
                throw PageNotFoundException::forPageNotFound();
×
120
            }
121

122
            // Validate attempts if enabled
NEW
123
            $this->attemptHandler->validateAttempts($this->response);
×
124

125
            // Execute the method
UNCOV
126
            $data = $this->{$method}(...$params);
×
127

128
            // Handle different response types
129
            if ($data instanceof ResponseInterface) {
×
130
                return $data;
×
131
            }
132

133
            // Return JSON for AJAX requests
NEW
134
            if (method_exists($this->request, 'isAJAX') && $this->request->isAJAX() && (is_array($data) || is_object($data))) {
×
UNCOV
135
                return $this->response->setJSON($data);
×
136
            }
137

138
            // Return regular response
139
            return $this->response->setBody($data);
×
140
        } catch (ExceptionInterface $ex) {
×
NEW
141
            return $this->exceptionHandler->handleException(
×
NEW
142
                $ex,
×
NEW
143
                $this->request,
×
NEW
144
                $this->response,
×
NEW
145
                $this->validator ?? null,
×
NEW
146
                $this,
×
NEW
147
            );
×
148
        }
149
    }
150

151
    /**
152
     * Mark request as unauthorized
153
     */
154
    protected function setRequestUnauthorized(): void
155
    {
NEW
156
        $this->requestLogger->setRequestAuthorized(false);
×
157
    }
158

159
    /**
160
     * Check if request is authorized
161
     */
162
    protected function isRequestAuthorized(): bool
163
    {
NEW
164
        return $this->requestLogger->isRequestAuthorized();
×
165
    }
166
}
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

© 2026 Coveralls, Inc