<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private 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  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Api\Mapper;

class Index
{
    /**
     * @param object $modelIn
     * @param object $modelOut
     * @return object $modelOut
     */
    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 => $setName) {
            if (array_key_exists($method, $getArray)) {
                $getName = $getArray[$method];
                $ormClass->{$setName}($helperClass->{$getName}());
            }
        }

        return $ormClass;
    }

    /**
     * @param string $className
     * @return array
     */
    private function getClassSetMethods($className)
    {
        $reflectionClass = new \ReflectionClass($className);
        $setMethods = array();
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
            if (
                1 === $reflectionMethod->getNumberOfParameters() &&
                preg_match("/^(set)[A-Z]/", $reflectionMethod->name, $match)
            ) {
                $name = substr($reflectionMethod->name, strlen($match[1]));
                $setMethods[$name] = $reflectionMethod->name;
            }
        }

        return $setMethods;
    }

    /**
     * @param string $className
     * @return array
     */
    private function getClassGetMethods($className)
    {
        $reflectionClass = new \ReflectionClass($className);
        $getMethods = array();
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
            if (
                0 === $reflectionMethod->getNumberOfParameters() &&
                preg_match("/^(get|has|is)[A-Z]/", $reflectionMethod->name, $match)
            ) {
                $name = substr($reflectionMethod->name, strlen($match[1]));
                $getMethods[$name] = $reflectionMethod->name;
            }
        }

        return $getMethods;
    }
}
