Skip to content

FormatterIntl.php #13

@fuga00

Description

@fuga00

This file is wrong and getting error 500 when i want go to product details.
fixed:

<?php declare(strict_types=1);

namespace BulkGate\Plugin\Localization;

/**
 * @author Lukáš Piják 2023 TOPefekt s.r.o.
 * @link https://www.bulkgate.com/
 */

use DateTime, Exception;
use Locale, IntlDateFormatter, NumberFormatter;
use BulkGate\Plugin\{Strict, Utils\Strings};
use function date_default_timezone_get, is_integer;

class FormatterIntl implements Formatter
{
	use Strict;

	private string $locale;

	public function __construct(string $language, ?string $country = null)
	{
		$this->locale = $language . ($country !== null ? '_' . Strings::upper($country) : '');
	}

	/**
	 * @param string $type 'date', 'time', 'datetime', 'price', 'number', 'country'
	 * @param scalar|null|mixed $value
	 * @param mixed ...$parameters
	 */
	public function format(string $type, $value, ...$parameters): ?string
	{
		try
		{
			switch ($type)
			{
				case 'date':
				case 'time':
				case 'datetime':
					if ($value === null || $value === '') {
						return null;
					}
					$dateValue = is_integer($value) ? "@$value" : $value;
					try {
						$date = new DateTime($dateValue);
					} catch (Exception $e) {
						return null;
					}

					$formatter = new IntlDateFormatter(
						$this->locale,
						match($type) {
							'date' => IntlDateFormatter::MEDIUM,
							'time' => IntlDateFormatter::NONE,
							'datetime' => IntlDateFormatter::MEDIUM,
						},
						match($type) {
							'date' => IntlDateFormatter::NONE,
							'time' => IntlDateFormatter::SHORT,
							'datetime' => IntlDateFormatter::SHORT,
						},
						$parameters[0] ?? date_default_timezone_get(),
						IntlDateFormatter::GREGORIAN
					);

					return $formatter->format($date) ?: null;

				case 'price':
					if (!is_numeric($value)) {
						return null;
					}
					$formatted = (new NumberFormatter($this->locale, NumberFormatter::CURRENCY))
						->formatCurrency((float)$value, $parameters[0] ?? 'EUR');
					return $formatted !== false ? $formatted : null;

				case 'number':
					if (!is_numeric($value)) {
						return null;
					}
					$formatted = (new NumberFormatter($this->locale, NumberFormatter::DECIMAL))
						->format((float)$value);
					return $formatted !== false ? $formatted : null;

				case 'country':
					if (!is_string($value) || $value === '') {
						return null;
					}
					$result = Locale::getDisplayRegion("-$value", $this->locale);
					return $result ?: $value;
			}
		}
		catch (Exception $e)
		{
			// Cicha obsługa błędów
		}

		return null;
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions