Completed
Branch unit-test-view-helpers (44bfe0)
by Romain
02:02
created

Core::getMessageKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
/*
3
 * 2016 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\Configuration\ConfigurationFactory;
17
use Romm\Formz\Error\FormzMessageInterface;
18
use Romm\Formz\Form\FormObjectFactory;
19
use Romm\Formz\Utility\TypoScriptUtility;
20
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21
use TYPO3\CMS\Core\Cache\Backend\AbstractBackend;
22
use TYPO3\CMS\Core\Cache\CacheManager;
23
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
24
use TYPO3\CMS\Core\SingletonInterface;
25
use TYPO3\CMS\Core\Utility\ArrayUtility;
26
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
27
use TYPO3\CMS\Core\Utility\GeneralUtility;
28
use TYPO3\CMS\Core\Utility\MathUtility;
29
use TYPO3\CMS\Core\Utility\PathUtility;
30
use TYPO3\CMS\Extbase\Error\Message;
31
use TYPO3\CMS\Extbase\Object\ObjectManager;
32
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
33
use TYPO3\CMS\Extbase\Service\EnvironmentService;
34
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
35
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
36
37
/**
38
 * Class containing general functions.
39
 */
40
class Core implements SingletonInterface
41
{
42
    const EXTENSION_KEY = 'formz';
43
    const CACHE_IDENTIFIER = 'cache_formz';
44
    const GENERATED_FILES_PATH = 'typo3temp/Formz/';
45
46
    /**
47
     * @var Core
48
     */
49
    protected static $instance;
50
51
    /**
52
     * @var int|null
53
     */
54
    private $currentPageUid = -1;
55
56
    /**
57
     * @var ObjectManagerInterface
58
     */
59
    private $objectManager;
60
61
    /**
62
     * @var TypoScriptUtility
63
     */
64
    private $typoScriptUtility;
65
66
    /**
67
     * @var ConfigurationFactory
68
     */
69
    private $configurationFactory;
70
71
    /**
72
     * @var FormObjectFactory
73
     */
74
    private $formObjectFactory;
75
76
    /**
77
     * Contains the actual language key.
78
     *
79
     * @var string
80
     */
81
    private $languageKey;
82
83
    /**
84
     * @var array
85
     */
86
    private $extensionConfiguration;
87
88
    /**
89
     * @var FrontendInterface
90
     */
91
    protected $cacheInstance;
92
93
    /**
94
     * @return Core
95
     */
96
    public static function get()
97
    {
98
        if (null === self::$instance) {
99
            /** @var ObjectManager $objectManager */
100
            $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
101
102
            self::$instance = $objectManager->get(self::class);
103
        }
104
105
        return self::$instance;
106
    }
107
108
    /**
109
     * Translation handler. Does the same job as Extbase translation tools,
110
     * expect that if the index to the LLL reference is not found, the index is
111
     * returned (Extbase would have returned an empty string).
112
     *
113
     * @param    string $index        The index to the LLL reference.
114
     * @param    string $extensionKey Key of the extension containing the LLL reference.
115
     * @param    array  $arguments    Arguments passed over to vsprintf.
116
     * @return   string               The translated string.
117
     */
118
    public function translate($index, $extensionKey = null, $arguments = null)
119
    {
120
        $extensionKey = ($extensionKey) ?: self::EXTENSION_KEY;
121
        $result = LocalizationUtility::translate($index, $extensionKey, $arguments);
122
        if ($result === '' && $index !== '') {
123
            $result = $index;
124
        }
125
126
        return $result;
127
    }
128
129
    /**
130
     * Converts an array to a clean JSON string which can be used by JavaScript.
131
     *
132
     * @param array $array
133
     * @return string
134
     */
135
    public function arrayToJavaScriptJson(array $array)
136
    {
137
        return json_encode($array, JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_TAG);
138
    }
139
140
    /**
141
     * Returns the type of backend cache defined in TypoScript at the path:
142
     * `settings.defaultBackendCache`.
143
     *
144
     * @return string
145
     * @throws \Exception
146
     */
147
    public function getBackendCache()
148
    {
149
        $backendCache = $this->getTypoScriptUtility()
150
            ->getExtensionConfigurationFromPath('settings.defaultBackendCache');
151
152
        if (false === class_exists($backendCache)
153
            && false === in_array(AbstractBackend::class, class_parents($backendCache))
154
        ) {
155
            throw new \Exception(
156
                'The cache class name given in configuration "config.tx_formz.settings.defaultBackendCache" must inherit "' . AbstractBackend::class . '" (current value: "' . (string)$backendCache . '")',
157
                1459251263
158
            );
159
        }
160
161
        return $backendCache;
162
    }
163
164
    /**
165
     * Returns the current page uid, in a frontend or backend context.
166
     *
167
     * Returns null if the uid can't be found (backend module, ajax call, etc.).
168
     *
169
     * @return int|null
170
     */
171
    public function getCurrentPageUid()
172
    {
173
        if (-1 === $this->currentPageUid) {
174
            /** @var EnvironmentService $environmentService */
175
            $environmentService = GeneralUtility::makeInstance(EnvironmentService::class);
176
177
            $id = ($environmentService->isEnvironmentInFrontendMode())
178
                ? $this->getPageController()->id
179
                : GeneralUtility::_GP('id');
180
181
            if (false === MathUtility::canBeInterpretedAsInteger($id)
182
                || intval($id) < 0
183
            ) {
184
                $id = null;
185
            }
186
187
            $this->currentPageUid = $id;
188
        }
189
190
        return $this->currentPageUid;
191
    }
192
193
    /**
194
     * Allows you to set manually the current page uid. Useful when editing a
195
     * record, for example.
196
     *
197
     * @param int $uid The uid of the page.
198
     */
199
    public function setCurrentPageUid($uid)
200
    {
201
        $this->currentPageUid = intval($uid);
202
    }
203
204
    /**
205
     * Returns the cache instance for this extension.
206
     *
207
     * @return FrontendInterface
208
     */
209
    public function getCacheInstance()
210
    {
211
        if (null === $this->cacheInstance) {
212
            /** @var $cacheManager CacheManager */
213
            $cacheManager = $this->getObjectManager()->get(CacheManager::class);
214
215
            if ($cacheManager->hasCache(self::CACHE_IDENTIFIER)) {
216
                $this->cacheInstance = $cacheManager->getCache(self::CACHE_IDENTIFIER);
217
            }
218
        }
219
220
        return $this->cacheInstance;
221
    }
222
223
    /**
224
     * @param FrontendInterface $cacheInstance
225
     */
226
    public function setCacheInstance(FrontendInterface $cacheInstance)
227
    {
228
        $this->cacheInstance = $cacheInstance;
229
    }
230
231
    /**
232
     * Generic cache identifier creation for usages in the extension.
233
     *
234
     * @param string $string
235
     * @param string $formClassName
236
     * @param int    $maxLength
237
     * @return string
238
     */
239
    public function getCacheIdentifier($string, $formClassName, $maxLength = 55)
240
    {
241
        $explodedClassName = explode('\\', $formClassName);
242
243
        $identifier = strtolower(
244
            $string .
245
            end($explodedClassName) .
246
            '-' .
247
            sha1($formClassName)
248
        );
249
250
        return substr($identifier, 0, $maxLength);
251
    }
252
253
    /**
254
     * Return the wanted extension configuration.
255
     *
256
     * @param string $configurationName
257
     * @return mixed
258
     */
259
    public function getExtensionConfiguration($configurationName)
260
    {
261
        $result = null;
262
        $extensionConfiguration = $this->getFullExtensionConfiguration();
263
264
        if (null === $configurationName) {
265
            $result = $extensionConfiguration;
266
        } elseif (ArrayUtility::isValidPath($extensionConfiguration, $configurationName, '.')) {
267
            $result = ArrayUtility::getValueByPath($extensionConfiguration, $configurationName, '.');
268
        }
269
270
        return $result;
271
    }
272
273
    /**
274
     * @return array
275
     */
276
    protected function getFullExtensionConfiguration()
277
    {
278
        if (null === $this->extensionConfiguration) {
279
            $this->extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::EXTENSION_KEY]);
280
281
            if (false === $this->extensionConfiguration) {
282
                $this->extensionConfiguration = [];
283
            }
284
        }
285
286
        return $this->extensionConfiguration;
287
    }
288
289
    /**
290
     * Function called when clearing TYPO3 caches. It will remove the temporary
291
     * asset files created by Formz.
292
     *
293
     * @param array $parameters
294
     */
295
    public function clearCacheCommand($parameters)
296
    {
297
        if (false === in_array($parameters['cacheCmd'], ['all', 'system'])) {
298
            return;
299
        }
300
301
        $files = glob(GeneralUtility::getFileAbsFileName(self::GENERATED_FILES_PATH . '*'));
302
303
        if (false === $files) {
304
            return;
305
        }
306
307
        foreach ($files as $assetCacheFile) {
308
            unlink($assetCacheFile);
309
        }
310
    }
311
312
    /**
313
     * Returns the current language key.
314
     *
315
     * @return string
316
     */
317
    public function getLanguageKey()
318
    {
319
        if (null === $this->languageKey) {
320
            $this->languageKey = 'default';
321
322
            /** @var EnvironmentService $environmentService */
323
            $environmentService = GeneralUtility::makeInstance(EnvironmentService::class);
324
325
            if ($environmentService->isEnvironmentInFrontendMode()) {
326
                $pageController = $this->getPageController();
327
328
                if (isset($pageController->config['config']['language'])) {
329
                    $this->languageKey = $pageController->config['config']['language'];
330
                }
331
            } else {
332
                $backendUser = $this->getBackendUser();
333
334
                if (strlen($backendUser->uc['lang']) > 0) {
335
                    $this->languageKey = $backendUser->uc['lang'];
336
                }
337
            }
338
        }
339
340
        return $this->languageKey;
341
    }
342
343
    /**
344
     * Will check if the TypoScript was indeed included, as it contains required
345
     * configuration to make the forms work properly.
346
     *
347
     * @return bool
348
     */
349
    public function isTypoScriptIncluded()
350
    {
351
        return null !== $this->getTypoScriptUtility()->getExtensionConfigurationFromPath('settings.typoScriptIncluded');
352
    }
353
354
    /**
355
     * @return bool
356
     */
357
    public function isInDebugMode()
358
    {
359
        return (bool)$this->getExtensionConfiguration('debugMode');
360
    }
361
362
    /**
363
     * @param string|null $path If a string is given, it will be precessed by the extension relative path and returned.
364
     * @return string
365
     */
366
    public function getExtensionRelativePath($path = null)
367
    {
368
        $relativePath = ExtensionManagementUtility::siteRelPath('formz');
369
370
        return (null !== $path)
371
            ? $relativePath . $path
372
            : $relativePath;
373
    }
374
375
    /**
376
     * @param string $path
377
     * @return string
378
     */
379
    public function getResourceRelativePath($path)
380
    {
381
        return rtrim(
382
            PathUtility::getRelativePath(
383
                GeneralUtility::getIndpEnv('TYPO3_DOCUMENT_ROOT'),
384
                GeneralUtility::getFileAbsFileName($path)
385
            ),
386
            '/'
387
        );
388
    }
389
390
    /**
391
     * Returns the validation name of a message: if it is an instance of
392
     * `FormzMessageInterface`, we can fetch it, otherwise `unknown` is
393
     * returned.
394
     *
395
     * @param Message $message
396
     * @return string
397
     */
398
    public function getMessageValidationName(Message $message)
399
    {
400
        return ($message instanceof FormzMessageInterface)
401
            ? $message->getValidationName()
402
            : 'unknown';
403
    }
404
405
    /**
406
     * Returns the key of a message: if it is an instance of
407
     * `FormzMessageInterface`, we can fetch it, otherwise `unknown` is
408
     * returned.
409
     *
410
     * @param Message $message
411
     * @return string
412
     */
413
    public function getMessageKey(Message $message)
414
    {
415
        return ($message instanceof FormzMessageInterface)
416
            ? $message->getMessageKey()
417
            : 'unknown';
418
    }
419
420
    /**
421
     * @return ObjectManagerInterface
422
     */
423
    public function getObjectManager()
424
    {
425
        return $this->objectManager;
426
    }
427
428
    /**
429
     * @param ObjectManagerInterface $objectManager
430
     */
431
    public function injectObjectManager(ObjectManagerInterface $objectManager)
432
    {
433
        $this->objectManager = $objectManager;
434
    }
435
436
    /**
437
     * @return TypoScriptUtility
438
     */
439
    public function getTypoScriptUtility()
440
    {
441
        return $this->typoScriptUtility;
442
    }
443
444
    /**
445
     * @param TypoScriptUtility $typoScriptUtility
446
     */
447
    public function injectTypoScriptUtility(TypoScriptUtility $typoScriptUtility)
448
    {
449
        $this->typoScriptUtility = $typoScriptUtility;
450
    }
451
452
    /**
453
     * @return ConfigurationFactory
454
     */
455
    public function getConfigurationFactory()
456
    {
457
        return $this->configurationFactory;
458
    }
459
460
    /**
461
     * @param ConfigurationFactory $configurationFactory
462
     */
463
    public function injectConfigurationFactory(ConfigurationFactory $configurationFactory)
464
    {
465
        $this->configurationFactory = $configurationFactory;
466
    }
467
468
    /**
469
     * @return FormObjectFactory
470
     */
471
    public function getFormObjectFactory()
472
    {
473
        return $this->formObjectFactory;
474
    }
475
476
    /**
477
     * @param FormObjectFactory $formObjectFactory
478
     */
479
    public function injectFormObjectFactory(FormObjectFactory $formObjectFactory)
480
    {
481
        $this->formObjectFactory = $formObjectFactory;
482
    }
483
484
    /**
485
     * Returns the extension key.
486
     *
487
     * @return string
488
     */
489
    public function getExtensionKey()
490
    {
491
        return self::EXTENSION_KEY;
492
    }
493
494
    /**
495
     * @return TypoScriptFrontendController
496
     */
497
    public function getPageController()
498
    {
499
        return $GLOBALS['TSFE'];
500
    }
501
502
    /**
503
     * @return BackendUserAuthentication
504
     */
505
    public function getBackendUser()
506
    {
507
        return $GLOBALS['BE_USER'];
508
    }
509
}
510