You are here

protected function ContactMessageResource::validate in Contact message REST 8

Verifies that the whole entity does not violate any validation constraints.

Copied from Drupal\rest\Plugin\rest\resource\EntityResource::validate.

Parameters

\Drupal\contact\MessageInterface $message: The message entity object.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException If validation errors are found.

1 call to ContactMessageResource::validate()
ContactMessageResource::post in src/Plugin/rest/resource/ContactMessageResource.php
Responds to entity POST requests and saves the new entity.

File

src/Plugin/rest/resource/ContactMessageResource.php, line 193
Contains \Drupal\contact_message_rest\Plugin\rest\resource\ContactMessageResource.

Class

ContactMessageResource
Creates a resource for adding contact Message entities and sending them.

Namespace

Drupal\contact_message_rest\Plugin\rest\resource

Code

protected function validate(MessageInterface $message = NULL) {
  $violations = $message
    ->validate();

  // Remove violations of inaccessible fields as they cannot stem from our
  // changes.
  $violations
    ->filterByFieldAccess();
  if (count($violations) > 0) {
    $error_message = "Unprocessable Entity: validation failed.\n";
    foreach ($violations as $violation) {
      $error_message .= $violation
        ->getPropertyPath() . ': ' . $violation
        ->getMessage() . "\n";
    }

    // Instead of returning a generic 400 response we use the more specific
    // 422 Unprocessable Entity code from RFC 4918. That way clients can
    // distinguish between general syntax errors in bad serializations (code
    // 400) and semantic errors in well-formed requests (code 422).
    throw new HttpException(422, $error_message);
  }

  // Check if flood control has been activated for sending emails.
  if (!$this->currentUser
    ->hasPermission('administer contact forms') && (!$message
    ->isPersonal() || !$this->currentUser
    ->hasPermission('administer users'))) {
    $limit = $this->config
      ->get('flood.limit');
    $interval = $this->config
      ->get('flood.interval');
    if (!$this->flood
      ->isAllowed('contact', $limit, $interval)) {
      $flood_error = $this
        ->t('You cannot send more than %limit messages in @interval. Try again later.', array(
        '%limit' => $limit,
        '@interval' => $this->dateFormatter
          ->formatInterval($interval),
      ));
      throw new AccessDeniedHttpException($flood_error);
    }
  }
}