<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\Common\Collections\ArrayCollection;

require_once __DIR__ . '/../../../TestInit.php';

class DDC767Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp()
    {
        parent::setUp();
        
        try {
            $this->_schemaTool->createSchema(array(
                $this->_em->getClassMetadata(__NAMESPACE__ . '\Article'),
                $this->_em->getClassMetadata(__NAMESPACE__ . '\Category')
            ));
        } catch(\Exception $e) {

        }
    }
    
    /**
     * @group DDC-767
     */
    public function testAddingEntityIntoDQLResultCollection()
    {
        $category = new Category();
        $this->_em->persist($category);
        $this->_em->flush();
        $this->_em->clear();

        $article = new Article();
        $this->_em->persist($article);
        $this->_em->flush();
        $this->_em->clear();

        $category = $this->_em->find(get_class($category), $category->id);
        
        $query = $this->_em->createQuery("
            SELECT
                article
                , categories
            FROM Doctrine\Tests\ORM\Functional\Ticket\Article article
            LEFT JOIN article.categories categories
        ");
    
        $article = $query->getSingleResult();
        
        $article->addCategory($category);
        $this->_em->flush();
        $this->_em->clear();

    }
}

/**
 * @Entity
 * @Table(name="article")
 */
class Article
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    public $id;

    /**
     * @ManyToMany(targetEntity="Category")
     * @JoinTable(name="article_category",
     *      joinColumns={@JoinColumn(name="article_id")},
     *      inverseJoinColumns={@JoinColumn(name="category_id")}
     *      )
     */
    private $categories;
    public function __construct()
    {
        $this->categories = new ArrayCollection();
    }
    public function addCategory(Category $category)
    {
        $this->categories->add($category);
    }
}

/**
 * @Entity
 * @Table(name="category")
 */
class Category
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    public $id;
}