<?php

/**
 * Model Mapper
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\RestBundle\Api\Helper\Mapper;

/**
 * Model Mapper
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */
class Index
{
    /**
     * @param object $modelIn
     * @param object $modelOut
     * @return object $modelOut
     * @throws \ReflectionException
     */
    public function modelInToModelOut($modelIn, $modelOut)
    {

        $helperEntityClass = $modelIn;
        $ormEntityClass = $modelOut;

        $helperClass = $modelIn;
        $ormClass = $modelOut;

        $getArray = $this->getClassGetMethods($helperEntityClass);
        $setArray = $this->getClassSetMethods($ormEntityClass);

        // looping the set array
        foreach ($setArray as $method) {
            if (in_array($method, $getArray)) {
                $setName = "set" . $method;
                $getName = "get" . $method;
                $ormClass->{$setName}($helperClass->{$getName}());
            }
        }
        return $ormClass;
    }

    /**
     * @param string $className
     * @return array
     * @throws \ReflectionException
     */
    protected function getClassSetMethods($className)
    {
        $reflectionClass = new \ReflectionClass($className);
        $setMethods = array();
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
            preg_match("/(set+[A-Z]+[a-z])/", $reflectionMethod->name, $match);
            if ($match) {
                $name = str_ireplace("set", "", $reflectionMethod->name);
                $setMethods[$name] = $name;
            }
        }
        return $setMethods;
    }

    /**
     * @param string $className
     * @return array
     * @throws \ReflectionException
     */
    protected function getClassGetMethods($className)
    {
        $reflectionClass = new \ReflectionClass($className);
        $getMethods = array();
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
            preg_match("/(get+[A-Z]+[a-z])/", $reflectionMethod->name, $match);
            if ($match) {
                $name = str_ireplace("get", "", $reflectionMethod->name);
                $getMethods[$name] = $name;
            }
        }
        return $getMethods;
    }
}
