/
PageHandler.php
123 lines (107 loc) · 2.89 KB
/
PageHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php
namespace Acme\BlogBundle\Handler;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\FormFactoryInterface;
use Acme\BlogBundle\Model\PageInterface;
use Acme\BlogBundle\Form\PageType;
use Acme\BlogBundle\Exception\InvalidFormException;
class PageHandler implements PageHandlerInterface
{
private $om;
private $entityClass;
private $repository;
private $formFactory;
public function __construct(ObjectManager $om, $entityClass, FormFactoryInterface $formFactory)
{
$this->om = $om;
$this->entityClass = $entityClass;
$this->repository = $this->om->getRepository($this->entityClass);
$this->formFactory = $formFactory;
}
/**
* Get a Page.
*
* @param mixed $id
*
* @return PageInterface
*/
public function get($id)
{
return $this->repository->find($id);
}
/**
* Get a list of Pages.
*
* @param int $limit the limit of the result
* @param int $offset starting from the offset
*
* @return array
*/
public function all($limit = 5, $offset = 0)
{
return $this->repository->findBy(array(), null, $limit, $offset);
}
/**
* Create a new Page.
*
* @param array $parameters
*
* @return PageInterface
*/
public function post(array $parameters)
{
$page = $this->createPage();
return $this->processForm($page, $parameters, 'POST');
}
/**
* Edit a Page.
*
* @param PageInterface $page
* @param array $parameters
*
* @return PageInterface
*/
public function put(PageInterface $page, array $parameters)
{
return $this->processForm($page, $parameters, 'PUT');
}
/**
* Partially update a Page.
*
* @param PageInterface $page
* @param array $parameters
*
* @return PageInterface
*/
public function patch(PageInterface $page, array $parameters)
{
return $this->processForm($page, $parameters, 'PATCH');
}
/**
* Processes the form.
*
* @param PageInterface $page
* @param array $parameters
* @param String $method
*
* @return PageInterface
*
* @throws \Acme\BlogBundle\Exception\InvalidFormException
*/
private function processForm(PageInterface $page, array $parameters, $method = "PUT")
{
$form = $this->formFactory->create(new PageType(), $page, array('method' => $method));
$form->submit($parameters, 'PATCH' !== $method);
if ($form->isValid()) {
$page = $form->getData();
$this->om->persist($page);
$this->om->flush($page);
return $page;
}
throw new InvalidFormException('Invalid submitted data', $form);
}
private function createPage()
{
return new $this->entityClass();
}
}