| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- class CountryHandler
- {
- private array $countries;
- private array $default = [
- [
- 'en' => 'Hungary',
- 'hu' => 'Magyarország',
- 'code' => 'HU'
- ]
- ];
- /**
- *
- */
- public function __construct()
- {
- $this->initCountries();
- }
- /**
- *
- */
- public function initCountries(): void
- {
- $file = __DIR__.DIRECTORY_SEPARATOR.'countries.csv';
- if (file_exists($file)) {
- if (is_readable($file)) {
- // get CSV file rows into array
- $csv = array_map(
- function ($r) {
- return str_getcsv($r, ';');
- },
- file($file)
- );
- // set eys to associative array
- if (count($csv) > 1) {
- $this->countries = array_map(
- function ($country) {
- return array_combine(
- ['en', 'hu', 'code'],
- $country
- );
- },
- array_slice($csv, 1)
- );
- }
- }
- } else {
- $this->countries = $this->default;
- }
- }
- /**
- *
- */
- public function getCountries(string $lang='hu', string $search=''): array
- {
- $result = [];
- $list = $this->countries;
- $lang = strtolower($lang);
-
- $result = array_filter(
- array_map(
- function ($item) use ($lang, $search) {
- $result = null;
- if (empty($search)) {
- $result = [
- 'label' => $item[$lang],
- 'code' => $item['code']
- ];
- } else {
- if (preg_match('/'.$search.'/', strtolower($item[$lang]))) {
- $result = [
- 'label' => $item[$lang],
- 'code' => $item['code']
- ];
- }
- }
-
- return $result;
- },
- $list
- )
- );
- return $result;
- }
- }
|