for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
/**
* Created by PhpStorm.
* User: vlitvinovs
* Date: 2/8/17
* Time: 4:28 PM
*/
namespace CodinPro\DataTransferObject;
class DTOBaseBuilder
{
public function __construct(DTOBase $dtoBase)
$this->dto = $dtoBase;
dto
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
class MyClass { } $x = new MyClass(); $x->foo = true;
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:
class MyClass { public $foo; } $x = new MyClass(); $x->foo = true;
}
* Build DTO from given type of data
* @param $data
* @throws \InvalidArgumentException
public function build($data)
switch (gettype($data)) {
case 'array':
case 'object':
$this->buildFromData($data);
break;
case 'string':
$this->buildFromJson($data);
default:
throw new \InvalidArgumentException('DTO can be built from array|object|json, "'.gettype($data).'" given.');
* Build DTO from provided data
* @param object|array $data
private function buildFromData($data)
foreach ($this->dto->getDefault() as $key => $value) {
if (is_object($data) && isset($data->{$key})) {
$this->dto[$key] = $data->{$key};
} else if (is_array($data) && isset($data[$key])) {
$this->dto[$key] = $data[$key];
} else {
$this->dto[$key] = $value;
* Try to build from provided string as JSON
* @param string $data
private function buildFromJson($data)
$triedToDecodeData = json_decode($data);
if ($triedToDecodeData !== null) {
$this->buildFromData($triedToDecodeData);
throw new \InvalidArgumentException(
'DTO can be built from array|object|json, "'.gettype($data).'" given. Probably tried to pass invalid JSON.'
);
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: