Completed
Pull Request — master (#95)
by korelstar
05:25
created

MetaService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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);
0 ignored issues
show
Bug introduced by
The method create() does not seem to exist on object<OCA\Notes\Service\MetaService>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
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 updateIfNeeded(&$meta, $note) {
63
		if($note->getEtag()!==$meta->getEtag()) {
64
			$meta->setEtag($note->getEtag());
65
			$meta->setLastUpdate(time());
66
			$this->metaMapper->update($meta);
67
		}
68
	}
69
}
70