initial commit
[namibia] / module / Utility / src / Utility / Registry.php
1 <?php
2 namespace Utility;
3
4
5
6 /**
7  * Central registry for storing item during script execution.
8  * @author andre.fourie
9  *
10  */
11 class Registry
12 {
13
14         /**
15          * @var \Zend\Session\Container
16          */
17         static protected $session;
18         /**
19          * @var \Doctrine\ORM\EntityManager
20          */
21         static protected $em;
22         /**
23          * @var \Zend\ServiceManager\ServiceLocatorInterface
24          */
25         static protected $sm;
26         /**
27          * @var array
28          */
29         static protected $container = array(
30                         'UseOnce' => array()
31         );
32         /**
33          * @var array
34          */
35         static protected $config;
36
37
38         /**
39          * Initiate session container.
40          */
41         static protected function initSession()
42         {
43                 is_null(self::$session)
44                         && self::$session = new \Zend\Session\Container(__CLASS__);
45         }
46
47         /**
48          * Store an item.
49          * @param string $key
50          * @param unknown $value
51          * @return boolean
52          */
53         static public function set($key, $value)
54         {
55                 self::$container[$key] = $value;
56                 return true;
57         }
58
59         /**
60          * Retrieve an item.
61          * @param string $key
62          * @param unknown|null $default
63          * @return unknown|null
64          */
65         static public function get($key, $default = null)
66         {
67                 return isset(self::$container[$key])
68                         ? self::$container[$key]
69                         : $default;
70         }
71
72         /**
73          * Set value for single retrieval.
74          * @param string $key
75          * @param unknown $value
76          */
77         static public function setOnce($key, $value)
78         {
79                 self::$container['UseOnce'][$key] = $value;
80                 return true;
81         }
82
83         /**
84          * Retrieve single use value. Value will be destroyed after this call.
85          * @param string $key
86          * @param unknown|null $default
87          * @return unknown|null
88          */
89         static public function checkOnce($key, $default = null)
90         {
91                 if (isset(self::$container['UseOnce'][$key]))
92                 {
93                         $value = self::$container['UseOnce'][$key];
94                         unset(self::$container['UseOnce'][$key]);
95                         return $value;
96                 }
97                 else
98                 {
99                         return $default;
100                 }
101         }
102
103         /**
104          * Set Doctrine Entity Manager for easy access.
105          * @param \Doctrine\ORM\EntityManager $em
106          * @return boolean
107          */
108         static public function setEntityManager($em)
109         {
110                 self::$em = $em;
111                 $config = new \Doctrine\ORM\Configuration();
112                 $config->setQueryCacheImpl(new \Doctrine\Common\Cache\FilesystemCache('data/DoctrineORMModule/QueryCache'));
113                 $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\FilesystemCache('data/DoctrineORMModule/MetaCache'));
114                 $config->setAutoGenerateProxyClasses(false);
115                 return true;
116         }
117
118         /**
119          * Retrieve Doctrine Entity Manager.
120          * @return \Doctrine\ORM\EntityManager
121          */
122         static public function getEntityManager()
123         {
124                 return self::$em;
125         }
126
127         /**
128          * Set Doctrine Entity Manager for easy access.
129          * @param \Zend\ServiceManager\ServiceLocatorInterface $sm
130          * @return boolean
131          */
132         static public function setServiceManager($sm)
133         {
134                 self::$sm = $sm;
135                 self::$em = self::$sm->get('doctrine.entitymanager.orm_default');
136                 $config = new \Doctrine\ORM\Configuration();
137                 $config->setQueryCacheImpl(new \Doctrine\Common\Cache\FilesystemCache('data/DoctrineORMModule/QueryCache'));
138                 $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\FilesystemCache('data/DoctrineORMModule/MetaCache'));
139                 $config->setAutoGenerateProxyClasses(false);
140                 //$config->ensureProductionSettings();
141                 return true;
142         }
143
144         /**
145          * Retrieve Doctrine Entity Manager.
146          * @return \Zend\ServiceManager\ServiceLocatorInterface
147          */
148         static public function getServiceManager()
149         {
150                 return self::$sm;
151         }
152
153         /**
154          * Set device session from token.
155          * @param string $token
156          * @throws \Exception
157          * @return boolean
158          */
159         static public function setSession($token)
160         {
161                 self::$session = null;
162                 $sm = new \Zend\Session\SessionManager();
163                 $sm->setId($token);
164                 self::initSession();
165                 if (!isset(self::$session->authData)
166                         || self::$session->authData['authToken'] != $token)
167                 {
168                         throw new \Exception('Invalid session requested.');
169                 }
170                 return true;
171         }
172
173         /**
174          * Set authentication data in session for global accessibility.
175          * @param array $authData
176          * @return boolean
177          */
178         static public function clearAuthData()
179         {
180                 self::initSession();
181                 if (isset(self::$session->authData))
182                 {
183                         unset(self::$session->authData);
184                 }
185                 return true;
186         }
187
188         /**
189          * Clear grid data stored in session.
190          * @param array $authData
191          * @return boolean
192          */
193         static public function clearSessionData()
194         {
195                 self::initSession();
196                 if (isset(self::$session->sessData))
197                 {
198                         unset(self::$session->sessData);
199                 }
200                 return true;
201         }
202
203         /**
204          * Should session data be cleared?
205          * @param string $containerName
206          * @return boolean
207          */
208         static public function initSessionStorage($containerName)
209         {
210                 self::initSession();
211                 isset(self::$session->sessData)
212                         || self::$session->sessData = array();
213                 if (!isset(self::$session->sessData[$containerName]))
214                 {
215                         self::$session->sessData[$containerName] = true;
216                         return true;
217                 }
218                 return false;
219         }
220
221         /**
222          * Set authentication data in session for global accessibility.
223          * @param array $authData
224          * @return boolean
225          */
226         static public function setAuthData(array $authData)
227         {
228                 self::initSession();
229                 $sm = new \Zend\Session\SessionManager();
230                 isset($authData['Sudo'])
231                         || $authData['Sudo'] = array();
232                 $authData['authToken'] = $sm->getId();
233                 self::$session->authData = $authData;
234                 return true;
235         }
236
237         /**
238          * Set a data parameter in the authentication packet.
239          * @param string $param
240          * @param unknown $value
241          * @return boolean
242          */
243         static public function setAuthParam($param, $value)
244         {
245                 self::initSession();
246                 if (isset(self::$session->authData))
247                 {
248                         self::$session->authData[$param] = $value;
249                 }
250                 return isset(self::$session->authData);
251         }
252
253         /**
254          * Set a data parameter in the authentication packet.
255          * @param string $param
256          * @param unknown $value
257          * @return boolean
258          */
259         static public function setAuthSudo($param, $label, $value)
260         {
261                 self::initSession();
262                 if (isset(self::$session->authData))
263                 {
264                         self::$session->authData['Sudo'][$param] = $value;
265                         self::$session->authData['Sudo'][$param . 'Id'] = $value;
266                         self::$session->authData['Sudo'][$param . 'Name'] = $label;
267                         self::$session->authData['Sudo']['Names'][$param] = $label;
268                 }
269                 return isset(self::$session->authData);
270         }
271
272         /**
273          * Retrieve sudo filter.
274          * @param string $param
275          * @param unknown $default
276          * @return unknown
277          */
278         static public function getSudo($param, $default)
279         {
280                 self::initSession();
281                 return isset(self::$session->authData)
282                                 && isset(self::$session->authData['Sudo'][$param])
283                         ? self::$session->authData['Sudo'][$param]
284                         : $default;
285         }
286
287         /**
288          * Retrieve authentication data.
289          * @return array|null
290          */
291         static public function getAuthData()
292         {
293                 self::initSession();
294                 return isset(self::$session->authData)
295                         ? self::$session->authData
296                         : null;
297         }
298
299         /**
300          * Check if we have authentication data.
301          * @return boolean
302          */
303         static public function isAuthenticated()
304         {
305                 self::initSession();
306                 return isset(self::$session->authData);
307         }
308
309         /**
310          * Get an authentication parameter.
311          * @param string $key
312          * @return unknown|null
313          */
314         static public function getAuthParam($key)
315         {
316                 self::initSession();
317                 return isset(self::$session->authData) && isset(self::$session->authData[$key])
318                         ? self::$session->authData[$key]
319                         : null;
320         }
321
322         /**
323          * Get authenticated user's user type.
324          * @return string|null
325          */
326         static public function getUserType()
327         {
328                 self::initSession();
329                 return isset(self::$session->authData) && isset(self::$session->authData['permissions']['name'])
330                         ? self::$session->authData['permissions']['name']
331                         : null;
332         }
333
334         /**
335          * Resolve Company from session and sudo settings.
336          * @param integer|null $companyId
337          * @throws \Exception
338          * @return integer|object|null
339          */
340         static public function resolveCompanyContext($companyId = null)
341         {
342                 if (is_null(self::$em))
343                 {
344                         return $companyId;
345                 }
346                 self::initSession();
347                 if (!isset(self::$session->authData)
348                         || (!is_null($companyId)
349                                         && 'Administrator' == self::$session->authData['userType']))
350                 {
351                         return !is_null($companyId)
352                                 ? self::$em->getReference(
353                                                 '\Company\Entity\Company',
354                                                 $companyId
355                                                 )
356                                 : null;
357                 }
358                 if (is_null($companyId))
359                 {
360                         $companyFilter = \Utility\Registry::getSudo('Company', false);
361                         if (!$companyFilter)
362                         {
363                                 return self::$em->getReference(
364                                                 '\Company\Entity\Company',
365                                                 self::$session->authData['company']['id']
366                                 );
367                         }
368                         else
369                         {
370                                 return self::$em->getReference(
371                                                 '\Company\Entity\Company',
372                                                 $companyFilter
373                                 );
374                         }
375                 }
376                 else
377                 {
378                         $companyFilter = \Utility\Registry::getSudo('Company', false);
379                         if ('Administrator' != self::$session->authData['userType'] || !$companyFilter)
380                         {
381                                 throw new \Exception('No dealership selected for actioning.');
382                         }
383                         return self::$em->getReference(
384                                         '\Company\Entity\Company',
385                                         $companyFilter
386                         );
387                 }
388         }
389
390         /**
391          * Resolve Profile from session and sudo settings.
392          * @param integer|null $profileId
393          * @throws \Exception
394          * @return \User\Entity\Profile|null
395          */
396         static public function resolveProfileContext($profileId = null)
397         {
398                 if (is_null(self::$em))
399                 {
400                         return $profileId;
401                 }
402                 self::initSession();
403                 if (!isset(self::$session->authData))
404                 {
405                         return !is_null($profileId)
406                                 ? self::$em->getReference(
407                                                 '\User\Entity\Profile',
408                                                 $profileId
409                                                 )
410                                 : null;
411                 }
412                 else
413                 {
414                         $profileFilter = \Utility\Registry::getSudo('Profile', false);
415                         return ($profileFilter)
416                                 ? self::$em->getReference(
417                                                 '\User\Entity\Profile',
418                                                 $profileFilter
419                                                 )
420                                 : self::$em->getReference(
421                                                 '\User\Entity\Profile',
422                                                 self::$session->authData['id']
423                                                 );
424                 }
425         }
426
427         /**
428          * Retrieve global config.
429          * @return array
430          */
431         static public function getGlobalConfig()
432         {
433                 is_null(self::$config)
434                         && self::$config = array_merge(
435                                 include __DIR__ . '/../../../../config/autoload/global.php',
436                                 include __DIR__ . '/../../../../config/autoload/local.php'
437                                 );
438                 return self::$config;
439         }
440
441         /**
442          * Add changable config data to global config.
443          * @param array $config
444          * @return boolean
445          */
446         static public function addDynamicConfig(array $config)
447         {
448                 self::getGlobalConfig();
449                 self::$config = array_merge(self::$config, $config);
450                 return true;
451         }
452
453         /**
454          * Retrieve section from global config.
455          * @param string $key
456          * @return unknown|null
457          */
458         static public function getConfigParam($key)
459         {
460                 self::getGlobalConfig();
461                 return isset(self::$config[$key])
462                         ? self::$config[$key]
463                         : null;
464         }
465
466         /**
467          * Store data to file.
468          * @param  string  $key  Storage key
469          * @param  unknown $data Data to store
470          * @return void
471          */
472         static public function storeJson($key, $data)
473         {
474                 file_put_contents(getcwd() . '/data/file/' . $key . '.json', json_encode($data));
475         }
476
477         /**
478          * Retrieve data from file.
479          * @param  string  $key Storage key
480          * @return unknown      Stored data or null
481          */
482         static public function fetchJson($key)
483         {
484                 if (!file_exists(getcwd() . '/data/file/' . $key . '.json'))
485                 {
486                         return null;
487                 }
488                 $result = file_get_contents(getcwd() . '/data/file/' . $key . '.json');
489                 return json_decode($result, true);
490         }
491
492         /**
493          * Delete data file.
494          * @param  string  $key Storage key
495          * @return void
496          */
497         static public function deleteJson($key)
498         {
499                 if (file_exists(getcwd() . '/data/file/' . $key . '.json'))
500                 {
501                         unlink(getcwd() . '/data/file/' . $key . '.json');
502                 }
503         }
504
505         /**
506          * Cleanup files older than [hours].
507          * @param  integer $hours Number of hours
508          * @return void
509          */
510         static public function cleanupJson($hours)
511         {
512                 $files = glob(getcwd() . '/data/file/*');
513                 $now   = time();
514                 foreach ($files as $file)
515                 {
516                         if (is_file($file))
517                         {
518                                 if ($now - filemtime($file) >= 60 * 60 * (int) $hours)
519                                 {
520                                         unlink($file);
521                                 }
522                         }
523                 }
524         }
525
526 }