Completed
Push — master ( e5616c...ad2eea )
by Roberto
03:41
created

Component   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 200
Duplicated Lines 2 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 51.67%

Importance

Changes 0
Metric Value
wmc 19
lcom 2
cbo 2
dl 4
loc 200
ccs 31
cts 60
cp 0.5167
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
A clearInstance() 0 4 1
A getActiveComponent() 0 4 1
A getInstance() 4 14 3
A getPrefix() 0 17 2
A getTable() 0 19 3
A loadExtension() 0 13 2
A loadParams() 0 4 1
B saveParams() 0 23 4

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 21 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Joomla! common library.
4
 *
5
 * @copyright  Copyright (C) 2017 Roberto Segura López, Inc. All rights reserved.
6
 * @license    GNU/GPL 2, http://www.gnu.org/licenses/gpl-2.0.htm
7
 */
8
9
namespace Phproberto\Joomla\Component;
10
11
use Joomla\Registry\Registry;
12
use Phproberto\Joomla\Traits;
13
14 1
defined('JPATH_PLATFORM') || die;
15
16
/**
17
 * Table finder.
18
 *
19
 * @since  __DEPLOY_VERSION__
20
 */
21
class Component
22
{
23
	use Traits\HasExtension, Traits\HasParams;
24
25
	/**
26
	 * Component option. Example: com_content
27
	 *
28
	 * @var  string
29
	 */
30
	protected $option;
31
32
	/**
33
	 * Component prefix for classes, etc.
34
	 *
35
	 * @var  string
36
	 */
37
	protected $prefix;
38
39
	/**
40
	 * Cached instances.
41
	 *
42
	 * @var  array
43
	 */
44
	protected static $instances = array();
45
46
	/**
47
	 * Constructor
48
	 *
49
	 * @param   string  $option  Component option
50
	 */
51 3
	public function __construct($option)
52
	{
53 3
		$option = trim(strtolower($option));
54
55 3
		if (empty($option))
56
		{
57
			throw new \InvalidArgumentException(__CLASS__ . ': Empty component option.');
58
		}
59
60 3
		$this->option = $option;
61 3
	}
62
63
	/**
64
	 * Clear a singleton instance.
65
	 *
66
	 * @param   string  $option  Component option
67
	 *
68
	 * @return  void
69
	 */
70 1
	public static function clearInstance($option)
71
	{
72 1
		unset(static::$instances[get_called_class()][$option]);
73 1
	}
74
75
	/**
76
	 * Get the active component. Mainly for testing purposes.
77
	 *
78
	 * @return  string
79
	 */
80
	protected static function getActiveComponent()
81
	{
82
		return \JApplicationHelper::getComponentName();
83
	}
84
85
	/**
86
	 * Get a singleton instance.
87
	 *
88
	 * @param   string  $option  Component option
89
	 *
90
	 * @return  $this
91
	 */
92 4
	public static function getInstance($option = null)
93
	{
94 4
		$option = trim(strtolower($option));
95 4
		$option = $option ?: static::getActiveComponent();
96
97 4
		$class = get_called_class();
98
99 4 View Code Duplication
		if (empty(static::$instances[$class][$option]))
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...
100
		{
101 3
			static::$instances[$class][$option] = new static($option);
102
		}
103
104 4
		return static::$instances[$class][$option];
105
	}
106
107
	/**
108
	 * Get the component prefix.
109
	 *
110
	 * @return  string
111
	 */
112 4
	public function getPrefix()
113
	{
114 4
		if (null === $this->prefix)
115
		{
116 4
			$parts = array_map(
117 4
				function ($part)
118
				{
119 4
					return ucfirst(strtolower($part));
120 4
				},
121 4
				explode('_', substr($this->option, 4))
122
			);
123
124 4
			$this->prefix = implode('_', $parts);
125
		}
126
127 4
		return $this->prefix;
128
	}
129
130
	/**
131
	 * Get a component table.
132
	 *
133
	 * @param   string   $name     Name of the table to load. Example: Article
134
	 * @param   array    $config   Optional array of configuration for the table
135
	 * @param   boolean  $backend  Search in backend folder?
136
	 *
137
	 * @return  \JTable
138
	 *
139
	 * @throws  \InvalidArgumentException  If table not found
140
	 */
141 1
	public function getTable($name, array $config = array(), $backend = true)
142
	{
143 1
		$prefix = $this->getPrefix() . 'Table';
144
145 1
		$baseFolder = $backend ? JPATH_ADMINISTRATOR : JPATH_SITE;
146
147 1
		\JTable::addIncludePath($baseFolder . '/components/' . $this->option . '/tables');
148
149 1
		$table = \JTable::getInstance($name, $prefix, $config);
150
151 1
		if (!$table instanceof \JTable)
0 ignored issues
show
Bug introduced by
The class JTable 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...
152
		{
153
			throw new \InvalidArgumentException(
154
				sprintf('Cannot find the table %s in component %s.', $prefix . $name, $this->option)
155
			);
156
		}
157
158 1
		return $table;
159
	}
160
161
	/**
162
	 * Load extension from DB.
163
	 *
164
	 * @return  \stdClass
165
	 */
166
	protected function loadExtension()
167
	{
168
		$db = \JFactory::getDbo();
169
		$query = $db->getQuery(true)
170
			->select('*')
171
			->from('#__extensions')
172
			->where('type = ' . $db->quote('component'))
173
			->where('element = ' . $db->q($this->option));
174
175
		$db->setQuery($query);
176
177
		return $db->loadObject() ?: new \stdClass;
178
	}
179
180
	/**
181
	 * Load parameters from database.
182
	 *
183
	 * @return  Registry
184
	 */
185
	protected function loadParams()
186
	{
187
		return new Registry($this->getExtensionProperty('params', array()));
188
	}
189
190
	/**
191
	 * Save parameters to database.
192
	 *
193
	 * @param   Registry  $params  Optional parameters. Null to use current ones.
194
	 *
195
	 * @return  Registry
196
	 */
197
	public function saveParams($params = null)
198
	{
199
		$params = null !== $params ? $params : $this->getParams();
200
201
		if (!$params instanceof \Joomla\Registry\Registry)
0 ignored issues
show
Bug introduced by
The class Joomla\Registry\Registry 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...
202
		{
203
			throw new \InvalidArgumentException(__CLASS__ . '::' . __METHOD__ . ' requires a Registry instance. ' . get_class($params) . ' received.');
204
		}
205
206
		$db = \JFactory::getDbo();
207
208
		$query = $db->getQuery(true)
209
			->update('#__extensions')
210
			->set('params = ' . $db->q($params->toString()))
211
			->where('type = ' . $db->quote('component'))
212
			->where('element = ' . $db->q($this->option));
213
214
		$db->setQuery($query);
215
216
		$this->setParams($params);
217
218
		return $db->execute() ? true : false;
219
	}
220
}
221