Файл: PHP_CountryHelper/script/CountryHelper.php
Строк: 113
<?php
class CountryHelper
{
public $countries = array();
public function __construct($path = null)
{
if (isset($path)) {
$this->countries = require $path;
} else {
$this->countries = require __DIR__.'/CountriesArray.php';
}
}
/**
* Get Country Name by Country Code
*
* @param string $code
* @return string
*/
public function getCountryNameByCode($code, $type = 'alpha2')
{
if ($type == 'alpha3') {
return $this->getValueByKeys('country_code_alpha3', 'country_name', $code);
} else {
return $this->getValueByKeys('country_code_alpha2', 'country_name', $code);
}
}
/**
* Get Country Calling Code by Country Code
*
* @param string $code
* @return string
*/
public function getCountryCallingCodeByCode($code, $type = 'alpha2')
{
if ($type == 'alpha3') {
return $this->getValueByKeys('country_code_alpha3', 'country_calling_code', $code);
} else {
return $this->getValueByKeys('country_code_alpha2', 'country_calling_code', $code);
}
}
/**
* Get Country Currency by Country Code
*
* @param string $code
* @return string
*/
public function getCountryCurrencyCodeByCode($code, $type = 'alpha2')
{
if ($type == 'alpha3') {
return $this->getValueByKeys('country_code_alpha3', 'country_curreny_code', $code);
} else {
return $this->getValueByKeys('country_code_alpha2', 'country_curreny_code', $code);
}
}
/**
* Get Country Name by Calling Code
*
* @param string $code
* @return string
*/
public function getCountryNameByCallingCode($code)
{
return $this->getValueByKeys('country_calling_code', 'country_name', $code);
}
/**
* Get value by key
*
* @param string $key1
* @param string $key2
* @param string $search
* @return string
*/
public function getValueByKeys($key1, $key2, $search)
{
foreach ($this->countries as $value) {
if (isset($value[$key1]) && strtolower($value[$key1]) == strtolower($search)) {
return $value[$key2];
}
}
return false;
}
/**
* Generates array of values by selecting a key form the country array list
*
* @param string $key
* @return array
*/
public function getArrayFromKey($key)
{
$temp = array();
foreach ($this->countries as $value) {
if (isset($value[$key])) {
array_push($temp, $value[$key]);
}
}
return $temp;
}
/**
* Generates array with key1 as key of the array and key2,key3 has the value
* from the countries array list
*
* @param string $key1
* @param string $key2
* @param string $key3
* @param string $format
* @return array
*/
public function getArrayFromKeys($key1, $key2, $key3 = null, $format = "%s")
{
$temp = array();
foreach ($this->countries as $value) {
if (isset($value[$key1]) && isset($value[$key2])) {
try {
if (isset($key3) && isset($value[$key3])) {
$temp[$value[$key1]] = sprintf($format, $value[$key2], $value[$key3]);
} else {
$temp[$value[$key1]] = sprintf($format, $value[$key2]);
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
}
return $temp;
}
}