initial commit

This commit is contained in:
2021-12-20 12:50:53 +01:00
commit 839913d51a
51 changed files with 13051 additions and 0 deletions

View File

@ -0,0 +1,42 @@
name: tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
php: [ '7.1', '7.2', '7.3', '7.4' ]
steps:
- uses: actions/checkout@v2
- uses: nanasess/setup-php@master
with:
php-version: ${{ matrix.php }}
- name: Validate composer.json and composer.lock
run: composer validate
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php }}
- name: Install dependencies
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest
- name: Run test suite
run: composer test

1
vendor/biblys/isbn/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/vendor/

2
vendor/biblys/isbn/.gitpod.yml vendored Normal file
View File

@ -0,0 +1,2 @@
tasks:
- init: composer install && composer test

21
vendor/biblys/isbn/LICENSE vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Clément Bourgoin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

141
vendor/biblys/isbn/README.md vendored Normal file
View File

@ -0,0 +1,141 @@
# biblys/isbn
[![tests](https://github.com/biblys/isbn/actions/workflows/tests.yml/badge.svg)](https://github.com/biblys/isbn/actions/workflows/tests.yml)
[![Latest Stable Version](https://poser.pugx.org/biblys/isbn/v/stable)](https://packagist.org/packages/biblys/isbn)
[![Total Downloads](https://poser.pugx.org/biblys/isbn/downloads)](https://packagist.org/packages/biblys/isbn)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT)
[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/biblys/isbn)
biblys/isbn can be used to:
- [validate](#validate) a string against the ISBN-10, ISBN-13 and EAN-13 formats
- [convert](#convert) an ISBN to ISBN-10, ISBN-13, EAN-13 and GTIN-14 formats
- parse an ISBN and extract registration agency, publisher code, publication code, checksum, etc.
[CHANGELOG](https://github.com/biblys/isbn/releases)
## Installation
Install with composer:
```console
composer require biblys/isbn:^2.4.0
```
## Usage
### Convert
Use case: converting an EAN (9782843449499) to an ISBN-13 (978-2-84344-949-9).
```php
<?php
use Biblys\Isbn\Isbn;
try {
$input = "9782843449499";
$isbn13 = Isbn::convertToIsbn13($input);
echo "ISBN-13: $isbn13"; // Prints ISBN-13: 978-2-84344-949-9
} catch(Exception $e) {
echo "An error occurred while attempting to format ISBN $input: ".$e->getMessage();
}
```
All formatting methods:
- `Isbn::convertToIsbn10`
- `Isbn::convertToIsbn13`
- `Isbn::convertToEan13`
- `Isbn::convertToGtin14`
### Validate
Use case: validating an incorrectly formed ISBN-13 (978-2-843-44949-9, should
be 978-2-84344-949-9).
```php
<?php
use Biblys\Isbn\Isbn;
try {
$input = "978-2-843-44949-9";
Isbn::validateAsIsbn13($input);
echo "ISBN $input is valid!";
} catch(Exception $e) { // Will throw because third hyphen is misplaced
echo "ISBN $input is invalid: ".$e->getMessage();
}
```
All validating methods:
- `Isbn::validateAsIsbn10`
- `Isbn::validateAsIbsn13`
- `Isbn::validateAsEan13`
- `Isbn::isParsable`
[Learn more about validating ISBNs](https://github.com/biblys/isbn/wiki/Validating-ISBNs-using-the-new-public-API)
## Development
### Using Gitpod
You can start a dev environment by clicking
[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/biblys/isbn)
and start hacking in your browser right away!
### Locally
If you'd rather set up a local dev environment, you'll need:
- PHP 7.x
- Composer
- (Optional) Docker to run tests and debug against different version of PHP
Clone this repository and run `composer install` to get started!
## Tests
Run tests with PHPUnit:
```console
composer install
composer test
```
Run tests in a docker container:
```console
composer docker:test
```
Run tests in a docker container using a specific PHP version:
```console
PHP_VERSION=7.1 composer docker:test
```
## ISBN ranges update
New ISBN ranges may be added from time to time by the
[International ISBN Agency](https://www.isbn-international.org/). Whenever it
happens, this library must be updated. If a range update is necessary, please
open an issue on GitHub.
You can also open a pull request after updating the ranges your self with the
following commands:
```console
composer install
composer run update-ranges
```
Or using a docker container:
```console
composer docker:update-ranges
```
## Changelog
[See GitHub releases](https://github.com/biblys/isbn/releases)

View File

@ -0,0 +1,78 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*
* This script is used to update the ISBN ranges. See README.md for more info.
*
*/
use GuzzleHttp\Client;
include('vendor/autoload.php');
echo "Requesting range information...\n";
$client = new Client();
$url = 'https://www.isbn-international.org/?q=bl_proxy/GetRangeInformations';
$res = $client->request('POST', $url, [
'form_params' => [
'format' => 1,
'language' => 'en',
'translatedTexts' => 'Printed;Last Change'
]
]);
$result = json_decode($res->getBody()->getContents());
if ($result === null || !property_exists($result, 'result')) {
exit("The ISBN range API at $url is currently unavailable, exiting...\n");
}
$value = $result->result->value;
$filename = $result->result->filename;
$url = sprintf('https://www.isbn-international.org/?q=download_range/%s/%s', $value, $filename);
echo "Getting XML from $url...\n";
$res = $client->request('GET', $url);
$xml = $res->getBody()->getContents();
echo "Converting to PHP array...\n";
$ranges = (array) simplexml_load_string($xml);
$ranges = json_encode($ranges);
$ranges = json_decode($ranges, true);
$prefixes = (array) $ranges['EAN.UCCPrefixes']['EAN.UCC'];
$groups = (array) $ranges['RegistrationGroups']['Group'];
foreach ($groups as &$group) {
// Fix entries with a single "range", converting it to an array
if (isset($group['Rules']['Rule']['Range'])) {
$group['Rules']['Rule'] = array($group['Rules']['Rule']);
}
}
$file = dirname(__FILE__) . '/../src/Biblys/Isbn/ranges-array.php';
echo "Saving to $file...\n";
file_put_contents($file,
'<?php ' . "\n"
. '/*' . "\n"
. ' * This file is generated automatically by update-ranges.php, do not edit' . "\n"
. ' * manually! See README.md for more info. ' . "\n"
. ' *' . "\n"
. ' * This file is part of the biblys/isbn package.' . "\n"
. ' *' . "\n"
. ' * (c) Clément Bourgoin' . "\n"
. ' *' . "\n"
. ' * This package is Open Source Software. For the full copyright and license' . "\n"
. ' * information, please view the LICENSE file which was distributed with this' . "\n"
. ' * source code.' . "\n"
. ' */' . "\n\n"
. '$groups = ' . var_export($groups, TRUE) . ";\n"
. '$prefixes = ' . var_export($prefixes, TRUE) . ";\n"
);

41
vendor/biblys/isbn/composer.json vendored Normal file
View File

@ -0,0 +1,41 @@
{
"name": "biblys/isbn",
"description": "A PHP library to convert and validate ISBNs",
"time": "2021-03-05",
"keywords": [
"ISBN",
"EAN",
"GTIN",
"Book"
],
"license": "MIT",
"homepage": "https://github.com/biblys/isbn",
"authors": [
{
"name": "Clement Bourgoin",
"email": "c@iwzr.fr"
}
],
"support": {
"issues": "https://github.com/biblys/isbn/issues"
},
"require": {
"php": "^7.1"
},
"require-dev": {
"phpunit/phpunit": "^6 || ^7 || ^8",
"guzzlehttp/guzzle": "^6.2"
},
"autoload": {
"psr-0": {
"Biblys": "src/"
}
},
"scripts": {
"test": "vendor/bin/phpunit tests",
"update-ranges": "php bin/update-ranges.php",
"docker:install": "docker run --rm -v $PWD:/app prooph/composer:${PHP_VERSION:-7.4} install",
"docker:test": "@composer docker:install && docker run --rm -v $PWD:/app prooph/composer:${PHP_VERSION:-7.4} test",
"docker:update-ranges": "@composer docker:install && docker run --rm -v $PWD:/app prooph/composer:${PHP_VERSION:-7.4} update-ranges"
}
}

View File

@ -0,0 +1,115 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
namespace Biblys\Isbn;
class Formatter
{
public static function formatAsIsbn10(string $input): string
{
$parsedInput = Parser::parse($input);
$countryCode = $parsedInput["countryCode"];
$publisherCode = $parsedInput["publisherCode"];
$publicationCode = $parsedInput["publicationCode"];
$checksum = self::_calculateChecksumForIsbn10Format($countryCode, $publisherCode, $publicationCode);
return "$countryCode-$publisherCode-$publicationCode-$checksum";
}
public static function formatAsIsbn13(string $input): string
{
$parsedInput = Parser::parse($input);
$productCode = $parsedInput['productCode'];
$countryCode = $parsedInput["countryCode"];
$publisherCode = $parsedInput["publisherCode"];
$publicationCode = $parsedInput["publicationCode"];
$checksum = self::_calculateChecksumForIsbn13Format($productCode, $countryCode, $publisherCode, $publicationCode);
return "$productCode-$countryCode-$publisherCode-$publicationCode-$checksum";
}
public static function formatAsEan13(string $input): string
{
$parsedInput = Parser::parse($input);
$productCode = $parsedInput['productCode'];
$countryCode = $parsedInput["countryCode"];
$publisherCode = $parsedInput["publisherCode"];
$publicationCode = $parsedInput["publicationCode"];
$checksum = self::_calculateChecksumForIsbn13Format($productCode, $countryCode, $publisherCode, $publicationCode);
return $productCode . $countryCode . $publisherCode . $publicationCode . $checksum;
}
public static function formatAsGtin14(string $input, int $prefix): string
{
$parsedInput = Parser::parse($input);
$productCode = $parsedInput['productCode'];
$countryCode = $parsedInput['countryCode'];
$publisherCode = $parsedInput['publisherCode'];
$publicationCode = $parsedInput['publicationCode'];
$productCodeWithPrefix = $prefix . $productCode;
$checksum = self::_calculateChecksumForIsbn13Format($productCodeWithPrefix, $countryCode, $publisherCode, $publicationCode);
return $prefix . $productCode . $countryCode . $publisherCode . $publicationCode . $checksum;
}
private static function _calculateChecksumForIsbn10Format(
string $countryCode,
string $publisherCode,
string $publicationCode
): string {
$code = $countryCode . $publisherCode . $publicationCode;
$chars = str_split($code);
$checksum = (11 - (
($chars[0] * 10) +
($chars[1] * 9) +
($chars[2] * 8) +
($chars[3] * 7) +
($chars[4] * 6) +
($chars[5] * 5) +
($chars[6] * 4) +
($chars[7] * 3) +
($chars[8] * 2)) % 11) % 11;
if ($checksum == 10) {
$checksum = 'X';
}
return $checksum;
}
private static function _calculateChecksumForIsbn13Format(
string $productCode,
string $countryCode,
string $publisherCode,
string $publicationCode
): string {
$checksum = null;
$code = $productCode . $countryCode . $publisherCode . $publicationCode;
$chars = array_reverse(str_split($code));
foreach ($chars as $index => $char) {
if ($index & 1) {
$checksum += $char;
} else {
$checksum += $char * 3;
}
}
$checksum = (10 - ($checksum % 10)) % 10;
return $checksum;
}
}

View File

@ -0,0 +1,345 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
namespace Biblys\Isbn;
class Isbn
{
/**
* Converts input into an ISBN-10
*
* ISBN-10 are 10 characters long and includes hyphens.
*
* // Returns 3-464-60352-0
* $isbn10 = Isbn::convertToIsbn10("9783464603529");
*
* @param string $input A string to convert
*
* @return string
*/
static public function convertToIsbn10(string $input): string
{
return Formatter::formatAsIsbn10($input);
}
/**
* Converts input into an ISBN-13
*
* ISBN-13 are 13 characters long and includes hyphens.
*
* // Returns 978-2-207-25804-0
* $isbn10 = Isbn::convertToIsbn13("9782207258040");
*
* @param string $input A string to convert
*
* @return string
*/
static public function convertToIsbn13(string $input): string
{
return Formatter::formatAsIsbn13($input);
}
/**
* Converts input into an EAN-13
*
* EAN-13 are 13 characters long and does not include hyphens.
*
* // Returns 9782207258040
* $isbn10 = Isbn::convertToEan13("978-2-207-25804-0");
*
* @param string $input A string to convert
*
* @return string
*/
static public function convertToEan13(string $input): string
{
return Formatter::formatAsEan13($input);
}
/**
* Converts input into a GTIN-14
*
* GTIN-14 are 14 characters long and does not include hyphens.
*
* // Returns 19783464603526
* $isbn10 = Isbn::convertToGtin14("9783464603529", 1);
*
* @param string $input A string to convert
* @param int $prefix A int to preprend (defaults to 1)
*
* @return string
*/
static public function convertToGtin14(string $input, int $prefix = 1): string
{
return Formatter::formatAsGtin14($input, $prefix);
}
/**
* Validates input as a correctly formed ISBN-10
*
* // Throws because second hyphen is misplaced
* Isbn::validateAsIsbn10("3-46460-352-0");
*
* @param string $input A string to validate
*
* @throws IsbnValidationException
*/
static public function validateAsIsbn10(string $input): void
{
$expected = Formatter::formatAsIsbn10($input);
if ($input !== $expected) {
throw new IsbnValidationException(
"$input is not a valid ISBN-10. Expected $expected."
);
}
}
/**
* Validates input as a correctly formed ISBN-13
*
* // Throws because second hyphen is misplaced
* Isbn::validateAsIsbn13("978-220-7-25804-0");
*
* @param string $input A string to validate
*
* @throws IsbnValidationException
*/
static public function validateAsIsbn13(string $input): void
{
$expected = Formatter::formatAsIsbn13($input);
if ($input !== $expected) {
throw new IsbnValidationException(
"$input is not a valid ISBN-13. Expected $expected."
);
}
}
/**
* Validates input as a correctly formed EAN-13
*
* // Throws because checksum character is invalid
* Isbn::validateAsEan13("9782207258045");
*
* @param string $input A string to validate
*
* @throws IsbnValidationException
*/
static public function validateAsEan13(string $input): void
{
$expected = Formatter::formatAsEan13($input);
if ($input !== $expected) {
throw new IsbnValidationException(
"$input is not a valid EAN-13. Expected $expected."
);
}
}
/**
* Checks that an input can be parsed (and thus, formatted) by the library
*
* // Returns false because string contains invalid characters
* Isbn::validateAsEan13("9782SPI258040");
*
* @param string $input A string to check for parsability
*
* @return boolean true if the input can be parsed
*/
static public function isParsable(string $input): bool
{
try {
Parser::parse($input);
return true;
} catch (IsbnParsingException $exception) {
return false;
}
}
/* Legacy non static properties and methods (backward compatibility) */
// FIXME: deprecate and remove on next major version
private $_input;
private $_gs1productCode;
private $_countryCode;
private $_publisherCode;
private $_publicationCode;
private $_isbnAgencyCode;
private $_checksumCharacter;
private $_gtin14Prefix;
public function __construct($code = null)
{
$this->_input = $code;
try {
$parsedCode = Parser::parse($code);
$this->_gs1productCode = $parsedCode["productCode"];
$this->_countryCode = $parsedCode["countryCode"];
$this->_isbnAgencyCode = $parsedCode["agencyCode"];
$this->_publisherCode = $parsedCode["publisherCode"];
$this->_publicationCode = $parsedCode["publicationCode"];
} catch (IsbnParsingException $exception) {
// FIXME in next major version (breaking change)
// For backward compatibility reason, instanciating should not throw
}
}
/**
* Checks if ISBN is valid
*
* @deprecated
*
* @return boolean true if the ISBN is valid
*/
public function isValid()
{
trigger_error(
"Isbn->isValid is deprecated and will be removed in the future. Use Isbn::validateAs… methods instead. Learn more: https://git.io/JtAEx",
E_USER_DEPRECATED
);
try {
Parser::parse($this->_input);
return true;
} catch (\Exception $exception) {
return false;
}
}
/**
* Returns a list of errors if ISBN is invalid
*
* @deprecated
*
* @return string the error list
*/
public function getErrors()
{
trigger_error(
"Isbn->getErrors is deprecated and will be removed in the future. Use Isbn::validateAs… methods instead. Learn more: https://git.io/JtAEx",
E_USER_DEPRECATED
);
try {
Parser::parse($this->_input);
} catch (\Exception $exception) {
return '[' . $this->_input . '] ' . $exception->getMessage();
}
}
/**
* Throws an exception if ISBN is invalid
*
* @deprecated
*/
public function validate()
{
trigger_error(
"Isbn->validate is deprecated and will be removed in the future. Use Isbn::validateAs… methods instead. Learn more: https://git.io/JtAEx",
E_USER_DEPRECATED
);
Parser::parse($this->_input);
return true;
}
/**
* Formats an ISBN according to specified format
*
* @deprecated
*
* @param string $format (ISBN-10, ISBN-13, EAN-13, GTIN-14), default EAN-13
* @param string $prefix The prefix to use when formatting, default 1
*
* @return string the formatted ISBN
*/
public function format($format = 'EAN-13', $prefix = 1)
{
try {
switch ($format) {
case 'ISBN-10':
trigger_error(
"Isbn->format is deprecated and will be removed in the future. Use the Isbn::convertToIsbn10 method instead. Learn more: https://git.io/JtAEx",
E_USER_DEPRECATED
);
return Formatter::formatAsIsbn10($this->_input);
case 'ISBN-13':
case 'ISBN':
trigger_error(
"Isbn->format is deprecated and will be removed in the future. Use the Isbn::convertToIsbn13 method instead. Learn more: https://git.io/JtAEx",
E_USER_DEPRECATED
);
return Formatter::formatAsIsbn13($this->_input);
case 'GTIN-14':
trigger_error(
"Isbn->format is deprecated and will be removed in the future. Use the Isbn::convertToGtin14 method instead. Learn more: https://git.io/JtAEx",
E_USER_DEPRECATED
);
return Formatter::formatAsGtin14($this->_input, $prefix);
case 'EAN-13':
case 'EAN':
default:
trigger_error(
"Isbn->format is deprecated and will be removed in the future. Use the Isbn::convertToEan13 method instead. Learn more: https://git.io/JtAEx",
E_USER_DEPRECATED
);
return Formatter::formatAsEan13($this->_input);
}
} catch (IsbnParsingException $exception) {
// FIXME: remove message customization
// (kept for backward compatibility)
throw new IsbnParsingException(
"Cannot format invalid ISBN: [$this->_input] " . $exception->getMessage()
);
}
}
public function getProduct()
{
return $this->_gs1productCode;
}
public function getCountry()
{
return $this->_countryCode;
}
public function getPublisher()
{
return $this->_publisherCode;
}
public function getPublication()
{
return $this->_publicationCode;
}
public function getChecksum()
{
return $this->_checksumCharacter;
}
public function getAgency()
{
return $this->_isbnAgencyCode;
}
public function getGtin14Prefix()
{
return $this->_gtin14Prefix;
}
}

View File

@ -0,0 +1,17 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
namespace Biblys\Isbn;
class IsbnParsingException extends \Exception
{
}

View File

@ -0,0 +1,17 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
namespace Biblys\Isbn;
class IsbnValidationException extends \Exception
{
}

View File

@ -0,0 +1,179 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
namespace Biblys\Isbn;
class Parser
{
// FIXME: Create custom exceptions for each case
const ERROR_EMPTY = 'No code provided',
ERROR_INVALID_CHARACTERS = 'Invalid characters in the code',
ERROR_INVALID_LENGTH = 'Code is too short or too long',
ERROR_INVALID_PRODUCT_CODE = 'Product code should be 978 or 979',
ERROR_INVALID_COUNTRY_CODE = 'Country code is unknown';
public static function parse($input)
{
if (empty($input)) {
throw new IsbnParsingException(static::ERROR_EMPTY);
}
$inputWithoutHyphens = self::_stripHyphens($input);
$inputWithoutChecksum = self::_stripChecksum($inputWithoutHyphens);
if (!is_numeric($inputWithoutChecksum)) {
throw new IsbnParsingException(static::ERROR_INVALID_CHARACTERS);
}
$result = self::_extractProductCode($inputWithoutChecksum);
$inputWithoutProductCode = $result[0];
$productCode = $result[1];
$result = self::_extractCountryCode($inputWithoutProductCode, $productCode);
$inputWithoutCountryCode = $result[0];
$countryCode = $result[1];
$result = self::_extractPublisherCode($inputWithoutCountryCode, $productCode, $countryCode);
$agencyCode = $result[0];
$publisherCode = $result[1];
$publicationCode = $result[2];
return [
"productCode" => $productCode,
"countryCode" => $countryCode,
"agencyCode" => $agencyCode,
"publisherCode" => $publisherCode,
"publicationCode" => $publicationCode,
];
}
private static function _stripHyphens($input)
{
$replacements = array('-', '_', ' ');
$input = str_replace($replacements, '', $input);
return $input;
}
private static function _stripChecksum($input)
{
$length = strlen($input);
if ($length == 13 || $length == 10) {
$input = substr_replace($input, "", -1);
return $input;
}
if ($length == 12 || $length == 9) {
return $input;
}
throw new IsbnParsingException(static::ERROR_INVALID_LENGTH);
}
private static function _extractProductCode($input)
{
if (strlen($input) == 9) {
return [$input, 978];
}
$first3 = substr($input, 0, 3);
if ($first3 == 978 || $first3 == 979) {
$input = substr($input, 3);
return [$input, $first3];
}
throw new IsbnParsingException(static::ERROR_INVALID_PRODUCT_CODE);
}
private static function _extractCountryCode($input, $productCode)
{
// Get the seven first digits
$first7 = substr($input, 0, 7);
// Select the right set of rules according to the product code
$ranges = new Ranges();
$prefixes = $ranges->getPrefixes();
foreach ($prefixes as $p) {
if ($p['Prefix'] == $productCode) {
$rules = $p['Rules']['Rule'];
break;
}
}
// Select the right rule
foreach ($rules as $r) {
$ra = explode('-', $r['Range']);
if ($first7 >= $ra[0] && $first7 <= $ra[1]) {
$length = $r['Length'];
break;
}
}
// Country code is invalid
if (!isset($length) || $length === "0") {
throw new IsbnParsingException(static::ERROR_INVALID_COUNTRY_CODE);
};
$countryCode = substr($input, 0, $length);
$input = substr($input, $length);
return [$input, $countryCode];
}
/**
* Remove and save Publisher Code and Publication Code
*/
private static function _extractPublisherCode($input, $productCode, $countryCode)
{
// Get the seven first digits or less
$first7 = substr($input, 0, 7);
$inputLength = strlen($first7);
// Select the right set of rules according to the agency (product + country code)
$ranges = new Ranges();
$groups = $ranges->getGroups();
foreach ($groups as $g) {
if ($g['Prefix'] <> $productCode . '-' . $countryCode) {
continue;
}
$rules = $g['Rules']['Rule'];
$agency = $g['Agency'];
// Select the right rule
foreach ($rules as $rule) {
// Get min and max value in range
// and trim values to match code length
$range = explode('-', $rule['Range']);
$min = substr($range[0], 0, $inputLength);
$max = substr($range[1], 0, $inputLength);
// If first 7 digits is smaller than min
// or greater than max, continue to next rule
if ($first7 < $min || $first7 > $max) {
continue;
}
$length = $rule['Length'];
$publisherCode = substr($input, 0, $length);
$publicationCode = substr($input, $length);
return [$agency, $publisherCode, $publicationCode];
}
break;
}
}
}

View File

@ -0,0 +1,35 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
namespace Biblys\Isbn;
class Ranges
{
private $prefixes, $groups;
public function __construct()
{
include('ranges-array.php');
$this->prefixes = $prefixes;
$this->groups = $groups;
}
public function getPrefixes()
{
return $this->prefixes;
}
public function getGroups()
{
return $this->groups;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testConvertToEan13 extends TestCase
{
public function testFormatEan13()
{
$ean13 = Isbn::convertToEan13("978-2-207-25804-0");
$this->assertEquals(
"9782207258040",
$ean13,
"It should convert to EAN-13"
);
}
public function testFormatEan13InvalidIsbn()
{
$this->expectException("Biblys\Isbn\IsbnParsingException");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::convertToEan13("ABC-80-7203-7");
}
}

View File

@ -0,0 +1,51 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testConvertToGtin14 extends TestCase
{
public function testFormatGtin14()
{
$gtin14 = Isbn::convertToGtin14("9783464603529", 2);
$this->assertEquals(
"29783464603523",
$gtin14,
"It should convert to GTIN-14"
);
}
public function testFormatGtin14WithDefaultPrefix()
{
$gtin14 = Isbn::convertToGtin14("9783464603529");
$this->assertEquals(
"19783464603526",
$gtin14,
"It should convert to GTIN-14 using 1 as default prefix"
);
}
public function testFormatGtin14InvalidIsbn()
{
$this->expectException("Biblys\Isbn\IsbnParsingException");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::convertToGtin14("ABC-80-7203-7", 1);
}
}

View File

@ -0,0 +1,52 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testConvertToIsbn10 extends TestCase
{
public function testFormatIsbn10()
{
$isbn10 = Isbn::convertToIsbn10("9783464603529");
$this->assertEquals(
"3-464-60352-0",
$isbn10,
"It should convert to ISBN-10"
);
}
public function testFormatIsbn10WithX()
{
$isbn10 = Isbn::convertToIsbn10("978-80-7203-717-9");
$this->assertEquals(
"80-7203-717-X",
$isbn10,
"It should convert to ISBN-10 with X as a checksum character"
);
}
public function testFormatIsbn10InvalidIsbn()
{
$this->expectException("Biblys\Isbn\IsbnParsingException");
// FIXME: Improve message: Input contains invalid characters "ABC"
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::convertToIsbn10("ABC-80-7203-7");
}
}

View File

@ -0,0 +1,41 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testConvertToIsbn13 extends TestCase
{
public function testFormatIsbn13()
{
$Isbn13 = Isbn::convertToIsbn13("9782207258040");
$this->assertEquals(
"978-2-207-25804-0",
$Isbn13,
"It should convert to ISBN-13"
);
}
public function testFormatIsbn13InvalidIsbn()
{
$this->expectException("Biblys\Isbn\IsbnParsingException");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::convertToIsbn13("ABC-80-7203-7");
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../../vendor/autoload.php';
use Biblys\Isbn\Isbn as Isbn;
use PHPUnit\Framework\TestCase;
class testConstructor extends TestCase
{
/**
* Non-regression test for Github issue #5
* https://github.com/biblys/isbn/pull/5
*/
public function testUnknownPrefix()
{
$isbn = new Isbn("9790706801940");
$this->expectNotToPerformAssertions("Should not throw");
}
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../../vendor/autoload.php';
use Biblys\Isbn\Isbn as Isbn;
use PHPUnit\Framework\TestCase;
class testFormatIsbn extends TestCase
{
protected function setUp(): void
{
PHPUnit\Framework\Error\Deprecated::$enabled = false;
}
public function testDeprecatedNotice()
{
PHPUnit\Framework\Error\Deprecated::$enabled = true;
$this->expectException('PHPUnit\Framework\Error\Deprecated');
$this->expectExceptionMessage(
"Isbn->format is deprecated and will be removed in the future. Use the Isbn::convertToIsbn13 method instead. Learn more: https://git.io/JtAEx"
);
$isbn = new Isbn('9782207258040');
$isbn->format('ISBN-13');
}
public function testFormatIsbn13()
{
$isbn = new Isbn('9782207258040');
$this->assertEquals($isbn->format('ISBN-13'), "978-2-207-25804-0");
}
public function testFormatIsbn10()
{
$isbn10 = new Isbn('9783464603529');
$this->assertEquals($isbn10->format('ISBN-10'), "3-464-60352-0");
}
public function testFormatEan13()
{
$isbn10 = new Isbn("978-2-207-25804-0");
$this->assertEquals($isbn10->format('EAN'), "9782207258040");
}
public function testFormatEan_13()
{
$isbn10 = new Isbn("978-2-207-25804-0");
$this->assertEquals($isbn10->format('EAN-13'), "9782207258040");
}
public function testFormatGtin14()
{
$isbn = new Isbn('9783464603529');
$this->assertEquals($isbn->format('GTIN-14'), '19783464603526');
}
public function testMauritiusRange()
{
$isbn = new Isbn('9786130971311');
$this->assertEquals($isbn->format('ISBN-13'), "978-613-0-97131-1");
}
}

View File

@ -0,0 +1,42 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../../vendor/autoload.php';
use Biblys\Isbn\Isbn as Isbn;
use PHPUnit\Framework\TestCase;
class testGetErrors extends TestCase
{
public function testDeprecatedNotice()
{
PHPUnit\Framework\Error\Deprecated::$enabled = true;
$this->expectException('PHPUnit\Framework\Error\Deprecated');
$this->expectExceptionMessage(
"Isbn->getErrors is deprecated and will be removed in the future. Use Isbn::validateAs… methods instead. Learn more: https://git.io/JtAEx"
);
$isbn = new Isbn("6897896354577");
$isbn->getErrors();
}
public function testInvalidIsbn()
{
PHPUnit\Framework\Error\Deprecated::$enabled = false;
$isbn = new Isbn("6897896354577");
$this->assertEquals($isbn->getErrors(), '[6897896354577] Product code should be 978 or 979');
}
}

View File

@ -0,0 +1,65 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../../vendor/autoload.php';
use Biblys\Isbn\Isbn as Isbn;
use PHPUnit\Framework\TestCase;
class testIsbnIsValid extends TestCase
{
protected function setUp(): void
{
PHPUnit\Framework\Error\Deprecated::$enabled = false;
}
public function testDeprecationNotice(): void
{
PHPUnit\Framework\Error\Deprecated::$enabled = true;
$this->expectException('PHPUnit\Framework\Error\Deprecated');
$this->expectExceptionMessage(
"Isbn->isValid is deprecated and will be removed in the future. Use Isbn::validateAs… methods instead. Learn more: https://git.io/JtAEx"
);
$isbn = new Isbn('9782207258040');
$isbn->isValid();
}
public function testIsValid()
{
$isbn = new Isbn('9782207258040');
$this->assertTrue($isbn->isValid());
}
public function testIsNotValid()
{
$invalid = new Isbn('5780AAC728440');
$this->assertFalse($invalid->isValid());
}
public function testIsbn10WithChecksumX()
{
$isbn = new ISBN('80-7203-717-X');
$this->assertTrue($isbn->isValid());
}
public function testValidateMexicanIsbn()
{
$isbn = new Isbn("9700764923");
$this->assertTrue($isbn->isValid());
}
}

View File

@ -0,0 +1,66 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../../vendor/autoload.php';
use Biblys\Isbn\Isbn as Isbn;
use PHPUnit\Framework\TestCase;
class testValidateIsbn extends TestCase
{
protected function setUp(): void
{
PHPUnit\Framework\Error\Deprecated::$enabled = false;
}
public function testDeprecatedNotice(): void
{
PHPUnit\Framework\Error\Deprecated::$enabled = true;
$this->expectException('PHPUnit\Framework\Error\Deprecated');
$this->expectExceptionMessage(
"Isbn->validate is deprecated and will be removed in the future. Use Isbn::validateAs… methods instead. Learn more: https://git.io/JtAEx"
);
$isbn = new Isbn('9782843449499');
$isbn->validate();
}
public function testValidateValidIsbn()
{
$isbn = new Isbn('9782843449499');
$this->assertTrue($isbn->validate());
}
/**
* Non-regression test for Github issue #6
* https://github.com/biblys/isbn/issues/6
*/
public function testValidateIsbn10WithChecksumX()
{
$isbn = new Isbn('80-7203-717-X');
$this->assertTrue($isbn->validate());
}
/**
* Non-regression test for Github issue #21
* https://github.com/biblys/isbn/issues/21
*/
public function testValidateMexicanIsbn()
{
$isbn = new Isbn("9700764923");
$this->assertTrue($isbn->validate());
}
}

View File

@ -0,0 +1,37 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testIsParsable extends TestCase
{
public function testParsableIsbn()
{
$isParsable = Isbn::isParsable("9782207258040");
$this->assertTrue($isParsable);
}
public function testUnparsableIsbn()
{
$isParsable = Isbn::isParsable("9782SPI258040");
$this->assertFalse($isParsable);
}
}

View File

@ -0,0 +1,54 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testValidateAsEan13 extends TestCase
{
public function testValidIsbn()
{
Isbn::validateAsEan13("9782207258040");
$this->expectNotToPerformAssertions("It should not throw");
}
public function testUnparsableIsbn()
{
$this->expectException("Biblys\Isbn\IsbnParsingException");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::validateAsEan13("9782SPI258040");
}
public function testIsbnWithHyphens()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("978-2-207-25804-0 is not a valid EAN-13. Expected 9782207258040.");
Isbn::validateAsEan13("978-2-207-25804-0");
}
public function testIsbnWithIncorrectCheckum()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("9782207258049 is not a valid EAN-13. Expected 9782207258040.");
Isbn::validateAsEan13("9782207258049");
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testValidateAsIsbn10 extends TestCase
{
public function testValidIsbn()
{
Isbn::validateAsIsbn10("3-464-60352-0");
$this->expectNotToPerformAssertions("It should not throw");
}
public function testUnparsableIsbn()
{
$this->expectException("Biblys\Isbn\IsbnParsingException");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::validateAsIsbn10("3-ABC-60352-0");
}
public function testIsbnWithMisplacedHyphen()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("3-46460-352-0 is not a valid ISBN-10. Expected 3-464-60352-0.");
Isbn::validateAsIsbn10("3-46460-352-0");
}
public function testIsbnWithoutHyphens()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("3464603520 is not a valid ISBN-10. Expected 3-464-60352-0.");
Isbn::validateAsIsbn10("3464603520");
}
public function testIsbnWithIncorrectCheckum()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("3-46460-352-X is not a valid ISBN-10. Expected 3-464-60352-0.");
Isbn::validateAsIsbn10("3-46460-352-X");
}
}

View File

@ -0,0 +1,107 @@
<?php
/*
* This file is part of the biblys/isbn package.
*
* (c) Clément Bourgoin
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Biblys\Isbn\Isbn;
use PHPUnit\Framework\TestCase;
class testValidateAsIsbn13 extends TestCase
{
public function testValidIsbn()
{
Isbn::validateAsIsbn13("978-2-207-25804-0");
$this->expectNotToPerformAssertions("It should not throw");
}
public function testUnparsableIsbn()
{
$this->expectException("Biblys\Isbn\IsbnParsingException");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::validateAsIsbn13("978-2-SPI-25804-0");
}
public function testIsbnWithMisplacedHyphen()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("978-220-7-25804-0 is not a valid ISBN-13. Expected 978-2-207-25804-0.");
Isbn::validateAsIsbn13("978-220-7-25804-0");
}
public function testIsbnWithoutHyphens()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("9782207258040 is not a valid ISBN-13. Expected 978-2-207-25804-0.");
Isbn::validateAsIsbn13("9782207258040");
}
public function testIsbnWithIncorrectCheckum()
{
$this->expectException("Biblys\Isbn\IsbnValidationException");
$this->expectExceptionMessage("978-2-207-25804-2 is not a valid ISBN-13. Expected 978-2-207-25804-0.");
Isbn::validateAsIsbn13("978-2-207-25804-2");
}
public function testValidateInvalidProductCode()
{
$this->expectException("Exception");
$this->expectExceptionMessage("Product code should be 978 or 979");
Isbn::validateAsIsbn13('6752843449499');
}
public function testValidateInvalidCharacters()
{
$this->expectException("Exception");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::validateAsIsbn13('5780AAC728440');
}
public function testIsbnWithInvalidProductCode()
{
$this->expectException("Exception");
$this->expectExceptionMessage("Product code should be 978 or 979");
Isbn::validateAsIsbn13('6897896354577');
}
public function testIsbnWithInvalidCountryCode()
{
$this->expectException("Exception");
$this->expectExceptionMessage("Country code is unknown");
Isbn::validateAsIsbn13('9792887382562');
}
/**
* Non regression-test for Github issue #22
* https://github.com/biblys/isbn/issues/22
*/
public function testOtherInvalidIsbn()
{
$this->expectException("Exception");
$this->expectExceptionMessage("Invalid characters in the code");
Isbn::validateAsIsbn13("34995031X");
}
}