Completed
Push — master ( 2514a9...f79ce1 )
by Tim
29:24 queued 14:20
created

FaqController::addSchemaOrgHeader()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 41
rs 9.264
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
declare(strict_types = 1);
4
/**
5
 * FAQ.
6
 */
7
8
namespace HDNET\Faq\Controller;
9
10
use HDNET\Faq\Domain\Model\Question;
11
use HDNET\Faq\Domain\Model\Request\Faq;
12
use HDNET\Faq\Domain\Model\Request\QuestionRequest;
13
use HDNET\Faq\Domain\Repository\QuestionCategoryRepository;
14
use HDNET\Faq\Domain\Repository\QuestionRepository;
15
use TYPO3\CMS\Core\Utility\GeneralUtility;
16
use TYPO3\CMS\Extbase\Annotation\IgnoreValidation;
17
use TYPO3\CMS\Extbase\Mvc\Exception\StopActionException;
18
use TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException;
19
20
/**
21
 * FAQ.
22
 */
23
class FaqController extends AbstractController
24
{
25
    const TEASER_MODE_VOTING = 0;
26
27
    const TEASER_MODE_CUSTOM = 1;
28
29
    /**
30
     * Question repository.
31
     *
32
     * @var QuestionRepository
33
     */
34
    protected $questionRepository;
35
36
    /**
37
     * Question category repository.
38
     *
39
     * @var QuestionCategoryRepository
40
     */
41
    protected $questionCategoryRepository;
42
43
    public function __construct(QuestionRepository $questionRepository, QuestionCategoryRepository $questionCategoryRepository)
44
    {
45
        $this->questionRepository = $questionRepository;
46
        $this->questionCategoryRepository = $questionCategoryRepository;
47
    }
48
49
    /**
50
     * Index action.
51
     *
52
     * @throws InvalidQueryException
53
     */
54
    public function indexAction(Faq $faq = null, bool $showAll = false): void
55
    {
56
        $topCategory = (int)$this->settings['faq']['topCategory'];
57
58
        if (true === (bool)$this->settings['overrideShowAll']) {
59
            $showAll = true;
60
        }
61
        if (0 !== (int)$this->settings['overrideTopCategory']) {
62
            $topCategory = (int)$this->settings['overrideTopCategory'];
63
        }
64
65
        if (\is_object($faq)) {
66
            $questions = $this->questionRepository->findByFaq($faq, $topCategory);
67
            $showResults = true;
68
        } elseif ($showAll) {
69
            $showResults = true;
70
            $questions = $this->questionRepository->findAll($topCategory);
71
        } else {
72
            $questions = [];
73
            $showResults = false;
74
        }
75
76
        if (self::TEASER_MODE_VOTING === (int)$this->settings['topMode']) {
77
            $topQuestions = $this->questionRepository->findTop(
78
                (int)$this->settings['faq']['limitTop'],
79
                $topCategory,
80
                GeneralUtility::intExplode(',', $this->settings['faq']['topQuestions'], true)
81
            );
82
        } else {
83
            $topQuestions = $this->questionRepository->findByUidsSorted(GeneralUtility::intExplode(
84
                ',',
85
                $this->settings['custom'],
86
                true
87
            ));
88
        }
89
90
        if (null === $faq) {
91
            $faq = $this->objectManager->get(Faq::class);
0 ignored issues
show
Deprecated Code introduced by
The method TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated with message: since TYPO3 10.4, will be removed in version 12.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
92
        }
93
        
94
        $this->addSchemaOrgHeader($questions);
95
96
        $this->view->assignMultiple([
97
            'showResults' => $showResults,
98
            'faq' => $faq,
99
            'questions' => $questions,
100
            'newQuestions' => $this->questionRepository->findNewest(
101
                (int)$this->settings['faq']['limitNewest'],
102
                $topCategory
103
            ),
104
            'topQuestions' => $topQuestions,
105
            'categories' => $this->questionCategoryRepository->findByParent(
106
                $topCategory,
107
                (bool)$this->settings['faq']['categorySort'] ?: false
108
            ),
109
        ]);
110
    }
111
112
    /**
113
     * Render the teaser action.
114
     */
115
    public function teaserAction(): void
116
    {
117
        $topQuestions = GeneralUtility::intExplode(',', $this->settings['faq']['topQuestions'], true);
118
        $teaserCategories = GeneralUtility::intExplode(',', $this->settings['faq']['teaserCategories'], true);
119
        $teaserLimit = (int)$this->settings['faq']['teaserLimit'];
120
        $questions = $this->questionRepository->findByTeaserConfiguration(
121
            $topQuestions,
122
            $teaserCategories,
123
            $teaserLimit
124
        );
125
        $this->addSchemaOrgHeader($questions);
126
        $this->view->assign('questions', $questions);
127
    }
128
129
    /**
130
     * Render the detail action.
131
     */
132
    public function detailAction(Question $question): void
133
    {
134
        $this->addSchemaOrgHeader([$question]);
135
        $this->view->assign('question', $question);
136
    }
137
138
    /**
139
     * Enter form.
140
     *
141
     * @IgnoreValidation(argumentName="question")
142
     */
143
    public function formAction(QuestionRequest $question = null): void
144
    {
145
        if (null === $question) {
146
            $question = new QuestionRequest();
147
        }
148
149
        $this->view->assign('question', $question);
150
    }
151
152
    /**
153
     * Send action.
154
     *
155
     * @throws StopActionException
156
     */
157
    public function sendAction(QuestionRequest $question, string $captcha = null): void
158
    {
159
        // @todo integrate captcha based on $this->settings['enableCaptcha']
160
        // * @validate $captcha \SJBR\SrFreecap\Validation\Validator\CaptchaValidator && Not Empty
161
        $this->disableIndexing();
162
163
        $targetEmailAddress = $this->getTargetEmailAddress();
164
        if (GeneralUtility::validEmail($targetEmailAddress)) {
165
            $this->view->assign('to', [$targetEmailAddress => $targetEmailAddress]);
166
            $this->view->assign('subject', 'Neue Frage eingestellt');
167
            $this->view->assign('question', $question);
168
            $this->view->assign('captcha', $captcha);
169
            $this->view->render();
170
        }
171
        $this->forward('user');
172
    }
173
174
    /**
175
     * user action.
176
     *
177
     * @throws StopActionException
178
     */
179
    public function userAction(QuestionRequest $question): void
180
    {
181
        if (GeneralUtility::validEmail($question->getEmail())) {
182
            $this->view->assignMultiple([
183
                'subject' => 'FAQ eingereicht',
184
                'to' => [$question->getEmail() => $question->getEmail()],
185
                'question' => $question,
186
            ]);
187
            $this->view->render();
188
        }
189
        $this->forward('thanks');
190
    }
191
192
    /**
193
     * Send action.
194
     */
195
    public function thanksAction(QuestionRequest $question): void
196
    {
197
        $this->disableIndexing();
198
        $this->view->assign('question', $question);
199
    }
200
201
    /**
202
     * Get the target Email address.
203
     *
204
     * @throws \Exception
205
     */
206
    protected function getTargetEmailAddress(): string
207
    {
208
        if (isset($this->settings['faq']['targetEmail']) && GeneralUtility::validEmail(\trim((string)$this->settings['faq']['targetEmail']))) {
209
            return \trim((string)$this->settings['faq']['targetEmail']);
210
        }
211
        throw new \Exception('No target e-mail address found', 123718231823);
212
    }
213
214
    protected function addSchemaOrgHeader(iterable $questions): void
215
    {
216
        if (!$this->settings['faq']['addSchmemaOrgHeader']) {
217
            return;
218
        }
219
        
220
        $additionalHeaderData = '
221
        <script type="application/ld+json">
222
        {
223
            "@context": "http://schema.org",
224
            "@type": "FAQPage",
225
            "mainEntity": [';
226
        foreach ($questions as $question) {
227
            $additionalHeaderData .= \str_replace([
228
                'QUESTION_TEXT',
229
                'CREATED',
230
                'ANSWER_TEXT',
231
            ],
232
                [
233
                    $question->getTitle(),
234
                    $question->getCrdate()->format('Y-m-d H:i:s'),
235
                    $question->getAnswer(),
236
                ],
237
                '{
238
                "@type": "Question",
239
                "name": "QUESTION_TEXT",
240
                "dateCreated": "CREATED",
241
                "acceptedAnswer": {
242
                    "@type": "answer",
243
                    "text": "ANSWER_TEXT",
244
                    "dateCreated": "CREATED"
245
                }
246
            },');
247
        }
248
        $additionalHeaderData = \substr($additionalHeaderData, 0, -1);
249
        $additionalHeaderData .= '
250
            ]
251
        }
252
        </script>';
253
        $this->response->addAdditionalHeaderData($additionalHeaderData);
254
    }
255
}
256