public function flush($flushEntityManager = false)
    {
        $this->queue->rewind();

        while ($this->queue->valid()) {
            list($item, $mode) = $this->queue->dequeue();
            switch ($mode) {
                case self::REMOVE:
                    if (($repo = $this->getRepository(get_class($item))) && $repo instanceof NestedTreeRepository) {
                        $repo->removeFromTree($item);
                    } else {
                        $this->doctrine->getManager()->remove($item);
                    }
                    break;
                case self::ADD:
                    $this->doctrine->getManager()->persist($item);
                    break;
            }
            $this->queue->next();
        }

        if ($flushEntityManager) {
            $this->doctrine->getManager()->flush();
        }
    }