forked from nextcloud/notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMetaService.php
75 lines (66 loc) · 1.72 KB
/
MetaService.php
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
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*/
namespace OCA\Notes\Service;
use OCA\Notes\Db\Note;
use OCA\Notes\Db\Meta;
use OCA\Notes\Db\MetaMapper;
/**
* Class MetaService
*
* @package OCA\Notes\Service
*/
class MetaService {
private $metaMapper;
public function __construct(MetaMapper $metaMapper) {
$this->metaMapper = $metaMapper;
}
public function updateAll($userId, Array $notes) {
$metas = $this->metaMapper->getAll($userId);
$metas = $this->getIndexedArray($metas, 'fileId');
$notes = $this->getIndexedArray($notes, 'id');
foreach($metas as $id=>$meta) {
if(!array_key_exists($id, $notes)) {
// DELETE obsolete notes
$this->metaMapper->delete($meta);
unset($metas[$id]);
}
}
foreach($notes as $id=>$note) {
if(!array_key_exists($id, $metas)) {
// INSERT new notes
$metas[$note->getId()] = $this->create($userId, $note);
} elseif($note->getEtag()!==$metas[$id]->getEtag()) {
// UPDATE changed notes
$meta = $metas[$id];
$this->updateIfNeeded($meta, $note);
}
}
return $metas;
}
private function getIndexedArray(array $data, $property) {
$property = ucfirst($property);
$getter = 'get'.$property;
$result = array();
foreach($data as $entity) {
$result[$entity->$getter()] = $entity;
}
return $result;
}
private function create($userId, $note) {
$meta = Meta::fromNote($note, $userId);
$this->metaMapper->insert($meta);
return $meta;
}
private function updateIfNeeded(&$meta, $note) {
if($note->getEtag()!==$meta->getEtag()) {
$meta->setEtag($note->getEtag());
$meta->setLastUpdate(time());
$this->metaMapper->update($meta);
}
}
}