Locale   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 11
c 1
b 0
f 0
dl 0
loc 37
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 4 2
A __construct() 0 8 4
1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2015-2025
6
 * @package Base
7
 * @subpackage View
8
 */
9
10
11
namespace Aimeos\Base\View\Helper\Number;
12
13
14
/**
15
 * View helper class for formatting numbers.
16
 *
17
 * @package Base
18
 * @subpackage View
19
 */
20
class Locale
21
	extends \Aimeos\Base\View\Helper\Base
22
	implements \Aimeos\Base\View\Helper\Number\Iface
23
{
24
	private \NumberFormatter $formatter;
25
26
27
	/**
28
	 * Initializes the Number view helper.
29
	 *
30
	 * @param \Aimeos\Base\View\Iface $view View instance with registered view helpers
31
	 * @param string|null $locale Language locale like "en" or "en_UK" or null for default
32
	 * @param string|null $pattern ICU pattern to format the number or null for default formatting
33
	 */
34
	public function __construct( \Aimeos\Base\View\Iface $view, ?string $locale = null, ?string $pattern = null )
35
	{
36
		parent::__construct( $view );
37
38
		if( $pattern !== null ) {
39
			$this->formatter = new \NumberFormatter( $locale ?: 'en', \NumberFormatter::PATTERN_DECIMAL, $pattern );
40
		} else {
41
			$this->formatter = new \NumberFormatter( $locale ?: 'en', \NumberFormatter::DECIMAL );
42
		}
43
	}
44
45
46
	/**
47
	 * Returns the formatted number.
48
	 *
49
	 * @param int|double|string $number Number to format
50
	 * @param int|null $decimals Number of decimals behind the decimal point or null for default value
51
	 * @return string Formatted number
52
	 */
53
	public function transform( $number, ?int $decimals = null ) : string
54
	{
55
		$this->formatter->setAttribute( \NumberFormatter::FRACTION_DIGITS, $decimals !== null ? (int) $decimals : 2 );
56
		return $this->formatter->format( (double) $number );
57
	}
58
}
59