countryhandler.class.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. class CountryHandler
  3. {
  4. private array $countries;
  5. private array $default = [
  6. [
  7. 'en' => 'Hungary',
  8. 'hu' => 'Magyarország',
  9. 'code' => 'HU'
  10. ]
  11. ];
  12. /**
  13. *
  14. */
  15. public function __construct()
  16. {
  17. $this->initCountries();
  18. }
  19. /**
  20. *
  21. */
  22. public function initCountries(): void
  23. {
  24. $file = __DIR__.DIRECTORY_SEPARATOR.'countries.csv';
  25. if (file_exists($file)) {
  26. if (is_readable($file)) {
  27. // get CSV file rows into array
  28. $csv = array_map(
  29. function ($r) {
  30. return str_getcsv($r, ';');
  31. },
  32. file($file)
  33. );
  34. // set eys to associative array
  35. if (count($csv) > 1) {
  36. $this->countries = array_map(
  37. function ($country) {
  38. return array_combine(
  39. ['en', 'hu', 'code'],
  40. $country
  41. );
  42. },
  43. array_slice($csv, 1)
  44. );
  45. }
  46. }
  47. } else {
  48. $this->countries = $this->default;
  49. }
  50. }
  51. /**
  52. *
  53. */
  54. public function getCountries(string $lang='hu', string $search=''): array
  55. {
  56. $result = [];
  57. $list = $this->countries;
  58. $lang = strtolower($lang);
  59. $result = array_filter(
  60. array_map(
  61. function ($item) use ($lang, $search) {
  62. $result = null;
  63. if (empty($search)) {
  64. $result = [
  65. 'label' => $item[$lang],
  66. 'code' => $item['code']
  67. ];
  68. } else {
  69. if (preg_match('/'.$search.'/', strtolower($item[$lang]))) {
  70. $result = [
  71. 'label' => $item[$lang],
  72. 'code' => $item['code']
  73. ];
  74. }
  75. }
  76. return $result;
  77. },
  78. $list
  79. )
  80. );
  81. return $result;
  82. }
  83. }