Complex classes like CRUDController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use CRUDController, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 58 | class CRUDController implements ContainerAwareInterface |
||
| 59 | { |
||
| 60 | // NEXT_MAJOR: Don't use these traits anymore (inherit from Controller instead) |
||
| 61 | use ControllerTrait, ContainerAwareTrait { |
||
| 62 | ControllerTrait::render as originalRender; |
||
| 63 | } |
||
| 64 | |||
| 65 | /** |
||
| 66 | * The related Admin class. |
||
| 67 | * |
||
| 68 | * @var AdminInterface |
||
| 69 | */ |
||
| 70 | protected $admin; |
||
| 71 | |||
| 72 | /** |
||
| 73 | * The template registry of the related Admin class. |
||
| 74 | * |
||
| 75 | * @var TemplateRegistryInterface |
||
| 76 | */ |
||
| 77 | private $templateRegistry; |
||
| 78 | |||
| 79 | // BC for Symfony 3.3 where ControllerTrait exists but does not contain get() and has() methods. |
||
| 80 | public function __call($method, $arguments) |
||
| 81 | { |
||
| 82 | if (\in_array($method, ['get', 'has'], true)) { |
||
| 83 | return $this->container->{$method}(...$arguments); |
||
| 84 | } |
||
| 85 | |||
| 86 | if (method_exists($this, 'proxyToControllerClass')) { |
||
| 87 | return $this->proxyToControllerClass($method, $arguments); |
||
|
|
|||
| 88 | } |
||
| 89 | |||
| 90 | throw new \LogicException('Call to undefined method '.__CLASS__.'::'.$method); |
||
| 91 | } |
||
| 92 | |||
| 93 | public function setContainer(ContainerInterface $container = null) |
||
| 94 | { |
||
| 95 | $this->container = $container; |
||
| 96 | |||
| 97 | $this->configure(); |
||
| 98 | } |
||
| 99 | |||
| 100 | /** |
||
| 101 | * NEXT_MAJOR: Remove this method. |
||
| 102 | * |
||
| 103 | * @see renderWithExtraParams() |
||
| 104 | * |
||
| 105 | * @param string $view The view name |
||
| 106 | * @param array $parameters An array of parameters to pass to the view |
||
| 107 | * |
||
| 108 | * @return Response A Response instance |
||
| 109 | * |
||
| 110 | * @deprecated since version 3.27, to be removed in 4.0. Use Sonata\AdminBundle\Controller\CRUDController::renderWithExtraParams() instead. |
||
| 111 | */ |
||
| 112 | public function render($view, array $parameters = [], Response $response = null) |
||
| 113 | { |
||
| 114 | @trigger_error( |
||
| 115 | 'Method '.__CLASS__.'::render has been renamed to '.__CLASS__.'::renderWithExtraParams.', |
||
| 116 | E_USER_DEPRECATED |
||
| 117 | ); |
||
| 118 | |||
| 119 | return $this->renderWithExtraParams($view, $parameters, $response); |
||
| 120 | } |
||
| 121 | |||
| 122 | /** |
||
| 123 | * Renders a view while passing mandatory parameters on to the template. |
||
| 124 | * |
||
| 125 | * @param string $view The view name |
||
| 126 | * |
||
| 127 | * @return Response A Response instance |
||
| 128 | */ |
||
| 129 | public function renderWithExtraParams($view, array $parameters = [], Response $response = null) |
||
| 130 | { |
||
| 131 | if (!$this->isXmlHttpRequest()) { |
||
| 132 | $parameters['breadcrumbs_builder'] = $this->get('sonata.admin.breadcrumbs_builder'); |
||
| 133 | } |
||
| 134 | $parameters['admin'] = $parameters['admin'] ?? |
||
| 135 | $this->admin; |
||
| 136 | |||
| 137 | $parameters['base_template'] = $parameters['base_template'] ?? |
||
| 138 | $this->getBaseTemplate(); |
||
| 139 | |||
| 140 | $parameters['admin_pool'] = $this->get('sonata.admin.pool'); |
||
| 141 | |||
| 142 | //NEXT_MAJOR: Remove method alias and use $this->render() directly. |
||
| 143 | return $this->originalRender($view, $parameters, $response); |
||
| 144 | } |
||
| 145 | |||
| 146 | /** |
||
| 147 | * List action. |
||
| 148 | * |
||
| 149 | * @throws AccessDeniedException If access is not granted |
||
| 150 | * |
||
| 151 | * @return Response |
||
| 152 | */ |
||
| 153 | public function listAction() |
||
| 154 | { |
||
| 155 | $request = $this->getRequest(); |
||
| 156 | |||
| 157 | $this->admin->checkAccess('list'); |
||
| 158 | |||
| 159 | $preResponse = $this->preList($request); |
||
| 160 | if (null !== $preResponse) { |
||
| 161 | return $preResponse; |
||
| 162 | } |
||
| 163 | |||
| 164 | if ($listMode = $request->get('_list_mode')) { |
||
| 165 | $this->admin->setListMode($listMode); |
||
| 166 | } |
||
| 167 | |||
| 168 | $datagrid = $this->admin->getDatagrid(); |
||
| 169 | $formView = $datagrid->getForm()->createView(); |
||
| 170 | |||
| 171 | // set the theme for the current Admin Form |
||
| 172 | $this->setFormTheme($formView, $this->admin->getFilterTheme()); |
||
| 173 | |||
| 174 | // NEXT_MAJOR: Remove this line and use commented line below it instead |
||
| 175 | $template = $this->admin->getTemplate('list'); |
||
| 176 | // $template = $this->templateRegistry->getTemplate('list'); |
||
| 177 | |||
| 178 | return $this->renderWithExtraParams($template, [ |
||
| 179 | 'action' => 'list', |
||
| 180 | 'form' => $formView, |
||
| 181 | 'datagrid' => $datagrid, |
||
| 182 | 'csrf_token' => $this->getCsrfToken('sonata.batch'), |
||
| 183 | 'export_formats' => $this->has('sonata.admin.admin_exporter') ? |
||
| 184 | $this->get('sonata.admin.admin_exporter')->getAvailableFormats($this->admin) : |
||
| 185 | $this->admin->getExportFormats(), |
||
| 186 | ], null); |
||
| 187 | } |
||
| 188 | |||
| 189 | /** |
||
| 190 | * Execute a batch delete. |
||
| 191 | * |
||
| 192 | * @throws AccessDeniedException If access is not granted |
||
| 193 | * |
||
| 194 | * @return RedirectResponse |
||
| 195 | */ |
||
| 196 | public function batchActionDelete(ProxyQueryInterface $query) |
||
| 197 | { |
||
| 198 | $this->admin->checkAccess('batchDelete'); |
||
| 199 | |||
| 200 | $modelManager = $this->admin->getModelManager(); |
||
| 201 | |||
| 202 | try { |
||
| 203 | $modelManager->batchDelete($this->admin->getClass(), $query); |
||
| 204 | $this->addFlash( |
||
| 205 | 'sonata_flash_success', |
||
| 206 | $this->trans('flash_batch_delete_success', [], 'SonataAdminBundle') |
||
| 207 | ); |
||
| 208 | } catch (ModelManagerException $e) { |
||
| 209 | $this->handleModelManagerException($e); |
||
| 210 | $this->addFlash( |
||
| 211 | 'sonata_flash_error', |
||
| 212 | $this->trans('flash_batch_delete_error', [], 'SonataAdminBundle') |
||
| 213 | ); |
||
| 214 | } |
||
| 215 | |||
| 216 | return $this->redirectToList(); |
||
| 217 | } |
||
| 218 | |||
| 219 | /** |
||
| 220 | * Delete action. |
||
| 221 | * |
||
| 222 | * @param int|string|null $id |
||
| 223 | * |
||
| 224 | * @throws NotFoundHttpException If the object does not exist |
||
| 225 | * @throws AccessDeniedException If access is not granted |
||
| 226 | * |
||
| 227 | * @return Response|RedirectResponse |
||
| 228 | */ |
||
| 229 | public function deleteAction($id) |
||
| 230 | { |
||
| 231 | $request = $this->getRequest(); |
||
| 232 | $id = $request->get($this->admin->getIdParameter()); |
||
| 233 | $object = $this->admin->getObject($id); |
||
| 234 | |||
| 235 | if (!$object) { |
||
| 236 | throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id)); |
||
| 237 | } |
||
| 238 | |||
| 239 | $this->checkParentChildAssociation($request, $object); |
||
| 240 | |||
| 241 | $this->admin->checkAccess('delete', $object); |
||
| 242 | |||
| 243 | $preResponse = $this->preDelete($request, $object); |
||
| 244 | if (null !== $preResponse) { |
||
| 245 | return $preResponse; |
||
| 246 | } |
||
| 247 | |||
| 248 | if ('DELETE' === $this->getRestMethod()) { |
||
| 249 | // check the csrf token |
||
| 250 | $this->validateCsrfToken('sonata.delete'); |
||
| 251 | |||
| 252 | $objectName = $this->admin->toString($object); |
||
| 253 | |||
| 254 | try { |
||
| 255 | $this->admin->delete($object); |
||
| 256 | |||
| 257 | if ($this->isXmlHttpRequest()) { |
||
| 258 | return $this->renderJson(['result' => 'ok'], 200, []); |
||
| 259 | } |
||
| 260 | |||
| 261 | $this->addFlash( |
||
| 262 | 'sonata_flash_success', |
||
| 263 | $this->trans( |
||
| 264 | 'flash_delete_success', |
||
| 265 | ['%name%' => $this->escapeHtml($objectName)], |
||
| 266 | 'SonataAdminBundle' |
||
| 267 | ) |
||
| 268 | ); |
||
| 269 | } catch (ModelManagerException $e) { |
||
| 270 | $this->handleModelManagerException($e); |
||
| 271 | |||
| 272 | if ($this->isXmlHttpRequest()) { |
||
| 273 | return $this->renderJson(['result' => 'error'], 200, []); |
||
| 274 | } |
||
| 275 | |||
| 276 | $this->addFlash( |
||
| 277 | 'sonata_flash_error', |
||
| 278 | $this->trans( |
||
| 279 | 'flash_delete_error', |
||
| 280 | ['%name%' => $this->escapeHtml($objectName)], |
||
| 281 | 'SonataAdminBundle' |
||
| 282 | ) |
||
| 283 | ); |
||
| 284 | } |
||
| 285 | |||
| 286 | return $this->redirectTo($object); |
||
| 287 | } |
||
| 288 | |||
| 289 | // NEXT_MAJOR: Remove this line and use commented line below it instead |
||
| 290 | $template = $this->admin->getTemplate('delete'); |
||
| 291 | // $template = $this->templateRegistry->getTemplate('delete'); |
||
| 292 | |||
| 293 | return $this->renderWithExtraParams($template, [ |
||
| 294 | 'object' => $object, |
||
| 295 | 'action' => 'delete', |
||
| 296 | 'csrf_token' => $this->getCsrfToken('sonata.delete'), |
||
| 297 | ], null); |
||
| 298 | } |
||
| 299 | |||
| 300 | /** |
||
| 301 | * Edit action. |
||
| 302 | * |
||
| 303 | * @param int|string|null $id |
||
| 304 | * |
||
| 305 | * @throws NotFoundHttpException If the object does not exist |
||
| 306 | * @throws \RuntimeException If no editable field is defined |
||
| 307 | * @throws AccessDeniedException If access is not granted |
||
| 308 | * |
||
| 309 | * @return Response|RedirectResponse |
||
| 310 | */ |
||
| 311 | public function editAction($id = null) |
||
| 312 | { |
||
| 313 | $request = $this->getRequest(); |
||
| 314 | // the key used to lookup the template |
||
| 315 | $templateKey = 'edit'; |
||
| 316 | |||
| 317 | $id = $request->get($this->admin->getIdParameter()); |
||
| 318 | $existingObject = $this->admin->getObject($id); |
||
| 319 | |||
| 320 | if (!$existingObject) { |
||
| 321 | throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id)); |
||
| 322 | } |
||
| 323 | |||
| 324 | $this->checkParentChildAssociation($request, $existingObject); |
||
| 325 | |||
| 326 | $this->admin->checkAccess('edit', $existingObject); |
||
| 327 | |||
| 328 | $preResponse = $this->preEdit($request, $existingObject); |
||
| 329 | if (null !== $preResponse) { |
||
| 330 | return $preResponse; |
||
| 331 | } |
||
| 332 | |||
| 333 | $this->admin->setSubject($existingObject); |
||
| 334 | $objectId = $this->admin->getNormalizedIdentifier($existingObject); |
||
| 335 | |||
| 336 | $form = $this->admin->getForm(); |
||
| 337 | |||
| 338 | if (!\is_array($fields = $form->all()) || 0 === \count($fields)) { |
||
| 339 | throw new \RuntimeException( |
||
| 340 | 'No editable field defined. Did you forget to implement the "configureFormFields" method?' |
||
| 341 | ); |
||
| 342 | } |
||
| 343 | |||
| 344 | $form->setData($existingObject); |
||
| 345 | $form->handleRequest($request); |
||
| 346 | |||
| 347 | if ($form->isSubmitted()) { |
||
| 348 | $isFormValid = $form->isValid(); |
||
| 349 | |||
| 350 | // persist if the form was valid and if in preview mode the preview was approved |
||
| 351 | if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) { |
||
| 352 | $submittedObject = $form->getData(); |
||
| 353 | $this->admin->setSubject($submittedObject); |
||
| 354 | |||
| 355 | try { |
||
| 356 | $existingObject = $this->admin->update($submittedObject); |
||
| 357 | |||
| 358 | if ($this->isXmlHttpRequest()) { |
||
| 359 | return $this->handleXmlHttpRequestSuccessResponse($request, $existingObject); |
||
| 360 | } |
||
| 361 | |||
| 362 | $this->addFlash( |
||
| 363 | 'sonata_flash_success', |
||
| 364 | $this->trans( |
||
| 365 | 'flash_edit_success', |
||
| 366 | ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))], |
||
| 367 | 'SonataAdminBundle' |
||
| 368 | ) |
||
| 369 | ); |
||
| 370 | |||
| 371 | // redirect to edit mode |
||
| 372 | return $this->redirectTo($existingObject); |
||
| 373 | } catch (ModelManagerException $e) { |
||
| 374 | $this->handleModelManagerException($e); |
||
| 375 | |||
| 376 | $isFormValid = false; |
||
| 377 | } catch (LockException $e) { |
||
| 378 | $this->addFlash('sonata_flash_error', $this->trans('flash_lock_error', [ |
||
| 379 | '%name%' => $this->escapeHtml($this->admin->toString($existingObject)), |
||
| 380 | '%link_start%' => '<a href="'.$this->admin->generateObjectUrl('edit', $existingObject).'">', |
||
| 381 | '%link_end%' => '</a>', |
||
| 382 | ], 'SonataAdminBundle')); |
||
| 383 | } |
||
| 384 | } |
||
| 385 | |||
| 386 | // show an error message if the form failed validation |
||
| 387 | if (!$isFormValid) { |
||
| 388 | if ($this->isXmlHttpRequest() && null !== ($response = $this->handleXmlHttpRequestErrorResponse($request, $form))) { |
||
| 389 | return $response; |
||
| 390 | } |
||
| 391 | |||
| 392 | $this->addFlash( |
||
| 393 | 'sonata_flash_error', |
||
| 394 | $this->trans( |
||
| 395 | 'flash_edit_error', |
||
| 396 | ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))], |
||
| 397 | 'SonataAdminBundle' |
||
| 398 | ) |
||
| 399 | ); |
||
| 400 | } elseif ($this->isPreviewRequested()) { |
||
| 401 | // enable the preview template if the form was valid and preview was requested |
||
| 402 | $templateKey = 'preview'; |
||
| 403 | $this->admin->getShow(); |
||
| 404 | } |
||
| 405 | } |
||
| 406 | |||
| 407 | $formView = $form->createView(); |
||
| 408 | // set the theme for the current Admin Form |
||
| 409 | $this->setFormTheme($formView, $this->admin->getFormTheme()); |
||
| 410 | |||
| 411 | // NEXT_MAJOR: Remove this line and use commented line below it instead |
||
| 412 | $template = $this->admin->getTemplate($templateKey); |
||
| 413 | // $template = $this->templateRegistry->getTemplate($templateKey); |
||
| 414 | |||
| 415 | return $this->renderWithExtraParams($template, [ |
||
| 416 | 'action' => 'edit', |
||
| 417 | 'form' => $formView, |
||
| 418 | 'object' => $existingObject, |
||
| 419 | 'objectId' => $objectId, |
||
| 420 | ], null); |
||
| 421 | } |
||
| 422 | |||
| 423 | /** |
||
| 424 | * Batch action. |
||
| 425 | * |
||
| 426 | * @throws NotFoundHttpException If the HTTP method is not POST |
||
| 427 | * @throws \RuntimeException If the batch action is not defined |
||
| 428 | * |
||
| 429 | * @return Response|RedirectResponse |
||
| 430 | */ |
||
| 431 | public function batchAction() |
||
| 432 | { |
||
| 433 | $request = $this->getRequest(); |
||
| 434 | $restMethod = $this->getRestMethod(); |
||
| 435 | |||
| 436 | if ('POST' !== $restMethod) { |
||
| 437 | throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod)); |
||
| 438 | } |
||
| 439 | |||
| 440 | // check the csrf token |
||
| 441 | $this->validateCsrfToken('sonata.batch'); |
||
| 442 | |||
| 443 | $confirmation = $request->get('confirmation', false); |
||
| 444 | |||
| 445 | if ($data = json_decode((string) $request->get('data'), true)) { |
||
| 446 | $action = $data['action']; |
||
| 447 | $idx = $data['idx']; |
||
| 448 | $allElements = $data['all_elements']; |
||
| 449 | $request->request->replace(array_merge($request->request->all(), $data)); |
||
| 450 | } else { |
||
| 451 | $request->request->set('idx', $request->get('idx', [])); |
||
| 452 | $request->request->set('all_elements', $request->get('all_elements', false)); |
||
| 453 | |||
| 454 | $action = $request->get('action'); |
||
| 455 | $idx = $request->get('idx'); |
||
| 456 | $allElements = $request->get('all_elements'); |
||
| 457 | $data = $request->request->all(); |
||
| 458 | |||
| 459 | unset($data['_sonata_csrf_token']); |
||
| 460 | } |
||
| 461 | |||
| 462 | // NEXT_MAJOR: Remove reflection check. |
||
| 463 | $reflector = new \ReflectionMethod($this->admin, 'getBatchActions'); |
||
| 464 | if ($reflector->getDeclaringClass()->getName() === \get_class($this->admin)) { |
||
| 465 | @trigger_error('Override Sonata\AdminBundle\Admin\AbstractAdmin::getBatchActions method' |
||
| 466 | .' is deprecated since version 3.2.' |
||
| 467 | .' Use Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions instead.' |
||
| 468 | .' The method will be final in 4.0.', E_USER_DEPRECATED |
||
| 469 | ); |
||
| 470 | } |
||
| 471 | $batchActions = $this->admin->getBatchActions(); |
||
| 472 | if (!\array_key_exists($action, $batchActions)) { |
||
| 473 | throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action)); |
||
| 474 | } |
||
| 475 | |||
| 476 | $camelizedAction = Inflector::classify($action); |
||
| 477 | $isRelevantAction = sprintf('batchAction%sIsRelevant', $camelizedAction); |
||
| 478 | |||
| 479 | if (method_exists($this, $isRelevantAction)) { |
||
| 480 | $nonRelevantMessage = $this->{$isRelevantAction}($idx, $allElements, $request); |
||
| 481 | } else { |
||
| 482 | $nonRelevantMessage = 0 !== \count($idx) || $allElements; // at least one item is selected |
||
| 483 | } |
||
| 484 | |||
| 485 | if (!$nonRelevantMessage) { // default non relevant message (if false of null) |
||
| 486 | $nonRelevantMessage = 'flash_batch_empty'; |
||
| 487 | } |
||
| 488 | |||
| 489 | $datagrid = $this->admin->getDatagrid(); |
||
| 490 | $datagrid->buildPager(); |
||
| 491 | |||
| 492 | if (true !== $nonRelevantMessage) { |
||
| 493 | $this->addFlash( |
||
| 494 | 'sonata_flash_info', |
||
| 495 | $this->trans($nonRelevantMessage, [], 'SonataAdminBundle') |
||
| 496 | ); |
||
| 497 | |||
| 498 | return $this->redirectToList(); |
||
| 499 | } |
||
| 500 | |||
| 501 | $askConfirmation = $batchActions[$action]['ask_confirmation'] ?? |
||
| 502 | true; |
||
| 503 | |||
| 504 | if ($askConfirmation && 'ok' !== $confirmation) { |
||
| 505 | $actionLabel = $batchActions[$action]['label']; |
||
| 506 | $batchTranslationDomain = $batchActions[$action]['translation_domain'] ?? |
||
| 507 | $this->admin->getTranslationDomain(); |
||
| 508 | |||
| 509 | $formView = $datagrid->getForm()->createView(); |
||
| 510 | $this->setFormTheme($formView, $this->admin->getFilterTheme()); |
||
| 511 | |||
| 512 | // NEXT_MAJOR: Remove these lines and use commented lines below them instead |
||
| 513 | $template = !empty($batchActions[$action]['template']) ? |
||
| 514 | $batchActions[$action]['template'] : |
||
| 515 | $this->admin->getTemplate('batch_confirmation'); |
||
| 516 | // $template = !empty($batchActions[$action]['template']) ? |
||
| 517 | // $batchActions[$action]['template'] : |
||
| 518 | // $this->templateRegistry->getTemplate('batch_confirmation'); |
||
| 519 | |||
| 520 | return $this->renderWithExtraParams($template, [ |
||
| 521 | 'action' => 'list', |
||
| 522 | 'action_label' => $actionLabel, |
||
| 523 | 'batch_translation_domain' => $batchTranslationDomain, |
||
| 524 | 'datagrid' => $datagrid, |
||
| 525 | 'form' => $formView, |
||
| 526 | 'data' => $data, |
||
| 527 | 'csrf_token' => $this->getCsrfToken('sonata.batch'), |
||
| 528 | ], null); |
||
| 529 | } |
||
| 530 | |||
| 531 | // execute the action, batchActionXxxxx |
||
| 532 | $finalAction = sprintf('batchAction%s', $camelizedAction); |
||
| 533 | if (!method_exists($this, $finalAction)) { |
||
| 534 | throw new \RuntimeException(sprintf('A `%s::%s` method must be callable', static::class, $finalAction)); |
||
| 535 | } |
||
| 536 | |||
| 537 | $query = $datagrid->getQuery(); |
||
| 538 | |||
| 539 | $query->setFirstResult(null); |
||
| 540 | $query->setMaxResults(null); |
||
| 541 | |||
| 542 | $this->admin->preBatchAction($action, $query, $idx, $allElements); |
||
| 543 | |||
| 544 | if (\count($idx) > 0) { |
||
| 545 | $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx); |
||
| 546 | } elseif (!$allElements) { |
||
| 547 | $this->addFlash( |
||
| 548 | 'sonata_flash_info', |
||
| 549 | $this->trans('flash_batch_no_elements_processed', [], 'SonataAdminBundle') |
||
| 550 | ); |
||
| 551 | |||
| 552 | return $this->redirectToList(); |
||
| 553 | } |
||
| 554 | |||
| 555 | return $this->{$finalAction}($query, $request); |
||
| 556 | } |
||
| 557 | |||
| 558 | /** |
||
| 559 | * Create action. |
||
| 560 | * |
||
| 561 | * @throws AccessDeniedException If access is not granted |
||
| 562 | * @throws \RuntimeException If no editable field is defined |
||
| 563 | * |
||
| 564 | * @return Response |
||
| 565 | */ |
||
| 566 | public function createAction() |
||
| 567 | { |
||
| 568 | $request = $this->getRequest(); |
||
| 569 | // the key used to lookup the template |
||
| 570 | $templateKey = 'edit'; |
||
| 571 | |||
| 572 | $this->admin->checkAccess('create'); |
||
| 573 | |||
| 574 | $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass()); |
||
| 575 | |||
| 576 | if ($class->isAbstract()) { |
||
| 577 | return $this->renderWithExtraParams( |
||
| 578 | '@SonataAdmin/CRUD/select_subclass.html.twig', |
||
| 579 | [ |
||
| 580 | 'base_template' => $this->getBaseTemplate(), |
||
| 581 | 'admin' => $this->admin, |
||
| 582 | 'action' => 'create', |
||
| 583 | ], |
||
| 584 | null |
||
| 585 | ); |
||
| 586 | } |
||
| 587 | |||
| 588 | $newObject = $this->admin->getNewInstance(); |
||
| 589 | |||
| 590 | $preResponse = $this->preCreate($request, $newObject); |
||
| 591 | if (null !== $preResponse) { |
||
| 592 | return $preResponse; |
||
| 593 | } |
||
| 594 | |||
| 595 | $this->admin->setSubject($newObject); |
||
| 596 | |||
| 597 | $form = $this->admin->getForm(); |
||
| 598 | |||
| 599 | if (!\is_array($fields = $form->all()) || 0 === \count($fields)) { |
||
| 600 | throw new \RuntimeException( |
||
| 601 | 'No editable field defined. Did you forget to implement the "configureFormFields" method?' |
||
| 602 | ); |
||
| 603 | } |
||
| 604 | |||
| 605 | $form->setData($newObject); |
||
| 606 | $form->handleRequest($request); |
||
| 607 | |||
| 608 | if ($form->isSubmitted()) { |
||
| 609 | $isFormValid = $form->isValid(); |
||
| 610 | |||
| 611 | // persist if the form was valid and if in preview mode the preview was approved |
||
| 612 | if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) { |
||
| 613 | $submittedObject = $form->getData(); |
||
| 614 | $this->admin->setSubject($submittedObject); |
||
| 615 | $this->admin->checkAccess('create', $submittedObject); |
||
| 616 | |||
| 617 | try { |
||
| 618 | $newObject = $this->admin->create($submittedObject); |
||
| 619 | |||
| 620 | if ($this->isXmlHttpRequest()) { |
||
| 621 | return $this->handleXmlHttpRequestSuccessResponse($request, $newObject); |
||
| 622 | } |
||
| 623 | |||
| 624 | $this->addFlash( |
||
| 625 | 'sonata_flash_success', |
||
| 626 | $this->trans( |
||
| 627 | 'flash_create_success', |
||
| 628 | ['%name%' => $this->escapeHtml($this->admin->toString($newObject))], |
||
| 629 | 'SonataAdminBundle' |
||
| 630 | ) |
||
| 631 | ); |
||
| 632 | |||
| 633 | // redirect to edit mode |
||
| 634 | return $this->redirectTo($newObject); |
||
| 635 | } catch (ModelManagerException $e) { |
||
| 636 | $this->handleModelManagerException($e); |
||
| 637 | |||
| 638 | $isFormValid = false; |
||
| 639 | } |
||
| 640 | } |
||
| 641 | |||
| 642 | // show an error message if the form failed validation |
||
| 643 | if (!$isFormValid) { |
||
| 644 | if ($this->isXmlHttpRequest() && null !== ($response = $this->handleXmlHttpRequestErrorResponse($request, $form))) { |
||
| 645 | return $response; |
||
| 646 | } |
||
| 647 | |||
| 648 | $this->addFlash( |
||
| 649 | 'sonata_flash_error', |
||
| 650 | $this->trans( |
||
| 651 | 'flash_create_error', |
||
| 652 | ['%name%' => $this->escapeHtml($this->admin->toString($newObject))], |
||
| 653 | 'SonataAdminBundle' |
||
| 654 | ) |
||
| 655 | ); |
||
| 656 | } elseif ($this->isPreviewRequested()) { |
||
| 657 | // pick the preview template if the form was valid and preview was requested |
||
| 658 | $templateKey = 'preview'; |
||
| 659 | $this->admin->getShow(); |
||
| 660 | } |
||
| 661 | } |
||
| 662 | |||
| 663 | $formView = $form->createView(); |
||
| 664 | // set the theme for the current Admin Form |
||
| 665 | $this->setFormTheme($formView, $this->admin->getFormTheme()); |
||
| 666 | |||
| 667 | // NEXT_MAJOR: Remove this line and use commented line below it instead |
||
| 668 | $template = $this->admin->getTemplate($templateKey); |
||
| 669 | // $template = $this->templateRegistry->getTemplate($templateKey); |
||
| 670 | |||
| 671 | return $this->renderWithExtraParams($template, [ |
||
| 672 | 'action' => 'create', |
||
| 673 | 'form' => $formView, |
||
| 674 | 'object' => $newObject, |
||
| 675 | 'objectId' => null, |
||
| 676 | ], null); |
||
| 677 | } |
||
| 678 | |||
| 679 | /** |
||
| 680 | * Show action. |
||
| 681 | * |
||
| 682 | * @param int|string|null $id |
||
| 683 | * |
||
| 684 | * @throws NotFoundHttpException If the object does not exist |
||
| 685 | * @throws AccessDeniedException If access is not granted |
||
| 686 | * |
||
| 687 | * @return Response |
||
| 688 | */ |
||
| 689 | public function showAction($id = null) |
||
| 690 | { |
||
| 691 | $request = $this->getRequest(); |
||
| 692 | $id = $request->get($this->admin->getIdParameter()); |
||
| 693 | |||
| 694 | $object = $this->admin->getObject($id); |
||
| 695 | |||
| 696 | if (!$object) { |
||
| 697 | throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id)); |
||
| 698 | } |
||
| 699 | |||
| 700 | $this->checkParentChildAssociation($request, $object); |
||
| 701 | |||
| 702 | $this->admin->checkAccess('show', $object); |
||
| 703 | |||
| 704 | $preResponse = $this->preShow($request, $object); |
||
| 705 | if (null !== $preResponse) { |
||
| 706 | return $preResponse; |
||
| 707 | } |
||
| 708 | |||
| 709 | $this->admin->setSubject($object); |
||
| 710 | |||
| 711 | $fields = $this->admin->getShow(); |
||
| 712 | \assert($fields instanceof FieldDescriptionCollection); |
||
| 713 | |||
| 714 | // NEXT_MAJOR: replace deprecation with exception |
||
| 715 | if (!\is_array($fields->getElements()) || 0 === $fields->count()) { |
||
| 716 | @trigger_error( |
||
| 717 | 'Calling this method without implementing "configureShowFields"' |
||
| 718 | .' is not supported since 3.40.0' |
||
| 719 | .' and will no longer be possible in 4.0', |
||
| 720 | E_USER_DEPRECATED |
||
| 721 | ); |
||
| 722 | } |
||
| 723 | |||
| 724 | // NEXT_MAJOR: Remove this line and use commented line below it instead |
||
| 725 | $template = $this->admin->getTemplate('show'); |
||
| 726 | //$template = $this->templateRegistry->getTemplate('show'); |
||
| 727 | |||
| 728 | return $this->renderWithExtraParams($template, [ |
||
| 729 | 'action' => 'show', |
||
| 730 | 'object' => $object, |
||
| 731 | 'elements' => $fields, |
||
| 732 | ], null); |
||
| 733 | } |
||
| 734 | |||
| 735 | /** |
||
| 736 | * Show history revisions for object. |
||
| 737 | * |
||
| 738 | * @param int|string|null $id |
||
| 739 | * |
||
| 740 | * @throws AccessDeniedException If access is not granted |
||
| 741 | * @throws NotFoundHttpException If the object does not exist or the audit reader is not available |
||
| 742 | * |
||
| 743 | * @return Response |
||
| 744 | */ |
||
| 745 | public function historyAction($id = null) |
||
| 784 | |||
| 785 | /** |
||
| 786 | * View history revision of object. |
||
| 787 | * |
||
| 788 | * @param int|string|null $id |
||
| 789 | * @param string|null $revision |
||
| 790 | * |
||
| 791 | * @throws AccessDeniedException If access is not granted |
||
| 792 | * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available |
||
| 793 | * |
||
| 794 | * @return Response |
||
| 795 | */ |
||
| 796 | public function historyViewRevisionAction($id = null, $revision = null) |
||
| 848 | |||
| 849 | /** |
||
| 850 | * Compare history revisions of object. |
||
| 851 | * |
||
| 852 | * @param int|string|null $id |
||
| 853 | * @param int|string|null $base_revision |
||
| 854 | * @param int|string|null $compare_revision |
||
| 855 | * |
||
| 856 | * @throws AccessDeniedException If access is not granted |
||
| 857 | * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available |
||
| 858 | * |
||
| 859 | * @return Response |
||
| 860 | */ |
||
| 861 | public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null) |
||
| 927 | |||
| 928 | /** |
||
| 929 | * Export data to specified format. |
||
| 930 | * |
||
| 931 | * @throws AccessDeniedException If access is not granted |
||
| 932 | * @throws \RuntimeException If the export format is invalid |
||
| 933 | * |
||
| 934 | * @return Response |
||
| 935 | */ |
||
| 936 | public function exportAction(Request $request) |
||
| 983 | |||
| 984 | /** |
||
| 985 | * Returns the Response object associated to the acl action. |
||
| 986 | * |
||
| 987 | * @param int|string|null $id |
||
| 988 | * |
||
| 989 | * @throws AccessDeniedException If access is not granted |
||
| 990 | * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled |
||
| 991 | * |
||
| 992 | * @return Response|RedirectResponse |
||
| 993 | */ |
||
| 994 | public function aclAction($id = null) |
||
| 1066 | |||
| 1067 | /** |
||
| 1068 | * @return Request |
||
| 1069 | */ |
||
| 1070 | public function getRequest() |
||
| 1074 | |||
| 1075 | /** |
||
| 1076 | * Gets a container configuration parameter by its name. |
||
| 1077 | * |
||
| 1078 | * @param string $name The parameter name |
||
| 1079 | * |
||
| 1080 | * @return mixed |
||
| 1081 | */ |
||
| 1082 | protected function getParameter($name) |
||
| 1086 | |||
| 1087 | /** |
||
| 1088 | * Render JSON. |
||
| 1089 | * |
||
| 1090 | * @param mixed $data |
||
| 1091 | * @param int $status |
||
| 1092 | * @param array $headers |
||
| 1093 | * |
||
| 1094 | * @return JsonResponse with json encoded data |
||
| 1095 | */ |
||
| 1096 | protected function renderJson($data, $status = 200, $headers = []) |
||
| 1100 | |||
| 1101 | /** |
||
| 1102 | * Returns true if the request is a XMLHttpRequest. |
||
| 1103 | * |
||
| 1104 | * @return bool True if the request is an XMLHttpRequest, false otherwise |
||
| 1105 | */ |
||
| 1106 | protected function isXmlHttpRequest() |
||
| 1112 | |||
| 1113 | /** |
||
| 1114 | * Returns the correct RESTful verb, given either by the request itself or |
||
| 1115 | * via the "_method" parameter. |
||
| 1116 | * |
||
| 1117 | * @return string HTTP method, either |
||
| 1118 | */ |
||
| 1119 | protected function getRestMethod() |
||
| 1129 | |||
| 1130 | /** |
||
| 1131 | * Contextualize the admin class depends on the current request. |
||
| 1132 | * |
||
| 1133 | * @throws \RuntimeException |
||
| 1134 | */ |
||
| 1135 | protected function configure() |
||
| 1179 | |||
| 1180 | /** |
||
| 1181 | * Proxy for the logger service of the container. |
||
| 1182 | * If no such service is found, a NullLogger is returned. |
||
| 1183 | * |
||
| 1184 | * @return LoggerInterface |
||
| 1185 | */ |
||
| 1186 | protected function getLogger() |
||
| 1187 | { |
||
| 1188 | if ($this->container->has('logger')) { |
||
| 1189 | $logger = $this->container->get('logger'); |
||
| 1190 | \assert($logger instanceof LoggerInterface); |
||
| 1191 | |||
| 1192 | return $logger; |
||
| 1193 | } |
||
| 1194 | |||
| 1195 | return new NullLogger(); |
||
| 1196 | } |
||
| 1197 | |||
| 1198 | /** |
||
| 1199 | * Returns the base template name. |
||
| 1200 | * |
||
| 1201 | * @return string The template name |
||
| 1202 | */ |
||
| 1203 | protected function getBaseTemplate() |
||
| 1204 | { |
||
| 1205 | if ($this->isXmlHttpRequest()) { |
||
| 1206 | // NEXT_MAJOR: Remove this line and use commented line below it instead |
||
| 1207 | return $this->admin->getTemplate('ajax'); |
||
| 1208 | // return $this->templateRegistry->getTemplate('ajax'); |
||
| 1209 | } |
||
| 1210 | |||
| 1211 | // NEXT_MAJOR: Remove this line and use commented line below it instead |
||
| 1212 | return $this->admin->getTemplate('layout'); |
||
| 1213 | // return $this->templateRegistry->getTemplate('layout'); |
||
| 1214 | } |
||
| 1215 | |||
| 1216 | /** |
||
| 1217 | * @throws \Exception |
||
| 1218 | */ |
||
| 1219 | protected function handleModelManagerException(\Exception $e) |
||
| 1220 | { |
||
| 1221 | if ($this->get('kernel')->isDebug()) { |
||
| 1222 | throw $e; |
||
| 1223 | } |
||
| 1224 | |||
| 1225 | $context = ['exception' => $e]; |
||
| 1226 | if ($e->getPrevious()) { |
||
| 1227 | $context['previous_exception_message'] = $e->getPrevious()->getMessage(); |
||
| 1228 | } |
||
| 1229 | $this->getLogger()->error($e->getMessage(), $context); |
||
| 1230 | } |
||
| 1231 | |||
| 1232 | /** |
||
| 1233 | * Redirect the user depend on this choice. |
||
| 1234 | * |
||
| 1235 | * @param object $object |
||
| 1236 | * |
||
| 1237 | * @return RedirectResponse |
||
| 1238 | */ |
||
| 1239 | protected function redirectTo($object) |
||
| 1240 | { |
||
| 1241 | $request = $this->getRequest(); |
||
| 1242 | |||
| 1243 | $url = false; |
||
| 1244 | |||
| 1245 | if (null !== $request->get('btn_update_and_list')) { |
||
| 1246 | return $this->redirectToList(); |
||
| 1247 | } |
||
| 1248 | if (null !== $request->get('btn_create_and_list')) { |
||
| 1249 | return $this->redirectToList(); |
||
| 1250 | } |
||
| 1251 | |||
| 1252 | if (null !== $request->get('btn_create_and_create')) { |
||
| 1253 | $params = []; |
||
| 1254 | if ($this->admin->hasActiveSubClass()) { |
||
| 1255 | $params['subclass'] = $request->get('subclass'); |
||
| 1256 | } |
||
| 1257 | $url = $this->admin->generateUrl('create', $params); |
||
| 1258 | } |
||
| 1259 | |||
| 1260 | if ('DELETE' === $this->getRestMethod()) { |
||
| 1261 | return $this->redirectToList(); |
||
| 1262 | } |
||
| 1263 | |||
| 1264 | if (!$url) { |
||
| 1265 | foreach (['edit', 'show'] as $route) { |
||
| 1266 | if ($this->admin->hasRoute($route) && $this->admin->hasAccess($route, $object)) { |
||
| 1267 | $url = $this->admin->generateObjectUrl( |
||
| 1268 | $route, |
||
| 1269 | $object, |
||
| 1270 | $this->getSelectedTab($request) |
||
| 1271 | ); |
||
| 1272 | |||
| 1273 | break; |
||
| 1274 | } |
||
| 1275 | } |
||
| 1276 | } |
||
| 1277 | |||
| 1278 | if (!$url) { |
||
| 1279 | return $this->redirectToList(); |
||
| 1280 | } |
||
| 1281 | |||
| 1282 | return new RedirectResponse($url); |
||
| 1283 | } |
||
| 1284 | |||
| 1285 | /** |
||
| 1286 | * Redirects the user to the list view. |
||
| 1287 | * |
||
| 1288 | * @return RedirectResponse |
||
| 1289 | */ |
||
| 1290 | final protected function redirectToList() |
||
| 1300 | |||
| 1301 | /** |
||
| 1302 | * Returns true if the preview is requested to be shown. |
||
| 1303 | * |
||
| 1304 | * @return bool |
||
| 1305 | */ |
||
| 1306 | protected function isPreviewRequested() |
||
| 1312 | |||
| 1313 | /** |
||
| 1314 | * Returns true if the preview has been approved. |
||
| 1315 | * |
||
| 1316 | * @return bool |
||
| 1317 | */ |
||
| 1318 | protected function isPreviewApproved() |
||
| 1324 | |||
| 1325 | /** |
||
| 1326 | * Returns true if the request is in the preview workflow. |
||
| 1327 | * |
||
| 1328 | * That means either a preview is requested or the preview has already been shown |
||
| 1329 | * and it got approved/declined. |
||
| 1330 | * |
||
| 1331 | * @return bool |
||
| 1332 | */ |
||
| 1333 | protected function isInPreviewMode() |
||
| 1340 | |||
| 1341 | /** |
||
| 1342 | * Returns true if the preview has been declined. |
||
| 1343 | * |
||
| 1344 | * @return bool |
||
| 1345 | */ |
||
| 1346 | protected function isPreviewDeclined() |
||
| 1352 | |||
| 1353 | /** |
||
| 1354 | * Gets ACL users. |
||
| 1355 | * |
||
| 1356 | * @return \Traversable |
||
| 1357 | */ |
||
| 1358 | protected function getAclUsers() |
||
| 1373 | |||
| 1374 | /** |
||
| 1375 | * Gets ACL roles. |
||
| 1376 | * |
||
| 1377 | * @return \Traversable |
||
| 1378 | */ |
||
| 1379 | protected function getAclRoles() |
||
| 1408 | |||
| 1409 | /** |
||
| 1410 | * Validate CSRF token for action without form. |
||
| 1411 | * |
||
| 1412 | * @param string $intention |
||
| 1413 | * |
||
| 1414 | * @throws HttpException |
||
| 1415 | */ |
||
| 1416 | protected function validateCsrfToken($intention) |
||
| 1431 | |||
| 1432 | /** |
||
| 1433 | * Escape string for html output. |
||
| 1434 | * |
||
| 1435 | * @param string $s |
||
| 1436 | * |
||
| 1437 | * @return string |
||
| 1438 | */ |
||
| 1439 | protected function escapeHtml($s) |
||
| 1443 | |||
| 1444 | /** |
||
| 1445 | * Get CSRF token. |
||
| 1446 | * |
||
| 1447 | * @param string $intention |
||
| 1448 | * |
||
| 1449 | * @return string|false |
||
| 1450 | */ |
||
| 1451 | protected function getCsrfToken($intention) |
||
| 1459 | |||
| 1460 | /** |
||
| 1461 | * This method can be overloaded in your custom CRUD controller. |
||
| 1462 | * It's called from createAction. |
||
| 1463 | * |
||
| 1464 | * @param object $object |
||
| 1465 | * |
||
| 1466 | * @return Response|null |
||
| 1467 | */ |
||
| 1468 | protected function preCreate(Request $request, $object) |
||
| 1469 | { |
||
| 1470 | return null; |
||
| 1471 | } |
||
| 1472 | |||
| 1473 | /** |
||
| 1474 | * This method can be overloaded in your custom CRUD controller. |
||
| 1475 | * It's called from editAction. |
||
| 1476 | * |
||
| 1477 | * @param object $object |
||
| 1478 | * |
||
| 1479 | * @return Response|null |
||
| 1480 | */ |
||
| 1481 | protected function preEdit(Request $request, $object) |
||
| 1485 | |||
| 1486 | /** |
||
| 1487 | * This method can be overloaded in your custom CRUD controller. |
||
| 1488 | * It's called from deleteAction. |
||
| 1489 | * |
||
| 1490 | * @param object $object |
||
| 1491 | * |
||
| 1492 | * @return Response|null |
||
| 1493 | */ |
||
| 1494 | protected function preDelete(Request $request, $object) |
||
| 1498 | |||
| 1499 | /** |
||
| 1500 | * This method can be overloaded in your custom CRUD controller. |
||
| 1501 | * It's called from showAction. |
||
| 1502 | * |
||
| 1503 | * @param object $object |
||
| 1504 | * |
||
| 1505 | * @return Response|null |
||
| 1506 | */ |
||
| 1507 | protected function preShow(Request $request, $object) |
||
| 1511 | |||
| 1512 | /** |
||
| 1513 | * This method can be overloaded in your custom CRUD controller. |
||
| 1514 | * It's called from listAction. |
||
| 1515 | * |
||
| 1516 | * @return Response|null |
||
| 1517 | */ |
||
| 1518 | protected function preList(Request $request) |
||
| 1522 | |||
| 1523 | /** |
||
| 1524 | * Translate a message id. |
||
| 1525 | * |
||
| 1526 | * @param string $id |
||
| 1527 | * @param string $domain |
||
| 1528 | * @param string $locale |
||
| 1529 | * |
||
| 1530 | * @return string translated string |
||
| 1531 | */ |
||
| 1532 | final protected function trans($id, array $parameters = [], $domain = null, $locale = null) |
||
| 1538 | |||
| 1539 | private function getSelectedTab(Request $request) |
||
| 1543 | |||
| 1544 | private function checkParentChildAssociation(Request $request, $object): void |
||
| 1568 | |||
| 1569 | /** |
||
| 1570 | * Sets the admin form theme to form view. Used for compatibility between Symfony versions. |
||
| 1571 | */ |
||
| 1572 | private function setFormTheme(FormView $formView, array $theme = null): void |
||
| 1592 | |||
| 1593 | private function handleXmlHttpRequestErrorResponse(Request $request, FormInterface $form): ?JsonResponse |
||
| 1611 | |||
| 1612 | /** |
||
| 1613 | * @param object $object |
||
| 1614 | */ |
||
| 1615 | private function handleXmlHttpRequestSuccessResponse(Request $request, $object): JsonResponse |
||
| 1627 | } |
||
| 1628 |
If you implement
__calland you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.This is often the case, when
__callis implemented by a parent class and only the child class knows which methods exist: