<?php

namespace RxConnexionBundle\Repository;

use RxConnexionBundle\Entity\ItemPackageItemEntity;

/**
 * ItemPackageItemRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ItemPackageItemRepository extends \Doctrine\ORM\EntityRepository
{
    /**
     * @param $data
     * @return ItemPackageItemEntity
     * @throws \Doctrine\ORM\Mapping\MappingException
     */
    public function createFromArray($data)
    {
        $class = $this->getClassName();

        /**@var ItemPackageItemEntity $object*/
        if(!empty($data['id']) && !is_null($data['id'])) {
            $object = $this->find($data['id']);
        } else {
            $object = new $class();
        }

        $meta = $this->getClassMetadata();

        foreach ($data as $property => $value) {
            if(is_array($value)) continue;

            $v = $value;

            // snake case to camel case
            $property = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $property))));

            if($meta->hasAssociation($property)) {
                if(!empty($value)) {
                    $map = $meta->getAssociationMapping($property);
                    $v = $this->_em->getRepository($map['targetEntity'])->find($value);
                } else {
                    $v = null;
                }
            }

            // caps first letter for setter method
            $property = ucfirst($property);

            $method = "set{$property}";
            if(method_exists($object, $method)) {
                $object->$method($v);
            }
        }

        return $object;
    }
}
