Passed
Push — master ( 06cda6...c12030 )
by Roberto
03:54
created

Component::getActive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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
	 * @throws  \InvalidArgumentException
52
	 */
53 4
	public function __construct($option)
54
	{
55 4
		$option = trim(strtolower($option));
56
57 4
		if (empty($option))
58
		{
59 1
			throw new \InvalidArgumentException(__CLASS__ . ': Empty component option.');
60
		}
61
62 3
		$this->option = $option;
63 3
	}
64
65
	/**
66
	 * Clear a singleton instance.
67
	 *
68
	 * @param   string  $option  Component option
69
	 *
70
	 * @return  void
71
	 */
72 1
	public static function clearInstance($option)
73
	{
74 1
		unset(static::$instances[get_called_class()][$option]);
75 1
	}
76
77
	/**
78
	 * Get the active component.
79
	 *
80
	 * @return  $this
81
	 *
82
	 * @throws  \InvalidArgumentException
83
	 */
84 1
	public static function getActive()
85
	{
86 1
		return static::getInstance(static::getActiveComponent());
87
	}
88
89
	/**
90
	 * Get the active component. Isolated for testing purposes.
91
	 *
92
	 * @return  string
93
	 *
94
	 * @codeCoverageIgnore
95
	 */
96
	protected static function getActiveComponent()
97
	{
98
		return \JApplicationHelper::getComponentName();
99
	}
100
101
	/**
102
	 * Get a singleton instance.
103
	 *
104
	 * @param   string  $option  Component option
105
	 *
106
	 * @return  $this
107
	 */
108 10
	public static function getInstance($option)
109
	{
110 10
		$option = trim(strtolower($option));
111
112 10
		$class = get_called_class();
113
114 10
		if (empty(static::$instances[$class][$option]))
115
		{
116 3
			static::$instances[$class][$option] = new static($option);
117
		}
118
119 10
		return static::$instances[$class][$option];
120
	}
121
122
	/**
123
	 * Get the component prefix.
124
	 *
125
	 * @return  string
126
	 */
127 6
	public function getPrefix()
128
	{
129 6
		if (null === $this->prefix)
130
		{
131 4
			$parts = array_map(
132 4
				function ($part)
133
				{
134 4
					return ucfirst(strtolower($part));
135 4
				},
136 4
				explode('_', substr($this->option, 4))
137
			);
138
139 4
			$this->prefix = implode('_', $parts);
140
		}
141
142 6
		return $this->prefix;
143
	}
144
145
	/**
146
	 * Get a component table.
147
	 *
148
	 * @param   string   $name     Name of the table to load. Example: Article
149
	 * @param   array    $config   Optional array of configuration for the table
150
	 * @param   boolean  $backend  Search in backend folder?
151
	 *
152
	 * @return  \JTable
153
	 *
154
	 * @throws  \InvalidArgumentException  If table not found
155
	 */
156 2
	public function getTable($name, array $config = array(), $backend = true)
157
	{
158 2
		$prefix = $this->getPrefix() . 'Table';
159
160 2
		$baseFolder = $backend ? JPATH_ADMINISTRATOR : JPATH_SITE;
161
162 2
		\JTable::addIncludePath($baseFolder . '/components/' . $this->option . '/tables');
163
164 2
		$table = \JTable::getInstance($name, $prefix, $config);
165
166 2
		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...
167
		{
168 1
			throw new \InvalidArgumentException(
169 1
				sprintf('Cannot find the table %s in component %s.', $prefix . $name, $this->option)
170
			);
171
		}
172
173 1
		return $table;
174
	}
175
176
	/**
177
	 * Load extension from DB.
178
	 *
179
	 * @return  \stdClass
180
	 */
181 1
	protected function loadExtension()
182
	{
183 1
		$db = \JFactory::getDbo();
184 1
		$query = $db->getQuery(true)
185 1
			->select('*')
186 1
			->from('#__extensions')
187 1
			->where('type = ' . $db->quote('component'))
188 1
			->where('element = ' . $db->q($this->option));
189
190 1
		$db->setQuery($query);
191
192 1
		return $db->loadObject() ?: new \stdClass;
193
	}
194
195
	/**
196
	 * Load parameters from database.
197
	 *
198
	 * @return  Registry
199
	 */
200 1
	protected function loadParams()
201
	{
202 1
		return new Registry($this->getExtensionProperty('params', array()));
203
	}
204
205
	/**
206
	 * Save parameters to database.
207
	 *
208
	 * @param   Registry  $params  Optional parameters. Null to use current ones.
209
	 *
210
	 * @return  Registry
211
	 */
212 2
	public function saveParams($params = null)
213
	{
214 2
		$params = null !== $params ? $params : $this->getParams();
215
216 2
		if (!$params instanceof \Joomla\Registry\Registry)
217
		{
218 1
			throw new \InvalidArgumentException(__CLASS__ . '::' . __METHOD__ . ' requires a Registry instance. ' . gettype($params) . ' received.');
219
		}
220
221 1
		$db = \JFactory::getDbo();
222
223 1
		$query = $db->getQuery(true)
224 1
			->update('#__extensions')
225 1
			->set('params = ' . $db->q($params->toString()))
226 1
			->where('type = ' . $db->quote('component'))
227 1
			->where('element = ' . $db->q($this->option));
228
229 1
		$db->setQuery($query);
230
231 1
		$this->setParams($params);
232
233 1
		return $db->execute() ? true : false;
234
	}
235
}
236