Last active
February 23, 2023 22:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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