Created
May 16, 2022 11:48
-
-
Save marcguyer/0ce67963c784576ca754cccabcc011c7 to your computer and use it in GitHub Desktop.
Laminas Country Code Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Api\Filter; | |
use Laminas\Filter\FilterInterface; | |
use League\ISO3166\ISO3166; | |
use Throwable; | |
/** | |
* Converts country names and ISO alpha3/numeric to ISO alpha2. | |
*/ | |
class CountryCodeFilter implements FilterInterface | |
{ | |
/** | |
* @var string | |
*/ | |
protected $returnKey; | |
/** | |
* Sets filter options | |
* | |
* @param string $returnKey | |
*/ | |
public function __construct($returnKey = 'alpha2') | |
{ | |
$this->returnKey = $returnKey; | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function filter($value) | |
{ | |
if (null === $value) { | |
return $value; | |
} | |
$value = (string) $value; | |
$iso = new ISO3166(); | |
// maybe alpha2 | |
if (1 === preg_match('/^[a-zA-Z]{2}$/', $value)) { | |
try { | |
$data = $iso->alpha2($value); | |
return $data[$this->returnKey]; | |
} catch (Throwable $e) { | |
} | |
} | |
// maybe alpha3 | |
if (1 === preg_match('/^[a-zA-Z]{3}$/', $value)) { | |
try { | |
$data = $iso->alpha3($value); | |
return $data[$this->returnKey]; | |
} catch (Throwable $e) { | |
} | |
} | |
// maybe numeric | |
if (1 === preg_match('/^[0-9]{3}$/', $value)) { | |
try { | |
$data = $iso->numeric($value); | |
return $data[$this->returnKey]; | |
} catch (Throwable $e) { | |
} | |
} | |
// last try by name string exact match | |
try { | |
$data = $iso->name($value); | |
return $data[$this->returnKey]; | |
} catch (Throwable $e) { | |
} | |
return $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment