DTO.php 1000 Bytes
<?php

namespace FootyRoom\App;

use Exception;

abstract class Dto
{
    /**
     * Convenience method with construction by mapping an array input to class
     * properties. If a passed property does not exist on the class an exception
     * is thrown.
     *
     * @param array $data
     *
     * @throws \Exception
     */
    public function __construct(array $data = [])
    {
        foreach ($data as $key => $value) {
            if (!property_exists($this, $key)) {
                throw new Exception(
                    sprintf('Property "%s" is not a valid property on "%s".', $key, get_class($this))
                );
            }

            $this->$key = $value;
        }
    }

    /**
     * Prevents setting undefined public properties.
     *
     * @param string $name
     * @param mixed $value
     *
     * @throws \Exception
     */
    public function __set($name, $value)
    {
        throw new Exception('Attempting to set non-existent public propety.');
    }
}