<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig;

use Symfony\Component\Intl\Countries;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class IntToDateConvertExtension extends AbstractExtension
{

    public function getFilters()
    {
        return [
            new TwigFilter('intToDate', [$this, 'inToDate']),
            new TwigFilter('country_name_alpha3', [$this, 'getCountryNameAlpha3']),
        ];
    }

    public function inToDate($int)
    {
        if (strlen($int) < 4) {
            $month = '0'.substr($int, 0, 1);
            $day   = substr($int, 1, 2);
        } else {
            $month = substr($int, 0, 2);
            $day   = substr($int, 2, 2);
        }
        $date = $day.'-'.$month;

        return $date;
    }

    public function getCountryNameAlpha3(?string $country, string $locale = null)
    {
        if (empty($country) || !Countries::alpha3CodeExists($country)) {
            return $country;
        }

        return Countries::getAlpha3Name($country, $locale);
    }
}
