Completed
Push — feature/aggregation-params ( b242d2...331dde )
by Narcotic
11:59
created

ServiceManager::getServiceParameters()   D

Complexity

Conditions 10
Paths 8

Size

Total Lines 41
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 0
cts 34
cp 0
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 24
nc 8
nop 1
crap 110

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * ParamConverter class for entry point to Analytics Bundle
4
 */
5
6
namespace Graviton\AnalyticsBundle\Manager;
7
8
use Graviton\AnalyticsBundle\Helper\JsonMapper;
9
use Graviton\AnalyticsBundle\Model\AnalyticModel;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\Finder\Finder;
12
use Doctrine\Common\Cache\CacheProvider;
13
use Symfony\Component\HttpFoundation\RequestStack;
14
use Symfony\Component\Routing\Router;
15
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
16
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
17
18
/**
19
 * Service Request Converter and startup for Analytics
20
 *
21
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
22
 * @license  https://opensource.org/licenses/MIT MIT License
23
 * @link     http://swisscom.ch
24
 */
25
class ServiceManager
26
{
27
    /** Cache name for services */
28
    const CACHE_KEY_SERVICES = 'analytics_services';
29
    const CACHE_KEY_SERVICES_TIME = 10;
30
    const CACHE_KEY_SERVICES_URLS = 'analytics_services_urls';
31
    const CACHE_KEY_SERVICES_URLS_TIME = 10;
32
    const CACHE_KEY_SERVICES_PREFIX = 'analytics_';
33
34
    /** @var RequestStack */
35
    protected $requestStack;
36
37
    /** @var AnalyticsManager */
38
    protected $analyticsManager;
39
40
    /** @var CacheProvider */
41
    protected $cacheProvider;
42
43
    /** @var Router */
44
    protected $router;
45
46
    /** @var string */
47
    protected $directory;
48
49
    /**
50
     * ServiceConverter constructor.
51
     * @param RequestStack     $requestStack        Sf Request information service
52
     * @param AnalyticsManager $analyticsManager    Db Manager and query control
53
     * @param CacheProvider    $cacheProvider       Cache service
54
     * @param Router           $router              To manage routing generation
55
     * @param string           $definitionDirectory Where definitions are stored
56
     */
57
    public function __construct(
58
        RequestStack $requestStack,
59
        AnalyticsManager $analyticsManager,
60
        CacheProvider $cacheProvider,
61
        Router $router,
62
        $definitionDirectory
63
    ) {
64
        $this->requestStack = $requestStack;
65
        $this->analyticsManager = $analyticsManager;
66
        $this->cacheProvider = $cacheProvider;
67
        $this->router = $router;
68
        $this->directory = $definitionDirectory;
69
    }
70
71
    /**
72
     * Scan base root directory for analytic definitions
73
     * @return array
74
     */
75
    private function getDirectoryServices()
76
    {
77
        $services = $this->cacheProvider->fetch(self::CACHE_KEY_SERVICES);
78
79
        if (is_array($services)) {
80
            return $services;
81
        }
82
83
        $services = [];
84
        if (strpos($this->directory, 'vendor/graviton/graviton')) {
85
            $this->directory = str_replace('vendor/graviton/graviton/', '', $this->directory);
86
        }
87
        if (!is_dir($this->directory)) {
88
            return $services;
89
        }
90
91
        $finder = new Finder();
92
        $finder
93
            ->files()
94
            ->in($this->directory)
95
            ->path('/\/analytics\//i')
96
            ->name('*.json')
97
            ->notName('_*')
98
            ->sortByName();
99
100
        foreach ($finder as $file) {
101
            $key = $file->getFilename();
102
            $data = json_decode($file->getContents());
103
            if (json_last_error()) {
104
                throw new InvalidConfigurationException(
105
                    sprintf('Analytics file: %s could not be loaded due to error: ', $key, json_last_error_msg())
106
                );
107
            }
108
            $services[$data->route] = $data;
109
        }
110
111
        $this->cacheProvider->save(self::CACHE_KEY_SERVICES, $services, self::CACHE_KEY_SERVICES_TIME);
112
        return $services;
113
    }
114
115
    /**
116
     * Return array of available services
117
     *
118
     * @return array
119
     */
120
    public function getServices()
121
    {
122
        $services = $this->cacheProvider->fetch(self::CACHE_KEY_SERVICES_URLS);
123
        if (is_array($services)) {
124
            return $services;
125
        }
126
        $services = [];
127
        foreach ($this->getDirectoryServices() as $name => $service) {
128
            $services[] = [
129
                '$ref' => $this->router->generate(
130
                    'graviton_analytics_service',
131
                    [
132
                        'service' => $service->route
133
                    ],
134
                    false
135
                ),
136
                'profile' => $this->router->generate(
137
                    'graviton_analytics_service_schema',
138
                    [
139
                        'service' => $service->route
140
                    ],
141
                    true
142
                )
143
            ];
144
        }
145
        $this->cacheProvider->save(
146
            self::CACHE_KEY_SERVICES_URLS,
147
            $services,
148
            self::CACHE_KEY_SERVICES_URLS_TIME
149
        );
150
        return $services;
151
    }
152
153
    /**
154
     * Get service definition
155
     *
156
     * @param string $name Route name for service
157
     * @throws NotFoundHttpException
158
     * @return AnalyticModel
159
     */
160
    private function getServiceSchemaByRoute($name)
161
    {
162
        $services = $this->getDirectoryServices();
163
        // Locate the schema definition
164
        if (!array_key_exists($name, $services)) {
165
            throw new NotFoundHttpException(
166
                sprintf('Service Analytics for %s was not found', $name)
167
            );
168
        }
169
        $mapper = new JsonMapper();
170
        /** @var AnalyticModel $schema */
171
        $schema = $mapper->map($services[$name], new AnalyticModel());
172
        return $schema;
173
    }
174
175
    /**
176
     * Will map and find data for defined route
177
     *
178
     * @return array
179
     */
180
    public function getData()
181
    {
182
        $serviceRoute = $this->requestStack->getCurrentRequest()->get('service');
183
184
        // Locate the schema definition
185
        $schema = $this->getServiceSchemaByRoute($serviceRoute);
186
        $cacheTime = $schema->getCacheTime();
187
188
        // check parameters
189
190
        //Cached data if configured
191
        if ($cacheTime &&
192
            $cache = $this->cacheProvider->fetch(self::CACHE_KEY_SERVICES_PREFIX.$schema->getRoute())
193
        ) {
194
            return $cache;
195
        }
196
197
        $data = $this->analyticsManager->getData($schema, $this->getServiceParameters($schema));
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->analyticsManager-...ceParameters($schema)); of type array|object adds the type object to the return on line 203 which is incompatible with the return type documented by Graviton\AnalyticsBundle...ServiceManager::getData of type array.
Loading history...
198
199
        if ($cacheTime) {
200
            $this->cacheProvider->save(self::CACHE_KEY_SERVICES_PREFIX.$schema->getRoute(), $data, $cacheTime);
201
        }
202
203
        return $data;
204
    }
205
206
    /**
207
     * Locate and display service definition schema
208
     *
209
     * @return mixed
210
     */
211
    public function getSchema()
212
    {
213
        $serviceRoute = $this->requestStack->getCurrentRequest()->get('service');
214
215
        // Locate the schema definition
216
        $schema =  $this->getServiceSchemaByRoute($serviceRoute);
217
218
        return $schema->getSchema();
219
    }
220
221
    private function getServiceParameters(AnalyticModel $model)
222
    {
223
        $params = [];
224
        if (!is_array($model->getParams())) {
225
            return $params;
226
        }
227
228
        foreach ($model->getParams() as $param) {
229
            if (!isset($param->name)) {
230
                throw new \LogicException("Incorrect spec (no name) of param in analytics route " . $model->getRoute());
231
            }
232
233
            $paramValue = $this->requestStack->getCurrentRequest()->query->get($param->name, null);
234
235
            // required missing?
236
            if (is_null($paramValue) && (isset($param->required) && $param->required === true)) {
237
                throw new \LogicException(
238
                    sprintf(
239
                        "Missing parameter '%s' in analytics route '%s'",
240
                        $param->name,
241
                        $model->getRoute()
242
                    )
243
                );
244
            }
245
246
            if (!is_null($param->type)) {
247
                switch ($param->type) {
248
                    case "integer":
249
                        $paramValue = intval($paramValue);
250
                        break;
251
                    case "boolean":
252
                        $paramValue = boolval($paramValue);
253
                        break;
254
                }
255
            }
256
257
            $params[$param->name] = $paramValue;
258
        }
259
260
        return $params;
261
    }
262
}
263