Skip to content

Instantly share code, notes, and snippets.

@D1360-64RC14
Last active January 13, 2025 13:16
Show Gist options
  • Select an option

  • Save D1360-64RC14/b2e949c7000e1888b5650da118c75c1a to your computer and use it in GitHub Desktop.

Select an option

Save D1360-64RC14/b2e949c7000e1888b5650da118c75c1a to your computer and use it in GitHub Desktop.
Create a remap object that maps an input array to an output array by a given schema. Requires minimum PHP 8.1.
<?php
/**
* Create a remap object that maps an input array to an output array by a given
* schema.
*
* The schema is an array of `key`-`value` pairs, or a `string` value, where the
* `key` is the key from the input array and the `value` is the key to be mapped
* to in the output array. If a `string` is given, the value will be passed-through.
*
* Any other key not present in the schema will be ignored.
*
* Example:
* ```
* $dbUserToUserRemapper = new ArrayRemapper([
* 'from-key' => 'to-key',
* 'user_id' => 'id',
* 'user_name' => 'name',
* ]);
*
* $userA = $dbUserToUserRemapper->apply($dbUserA);
* $userB = $dbUserToUserRemapper->apply($dbUserB);
* ```
*
* @template R of array
*/
class ArrayRemapper
{
private readonly array $schema;
/**
* Create a new ArrayRemapper instance applying the given schema.
*
* @param (array<string, string>|string)[] $schema
*/
public function __construct(array $schema)
{
$this->schema = $schema;
}
/**
* Apply the remap schema to the given value, being It an array or an object.
*
* If an object is passed, keys will be accessed as properties. To use it as
* an array, pass `true` to the `$objectAsArray` argument.
*
* @param array|object $value
* @return R
*/
public function apply(array|object $value, bool $objectAsArray = false): array
{
$accessAsArray = is_array($value) || $objectAsArray;
$result = [];
foreach ($this->schema as $fromKey => $toKey) {
if (gettype($fromKey) === 'integer') {
$fromKey = $toKey;
}
if ($accessAsArray ? ! array_key_exists($fromKey, $value) : ! property_exists($value, $fromKey)) {
continue;
}
$result[$toKey] = $accessAsArray ? $value[$fromKey] : $value->$fromKey;
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment