You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.8 KiB
PHP
59 lines
1.8 KiB
PHP
<?php
|
|
|
|
class TrackingBarcode {
|
|
|
|
private $code = "";
|
|
|
|
public function __construct(string $code) {
|
|
$this->code = $code;
|
|
}
|
|
|
|
/**
|
|
* Trim and clean up the code so it's all caps and only A-Z and 0-9.
|
|
* Does not change the actual barcode represented by this object.
|
|
* @param string $code
|
|
* @return string the sanitized code
|
|
*/
|
|
public function getSanitized(): string {
|
|
$code = strtoupper($this->code);
|
|
$code = trim($code);
|
|
$code = preg_replace("/[^0-9A-Z]/", "", $code);
|
|
return $code;
|
|
}
|
|
|
|
/**
|
|
* Guess the carrier for the tracking code.
|
|
* @return string An ID string representing the carrier. Some codes that
|
|
* require extra processing before use will return a non-standard ID, use
|
|
* Carriers::getCarrierName()/getCarrierCode() to resolve a standard ID code.
|
|
*/
|
|
public function getCarrier(): string {
|
|
$carrier = "";
|
|
foreach (Carriers::CARRIER_REGEXES as $p) {
|
|
if (preg_match($p["pattern"], strtoupper($this->code))) {
|
|
$carrier = $p["carrier"];
|
|
break;
|
|
}
|
|
}
|
|
if ($carrier == "") {
|
|
// check again but strip out anything extra this time
|
|
// makes it work with codes containing nonprintable stuff like the GS (group separator, %1D) char
|
|
foreach (Carriers::CARRIER_REGEXES as $p) {
|
|
if (preg_match($p["pattern"], $this->getSanitized())) {
|
|
$carrier = $p["carrier"];
|
|
break;
|
|
}
|
|
}
|
|
if ($carrier == "") {
|
|
throw new TrackingException("Unrecognized tracking code.");
|
|
}
|
|
}
|
|
return $carrier;
|
|
}
|
|
|
|
public function getCode(): string {
|
|
return $this->code;
|
|
}
|
|
|
|
}
|