Completed
Push — master ( 64a4da...21cb6b )
by Thomas
07:39
created

EntityCollection::propPatch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Arthur Schiwon <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 *
6
 * @copyright Copyright (c) 2016, ownCloud GmbH.
7
 * @license AGPL-3.0
8
 *
9
 * This code is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License, version 3,
11
 * as published by the Free Software Foundation.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License, version 3,
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
20
 *
21
 */
22
23
namespace OCA\Comments\Dav;
24
25
use OCP\Comments\ICommentsManager;
26
use OCP\Comments\NotFoundException;
27
use OCP\ILogger;
28
use OCP\IUserManager;
29
use OCP\IUserSession;
30
use Sabre\DAV\Exception\NotFound;
31
use Sabre\DAV\IProperties;
32
use Sabre\DAV\PropPatch;
33
34
/**
35
 * Class EntityCollection
36
 *
37
 * this represents a specific holder of comments, identified by an entity type
38
 * (class member $name) and an entity id (class member $id).
39
 *
40
 * @package OCA\Comments\Dav
41
 */
42
class EntityCollection extends RootCollection implements IProperties {
43
	const PROPERTY_NAME_READ_MARKER  = '{http://owncloud.org/ns}readMarker';
44
45
	/** @var  string */
46
	protected $id;
47
48
	/** @var  ILogger */
49
	protected $logger;
50
51
	/**
52
	 * @param string $id
53
	 * @param string $name
54
	 * @param ICommentsManager $commentsManager
55
	 * @param IUserManager $userManager
56
	 * @param IUserSession $userSession
57
	 * @param ILogger $logger
58
	 */
59
	public function __construct(
60
		$id,
61
		$name,
62
		ICommentsManager $commentsManager,
63
		IUserManager $userManager,
64
		IUserSession $userSession,
65
		ILogger $logger
66
	) {
67
		foreach(['id', 'name'] as $property) {
68
			$$property = trim($$property);
69
			if(empty($$property) || !is_string($$property)) {
70
				throw new \InvalidArgumentException('"' . $property . '" parameter must be non-empty string');
71
			}
72
		}
73
		$this->id = $id;
74
		$this->name = $name;
75
		$this->commentsManager = $commentsManager;
76
		$this->logger = $logger;
77
		$this->userManager = $userManager;
78
		$this->userSession = $userSession;
79
	}
80
81
	/**
82
	 * returns the ID of this entity
83
	 *
84
	 * @return string
85
	 */
86
	public function getId() {
87
		return $this->id;
88
	}
89
90
	/**
91
	 * Returns a specific child node, referenced by its name
92
	 *
93
	 * This method must throw Sabre\DAV\Exception\NotFound if the node does not
94
	 * exist.
95
	 *
96
	 * @param string $name
97
	 * @return \Sabre\DAV\INode
98
	 * @throws NotFound
99
	 */
100 View Code Duplication
	function getChild($name) {
101
		try {
102
			$comment = $this->commentsManager->get($name);
103
			return new CommentNode(
104
				$this->commentsManager,
105
				$comment,
106
				$this->userManager,
107
				$this->userSession,
108
				$this->logger
109
			);
110
		} catch (NotFoundException $e) {
111
			throw new NotFound();
112
		}
113
	}
114
115
	/**
116
	 * Returns an array with all the child nodes
117
	 *
118
	 * @return \Sabre\DAV\INode[]
119
	 */
120
	function getChildren() {
121
		return $this->findChildren();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->findChildren(); (OCA\Comments\Dav\CommentNode[]) is incompatible with the return type of the parent method OCA\Comments\Dav\RootCollection::getChildren of type OCA\Comments\Dav\EntityTypeCollection[]|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
122
	}
123
124
	/**
125
	 * Returns an array of comment nodes. Result can be influenced by offset,
126
	 * limit and date time parameters.
127
	 *
128
	 * @param int $limit
129
	 * @param int $offset
130
	 * @param \DateTime|null $datetime
131
	 * @return CommentNode[]
132
	 */
133
	function findChildren($limit = 0, $offset = 0, \DateTime $datetime = null) {
134
		$comments = $this->commentsManager->getForObject($this->name, $this->id, $limit, $offset, $datetime);
135
		$result = [];
136
		foreach($comments as $comment) {
137
			$result[] = new CommentNode(
138
				$this->commentsManager,
139
				$comment,
140
				$this->userManager,
141
				$this->userSession,
142
				$this->logger
143
			);
144
		}
145
		return $result;
146
	}
147
148
	/**
149
	 * Checks if a child-node with the specified name exists
150
	 *
151
	 * @param string $name
152
	 * @return bool
153
	 */
154
	function childExists($name) {
155
		try {
156
			$this->commentsManager->get($name);
157
			return true;
158
		} catch (NotFoundException $e) {
159
			return false;
160
		}
161
	}
162
163
	/**
164
	 * Sets the read marker to the specified date for the logged in user
165
	 *
166
	 * @param \DateTime $value
167
	 * @return bool
168
	 */
169
	public function setReadMarker($value) {
170
		$dateTime = new \DateTime($value);
171
		$user = $this->userSession->getUser();
172
		$this->commentsManager->setReadMark($this->name, $this->id, $dateTime, $user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 171 can be null; however, OCP\Comments\ICommentsManager::setReadMark() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
173
		return true;
174
	}
175
176
	/**
177
	 * @inheritdoc
178
	 */
179
	function propPatch(PropPatch $propPatch) {
180
		$propPatch->handle(self::PROPERTY_NAME_READ_MARKER, [$this, 'setReadMarker']);
181
	}
182
183
	/**
184
	 * @inheritdoc
185
	 */
186
	function getProperties($properties) {
187
		$marker = null;
188
		$user = $this->userSession->getUser();
189
		if(!is_null($user)) {
190
			$marker = $this->commentsManager->getReadMark($this->name, $this->id, $user);
191
		}
192
		return [self::PROPERTY_NAME_READ_MARKER => $marker];
193
	}
194
}
195
196