-
-
Notifications
You must be signed in to change notification settings - Fork 16
Validating ISBNs using the new public API
The 2.3.0 update introduced three new validation methods:
Isbn::validateAsIsbn10 ( string $value ) : void
Isbn::validateAsIsbn13 ( string $value ) : void
Isbn::validateAsEan13 ( string $value ) : void
These methods are the recommended way if you want to strictly assert that a string is a valid ISBN-10, ISBN-13 or EAN-13.
They throw exceptions if string passed as an argument:
- is parsable (and thus, can be converted to a valid ISBN) but does not match the excepted format,
- or if it can even be parsed at all.
Example:
$input = "9781234567890";
try {
Isbn::validateAsIsbn13($input);
echo "ISBN $input is valid!";
} catch(Exception $e) {
echo "ISBN $input is invalid!";
}
The 2.4.0 update introduced a new method:
Isbn::isParsable ( string $value ) : boolean
This method returns true
if the $value
string can be parsed (and thus, converted into a valid ISBN-10, ISBN-13, EAN-13 or GTIN-14) and false
if it cannot be.
Example usage:
$input = "978-2-84344-949-9";
if (Isbn::isParsable($input)) {
$ean = Isbn::convertToEan13($input);
echo "String $input was converted to EAN-13 $ean";
} else {
echo "String $input was not converted because it is not parsable!";
}
Please note that Isbn::isParsable
does not guaranty that $value
is valid in any way, but only that it is parsable enough that it can be converted to a valid ISBN. This is a similar behavior to the legacy Isbn->isValid
and Isbn->validate
methods (deprecated in 2.3.0) but with a much less confusing name.
You don’t need to call Isbn::isParsable
before trying to attempt to convert a string using one of the Isbn::convertAs…
methods, unlike the legacy Isbn->format
that required you to preventively call Isbn->isValid
to avoid unexpected behavior. Now, you can just catch exceptions :
$input = "978-2-84344-949-9";
try {
$ean = Isbn::convertToEan13($input);
echo "String $input was converted to EAN-13 $ean";
} catch(Exception $e) {
echo "String $input was not converted because it is not parsable!";
}
One reason to use Isbn::isParsable
is if you want to validate parsability in a condition among others.
function searchFor(string $value) {
if (Isbn::isParsable($value)) {
$ean = Isbn::convertToEan13($value);
searchByEan($ean);
} elseif (is_numeric($value)) {
searchById(int $value);
} else {
searchByKeyword($value);
}
}
The above function would have been much less easy to read if it would have been implemented using try…catch
.