8752cb288a0dd1b45867aedd960b62428cffeff6
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Messaging / FlashMessageRendererResolver.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Core\Messaging;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use TYPO3\CMS\Core\Messaging\Renderer\FlashMessageRendererInterface;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * A class for rendering flash messages.
23 */
24 class FlashMessageRendererResolver
25 {
26 /**
27 * @var array
28 */
29 protected $renderer = [
30 'BE' => Renderer\BootstrapRenderer::class,
31 'FE' => Renderer\ListRenderer::class,
32 'CLI' => Renderer\PlaintextRenderer::class,
33 '_default' => Renderer\PlaintextRenderer::class,
34 ];
35
36 /**
37 * This method resolves a FlashMessageRendererInterface for the given $context.
38 *
39 * In case $context is null, the context will be detected automatic.
40 *
41 * @return FlashMessageRendererInterface
42 */
43 public function resolve(): FlashMessageRendererInterface
44 {
45 $rendererClass = $this->resolveFlashMessageRenderClass();
46 $renderer = GeneralUtility::makeInstance($rendererClass);
47 if (!$renderer instanceof FlashMessageRendererInterface) {
48 throw new \RuntimeException('Renderer ' . get_class($renderer)
49 . ' does not implement FlashMessageRendererInterface', 1476958086);
50 }
51 return $renderer;
52 }
53
54 /**
55 * This method resolves the renderer class by given context.
56 *
57 * @return string
58 */
59 protected function resolveFlashMessageRenderClass(): string
60 {
61 $context = $this->resolveContext();
62 $renderClass = $this->renderer['_default'];
63
64 if (!empty($this->renderer[$context])) {
65 $renderClass = $this->renderer[$context];
66 }
67
68 return $renderClass;
69 }
70
71 /**
72 * This method detect the current context and return one of the
73 * following strings:
74 * - FE
75 * - BE
76 * - CLI
77 *
78 * @return string
79 */
80 protected function resolveContext(): string
81 {
82 $context = '';
83 if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
84 $context = 'CLI';
85 } elseif (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_BE) {
86 $context = 'BE';
87 } elseif (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_FE) {
88 $context = 'FE';
89 }
90 return $context;
91 }
92 }