Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
TagsController
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 3
20
0.00% covered (danger)
0.00%
0 / 1
 beforeFilter
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 index
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 viewBySlug
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2declare(strict_types=1);
3
4namespace App\Controller;
5
6use Cake\Event\EventInterface;
7use Cake\Http\Exception\NotFoundException;
8
9/**
10 * Tags Controller
11 *
12 * Handles operations related to tags, including listing all tags and viewing articles associated with a specific tag.
13 *
14 * @property \App\Model\Table\TagsTable $Tags
15 */
16class TagsController extends AppController
17{
18    /**
19     * Configures actions that can be accessed without authentication.
20     *
21     * @param \Cake\Event\EventInterface $event The event object.
22     * @return void
23     */
24    public function beforeFilter(EventInterface $event): void
25    {
26        parent::beforeFilter($event);
27        $this->Authentication->allowUnauthenticated(['index', 'view', 'viewBySlug']);
28    }
29
30    /**
31     * Displays a paginated list of all tags.
32     *
33     * @return void
34     */
35    public function index(): void
36    {
37        $tags = $this->Tags->find()->all();
38        $this->set(compact('tags'));
39    }
40
41    /**
42     * Displays a tag and its associated published articles.
43     *
44     * Retrieves a tag by its slug and loads associated published articles with their authors.
45     * Throws an exception if the tag is not found.
46     *
47     * @param string $slug The unique slug of the tag to retrieve.
48     * @throws \Cake\Http\Exception\NotFoundException If the tag is not found.
49     * @return void
50     */
51    public function viewBySlug(string $slug): void
52    {
53        $query = $this->Tags->find()
54            ->contain(['Articles' => function ($q) {
55                return $q->select(['id', 'title', 'slug', 'user_id', 'image', 'created'])
56                    ->where([
57                        'Articles.is_published' => true,
58                        'Articles.kind' => 'article',
59                        ])
60                    ->contain(['Users' => function ($q) {
61                        return $q->select(['id', 'username']);
62                    }]);
63            }])
64            ->where(['Tags.slug' => $slug]);
65
66        $tag = $query->first();
67
68        if (!$tag) {
69            throw new NotFoundException(__('Tag not found'));
70        }
71
72        $this->set(compact('tag'));
73    }
74}