| Total Complexity | 79 |
| Total Lines | 509 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 1 | Features | 0 |
Complex classes like AppController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use AppController, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 34 | class AppController extends Controller |
||
| 35 | { |
||
| 36 | /** |
||
| 37 | * BEdita4 API client |
||
| 38 | * |
||
| 39 | * @var \BEdita\SDK\BEditaClient |
||
| 40 | */ |
||
| 41 | protected $apiClient = null; |
||
| 42 | |||
| 43 | /** |
||
| 44 | * @inheritDoc |
||
| 45 | */ |
||
| 46 | public function initialize(): void |
||
| 47 | { |
||
| 48 | parent::initialize(); |
||
| 49 | |||
| 50 | $this->loadComponent('RequestHandler', ['enableBeforeRedirect' => false]); |
||
| 51 | $this->loadComponent('App.Flash', ['clear' => true]); |
||
| 52 | $this->loadComponent('Security'); |
||
| 53 | |||
| 54 | // API config may not be set in `login` for a multi-project setup |
||
| 55 | if (Configure::check('API.apiBaseUrl')) { |
||
| 56 | $this->apiClient = ApiClientProvider::getApiClient(); |
||
| 57 | } |
||
| 58 | |||
| 59 | $this->loadComponent('Authentication.Authentication', [ |
||
| 60 | 'logoutRedirect' => '/login', |
||
| 61 | ]); |
||
| 62 | |||
| 63 | $this->loadComponent('Modules', [ |
||
| 64 | 'currentModuleName' => $this->name, |
||
| 65 | ]); |
||
| 66 | $this->loadComponent('Schema'); |
||
| 67 | } |
||
| 68 | |||
| 69 | /** |
||
| 70 | * @inheritDoc |
||
| 71 | */ |
||
| 72 | public function beforeFilter(EventInterface $event): ?Response |
||
| 73 | { |
||
| 74 | /** @var \Authentication\Identity|null $identity */ |
||
| 75 | $identity = $this->Authentication->getIdentity(); |
||
| 76 | if ($identity && $identity->get('tokens')) { |
||
| 77 | $this->apiClient->setupTokens($identity->get('tokens')); |
||
| 78 | } elseif (!in_array(rtrim($this->getRequest()->getPath(), '/'), ['/login'])) { |
||
| 79 | $route = $this->loginRedirectRoute(); |
||
| 80 | $this->Flash->error(__('Login required')); |
||
| 81 | |||
| 82 | return $this->redirect($route); |
||
| 83 | } |
||
| 84 | $this->setupOutputTimezone(); |
||
| 85 | $this->Security->setConfig('blackHoleCallback', 'blackhole'); |
||
| 86 | |||
| 87 | return null; |
||
| 88 | } |
||
| 89 | |||
| 90 | /** |
||
| 91 | * Handle security blackhole with logs for now |
||
| 92 | * |
||
| 93 | * @param string $type Exception type |
||
| 94 | * @param \Cake\Controller\Exception\SecurityException $exception Raised exception |
||
| 95 | * @return void |
||
| 96 | * @throws \Cake\Http\Exception\BadRequestException |
||
| 97 | * @codeCoverageIgnore |
||
| 98 | */ |
||
| 99 | public function blackhole(string $type, SecurityException $exception): void |
||
| 100 | { |
||
| 101 | // Log original exception |
||
| 102 | $this->log($exception->getMessage(), 'error'); |
||
| 103 | |||
| 104 | // Log form data & session id |
||
| 105 | $token = (array)$this->getRequest()->getData('_Token'); |
||
| 106 | unset($token['debug']); |
||
| 107 | $this->log('[Blackhole] type: ' . $type, 'debug'); |
||
| 108 | $this->log('[Blackhole] form token: ' . json_encode($token), 'debug'); |
||
| 109 | $this->log('[Blackhole] form fields: ' . json_encode(array_keys((array)$this->getRequest()->getData())), 'debug'); |
||
| 110 | $this->log('[Blackhole] form session id: ' . (string)$this->getRequest()->getData('_session_id'), 'debug'); |
||
| 111 | $sessionId = $this->getRequest()->getSession()->id(); |
||
| 112 | $this->log('[Blackhole] current session id: ' . $sessionId, 'debug'); |
||
| 113 | |||
| 114 | // Throw a generic bad request exception. |
||
| 115 | throw new BadRequestException(); |
||
| 116 | } |
||
| 117 | |||
| 118 | /** |
||
| 119 | * Return route array for login redirect. |
||
| 120 | * When request is not a get, return route without redirect. |
||
| 121 | * When request uri path equals request attribute webroot (the app 'webroot'), return route without redirect. |
||
| 122 | * Return route with redirect, otherwise. |
||
| 123 | * |
||
| 124 | * @return array |
||
| 125 | */ |
||
| 126 | protected function loginRedirectRoute(): array |
||
| 142 | } |
||
| 143 | |||
| 144 | /** |
||
| 145 | * Setup output timezone from user session |
||
| 146 | * |
||
| 147 | * @return void |
||
| 148 | */ |
||
| 149 | protected function setupOutputTimezone(): void |
||
| 163 | } |
||
| 164 | |||
| 165 | /** |
||
| 166 | * {@inheritDoc} |
||
| 167 | * |
||
| 168 | * Update session tokens if updated/refreshed by client |
||
| 169 | */ |
||
| 170 | public function beforeRender(EventInterface $event): ?Response |
||
| 171 | { |
||
| 172 | /** @var \Authentication\Identity|null $user */ |
||
| 173 | $user = $this->Authentication->getIdentity(); |
||
| 174 | if ($user) { |
||
| 175 | $tokens = $this->apiClient->getTokens(); |
||
| 176 | if ($tokens && $user->get('tokens') !== $tokens) { |
||
| 177 | $data = compact('tokens') + (array)$user->getOriginalData(); |
||
| 178 | $user = new Identity($data); |
||
| 179 | $this->Authentication->setIdentity($user); |
||
| 180 | } |
||
| 181 | |||
| 182 | $this->set(compact('user')); |
||
| 183 | } |
||
| 184 | |||
| 185 | $path = $this->viewBuilder()->getTemplatePath(); |
||
| 186 | $this->viewBuilder()->setTemplatePath('Pages/' . $path); |
||
| 187 | |||
| 188 | return null; |
||
| 189 | } |
||
| 190 | |||
| 191 | /** |
||
| 192 | * Prepare request, set properly json data. |
||
| 193 | * |
||
| 194 | * @param string $type Object type |
||
| 195 | * @return array request data |
||
| 196 | */ |
||
| 197 | protected function prepareRequest($type): array |
||
| 212 | } |
||
| 213 | |||
| 214 | /** |
||
| 215 | * Setup special attributes to be saved. |
||
| 216 | * |
||
| 217 | * @param array $data Request data |
||
| 218 | * @return void |
||
| 219 | */ |
||
| 220 | protected function specialAttributes(array &$data): void |
||
| 221 | { |
||
| 222 | // remove temporary session id |
||
| 223 | unset($data['_session_id']); |
||
| 224 | |||
| 225 | // if password is empty, unset it |
||
| 226 | if (array_key_exists('password', $data) && empty($data['password'])) { |
||
| 227 | unset($data['password']); |
||
| 228 | unset($data['confirm-password']); |
||
| 229 | } |
||
| 230 | |||
| 231 | $this->decodeJsonAttributes($data); |
||
| 232 | |||
| 233 | // remove date_ranges items having empty both start & end dates |
||
| 234 | if (!empty($data['date_ranges'])) { |
||
| 235 | $data['date_ranges'] = array_filter( |
||
| 236 | (array)$data['date_ranges'], |
||
| 237 | function ($item) { |
||
| 238 | return !empty($item['start_date']) || !empty($item['end_date']); |
||
| 239 | } |
||
| 240 | ); |
||
| 241 | } |
||
| 242 | |||
| 243 | // prepare categories |
||
| 244 | if (!empty($data['categories'])) { |
||
| 245 | $data['categories'] = array_map(function ($category) { |
||
| 246 | return ['name' => $category]; |
||
| 247 | }, $data['categories']); |
||
| 248 | } |
||
| 249 | |||
| 250 | // decode json fields |
||
| 251 | $types = (array)Hash::get($data, '_types'); |
||
| 252 | if (!empty($types)) { |
||
| 253 | foreach ($types as $field => $type) { |
||
| 254 | if ($type === 'json' && is_string($data[$field])) { |
||
| 255 | $data[$field] = json_decode($data[$field], true); |
||
| 256 | } |
||
| 257 | } |
||
| 258 | unset($data['_types']); |
||
| 259 | } |
||
| 260 | } |
||
| 261 | |||
| 262 | /** |
||
| 263 | * Decodes JSON attributes. |
||
| 264 | * |
||
| 265 | * @param array $data Request data |
||
| 266 | * @return void |
||
| 267 | */ |
||
| 268 | protected function decodeJsonAttributes(array &$data): void |
||
| 269 | { |
||
| 270 | if (empty($data['_jsonKeys'])) { |
||
| 271 | return; |
||
| 272 | } |
||
| 273 | |||
| 274 | $keys = explode(',', (string)$data['_jsonKeys']); |
||
| 275 | foreach ($keys as $key) { |
||
| 276 | $value = Hash::get($data, $key); |
||
| 277 | $decoded = json_decode((string)$value, true); |
||
| 278 | if ($decoded === []) { |
||
| 279 | // decode as empty object in case of empty array |
||
| 280 | $decoded = json_decode((string)$value); |
||
| 281 | } |
||
| 282 | $data = Hash::insert($data, $key, $decoded); |
||
| 283 | } |
||
| 284 | unset($data['_jsonKeys']); |
||
| 285 | } |
||
| 286 | |||
| 287 | /** |
||
| 288 | * Prepare request relation data. |
||
| 289 | * |
||
| 290 | * @param array $data Request data |
||
| 291 | * @return void |
||
| 292 | */ |
||
| 293 | protected function prepareRelations(array &$data): void |
||
| 294 | { |
||
| 295 | // relations data for view/save - prepare api calls |
||
| 296 | if (!empty($data['relations'])) { |
||
| 297 | $api = []; |
||
| 298 | foreach ($data['relations'] as $relation => $relationData) { |
||
| 299 | $id = $data['id']; |
||
| 300 | foreach ($relationData as $method => $ids) { |
||
| 301 | if (is_string($ids)) { |
||
| 302 | $relatedIds = json_decode($ids, true); |
||
| 303 | } else { |
||
| 304 | $relatedIds = array_map( |
||
| 305 | function ($id) { |
||
| 306 | return json_decode($id, true); |
||
| 307 | }, |
||
| 308 | $ids |
||
| 309 | ); |
||
| 310 | } |
||
| 311 | if ($method === 'replaceRelated' || !empty($relatedIds)) { |
||
| 312 | $api[] = compact('method', 'id', 'relation', 'relatedIds'); |
||
| 313 | } |
||
| 314 | } |
||
| 315 | } |
||
| 316 | $data['_api'] = $api; |
||
| 317 | } |
||
| 318 | unset($data['relations']); |
||
| 319 | } |
||
| 320 | |||
| 321 | /** |
||
| 322 | * Handle `parents` or `parent` relationship looking at `_changedParents` input flag |
||
| 323 | * |
||
| 324 | * @param string $type Object type |
||
| 325 | * @param array $data Form data |
||
| 326 | * @return void |
||
| 327 | */ |
||
| 328 | protected function setupParentsRelation(string $type, array &$data): void |
||
| 329 | { |
||
| 330 | $changedParents = (bool)Hash::get($data, '_changedParents'); |
||
| 331 | unset($data['_changedParents']); |
||
| 332 | $relation = 'parents'; |
||
| 333 | if ($type === 'folders') { |
||
| 334 | $relation = 'parent'; |
||
| 335 | } |
||
| 336 | if (empty($changedParents)) { |
||
| 337 | unset($data['relations'][$relation]); |
||
| 338 | |||
| 339 | return; |
||
| 340 | } |
||
| 341 | if (empty($data['relations'][$relation])) { |
||
| 342 | // all parents deselected => replace with empty set |
||
| 343 | $data['relations'][$relation] = ['replaceRelated' => []]; |
||
| 344 | } |
||
| 345 | } |
||
| 346 | |||
| 347 | /** |
||
| 348 | * Setup changed attributes to be saved. |
||
| 349 | * Remove unchanged attributes from $data array. |
||
| 350 | * |
||
| 351 | * @param array $data Request data |
||
| 352 | * @return void |
||
| 353 | */ |
||
| 354 | protected function changedAttributes(array &$data): void |
||
| 355 | { |
||
| 356 | if (!empty($data['_actualAttributes'])) { |
||
| 357 | $attributes = json_decode($data['_actualAttributes'], true); |
||
| 358 | if ($attributes === null) { |
||
| 359 | $this->log(sprintf('Wrong _actualAttributes, not a json string: %s', $data['_actualAttributes']), 'error'); |
||
| 360 | $attributes = []; |
||
| 361 | } |
||
| 362 | foreach ($attributes as $key => $value) { |
||
| 363 | // remove unchanged attributes from $data |
||
| 364 | if (array_key_exists($key, $data) && !$this->hasFieldChanged($value, $data[$key])) { |
||
| 365 | unset($data[$key]); |
||
| 366 | } |
||
| 367 | } |
||
| 368 | unset($data['_actualAttributes']); |
||
| 369 | } |
||
| 370 | } |
||
| 371 | |||
| 372 | /** |
||
| 373 | * Return true if $value1 equals $value2 or both are empty (null|'') |
||
| 374 | * |
||
| 375 | * @param mixed $value1 The first value | field value in model data (db) |
||
| 376 | * @param mixed $value2 The second value | field value from form |
||
| 377 | * @return bool |
||
| 378 | */ |
||
| 379 | protected function hasFieldChanged($value1, $value2): bool |
||
| 380 | { |
||
| 381 | if ($value1 === $value2) { |
||
| 382 | return false; // not changed |
||
| 383 | } |
||
| 384 | if (($value1 === null || $value1 === '') && ($value2 === null || $value2 === '')) { |
||
| 385 | return false; // not changed |
||
| 386 | } |
||
| 387 | $booleanItems = ['0', '1', 'true', 'false', 0, 1]; |
||
| 388 | if (is_bool($value1) && !is_bool($value2) && in_array($value2, $booleanItems, true)) { // i.e. true / "1" |
||
| 389 | return $value1 !== boolval($value2); |
||
| 390 | } |
||
| 391 | if (is_numeric($value1) && is_string($value2)) { |
||
| 392 | return (string)$value1 !== $value2; |
||
| 393 | } |
||
| 394 | if (is_string($value1) && is_numeric($value2)) { |
||
| 395 | return $value1 !== (string)$value2; |
||
| 396 | } |
||
| 397 | |||
| 398 | return $value1 !== $value2; |
||
| 399 | } |
||
| 400 | |||
| 401 | /** |
||
| 402 | * Check request data by options. |
||
| 403 | * |
||
| 404 | * - $options['allowedMethods']: check allowed method(s) |
||
| 405 | * - $options['requiredParameters']: check required parameter(s) |
||
| 406 | * |
||
| 407 | * @param array $options The options for request check(s) |
||
| 408 | * @return array The request data for required parameters, if any |
||
| 409 | * @throws \Cake\Http\Exception\BadRequestException on empty request or empty data by parameter |
||
| 410 | */ |
||
| 411 | protected function checkRequest(array $options = []): array |
||
| 412 | { |
||
| 413 | // check allowed methods |
||
| 414 | if (!empty($options['allowedMethods'])) { |
||
| 415 | $this->getRequest()->allowMethod($options['allowedMethods']); |
||
| 416 | } |
||
| 417 | |||
| 418 | // check request required parameters, if any |
||
| 419 | $data = []; |
||
| 420 | if (!empty($options['requiredParameters'])) { |
||
| 421 | foreach ($options['requiredParameters'] as $param) { |
||
| 422 | $val = $this->getRequest()->getData($param); |
||
| 423 | if (empty($val)) { |
||
| 424 | throw new BadRequestException(sprintf('Empty %s', $param)); |
||
| 425 | } |
||
| 426 | $data[$param] = $val; |
||
| 427 | } |
||
| 428 | } |
||
| 429 | |||
| 430 | return $data; |
||
| 431 | } |
||
| 432 | |||
| 433 | /** |
||
| 434 | * Apply session filter (if any): if found, redirect properly. |
||
| 435 | * Session key: '{$currentModuleName}.filter' |
||
| 436 | * Scenarios: |
||
| 437 | * |
||
| 438 | * Query parameter 'reset=1': remove session key and redirect |
||
| 439 | * Query parameters found: write them on session with proper key ({currentModuleName}.filter) |
||
| 440 | * Session data for session key: build uri from session data and redirect to new uri. |
||
| 441 | * |
||
| 442 | * @return \Cake\Http\Response|null |
||
| 443 | */ |
||
| 444 | protected function applySessionFilter(): ?Response |
||
| 445 | { |
||
| 446 | $session = $this->getRequest()->getSession(); |
||
| 447 | $sessionKey = sprintf('%s.filter', $this->Modules->getConfig('currentModuleName')); |
||
| 448 | |||
| 449 | // if reset request, delete session data by key and redirect to proper uri |
||
| 450 | if ($this->getRequest()->getQuery('reset') === '1') { |
||
| 451 | $session->delete($sessionKey); |
||
| 452 | |||
| 453 | return $this->redirect((string)$this->getRequest()->getUri()->withQuery('')); |
||
| 454 | } |
||
| 455 | |||
| 456 | // write request query parameters (if any) in session |
||
| 457 | $params = $this->getRequest()->getQueryParams(); |
||
| 458 | if (!empty($params)) { |
||
| 459 | unset($params['_search']); |
||
| 460 | $session->write($sessionKey, $params); |
||
| 461 | |||
| 462 | return null; |
||
| 463 | } |
||
| 464 | |||
| 465 | // read request query parameters from session and redirect to proper page |
||
| 466 | $params = (array)$session->read($sessionKey); |
||
| 467 | if (!empty($params)) { |
||
| 468 | $query = http_build_query($params, '', '&', PHP_QUERY_RFC3986); |
||
| 469 | |||
| 470 | return $this->redirect((string)$this->getRequest()->getUri()->withQuery($query)); |
||
| 471 | } |
||
| 472 | |||
| 473 | return null; |
||
| 474 | } |
||
| 475 | |||
| 476 | /** |
||
| 477 | * Set objectNav array and objectNavModule. |
||
| 478 | * Objects can be in different modules: |
||
| 479 | * |
||
| 480 | * - a document is in "documents" and "objects" index |
||
| 481 | * - an image is in "images" and "media" index |
||
| 482 | * - etc. |
||
| 483 | * |
||
| 484 | * The session variable objectNavModule stores the last module index visited; |
||
| 485 | * this is used then in controller view, to obtain the proper object nav (@see \App\Controller\AppController::getObjectNav) |
||
| 486 | * |
||
| 487 | * @param array $objects The objects to parse to set prev and next data |
||
| 488 | * @return void |
||
| 489 | */ |
||
| 490 | protected function setObjectNav($objects): void |
||
| 491 | { |
||
| 492 | $moduleName = $this->Modules->getConfig('currentModuleName'); |
||
| 493 | $total = count(array_keys($objects)); |
||
| 494 | $objectNav = []; |
||
| 495 | foreach ($objects as $i => $object) { |
||
| 496 | $objectNav[$moduleName][$object['id']] = [ |
||
| 497 | 'prev' => $i > 0 ? Hash::get($objects, sprintf('%d.id', $i - 1)) : null, |
||
| 498 | 'next' => $i + 1 < $total ? Hash::get($objects, sprintf('%d.id', $i + 1)) : null, |
||
| 499 | 'index' => $i + 1, |
||
| 500 | 'total' => $total, |
||
| 501 | 'object_type' => Hash::get($objects, sprintf('%d.object_type', $i)), |
||
| 502 | ]; |
||
| 503 | } |
||
| 504 | $session = $this->getRequest()->getSession(); |
||
| 505 | $session->write('objectNav', $objectNav); |
||
| 506 | $session->write('objectNavModule', $moduleName); |
||
| 507 | } |
||
| 508 | |||
| 509 | /** |
||
| 510 | * Get objectNav for ID and current module name |
||
| 511 | * |
||
| 512 | * @param string $id The object ID |
||
| 513 | * @return array |
||
| 514 | */ |
||
| 515 | protected function getObjectNav($id): array |
||
| 516 | { |
||
| 517 | // get objectNav from session |
||
| 518 | $session = $this->getRequest()->getSession(); |
||
| 519 | $objectNav = (array)$session->read('objectNav'); |
||
| 520 | if (empty($objectNav)) { |
||
| 521 | return []; |
||
| 522 | } |
||
| 523 | |||
| 524 | // get objectNav by session objectNavModule |
||
| 525 | $objectNavModule = (string)$session->read('objectNavModule'); |
||
| 526 | |||
| 527 | return (array)Hash::get($objectNav, sprintf('%s.%s', $objectNavModule, $id), []); |
||
| 528 | } |
||
| 529 | |||
| 530 | /** |
||
| 531 | * Cake 4 compatibility wrapper method: set items to serialize for the view |
||
| 532 | * |
||
| 533 | * In Cake 3 => $this->set('_serialize', ['data']); |
||
| 534 | * In Cake 4 => $this->viewBuilder()->setOption('serialize', ['data']) |
||
| 535 | * |
||
| 536 | * @param array $items Items to serialize |
||
| 537 | * @return void |
||
| 538 | * @codeCoverageIgnore |
||
| 539 | */ |
||
| 540 | protected function setSerialize(array $items): void |
||
| 543 | } |
||
| 544 | } |
||
| 545 |