Completed
Push — master ( 03449d...db6361 )
by Lukas
44s queued 24s
created

ImageExportPlugin   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 113
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 113
rs 10
wmc 17
lcom 1
cbo 1

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A initialize() 0 5 1
B httpGet() 0 34 5
B getPhoto() 0 23 4
A readCard() 0 3 1
B getType() 0 15 5
1
<?php
2
/**
3
 * @author Thomas Müller <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\DAV\CardDAV;
23
24
use OCP\ILogger;
25
use Sabre\CardDAV\Card;
26
use Sabre\DAV\Server;
27
use Sabre\DAV\ServerPlugin;
28
use Sabre\HTTP\RequestInterface;
29
use Sabre\HTTP\ResponseInterface;
30
use Sabre\VObject\Parameter;
31
use Sabre\VObject\Property\Binary;
32
use Sabre\VObject\Reader;
33
34
class ImageExportPlugin extends ServerPlugin {
35
36
	/** @var Server */
37
	protected $server;
38
	/** @var ILogger */
39
	private $logger;
40
41
	public function __construct(ILogger $logger) {
42
		$this->logger = $logger;
43
	}
44
45
	/**
46
	 * Initializes the plugin and registers event handlers
47
	 *
48
	 * @param Server $server
49
	 * @return void
50
	 */
51
	function initialize(Server $server) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
52
53
		$this->server = $server;
54
		$this->server->on('method:GET', [$this, 'httpGet'], 90);
55
	}
56
57
	/**
58
	 * Intercepts GET requests on addressbook urls ending with ?photo.
59
	 *
60
	 * @param RequestInterface $request
61
	 * @param ResponseInterface $response
62
	 * @return bool|void
63
	 */
64
	function httpGet(RequestInterface $request, ResponseInterface $response) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
65
66
		$queryParams = $request->getQueryParameters();
67
		// TODO: in addition to photo we should also add logo some point in time
68
		if (!array_key_exists('photo', $queryParams)) {
69
			return true;
70
		}
71
72
		$path = $request->getPath();
73
		$node = $this->server->tree->getNodeForPath($path);
74
75
		if (!($node instanceof Card)) {
0 ignored issues
show
Bug introduced by
The class Sabre\CardDAV\Card does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
76
			return true;
77
		}
78
79
		$this->server->transactionType = 'carddav-image-export';
80
81
		// Checking ACL, if available.
82
		if ($aclPlugin = $this->server->getPlugin('acl')) {
83
			/** @var \Sabre\DAVACL\Plugin $aclPlugin */
84
			$aclPlugin->checkPrivileges($path, '{DAV:}read');
85
		}
86
87
		if ($result = $this->getPhoto($node)) {
88
			$response->setHeader('Content-Type', $result['Content-Type']);
89
			$response->setStatus(200);
90
91
			$response->setBody($result['body']);
92
93
			// Returning false to break the event chain
94
			return false;
95
		}
96
		return true;
97
	}
98
99
	function getPhoto(Card $node) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
100
		// TODO: this is kind of expensive - load carddav data from database and parse it
101
		//       we might want to build up a cache one day
102
		try {
103
			$vObject = $this->readCard($node->get());
104
			if (!$vObject->PHOTO) {
105
				return false;
106
			}
107
108
			$photo = $vObject->PHOTO;
109
			$type = $this->getType($photo);
110
111
			$valType = $photo->getValueType();
112
			$val = ($valType === 'URI' ? $photo->getRawMimeDirValue() : $photo->getValue());
113
			return [
114
				'Content-Type' => $type,
115
				'body' => $val
116
			];
117
		} catch(\Exception $ex) {
118
			$this->logger->logException($ex);
119
		}
120
		return false;
121
	}
122
123
	private function readCard($cardData) {
124
		return Reader::read($cardData);
125
	}
126
127
	/**
128
	 * @param Binary $photo
129
	 * @return Parameter
130
	 */
131
	private function getType($photo) {
132
		$params = $photo->parameters();
133
		if (isset($params['TYPE']) || isset($params['MEDIATYPE'])) {
134
			/** @var Parameter $typeParam */
135
			$typeParam = isset($params['TYPE']) ? $params['TYPE'] : $params['MEDIATYPE'];
136
			$type = $typeParam->getValue();
137
138
			if (strpos($type, 'image/') === 0) {
139
				return $type;
140
			} else {
141
				return 'image/' . strtolower($type);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return 'image/' . strtolower($type); (string) is incompatible with the return type documented by OCA\DAV\CardDAV\ImageExportPlugin::getType of type Sabre\VObject\Parameter.

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...
142
			}
143
		}
144
		return '';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return ''; (string) is incompatible with the return type documented by OCA\DAV\CardDAV\ImageExportPlugin::getType of type Sabre\VObject\Parameter.

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...
145
	}
146
}
147