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

Improve barcode formatter speed, add tests for it #412

Merged
merged 1 commit into from
Sep 1, 2014
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: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ The populator uses name and column type guessers to populate each column with re
```php
<?php
$populator->addEntity('Book', 5, array(
'ISBN' => function() use ($generator) { return $generator->randomNumber(13); }
'ISBN' => function() use ($generator) { return $generator->ean13(); }
));
```

Expand Down
21 changes: 11 additions & 10 deletions src/Faker/Provider/Barcode.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,22 @@ class Barcode extends \Faker\Provider\Base
{
private function ean($length = 13)
{
$code = array();
for ($i = 0; $i < $length - 1; $i++) {
$code[] = static::randomDigit();
}
$code = $this->numerify(str_repeat('#', $length - 1));

$sequence = $length == 8 ? array(3, 1) : array(1, 3);
return $code . static::eanChecksum($code);
}

/**
* Utility function for computing EAN checksums
*/
protected static function eanChecksum($input)
{
$sequence = (strlen($input) - 1) == 8 ? array(3, 1) : array(1, 3);
$sums = 0;
foreach ($code as $n => $digit) {
foreach (str_split($input) as $n => $digit) {
$sums += $digit * $sequence[$n % 2];
}

$checksum = (10 - $sums % 10) % 10;

return implode('', $code) . $checksum;
return (10 - $sums % 10) % 10;
}

/**
Expand Down
23 changes: 21 additions & 2 deletions test/Faker/Provider/BarcodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,39 @@

class BarcodeTest extends \PHPUnit_Framework_TestCase
{
private $faker;

public function setUp()
{
$faker = new Generator();
$faker->addProvider(new Barcode($faker));
$faker->seed(0);
$this->faker = $faker;
}

public function testEan8()
{
$this->assertRegExp('/[\d]{8}/', $this->faker->ean8());
$code = $this->faker->ean8();
$this->assertRegExp('/^\d{8}$/i', $code);
$codeWitoutChecksum = substr($code, 0, -1);
$checksum = substr($code, -1);
$this->assertEquals(TestableBarcode::eanChecksum($codeWitoutChecksum), $checksum);
}

public function testEan13()
{
$this->assertRegExp('/[\d]{13}/', $this->faker->ean13());
$code = $this->faker->ean13();
$this->assertRegExp('/^\d{13}$/i', $code);
$codeWitoutChecksum = substr($code, 0, -1);
$checksum = substr($code, -1);
$this->assertEquals(TestableBarcode::eanChecksum($codeWitoutChecksum), $checksum);
}
}

class TestableBarcode extends Barcode
{
public static function eanChecksum($input)
{
return parent::eanChecksum($input);
}
}