janisvepris / gs1-decoder
A library for parsing GS1 codes in PHP
Installs: 5 732
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.48
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10
README
GS1 Barcode decoder
A simple library that decodes GS1 barcodes. For a full list of supported application identifiers that ship with this package, see supported identifiers.
Instalation
This package requires PHP ^8.2
composer require janisvepris/gs1-decoder
Usage
Decode GS1 barcode
<?php use JanisVepris\GS1Decoder\Decoder; use Janisvepris\Gs1Decoder\ApplicationIdentifier\Gtin; $barcode = '0112345678901234[FNC1]2140928049820384[FNC1]'; $decoder = new Decoder(); $decoded = $decoder->decode($barcode); $decoded->hasIdentifier(Gtin::CODE); $decoded->getIdentifier(Gtin::CODE)->getValue();
Custom application identifier code -> class map
Normally, the decoder gets initialized with a default identifier class map which includes all the identifiers that ship with this package. You can override it with your own.
<?php use JanisVepris\GS1Decoder\Decoder; use Janisvepris\Gs1Decoder\ApplicationIdentifier\Gtin; use Janisvepris\Gs1Decoder\IdentifierMap; $barcode = '0112345678901234'; $decoder = new Decoder(new IdentifierMap([ '01' => Gtin::class, ])); // or $decoder = new Decoder(); $decoder->setIdentifierMap(new IdentifierMap([ '01' => Gtin::class, ])); $decoded = $decoder->decode($barcode);
Define your own application identifier class
Multiple abstract identifier classes are available for extension:
SimpleIdentifier
-string
value, set lengthDateIdentifier
-DateTime
value, set lengthDecimalIdentifier
-float
value, set lengthVariableLengthIdentifier
-string
value, variable length (min-max)
You can define your own as long as they implement ApplicationIdentifierInterface
.
<?php use JanisVepris\GS1Decoder\Decoder; class MyGtinIdentifier extends SimpleIdentifier { protected $code = '01'; protected int $length = 99; protected string $englishTitle = 'My awesome title'; } // Replace the default identifier class map with your own $decoder = new Decoder(new IdentifierMap([ '01' => MyGtinIdentifier::class, ])); // or add your own identifier class to the default map $decoder = new Decoder(); $decoder->getIdentifierMap() ->addIdentifierClass('01', MyGtinIdentifier::class)
Note
This package does not validate the barcode. It tries to decode it as is.