-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathKeyValueStore.php
More file actions
90 lines (74 loc) · 1.92 KB
/
KeyValueStore.php
File metadata and controls
90 lines (74 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace Elcweb\KeyValueStoreBundle;
use Doctrine\ORM\EntityManager;
use Elcweb\KeyValueStoreBundle\Entity\KeyValue;
class KeyValueStore
{
/**
*
* @var EntityManager
*/
protected $em;
/**
*
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* Gets the value of the exact key
*
* @param string $key
* @return mixed
*/
public function get($key)
{
$value = $this->em->getRepository('ElcwebKeyValueStoreBundle:KeyValue')->findOneByKey($key);
if (!$value) {
return null;
}
return $value->getValue();
}
/**
* Adds a new pair of key value
*
* @param mixed $key
* @param mixed $value
* @param string $description
*/
public function set($key, $value, $description = '')
{
$keyvalue = $this->em->getRepository('ElcwebKeyValueStoreBundle:KeyValue')->findOneByKey($key);
if (!$keyvalue) {
$keyvalue = new KeyValue;
$keyvalue->setKey($key);
}
$keyvalue->setValue($value);
$keyvalue->setDescription($description);
$this->em->persist($keyvalue);
$this->em->flush();
}
/**
* Gets all the matching key prefixs Ex. '$key%' and returns array of postfix keys
*
* @param $key
* @return array
*/
public function getAll($key)
{
$qb = $this->em->createQueryBuilder();
$result = $qb->select('u')
->from('ElcwebKeyValueStoreBundle:KeyValue', 'u')
->where($qb->expr()->like('u.key', ':key'))
->setParameter('key', "{$key}%")
->getQuery()
->getResult();
$return = array();
foreach ($result as $row) {
$return[substr($row->getKey(), strlen($key))] = $row->getValue();
}
return $return;
}
}