<?php

namespace Vlabs\CmsBundle\Repository;

use Vlabs\CmsBundle\Entity\CategoryInterface;

/**
 * CategoryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CategoryRepository extends \Doctrine\ORM\EntityRepository
{
    /**
     * @return array
     */
    public function findAll()
    {
        $categories = $this->_em->createQueryBuilder()
            ->select('c, p, c2')
            ->from($this->_entityName, 'c')
            ->leftJoin('c.posts', 'p')
            ->leftJoin('c.children', 'c2')
            ->orderBy('c.position')
            ->addOrderBy('c.name')
            ->addOrderBy('c2.position')
            ->addOrderBy('c2.name')
            ->getQuery()
            ->getResult();

        return $this->getRootCategories($categories);
    }

    /**
     * @param array $categories
     * @return array
     */
    private function getRootCategories(array $categories)
    {
        $rootCategories = [];
        /** @var CategoryInterface $category */
        foreach ($categories as $category) {
            if ($category->getParent()) continue;
            $rootCategories [] = $category;
        }

        return $rootCategories;
    }
}