Skip to content

Instantly share code, notes, and snippets.

@barokurniawan
Created February 22, 2020 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barokurniawan/20d6367da638457ad6788a406b6f2f0b to your computer and use it in GitHub Desktop.
Save barokurniawan/20d6367da638457ad6788a406b6f2f0b to your computer and use it in GitHub Desktop.
Check ISO Container Number
<?php
class ContainerNumber
{
private array $charMap;
private string $containerNumber;
public function __construct(string $containerNumber)
{
$this->setContainerNumber($containerNumber);
$this->charMap = ['A' => 10, 'B' => 12, 'C' => 13, 'D' => 14, 'E' => 15, 'F' => 16, 'G' => 17, 'H' => 18, 'I' => 19, 'J' => 20, 'K' => 21, 'L' => 23, 'M' => 24, 'N' => 25, 'O' => 26, 'P' => 27, 'Q' => 28, 'R' => 29, 'S' => 30, 'T' => 31, 'U' => 32, 'V' => 34, 'W' => 35, 'X' => 36, 'Y' => 37, 'Z' => 38];
}
/**
* remove space from container number.
* In some case container number written like `SITU 123 123 2`
*
* @return string
*/
private function removeSpace(string $containerNumber)
{
return str_replace(" ", "", strtoupper($containerNumber));
}
/**
* @return bool
*/
public function isValid()
{
if ($this->getContainerNumber() == null || empty($this->getContainerNumber()) || strlen($this->getContainerNumber()) < 11) {
return false;
}
$acc = 0;
$num = str_split($this->getContainerNumber());
for ($i = 0; $i < 10; $i++) {
if ($i < 4) {
$p = isset($num[$i]) ? $num[$i] : 0;
$c = isset($this->charMap[$p]) ? $this->charMap[$p] : 0;
if (is_numeric($c)) {
$acc += ($c * pow(2, $i));
}
} else {
$p = isset($num[$i]) ? $num[$i] : 0;
if (is_numeric($p)) {
$acc += $p * pow(2, $i);
}
}
}
$rem = $acc % 11;
if ($rem == 10) {
$rem = 0;
}
if (strlen($this->getContainerNumber()) == 11 && $num[10] == $rem) {
return true;
}
return false;
}
/**
* Get the value of containerNumber
*
* @return mixed
*/
public function getContainerNumber()
{
return $this->containerNumber;
}
/**
* Set the value of containerNumber
*
* @param mixed $containerNumber
*
* @return self
*/
public function setContainerNumber($containerNumber)
{
$this->containerNumber = $this->removeSpace($containerNumber);
return $this;
}
}
// penggunaan :
// var_dump(
// (new ContainerNumber('TCNU 549 931 0'))->isValid()
// );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment