* initial commit
This commit is contained in:
61
src/App/ConfigProvider.php
Normal file
61
src/App/ConfigProvider.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
/**
|
||||
* The configuration provider for the App module
|
||||
*
|
||||
* @see https://docs.zendframework.com/zend-component-installer/
|
||||
*/
|
||||
class ConfigProvider
|
||||
{
|
||||
/**
|
||||
* Returns the configuration array
|
||||
*
|
||||
* To add a bit of a structure, each section is defined in a separate
|
||||
* method which returns an array with its configuration.
|
||||
*
|
||||
*/
|
||||
public function __invoke() : array
|
||||
{
|
||||
return [
|
||||
'dependencies' => $this->getDependencies(),
|
||||
'templates' => $this->getTemplates(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the container dependencies
|
||||
*/
|
||||
public function getDependencies() : array
|
||||
{
|
||||
return [
|
||||
'invokables' => [
|
||||
Handler\PingHandler::class => Handler\PingHandler::class,
|
||||
],
|
||||
'factories' => [
|
||||
Handler\HomePageHandler::class => Handler\HomePageHandlerFactory::class,
|
||||
Handler\TeamHandler::class => Handler\TeamHandlerFactory::class,
|
||||
|
||||
Service\TeamService::class => Service\TeamServiceFactory::class,
|
||||
Service\SlideManager::class => Service\SlideManagerFactory::class,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the templates configuration
|
||||
*/
|
||||
public function getTemplates() : array
|
||||
{
|
||||
return [
|
||||
'paths' => [
|
||||
'app' => ['templates/app'],
|
||||
'error' => ['templates/error'],
|
||||
'layout' => ['templates/layout'],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
209
src/App/Entity/Slide.php
Normal file
209
src/App/Entity/Slide.php
Normal file
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Gedmo\Mapping\Annotation as Gedmo;
|
||||
use JsonSerializable;
|
||||
|
||||
/**
|
||||
* @ORM\Entity
|
||||
* @ORM\Table(name="slides")
|
||||
*/
|
||||
class Slide implements JsonSerializable
|
||||
{
|
||||
/**
|
||||
* @ORM\Id
|
||||
* @ORM\GeneratedValue(strategy="IDENTITY")
|
||||
* @ORM\Column(name="id", type="integer")
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="title", type="string", length=200, unique=true)
|
||||
* @var string
|
||||
*/
|
||||
private $title;
|
||||
|
||||
/**
|
||||
* @ORM\ManyToOne(targetEntity="Team", inversedBy="slides")
|
||||
* @ORM\JoinColumn(name="team_id", referencedColumnName="id")
|
||||
* @var Team
|
||||
*/
|
||||
private $team;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="slide_data", type="text")
|
||||
* @var string
|
||||
*/
|
||||
private $slideData;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="is_visible", type="boolean")
|
||||
* @var bool
|
||||
*/
|
||||
private $isVisible;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="created_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="create")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $createdAt;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="updated_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="update")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $updatedAt;
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Slide
|
||||
*/
|
||||
public function setId(int $id): Slide
|
||||
{
|
||||
$this->id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $title
|
||||
* @return Slide
|
||||
*/
|
||||
public function setTitle(string $title)
|
||||
{
|
||||
$this->title = $title;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Team
|
||||
*/
|
||||
public function getTeam(): ?Team
|
||||
{
|
||||
return $this->team;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Team $team
|
||||
* @return Slide
|
||||
*/
|
||||
public function setTeam(Team $team): Slide
|
||||
{
|
||||
$this->team = $team;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getSlideData(): ?string
|
||||
{
|
||||
return $this->slideData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $slideData
|
||||
* @return Slide
|
||||
*/
|
||||
public function setSlideData(string $slideData): Slide
|
||||
{
|
||||
$this->slideData = $slideData;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isVisible(): ?bool
|
||||
{
|
||||
return $this->isVisible;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $isVisible
|
||||
* @return Slide
|
||||
*/
|
||||
public function setIsVisible(bool $isVisible): Slide
|
||||
{
|
||||
$this->isVisible = $isVisible;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getCreatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $createdAt
|
||||
* @return Slide
|
||||
*/
|
||||
public function setCreatedAt(\DateTimeImmutable $createdAt): Slide
|
||||
{
|
||||
$this->createdAt = $createdAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getUpdatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->updatedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $updatedAt
|
||||
* @return Slide
|
||||
*/
|
||||
public function setUpdatedAt(\DateTimeImmutable $updatedAt): Slide
|
||||
{
|
||||
$this->updatedAt = $updatedAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function jsonSerialize()
|
||||
{
|
||||
return [
|
||||
'id' => $this->getId(),
|
||||
'title' => $this->getTitle(),
|
||||
'team' => $this->getTeam(),
|
||||
'slideData' => $this->getSlideData(),
|
||||
'isVisible' => $this->isVisible(),
|
||||
'createdAt' => $this->getCreatedAt()
|
||||
? $this->getCreatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
'updatedAt' => $this->getUpdatedAt()
|
||||
? $this->getUpdatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
];
|
||||
}
|
||||
}
|
||||
234
src/App/Entity/Team.php
Normal file
234
src/App/Entity/Team.php
Normal file
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Gedmo\Mapping\Annotation as Gedmo;
|
||||
use JsonSerializable;
|
||||
|
||||
/**
|
||||
* @ORM\Entity
|
||||
* @ORM\Table(name="teams")
|
||||
*/
|
||||
class Team implements JsonSerializable
|
||||
{
|
||||
/**
|
||||
* @ORM\Id
|
||||
* @ORM\GeneratedValue(strategy="IDENTITY")
|
||||
* @ORM\Column(name="id", type="integer")
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="name", type="string", length=200, unique=true)
|
||||
* @var string
|
||||
*/
|
||||
private $name;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="members", type="json")
|
||||
* @var array
|
||||
*/
|
||||
private $members;
|
||||
|
||||
/**
|
||||
* @ORM\OneToMany(
|
||||
* targetEntity="Slide",
|
||||
* mappedBy="team",
|
||||
* cascade={"persist", "remove"},
|
||||
* orphanRemoval=true
|
||||
* )
|
||||
* @var Slide[]|Collection
|
||||
*/
|
||||
private $slides;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="is_active", type="boolean")
|
||||
* @var bool
|
||||
*/
|
||||
private $isActive;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="created_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="create")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $createdAt;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="updated_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="update")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $updatedAt;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->slides = new ArrayCollection;
|
||||
$this->members = new \ArrayObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Team
|
||||
*/
|
||||
public function setId(int $id): Team
|
||||
{
|
||||
$this->id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return Team
|
||||
*/
|
||||
public function setName(string $name): Team
|
||||
{
|
||||
$this->name = $name;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getMembers()
|
||||
{
|
||||
return $this->members;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $members
|
||||
* @return Team
|
||||
*/
|
||||
public function setMembers(array $members): Team
|
||||
{
|
||||
$this->members = $members;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Slide $slide
|
||||
* @return Team
|
||||
*/
|
||||
public function addSlides(Slide $slide): Team
|
||||
{
|
||||
if (!$this->slides->contains($slide)) {
|
||||
$this->slides->removeElement($slide);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Slide[]|Collection
|
||||
*/
|
||||
public function getSlides(): ?Collection
|
||||
{
|
||||
return $this->slides;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Slide $slide
|
||||
* @return Team
|
||||
*/
|
||||
public function removeSlide(Slide $slide): Team
|
||||
{
|
||||
if ($this->slides->contains($slide)) {
|
||||
$this->slides->removeElement($slide);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isActive(): ?bool
|
||||
{
|
||||
return $this->isActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $isActive
|
||||
* @return Team
|
||||
*/
|
||||
public function setIsActive(bool $isActive): Team
|
||||
{
|
||||
$this->isActive = $isActive;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getCreatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $createdAt
|
||||
* @return Team
|
||||
*/
|
||||
public function setCreatedAt(\DateTimeImmutable $createdAt): Team
|
||||
{
|
||||
$this->createdAt = $createdAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getUpdatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->updatedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $updatedAt
|
||||
* @return Team
|
||||
*/
|
||||
public function setUpdatedAt(\DateTimeImmutable $updatedAt): Team
|
||||
{
|
||||
$this->updatedAt = $updatedAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function jsonSerialize()
|
||||
{
|
||||
return [
|
||||
'id' => $this->getId(),
|
||||
'name' => $this->getName(),
|
||||
'members' => $this->getMembers(),
|
||||
'isActive' => $this->isActive(),
|
||||
'createdAt' => $this->getCreatedAt()
|
||||
? $this->getCreatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
'updatedAt' => $this->getUpdatedAt()
|
||||
? $this->getUpdatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
];
|
||||
}
|
||||
}
|
||||
73
src/App/Form/Slide.php
Normal file
73
src/App/Form/Slide.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use Zend\Form\Annotation;
|
||||
|
||||
/**
|
||||
* @Annotation\Name("slide")
|
||||
* @Annotation\Hydrator("doctrine.hydrator")
|
||||
*/
|
||||
class Slide
|
||||
{
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Hidden")
|
||||
* @Annotation\Required(false)
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\InputFilter("Zend\Filter\StringTrim")
|
||||
* @Annotation\Options({
|
||||
* "label": "Slide title"
|
||||
* })
|
||||
* @var string
|
||||
*/
|
||||
private $title;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\Options({
|
||||
* "label": "Team",
|
||||
* "target_class": "App\Entity\Team",
|
||||
* "display_empty_item": false,
|
||||
* "empty_item_label": "",
|
||||
* "is_method": true,
|
||||
* "find_method": {
|
||||
* "name": "findBy",
|
||||
* "params": {
|
||||
* "criteria": {"isActive": true},
|
||||
* "orderBy": {"name": "ASC"}
|
||||
* }
|
||||
* }
|
||||
* })
|
||||
* @var
|
||||
*/
|
||||
private $team;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\InputFilter("Zend\Filter\StringTrim")
|
||||
* @Annotation\Options({
|
||||
* "label": "Slide contents"
|
||||
* })
|
||||
* @var
|
||||
*/
|
||||
private $slideData;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Checkbox")
|
||||
* @Annotation\Options({
|
||||
* "label": "Visible"
|
||||
* })
|
||||
* @var bool
|
||||
*/
|
||||
private $isVisible;
|
||||
}
|
||||
52
src/App/Form/Team.php
Normal file
52
src/App/Form/Team.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use Zend\Form\Annotation;
|
||||
|
||||
/**
|
||||
* @Annotation\Name("team")
|
||||
* @Annotation\Hydrator("doctrine.hydrator")
|
||||
*/
|
||||
class Team
|
||||
{
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Hidden")
|
||||
* @Annotation\Required(false)
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\InputFilter("Zend\Filter\StringTrim")
|
||||
* @Annotation\Options({
|
||||
* "label": "Team name"
|
||||
* })
|
||||
* @var string
|
||||
*/
|
||||
private $name;
|
||||
|
||||
/**
|
||||
* This is a dummy field, not a text actually. Only used to filter the input
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\Options({
|
||||
* "label": "Members"
|
||||
* })
|
||||
* @var array
|
||||
*/
|
||||
private $members;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Checkbox")
|
||||
* @Annotation\Options({
|
||||
* "label": "Active"
|
||||
* })
|
||||
* @var bool
|
||||
*/
|
||||
private $isActive;
|
||||
}
|
||||
161
src/App/Handler/AbstractCrudHandler.php
Normal file
161
src/App/Handler/AbstractCrudHandler.php
Normal file
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Diactoros\Response\EmptyResponse;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
use Zend\Json\Json;
|
||||
|
||||
abstract class AbstractCrudHandler implements RequestHandlerInterface
|
||||
{
|
||||
const IDENTIFIER_NAME = 'id';
|
||||
|
||||
public function handle(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
$requestMethod = strtoupper($request->getMethod());
|
||||
$id = $request->getAttribute(static::IDENTIFIER_NAME);
|
||||
|
||||
switch ($requestMethod) {
|
||||
case 'GET':
|
||||
return isset($id)
|
||||
? $this->get($request)
|
||||
: $this->getList($request);
|
||||
case 'POST':
|
||||
return $this->create($request);
|
||||
case 'PUT':
|
||||
return $this->update($request);
|
||||
case 'DELETE':
|
||||
return isset($id)
|
||||
? $this->delete($request)
|
||||
: $this->deleteList($request);
|
||||
case 'HEAD':
|
||||
return $this->head($request);
|
||||
case 'OPTIONS':
|
||||
return $this->options($request);
|
||||
case 'PATCH':
|
||||
return $this->patch($request);
|
||||
default:
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
}
|
||||
|
||||
public function get(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function getList(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function create(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function update(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function delete(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function deleteList(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function head(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function options(ServerRequestInterface $request)
|
||||
{
|
||||
return new EmptyResponse(200);
|
||||
}
|
||||
|
||||
public function patch(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
final protected function createResponse($data, $status = 200)
|
||||
{
|
||||
return new JsonResponse($data, $status);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param ServerRequestInterface $request
|
||||
* @return array|object
|
||||
*/
|
||||
public function getRequestData(ServerRequestInterface $request)
|
||||
{
|
||||
$body = $request->getParsedBody();
|
||||
|
||||
if (!empty($body)) {
|
||||
return $body;
|
||||
}
|
||||
|
||||
return $this->parseRequestData(
|
||||
$request->getBody()->getContents(),
|
||||
$request->getHeaderLine('content-type')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $input
|
||||
* @param string $contentType
|
||||
* @return mixed
|
||||
*/
|
||||
private function parseRequestData($input, $contentType)
|
||||
{
|
||||
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
|
||||
$parser = $this->returnParserContentType($contentTypeParts[0]);
|
||||
|
||||
return $parser($input);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $contentType
|
||||
* @return callable
|
||||
*/
|
||||
private function returnParserContentType(string $contentType): callable
|
||||
{
|
||||
if ($contentType === 'application/x-www-form-urlencoded') {
|
||||
return function ($input) {
|
||||
parse_str($input, $data);
|
||||
return $data;
|
||||
};
|
||||
} elseif ($contentType === 'application/json') {
|
||||
return function ($input) {
|
||||
$jsonDecoder = new Json();
|
||||
try {
|
||||
return $jsonDecoder->decode($input, Json::TYPE_ARRAY);
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
} elseif ($contentType === 'multipart/form-data') {
|
||||
return function ($input) {
|
||||
return $input;
|
||||
};
|
||||
}
|
||||
|
||||
return function ($input) {
|
||||
return $input;
|
||||
};
|
||||
}
|
||||
}
|
||||
94
src/App/Handler/HomePageHandler.php
Normal file
94
src/App/Handler/HomePageHandler.php
Normal file
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Diactoros\Response\HtmlResponse;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
use Zend\Expressive\Plates\PlatesRenderer;
|
||||
use Zend\Expressive\Router;
|
||||
use Zend\Expressive\Template;
|
||||
use Zend\Expressive\Twig\TwigRenderer;
|
||||
use Zend\Expressive\ZendView\ZendViewRenderer;
|
||||
|
||||
class HomePageHandler implements RequestHandlerInterface
|
||||
{
|
||||
private $containerName;
|
||||
|
||||
private $router;
|
||||
|
||||
private $template;
|
||||
|
||||
public function __construct(
|
||||
Router\RouterInterface $router,
|
||||
Template\TemplateRendererInterface $template = null,
|
||||
string $containerName
|
||||
) {
|
||||
$this->router = $router;
|
||||
$this->template = $template;
|
||||
$this->containerName = $containerName;
|
||||
}
|
||||
|
||||
public function handle(ServerRequestInterface $request) : ResponseInterface
|
||||
{
|
||||
if (! $this->template) {
|
||||
return new JsonResponse([
|
||||
'welcome' => 'Congratulations! You have installed the zend-expressive skeleton application.',
|
||||
'docsUrl' => 'https://docs.zendframework.com/zend-expressive/',
|
||||
]);
|
||||
}
|
||||
|
||||
$data = [];
|
||||
|
||||
switch ($this->containerName) {
|
||||
case 'Aura\Di\Container':
|
||||
$data['containerName'] = 'Aura.Di';
|
||||
$data['containerDocs'] = 'http://auraphp.com/packages/2.x/Di.html';
|
||||
break;
|
||||
case 'Pimple\Container':
|
||||
$data['containerName'] = 'Pimple';
|
||||
$data['containerDocs'] = 'https://pimple.symfony.com/';
|
||||
break;
|
||||
case 'Zend\ServiceManager\ServiceManager':
|
||||
$data['containerName'] = 'Zend Servicemanager';
|
||||
$data['containerDocs'] = 'https://docs.zendframework.com/zend-servicemanager/';
|
||||
break;
|
||||
case 'Auryn\Injector':
|
||||
$data['containerName'] = 'Auryn';
|
||||
$data['containerDocs'] = 'https://github.com/rdlowrey/Auryn';
|
||||
break;
|
||||
case 'Symfony\Component\DependencyInjection\ContainerBuilder':
|
||||
$data['containerName'] = 'Symfony DI Container';
|
||||
$data['containerDocs'] = 'https://symfony.com/doc/current/service_container.html';
|
||||
break;
|
||||
}
|
||||
|
||||
if ($this->router instanceof Router\AuraRouter) {
|
||||
$data['routerName'] = 'Aura.Router';
|
||||
$data['routerDocs'] = 'http://auraphp.com/packages/2.x/Router.html';
|
||||
} elseif ($this->router instanceof Router\FastRouteRouter) {
|
||||
$data['routerName'] = 'FastRoute';
|
||||
$data['routerDocs'] = 'https://github.com/nikic/FastRoute';
|
||||
} elseif ($this->router instanceof Router\ZendRouter) {
|
||||
$data['routerName'] = 'Zend Router';
|
||||
$data['routerDocs'] = 'https://docs.zendframework.com/zend-router/';
|
||||
}
|
||||
|
||||
if ($this->template instanceof PlatesRenderer) {
|
||||
$data['templateName'] = 'Plates';
|
||||
$data['templateDocs'] = 'http://platesphp.com/';
|
||||
} elseif ($this->template instanceof TwigRenderer) {
|
||||
$data['templateName'] = 'Twig';
|
||||
$data['templateDocs'] = 'http://twig.sensiolabs.org/documentation';
|
||||
} elseif ($this->template instanceof ZendViewRenderer) {
|
||||
$data['templateName'] = 'Zend View';
|
||||
$data['templateDocs'] = 'https://docs.zendframework.com/zend-view/';
|
||||
}
|
||||
|
||||
return new HtmlResponse($this->template->render('app::home-page', $data));
|
||||
}
|
||||
}
|
||||
23
src/App/Handler/HomePageHandlerFactory.php
Normal file
23
src/App/Handler/HomePageHandlerFactory.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Expressive\Router\RouterInterface;
|
||||
use Zend\Expressive\Template\TemplateRendererInterface;
|
||||
|
||||
class HomePageHandlerFactory
|
||||
{
|
||||
public function __invoke(ContainerInterface $container) : RequestHandlerInterface
|
||||
{
|
||||
$router = $container->get(RouterInterface::class);
|
||||
$template = $container->has(TemplateRendererInterface::class)
|
||||
? $container->get(TemplateRendererInterface::class)
|
||||
: null;
|
||||
|
||||
return new HomePageHandler($router, $template, get_class($container));
|
||||
}
|
||||
}
|
||||
18
src/App/Handler/PingHandler.php
Normal file
18
src/App/Handler/PingHandler.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class PingHandler implements RequestHandlerInterface
|
||||
{
|
||||
public function handle(ServerRequestInterface $request) : ResponseInterface
|
||||
{
|
||||
return new JsonResponse(['ack' => time()]);
|
||||
}
|
||||
}
|
||||
73
src/App/Handler/SlideHandler.php
Normal file
73
src/App/Handler/SlideHandler.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\SlideManager;
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class SlideHandler extends AbstractCrudHandler
|
||||
{
|
||||
/** @var SlideManager */
|
||||
private $slideManager;
|
||||
|
||||
public function __construct(SlideManager $teamService) {
|
||||
$this->slideManager = $teamService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function getList(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
return new JsonResponse($this->slideManager->listSlides());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function get(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->slideManager->getSlide((int)$id));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function create(ServerRequestInterface $request)
|
||||
{
|
||||
$data = $this->getRequestData($request);
|
||||
try {
|
||||
return new JsonResponse($this->slideManager->addSlide($data));
|
||||
} catch (UniqueConstraintViolationException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => 'The field `name` must be unique',
|
||||
], 500);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function delete(ServerRequestInterface $request)
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->slideManager->removeSlide($id));
|
||||
}
|
||||
}
|
||||
22
src/App/Handler/SlideHandlerFactory.php
Normal file
22
src/App/Handler/SlideHandlerFactory.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\SlideManager;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
class SlideHandlerFactory
|
||||
{
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @return RequestHandlerInterface
|
||||
*/
|
||||
public function __invoke(ContainerInterface $container) : RequestHandlerInterface
|
||||
{
|
||||
$slideManager = $container->get(SlideManager::class);
|
||||
return new SlideHandler($slideManager);
|
||||
}
|
||||
}
|
||||
73
src/App/Handler/TeamHandler.php
Normal file
73
src/App/Handler/TeamHandler.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\TeamService;
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class TeamHandler extends AbstractCrudHandler
|
||||
{
|
||||
/** @var TeamService */
|
||||
private $teamService;
|
||||
|
||||
public function __construct(TeamService $teamService) {
|
||||
$this->teamService = $teamService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function getList(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
return new JsonResponse($this->teamService->listTeams());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function get(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->teamService->getTeam((int)$id));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function create(ServerRequestInterface $request)
|
||||
{
|
||||
$data = $this->getRequestData($request);
|
||||
try {
|
||||
return new JsonResponse($this->teamService->addTeam($data));
|
||||
} catch (UniqueConstraintViolationException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => 'The field `name` must be unique',
|
||||
], 500);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function delete(ServerRequestInterface $request)
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->teamService->removeTeam($id));
|
||||
}
|
||||
}
|
||||
22
src/App/Handler/TeamHandlerFactory.php
Normal file
22
src/App/Handler/TeamHandlerFactory.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\TeamService;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
class TeamHandlerFactory
|
||||
{
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @return RequestHandlerInterface
|
||||
*/
|
||||
public function __invoke(ContainerInterface $container) : RequestHandlerInterface
|
||||
{
|
||||
$teamService = $container->get(TeamService::class);
|
||||
return new TeamHandler($teamService);
|
||||
}
|
||||
}
|
||||
124
src/App/Service/SlideManager.php
Normal file
124
src/App/Service/SlideManager.php
Normal file
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Slide;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class SlideManager
|
||||
{
|
||||
const ENTITY_NAME = Slide::class;
|
||||
|
||||
/** @var EntityManager */
|
||||
private $em;
|
||||
|
||||
/** @var Form */
|
||||
private $form;
|
||||
|
||||
public function __construct(EntityManager $em, Form $form)
|
||||
{
|
||||
$this->em = $em;
|
||||
$this->form = $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function listSlides(): array
|
||||
{
|
||||
return $this->em->getRepository(self::ENTITY_NAME)->findBy([
|
||||
'isActive' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Slide
|
||||
*/
|
||||
public function getSlide(int $id): Slide
|
||||
{
|
||||
/** @var Slide $entity */
|
||||
$entity = $this->em->getRepository(self::ENTITY_NAME)->find($id);
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return Slide
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
* @throws \Doctrine\DBAL\Exception\UniqueConstraintViolationException
|
||||
*/
|
||||
public function addSlide(array $data)
|
||||
{
|
||||
$entity = new Slide();
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->persist($entity);
|
||||
$this->em->flush();
|
||||
return $entity;
|
||||
} else {
|
||||
$messages = $this->form->getMessages();
|
||||
$fields = array_keys($messages);
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"The following fields are invalid: (%s)",
|
||||
implode(", ", $fields)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function changeSlide(int $id, array $data): bool
|
||||
{
|
||||
if (null === ($entity = $this->getSlide($id))) {
|
||||
return false;
|
||||
}
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->flush();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function removeSlide(int $id): bool
|
||||
{
|
||||
if (null !== ($entity = $this->getSlide($id))) {
|
||||
$this->em->remove($entity);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param bool $isVisible
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function setSlideVisible(int $id, bool $isVisible): bool
|
||||
{
|
||||
return $this->changeSlide($id, ['isVisible' => $isVisible]);
|
||||
}
|
||||
}
|
||||
23
src/App/Service/SlideManagerFactory.php
Normal file
23
src/App/Service/SlideManagerFactory.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Form\Team;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Zend\Form\Annotation\AnnotationBuilder;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class SlideManagerFactory
|
||||
{
|
||||
public function __invoke(ContainerInterface $container) : SlideManager
|
||||
{
|
||||
$em = $container->get(EntityManager::class);
|
||||
$formBuilder = $container->get(AnnotationBuilder::class);
|
||||
/** @var Form $form */
|
||||
$form = $formBuilder->createForm(Team::class);
|
||||
return new SlideManager($em, $form);
|
||||
}
|
||||
}
|
||||
124
src/App/Service/TeamService.php
Normal file
124
src/App/Service/TeamService.php
Normal file
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Team;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class TeamService
|
||||
{
|
||||
const ENTITY_NAME = Team::class;
|
||||
|
||||
/** @var EntityManager */
|
||||
private $em;
|
||||
|
||||
/** @var Form */
|
||||
private $form;
|
||||
|
||||
public function __construct(EntityManager $em, Form $form)
|
||||
{
|
||||
$this->em = $em;
|
||||
$this->form = $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function listTeams(): array
|
||||
{
|
||||
return $this->em->getRepository(self::ENTITY_NAME)->findBy([
|
||||
'isActive' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Team
|
||||
*/
|
||||
public function getTeam(int $id): ?Team
|
||||
{
|
||||
/** @var Team $entity */
|
||||
$entity = $this->em->getRepository(self::ENTITY_NAME)->find($id);
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return Team
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
* @throws \Doctrine\DBAL\Exception\UniqueConstraintViolationException
|
||||
*/
|
||||
public function addTeam(array $data): Team
|
||||
{
|
||||
$entity = new Team();
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->persist($entity);
|
||||
$this->em->flush();
|
||||
return $entity;
|
||||
} else {
|
||||
$messages = $this->form->getMessages();
|
||||
$fields = array_keys($messages);
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"The following fields are invalid: (%s)",
|
||||
implode(", ", $fields)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function changeTeam(int $id, array $data): bool
|
||||
{
|
||||
if (null === ($entity = $this->getTeam($id))) {
|
||||
return false;
|
||||
}
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->flush();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function removeTeam(int $id): bool
|
||||
{
|
||||
if (null !== ($entity = $this->getTeam($id))) {
|
||||
$this->em->remove($entity);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param bool $isVisible
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function setTeamActive(int $id, bool $isVisible): bool
|
||||
{
|
||||
return $this->changeTeam($id, ['isVisible' => $isVisible]);
|
||||
}
|
||||
}
|
||||
23
src/App/Service/TeamServiceFactory.php
Normal file
23
src/App/Service/TeamServiceFactory.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Form\Team;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Zend\Form\Annotation\AnnotationBuilder;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class TeamServiceFactory
|
||||
{
|
||||
public function __invoke(ContainerInterface $container) : TeamService
|
||||
{
|
||||
$em = $container->get(EntityManager::class);
|
||||
$formBuilder = $container->get(AnnotationBuilder::class);
|
||||
/** @var Form $form */
|
||||
$form = $formBuilder->createForm(Team::class);
|
||||
return new TeamService($em, $form);
|
||||
}
|
||||
}
|
||||
48
src/DoctrineExpressiveModule/ConfigProvider.php
Normal file
48
src/DoctrineExpressiveModule/ConfigProvider.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineExpressiveModule;
|
||||
|
||||
use Zend\EventManager\EventManager;
|
||||
|
||||
/**
|
||||
* The configuration provider for the DoctrineExpressiveModule module
|
||||
*
|
||||
* @see https://docs.zendframework.com/zend-component-installer/
|
||||
*/
|
||||
class ConfigProvider
|
||||
{
|
||||
/**
|
||||
* Returns the configuration array
|
||||
*
|
||||
* To add a bit of a structure, each section is defined in a separate
|
||||
* method which returns an array with its configuration.
|
||||
*
|
||||
*/
|
||||
public function __invoke() : array
|
||||
{
|
||||
return [
|
||||
'dependencies' => $this->getDependencies(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the container dependencies
|
||||
*/
|
||||
public function getDependencies() : array
|
||||
{
|
||||
return [
|
||||
'aliases' => [
|
||||
'doctrine.hydrator' => Hydrator\DoctrineObject::class,
|
||||
'EventManager' => EventManager::class,
|
||||
],
|
||||
'invokables' => [
|
||||
EventManager::class => EventManager::class,
|
||||
],
|
||||
'factories' => [
|
||||
Hydrator\DoctrineObject::class => Hydrator\DoctrineObjectFactory::class,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element\Exception;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class InvalidRepositoryResultException extends InvalidArgumentException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\MultiCheckbox;
|
||||
use Zend\Form\Form;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
class ObjectMultiCheckbox extends MultiCheckbox
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
if ($value instanceof \Traversable) {
|
||||
$value = ArrayUtils::iteratorToArray($value);
|
||||
} elseif ($value == null) {
|
||||
return parent::setValue([]);
|
||||
} elseif (! is_array($value)) {
|
||||
$value = (array)$value;
|
||||
}
|
||||
|
||||
return parent::setValue(array_map([$this->getProxy(), 'getValue'], $value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
73
src/DoctrineExpressiveModule/Form/Element/ObjectRadio.php
Normal file
73
src/DoctrineExpressiveModule/Form/Element/ObjectRadio.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineExpressiveModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\Radio as RadioElement;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class ObjectRadio extends RadioElement
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
return parent::setValue($this->getProxy()->getValue($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
88
src/DoctrineExpressiveModule/Form/Element/ObjectSelect.php
Normal file
88
src/DoctrineExpressiveModule/Form/Element/ObjectSelect.php
Normal file
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineExpressiveModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\Select as SelectElement;
|
||||
use Zend\Form\Form;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
class ObjectSelect extends SelectElement
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
$multiple = $this->getAttribute('multiple');
|
||||
|
||||
if (true === $multiple || 'multiple' === $multiple) {
|
||||
if ($value instanceof \Traversable) {
|
||||
$value = ArrayUtils::iteratorToArray($value);
|
||||
} elseif ($value == null) {
|
||||
return parent::setValue([]);
|
||||
} elseif (! is_array($value)) {
|
||||
$value = (array) $value;
|
||||
}
|
||||
|
||||
return parent::setValue(array_map([$this->getProxy(), 'getValue'], $value));
|
||||
}
|
||||
|
||||
return parent::setValue($this->getProxy()->getValue($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
653
src/DoctrineExpressiveModule/Form/Element/Proxy.php
Normal file
653
src/DoctrineExpressiveModule/Form/Element/Proxy.php
Normal file
@@ -0,0 +1,653 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use Traversable;
|
||||
use ReflectionMethod;
|
||||
use RuntimeException;
|
||||
use InvalidArgumentException;
|
||||
use Zend\Stdlib\Guard\ArrayOrTraversableGuardTrait;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Doctrine\Common\Util\Inflector;
|
||||
|
||||
class Proxy
|
||||
{
|
||||
use ArrayOrTraversableGuardTrait;
|
||||
|
||||
/**
|
||||
* @var array|Traversable
|
||||
*/
|
||||
protected $objects;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $targetClass;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $valueOptions = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $findMethod = [];
|
||||
|
||||
/**
|
||||
* @var
|
||||
*/
|
||||
protected $property;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $option_attributes = [];
|
||||
|
||||
/**
|
||||
* @var callable $labelGenerator A callable used to create a label based on an item in the collection an Entity
|
||||
*/
|
||||
protected $labelGenerator;
|
||||
|
||||
/**
|
||||
* @var bool|null
|
||||
*/
|
||||
protected $isMethod;
|
||||
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $displayEmptyItem = false;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $emptyItemLabel = '';
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $optgroupIdentifier;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $optgroupDefault;
|
||||
|
||||
public function setOptions($options)
|
||||
{
|
||||
if (isset($options['object_manager'])) {
|
||||
$this->setObjectManager($options['object_manager']);
|
||||
}
|
||||
|
||||
if (isset($options['target_class'])) {
|
||||
$this->setTargetClass($options['target_class']);
|
||||
}
|
||||
|
||||
if (isset($options['property'])) {
|
||||
$this->setProperty($options['property']);
|
||||
}
|
||||
|
||||
if (isset($options['label_generator'])) {
|
||||
$this->setLabelGenerator($options['label_generator']);
|
||||
}
|
||||
|
||||
if (isset($options['find_method'])) {
|
||||
$this->setFindMethod($options['find_method']);
|
||||
}
|
||||
|
||||
if (isset($options['is_method'])) {
|
||||
$this->setIsMethod($options['is_method']);
|
||||
}
|
||||
|
||||
if (isset($options['display_empty_item'])) {
|
||||
$this->setDisplayEmptyItem($options['display_empty_item']);
|
||||
}
|
||||
|
||||
if (isset($options['empty_item_label'])) {
|
||||
$this->setEmptyItemLabel($options['empty_item_label']);
|
||||
}
|
||||
|
||||
if (isset($options['option_attributes'])) {
|
||||
$this->setOptionAttributes($options['option_attributes']);
|
||||
}
|
||||
|
||||
if (isset($options['optgroup_identifier'])) {
|
||||
$this->setOptgroupIdentifier($options['optgroup_identifier']);
|
||||
}
|
||||
|
||||
if (isset($options['optgroup_default'])) {
|
||||
$this->setOptgroupDefault($options['optgroup_default']);
|
||||
}
|
||||
}
|
||||
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (empty($this->valueOptions)) {
|
||||
$this->loadValueOptions();
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|Traversable
|
||||
*/
|
||||
public function getObjects()
|
||||
{
|
||||
$this->loadObjects();
|
||||
|
||||
return $this->objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the label for the empty option
|
||||
*
|
||||
* @param string $emptyItemLabel
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setEmptyItemLabel($emptyItemLabel)
|
||||
{
|
||||
$this->emptyItemLabel = $emptyItemLabel;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getEmptyItemLabel()
|
||||
{
|
||||
return $this->emptyItemLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getOptionAttributes()
|
||||
{
|
||||
return $this->option_attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $option_attributes
|
||||
*/
|
||||
public function setOptionAttributes(array $option_attributes)
|
||||
{
|
||||
$this->option_attributes = $option_attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a flag, whether to include the empty option at the beginning or not
|
||||
*
|
||||
* @param boolean $displayEmptyItem
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setDisplayEmptyItem($displayEmptyItem)
|
||||
{
|
||||
$this->displayEmptyItem = $displayEmptyItem;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function getDisplayEmptyItem()
|
||||
{
|
||||
return $this->displayEmptyItem;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the object manager
|
||||
*
|
||||
* @param ObjectManager $objectManager
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setObjectManager(ObjectManager $objectManager)
|
||||
{
|
||||
$this->objectManager = $objectManager;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the object manager
|
||||
*
|
||||
* @return ObjectManager
|
||||
*/
|
||||
public function getObjectManager()
|
||||
{
|
||||
return $this->objectManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the FQCN of the target object
|
||||
*
|
||||
* @param string $targetClass
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setTargetClass($targetClass)
|
||||
{
|
||||
$this->targetClass = $targetClass;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the target class
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getTargetClass()
|
||||
{
|
||||
return $this->targetClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the property to use as the label in the options
|
||||
*
|
||||
* @param string $property
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setProperty($property)
|
||||
{
|
||||
$this->property = $property;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getProperty()
|
||||
{
|
||||
return $this->property;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the label generator callable that is responsible for generating labels for the items in the collection
|
||||
*
|
||||
* @param callable $callable A callable used to create a label based off of an Entity
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setLabelGenerator($callable)
|
||||
{
|
||||
if (! is_callable($callable)) {
|
||||
throw new InvalidArgumentException(
|
||||
'Property "label_generator" needs to be a callable function or a \Closure'
|
||||
);
|
||||
}
|
||||
|
||||
$this->labelGenerator = $callable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return callable|null
|
||||
*/
|
||||
public function getLabelGenerator()
|
||||
{
|
||||
return $this->labelGenerator;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOptgroupIdentifier()
|
||||
{
|
||||
return $this->optgroupIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $optgroupIdentifier
|
||||
*/
|
||||
public function setOptgroupIdentifier($optgroupIdentifier)
|
||||
{
|
||||
$this->optgroupIdentifier = (string) $optgroupIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOptgroupDefault()
|
||||
{
|
||||
return $this->optgroupDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $optgroupDefault
|
||||
*/
|
||||
public function setOptgroupDefault($optgroupDefault)
|
||||
{
|
||||
$this->optgroupDefault = (string) $optgroupDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set if the property is a method to use as the label in the options
|
||||
*
|
||||
* @param boolean $method
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setIsMethod($method)
|
||||
{
|
||||
$this->isMethod = (bool) $method;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getIsMethod()
|
||||
{
|
||||
return $this->isMethod;
|
||||
}
|
||||
|
||||
/** Set the findMethod property to specify the method to use on repository
|
||||
*
|
||||
* @param array $findMethod
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setFindMethod($findMethod)
|
||||
{
|
||||
$this->findMethod = $findMethod;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get findMethod definition
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getFindMethod()
|
||||
{
|
||||
return $this->findMethod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $targetEntity
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
protected function generateLabel($targetEntity)
|
||||
{
|
||||
if (null === ($labelGenerator = $this->getLabelGenerator())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return call_user_func($labelGenerator, $targetEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
*
|
||||
* @return array|mixed|object
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function getValue($value)
|
||||
{
|
||||
if (! ($om = $this->getObjectManager())) {
|
||||
throw new RuntimeException('No object manager was set');
|
||||
}
|
||||
|
||||
if (! ($targetClass = $this->getTargetClass())) {
|
||||
throw new RuntimeException('No target class was set');
|
||||
}
|
||||
|
||||
$metadata = $om->getClassMetadata($targetClass);
|
||||
|
||||
if (is_object($value)) {
|
||||
if ($value instanceof Collection) {
|
||||
$data = [];
|
||||
|
||||
foreach ($value as $object) {
|
||||
$values = $metadata->getIdentifierValues($object);
|
||||
$data[] = array_shift($values);
|
||||
}
|
||||
|
||||
$value = $data;
|
||||
} else {
|
||||
$metadata = $om->getClassMetadata(get_class($value));
|
||||
$identifier = $metadata->getIdentifierFieldNames();
|
||||
|
||||
// TODO: handle composite (multiple) identifiers
|
||||
if (null !== $identifier && count($identifier) > 1) {
|
||||
//$value = $key;
|
||||
} else {
|
||||
$value = current($metadata->getIdentifierValues($value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load objects
|
||||
*
|
||||
* @throws RuntimeException
|
||||
* @throws Exception\InvalidRepositoryResultException
|
||||
* @return void
|
||||
*/
|
||||
protected function loadObjects()
|
||||
{
|
||||
if (! empty($this->objects)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$findMethod = (array) $this->getFindMethod();
|
||||
|
||||
if (! $findMethod) {
|
||||
$findMethodName = 'findAll';
|
||||
$repository = $this->objectManager->getRepository($this->targetClass);
|
||||
$objects = $repository->findAll();
|
||||
} else {
|
||||
if (! isset($findMethod['name'])) {
|
||||
throw new RuntimeException('No method name was set');
|
||||
}
|
||||
$findMethodName = $findMethod['name'];
|
||||
$findMethodParams = isset($findMethod['params']) ? array_change_key_case($findMethod['params']) : [];
|
||||
$repository = $this->objectManager->getRepository($this->targetClass);
|
||||
|
||||
if (! method_exists($repository, $findMethodName)) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Method "%s" could not be found in repository "%s"',
|
||||
$findMethodName,
|
||||
get_class($repository)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$r = new ReflectionMethod($repository, $findMethodName);
|
||||
$args = [];
|
||||
|
||||
foreach ($r->getParameters() as $param) {
|
||||
if (array_key_exists(strtolower($param->getName()), $findMethodParams)) {
|
||||
$args[] = $findMethodParams[strtolower($param->getName())];
|
||||
} elseif ($param->isDefaultValueAvailable()) {
|
||||
$args[] = $param->getDefaultValue();
|
||||
} elseif (! $param->isOptional()) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Required parameter "%s" with no default value for method "%s" in repository "%s"'
|
||||
. ' was not provided',
|
||||
$param->getName(),
|
||||
$findMethodName,
|
||||
get_class($repository)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
$objects = $r->invokeArgs($repository, $args);
|
||||
}
|
||||
|
||||
$this->guardForArrayOrTraversable(
|
||||
$objects,
|
||||
sprintf('%s::%s() return value', get_class($repository), $findMethodName),
|
||||
'DoctrineModule\Form\Element\Exception\InvalidRepositoryResultException'
|
||||
);
|
||||
|
||||
$this->objects = $objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load value options
|
||||
*
|
||||
* @throws RuntimeException
|
||||
* @return void
|
||||
*/
|
||||
protected function loadValueOptions()
|
||||
{
|
||||
if (! ($om = $this->objectManager)) {
|
||||
throw new RuntimeException('No object manager was set');
|
||||
}
|
||||
|
||||
if (! ($targetClass = $this->targetClass)) {
|
||||
throw new RuntimeException('No target class was set');
|
||||
}
|
||||
|
||||
$metadata = $om->getClassMetadata($targetClass);
|
||||
$identifier = $metadata->getIdentifierFieldNames();
|
||||
$objects = $this->getObjects();
|
||||
$options = [];
|
||||
$optionAttributes = [];
|
||||
|
||||
if ($this->displayEmptyItem) {
|
||||
$options[''] = $this->getEmptyItemLabel();
|
||||
}
|
||||
|
||||
foreach ($objects as $key => $object) {
|
||||
if (null !== ($generatedLabel = $this->generateLabel($object))) {
|
||||
$label = $generatedLabel;
|
||||
} elseif ($property = $this->property) {
|
||||
if ($this->isMethod == false && ! $metadata->hasField($property)) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Property "%s" could not be found in object "%s"',
|
||||
$property,
|
||||
$targetClass
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$getter = 'get' . Inflector::classify($property);
|
||||
|
||||
if (! is_callable([$object, $getter])) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Method "%s::%s" is not callable', $this->targetClass, $getter)
|
||||
);
|
||||
}
|
||||
|
||||
$label = $object->{$getter}();
|
||||
} else {
|
||||
if (! is_callable([$object, '__toString'])) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'%s must have a "__toString()" method defined if you have not set a property'
|
||||
. ' or method to use.',
|
||||
$targetClass
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$label = (string) $object;
|
||||
}
|
||||
|
||||
if (null !== $identifier && count($identifier) > 1) {
|
||||
$value = $key;
|
||||
} else {
|
||||
$value = current($metadata->getIdentifierValues($object));
|
||||
}
|
||||
|
||||
foreach ($this->getOptionAttributes() as $optionKey => $optionValue) {
|
||||
if (is_string($optionValue)) {
|
||||
$optionAttributes[$optionKey] = $optionValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_callable($optionValue)) {
|
||||
$callableValue = call_user_func($optionValue, $object);
|
||||
$optionAttributes[$optionKey] = (string) $callableValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Parameter "option_attributes" expects an array of key => value where value is of type'
|
||||
. '"string" or "callable". Value of type "%s" found.',
|
||||
gettype($optionValue)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// If no optgroup_identifier has been configured, apply default handling and continue
|
||||
if (is_null($this->getOptgroupIdentifier())) {
|
||||
$options[] = ['label' => $label, 'value' => $value, 'attributes' => $optionAttributes];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// optgroup_identifier found, handle grouping
|
||||
$optgroupGetter = 'get' . Inflector::classify($this->getOptgroupIdentifier());
|
||||
|
||||
if (! is_callable([$object, $optgroupGetter])) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Method "%s::%s" is not callable', $this->targetClass, $optgroupGetter)
|
||||
);
|
||||
}
|
||||
|
||||
$optgroup = $object->{$optgroupGetter}();
|
||||
|
||||
// optgroup_identifier contains a valid group-name. Handle default grouping.
|
||||
if (false === is_null($optgroup) && trim($optgroup) !== '') {
|
||||
$options[$optgroup]['label'] = $optgroup;
|
||||
$options[$optgroup]['options'][] = [
|
||||
'label' => $label,
|
||||
'value' => $value,
|
||||
'attributes' => $optionAttributes,
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$optgroupDefault = $this->getOptgroupDefault();
|
||||
|
||||
// No optgroup_default has been provided. Line up without a group
|
||||
if (is_null($optgroupDefault)) {
|
||||
$options[] = ['label' => $label, 'value' => $value, 'attributes' => $optionAttributes];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Line up entry with optgroup_default
|
||||
$options[$optgroupDefault]['label'] = $optgroupDefault;
|
||||
$options[$optgroupDefault]['options'][] = [
|
||||
'label' => $label,
|
||||
'value' => $value,
|
||||
'attributes' => $optionAttributes,
|
||||
];
|
||||
}
|
||||
|
||||
$this->valueOptions = $options;
|
||||
}
|
||||
}
|
||||
594
src/DoctrineExpressiveModule/Hydrator/DoctrineObject.php
Normal file
594
src/DoctrineExpressiveModule/Hydrator/DoctrineObject.php
Normal file
@@ -0,0 +1,594 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator;
|
||||
|
||||
use DateTime;
|
||||
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Doctrine\Common\Util\Inflector;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use Traversable;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
use Zend\Hydrator\AbstractHydrator;
|
||||
use Zend\Hydrator\Filter\FilterProviderInterface;
|
||||
|
||||
/**
|
||||
* This hydrator has been completely refactored for DoctrineModule 0.7.0. It provides an easy and powerful way
|
||||
* of extracting/hydrator objects in Doctrine, by handling most associations types.
|
||||
*
|
||||
* Starting from DoctrineModule 0.8.0, the hydrator can be used multiple times with different objects
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DoctrineObject extends AbstractHydrator
|
||||
{
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var ClassMetadata
|
||||
*/
|
||||
protected $metadata;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $byValue = true;
|
||||
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param ObjectManager $objectManager The ObjectManager to use
|
||||
* @param bool $byValue If set to true, hydrator will always use entity's public API
|
||||
*/
|
||||
public function __construct(ObjectManager $objectManager, $byValue = true)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->objectManager = $objectManager;
|
||||
$this->byValue = (bool) $byValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object
|
||||
*
|
||||
* @param object $object
|
||||
* @return array
|
||||
*/
|
||||
public function extract($object)
|
||||
{
|
||||
$this->prepare($object);
|
||||
|
||||
if ($this->byValue) {
|
||||
return $this->extractByValue($object);
|
||||
}
|
||||
|
||||
return $this->extractByReference($object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate $object with the provided $data.
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
public function hydrate(array $data, $object)
|
||||
{
|
||||
$this->prepare($object);
|
||||
|
||||
if ($this->byValue) {
|
||||
return $this->hydrateByValue($data, $object);
|
||||
}
|
||||
|
||||
return $this->hydrateByReference($data, $object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the hydrator by adding strategies to every collection valued associations
|
||||
*
|
||||
* @param object $object
|
||||
* @return void
|
||||
*/
|
||||
protected function prepare($object)
|
||||
{
|
||||
$this->metadata = $this->objectManager->getClassMetadata(get_class($object));
|
||||
$this->prepareStrategies();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare strategies before the hydrator is used
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareStrategies()
|
||||
{
|
||||
$associations = $this->metadata->getAssociationNames();
|
||||
|
||||
foreach ($associations as $association) {
|
||||
if ($this->metadata->isCollectionValuedAssociation($association)) {
|
||||
// Add a strategy if the association has none set by user
|
||||
if (!$this->hasStrategy($association)) {
|
||||
if ($this->byValue) {
|
||||
$this->addStrategy($association, new Strategy\AllowRemoveByValue());
|
||||
} else {
|
||||
$this->addStrategy($association, new Strategy\AllowRemoveByReference());
|
||||
}
|
||||
}
|
||||
|
||||
$strategy = $this->getStrategy($association);
|
||||
|
||||
if (!$strategy instanceof Strategy\AbstractCollectionStrategy) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf(
|
||||
'Strategies used for collections valued associations must inherit from '
|
||||
. 'Strategy\AbstractCollectionStrategy, %s given',
|
||||
get_class($strategy)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$strategy->setCollectionName($association)
|
||||
->setClassMetadata($this->metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object using a by-value logic (this means that it uses the entity
|
||||
* API, in this case, getters)
|
||||
*
|
||||
* @param object $object
|
||||
* @throws RuntimeException
|
||||
* @return array
|
||||
*/
|
||||
protected function extractByValue($object)
|
||||
{
|
||||
$fieldNames = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames());
|
||||
$methods = get_class_methods($object);
|
||||
$filter = $object instanceof FilterProviderInterface
|
||||
? $object->getFilter()
|
||||
: $this->filterComposite;
|
||||
|
||||
$data = [];
|
||||
foreach ($fieldNames as $fieldName) {
|
||||
if ($filter && !$filter->filter($fieldName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$getter = 'get' . Inflector::classify($fieldName);
|
||||
$isser = 'is' . Inflector::classify($fieldName);
|
||||
|
||||
$dataFieldName = $this->computeExtractFieldName($fieldName);
|
||||
if (in_array($getter, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$getter(), $object);
|
||||
} elseif (in_array($isser, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$isser(), $object);
|
||||
} elseif (substr($fieldName, 0, 2) === 'is'
|
||||
&& ctype_upper(substr($fieldName, 2, 1))
|
||||
&& in_array($fieldName, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$fieldName(), $object);
|
||||
}
|
||||
|
||||
// Unknown fields are ignored
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object using a by-reference logic (this means that values are
|
||||
* directly fetched without using the public API of the entity, in this case, getters)
|
||||
*
|
||||
* @param object $object
|
||||
* @return array
|
||||
*/
|
||||
protected function extractByReference($object)
|
||||
{
|
||||
$fieldNames = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames());
|
||||
$refl = $this->metadata->getReflectionClass();
|
||||
$filter = $object instanceof FilterProviderInterface
|
||||
? $object->getFilter()
|
||||
: $this->filterComposite;
|
||||
|
||||
$data = [];
|
||||
foreach ($fieldNames as $fieldName) {
|
||||
if ($filter && !$filter->filter($fieldName)) {
|
||||
continue;
|
||||
}
|
||||
$reflProperty = $refl->getProperty($fieldName);
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
$dataFieldName = $this->computeExtractFieldName($fieldName);
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $reflProperty->getValue($object), $object);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate the object using a by-value logic (this means that it uses the entity API, in this
|
||||
* case, setters)
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @throws RuntimeException
|
||||
* @return object
|
||||
*/
|
||||
protected function hydrateByValue(array $data, $object)
|
||||
{
|
||||
$tryObject = $this->tryConvertArrayToObject($data, $object);
|
||||
$metadata = $this->metadata;
|
||||
|
||||
if (is_object($tryObject)) {
|
||||
$object = $tryObject;
|
||||
}
|
||||
|
||||
foreach ($data as $field => $value) {
|
||||
$field = $this->computeHydrateFieldName($field);
|
||||
$value = $this->handleTypeConversions($value, $metadata->getTypeOfField($field));
|
||||
$setter = 'set' . Inflector::classify($field);
|
||||
|
||||
if ($metadata->hasAssociation($field)) {
|
||||
$target = $metadata->getAssociationTargetClass($field);
|
||||
|
||||
if ($metadata->isSingleValuedAssociation($field)) {
|
||||
if (! method_exists($object, $setter)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
|
||||
|
||||
if (null === $value
|
||||
&& !current($metadata->getReflectionClass()->getMethod($setter)->getParameters())->allowsNull()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$object->$setter($value);
|
||||
} elseif ($metadata->isCollectionValuedAssociation($field)) {
|
||||
$this->toMany($object, $field, $target, $value);
|
||||
}
|
||||
} else {
|
||||
if (! method_exists($object, $setter)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$object->$setter($this->hydrateValue($field, $value, $data));
|
||||
}
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate the object using a by-reference logic (this means that values are modified directly without
|
||||
* using the public API, in this case setters, and hence override any logic that could be done in those
|
||||
* setters)
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
protected function hydrateByReference(array $data, $object)
|
||||
{
|
||||
$tryObject = $this->tryConvertArrayToObject($data, $object);
|
||||
$metadata = $this->metadata;
|
||||
$refl = $metadata->getReflectionClass();
|
||||
|
||||
if (is_object($tryObject)) {
|
||||
$object = $tryObject;
|
||||
}
|
||||
|
||||
foreach ($data as $field => $value) {
|
||||
$field = $this->computeHydrateFieldName($field);
|
||||
|
||||
// Ignore unknown fields
|
||||
if (!$refl->hasProperty($field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->handleTypeConversions($value, $metadata->getTypeOfField($field));
|
||||
$reflProperty = $refl->getProperty($field);
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
if ($metadata->hasAssociation($field)) {
|
||||
$target = $metadata->getAssociationTargetClass($field);
|
||||
|
||||
if ($metadata->isSingleValuedAssociation($field)) {
|
||||
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
|
||||
$reflProperty->setValue($object, $value);
|
||||
} elseif ($metadata->isCollectionValuedAssociation($field)) {
|
||||
$this->toMany($object, $field, $target, $value);
|
||||
}
|
||||
} else {
|
||||
$reflProperty->setValue($object, $this->hydrateValue($field, $value, $data));
|
||||
}
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function tries, given an array of data, to convert it to an object if the given array contains
|
||||
* an identifier for the object. This is useful in a context of updating existing entities, without ugly
|
||||
* tricks like setting manually the existing id directly into the entity
|
||||
*
|
||||
* @param array $data The data that may contain identifiers keys
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
protected function tryConvertArrayToObject($data, $object)
|
||||
{
|
||||
$metadata = $this->metadata;
|
||||
$identifierNames = $metadata->getIdentifierFieldNames($object);
|
||||
$identifierValues = [];
|
||||
|
||||
if (empty($identifierNames)) {
|
||||
return $object;
|
||||
}
|
||||
|
||||
foreach ($identifierNames as $identifierName) {
|
||||
if (!isset($data[$identifierName])) {
|
||||
return $object;
|
||||
}
|
||||
|
||||
$identifierValues[$identifierName] = $data[$identifierName];
|
||||
}
|
||||
|
||||
return $this->find($identifierValues, $metadata->getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle ToOne associations
|
||||
*
|
||||
* When $value is an array but is not the $target's identifiers, $value is
|
||||
* most likely an array of fieldset data. The identifiers will be determined
|
||||
* and a target instance will be initialized and then hydrated. The hydrated
|
||||
* target will be returned.
|
||||
*
|
||||
* @param string $target
|
||||
* @param mixed $value
|
||||
* @return object
|
||||
*/
|
||||
protected function toOne($target, $value)
|
||||
{
|
||||
$metadata = $this->objectManager->getClassMetadata($target);
|
||||
|
||||
if (is_array($value) && array_keys($value) != $metadata->getIdentifier()) {
|
||||
// $value is most likely an array of fieldset data
|
||||
$identifiers = array_intersect_key(
|
||||
$value,
|
||||
array_flip($metadata->getIdentifier())
|
||||
);
|
||||
$object = $this->find($identifiers, $target) ?: new $target;
|
||||
return $this->hydrate($value, $object);
|
||||
}
|
||||
|
||||
return $this->find($value, $target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle ToMany associations. In proper Doctrine design, Collections should not be swapped, so
|
||||
* collections are always handled by reference. Internally, every collection is handled using specials
|
||||
* strategies that inherit from AbstractCollectionStrategy class, and that add or remove elements but without
|
||||
* changing the collection of the object
|
||||
*
|
||||
* @param object $object
|
||||
* @param mixed $collectionName
|
||||
* @param string $target
|
||||
* @param mixed $values
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function toMany($object, $collectionName, $target, $values)
|
||||
{
|
||||
$metadata = $this->objectManager->getClassMetadata(ltrim($target, '\\'));
|
||||
$identifier = $metadata->getIdentifier();
|
||||
|
||||
if (!is_array($values) && !$values instanceof Traversable) {
|
||||
$values = (array)$values;
|
||||
}
|
||||
|
||||
$collection = [];
|
||||
|
||||
// If the collection contains identifiers, fetch the objects from database
|
||||
foreach ($values as $value) {
|
||||
if ($value instanceof $target) {
|
||||
// assumes modifications have already taken place in object
|
||||
$collection[] = $value;
|
||||
continue;
|
||||
} elseif (empty($value)) {
|
||||
// assumes no id and retrieves new $target
|
||||
$collection[] = $this->find($value, $target);
|
||||
continue;
|
||||
}
|
||||
|
||||
$find = [];
|
||||
if (is_array($identifier)) {
|
||||
foreach ($identifier as $field) {
|
||||
switch (gettype($value)) {
|
||||
case 'object':
|
||||
$getter = 'get' . ucfirst($field);
|
||||
if (method_exists($value, $getter)) {
|
||||
$find[$field] = $value->$getter();
|
||||
} elseif (property_exists($value, $field)) {
|
||||
$find[$field] = $value->$field;
|
||||
}
|
||||
break;
|
||||
case 'array':
|
||||
if (array_key_exists($field, $value) && $value[$field] != null) {
|
||||
$find[$field] = $value[$field];
|
||||
unset($value[$field]); // removed identifier from persistable data
|
||||
}
|
||||
break;
|
||||
default:
|
||||
$find[$field] = $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($find) && $found = $this->find($find, $target)) {
|
||||
$collection[] = (is_array($value)) ? $this->hydrate($value, $found) : $found;
|
||||
} else {
|
||||
$collection[] = (is_array($value)) ? $this->hydrate($value, new $target) : new $target;
|
||||
}
|
||||
}
|
||||
|
||||
$collection = array_filter(
|
||||
$collection,
|
||||
function ($item) {
|
||||
return null !== $item;
|
||||
}
|
||||
);
|
||||
|
||||
// Set the object so that the strategy can extract the Collection from it
|
||||
|
||||
/** @var \DoctrineModule\Stdlib\Hydrator\Strategy\AbstractCollectionStrategy $collectionStrategy */
|
||||
$collectionStrategy = $this->getStrategy($collectionName);
|
||||
$collectionStrategy->setObject($object);
|
||||
|
||||
// We could directly call hydrate method from the strategy, but if people want to override
|
||||
// hydrateValue function, they can do it and do their own stuff
|
||||
$this->hydrateValue($collectionName, $collection, $values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle various type conversions that should be supported natively by Doctrine (like DateTime)
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param string $typeOfField
|
||||
* @return DateTime
|
||||
*/
|
||||
protected function handleTypeConversions($value, $typeOfField)
|
||||
{
|
||||
switch ($typeOfField) {
|
||||
case 'datetimetz':
|
||||
case 'datetime':
|
||||
case 'time':
|
||||
case 'date':
|
||||
if ('' === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_int($value)) {
|
||||
$dateTime = new DateTime();
|
||||
$dateTime->setTimestamp($value);
|
||||
$value = $dateTime;
|
||||
} elseif (is_string($value)) {
|
||||
$value = new DateTime($value);
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an object by a given target class and identifier
|
||||
*
|
||||
* @param mixed $identifiers
|
||||
* @param string $targetClass
|
||||
*
|
||||
* @return object|null
|
||||
*/
|
||||
protected function find($identifiers, $targetClass)
|
||||
{
|
||||
if ($identifiers instanceof $targetClass) {
|
||||
return $identifiers;
|
||||
}
|
||||
|
||||
if ($this->isNullIdentifier($identifiers)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->objectManager->find($targetClass, $identifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies if a provided identifier is to be considered null
|
||||
*
|
||||
* @param mixed $identifier
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function isNullIdentifier($identifier)
|
||||
{
|
||||
if (null === $identifier) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($identifier instanceof Traversable || is_array($identifier)) {
|
||||
$nonNullIdentifiers = array_filter(
|
||||
ArrayUtils::iteratorToArray($identifier),
|
||||
function ($value) {
|
||||
return null !== $value;
|
||||
}
|
||||
);
|
||||
|
||||
return empty($nonNullIdentifiers);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the naming strategy if there is one set
|
||||
*
|
||||
* @param string $field
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function computeHydrateFieldName($field)
|
||||
{
|
||||
if ($this->hasNamingStrategy()) {
|
||||
$field = $this->getNamingStrategy()->hydrate($field);
|
||||
}
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the naming strategy if there is one set
|
||||
*
|
||||
* @param string $field
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function computeExtractFieldName($field)
|
||||
{
|
||||
if ($this->hasNamingStrategy()) {
|
||||
$field = $this->getNamingStrategy()->extract($field);
|
||||
}
|
||||
return $field;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
|
||||
class DoctrineObjectFactory
|
||||
{
|
||||
|
||||
public function __invoke(ContainerInterface $container)
|
||||
{
|
||||
$em = $container->get('doctrine.entity_manager.orm_default');
|
||||
return new DoctrineObject($em);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Filter;
|
||||
|
||||
use Zend\Hydrator\Filter\FilterInterface;
|
||||
|
||||
/**
|
||||
* Provides a filter to restrict returned fields by whitelisting or
|
||||
* blacklisting property names.
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @author Liam O'Boyle <liam@ontheroad.net.nz>
|
||||
*/
|
||||
class PropertyName implements FilterInterface
|
||||
{
|
||||
/**
|
||||
* The propteries to exclude.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $properties = [];
|
||||
|
||||
/**
|
||||
* Either an exclude or an include.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $exclude = null;
|
||||
|
||||
/**
|
||||
* @param [ string | array ] $properties The properties to exclude or include.
|
||||
* @param bool $exclude If the method should be excluded
|
||||
*/
|
||||
public function __construct($properties, $exclude = true)
|
||||
{
|
||||
$this->exclude = $exclude;
|
||||
$this->properties = is_array($properties)
|
||||
? $properties
|
||||
: [$properties];
|
||||
}
|
||||
|
||||
public function filter($property)
|
||||
{
|
||||
return in_array($property, $this->properties)
|
||||
? !$this->exclude
|
||||
: $this->exclude;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
|
||||
use Zend\Hydrator\Strategy\StrategyInterface;
|
||||
|
||||
/**
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
abstract class AbstractCollectionStrategy implements StrategyInterface
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $collectionName;
|
||||
|
||||
/**
|
||||
* @var ClassMetadata
|
||||
*/
|
||||
protected $metadata;
|
||||
|
||||
/**
|
||||
* @var object
|
||||
*/
|
||||
protected $object;
|
||||
|
||||
|
||||
/**
|
||||
* Set the name of the collection
|
||||
*
|
||||
* @param string $collectionName
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setCollectionName($collectionName)
|
||||
{
|
||||
$this->collectionName = (string) $collectionName;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the collection
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getCollectionName()
|
||||
{
|
||||
return $this->collectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the class metadata
|
||||
*
|
||||
* @param ClassMetadata $classMetadata
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setClassMetadata(ClassMetadata $classMetadata)
|
||||
{
|
||||
$this->metadata = $classMetadata;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class metadata
|
||||
*
|
||||
* @return ClassMetadata
|
||||
*/
|
||||
public function getClassMetadata()
|
||||
{
|
||||
return $this->metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the object
|
||||
*
|
||||
* @param object $object
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setObject($object)
|
||||
{
|
||||
if (!is_object($object)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('The parameter given to setObject method of %s class is not an object', get_called_class())
|
||||
);
|
||||
}
|
||||
|
||||
$this->object = $object;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the object
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function getObject()
|
||||
{
|
||||
return $this->object;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function extract($value)
|
||||
{
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the collection by value (using the public API)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
protected function getCollectionFromObjectByValue()
|
||||
{
|
||||
$object = $this->getObject();
|
||||
$getter = 'get' . ucfirst($this->getCollectionName());
|
||||
|
||||
if (!method_exists($object, $getter)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf(
|
||||
'The getter %s to access collection %s in object %s does not exist',
|
||||
$getter,
|
||||
$this->getCollectionName(),
|
||||
get_class($object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $object->$getter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the collection by reference (not using the public API)
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
protected function getCollectionFromObjectByReference()
|
||||
{
|
||||
$object = $this->getObject();
|
||||
$refl = $this->getClassMetadata()->getReflectionClass();
|
||||
$reflProperty = $refl->getProperty($this->getCollectionName());
|
||||
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
return $reflProperty->getValue($object);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is used internally by array_udiff to check if two objects are equal, according to their
|
||||
* SPL hash. This is needed because the native array_diff only compare strings
|
||||
*
|
||||
* @param object $a
|
||||
* @param object $b
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function compareObjects($a, $b)
|
||||
{
|
||||
return strcmp(spl_object_hash($a), spl_object_hash($b));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy remove elements from the original collection. For instance, if the
|
||||
* collection initially contains elements A and B, and that the new collection contains elements B and C, then the
|
||||
* final collection will contain elements B and C (while element A will be asked to be removed).
|
||||
*
|
||||
* This strategy is by reference, this means it won't use public API to add/remove elements to the collection
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class AllowRemoveByReference extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
$collection = $this->getCollectionFromObjectByReference();
|
||||
$collectionArray = $collection->toArray();
|
||||
|
||||
$toAdd = array_udiff($value, $collectionArray, [$this, 'compareObjects']);
|
||||
$toRemove = array_udiff($collectionArray, $value, [$this, 'compareObjects']);
|
||||
|
||||
foreach ($toAdd as $element) {
|
||||
$collection->add($element);
|
||||
}
|
||||
|
||||
foreach ($toRemove as $element) {
|
||||
$collection->removeElement($element);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use LogicException;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy remove elements from the original collection. For instance, if the
|
||||
* collection initially contains elements A and B, and that the new collection contains elements B and C, then the
|
||||
* final collection will contain elements B and C (while element A will be asked to be removed).
|
||||
*
|
||||
* This strategy is by value, this means it will use the public API (in this case, adder and remover)
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class AllowRemoveByValue extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
// AllowRemove strategy need "adder" and "remover"
|
||||
$adder = 'add' . ucfirst($this->collectionName);
|
||||
$remover = 'remove' . ucfirst($this->collectionName);
|
||||
|
||||
if (!method_exists($this->object, $adder) || !method_exists($this->object, $remover)) {
|
||||
throw new LogicException(
|
||||
sprintf(
|
||||
'AllowRemove strategy for DoctrineModule hydrator requires both %s and %s to be defined in %s
|
||||
entity domain code, but one or both seem to be missing',
|
||||
$adder,
|
||||
$remover,
|
||||
get_class($this->object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$collection = $this->getCollectionFromObjectByValue();
|
||||
|
||||
if ($collection instanceof Collection) {
|
||||
$collection = $collection->toArray();
|
||||
}
|
||||
|
||||
$toAdd = new ArrayCollection(array_udiff($value, $collection, [$this, 'compareObjects']));
|
||||
$toRemove = new ArrayCollection(array_udiff($collection, $value, [$this, 'compareObjects']));
|
||||
|
||||
$this->object->$adder($toAdd);
|
||||
$this->object->$remover($toRemove);
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy will not remove those elements. At most, it will add new elements. For
|
||||
* instance, if the collection initially contains elements A and B, and that the new collection contains elements B
|
||||
* and C, then the final collection will contain elements A, B and C.
|
||||
*
|
||||
* This strategy is by reference, this means it won't use the public API to remove elements
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DisallowRemoveByReference extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
$collection = $this->getCollectionFromObjectByReference();
|
||||
$collectionArray = $collection->toArray();
|
||||
|
||||
$toAdd = array_udiff($value, $collectionArray, [$this, 'compareObjects']);
|
||||
|
||||
foreach ($toAdd as $element) {
|
||||
$collection->add($element);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use LogicException;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy will not remove those elements. At most, it will add new elements. For
|
||||
* instance, if the collection initially contains elements A and B, and that the new collection contains elements B
|
||||
* and C, then the final collection will contain elements A, B and C.
|
||||
*
|
||||
* This strategy is by value, this means it will use the public API (in this case, remover)
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DisallowRemoveByValue extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
// AllowRemove strategy need "adder"
|
||||
$adder = 'add' . ucfirst($this->collectionName);
|
||||
|
||||
if (!method_exists($this->object, $adder)) {
|
||||
throw new LogicException(
|
||||
sprintf(
|
||||
'DisallowRemove strategy for DoctrineModule hydrator requires %s to
|
||||
be defined in %s entity domain code, but it seems to be missing',
|
||||
$adder,
|
||||
get_class($this->object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$collection = $this->getCollectionFromObjectByValue();
|
||||
|
||||
if ($collection instanceof Collection) {
|
||||
$collection = $collection->toArray();
|
||||
}
|
||||
|
||||
$toAdd = new ArrayCollection(array_udiff($value, $collection, [$this, 'compareObjects']));
|
||||
|
||||
$this->object->$adder($toAdd);
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
43
src/DoctrineExpressiveModule/Validator/NoObjectExists.php
Normal file
43
src/DoctrineExpressiveModule/Validator/NoObjectExists.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
/**
|
||||
* Class that validates if objects does not exist in a given repository with a given list of matched fields
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.4.0
|
||||
* @author Marco Pivetta <ocramius@gmail.com>
|
||||
*/
|
||||
class NoObjectExists extends ObjectExists
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_OBJECT_FOUND = 'objectFound';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_OBJECT_FOUND => "An object matching '%value%' was found",
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isValid($value)
|
||||
{
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (is_object($match)) {
|
||||
$this->error(self::ERROR_OBJECT_FOUND, $value);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
175
src/DoctrineExpressiveModule/Validator/ObjectExists.php
Normal file
175
src/DoctrineExpressiveModule/Validator/ObjectExists.php
Normal file
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Doctrine\Common\Persistence\ObjectRepository;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
/**
|
||||
* Class that validates if objects exist in a given repository with a given list of matched fields
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.4.0
|
||||
* @author Marco Pivetta <ocramius@gmail.com>
|
||||
*/
|
||||
class ObjectExists extends AbstractValidator
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_NO_OBJECT_FOUND = 'noObjectFound';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_NO_OBJECT_FOUND => "No object matching '%value%' was found",
|
||||
];
|
||||
|
||||
/**
|
||||
* ObjectRepository from which to search for entities
|
||||
*
|
||||
* @var ObjectRepository
|
||||
*/
|
||||
protected $objectRepository;
|
||||
|
||||
/**
|
||||
* Fields to be checked
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fields;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $options required keys are `object_repository`, which must be an instance of
|
||||
* Doctrine\Common\Persistence\ObjectRepository, and `fields`, with either
|
||||
* a string or an array of strings representing the fields to be matched by the validator.
|
||||
* @throws \Zend\Validator\Exception\InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $options)
|
||||
{
|
||||
if (! isset($options['object_repository']) || ! $options['object_repository'] instanceof ObjectRepository) {
|
||||
if (! array_key_exists('object_repository', $options)) {
|
||||
$provided = 'nothing';
|
||||
} else {
|
||||
if (is_object($options['object_repository'])) {
|
||||
$provided = get_class($options['object_repository']);
|
||||
} else {
|
||||
$provided = getType($options['object_repository']);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf(
|
||||
'Option "object_repository" is required and must be an instance of'
|
||||
. ' Doctrine\Common\Persistence\ObjectRepository, %s given',
|
||||
$provided
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$this->objectRepository = $options['object_repository'];
|
||||
|
||||
if (! isset($options['fields'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Key `fields` must be provided and be a field or a list of fields to be used when searching for'
|
||||
. ' existing instances'
|
||||
);
|
||||
}
|
||||
|
||||
$this->fields = $options['fields'];
|
||||
$this->validateFields();
|
||||
|
||||
parent::__construct($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters and validates the fields passed to the constructor
|
||||
*
|
||||
* @throws \Zend\Validator\Exception\InvalidArgumentException
|
||||
* @return array
|
||||
*/
|
||||
private function validateFields()
|
||||
{
|
||||
$fields = (array) $this->fields;
|
||||
|
||||
if (empty($fields)) {
|
||||
throw new Exception\InvalidArgumentException('Provided fields list was empty!');
|
||||
}
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
if (! is_string($field)) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf('Provided fields must be strings, %s provided for key %s', gettype($field), $key)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->fields = array_values($fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $value a field value or an array of field values if more fields have been configured to be
|
||||
* matched
|
||||
* @return array
|
||||
* @throws \Zend\Validator\Exception\RuntimeException
|
||||
*/
|
||||
protected function cleanSearchValue($value)
|
||||
{
|
||||
$value = is_object($value) ? [$value] : (array) $value;
|
||||
|
||||
if (ArrayUtils::isHashTable($value)) {
|
||||
$matchedFieldsValues = [];
|
||||
|
||||
foreach ($this->fields as $field) {
|
||||
if (! array_key_exists($field, $value)) {
|
||||
throw new Exception\RuntimeException(
|
||||
sprintf(
|
||||
'Field "%s" was not provided, but was expected since the configured field lists needs'
|
||||
. ' it for validation',
|
||||
$field
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$matchedFieldsValues[$field] = $value[$field];
|
||||
}
|
||||
} else {
|
||||
$matchedFieldsValues = @array_combine($this->fields, $value);
|
||||
|
||||
if (false === $matchedFieldsValues) {
|
||||
throw new Exception\RuntimeException(
|
||||
sprintf(
|
||||
'Provided values count is %s, while expected number of fields to be matched is %s',
|
||||
count($value),
|
||||
count($this->fields)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $matchedFieldsValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isValid($value)
|
||||
{
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (is_object($match)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->error(self::ERROR_NO_OBJECT_FOUND, $value);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Zend\ServiceManager\FactoryInterface;
|
||||
use Interop\Container\ContainerInterface;
|
||||
use Zend\ServiceManager\ServiceLocatorInterface;
|
||||
use Zend\ServiceManager\ServiceLocatorAwareInterface;
|
||||
use DoctrineModule\Validator\Service\Exception\ServiceCreationException;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
/**
|
||||
* Factory for creating NoObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
abstract class AbstractValidatorFactory implements FactoryInterface
|
||||
{
|
||||
const DEFAULT_OBJECTMANAGER_KEY = 'doctrine.entitymanager.orm_default';
|
||||
|
||||
protected $creationOptions = [];
|
||||
|
||||
protected $validatorClass;
|
||||
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @param array $options
|
||||
* @return \Doctrine\Common\Persistence\ObjectRepository
|
||||
* @throws ServiceCreationException
|
||||
*/
|
||||
protected function getRepository(ContainerInterface $container, array $options)
|
||||
{
|
||||
if (empty($options['target_class'])) {
|
||||
throw new ServiceCreationException(sprintf(
|
||||
"Option 'target_class' is missing when creating validator %s",
|
||||
__CLASS__
|
||||
));
|
||||
}
|
||||
|
||||
$objectManager = $this->getObjectManager($container, $options);
|
||||
$targetClassName = $options['target_class'];
|
||||
$objectRepository = $objectManager->getRepository($targetClassName);
|
||||
|
||||
return $objectRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @param array $options
|
||||
* @return \Doctrine\Common\Persistence\ObjectManager
|
||||
*/
|
||||
protected function getObjectManager(ContainerInterface $container, array $options)
|
||||
{
|
||||
$objectManager = ($options['object_manager']) ?? self::DEFAULT_OBJECTMANAGER_KEY;
|
||||
|
||||
if (is_string($objectManager)) {
|
||||
$objectManager = $container->get($objectManager);
|
||||
}
|
||||
|
||||
return $objectManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $options
|
||||
* @return array
|
||||
*/
|
||||
protected function getFields(array $options)
|
||||
{
|
||||
if (isset($options['fields'])) {
|
||||
return (array) $options['fields'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to merge options array passed to `__invoke`
|
||||
* together with the options array created based on the above
|
||||
* helper methods.
|
||||
*
|
||||
* @param array $previousOptions
|
||||
* @param array $newOptions
|
||||
* @return array
|
||||
*/
|
||||
protected function merge($previousOptions, $newOptions)
|
||||
{
|
||||
return ArrayUtils::merge($previousOptions, $newOptions, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for ZF2 compatiblity.
|
||||
*
|
||||
* In ZF2 the plugin manager instance if passed to `createService`
|
||||
* instead of the global service manager instance (as in ZF3).
|
||||
*
|
||||
* @param ContainerInterface $container
|
||||
* @return ContainerInterface
|
||||
*/
|
||||
protected function container(ContainerInterface $container)
|
||||
{
|
||||
if ($container instanceof ServiceLocatorAwareInterface) {
|
||||
$container = $container->getServiceLocator();
|
||||
}
|
||||
|
||||
return $container;
|
||||
}
|
||||
|
||||
public function createService(ServiceLocatorInterface $serviceLocator)
|
||||
{
|
||||
return $this($serviceLocator, $this->validatorClass, $this->creationOptions);
|
||||
}
|
||||
|
||||
public function setCreationOptions(array $options)
|
||||
{
|
||||
$this->creationOptions = $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service\Exception;
|
||||
|
||||
use RuntimeException as BaseRuntimeException;
|
||||
|
||||
/**
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class ServiceCreationException extends BaseRuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\NoObjectExists;
|
||||
|
||||
/**
|
||||
* Factory for creating NoObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class NoObjectExistsFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = NoObjectExists::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$repository = $this->getRepository($container, $options);
|
||||
|
||||
$validator = new NoObjectExists($this->merge($options, [
|
||||
'object_repository' => $repository,
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\ObjectExists;
|
||||
|
||||
/**
|
||||
* Factory for creating ObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class ObjectExistsFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = ObjectExists::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$repository = $this->getRepository($container, $options);
|
||||
|
||||
$validator = new ObjectExists($this->merge($options, [
|
||||
'object_repository' => $repository,
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\UniqueObject;
|
||||
|
||||
class UniqueObjectFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = UniqueObject::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$useContext = isset($options['use_context']) ? (boolean) $options['use_context'] : false;
|
||||
|
||||
$validator = new UniqueObject($this->merge($options, [
|
||||
'object_manager' => $this->getObjectManager($container, $options),
|
||||
'use_context' => $useContext,
|
||||
'object_repository' => $this->getRepository($container, $options),
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
166
src/DoctrineExpressiveModule/Validator/UniqueObject.php
Normal file
166
src/DoctrineExpressiveModule/Validator/UniqueObject.php
Normal file
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
/**
|
||||
* Class that validates if objects exist in a given repository with a given list of matched fields only once.
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @author Oskar Bley <oskar@programming-php.net>
|
||||
*/
|
||||
class UniqueObject extends ObjectExists
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_OBJECT_NOT_UNIQUE = 'objectNotUnique';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_OBJECT_NOT_UNIQUE => "There is already another object matching '%value%'",
|
||||
];
|
||||
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $useContext;
|
||||
|
||||
/***
|
||||
* Constructor
|
||||
*
|
||||
* @param array $options required keys are `object_repository`, which must be an instance of
|
||||
* Doctrine\Common\Persistence\ObjectRepository, `object_manager`, which
|
||||
* must be an instance of Doctrine\Common\Persistence\ObjectManager,
|
||||
* and `fields`, with either a string or an array of strings representing
|
||||
* the fields to be matched by the validator.
|
||||
* @throws Exception\InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $options)
|
||||
{
|
||||
parent::__construct($options);
|
||||
|
||||
if (! isset($options['object_manager']) || ! $options['object_manager'] instanceof ObjectManager) {
|
||||
if (! array_key_exists('object_manager', $options)) {
|
||||
$provided = 'nothing';
|
||||
} else {
|
||||
if (is_object($options['object_manager'])) {
|
||||
$provided = get_class($options['object_manager']);
|
||||
} else {
|
||||
$provided = getType($options['object_manager']);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf(
|
||||
'Option "object_manager" is required and must be an instance of'
|
||||
. ' Doctrine\Common\Persistence\ObjectManager, %s given',
|
||||
$provided
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$this->objectManager = $options['object_manager'];
|
||||
$this->useContext = isset($options['use_context']) ? (boolean) $options['use_context'] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns false if there is another object with the same field values but other identifiers.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param array $context
|
||||
* @return boolean
|
||||
*/
|
||||
public function isValid($value, $context = null)
|
||||
{
|
||||
if (! $this->useContext) {
|
||||
$context = (array) $value;
|
||||
}
|
||||
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (! is_object($match)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$expectedIdentifiers = $this->getExpectedIdentifiers($context);
|
||||
$foundIdentifiers = $this->getFoundIdentifiers($match);
|
||||
|
||||
if (count(array_diff_assoc($expectedIdentifiers, $foundIdentifiers)) == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->error(self::ERROR_OBJECT_NOT_UNIQUE, $value);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the identifiers from the matched object.
|
||||
*
|
||||
* @param object $match
|
||||
* @return array
|
||||
* @throws Exception\RuntimeException
|
||||
*/
|
||||
protected function getFoundIdentifiers($match)
|
||||
{
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierValues($match);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the identifiers from the context.
|
||||
*
|
||||
* @param array|object $context
|
||||
* @return array
|
||||
* @throws Exception\RuntimeException
|
||||
*/
|
||||
protected function getExpectedIdentifiers($context = null)
|
||||
{
|
||||
if ($context === null) {
|
||||
throw new Exception\RuntimeException(
|
||||
'Expected context to be an array but is null'
|
||||
);
|
||||
}
|
||||
|
||||
$className = $this->objectRepository->getClassName();
|
||||
|
||||
if ($context instanceof $className) {
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierValues($context);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($this->getIdentifiers() as $identifierField) {
|
||||
if (! array_key_exists($identifierField, $context)) {
|
||||
throw new Exception\RuntimeException(\sprintf('Expected context to contain %s', $identifierField));
|
||||
}
|
||||
|
||||
$result[$identifierField] = $context[$identifierField];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array the names of the identifiers
|
||||
*/
|
||||
protected function getIdentifiers()
|
||||
{
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierFieldNames();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user