ImportLdifConnector   B
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 187
Duplicated Lines 20.86 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 2 Features 0
Metric Value
wmc 40
lcom 1
cbo 3
dl 39
loc 187
ccs 0
cts 130
cp 0
rs 8.2608
c 2
b 2
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getFormatMatch() 17 17 4
A getElementsFromInput() 0 12 2
C getSourceElementsFromFile() 6 53 17
B convertElementToVCard() 0 28 6
C convertElementToProperty() 16 24 8
A getImportEntry() 0 8 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ImportLdifConnector often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ImportLdifConnector, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * ownCloud - LDIF Import connector
4
 *
5
 * @author Nicolas Mora
6
 * @copyright 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\Connector;
24
25
use Sabre\VObject\Component;
26
use Sabre\VObject\StringUtil;
27
use Sabre\VObject;
28
29
/**
30
 * @brief Implementation of the LDIF import format
31
 */
32
class ImportLdifConnector extends ImportConnector{
33
34
	/**
35
	 * @brief separates elements from the input stream according to the entry_separator value in config
36
	 * ignoring the first line if mentionned in the config
37
	 * @param $input the input file to import
38
	 * @param $limit the number of elements to return (-1 = no limit)
39
	 * @return array of strings
40
	 */
41
	public function getElementsFromInput($file, $limit=-1) {
42
43
		$parts = $this->getSourceElementsFromFile($file, $limit);
44
		
45
		$elements = array();
46
		foreach($parts as $part)
47
		{
48
			$elements[] = $this->convertElementToVCard($part);
49
		}
50
		
51
		return array_values($elements);
52
	}
53
	
54
	/**
55
	 * @brief parses the file in vcard format
56
	 * @param $file the input file to import
57
	 * @param $limit the number of elements to return (-1 = no limit)
58
	 * @return array()
0 ignored issues
show
Documentation introduced by
The doc-type array() 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...
59
	 */
60
	private function getSourceElementsFromFile($file, $limit=-1) {
61
		$file = StringUtil::convertToUTF8(file_get_contents($file));
62
63
		$nl = "\n";
64
		$replaceFrom = array("\r","\n ");
65
		$replaceTo = array("\n","");
66 View Code Duplication
		foreach ($this->configContent->import_core->replace as $replace) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
			if (isset($replace['from']) && isset($replace['to'])) {
68
				$replaceFrom[] = $replace['from'];
69
				$replaceTo[] = $replace['to'];
70
			}
71
		}
72
		
73
		$file = str_replace($replaceFrom, $replaceTo, $file);
74
		
75
		$lines = explode($nl, $file);
76
		$parts = array();
77
		$card = array();
78
		$numParts = 0;
79
		foreach($lines as $line) {
80
			if (!preg_match("/^#/", $line)) { // Ignore comment line
81
				if(preg_match("/^\w+:: /",$line)) {
82
					$kv = explode(':: ', $line, 2);
83
					$key = $kv[0];
84
					$value = base64_decode($kv[1], true);
85
				} else {
86
					$kv = explode(': ', $line, 2);
87
					$key = $kv[0];
88
					if(count($kv) == 2) {
89
						$value = $kv[1];
90
					} else {
91
						$value = "";
92
					}
93
				}
94
				if ($key == "dn") {
95
					if (count($card) > 0) {
96
						$numParts++;
97
						if ($limit > -1 && count($card) == $limit) {
98
							break;
99
						}
100
						$parts[] = $card;
101
					}
102
					$card = array(array($key, $value));
103
				} else if ($key != "" && $key != "version" && $value != "") {
104
					$card[] = array($key, $value);
105
				}
106
			}
107
		}
108
		if ($numParts <= $limit && count($card) > 0) {
109
			$parts[] = $card;
110
		}
111
		return $parts;
112
	}
113
	
114
	/**
115
	 * @brief converts a ldif into a owncloud VCard
116
	 * @param $element the VCard element to convert
117
	 * @return VCard
118
	 */
119
	public function convertElementToVCard($element) {
120
		$dest = new \OCA\Contacts\VObject\VCard();
0 ignored issues
show
Bug introduced by
The call to VCard::__construct() misses a required argument $name.

This check looks for function calls that miss required arguments.

Loading history...
121
		
122
		foreach ($element as $ldifProperty) {
123
			$importEntry = $this->getImportEntry($ldifProperty[0]);
124
			if ($importEntry) {
125
				$value = $ldifProperty[1];
126
				if (isset($importEntry['remove'])) {
127
					$value = str_replace($importEntry['remove'], '', $ldifProperty[1]);
128
				}
129
				$values = array($value);
130
				if (isset($importEntry['separator'])) {
131
					$values = explode($importEntry['separator'], $value);
132
				}
133
				
134
				foreach ($values as $oneValue) {
135
					$this->convertElementToProperty($oneValue, $importEntry, $dest);
136
				}
137
			} else {
138
				$property = $dest->createProperty("X-Unknown-Element", ''.StringUtil::convertToUTF8($ldifProperty[1]));
139
				$property->add('TYPE', StringUtil::convertToUTF8($ldifProperty[0]));
140
				$dest->add($property);
141
			}
142
		}
143
		
144
		$dest->validate(\Sabre\VObject\Component\VCard::REPAIR);
145
		return $dest;
146
	}
147
	
148
	/**
149
	 * @brief converts an LDIF element into a VCard property
150
	 * and updates the VCard
151
	 * @param $value the LDIF value
152
	 * @param $importEntry the VCard entry to modify
153
	 * @param $dest the VCard to modify (for adding a X-FAVOURITE property)
154
	 */
155
	private function convertElementToProperty($value, $importEntry, &$dest) {
156
		if (isset($importEntry->vcard_favourites)) {
157
			foreach ($importEntry->vcard_favourites as $vcardFavourite) {
158
				if (strcasecmp((string)$vcardFavourite, trim($value)) == 0) {
159
					$property = $dest->createProperty("X-FAVOURITES", 'yes');
160
					$dest->add($property);
161 View Code Duplication
				} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
					$property = $this->getOrCreateVCardProperty($dest, $importEntry->vcard_entry);
163
					if (isset($importEntry['image']) && $importEntry['image'] == "true") {
164
						$this->updateImageProperty($property, $value);
165
					} else {
166
						$this->updateProperty($property, $importEntry, $value);
167
					}
168
				}
169
			}
170 View Code Duplication
		} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
171
			$property = $this->getOrCreateVCardProperty($dest, $importEntry->vcard_entry);
172
			if (isset($importEntry['image']) && $importEntry['image'] == "true") {
173
				$this->updateImageProperty($property, $value);
174
			} else {
175
				$this->updateProperty($property, $importEntry, $value);
176
			}
177
		}
178
	}
179
	
180
	/**
181
	 * @brief tests if the property has to be translated by looking for its signature in the xml configuration
182
	 * @param $property Sabre VObject Property too look
183
	 * @param $vcard the parent Sabre VCard object to look for a 
184
	 */
185
	private function getImportEntry($property) {
186
		foreach ($this->configContent->import_entry as $importEntry) {
187
			if ($importEntry['name'] == $property) {
188
				return $importEntry;
189
			}
190
		}
191
		return false;
192
	}
193
	
194
	/**
195
	 * @brief returns the probability that the first element is a match for this format
196
	 * @param $file the file to examine
197
	 * @return 0 if not a valid ldif file
0 ignored issues
show
Documentation introduced by
The doc-type 0 could not be parsed: Unknown type name "0" at position 0. (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...
198
	 *         1 - 0.5*(number of untranslated elements/total number of elements)
199
	 * The more the first element has untranslated elements, the more the result is close to 0.5
200
	 */
201 View Code Duplication
	public function getFormatMatch($file) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
202
		// Examining the first element only
203
		$parts = $this->getSourceElementsFromFile($file, 1);
204
205
		if (!$parts || count($parts[0]) == 0) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
206
			// Doesn't look like a ldif file
207
			return 0;
208
		} else {
209
			$element = $this->convertElementToVCard($parts[0]);
210
			if ($element) {
211
				$unknownElements = $element->select("X-Unknown-Element");
212
				return (1 - (0.5 * count($unknownElements)/count($parts[0])));
213
			} else {
214
				return 0;
215
			}
216
		}
217
	}	
218
}
219
220
?>
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...
221