Completed
Pull Request — master (#15)
by
unknown
02:10
created

Core::getBackendCache()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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