<?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\RestBundle\Api\Helper\Mapper;

/**
 * Class Index
 * @package Sso\RestBundle\Api\Helper\Mapper
 */
class Index
{
    /**
     * @param object $modelIn
     * @param object $modelOut
     * @return mixed
     * @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 object $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 object $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;
    }
}
