Completed
Push — cleanup-service ( 407da3...1eee72 )
by Romain
02:14
created

Core::getFullExtensionConfiguration()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 0
1
<?php
2
/*
3
 * 2017 Romain CANON <[email protected]>
4
 *
5
 * This file is part of the TYPO3 Formz project.
6
 * It is free software; you can redistribute it and/or modify it
7
 * under the terms of the GNU General Public License, either
8
 * version 3 of the License, or any later version.
9
 *
10
 * For the full copyright and license information, see:
11
 * http://www.gnu.org/licenses/gpl-3.0.html
12
 */
13
14
namespace Romm\Formz\Core;
15
16
use Romm\Formz\Error\FormzMessageInterface;
17
use Romm\Formz\Service\TypoScriptService;
18
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
19
use TYPO3\CMS\Core\SingletonInterface;
20
use TYPO3\CMS\Core\Utility\ArrayUtility;
21
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Core\Utility\PathUtility;
24
use TYPO3\CMS\Extbase\Error\Message;
25
use TYPO3\CMS\Extbase\Object\ObjectManager;
26
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
27
use TYPO3\CMS\Extbase\Service\EnvironmentService;
28
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
29
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
30
31
/**
32
 * Class containing general functions.
33
 */
34
class Core implements SingletonInterface
35
{
36
    const EXTENSION_KEY = 'formz';
37
    const GENERATED_FILES_PATH = 'typo3temp/Formz/';
38
39
    /**
40
     * @var Core
41
     */
42
    protected static $instance;
43
44
    /**
45
     * @var ObjectManagerInterface
46
     */
47
    protected $objectManager;
48
49
    /**
50
     * @var TypoScriptService
51
     */
52
    protected $typoScriptService;
53
54
    /**
55
     * @var EnvironmentService
56
     */
57
    protected $environmentService;
58
59
    /**
60
     * Contains the actual language key.
61
     *
62
     * @var string
63
     */
64
    private $languageKey;
65
66
    /**
67
     * @var array
68
     */
69
    private $extensionConfiguration;
70
71
    /**
72
     * @return Core
73
     */
74
    public static function get()
75
    {
76
        if (null === self::$instance) {
77
            /** @var ObjectManager $objectManager */
78
            $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
79
80
            self::$instance = $objectManager->get(self::class);
81
        }
82
83
        return self::$instance;
84
    }
85
86
    /**
87
     * Translation handler. Does the same job as Extbase translation tools,
88
     * expect that if the index to the LLL reference is not found, the index is
89
     * returned (Extbase would have returned an empty string).
90
     *
91
     * @param    string $index        The index to the LLL reference.
92
     * @param    string $extensionKey Key of the extension containing the LLL reference.
93
     * @param    array  $arguments    Arguments passed over to vsprintf.
94
     * @return   string               The translated string.
95
     */
96
    public function translate($index, $extensionKey = null, $arguments = null)
97
    {
98
        $extensionKey = ($extensionKey) ?: self::EXTENSION_KEY;
99
        $result = LocalizationUtility::translate($index, $extensionKey, $arguments);
100
        if ($result === '' && $index !== '') {
101
            $result = $index;
102
        }
103
104
        return $result;
105
    }
106
107
    /**
108
     * Converts an array to a clean JSON string which can be used by JavaScript.
109
     *
110
     * @param array $array
111
     * @return string
112
     */
113
    public function arrayToJavaScriptJson(array $array)
114
    {
115
        return json_encode($array, JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_TAG);
116
    }
117
118
    /**
119
     * Return the wanted extension configuration.
120
     *
121
     * @param string $configurationName
122
     * @return mixed
123
     */
124
    public function getExtensionConfiguration($configurationName)
125
    {
126
        $result = null;
127
        $extensionConfiguration = $this->getFullExtensionConfiguration();
128
129
        if (null === $configurationName) {
130
            $result = $extensionConfiguration;
131
        } elseif (ArrayUtility::isValidPath($extensionConfiguration, $configurationName, '.')) {
132
            $result = ArrayUtility::getValueByPath($extensionConfiguration, $configurationName, '.');
133
        }
134
135
        return $result;
136
    }
137
138
    /**
139
     * @return array
140
     */
141
    protected function getFullExtensionConfiguration()
142
    {
143
        if (null === $this->extensionConfiguration) {
144
            $this->extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::EXTENSION_KEY]);
145
146
            if (false === $this->extensionConfiguration) {
147
                $this->extensionConfiguration = [];
148
            }
149
        }
150
151
        return $this->extensionConfiguration;
152
    }
153
154
    /**
155
     * Function called when clearing TYPO3 caches. It will remove the temporary
156
     * asset files created by Formz.
157
     *
158
     * @param array $parameters
159
     */
160
    public function clearCacheCommand($parameters)
161
    {
162
        if (false === in_array($parameters['cacheCmd'], ['all', 'system'])) {
163
            return;
164
        }
165
166
        $files = glob(GeneralUtility::getFileAbsFileName(self::GENERATED_FILES_PATH . '*'));
167
168
        if (false === $files) {
169
            return;
170
        }
171
172
        foreach ($files as $assetCacheFile) {
173
            unlink($assetCacheFile);
174
        }
175
    }
176
177
    /**
178
     * Returns the current language key.
179
     *
180
     * @return string
181
     */
182
    public function getLanguageKey()
183
    {
184
        if (null === $this->languageKey) {
185
            $this->languageKey = 'default';
186
187
            if ($this->environmentService->isEnvironmentInFrontendMode()) {
188
                $pageController = $this->getPageController();
189
190
                if (isset($pageController->config['config']['language'])) {
191
                    $this->languageKey = $pageController->config['config']['language'];
192
                }
193
            } else {
194
                $backendUser = $this->getBackendUser();
195
196
                if (strlen($backendUser->uc['lang']) > 0) {
197
                    $this->languageKey = $backendUser->uc['lang'];
198
                }
199
            }
200
        }
201
202
        return $this->languageKey;
203
    }
204
205
    /**
206
     * Will check if the TypoScript was indeed included, as it contains required
207
     * configuration to make the forms work properly.
208
     *
209
     * @return bool
210
     */
211
    public function isTypoScriptIncluded()
212
    {
213
        return null !== $this->typoScriptService->getExtensionConfigurationFromPath('settings.typoScriptIncluded');
214
    }
215
216
    /**
217
     * @return bool
218
     */
219
    public function isInDebugMode()
220
    {
221
        return (bool)$this->getExtensionConfiguration('debugMode');
222
    }
223
224
    /**
225
     * @param string|null $path If a string is given, it will be precessed by the extension relative path and returned.
226
     * @return string
227
     */
228
    public function getExtensionRelativePath($path = null)
229
    {
230
        $relativePath = ExtensionManagementUtility::siteRelPath('formz');
231
232
        if ($this->environmentService->isEnvironmentInBackendMode()) {
233
            $relativePath = '../' . $relativePath;
234
        }
235
236
        return (null !== $path)
237
            ? $relativePath . $path
238
            : $relativePath;
239
    }
240
241
    /**
242
     * @param string $path
243
     * @return string
244
     */
245
    public function getResourceRelativePath($path)
246
    {
247
        $relativePath = rtrim(
248
            PathUtility::getRelativePath(
249
                GeneralUtility::getIndpEnv('TYPO3_DOCUMENT_ROOT'),
250
                GeneralUtility::getFileAbsFileName($path)
251
            ),
252
            '/'
253
        );
254
255
        if ($this->environmentService->isEnvironmentInBackendMode()) {
256
            $relativePath = '../' . $relativePath;
257
        }
258
259
        return $relativePath;
260
    }
261
262
    /**
263
     * Sanitizes a string: lower case with dash separation.
264
     *
265
     * @param string $string
266
     * @return string
267
     */
268
    public function sanitizeString($string)
269
    {
270
        $string = str_replace('_', '-', GeneralUtility::camelCaseToLowerCaseUnderscored($string));
271
272
        while (strpos($string, '--')) {
273
            $string = str_replace('--', '-', $string);
274
        }
275
276
        return $string;
277
    }
278
279
    /**
280
     * Returns the validation name of a message: if it is an instance of
281
     * `FormzMessageInterface`, we can fetch it, otherwise `unknown` is
282
     * returned.
283
     *
284
     * @param Message $message
285
     * @return string
286
     */
287
    public function getMessageValidationName(Message $message)
288
    {
289
        return ($message instanceof FormzMessageInterface)
290
            ? $message->getValidationName()
291
            : 'unknown';
292
    }
293
294
    /**
295
     * Returns the key of a message: if it is an instance of
296
     * `FormzMessageInterface`, we can fetch it, otherwise `unknown` is
297
     * returned.
298
     *
299
     * @param Message $message
300
     * @return string
301
     */
302
    public function getMessageKey(Message $message)
303
    {
304
        return ($message instanceof FormzMessageInterface)
305
            ? $message->getMessageKey()
306
            : 'unknown';
307
    }
308
309
    /**
310
     * Returns a unique hash for the context of the current request, depending
311
     * on whether the request comes from frontend or backend.
312
     *
313
     * @return string
314
     */
315
    public function getContextHash()
316
    {
317
        return ($this->environmentService->isEnvironmentInFrontendMode())
318
            ? 'fe-' . $this->getPageController()->id
319
            : 'be-' . $this->sanitizeString(GeneralUtility::_GET('M'));
320
    }
321
322
    /**
323
     * Shortcut for object manager `get()` function.
324
     *
325
     * @param string $className
326
     * @return object
327
     */
328
    public static function instantiate($className)
329
    {
330
        $objectManager = self::get()->getObjectManager();
331
332
        return call_user_func_array([$objectManager, 'get'], func_get_args());
333
    }
334
335
    /**
336
     * @return ObjectManagerInterface
337
     */
338
    public function getObjectManager()
339
    {
340
        return $this->objectManager;
341
    }
342
343
    /**
344
     * @param ObjectManagerInterface $objectManager
345
     */
346
    public function injectObjectManager(ObjectManagerInterface $objectManager)
347
    {
348
        $this->objectManager = $objectManager;
349
    }
350
351
    /**
352
     * @param TypoScriptService $typoScriptService
353
     */
354
    public function injectTypoScriptService(TypoScriptService $typoScriptService)
355
    {
356
        $this->typoScriptService = $typoScriptService;
357
    }
358
359
    /**
360
     * @param EnvironmentService $environmentService
361
     */
362
    public function injectEnvironmentService(EnvironmentService $environmentService)
363
    {
364
        $this->environmentService = $environmentService;
365
    }
366
367
    /**
368
     * Returns the extension key.
369
     *
370
     * @return string
371
     */
372
    public function getExtensionKey()
373
    {
374
        return self::EXTENSION_KEY;
375
    }
376
377
    /**
378
     * @return TypoScriptFrontendController
379
     */
380
    public function getPageController()
381
    {
382
        return $GLOBALS['TSFE'];
383
    }
384
385
    /**
386
     * @return BackendUserAuthentication
387
     */
388
    public function getBackendUser()
389
    {
390
        return $GLOBALS['BE_USER'];
391
    }
392
}
393