Completed
Push — develop ( 86030e...ecef87 )
by
unknown
22:25
created

ServiceManager::getServices()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 32
ccs 0
cts 32
cp 0
rs 8.8571
cc 3
eloc 20
nc 3
nop 0
crap 12
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\Finder\Finder;
11
use Doctrine\Common\Cache\CacheProvider;
12
use Symfony\Component\HttpFoundation\RequestStack;
13
use Symfony\Component\Routing\Router;
14
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
15
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
16
17
/**
18
 * Service Request Converter and startup for Analytics
19
 *
20
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
21
 * @license  https://opensource.org/licenses/MIT MIT License
22
 * @link     http://swisscom.ch
23
 */
24
class ServiceManager
25
{
26
    /** Cache name for services */
27
    const CACHE_KEY_SERVICES = 'analytics_services';
28
    const CACHE_KEY_SERVICES_TIME = 10;
29
    const CACHE_KEY_SERVICES_URLS = 'analytics_services_urls';
30
    const CACHE_KEY_SERVICES_URLS_TIME = 10;
31
    const CACHE_KEY_SERVICES_PREFIX = 'analytics_';
32
33
    /** @var RequestStack */
34
    protected $requestStack;
35
36
    /** @var AnalyticsManager */
37
    protected $analyticsManager;
38
39
    /** @var CacheProvider */
40
    protected $cacheProvider;
41
42
    /** @var Router */
43
    protected $router;
44
45
    /** @var string */
46
    protected $directory;
47
48
    /**
49
     * ServiceConverter constructor.
50
     * @param RequestStack     $requestStack        Sf Request information service
51
     * @param AnalyticsManager $analyticsManager    Db Manager and query control
52
     * @param CacheProvider    $cacheProvider       Cache service
53
     * @param Router           $router              To manage routing generation
54
     * @param string           $definitionDirectory Where definitions are stored
55
     */
56
    public function __construct(
57
        RequestStack $requestStack,
58
        AnalyticsManager $analyticsManager,
59
        CacheProvider $cacheProvider,
60
        Router $router,
61
        $definitionDirectory
62
    ) {
63
        $this->requestStack = $requestStack;
64
        $this->analyticsManager = $analyticsManager;
65
        $this->cacheProvider = $cacheProvider;
66
        $this->router = $router;
67
        $this->directory = $definitionDirectory;
68
    }
69
70
    /**
71
     * Scan base root directory for analytic definitions
72
     * @return array
73
     */
74
    private function getDirectoryServices()
75
    {
76
        $services = $this->cacheProvider->fetch(self::CACHE_KEY_SERVICES);
77
78
        if (is_array($services)) {
79
            return $services;
80
        }
81
82
        $services = [];
83
        if (strpos($this->directory, 'vendor/graviton/graviton')) {
84
            $this->directory = str_replace('vendor/graviton/graviton/', '', $this->directory);
85
        }
86
        if (!is_dir($this->directory)) {
87
            return $services;
88
        }
89
90
        $finder = new Finder();
91
        $finder
92
            ->files()
93
            ->in($this->directory)
94
            ->path('/\/analytics\//i')
95
            ->name('*.json')
96
            ->notName('_*')
97
            ->sortByName();
98
99
        foreach ($finder as $file) {
100
            $key = $file->getFilename();
101
            $data = json_decode($file->getContents());
102
            if (json_last_error()) {
103
                throw new InvalidConfigurationException(
104
                    sprintf('Analytics file: %s could not be loaded due to error: ', $key, json_last_error_msg())
105
                );
106
            }
107
            $services[$data->route] = $data;
108
        }
109
110
        $this->cacheProvider->save(self::CACHE_KEY_SERVICES, $services, self::CACHE_KEY_SERVICES_TIME);
111
        return $services;
112
    }
113
114
    /**
115
     * Return array of available services
116
     *
117
     * @return array
118
     */
119
    public function getServices()
120
    {
121
        $services = $this->cacheProvider->fetch(self::CACHE_KEY_SERVICES_URLS);
122
        if (is_array($services)) {
123
            return $services;
124
        }
125
        $services = [];
126
        foreach ($this->getDirectoryServices() as $name => $service) {
127
            $services[] = [
128
                '$ref' => $this->router->generate(
129
                    'graviton_analytics_service',
130
                    [
131
                        'service' => $service->route
132
                    ],
133
                    false
134
                ),
135
                'profile' => $this->router->generate(
136
                    'graviton_analytics_service_schema',
137
                    [
138
                        'service' => $service->route
139
                    ],
140
                    true
141
                )
142
            ];
143
        }
144
        $this->cacheProvider->save(
145
            self::CACHE_KEY_SERVICES_URLS,
146
            $services,
147
            self::CACHE_KEY_SERVICES_URLS_TIME
148
        );
149
        return $services;
150
    }
151
152
    /**
153
     * Get service definition
154
     *
155
     * @param string $name Route name for service
156
     * @throws NotFoundHttpException
157
     * @return AnalyticModel
158
     */
159
    private function getServiceSchemaByRoute($name)
160
    {
161
        $services = $this->getDirectoryServices();
162
        // Locate the schema definition
163
        if (!array_key_exists($name, $services)) {
164
            throw new NotFoundHttpException(
165
                sprintf('Service Analytics for %s was not found', $name)
166
            );
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
    /**
222
     * returns the params as passed from the user
223
     *
224
     * @param AnalyticModel $model model
225
     *
226
     * @return array the params, converted as specified
227
     */
228
    private function getServiceParameters(AnalyticModel $model)
229
    {
230
        $params = [];
231
        if (!is_array($model->getParams())) {
232
            return $params;
233
        }
234
235
        foreach ($model->getParams() as $param) {
236
            if (!isset($param->name)) {
237
                throw new \LogicException("Incorrect spec (no name) of param in analytics route " . $model->getRoute());
238
            }
239
240
            $paramValue = $this->requestStack->getCurrentRequest()->query->get($param->name, null);
241
242
            // required missing?
243
            if (is_null($paramValue) && (isset($param->required) && $param->required === true)) {
244
                throw new \LogicException(
245
                    sprintf(
246
                        "Missing parameter '%s' in analytics route '%s'",
247
                        $param->name,
248
                        $model->getRoute()
249
                    )
250
                );
251
            }
252
253
            if (!is_null($param->type)) {
254
                switch ($param->type) {
255
                    case "integer":
256
                        $paramValue = intval($paramValue);
257
                        break;
258
                    case "boolean":
259
                        $paramValue = boolval($paramValue);
260
                        break;
261
                    case "array":
262
                        $paramValue = explode(',', $paramValue);
263
                        break;
264
                    case "array<integer>":
265
                        $paramValue = array_map('intval', explode(',', $paramValue));
266
                        break;
267
                    case "array<boolean>":
268
                        $paramValue = array_map('boolval', explode(',', $paramValue));
269
                        break;
270
                }
271
            }
272
273
            $params[$param->name] = $paramValue;
274
        }
275
276
        return $params;
277
    }
278
}
279