Нет описания

RequiredCustomFieldValidator.php 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace MailPoet\Subscribers;
  3. if (!defined('ABSPATH')) exit;
  4. use Exception;
  5. use MailPoet\CustomFields\CustomFieldsRepository;
  6. use MailPoet\Entities\FormEntity;
  7. class RequiredCustomFieldValidator {
  8. /** @var CustomFieldsRepository */
  9. private $customFieldRepository;
  10. public function __construct(
  11. CustomFieldsRepository $customFieldRepository
  12. ) {
  13. $this->customFieldRepository = $customFieldRepository;
  14. }
  15. /**
  16. * @param array $data
  17. * @param FormEntity|null $form
  18. *
  19. * @throws Exception
  20. */
  21. public function validate(array $data, FormEntity $form = null) {
  22. $allCustomFields = $this->getCustomFields($form);
  23. foreach ($allCustomFields as $customFieldId => $customFieldName) {
  24. if ($this->isCustomFieldMissing($customFieldId, $data)) {
  25. throw new Exception(
  26. __(sprintf('Missing value for custom field "%s"', $customFieldName), 'mailpoet')
  27. );
  28. }
  29. }
  30. }
  31. private function isCustomFieldMissing(int $customFieldId, array $data): bool {
  32. if (!array_key_exists($customFieldId, $data) && !array_key_exists('cf_' . $customFieldId, $data)) {
  33. return true;
  34. }
  35. if (isset($data[$customFieldId]) && !$data[$customFieldId]) {
  36. return true;
  37. }
  38. if (isset($data['cf_' . $customFieldId]) && !$data['cf_' . $customFieldId]) {
  39. return true;
  40. }
  41. return false;
  42. }
  43. private function getCustomFields(FormEntity $form = null): array {
  44. $result = [];
  45. if ($form) {
  46. $ids = $this->getFormCustomFieldIds($form);
  47. if (!$ids) {
  48. return [];
  49. }
  50. $requiredCustomFields = $this->customFieldRepository->findBy(['id' => $ids]);
  51. } else {
  52. $requiredCustomFields = $this->customFieldRepository->findAll();
  53. }
  54. foreach ($requiredCustomFields as $customField) {
  55. $params = $customField->getParams();
  56. if (is_array($params) && isset($params['required']) && $params['required']) {
  57. $result[$customField->getId()] = $customField->getName();
  58. }
  59. }
  60. return $result;
  61. }
  62. /**
  63. * @return int[]
  64. */
  65. private function getFormCustomFieldIds(FormEntity $form): array {
  66. $formFields = $form->getBlocksByTypes(FormEntity::FORM_FIELD_TYPES);
  67. $customFieldIds = [];
  68. foreach ($formFields as $formField) {
  69. if (isset($formField['id']) && is_numeric($formField['id'])) {
  70. $customFieldIds[] = (int)$formField['id'];
  71. }
  72. }
  73. return $customFieldIds;
  74. }
  75. }