Passed
Push — developer ( 796144...7f419d )
by Radosław
16:31
created

Currency::getActiveBankForExchangeRateUpdate()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 0
crap 12
1
<?php
2
/**
3
 * Tools for currency class.
4
 *
5
 * @package App
6
 *
7
 * @copyright YetiForce S.A.
8
 * @license   YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
9
 * @author    Mariusz Krzaczkowski <[email protected]>
10
 * @author    Radosław Skrzypczak <[email protected]>
11
 */
12
13
namespace App\Fields;
14
15
/**
16
 * Currency class.
17
 */
18
class Currency
19
{
20
	/**
21
	 * Function returns the currency in user specified format.
22
	 *
23
	 * @param string     $value          Date time
24
	 * @param mixed|null $user
25
	 * @param mixed      $skipConversion
26
	 * @param mixed      $skipFormatting
27
	 *
28
	 * @return string
29
	 */
30
	public static function formatToDisplay($value, $user = null, $skipConversion = false, $skipFormatting = false)
31
	{
32
		if (empty($value)) {
33
			return 0;
34
		}
35
		return \CurrencyField::convertToUserFormat($value, $user, $skipConversion, $skipFormatting);
0 ignored issues
show
Deprecated Code introduced by
The function CurrencyField::convertToUserFormat() has been deprecated: Recommend using function \App\Fields\Currency::formatToDisplay ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

35
		return /** @scrutinizer ignore-deprecated */ \CurrencyField::convertToUserFormat($value, $user, $skipConversion, $skipFormatting);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
36
	}
37
38
	/**
39
	 * Function to get value for db format.
40
	 *
41
	 * @param string $value
42 1
	 *
43
	 * @return float
44 1
	 */
45
	public static function formatToDb(string $value): ?float
46
	{
47 1
		if (empty($value)) {
48 1
			return 0;
49 1
		}
50
		$currentUser = \App\User::getCurrentUserModel();
51
		$value = str_replace([$currentUser->getDetail('currency_grouping_separator'), $currentUser->getDetail('currency_decimal_separator'), ' '], ['', '.', ''], $value);
52 1
		if (!\is_numeric($value)) {
53
			return null;
54
		}
55
		return $value;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $value returns the type string which is incompatible with the type-hinted return double|null.
Loading history...
56
	}
57
58
	/**
59
	 * Get currency by module name.
60
	 *
61
	 * @param int    $record
62
	 * @param string $moduleName
63
	 *
64
	 * @return int
65
	 */
66
	public static function getCurrencyByModule(int $record, string $moduleName)
67
	{
68
		return \Vtiger_Record_Model::getInstanceById($record, $moduleName)->get('currency_id');
69
	}
70
71
	/**
72
	 * Get currency id by name.
73
	 *
74
	 * @param type $currencyName
0 ignored issues
show
Bug introduced by
The type App\Fields\type was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
75
	 *
76
	 * @return type
77
	 */
78
	public static function getCurrencyIdByName($currencyName)
79
	{
80
		$currencyId = 1;
81
		$row = (new \App\Db\Query())->select(['id'])->from('vtiger_currency_info')->where(['currency_name' => $currencyName, 'deleted' => 0])->scalar();
82
		if ($row) {
83
			$currencyId = $row;
84
		}
85
		return $currencyId;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $currencyId returns the type integer|string which is incompatible with the documented return type App\Fields\type.
Loading history...
86
	}
87
88
	/**
89
	 * Get currency by code.
90
	 *
91
	 * @param string $code
92
	 * @param bool   $active
93
	 *
94
	 * @return int|null
95
	 */
96
	public static function getIdByCode(string $code, bool $active = true): ?int
97
	{
98
		return array_column(static::getAll($active), 'id', 'currency_code')[\strtoupper($code)] ?? null;
99
	}
100
101
	/**
102
	 * Get all currencies.
103
	 *
104
	 * @param bool $onlyActive
105 11
	 *
106
	 * @return array
107 11
	 */
108 10
	public static function getAll($onlyActive = false)
109
	{
110 5
		if (\App\Cache::has('CurrencyGetAll', 'All')) {
111 5
			$currencies = \App\Cache::get('CurrencyGetAll', 'All');
112
		} else {
113 11
			$currencies = (new \App\Db\Query())->from('vtiger_currency_info')->where(['deleted' => 0])->indexBy('id')->all();
114 9
			\App\Cache::save('CurrencyGetAll', 'All', $currencies);
115 9
		}
116 2
		if ($onlyActive) {
117
			foreach ($currencies as $id => $currency) {
118
				if ('Active' !== $currency['currency_status']) {
119
					unset($currencies[$id]);
120 11
				}
121
			}
122
		}
123
		return $currencies;
124
	}
125
126
	/**
127
	 * Get supported currencies.
128
	 *
129
	 * @return array
130 2
	 */
131
	public static function getSupported(): array
132 2
	{
133 2
		if (\App\Cache::has('CurrencySupported', 'All')) {
134
			$currencies = \App\Cache::get('CurrencySupported', 'All');
135
		} else {
136
			$currencies = (new \App\Db\Query())->from('vtiger_currencies')->indexBy('currency_code')->all();
137
			\App\Cache::save('CurrencySupported', 'All', $currencies);
138
		}
139
		return $currencies;
140
	}
141 9
142
	/**
143 9
	 * Get currency by id.
144 9
	 *
145 9
	 * @param int $currencyId
146
	 *
147
	 * @return array
148
	 */
149
	public static function getById(int $currencyId)
150
	{
151
		$currencyInfo = static::getAll();
152
		return $currencyInfo[$currencyId] ?? [];
153
	}
154
155
	/**
156
	 * Get current default currency data.
157
	 *
158
	 * @return array|bool
159
	 */
160
	public static function getDefault()
161
	{
162
		foreach (self::getAll(true) as $currency) {
163
			if (-11 === (int) $currency['defaultid']) {
164
				return $currency;
165
			}
166
		}
167
		return false;
168
	}
169
170
	/**
171
	 * Function clears cache.
172
	 *
173
	 * @return void
174
	 */
175
	public static function clearCache(): void
176
	{
177
		\App\Cache::delete('CurrencyGetAll', 'All');
178
		\App\Cache::delete('CurrencySupported', 'All');
179
	}
180
181
	/**
182
	 * Add the currency by code.
183
	 *
184
	 * @param string $code
185
	 *
186
	 * @return int|null
187
	 */
188
	public static function addCurrency(string $code): ?int
189
	{
190
		$supported = self::getSupported();
191
		if (empty($supported[$code])) {
192
			\App\Log::error('No currency code to add found: ' . $code);
193
			return null;
194
		}
195
		$db = \App\Db::getInstance();
196
		$db->createCommand()
197
			->insert('vtiger_currency_info', [
198
				'currency_name' => $supported[$code]['currency_name'],
199
				'currency_code' => $code,
200
				'currency_symbol' => $supported[$code]['currency_symbol'],
201
				'conversion_rate' => 1,
202
				'currency_status' => 'Active',
203
			])->execute();
204
		self::clearCache();
205
		return $db->getLastInsertID('vtiger_currency_info_id_seq');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $db->getLastInser..._currency_info_id_seq') returns the type string which is incompatible with the type-hinted return integer|null.
Loading history...
206
	}
207
208
	/**
209
	 * Gets currency exchange rates from archive.
210
	 *
211
	 * @param string   $date
212
	 * @param int      $currencyId
213
	 * @param int|null $activeBankId
214
	 *
215
	 * @return array
216
	 */
217
	public static function getCurrencyRatesFromArchive(string $date, int $currencyId, ?int $activeBankId = null): array
218
	{
219
		if (null === $activeBankId) {
220
			$activeBankId = self::getActiveBankForExchangeRateUpdate()['id'] ?? 0;
221
		}
222
223
		return (new \App\Db\Query())->from('yetiforce_currencyupdate')
224
			->innerJoin('vtiger_currency_info', 'vtiger_currency_info.id = yetiforce_currencyupdate.currency_id AND deleted = :del', [':del' => 0])
225
			->where(['yetiforce_currencyupdate.exchange_date' => $date,
226
				'yetiforce_currencyupdate.bank_id' => $activeBankId,
227
				'vtiger_currency_info.id' => $currencyId])
228
			->one() ?: [];
229
	}
230
231
	/**
232
	 * Gets bank for exchange rate update.
233
	 *
234
	 * @return array
235
	 */
236
	public static function getActiveBankForExchangeRateUpdate(): array
237
	{
238
		$cacheName = 'ActiveBankForExchangeRate';
239
		$activeBank = [];
240
		if (\App\Cache::has($cacheName, '')) {
241
			$activeBank = \App\Cache::get($cacheName, '');
242
		} else {
243
			$activeBank = (new \App\Db\Query())->from('yetiforce_currencyupdate_banks')->where(['active' => 1])->one() ?: [];
244
			\App\Cache::save($cacheName, '', $activeBank);
245
		}
246
247
		return $activeBank;
248
	}
249
}
250