Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Add ISBN-10 & ISBN-13 codes #451

Merged
merged 3 commits into from
May 20, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,8 @@ Each of the generator properties (like `name`, `address`, and `lorem`) are calle

ean13 // '4006381333931'
ean8 // '73513537'
isbn13 // '9790404436093'
isbn10 // '4881416324

### `Faker\Provider\Miscellaneous`

Expand Down
2 changes: 2 additions & 0 deletions src/Faker/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
*
* @property string $ean13
* @property string $ean8
* @property string $isbn13
* @property string $isbn10
*
* @property string $phoneNumber
*
Expand Down
61 changes: 61 additions & 0 deletions src/Faker/Provider/Barcode.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

/**
* @see http://en.wikipedia.org/wiki/EAN-13
* @see http://en.wikipedia.org/wiki/ISBN
*/
class Barcode extends \Faker\Provider\Base
{
Expand All @@ -27,6 +28,38 @@ protected static function eanChecksum($input)
return (10 - $sums % 10) % 10;
}

/**
* ISBN-10 check digit
* @link http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digits
*
* @param string $input ISBN without check-digit
* @throws \LengthException When wrong input length passed
*
* @return integer Check digit
*/
protected static function isbnChecksum($input)
{
// We're calculating check digit for ISBN-10
// so, the length of the input should be 9
$length = 9;

if (strlen($input) != $length) {
throw new \LengthException(sprintf('Input length should be equal to %d', $length));
}

$digits = str_split($input);
array_walk(
$digits,
function (&$digit, $position) {
$digit = (10 - $position) * $digit;
}
);
$result = (11 - array_sum($digits) % 11) % 11;

// 10 is replaced by X
return ($result < 10)?$result:'X';
}

/**
* Get a random EAN13 barcode.
* @return string
Expand All @@ -46,4 +79,32 @@ public function ean8()
{
return $this->ean(8);
}

/**
* Get a random ISBN-10 code
* @link http://en.wikipedia.org/wiki/International_Standard_Book_Number
*
* @return string
* @example '4881416324'
*/
public function isbn10()
{
$code = $this->numerify(str_repeat('#', 9));

return $code . static::isbnChecksum($code);
}

/**
* Get a random ISBN-13 code
* @link http://en.wikipedia.org/wiki/International_Standard_Book_Number
*
* @return string
* @example '9790404436093'
*/
public function isbn13()
{
$code = '97' . static::numberBetween(8, 9) . $this->numerify(str_repeat('#', 9));

return $code . static::eanChecksum($code);
}
}