100 lines
2.2 KiB
PHP
100 lines
2.2 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Service\Article;
|
||
|
|
|
||
|
|
use App\Entity\Article;
|
||
|
|
use App\Hydrator\DoctrineObject;
|
||
|
|
use App\Service\EntityServiceInterface;
|
||
|
|
use Doctrine\ORM\EntityManager;
|
||
|
|
use Doctrine\ORM\Query;
|
||
|
|
use Exception;
|
||
|
|
|
||
|
|
class ArticleService implements EntityServiceInterface
|
||
|
|
{
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @var EntityManager
|
||
|
|
*/
|
||
|
|
private $em;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @var DoctrineObject
|
||
|
|
*/
|
||
|
|
private $hydrator;
|
||
|
|
|
||
|
|
public function __construct(EntityManager $em, DoctrineObject $hydrator)
|
||
|
|
{
|
||
|
|
$this->em = $em;
|
||
|
|
$this->hydrator = $hydrator;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function getList()
|
||
|
|
{
|
||
|
|
$qb = $this->em->createQueryBuilder();
|
||
|
|
$entities = $qb->select('a,u,c')
|
||
|
|
->from(Article::class, 'a')
|
||
|
|
->leftJoin('a.author', 'u')
|
||
|
|
->leftJoin('a.comments', 'c')
|
||
|
|
->getQuery()
|
||
|
|
->getArrayResult();
|
||
|
|
return $entities;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function get($id)
|
||
|
|
{
|
||
|
|
$qb = $this->em->createQueryBuilder();
|
||
|
|
|
||
|
|
$entity = $qb->select('a,u,c')
|
||
|
|
->from(Article::class, 'a')
|
||
|
|
->leftJoin('a.author', 'u')
|
||
|
|
->leftJoin('a.comments', 'c')
|
||
|
|
->where('a.id = :aid')
|
||
|
|
->setParameter('aid', $id)
|
||
|
|
->getQuery()
|
||
|
|
->getOneOrNullResult(Query::HYDRATE_ARRAY);
|
||
|
|
|
||
|
|
return $entity;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function create($data)
|
||
|
|
{
|
||
|
|
$entity = $this->hydrator->hydrate($data, new Article());
|
||
|
|
try {
|
||
|
|
$this->em->persist($entity);
|
||
|
|
$this->em->flush();
|
||
|
|
} catch (Exception $ex) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
return $entity;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function modify($id, $data)
|
||
|
|
{
|
||
|
|
if (null === ($entity = $this->em->find(Article::class, $id))) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
$entity = $this->hydrator->hydrate($data, $entity);
|
||
|
|
$this->em->persist($entity);
|
||
|
|
$this->em->flush();
|
||
|
|
|
||
|
|
return $entity;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function delete($id)
|
||
|
|
{
|
||
|
|
if (null === ($entity = $this->em->find(Article::class, $id))) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
$this->em->remove($entity);
|
||
|
|
$this->em->flush();
|
||
|
|
} catch (Exception $ex) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|