ImportManager::loadXmlFile()   B
last analyzed

Complexity

Conditions 9
Paths 4

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90
Metric Value
dl 0
loc 16
ccs 0
cts 14
cp 0
rs 7.756
cc 9
eloc 12
nc 4
nop 1
crap 90
1
<?php
2
/**
3
 * ownCloud - Import manager
4
 *
5
 * @author Nicolas Mora
6
 * @copyright 2013-2014 Nicolas Mora [email protected]
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
10
 * License as published by the Free Software Foundation
11
 * version 3 of the License
12
 *
13
 * This library 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
19
 * License along with this library.	If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
 
0 ignored issues
show
Coding Style introduced by
Tabs must be used to indent lines; spaces are not allowed
Loading history...
23
namespace OCA\Contacts;
24
use OCA\Contacts\Connector\ImportCsvConnector;
25
use OCA\Contacts\Connector\ImportVCardConnector;
26
use OCA\Contacts\Connector\ImportLdifConnector;
27
28
/**
29
 * Manages the import with basic functionalities
30
 */
31
class ImportManager {
32
	
33
	/**
34
	 * @param string $path
35
	 */
36
	private function loadXmlFile($path) {
37
		if (file_exists($path)) {
38
			$format = simplexml_load_file ( $path );
39
			if ($format) {
40
				if (isset($format->import_core)
41
				&& isset($format->import_core->name)
42
				&& isset($format->import_core->display_name)
43
				&& isset($format->import_core->type)
44
				&& isset($format->import_core->active)
45
				&& $format->import_core->active == '1') {
46
					return $format;
47
				}
48
			}
49
		}
50
		return false;
51
	}
52
	
53
	/**
54
	 * @brief return the different import formats available by scanning the contacts/formats folder
55
	 * @return array(string, string)
0 ignored issues
show
Documentation introduced by
The doc-type array(string, could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
56
	 */
57
	public function getTypes() {
58
		$prefix = "import_";
59
		$suffix = "_connector.xml";
60
		$path = __DIR__ . "/../formats/";
61
		$files = scandir($path);
62
		$formats = array();
63
		foreach ($files as $file) {
64
			if (!strncmp($file, $prefix, strlen($prefix)) && substr($file, - strlen($suffix)) === $suffix) {
65
				$format = $this->loadXmlFile(realpath($path.$file));
66
				if ($format) {
67
					$formats[(string)$format->import_core->name] = (string)$format->import_core->display_name;
68
				}
69
			}
70
		}
71
		return $formats;
72
	}
73
	
74
	/**
75
	 * @brief get all the preferences for the addressbook
76
	 * @return SimpleXml
77
	 */
78
	public function getType($typeName) {
79
		$path = __DIR__ . "/../formats/import_" . $typeName . "_connector.xml";
80
		return $this->loadXmlFile($path);
81
	}
82
		
83
	/**
84
	 * @brief imports the file with the selected type, and converts into VCards
85
	 * @param $file the path to the file
86
	 * @param $typeName the type name to use as stored into the app settings
87
	 * @param $limit the number of elements to import
88
	 * @return an array containing VCard elements|false if empty of error
89
	 */
90
	public function importFile($file, $typeName, $limit=-1) {
91
		\OCP\Util::writeLog('contacts import manager', __METHOD__.' importing as '.$typeName, \OCP\Util::INFO);
92
		$connector = $this->getConnector($typeName);
93
		if ($connector) {
94
			$elements = $connector->getElementsFromInput($file, $limit);
95
			if (count($elements) > 0) {
96
				return $elements;
97
			} else {
98
				return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by OCA\Contacts\ImportManager::importFile of type OCA\Contacts\an.

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...
99
			}
100
		} else {
101
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by OCA\Contacts\ImportManager::importFile of type OCA\Contacts\an.

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...
102
		}
103
	}
104
	
105
	public function getConnector($type) {
106
		$importType = $this->getType($type);
107
		$elements = array();
0 ignored issues
show
Unused Code introduced by
$elements is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
108
		if (!$importType) {
109
			return false;
110
		}
111
		if ((string)$importType->import_core->type == 'csv') {
112
			// use class ImportCsvConnector
113
			return new ImportCsvConnector($importType);
114
		} else if ((string)$importType->import_core->type == 'vcard') {
115
			// use class importVcardConnector
116
			return new ImportVCardConnector($importType);
117
		} else if ((string)$importType->import_core->type == 'ldif') {
118
			// use class importVcardConnector
119
			return new ImportLdifConnector($importType);
120
		}
121
		return false;
122
	}
123
	
124
	/**
125
	 * @brief import the first element of the file with all the types
126
	 * detects wich imported type has the least elements "X-Unknown-Element"
127
	 * then returns the corresponding type
128
	 * @param $file the path to the file
129
	 * @return array containing the probability for each format
130
	 */
131
	public function detectFileType($file) {
132
		$types = $this->getTypes();
133
		$probability = array();
134
		foreach ($types as $type => $description) {
135
			$connector = $this->getConnector($type);
136
				if ($connector) {
137
					$probability[$type] = $connector->getFormatMatch($file);
138
				}
139
		}
140
		return $probability;
141
	}
142
	
143
	/**
144
	 * @brief get the raw entries from the input file
145
	 * @param $file the path to the file
146
	 * @param $limit the maximum number of entries to return (-1: no limit)
147
	 * @return array|false
148
	 */
149
	public function getEntries($file, $limit=-1) {
150
		return $connector->getElementsFromInput($file, $limit);
0 ignored issues
show
Bug introduced by
The variable $connector does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
151
	}
152
}
153
154
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
155