Passed
Pull Request — master (#290)
by korelstar
02:02
created

MetaService   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 12
eloc 30
dl 0
loc 53
c 0
b 0
f 0
rs 10

5 Methods

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