Skip to content

Instantly share code, notes, and snippets.

@nrctkno
Last active February 23, 2023 22:39
Show Gist options
  • Save nrctkno/270f2b4a2f9e4c151c0b2b526c05c3d4 to your computer and use it in GitHub Desktop.
Save nrctkno/270f2b4a2f9e4c151c0b2b526c05c3d4 to your computer and use it in GitHub Desktop.
Trait to implement dynamic assignment of object variables from array with undefined keys. Useful for Request objects.
<?php
trait WithDynamicAssignment
{
public function set(
mixed $dest,
array $props,
string $field,
string $type = 'string',
mixed $default = null
): void {
$dest->$field = self::get($props, $field, $type, $default);
}
/**
* @param array<string,mixed> $props
*/
public function get(array $props, string $field, string $type = 'string', mixed $default = null): mixed
{
if (isset($props[$field])) {
$value = $props[$field];
if (!settype($value, $type)) {
throw new \Exception("Could not cast $field to type $type");
}
return $value;
}
return $default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment