Completed
Push — master ( 33a7b0...aefa23 )
by Roberto
03:49
created

Component::getPrefix()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

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