|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace OCA\Notes\Service; |
|
4
|
|
|
|
|
5
|
|
|
use OCA\Notes\Db\Meta; |
|
6
|
|
|
use OCA\Notes\Db\MetaMapper; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Class MetaService |
|
10
|
|
|
* |
|
11
|
|
|
* @package OCA\Notes\Service |
|
12
|
|
|
*/ |
|
13
|
|
|
class MetaService { |
|
14
|
|
|
|
|
15
|
|
|
private $metaMapper; |
|
16
|
|
|
|
|
17
|
|
|
public function __construct(MetaMapper $metaMapper) { |
|
18
|
|
|
$this->metaMapper = $metaMapper; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function updateAll($userId, Array $notes) { |
|
22
|
|
|
$metas = $this->metaMapper->getAll($userId); |
|
23
|
|
|
$metas = $this->getIndexedArray($metas, 'fileId'); |
|
24
|
|
|
$notes = $this->getIndexedArray($notes, 'id'); |
|
25
|
|
|
foreach ($metas as $id => $meta) { |
|
26
|
|
|
if (!array_key_exists($id, $notes)) { |
|
27
|
|
|
// DELETE obsolete notes |
|
28
|
|
|
$this->metaMapper->delete($meta); |
|
29
|
|
|
unset($metas[$id]); |
|
30
|
|
|
} |
|
31
|
|
|
} |
|
32
|
|
|
foreach ($notes as $id => $note) { |
|
33
|
|
|
if (!array_key_exists($id, $metas)) { |
|
34
|
|
|
// INSERT new notes |
|
35
|
|
|
$metas[$note->getId()] = $this->create($userId, $note); |
|
36
|
|
|
} elseif ($note->getEtag()!==$metas[$id]->getEtag()) { |
|
37
|
|
|
// UPDATE changed notes |
|
38
|
|
|
$meta = $metas[$id]; |
|
39
|
|
|
$this->updateIfNeeded($meta, $note); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
return $metas; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
private function getIndexedArray(array $data, $property) { |
|
46
|
|
|
$property = ucfirst($property); |
|
47
|
|
|
$getter = 'get'.$property; |
|
48
|
|
|
$result = array(); |
|
49
|
|
|
foreach ($data as $entity) { |
|
50
|
|
|
$result[$entity->$getter()] = $entity; |
|
51
|
|
|
} |
|
52
|
|
|
return $result; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
private function create($userId, $note) { |
|
56
|
|
|
$meta = Meta::fromNote($note, $userId); |
|
57
|
|
|
$this->metaMapper->insert($meta); |
|
58
|
|
|
return $meta; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
private function updateIfNeeded(&$meta, $note) { |
|
62
|
|
|
if ($note->getEtag()!==$meta->getEtag()) { |
|
63
|
|
|
$meta->setEtag($note->getEtag()); |
|
64
|
|
|
$meta->setLastUpdate(time()); |
|
65
|
|
|
$this->metaMapper->update($meta); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|