PHPackages                             xterr/php-cncodes - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. xterr/php-cncodes

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

xterr/php-cncodes
=================

CN (Combined Nomenclature) Codes

1.0.0(3mo ago)03MITPHPPHP ^8.0CI passing

Since Feb 18Pushed 3mo agoCompare

[ Source](https://github.com/xterr/php-cncodes)[ Packagist](https://packagist.org/packages/xterr/php-cncodes)[ RSS](/packages/xterr-php-cncodes/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (8)Versions (2)Used By (0)

PHP CN Codes
============

[](#php-cn-codes)

[![PHP Version](https://camo.githubusercontent.com/854124dd57cfd3aad3184fca9760bf1f33a5ec1e5d080cfbe8aa4e3337ba46e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e302d3838393242462e737667)](https://php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![Latest Version](https://camo.githubusercontent.com/9ad85bbe33754794170e25a763da8a5450effd4554a1edfff20c58d61036aaf9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f78746572722f7068702d636e636f6465732e737667)](https://packagist.org/packages/xterr/php-cncodes)

A framework-agnostic PHP library for working with CN (Combined Nomenclature) codes, including built-in translation support for 23 EU languages.

Overview
--------

[](#overview)

CN codes are the EU's 8-digit goods classification system used for international trade, customs declarations, and trade statistics. This library provides:

- Complete CN code database (2023, 2024, 2025, 2026)
- Five-level hierarchy: Sections, Chapters, Headings, Subheadings, CN Codes
- Lazy loading per version — only the requested year's data is loaded into memory
- Supplementary unit information on CN codes
- Framework-agnostic translation system with 23 language support
- Adapters for Symfony, Laravel, and native PHP
- Zero runtime dependencies for the core library

Installation
------------

[](#installation)

```
composer require xterr/php-cncodes
```

Quick Start
-----------

[](#quick-start)

### Basic Usage (No Translation)

[](#basic-usage-no-translation)

```
use Xterr\CnCodes\CnCodesFactory;
use Xterr\CnCodes\CnVersion;

$factory = new CnCodesFactory();
$codes = $factory->getCodes();

// Find a specific CN code
$cnCode = $codes->getByCodeAndVersion('01012100', CnVersion::VERSION_2026);

echo $cnCode->getCode();              // "01012100"
echo $cnCode->getRawCode();           // "0101 21 00"
echo $cnCode->getName();              // "Pure-bred breeding animals" (English)
echo $cnCode->getLocalName();         // "Pure-bred breeding animals" (falls back to English)
echo $cnCode->getSection();           // "I"
echo $cnCode->getChapter();           // "01"
echo $cnCode->getHeading();           // "0101"
echo $cnCode->getSupplementaryUnit(); // "PST"
```

### With Translation Support

[](#with-translation-support)

```
use Xterr\CnCodes\CnCodesFactory;
use Xterr\CnCodes\CnVersion;
use Xterr\CnCodes\Translation\Adapter\ArrayTranslator;

// Use the built-in ArrayTranslator for zero-dependency translations
$translator = new ArrayTranslator(null, 'de');
$factory = new CnCodesFactory(null, $translator);

$section = $factory->getSections()->getByCodeAndVersion('I', CnVersion::VERSION_2026);

echo $section->getName();      // "LIVE ANIMALS; ANIMAL PRODUCTS" (always English)
echo $section->getLocalName(); // "LEBENDE TIERE UND WAREN TIERISCHEN URSPRUNGS" (German translation)
```

Translation Adapters
--------------------

[](#translation-adapters)

The library provides a framework-agnostic `TranslatorInterface` with multiple adapter implementations.

### ArrayTranslator (Native PHP - Zero Dependencies)

[](#arraytranslator-native-php---zero-dependencies)

Best for standalone PHP applications or when you don't want any framework dependencies.

```
use Xterr\CnCodes\CnCodesFactory;
use Xterr\CnCodes\Translation\Adapter\ArrayTranslator;

// Simple usage with locale
$translator = new ArrayTranslator(null, 'fr');
$factory = new CnCodesFactory(null, $translator);

// With fallback locale
$translator = new ArrayTranslator(null, 'fr', 'en');

// Change locale at runtime
$translator->setLocale('de');

// Get available locales
$locales = $translator->getAvailableLocales();
// ['bg', 'cs', 'da', 'de', 'el', 'es', 'et', 'fi', 'fr', 'ga', 'hr', 'hu', 'it', 'lt', 'lv', 'mt', 'nl', 'pl', 'pt', 'ro', 'sk', 'sl', 'sv']
```

### SymfonyTranslatorAdapter

[](#symfonytranslatoradapter)

For Symfony applications. Requires `symfony/translation-contracts`.

```
composer require symfony/translation-contracts
```

```
use Xterr\CnCodes\CnCodesFactory;
use Xterr\CnCodes\Translation\Adapter\SymfonyTranslatorAdapter;
use Symfony\Contracts\Translation\TranslatorInterface;

// In a Symfony controller or service
public function __construct(
    TranslatorInterface $symfonyTranslator
) {
    $adapter = new SymfonyTranslatorAdapter($symfonyTranslator);
    $this->cnCodesFactory = new CnCodesFactory(null, $adapter);
}

// Usage
$codes = $this->cnCodesFactory->getCodes();
$cnCode = $codes->getByCodeAndVersion('01012100');

// Uses the locale from Symfony's translator (auto-detected from request)
echo $cnCode->getLocalName();
```

#### Symfony Configuration

[](#symfony-configuration)

Copy or generate translation files to your Symfony translations directory:

```
# Generate YAML files for Symfony
php bin/console cn:translations:build yaml-generate

# Copy to your Symfony project
cp Resources/translations/yaml/cnCodes.*.yaml /path/to/symfony/translations/
```

Or configure as a translation resource in `config/packages/translation.yaml`:

```
framework:
  translator:
    paths:
      - '%kernel.project_dir%/vendor/xterr/php-cncodes/Resources/translations'
```

### LaravelTranslatorAdapter

[](#laraveltranslatoradapter)

For Laravel applications. Requires `illuminate/contracts`.

```
composer require illuminate/contracts
```

```
use Xterr\CnCodes\CnCodesFactory;
use Xterr\CnCodes\Translation\Adapter\LaravelTranslatorAdapter;
use Illuminate\Contracts\Translation\Translator;

// In a Laravel service provider
public function register()
{
    $this->app->singleton(CnCodesFactory::class, function ($app) {
        $adapter = new LaravelTranslatorAdapter($app->make(Translator::class));
        return new CnCodesFactory(null, $adapter);
    });
}

// Usage in controller
public function show(CnCodesFactory $factory, string $code)
{
    $cnCode = $factory->getCodes()->getByCodeAndVersion($code);

    // Uses Laravel's current locale
    return response()->json([
        'code' => $cnCode->getCode(),
        'name' => $cnCode->getName(),
        'localName' => $cnCode->getLocalName(),
    ]);
}
```

#### Laravel Configuration

[](#laravel-configuration)

Generate and publish Laravel translation files:

```
# Generate Laravel PHP files
php bin/console cn:translations:build all

# Copy to your Laravel project
cp -r Resources/translations/laravel/cncodes /path/to/laravel/lang/vendor/
```

### NullTranslator (Default)

[](#nulltranslator-default)

Returns the original English text. Used internally as the default when no translator is provided.

```
use Xterr\CnCodes\Translation\Adapter\NullTranslator;

$translator = new NullTranslator();
echo $translator->translate('Pure-bred breeding animals'); // "Pure-bred breeding animals"
```

### Custom Translator

[](#custom-translator)

Implement the `TranslatorInterface` for custom translation sources:

```
use Xterr\CnCodes\Translation\TranslatorInterface;

class DatabaseTranslator implements TranslatorInterface
{
    public function translate(string $id, ?string $locale = null, string $domain = 'cnCodes'): string
    {
        // Your custom translation logic
        return $this->repository->findTranslation($id, $locale) ?? $id;
    }
}
```

Supported Languages
-------------------

[](#supported-languages)

The library includes translations for 23 EU languages:

CodeLanguageCodeLanguagebgBulgarianitItaliancsCzechltLithuaniandaDanishlvLatviandeGermanmtMalteseelGreeknlDutchesSpanishplPolishetEstonianptPortuguesefiFinnishroRomanianfrFrenchskSlovakgaIrishslSlovenianhrCroatiansvSwedishhuHungarianCnCode Properties
-----------------

[](#cncode-properties)

MethodReturn TypeDescription`getCode()``string`Normalized code (e.g., "01012100")`getRawCode()``string`Space-separated code (e.g., "0101 21 00")`getName()``string`English name`getLocalName()``string`Translated name (falls back to English)`getVersion()``int`Version year (2023, 2024, 2025, or 2026)`getSection()``?string`Parent section (e.g., "I")`getChapter()``?string`Parent chapter (e.g., "01")`getHeading()``?string`Parent heading (e.g., "0101")`getSubheading()``?string`Parent subheading (e.g., "010121") or null`getSupplementaryUnit()``?string`Supplementary unit code (e.g., "PST", "KGM") or nullCN Hierarchy
------------

[](#cn-hierarchy)

The Combined Nomenclature follows a five-level hierarchy:

```
Section (I-XXI)        — 21 broad categories
  └─ Chapter (01-97)   — 97 product groups
      └─ Heading (4-digit)    — ~957 product types
          └─ Subheading (6-digit) — ~1,830 HS subheadings
              └─ CN Code (8-digit)    — ~9,790 specific goods

```

CN Versions
-----------

[](#cn-versions)

```
CnVersion::VERSION_2023 // 2023
CnVersion::VERSION_2024 // 2024
CnVersion::VERSION_2025 // 2025
CnVersion::VERSION_2026 // 2026
```

Iterating Over Codes
--------------------

[](#iterating-over-codes)

```
$factory = new CnCodesFactory();
$codes = $factory->getCodes();

// Iterate all codes (loads all versions)
foreach ($codes as $cnCode) {
    echo $cnCode->getCode() . ': ' . $cnCode->getLocalName() . "\n";
}

// Count total codes across all versions
echo count($codes); // ~39,087 codes

// Get codes for a specific version only
$codes2026 = $codes->getAllByVersion(CnVersion::VERSION_2026);
echo count($codes2026); // 9,791 codes

// Convert to array
$array = $codes->toArray();
```

Data Source
-----------

[](#data-source)

CN classification data is sourced from the official [EU Vocabularies](https://op.europa.eu/en/web/eu-vocabularies/taxonomies) (RDF/XML format), published by the Publications Office of the European Union.

Individual datasets can be downloaded per year:

- [Combined Nomenclature 2026](https://op.europa.eu/en/web/eu-vocabularies/dataset/-/resource?uri=http://publications.europa.eu/resource/dataset/combined-nomenclature-2026)
- [Combined Nomenclature 2025](https://op.europa.eu/en/web/eu-vocabularies/dataset/-/resource?uri=http://publications.europa.eu/resource/dataset/combined-nomenclature-2025)
- [Combined Nomenclature 2024](https://op.europa.eu/en/web/eu-vocabularies/dataset/-/resource?uri=http://publications.europa.eu/resource/dataset/combined-nomenclature-2024)
- [Combined Nomenclature 2023](https://op.europa.eu/en/web/eu-vocabularies/dataset/-/resource?uri=http://publications.europa.eu/resource/dataset/combined-nomenclature-2023)

Building Translation Files
--------------------------

[](#building-translation-files)

The library includes console commands to build translation files in different formats.

```
# Build all formats
composer translations:build

# Build specific formats
composer translations:php      # PHP arrays (source of truth)
composer translations:yaml     # Symfony YAML format
composer translations:laravel  # Laravel PHP format
```

API Platform Integration
------------------------

[](#api-platform-integration)

For Symfony API Platform, expose `CpvCode` with the `localName` property:

```
# config/api_platform/cn_code.yaml
Xterr\CnCodes\CnCode:
  attributes:
    normalization_context:
      groups: [ 'cn_code:read' ]
  properties:
    code:
      groups: [ 'cn_code:read' ]
    name:
      groups: [ 'cn_code:read' ]
    localName:
      groups: [ 'cn_code:read' ]
    version:
      groups: [ 'cn_code:read' ]
    section:
      groups: [ 'cn_code:read' ]
    heading:
      groups: [ 'cn_code:read' ]
    subheading:
      groups: [ 'cn_code:read' ]
    supplementaryUnit:
      groups: [ 'cn_code:read' ]
```

Testing
-------

[](#testing)

```
composer install
./vendor/bin/phpunit
```

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0
- ext-json

### Optional Dependencies

[](#optional-dependencies)

- `symfony/translation-contracts` - For Symfony integration
- `illuminate/contracts` - For Laravel integration
- `symfony/console` + `symfony/yaml` + `sweetrdf/easyrdf` - For CLI data generation (dev only)

License
-------

[](#license)

This library is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Credits
-------

[](#credits)

- [Razvan Ceana](https://github.com/xterr) - Author
- CN code data sourced from the [EU Vocabularies](https://op.europa.eu/en/web/eu-vocabularies/taxonomies)

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance82

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

90d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d9526b453abaa7d569fdacdf58cb0f55aa8d889f68f5b622344a28b37eb6c17d?d=identicon)[razvanceana](/maintainers/razvanceana)

---

Top Contributors

[![xterr](https://avatars.githubusercontent.com/u/619509?v=4)](https://github.com/xterr "xterr (2 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/xterr-php-cncodes/health.svg)

```
[![Health](https://phpackages.com/badges/xterr-php-cncodes/health.svg)](https://phpackages.com/packages/xterr-php-cncodes)
```

###  Alternatives

[based/momentum-trail

Fully typed frontend route helper for Laravel apps

80389.6k](/packages/based-momentum-trail)[kornrunner/secp256k1

Pure PHP secp256k1

37566.4k109](/packages/kornrunner-secp256k1)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
