Skip to content

Instantly share code, notes, and snippets.

@barokurniawan
Last active January 31, 2023 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barokurniawan/f4816264c8aa8f22c72b3f3d67b431d1 to your computer and use it in GitHub Desktop.
Save barokurniawan/f4816264c8aa8f22c72b3f3d67b431d1 to your computer and use it in GitHub Desktop.
Convert PHP array or PHP Plain Object to PHP Class Entity
<?php
use ReflectionClass;
/**
* Scan database result into entity class
* Data member of the entity class should exactly match with the database result column
*
*/
class ObjectScanner
{
private $result;
public static function scan($targetClass, $dataSource)
{
$obj = new self($targetClass, $dataSource);
return $obj->getResult();
}
/**
* @param mixed $dataSource
* should be a single object instant, not a list of object
*/
public function __construct($targetClass, $dataSource)
{
$dataSource = $this->asArray($dataSource);
$entity = new $targetClass;
$n = new ReflectionClass($targetClass);
foreach ($n->getProperties() as $item) {
if (!isset($dataSource[$item->getName()])) {
continue;
}
$prop = $n->getProperty($item->getName());
$prop->setAccessible(true);
$prop->setValue($entity, $dataSource[$item->getName()]);
}
$this->setResult($entity);
}
private function asArray($item)
{
$dataSource = $item;
if (!is_array($item) && !method_exists($item, "toArray")) {
$dataSource = (array) $item;
}
if (!is_array($dataSource) && method_exists($item, "toArray")) {
$dataSource = $item->toArray();
}
return $dataSource;
}
/**
* Get the value of result
*
* @return mixed
*/
public function getResult()
{
return $this->result;
}
/**
* Set the value of result
*
* @param mixed $result
*
* @return self
*/
public function setResult($result)
{
$this->result = $result;
return $this;
}
}
// to use:
/**
class Person {
$name;
public function getName() {
return $this->name;
}
}
$array = ["name" => "Udin Sedunia"];
$entity = ObjectScanner::scan(Person::class, $array);
echo $entity->getName(); // output: "Udin Sedunia"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment