Completed
Push — 7LTS_compatible ( b51d35...40d99a )
by Tomas Norre
32:08
created

ElementFactory   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 267
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 44
lcom 1
cbo 4
dl 0
loc 267
rs 8.3396
c 1
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
C getElementForTable() 0 63 17
A getWorkspaceOverlay() 0 18 4
C getParentElementsFromElement() 0 28 7
B getOverlayedRootLine() 0 58 8
B _getTVDS() 0 26 6
A getElementInstance() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like ElementFactory 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 ElementFactory, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace AOE\Languagevisibility;
4
5
/***************************************************************
6
 *  Copyright notice
7
 *
8
 *  (c) 2014 AOE GmbH <[email protected]>
9
 *
10
 *  All rights reserved
11
 *
12
 *  This script is part of the TYPO3 project. The TYPO3 project is
13
 *  free software; you can redistribute it and/or modify
14
 *  it under the terms of the GNU General Public License as published by
15
 *  the Free Software Foundation; either version 3 of the License, or
16
 *  (at your option) any later version.
17
 *
18
 *  The GNU General Public License can be found at
19
 *  http://www.gnu.org/copyleft/gpl.html.
20
 *
21
 *  This script is distributed in the hope that it will be useful,
22
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 *  GNU General Public License for more details.
25
 *
26
 *  This copyright notice MUST APPEAR in all copies of the script!
27
 ***************************************************************/
28
use AOE\Languagevisibility\Services\FeServices;
29
30
/**
31
 * Class tx_languagevisibility_elementFactory
32
 */
33
class ElementFactory {
34
35
	/**
36
	 * @var tx_languagevisibility_daocommon
37
	 */
38
	protected $dao;
39
40
	/**
41
	 * Dependency is injected, this object needs a simple Data Access Object (can be replaced in testcase)
42
	 */
43
	public function __construct($dao) {
44
		$this->dao = $dao;
45
	}
46
47
	/**
48
	 * Returns ready initialised "element" object. Depending on the element the correct element class is used. (e.g. page/content/fce)
49
	 *
50
	 * @param string $table table
51
	 * @param int $uid identifier
52
	 * @param bool $overlay_ids boolean parameter to overlay uids if the user is in workspace context
53
	 * @throws UnexpectedValueException
54
	 * @return Element
55
	 */
56
	public function getElementForTable($table, $uid, $overlay_ids = TRUE) {
57
58
		if (!FeServices::isSupportedTable($table)) {
59
			throw new UnexpectedValueException($table . ' not supported ', 1195039394);
60
		}
61
62
		if (!is_numeric($uid) || (intval($uid) === 0)) {
63
				// no uid => maybe NEW element in BE
64
			$row = array();
65
		} else {
66
			if (is_object($GLOBALS['BE_USER']) && $GLOBALS['BE_USER']->workspace != 0 && $overlay_ids) {
67
				$row = $this->getWorkspaceOverlay($table, $uid);
68
			} else {
69
				$row = $this->dao->getRecord($uid, $table);
70
			}
71
		}
72
73
		/** @var Element $element */
74
		switch ($table) {
75
			case 'pages':
76
				$element = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('\\AOE\\Languagevisibility\\PageElement', $row, $table);
77
				break;
78
			case 'tt_news':
79
				$element = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('\\AOE\\Languagevisibility\\PageElement', $row, $table);
80
				break;
81
			case 'tt_content':
82
				if ($row['CType'] == 'templavoila_pi1') {
83
						// read DS:
84
					$srcPointer = $row['tx_templavoila_ds'];
85
					$DS = $this->_getTVDS($srcPointer);
86
					if (is_array($DS)) {
87
						if ($DS['meta']['langDisable'] == 1 && $DS['meta']['langDatabaseOverlay'] == 1) {
88
								// handle as special FCE with normal tt_content overlay:
89
							$element = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_languagevisibility_fceoverlayelement', $row);
90
						} else {
91
							$element = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_languagevisibility_fceelement', $row, $DS);
92
						}
93
					} else {
94
						throw new UnexpectedValueException($table . ' uid:' . $row['uid'] . ' has no valid Datastructure ', 1195039394);
95
					}
96
				} else {
97
					$element = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_languagevisibility_celement', $row, $table);
98
				}
99
				break;
100
			default:
101
102
				if (isset ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['languagevisibility']['getElementForTable'][$table])) {
103
					$hookObj = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['languagevisibility']['getElementForTable'][$table]);
104
					if (method_exists($hookObj, 'getElementForTable')) {
105
						$element = $hookObj->getElementForTable($table, $uid, $row, $overlay_ids);
106
					}
107
				} elseif (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['languagevisibility']['recordElementSupportedTables'][$table])) {
108
					$element = $this->getElementInstance('tx_languagevisibility_recordelement', $row, $table);
0 ignored issues
show
Unused Code introduced by
The call to ElementFactory::getElementInstance() has too many arguments starting with $table.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
109
				} else {
110
					throw new UnexpectedValueException($table . ' not supported ', 1195039394);
111
				}
112
				break;
113
		}
114
115
		$element->setTable($table);
0 ignored issues
show
Bug introduced by
The variable $element 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...
116
117
		return $element;
118
	}
119
120
	/**
121
	 * Get workspace overlay for a record.
122
	 *
123
	 * @param  string  $table   Table name
124
	 * @param  integer $uid     Record UID
125
	 * @return array
126
	 */
127
	protected function getWorkspaceOverlay($table, $uid) {
128
		$row = $this->dao->getRecord($uid, $table);
129
130
		if (is_array($row)) {
131
			if (is_object($GLOBALS['TSFE'])) {
132
				$GLOBALS['TSFE']->sys_page->versionOL($table, $row);
133
			} else {
134
				\TYPO3\CMS\Backend\Utility\BackendUtility::workspaceOL($table, $row);
135
			}
136
		}
137
			// the overlay row might be FALSE if the record is hidden
138
			// or deleted in workspace. In this case we return an empty array.
139
		if (!is_array($row)) {
140
			$row = array();
141
		}
142
143
		return $row;
144
	}
145
146
	/**
147
	 * This method is used to retrieve all parent elements (an parent elements needs to
148
	 * have the flag 'tx_languagevisibility_inheritanceflag_original' or
149
	 * needs to be orverlayed with a record, that has the field 'tx_languagevisibility_inheritanceflag_overlayed'
150
	 * configured or is the first element of the rootline
151
	 *
152
	 * @param tx_languagevisibility_element $element
153
	 * @param $language
154
	 * @return array $elements (collection of tx_languagevisibility_element)
155
	 */
156
	public function getParentElementsFromElement(Element $element, $language) {
157
		$elements = array();
158
159
		if ($element instanceof PageElement) {
160
			/* @var $sys_page \TYPO3\CMS\Frontend\Page\PageRepository */
161
			$rootline = $this->getOverlayedRootLine($element->getUid(), $language->getUid());
162
163
			if (is_array($rootline)) {
164
				foreach ($rootline as $rootlineElement) {
165
					if ($rootlineElement['tx_languagevisibility_inheritanceflag_original'] == 1 ||
166
							$rootlineElement['tx_languagevisibility_inheritanceflag_overlayed'] == 1
167
					) {
168
						$elements[] = self::getElementForTable('pages', $rootlineElement['uid']);
169
					}
170
				}
171
172
				if (sizeof($elements) == 0) {
173
					$root = end($rootline);
174
					$elements[] = self::getElementForTable('pages', $root['uid']);
175
				}
176
			}
177
		} else {
178
			$parentPage = $this->getElementForTable('pages', $element->getUid());
179
			$elements = $this->getParentElementsFromElement($parentPage, $language);
180
		}
181
182
		return $elements;
183
	}
184
185
	/**
186
	 * This method is needed because the getRootline method from \TYPO3\CMS\Frontend\Page\PageRepository causes an error when
187
	 * getRootline is called be cause getRootline internally uses languagevisibility to determine the
188
	 * visibility during the rootline calculation. This results in an unlimited recursion.
189
	 *
190
	 * @todo The rooline can be build in a smarter way, once the rootline for a page has been created
191
	 * same parts of the rootline not have to be calculated twice.
192
	 * @param $uid
193
	 * @param $languageid
194
	 * @return array
195
	 * @internal param \The $integer page uid for which to seek back to the page tree root.
196
	 * @see tslib_fe::getPageAndRootline()
197
	 */
198
	protected function getOverlayedRootLine($uid, $languageid) {
199
		$cacheManager = CacheManager::getInstance();
200
201
		$cacheData = $cacheManager->get('overlayedRootline');
202
		$isCacheEnabled = $cacheManager->isCacheEnabled();
203
204
		if (!$isCacheEnabled || !isset($cacheData[$uid][$languageid])) {
205
			$sys_page = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('\TYPO3\CMS\Frontend\Page\PageRepository');
206
			$sys_page->sys_language_uid = $languageid;
207
208
			$uid = intval($uid);
209
210
				// Initialize:
211
			$selFields = \TYPO3\CMS\Core\Utility\GeneralUtility::uniqueList('pid,uid,t3ver_oid,t3ver_wsid,t3ver_state,title,alias,nav_title,media,layout,hidden,starttime,endtime,fe_group,extendToSubpages,doktype,TSconfig,storage_pid,is_siteroot,mount_pid,mount_pid_ol,fe_login_mode,' . $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']);
212
213
			$loopCheck = 0;
214
			$theRowArray = Array();
215
216
			while ($uid != 0 && $loopCheck < 20) { // Max 20 levels in the page tree.
217
218
				$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($selFields, 'pages', 'uid=' . intval($uid) . ' AND pages.deleted=0 AND pages.doktype!=255');
219
				$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
220
				$GLOBALS['TYPO3_DB']->sql_free_result($res);
221
222
				if ($row) {
223
					$sys_page->versionOL('pages', $row, FALSE, TRUE);
224
					$sys_page->fixVersioningPid('pages', $row);
225
226
					if (is_array($row)) {
227
							// Mount Point page types are allowed ONLY a) if they are the outermost record in rootline and b) if the overlay flag is not set:
228
						$uid = $row['pid']; // Next uid
229
					}
230
						// Add row to rootline with language overlaid:
231
					$langvisHook = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay']['languagevisility'];
232
					unset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay']['languagevisility']);
233
					$theRowArray[] = $sys_page->getPageOverlay($row, $languageid);
234
					$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay']['languagevisility'] = $langvisHook;
235
				} else {
236
					return array(); // broken rootline.
237
				}
238
239
				$loopCheck++;
240
			}
241
242
				// Create output array (with reversed order of numeric keys):
243
			$output = Array();
244
			$c = count($theRowArray);
245
			foreach ($theRowArray as $key => $val) {
246
				$c--;
247
				$output[$c] = $val;
248
			}
249
250
			$cacheData[$uid][$languageid] = $output;
251
			$cacheManager->set('overlayedRootline', $cacheData);
252
		}
253
254
		return $cacheData[$uid][$languageid];
255
	}
256
257
	/**
258
	 * Determines the dataStructure from a given sourcePointer.
259
	 *
260
	 * @param $srcPointer
261
	 * @return array
262
	 */
263
	protected function _getTVDS($srcPointer) {
264
		$cacheManager = CacheManager::getInstance();
265
266
		$cacheData = $cacheManager->get('dataStructureCache');
267
		$isCacheEnabled = $cacheManager->isCacheEnabled();
268
269
		if (!$isCacheEnabled || !isset($cacheData[$srcPointer])) {
270
			$DS = array();
271
			$srcPointerIsInteger = \TYPO3\CMS\Core\Utility\MathUtility::convertToPositiveInteger($srcPointer);
272
			if ($srcPointerIsInteger) { // If integer, then its a record we will look up:
273
				$sys_page = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('\TYPO3\CMS\Frontend\Page\PageRepository');
274
				$DSrec = $sys_page->getRawRecord('tx_templavoila_datastructure', $srcPointer, 'dataprot');
275
				$DS = \TYPO3\CMS\Core\Utility\GeneralUtility::xml2array($DSrec['dataprot']);
276
			} else { // Otherwise expect it to be a file:
277
				$file = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($srcPointer);
278
				if ($file && @is_file($file)) {
279
					$DS = \TYPO3\CMS\Core\Utility\GeneralUtility::xml2array(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($file));
280
				}
281
			}
282
283
			$cacheData[$srcPointer] = $DS;
284
			$cacheManager->set('dataStructureCache', $cacheData);
285
		}
286
287
		return $cacheData[$srcPointer];
288
	}
289
290
	/**
291
	 * Gets instance depending on TYPO3 version
292
	 * @param $name name of the class
293
	 * @param array $row row that is used to initialaze element instance
294
	 * @return tx_languagevisibility_element
295
	 */
296
	private function getElementInstance($name, $row) {
297
		return \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($name, $row);
298
	}
299
}
300