zend-blog-3-backend

Форк
0
/
BaseController.php 
186 строк · 4.8 Кб
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: morontt
5
 * Date: 16.11.14
6
 * Time: 17:43
7
 */
8

9
namespace App\Controller;
10

11
use App\API\DataConverter;
12
use Doctrine\ORM\EntityManager;
13
use Doctrine\ORM\EntityManagerInterface;
14
use Knp\Component\Pager\Pagination\PaginationInterface;
15
use Knp\Component\Pager\Pagination\SlidingPagination;
16
use Knp\Component\Pager\Paginator;
17
use Knp\Component\Pager\PaginatorInterface;
18
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
19
use Symfony\Component\Form\Extension\Core\Type\FormType;
20
use Symfony\Component\Form\FormInterface;
21
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
22
use Symfony\Component\Validator\ConstraintViolationInterface;
23
use Symfony\Component\Validator\Validator\ValidatorInterface;
24

25
class BaseController extends AbstractController
26
{
27
    /**
28
     * @var EntityManagerInterface
29
     */
30
    protected EntityManagerInterface $em;
31

32
    /**
33
     * @var PaginatorInterface
34
     */
35
    protected PaginatorInterface $paginator;
36

37
    /**
38
     * @var DataConverter
39
     */
40
    protected DataConverter $apiDataConverter;
41

42
    protected array $errorsPathMap = [];
43

44
    /**
45
     * @param EntityManagerInterface $em
46
     * @param PaginatorInterface $paginator
47
     * @param DataConverter $apiDataConverter
48
     */
49
    public function __construct(
50
        EntityManagerInterface $em,
51
        PaginatorInterface $paginator,
52
        DataConverter $apiDataConverter
53
    ) {
54
        $this->em = $em;
55
        $this->paginator = $paginator;
56
        $this->apiDataConverter = $apiDataConverter;
57
    }
58

59
    /**
60
     * @return EntityManager
61
     */
62
    public function getEm(): EntityManagerInterface
63
    {
64
        return $this->em;
65
    }
66

67
    /**
68
     * @return DataConverter
69
     */
70
    public function getDataConverter(): DataConverter
71
    {
72
        return $this->apiDataConverter;
73
    }
74

75
    /**
76
     * @return Paginator
77
     */
78
    public function getPaginator(): PaginatorInterface
79
    {
80
        return $this->paginator;
81
    }
82

83
    /**
84
     * @param $query
85
     * @param $page
86
     * @param int $limit
87
     *
88
     * @return SlidingPagination
89
     */
90
    public function paginate($query, $page, int $limit = 15): PaginationInterface
91
    {
92
        return $this->getPaginator()
93
            ->paginate($query, (int)$page, $limit);
94
    }
95

96
    /**
97
     * @param array $data
98
     *
99
     * @return array
100
     */
101
    public function getPaginationMetadata(array $data): array
102
    {
103
        return [
104
            'last' => $data['last'],
105
            'current' => $data['current'],
106
            'previous' => $data['previous'] ?? false,
107
            'next' => $data['next'] ?? false,
108
        ];
109
    }
110

111
    /**
112
     * @param FormInterface $form
113
     *
114
     * @return array
115
     */
116
    protected function handleForm(FormInterface $form): array
117
    {
118
        if ($form->isSubmitted()) {
119
            if ($form->isValid()) {
120
                $formData = $form->getData();
121
            } else {
122
                $errors = ['errors' => []];
123
                /* @var \Symfony\Component\Form\FormError $formError */
124
                foreach ($form->getErrors(true) as $formError) {
125
                    $errors['errors'][] = [
126
                        'message' => $formError->getMessage(),
127
                        'path' => $this->fixErrorPath($formError->getCause()->getPropertyPath()),
128
                    ];
129
                }
130

131
                return [null, $errors];
132
            }
133
        } else {
134
            throw new BadRequestHttpException('Form not submitted');
135
        }
136

137
        return [$formData, null];
138
    }
139

140
    /**
141
     * @param $child
142
     * @param $type
143
     * @param bool $put
144
     *
145
     * @throws \Psr\Container\ContainerExceptionInterface
146
     * @throws \Psr\Container\NotFoundExceptionInterface
147
     *
148
     * @return FormInterface
149
     */
150
    protected function createObjectForm($child, $type, bool $put = false): FormInterface
151
    {
152
        $fb = $this->container
153
            ->get('form.factory')
154
            ->createNamedBuilder('', FormType::class, null, [
155
                'csrf_protection' => false,
156
                'method' => $put ? 'PUT' : 'POST',
157
            ]);
158

159
        $fb->add($child, $type);
160

161
        return $fb->getForm();
162
    }
163

164
    protected function validate(ValidatorInterface $validator, object $entity): array
165
    {
166
        $errors = [];
167
        $violations = $validator->validate($entity);
168
        if (count($violations) > 0) {
169
            $errors = ['errors' => []];
170
            /* @var ConstraintViolationInterface $violation */
171
            foreach ($violations as $violation) {
172
                $errors['errors'][] = [
173
                    'message' => $violation->getMessage(),
174
                    'path' => $this->fixErrorPath($violation->getPropertyPath()),
175
                ];
176
            }
177
        }
178

179
        return $errors;
180
    }
181

182
    private function fixErrorPath(string $path): string
183
    {
184
        return $this->errorsPathMap[$path] ?? 'unknown';
185
    }
186
}
187

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.