xaamin / array-analizer
Builds a brand new array from a template: reorders keys and removes unknown or empty values
Requires
- php: ^8.3
Requires (Dev)
- pestphp/pest: ^3.0
- phpstan/phpstan: ^2.1
- squizlabs/php_codesniffer: ^3.8
Suggests
- ext-mbstring: Multibyte-safe case-insensitive key matching
Provides
None
Conflicts
None
Replaces
None
README
Builds a brand new PHP array from a template ("key map" or "skeleton"): the result is reordered following the map, keys are matched case-insensitively and returned with the map's canonical name, and, in strict mode, unknown keys and empty values are removed.
Requirements
- PHP
^8.3. - Optional:
ext-mbstring, for multibyte-safe case-insensitive key matching (e.g.Año/AÑO). Without it, matching falls back tostrtolower.
No Composer dependencies.
Installation
composer require xaamin/array-analizer
Usage
Order and clean (strict mode)
use Xaamin\ArrayAnalizer\ArrayBonesAnalizer;
$analizer = new ArrayBonesAnalizer([
'Version', 'Series', 'Number',
'Author' => ['Code', 'Name', 'Category'],
'Items' => ['Item' => ['Sku', 'Quantity', 'Description', 'Amount']],
]);
$data = $analizer->clean([
'items' => ['Item' => [
['Amount' => '100.00', 'Description' => 'Product A', 'Quantity' => '1', 'Sku' => 'P-001'],
['Amount' => '50.00', 'Description' => '', 'quantity' => '2', 'Unknown' => 'x'],
]],
'AUTHOR' => ['Name' => 'ACME CORP', 'Code' => 'ACME-001'],
'Number' => null,
'Series' => '',
'Version' => '4.0',
'Extra' => 'dropped',
]);
// [
// 'Version' => '4.0',
// 'Author' => ['Code' => 'ACME-001', 'Name' => 'ACME CORP'],
// 'Items' => ['Item' => [
// ['Sku' => 'P-001', 'Quantity' => '1', 'Description' => 'Product A', 'Amount' => '100.00'],
// ['Quantity' => '2', 'Amount' => '50.00'],
// ]],
// ]
Order only (non-strict mode)
With $strict = false the result contains every key of the map, in order; missing keys are null.
$analizer->clean(['version' => '4.0', 'Extra' => 'x'], false);
// ['Version' => '4.0', 'Series' => null, 'Number' => null, 'Author' => null, 'Items' => null]
Extension nodes
Empty sub-arrays are normally removed in strict mode. Direct children of the nodes passed to
setExtensionNodes() are kept even when empty:
$analizer = (new ArrayBonesAnalizer(['Plugins' => ['Cache' => []]]))
->setExtensionNodes(['Plugins']);
$analizer->clean(['Plugins' => ['Cache' => []]]); // ['Plugins' => ['Cache' => []]]
Invalid input
If the data has a non-empty scalar where the map expects a node (or a scalar item inside a list of
nodes), clean() throws Xaamin\ArrayAnalizer\Exceptions\InvalidNodeException
(extends InvalidArgumentException); getPath() returns the dot path of the node:
use Xaamin\ArrayAnalizer\Exceptions\InvalidNodeException;
try {
$analizer->clean(['Items' => ['Item' => [['Amount' => '1'], 'oops']]]);
} catch (InvalidNodeException $e) {
$e->getPath(); // 'Items.Item.1'
$e->getMessage(); // 'The node "Items.Item.1" must be an array, scalar value given.'
}
Validation mode (order only, fix nothing)
For a validator (e.g. checking the data against a XML schema) the data must not be fixed:
setValidationMode() makes clean() only put the keys in the order of the map, so the validator
reports what is wrong.
- Names are compared as given: a wrong case (
nameforName) is an unknown key. - Unknown keys are kept, at the end of their node, in their order.
- Values are not touched: no trimming, empty values stay, missing keys are not added as
nulland a scalar where the map expects a node stays as is (noInvalidNodeException). - An empty value (
''ornull) of a key the map knows as a node becomes an empty node ([]). - An unknown key with its own map in
setExtensionKeys()(by its name) is ordered with that map: e.g. the children of an open node whose map is[]. The extension nodes are not used. $strictis ignored.
$data = (new ArrayBonesAnalizer($keys)) // ['Name', 'Plugins' => []]
->setExtensionKeys(['Cache' => ['Driver', 'Ttl'], 'Queue' => ['Driver', 'Retries']])
->setValidationMode()
->clean($input);
ElementOrder and ElementCleaner
ArrayBonesAnalizer is a configurable entry point over two classes that can be used directly:
use Xaamin\ArrayAnalizer\ElementCleaner;
use Xaamin\ArrayAnalizer\ElementOrder;
// Order only (the validation mode)
$data = (new ElementOrder($keys, ['Cache' => ['Driver', 'Ttl']]))->sort($input);
// Order and clean (clean() of ArrayBonesAnalizer)
$data = (new ElementCleaner($keys, ['Plugins']))->clean($input); // strict
$data = (new ElementCleaner($keys, ['Plugins']))->clean($input, false); // order only, null for the missing keys
| Class | Constructor | Method |
|---|---|---|
ElementOrder | (array $skeleton, array $extensions = []) | sort(array $data): array |
ElementCleaner | (array $skeleton, array $extensions = []) (nodes whose empty children are kept) | clean(array $data, bool $strict = true): array (orders and cleans in one pass) |
Nothing is assumed about the names of the keys: the extension nodes and maps come from the caller.
API
ArrayBonesAnalizer implements Xaamin\ArrayAnalizer\Contracts\ArrayAnalizerContract:
| Method | Description |
|---|---|
__construct(array $keys = []) | Creates the analizer with a map. |
setKeys(array $keys) / getKeys() | Sets / returns the map. |
setExtensionNodes(array $extensions) / getExtensionNodes() | Nodes whose empty children are preserved. setExtensionNodes() returns $this. |
setExtensionKeys(array $keys) / getExtensionKeys() | Map of each child of the extension nodes by its name, for the validation mode. Returns $this. |
setValidationMode(bool $enabled = true) / isValidationMode() | Validation mode: clean() only orders. Returns $this. Not part of the contract. |
clean(array $data, $strict = true) | Returns the ordered (and, if strict, cleaned) array; in validation mode only ordered. |
Behaviour notes
- Keys not in the map are always dropped, even with
$strict = false, because the result is built from the map, not from the data. - Keys are matched case-insensitively and returned with the map's name. On case-insensitive duplicates in the input, the first key wins.
- In strict mode only
null,''and whitespace-only strings are considered empty:false,0and'0'are kept. Empty nodes are removed (except direct children of extension nodes); an extension node that ends up empty itself is still removed. - Lists of nodes (
'Item' => [[...], [...]]) are ordered and cleaned item by item with the node's map and reindexed. Lists of scalars are returned as they are. - The exemption of
setExtensionNodes()only covers empty sub-arrays; scalars inside those nodes are still filtered by the map and by emptiness. - The package registers no global functions (the helpers of 1.0,
string_to_lowercase,array_get,array_is_associativeandarray_is_associative_values, were removed). - "analizer" (sic) is part of the package name and namespace.
Development
composer install && npm install # npm install sets up the husky commit-msg hook (commitlint)
npm test # Pest (or: composer test)
npm run lint:check # phpcs PSR12 on src/ (npm run lint:fix to fix)
npm run code:scan # phpstan level 5
Releases use release-it: npm run release[:patch|:minor|:major] bumps package.json and
composer.json, updates CHANGELOG.md, commits and tags vX.Y.Z (no push); then
git push --follow-tags. Commit messages follow Conventional Commits.
License
MIT. See LICENSE.