Skip to content

Instantly share code, notes, and snippets.

@mhamlet
Last active June 6, 2024 15:31
Show Gist options
  • Save mhamlet/090cd05bca903394b61c to your computer and use it in GitHub Desktop.
Save mhamlet/090cd05bca903394b61c to your computer and use it in GitHub Desktop.
Validation and normalization of Armenian Phone numbers
<?php
/**
* Class Phone
*/
class Phone {
/**
* Phone number
*
* @var string
*/
private $number;
/**
* Phone number in local format
*
* @var string
*/
private $number_local;
/**
* Phone number in international format
*
* @var string
*/
private $number_international;
/**
* Phone check status
*
* @var bool
*/
private $check_status = false;
/**
* Constructor
*
* @param string $number
*/
public function __construct($number) {
// Store phone number
$this->number = $number;
// Normalizing number and saving check status
$this->check_status = $this->normalize_number();
}
/**
* Normalizing phone number
*
* @return bool
*/
private function normalize_number() {
// Supported careers
$careers = array(91, 96, 99, 43, 77, 93, 94, 98, 97, 77, 55, 95, 41, 49);
// Getting phone number
$number = $this->number;
// If first to numbers are 00
if (substr($number, 0, 2) === '00') {
// Replace with +
$number = '+' . substr($number, 2);
}
// If number is in local format, change it with international format
if (substr($number, 0, 1) === '0') {
// Add Armenian code
$number = '+374' . substr($number, 1);
}
elseif (in_array(substr($number, 0, 2), $careers)) {
// Add Armenian code
$number = '+374' . $number;
}
// Check if number in armenia
if (substr($number, 0, 4) !== '+374') {
return false;
}
// Getting career code and phone number
$career = substr($number, 4, 2);
$phone = substr($number, 6);
// Length of phone number must be 6
if (strlen($phone) !== 6) return false;
// If career not supported
if (!in_array($career, $careers)) return false;
// Save phone number
$this->number_international = $number;
$this->number_local = '0' . $career . $phone;
return true;
}
/**
* Getting phone number in local format
*
* @return bool|string
*/
public function get_local() {
// If phone is wrong, return false
if ($this->check_phone() === FALSE) return false;
// Return local number
return $this->number_local;
}
/**
* Getting phone number in international format
*
* @return bool|string
*/
public function get_international() {
// If phone is wrong, return false
if ($this->check_phone() === FALSE) return false;
// Return international number
return $this->number_international;
}
/**
* Checking phone
*
* @return bool
*/
public function check_phone() {
return $this->check_status;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment