Completed
Push — unit-test-view-helpers ( d3d368...2e4ad4 )
by Romain
02:57
created

Core::injectEnvironmentService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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