Completed
Push — unit-test-view-helpers ( 05e77a...3ce587 )
by Romain
02:05
created

ConditionProcessorFactory::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
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\Condition\Processor;
15
16
use Romm\Formz\Core\Core;
17
use Romm\Formz\Form\FormObject;
18
use Romm\Formz\Service\CacheService;
19
use Romm\Formz\Service\Traits\ExtendedFacadeInstanceTrait;
20
use TYPO3\CMS\Core\SingletonInterface;
21
22
class ConditionProcessorFactory implements SingletonInterface
23
{
24
    use ExtendedFacadeInstanceTrait {
25
        get as getInstance;
26
    }
27
28
    /**
29
     * @var ConditionProcessor[]
30
     */
31
    private $processorInstances = [];
32
33
    /**
34
     * @param FormObject $formObject
35
     * @return ConditionProcessor
36
     */
37
    public function get(FormObject $formObject)
38
    {
39
        $cacheIdentifier = 'condition-processor-' . $formObject->getHash();
40
41
        if (false === array_key_exists($cacheIdentifier, $this->processorInstances)) {
42
            $this->processorInstances[$cacheIdentifier] = $this->getProcessorInstance($cacheIdentifier, $formObject);
43
        }
44
45
        return $this->processorInstances[$cacheIdentifier];
46
    }
47
48
    /**
49
     * Will either fetch the processor instance from cache, using the given
50
     * identifier, or calculate it and store it in cache.
51
     *
52
     * @param string     $cacheIdentifier
53
     * @param FormObject $formObject
54
     * @return ConditionProcessor
55
     */
56
    protected function getProcessorInstance($cacheIdentifier, FormObject $formObject)
57
    {
58
        $cacheInstance = CacheService::get()->getCacheInstance();
59
60
        /** @var ConditionProcessor $instance */
61
        if ($cacheInstance->has($cacheIdentifier)) {
62
            $instance = $cacheInstance->get($cacheIdentifier);
63
        } else {
64
            $instance = Core::instantiate(ConditionProcessor::class, $formObject);
65
            $instance->calculateAllTrees();
66
            $instance->attachFormObject($formObject);
67
68
            $cacheInstance->set($cacheIdentifier, $instance);
69
        }
70
71
        return $instance;
72
    }
73
}
74