ImportCsvConnector   C
last analyzed

Complexity

Total Complexity 57

Size/Duplication

Total Lines 213
Duplicated Lines 10.33 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 2 Features 0
Metric Value
wmc 57
lcom 1
cbo 3
dl 22
loc 213
ccs 0
cts 147
cp 0
rs 6.433
c 2
b 2
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getImportEntryFromPosition() 3 9 4
A getElementsFromInput() 0 12 2
C getSourceElementsFromFile() 0 60 21
C convertElementToVCard() 16 52 16
B getImportEntryFromName() 3 16 8
B getFormatMatch() 0 21 6

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 ImportCsvConnector 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 ImportCsvConnector, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * ownCloud - CSV Import connector
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
23
namespace OCA\Contacts\Connector;
24
25
use Sabre\VObject\Component;
26
use \SplFileObject as SplFileObject;
27
use Sabre\VObject\StringUtil;
28
29
/**
30
 * @brief Implementation of the Import class for CSV format
31
 * Doesn't really like csv that has fields with new lines in it, beware !
32
 */
33
class ImportCsvConnector 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 $file the input file to import
39
	 * @param $limit the number of elements to return (-1 = no limit)
40
	 * @return array(array(data), array(titles))
0 ignored issues
show
Documentation introduced by
The doc-type array(array(data), 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...
41
	 */
42
	public function getElementsFromInput($file, $limit=-1) {
43
44
		$linesAndTitles = $this->getSourceElementsFromFile($file, $limit);
45
		$lines = $linesAndTitles[0];
46
		$titles = $linesAndTitles[1];
47
		$elements = array();
48
		foreach ($lines as $line) {
49
			$elements[] = $this->convertElementToVCard($line, $titles);
50
		}
51
52
		return array_values($elements);
53
	}
54
55
	/**
56
	 * @brief parses the file in csv format
57
	 * @param $file the input file to import
58
	 * @param $limit the number of elements to return (-1 = no limit)
59
	 * @return array(array(data), array(titles))
0 ignored issues
show
Documentation introduced by
The doc-type array(array(data), 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...
60
	 */
61
	private function getSourceElementsFromFile($file, $limit=-1) {
62
		if (file_put_contents($file, StringUtil::convertToUTF8(file_get_contents($file)))) {
63
			$csv = new SplFileObject($file, 'r');
64
			$csv->setFlags(SplFileObject::READ_CSV);
65
66
			$delimiter = '';
67
			if (isset($this->configContent->import_core->delimiter)) {
68
				$delimiter = (string)$this->configContent->import_core->delimiter;
69
			} else {
70
				// Look for the delimiter in the first line, should be the most present character between ',', ';' and '\t'
71
				$splFile = new SplFileObject($file);
72
				$firstLine = $splFile->fgets();
73
				$nbComma = substr_count($firstLine, ',');
74
				$nbSemicolon = substr_count($firstLine, ';');
75
				$nbTab = substr_count($firstLine, "\t");
76
				if ($nbComma > $nbSemicolon && $nbComma > $nbTab) {
77
					// Comma it is
78
					$delimiter = ',';
79
				} else if ($nbSemicolon > $nbComma && $nbSemicolon > $nbTab) {
80
					// Semicolon it is
81
					$delimiter = ';';
82
				} else if ($nbTab > $nbComma && $nbTab > $nbSemicolon) {
83
					// Tab it is
84
					$delimiter = "\t";
85
				} else if ($nbTab == 0 && $nbComma == 0 && $nbSemicolon == 0) {
86
					// We have a problem, no delimiter found
87
					return array(array(), array());
88
				}
89
			}
90
			$csv->setCsvControl($delimiter, "\"", "\\");
91
92
			$ignoreFirstLine = (isset($this->configContent->import_core->ignore_first_line)
93
									&& (((string)$this->configContent->import_core->ignore_first_line) == 'true')
94
										|| ((string)$this->configContent->import_core->ignore_first_line) == '1');
95
96
			$titles = false;
97
98
			$lines = array();
99
100
			$index = 0;
101
			foreach($csv as $line) {
102
				if (!($ignoreFirstLine && $index == 0) && count($line) > 1) { // Ignore first line
103
104
					$lines[] = $line;
105
106
					if (count($lines) == $limit) {
107
						break;
108
					}
109
				} else if ($ignoreFirstLine && $index == 0) {
110
					$titles = $line;
111
				}
112
				$index++;
113
			}
114
115
			return array($lines, $titles);
116
		} else {
117
			error_log("Error converting file to utf8");
118
			return array(array(), array());
119
		}
120
	}
121
122
	/**
123
	 * @brief converts a unique element into a owncloud VCard
124
	 * @param $element the element to convert
125
	 * @return VCard, all unconverted elements are stored in X-Unknown-Element parameters
0 ignored issues
show
Documentation introduced by
The doc-type VCard, 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...
126
	 */
127
	public function convertElementToVCard($element, $title = null) {
128
		$vcard = 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...
129
130
		$nbElt = count($element);
131
		for ($i=0; $i < $nbElt; $i++) {
132
			if ($element[$i] != '') {
133
				//$importEntry = false;
134
				// Look for the right import_entry
135
				if (isset($this->configContent->import_core->base_parsing)) {
136
					if (strcasecmp((string)$this->configContent->import_core->base_parsing, 'position') == 0) {
137
						$importEntry = $this->getImportEntryFromPosition((String)$i);
138
					} else if (strcasecmp((string)$this->configContent->import_core->base_parsing, 'name') == 0 && isset($title[$i])) {
139
						$importEntry = $this->getImportEntryFromName($title[$i]);
140
					}
141
				}
142
				if ($importEntry) {
143
					// Create a new property and attach it to the vcard
144
					$value = $element[$i];
145
					if (isset($importEntry['remove'])) {
146
						$value = str_replace($importEntry['remove'], '', $element[$i]);
147
					}
148
					$values = array($value);
149
					if (isset($importEntry['separator'])) {
150
						$values = explode($importEntry['separator'], $value);
151
					}
152
					
153 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...
154
						if (isset($importEntry->vcard_favourites)) {
155
							foreach ($importEntry->vcard_favourites as $vcardFavourite) {
156
								if (strcasecmp((string)$vcardFavourite, trim($oneValue)) == 0) {
157
									$property = $vcard->createProperty("X-FAVOURITES", 'yes');
158
									$vcard->add($property);
159
								} else {
160
									$property = $this->getOrCreateVCardProperty($vcard, $importEntry->vcard_entry);
0 ignored issues
show
Bug introduced by
The variable $importEntry does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
161
									$this->updateProperty($property, $importEntry, trim($oneValue));
162
								}
163
							}
164
						} else {
165
							$property = $this->getOrCreateVCardProperty($vcard, $importEntry->vcard_entry);
166
							$this->updateProperty($property, $importEntry, trim($oneValue));
167
						}
168
					}
169
				} else if (isset($element[$i]) && isset($title[$i])) {
170
					$property = $vcard->createProperty("X-Unknown-Element", StringUtil::convertToUTF8($element[$i]));
171
					$property->add('TYPE', StringUtil::convertToUTF8($title[$i]));
172
					$vcard->add($property);
173
				}
174
			}
175
		}
176
		$vcard->validate(\Sabre\VObject\Component\VCard::REPAIR);
177
		return $vcard;
178
	}
179
180
	/**
181
	 * @brief gets the import entry corresponding to the position given in parameter
182
	 * @param string $position the position to look for in the connector
183
	 * @return int|false
184
	 */
185
	private function getImportEntryFromPosition($position) {
186
		$nbElt = $this->configContent->import_entry->count();
187
		for ($i=0; $i < $nbElt; $i++) {
188 View Code Duplication
			if ($this->configContent->import_entry[$i]['position'] == $position && $this->configContent->import_entry[$i]['enabled'] == 'true') {
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...
189
				return $this->configContent->import_entry[$i];
190
			}
191
		}
192
		return false;
193
	}
194
195
	/**
196
	 * @brief gets the import entry corresponding to the name given in parameter
197
	 * @param $name the parameter name to look for in the connector
198
	 * @return string|false
199
	 */
200
	private function getImportEntryFromName($name) {
201
		$nbElt = $this->configContent->import_entry->count();
202
		for ($i=0; $i < $nbElt; $i++) {
203 View Code Duplication
			if ($this->configContent->import_entry[$i]['name'] == StringUtil::convertToUTF8($name) && $this->configContent->import_entry[$i]['enabled'] == 'true') {
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...
204
				return $this->configContent->import_entry[$i];
205
			}
206
			if (isset($this->configContent->import_entry[$i]->altname)) {
207
				foreach ($this->configContent->import_entry[$i]->altname as $altname) {
208
					if ($altname == StringUtil::convertToUTF8($name) && $this->configContent->import_entry[$i]['enabled'] == 'true') {
209
						return $this->configContent->import_entry[$i];
210
					}
211
				}
212
			}
213
		}
214
		return false;
215
	}
216
217
	/**
218
	 * @brief returns the probability that the first element is a match for this format
219
	 * @param $file the file to examine
220
	 * @return 0 if not a valid csv 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...
221
	 *         1 - 0.5*(number of untranslated elements/total number of elements)
222
	 * The more the first element has untranslated elements, the more the result is close to 0.5
223
	 */
224
	public function getFormatMatch($file) {
225
		// Examining the first element only
226
		$partsAndTitle = $this->getSourceElementsFromFile($file, 1);
227
		$parts = $partsAndTitle[0];
228
		$titles = $partsAndTitle[1];
229
230
		if (!$parts || ($parts && isset($this->configContent->import_core->expected_columns)
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...
231
			&& count($parts[0]) != (string)$this->configContent->import_core->expected_columns)
232
		) {
233
			// Doesn't look like a csv file
234
			return 0;
235
		} else {
236
			$element = $this->convertElementToVCard($parts[0], $titles);
237
			if ($element) {
238
				$unknownElements = $element->select("X-Unknown-Element");
239
				return (1 - (0.5 * count($unknownElements)/count($parts[0])));
240
			} else {
241
				return 0;
242
			}
243
		}
244
	}
245
}
246
247
?>
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...
248