Completed
Push — develop ( ecef87...362d71 )
by
unknown
14s
created

ServiceManager::getCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 6
c 1
b 0
f 0
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 2
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 Graviton\AnalyticsBundle\Exception\AnalyticUsageException;
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
170
        $mapper = new JsonMapper();
171
        /** @var AnalyticModel $schema */
172
        $schema = $mapper->map($services[$name], new AnalyticModel());
173
        return $schema;
174
    }
175
176
    /**
177
     * Will map and find data for defined route
178
     *
179
     * @return array
180
     */
181
    public function getData()
182
    {
183
        $serviceRoute = $this->requestStack->getCurrentRequest()->get('service');
184
185
        // Locate the schema definition
186
        $schema = $this->getServiceSchemaByRoute($serviceRoute);
187
        $cacheTime = $schema->getCacheTime();
188
        $cacheKey = $this->getCacheKey($schema);
189
190
        //Cached data if configured
191
        if ($cacheTime &&
192
            $cache = $this->cacheProvider->fetch($cacheKey)
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($cacheKey, $data, $cacheTime);
201
        }
202
203
        return $data;
204
    }
205
206
    /**
207
     * generate a cache key also based on query
208
     *
209
     * @param AnalyticModel $schema schema
210
     *
211
     * @return string cache key
212
     */
213
    private function getCacheKey($schema)
214
    {
215
        return self::CACHE_KEY_SERVICES_PREFIX
216
            .$schema->getRoute()
217
            .sha1(serialize($this->requestStack->getCurrentRequest()->query->all()));
218
    }
219
220
    /**
221
     * Locate and display service definition schema
222
     *
223
     * @return mixed
224
     */
225
    public function getSchema()
226
    {
227
        $serviceRoute = $this->requestStack->getCurrentRequest()->get('service');
228
229
        // Locate the schema definition
230
        $schema =  $this->getServiceSchemaByRoute($serviceRoute);
231
232
        return $schema->getSchema();
233
    }
234
235
    /**
236
     * returns the params as passed from the user
237
     *
238
     * @param AnalyticModel $model model
239
     *
240
     * @return array the params, converted as specified
241
     */
242
    private function getServiceParameters(AnalyticModel $model)
243
    {
244
        $params = [];
245
        if (!is_array($model->getParams())) {
246
            return $params;
247
        }
248
249
        foreach ($model->getParams() as $param) {
250
            if (!isset($param->name)) {
251
                throw new \LogicException("Incorrect spec (no name) of param in analytics route " . $model->getRoute());
252
            }
253
254
            $paramValue = $this->requestStack->getCurrentRequest()->query->get($param->name, null);
255
256
            // required missing?
257
            if (is_null($paramValue) && (isset($param->required) && $param->required === true)) {
258
                throw new AnalyticUsageException(
259
                    sprintf(
260
                        "Missing parameter '%s' in analytics route '%s'",
261
                        $param->name,
262
                        $model->getRoute()
263
                    )
264
                );
265
            }
266
267
            if (!is_null($param->type)) {
268
                switch ($param->type) {
269
                    case "integer":
270
                        $paramValue = intval($paramValue);
271
                        break;
272
                    case "boolean":
273
                        $paramValue = boolval($paramValue);
274
                        break;
275
                    case "array":
276
                        $paramValue = explode(',', $paramValue);
277
                        break;
278
                    case "array<integer>":
279
                        $paramValue = array_map('intval', explode(',', $paramValue));
280
                        break;
281
                    case "array<boolean>":
282
                        $paramValue = array_map('boolval', explode(',', $paramValue));
283
                        break;
284
                }
285
            }
286
287
            $params[$param->name] = $paramValue;
288
        }
289
290
        return $params;
291
    }
292
}
293