Completed
Pull Request — dev (#67)
by
unknown
01:22
created

contentExtensionEntry_relationship_fieldSearch   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 128
Duplicated Lines 12.5 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 22
lcom 0
cbo 0
dl 16
loc 128
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
F view() 16 122 22

How to fix   Duplicated Code   

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:

1
<?php
2
/**
3
 * Copyright: Deux Huit Huit 2017
4
 * LICENCE: MIT https://deuxhuithuit.mit-license.org
5
 */
6
7
require_once(TOOLKIT . '/class.jsonpage.php');
8
9
class contentExtensionEntry_relationship_fieldSearch extends JSONPage
10
{
11
	const MAX_FILTERABLE_FIELDS = 7;
12
	const MAX_RESULT = 10;
13
14
	public function view()
15
	{
16 View Code Duplication
		if (class_exists('FLang')) {
17
			try {
18
				FLang::setMainLang(Lang::get());
19
				FLang::setLangCode(Lang::get(), '');
20
			} catch (Exception $ex) { }
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
21
		}
22
23
		$section = General::sanitize($this->_context[0]);
24
		$sectionId = SectionManager::fetchIDFromHandle($section);
25
		$sectionId = General::intval($sectionId);
26
		$excludes = !isset($this->_context[1]) ? [] : explode(',', General::sanitize($this->_context[1]));
27
28
		if ($sectionId < 1) {
29
			$this->_Result['status'] = Page::HTTP_STATUS_BAD_REQUEST;
30
			$this->_Result['error'] = __('No section id found');
31
			return;
32
		}
33
34
		$section = (new SectionManager)
35
			->select()
36
			->section($sectionId)
37
			->execute()
38
			->next();
39
40 View Code Duplication
		if (empty($section)) {
41
			$this->_Result['status'] = Page::HTTP_STATUS_NOT_FOUND;
42
			$this->_Result['error'] = __('Section not found');
43
			return;
44
		}
45
46
		$query = trim(General::sanitize($_GET['query']));
47
		$entries = array();
48
		$filterableFields = $section->fetchFilterableFields();
49 View Code Duplication
		if (empty($filterableFields)) {
50
			$this->_Result['status'] = Page::HTTP_STATUS_BAD_REQUEST;
51
			$this->_Result['error'] = __('Section not filterable');
52
			return;
53
		}
54
55
		foreach ($filterableFields as $key => $field) {
56
			if ($field instanceof FieldRelationship || $field instanceof FieldDate) {
0 ignored issues
show
Bug introduced by
The class FieldDate 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...
57
				unset($filterableFields[$key]);
58
			}
59
		}
60
		$filterableFields = array_values($filterableFields);
61
		if (count($filterableFields) > self::MAX_FILTERABLE_FIELDS) {
62
			$filterableFields = array_slice($filterableFields, 0, self::MAX_FILTERABLE_FIELDS);
63
		}
64
65
		$primaryField = $section->fetchVisibleColumns();
66
67
		$getId = function ($obj) { return $obj->get('id'); };
68
		$intersection = array_intersect(array_map($getId, $filterableFields), array_map($getId, $primaryField));
69
70
		if (empty($primaryField)) {
71
			$primaryField = current($filterableFields);
72
			reset($filterableFields);
73
		} else {
74
			$primaryField = current($primaryField);
75
		}
76
77
		foreach ($filterableFields as $field) {
78
			if (!empty($intersection) && !in_array($field->get('id'), $intersection)) {
79
				continue;
80
			}
81
			$q = (new EntryManager)
82
				->select()
83
				->sort('system:id', 'asc')
84
				->schema([$primaryField->get('element_name')])
85
				->section($sectionId)
86
				->disableDefaultSort()
87
				->limit(self::MAX_RESULT);
88
89
			if (!empty($query)) {
90
				try {
91
					$opt = array_map(function ($op) {
92
						return trim($op['filter']);
93
					}, $field->fetchFilterableOperators());
94
					if (in_array('contains:', $opt)) {
95
						$q->filter($field, ['contains: ' . $query . '%']);
96
					} elseif (in_array('regexp:', $opt)) {
97
						$q->filter($field, ['regexp: ' . $query]);
98
					} else {
99
						$q->filter($field, [$query]);
100
					}
101
				} catch (DatabaseStatementException $ex) {
0 ignored issues
show
Bug introduced by
The class DatabaseStatementException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
102
					continue;
103
				}
104
			}
105
106
			if (!empty($excludes)) {
107
				$q->filter('system:id', ['not:' . implode(',', $excludes)]);
108
			}
109
110
			$fEntries = $q
111
				->execute()
112
				->rows();
113
114
			if (!empty($fEntries)) {
115
				$entries = array_merge($entries, $fEntries);
116
				$excludes = array_merge($excludes, array_map($getId, $fEntries));
117
			}
118
119
			if (count($entries) > self::MAX_RESULT) {
120
				break;
121
			}
122
		}
123
124
		$entries = array_map(function ($entry) use ($primaryField) {
125
			return array(
126
				'value' => $entry->get('id') . ':' .
127
					$primaryField->prepareReadableValue(
128
						$entry->getData($primaryField->get('id')),
129
						$entry->get('id')
130
				),
131
			);
132
		}, $entries);
133
134
		$this->_Result['entries'] = $entries;
135
	}
136
}
137