Completed
Push — master ( c17b1b...8f13d8 )
by Olivier
13:31 queued 09:59
created

Service::getFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * ownCloud - galleryplus
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Olivier Paroz <[email protected]>
9
 *
10
 * @copyright Olivier Paroz 2014-2016
11
 */
12
13
namespace OCA\GalleryPlus\Service;
14
15
use OCP\Files\Node;
16
use OCP\ILogger;
17
18
use OCA\GalleryPlus\Environment\Environment;
19
20
/**
21
 * Contains methods which all services will need
22
 *
23
 * @package OCA\GalleryPlus\Service
24
 */
25
abstract class Service {
26
27
	/**
28
	 * @var string
29
	 */
30
	protected $appName;
31
	/**
32
	 * @var Environment
33
	 */
34
	protected $environment;
35
	/**
36
	 * @var ILogger
37
	 */
38
	protected $logger;
39
40
	/**
41
	 * Constructor
42
	 *
43
	 * @param string $appName
44
	 * @param Environment $environment
45
	 * @param ILogger $logger
46
	 */
47 111
	public function __construct(
48
		$appName,
49
		Environment $environment,
50
		ILogger $logger
51
	) {
52 111
		$this->appName = $appName;
53 111
		$this->environment = $environment;
54 111
		$this->logger = $logger;
55 111
	}
56
57
	/**
58
	 * Returns the file matching the given ID
59
	 *
60
	 * @param int $nodeId ID of the resource to locate
61
	 *
62
	 * @return Node
63
	 * @throws NotFoundServiceException
64
	 */
65 17
	public function getFile($nodeId) {
66 17
		$node = $this->getNode($nodeId);
67
68 14
		if ($node->getType() === 'file') {
69 13
			$this->validateNode($node);
70
71 12
			return $node;
72
		} else {
73 1
			throw new NotFoundServiceException("Cannot find a file with this ID");
74
		}
75
	}
76
77
	/**
78
	 * Returns the node matching the given ID
79
	 *
80
	 * @param int $nodeId ID of the resource to locate
81
	 *
82
	 * @return Node
83
	 * @throws NotFoundServiceException
84
	 */
85 17
	private function getNode($nodeId) {
86
		try {
87 17
			$node = $this->environment->getResourceFromId($nodeId);
88
89 14
			return $node;
90 3
		} catch (\Exception $exception) {
91 3
			throw new NotFoundServiceException($exception->getMessage());
92
		}
93
	}
94
95
	/**
96
	 * Makes extra sure that we can actually do something with the file
97
	 *
98
	 * @param Node $node
99
	 *
100
	 * @throws NotFoundServiceException
101
	 */
102 13
	private function validateNode($node) {
103 13
		if (!$node->getMimetype() || !$node->isReadable()) {
104 1
			throw new NotFoundServiceException("Can't access the file");
105
		}
106 12
	}
107
108
}
109