Skip to content

Instantly share code, notes, and snippets.

@ewertoncode
Created December 22, 2015 18:34
Show Gist options
  • Save ewertoncode/52fc5fe26b9b48e2c260 to your computer and use it in GitHub Desktop.
Save ewertoncode/52fc5fe26b9b48e2c260 to your computer and use it in GitHub Desktop.
<?php
namespace SON\BaseBundle\Services;
use Doctrine\ORM\EntityManager;
use SON\BaseBundle\Entity\EntityInterface;
use Zend\Stdlib\Hydrator\ClassMethods;
abstract class AbstractService
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $entityManager;
protected $entityName;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function loadEntity($entity)
{
if(!is_array($entity)
&& !($entity instanceof $this->entityName)) {
throw new \InvalidArgumentException(
sprintf("Você está passando um objeto ao invés
de um array e o objeto é inválido. Deveria passar '%s' e está passando '%s'", $this->entityName, get_class($entity))
);
}
$data = $entity;
if(!isset($data['id'])) {
$entity = new $this->entityName;
} else {
$entity = $this->entityManager->getReference($this->entityName, $data['id']);
}
if(array_key_exists('ativo', $data)
&& isset($data['ativo'])) {
$data['ativo'] = true;
}
$entity = $this->hydrate($data, $entity);
return $entity;
}
public function save($entity)
{
if(!($entity instanceOf $this->entityName))
{
$entity = $this->loadEntity($entity);
}
$this->entityManager->persist($entity);
$this->entityManager->flush();
return $entity;
}
public function hydrate($data, $entity)
{
$hydrator = new ClassMethods;
$entity = $hydrator->hydrate($data, $entity);
return $entity;
}
public function fetchAll()
{
$entities = $this->entityManager->getRepository($this->entityName)->findAll();
return $entities;
}
public function find($id)
{
$entity = $this->entityManager->getRepository($this->entityName)->find($id);
return $entity;
}
public function delete(EntityInterface $entity)
{
$this->entityManager->remove($entity);
$this->entityManager->flush();
return $entity;
}
public function deleteSoft(EntityInterface $entity)
{
$entity->setAtivo(false);
$this->entityManager->persist($entity);
$this->entityManager->flush();
return $entity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment