Completed
Push — develop ( e654c4...c5af05 )
by Neomerx
01:44
created

Application::createApplicationConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 0
cts 0
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 0
crap 2
1
<?php namespace Limoncello\Application\Packages\Application;
2
3
/**
4
 * Copyright 2015-2017 [email protected]
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
use Limoncello\Application\CoreSettings\CoreData;
20
use Limoncello\Application\Settings\CacheSettingsProvider;
21
use Limoncello\Application\Settings\FileSettingsProvider;
22
use Limoncello\Application\Settings\InstanceSettingsProvider;
23
use Limoncello\Container\Container;
24
use Limoncello\Contracts\Application\ApplicationConfigurationInterface as A;
25
use Limoncello\Contracts\Application\CacheSettingsProviderInterface;
26
use Limoncello\Contracts\Container\ContainerInterface as LimoncelloContainerInterface;
27
use Limoncello\Contracts\Core\SapiInterface;
28
use Limoncello\Contracts\Provider\ProvidesSettingsInterface;
29
use Limoncello\Contracts\Settings\SettingsProviderInterface;
30
use Limoncello\Core\Application\Sapi;
31
use Limoncello\Core\Reflection\ClassIsTrait;
32
use Zend\Diactoros\Response\SapiEmitter;
33
34
/**
35
 * @package Limoncello\Application
36
 *
37
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
38
 */
39
class Application extends \Limoncello\Core\Application\Application
0 ignored issues
show
Bug introduced by
There is one abstract method createSettingsProvider in this class; you could implement it, or declare this class as abstract.
Loading history...
40
{
41
    use ClassIsTrait;
42
43
    /**
44
     * @var string
45
     */
46
    private $settingsPath;
47
48
    /**
49
     * @var callable|string|null
50
     */
51
    private $settingCacheMethod;
52
53
    /**
54
     * @var CacheSettingsProviderInterface|null
55
     */
56
    private $cacheSettingsProvider = null;
57
58
    /**
59 2
     * @param string                     $settingsPath
60
     * @param string|array|callable|null $settingCacheMethod
61
     * @param SapiInterface|null         $sapi
62
     */
63
    public function __construct(string $settingsPath, $settingCacheMethod = null, SapiInterface $sapi = null)
64 2
    {
65
        // The reason we do not use `callable` for the input parameter is that at the moment
66 2
        // of calling the callable might not exist. Therefore when created it will pass
67 2
        // `is_callable` check and will be used for getting the cached data.
68
        assert(is_null($settingCacheMethod) || is_string($settingCacheMethod) || is_array($settingCacheMethod));
69 2
70
        $this->settingsPath       = $settingsPath;
71
        $this->settingCacheMethod = $settingCacheMethod;
72
73
        $this->setSapi($sapi ?? new Sapi(new SapiEmitter()));
74
    }
75
76
    /**
77
     * @inheritdoc
78
     */
79
    protected function getCoreData(): array
80
    {
81
        return $this->getCacheSettingsProvider()->getCoreData();
82
    }
83 2
84
    /**
85 2
     * Get container from application. If `method` and `path` are specified the container will be configured
86
     * not only with global container configurators but with route's one as well.
87 2
     *
88 2
     * @param string|null $method
89 2
     * @param string|null $path
90
     *
91 2
     * @return LimoncelloContainerInterface
92
     *
93 2
     * @SuppressWarnings(PHPMD.StaticAccess)
94 2
     */
95 2
    public function createContainer(string $method = null, string $path = null): LimoncelloContainerInterface
96
    {
97
        $container = $this->createContainerInstance();
98
99 2
        $settingsProvider = $this->getCacheSettingsProvider();
100 2
        $container->offsetSet(SettingsProviderInterface::class, $settingsProvider);
101
        $container->offsetSet(CacheSettingsProviderInterface::class, $settingsProvider);
102 2
103
        $routeConfigurators = [];
104
        $coreData           = $this->getCoreData();
105
        if (empty($method) === false && empty($path) === false) {
106
            list(, , , , , $routeConfigurators) = $this->initRouter($coreData)->match($method, $path);
107
        }
108
109
        // configure container
110 2
        assert(!empty($coreData));
111
        $globalConfigurators = CoreData::getGlobalConfiguratorsFromData($coreData);
112 2
        $this->configureContainer($container, $globalConfigurators, $routeConfigurators);
113 2
114 1
        return $container;
115 1
    }
116
117 1
    /**
118
     * @return LimoncelloContainerInterface
119
     */
120 2
    protected function createContainerInstance(): LimoncelloContainerInterface
121
    {
122
        return new Container();
123
    }
124
125
    /**
126 1
     * @return string
127
     */
128
    protected function getSettingsPath(): string
129 1
    {
130
        return $this->settingsPath;
131
    }
132 1
133 1
    /**
134 1
     * @return callable|string|null
135
     */
136 1
    protected function getSettingCacheMethod()
137 1
    {
138
        return $this->settingCacheMethod;
139
    }
140
141
    /**
142 1
     * @return CacheSettingsProviderInterface
143 1
     */
144 1
    private function getCacheSettingsProvider(): CacheSettingsProviderInterface
145
    {
146 1
        if ($this->cacheSettingsProvider === null) {
147
            $provider = new CacheSettingsProvider();
148 1
149
            if (is_callable($method = $this->getSettingCacheMethod()) === true) {
150
                $data = call_user_func($method);
151
                $provider->unserialize($data);
152
            } else {
153
                $appConfig = $this->createApplicationConfiguration();
154 2
                $appData   = $appConfig->get();
155
                $coreData  = new CoreData(
156 2
                    $appData[A::KEY_ROUTES_PATH],
157
                    $appData[A::KEY_CONTAINER_CONFIGURATORS_PATH],
158
                    $appData[A::KEY_PROVIDER_CLASSES]
159
                );
160
161
                $provider->setInstanceSettings($appConfig, $coreData, $this->createInstanceSettingsProvider($appData));
162 1
            }
163
164 1
            $this->cacheSettingsProvider = $provider;
165
        }
166
167
        return $this->cacheSettingsProvider;
168
    }
169
170 2
    /**
171
     * @return A
172 2
     */
173
    private function createApplicationConfiguration(): A
174
    {
175
        $classes = iterator_to_array(static::selectClasses($this->getSettingsPath(), A::class));
176
        assert(
177
            count($classes) > 0,
178
            'Settings path must contain a class implementing ApplicationConfigurationInterface.'
179
        );
180
        assert(
181
            count($classes) === 1,
182
            'Settings path must contain only one class implementing ApplicationConfigurationInterface.'
183
        );
184
        $class    = reset($classes);
185
        $instance = new $class();
186
        assert($instance instanceof A);
0 ignored issues
show
Bug introduced by
The class Limoncello\Contracts\App...nConfigurationInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
187
188
        return $instance;
189
    }
190
191
    /**
192
     * @param array $applicationData
193
     *
194
     * @return InstanceSettingsProvider
195
     */
196
    private function createInstanceSettingsProvider(array $applicationData): InstanceSettingsProvider
197
    {
198
        // Load all settings from path specified
199
        $provider = (new FileSettingsProvider($applicationData))->load($this->getSettingsPath());
200
201
        // Application settings have a list of providers which might have additional settings to load
202
        $providerClasses = $applicationData[A::KEY_PROVIDER_CLASSES];
203
        $selectedClasses = $this->selectClassImplements($providerClasses, ProvidesSettingsInterface::class);
204
        foreach ($selectedClasses as $providerClass) {
205
            /** @var ProvidesSettingsInterface $providerClass */
206
            foreach ($providerClass::getSettings() as $setting) {
207
                $provider->register($setting);
208
            }
209
        }
210
211
        return $provider;
212
    }
213
}
214