<?php

namespace Comitium5\DesignerBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Class AbstractRepository
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Repository
 */
abstract class AbstractRepository extends EntityRepository
{
    /**
     * @param  string                     $method
     * @param  array                      $arguments
     * @return array|object
     * @throws \Doctrine\ORM\ORMException
     */
    public function __call($method, $arguments)
    {
        if ($this->endsWith($method, 'OneResult')) {
            $originalMethod = substr($method, 0, strlen($method) - 9);

            return call_user_func_array(array($this, $originalMethod), $arguments)->getQuery()->getOneOrNullResult();
        } elseif ($this->endsWith($method, 'Result')) {
            $originalMethod = substr($method, 0, strlen($method) - 6);

            return call_user_func_array(array($this, $originalMethod), $arguments)->getQuery()->getResult();
        }

        return parent::__call($method, $arguments);
    }

    /**
     * @param $haystack
     * @param $needle
     * @return bool
     */
    private function endsWith($haystack, $needle)
    {
        // search forward starting from end minus needle length characters
        return $needle === "" || strpos($haystack, $needle, strlen($haystack) - strlen($needle)) !== false;
    }

    /**
     * @desc Returns the class alias (usually the first letter of name class)
     * @return string
     */
    public function getAlias()
    {
        if (preg_match('/(?:\\w*\\\\)+(\\w*)/', $this->getEntityName(), $matches)) {
            return strtolower(substr($matches[1], 0, 1));
        }

        return strtolower(substr(__CLASS__, 0, 1));
    }

    /**
     * @param  null                       $alias
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function createQueryBuilder($alias = null, $indexBy = null)
    {
        if (!$alias) {
            $alias = $this->getAlias();
        }

        return parent::createQueryBuilder($alias);
    }
}
