ImportVCardConnector::getSourceElementsFromFile()   D
last analyzed

Complexity

Conditions 10
Paths 24

Size

Total Lines 39
Code Lines 29

Duplication

Lines 6
Ratio 15.38 %

Code Coverage

Tests 0
CRAP Score 110
Metric Value
dl 6
loc 39
ccs 0
cts 36
cp 0
rs 4.8196
cc 10
eloc 29
nc 24
nop 2
crap 110

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * ownCloud - VCard 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
	Sabre\VObject\StringUtil,
27
	\SplFileObject as SplFileObject,
28
	Sabre\VObject;
29
30
/**
31
 * @brief Implementation of the VCard import format
32
 */
33
class ImportVCardConnector extends ImportConnector{
34
35
	/**
36
	 * @brief separates elements from the input stream according to the entry_separator value in config
37
	 * ignoring the first line if mentionned in the config
38
	 * @param $input the input file to import
39
	 * @param $limit the number of elements to return (-1 = no limit)
40
	 * @return array of strings
41
	 */
42
	public function getElementsFromInput($file, $limit=-1) {
43
44
		$parts = $this->getSourceElementsFromFile($file, $limit);
45
		
46
		$elements = array();
47
		foreach($parts as $part) {
48
			$converted = $this->convertElementToVCard($part);
49
			if ($converted) {
50
				$elements[] = $converted;
51
			}
52
		}
53
		
54
		return array_values($elements);
55
	}
56
	
57
	/**
58
	 * @brief parses the file in vcard format
59
	 * @param $file the input file to import
60
	 * @param $limit the number of elements to return (-1 = no limit)
61
	 * @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...
62
	 */
63
	private function getSourceElementsFromFile($file, $limit=-1) {
64
		$file = StringUtil::convertToUTF8(file_get_contents($file));
65
66
		$nl = "\n";
67
		$replaceFrom = array("\r","\n\n");
68
		$replaceTo = array("\n","\n");
69 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...
70
			if (isset($replace['from']) && isset($replace['to'])) {
71
				$replaceFrom[] = $replace['from'];
72
				$replaceTo[] = $replace['to'];
73
			}
74
		}
75
		
76
		$file = str_replace($replaceFrom, $replaceTo, $file);
77
		
78
		$lines = explode($nl, $file);
79
		$inelement = false;
80
		$parts = array();
81
		$card = array();
82
		$numParts = 0;
83
		foreach($lines as $line) {
84
				if(strtoupper(trim($line)) == (string)$this->configContent->import_core->card_begin) {
85
						$inelement = true;
86
				} elseif (strtoupper(trim($line)) == (string)$this->configContent->import_core->card_end) {
87
						$card[] = $line;
88
						$parts[] = implode($nl, $card);
89
						$card = array();
90
						$inelement = false;
91
						$numParts++;
92
						if ($numParts == $limit) {
93
							break;
94
						}
95
				}
96
				if ($inelement === true && trim($line) != '') {
97
						$card[] = $line;
98
				}
99
		}
100
		return $parts;
101
	}
102
	
103
	/**
104
	 * @brief converts a VCard into a owncloud VCard
105
	 * @param $element the VCard element to convert
106
	 * @return VCard|false
107
	 */
108
	public function convertElementToVCard($element) {
109
		try {
110
			$source = VObject\Reader::read($element, VObject\Reader::OPTION_FORGIVING);
111
		} catch (VObject\ParseException $error) {
112
			return false;
113
		}
114
		$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...
115
		
116
		foreach ($source->children() as $sourceProperty) {
0 ignored issues
show
Bug introduced by
The method children does only exist in Sabre\VObject\Component, but not in Sabre\VObject\Property.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
117
			$importEntry = $this->getImportEntry($sourceProperty, $source);
118
			if ($importEntry) {
119
				$value = $sourceProperty->getValue();
120
				if (isset($importEntry['remove'])) {
121
					$value = str_replace($importEntry['remove'], '', $sourceProperty->getValue());
122
				}
123
				$values = array($value);
124
				if (isset($importEntry['separator'])) {
125
					$values = explode($importEntry['separator'], $value);
126
				}
127
				
128 View Code Duplication
				foreach ($values as $oneValue) {
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...
129
					if (isset($importEntry->vcard_favourites)) {
130
						foreach ($importEntry->vcard_favourites as $vcardFavourite) {
131
							if (strcasecmp((string)$vcardFavourite, trim($oneValue)) == 0) {
132
								$property = $dest->createProperty("X-FAVOURITES", 'yes');
133
								$dest->add($property);
134
							} else {
135
								$property = $this->getOrCreateVCardProperty($dest, $importEntry->vcard_entry);
136
								$this->updateProperty($property, $importEntry, trim($oneValue));
137
							}
138
						}
139
					} else {
140
						$property = $this->getOrCreateVCardProperty($dest, $importEntry->vcard_entry);
141
						$this->updateProperty($property, $importEntry, $sourceProperty->getValue());
142
					}
143
				}
144
			} else {
145
				$property = clone $sourceProperty;
146
				// VERSION and PRODID are set by default in any new empty vcard object.
147
				// Thus it needs to be replaced instead of simply added as additional value.
148
				if ( $property->name === 'PRODID' || $property->name === 'VERSION' ) {
149
					$dest->__set($property->name, $property);
150
				} else {
151
					$dest->add($property);
152
				}
153
			}
154
		}
155
		
156
		$dest->validate(\Sabre\VObject\Component\VCard::REPAIR);
157
		return $dest;
158
	}
159
	
160
	/**
161
	 * @brief tests if the property has to be translated by looking for its signature in the xml configuration
162
	 * @param $property Sabre VObject Property too look
163
	 * @param $vcard the parent Sabre VCard object to look for a 
164
	 */
165
	private function getImportEntry($property, $vcard) {
166
		$nbElt = $this->configContent->import_entry->count();
167
		for ($i=0; $i < $nbElt; $i++) {
168
			if ($this->configContent->import_entry[$i]['property'] == $property->name && $this->configContent->import_entry[$i]['enabled'] == 'true') {
169
				if (isset($this->configContent->import_entry[$i]->group_entry)) {
170
					$numElt = 0;
171
					foreach($this->configContent->import_entry[$i]->group_entry as $groupEntry) {
172
						$sourceGroupList = $vcard->select($groupEntry['property']);
173
						if (count($sourceGroupList>0)) {
174
							foreach ($sourceGroupList as $oneSourceGroup) {
175
								if ($oneSourceGroup->getValue() == $groupEntry['value'] && isset($oneSourceGroup->group) && isset($property->group) && $oneSourceGroup->group == $property->group) {
176
									$numElt++;
177
								}
178
							}
179
						}
180
					}
181
					if ($numElt == count($this->configContent->import_entry[$i]->group_entry)) {
182
						return $this->configContent->import_entry[$i];
183
					}
184
				} else {
185
					return $this->configContent->import_entry[$i];
186
				}
187
			}
188
		}
189
		return false;
190
	}
191
	
192
	/**
193
	 * @brief returns the probability that the first element is a match for this format
194
	 * @param $file the file to examine
195
	 * @return 0 if not a valid vcard
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...
196
	 *         1-0.5^(number of translated elements+1)
197
	 * The more the first element has parameters to translate, the more the result is close to 1
198
	 */
199 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...
200
		// Examining the first element only
201
		$parts = $this->getSourceElementsFromFile($file, 1);
202
		
203
		if (!$parts || ($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...
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...
204
			// Doesn't look like a vcf file
205
			return 0;
206
		} else {
207
			$element = $this->convertElementToVCard($parts[0]);
208
			if ($element) {
209
				$unknownElements = $element->select("X-Unknown-Element");
210
				return (1 - (0.5 * count($unknownElements)/count($parts[0])));
211
			} else {
212
				return 0;
213
			}
214
		}
215
	}
216
	
217
}
218
219
?>
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...
220