summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/Recipe/InvalidConfigException.php
blob: 0c92a42f55cd758bc33106960dc478d9264bbecc (plain) (blame)
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
<?php

declare(strict_types=1);

namespace Drupal\Core\Recipe;

use Drupal\Core\Config\Schema\Mapping;
use Symfony\Component\Validator\ConstraintViolationList;

/**
 * Thrown if config created or changed by a recipe fails validation.
 *
 * @internal
 *   This API is experimental.
 */
final class InvalidConfigException extends \RuntimeException {

  /**
   * Constructs an InvalidConfigException object.
   *
   * @param \Symfony\Component\Validator\ConstraintViolationList $violations
   *   The validation constraint violations.
   * @param \Drupal\Core\Config\Schema\Mapping $data
   *   A typed data wrapper around the invalid config data.
   * @param string $message
   *   (optional) The exception message. Defaults to the string representation
   *   of the constraint violation list.
   * @param int $code
   *   (optional) The exception code. Defaults to 0.
   * @param \Throwable|null $previous
   *   (optional) The previous exception, if any.
   */
  public function __construct(
    public readonly ConstraintViolationList $violations,
    public readonly Mapping $data,
    string $message = '',
    int $code = 0,
    ?\Throwable $previous = NULL,
  ) {
    parent::__construct($message ?: $this->formatMessage(), $code, $previous);
  }

  /**
   * Formats the constraint violation list as a human-readable message.
   *
   * @return string
   *   The formatted message.
   */
  private function formatMessage(): string {
    $lines = [
      sprintf('There were validation errors in %s:', $this->data->getName()),
    ];
    /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
    foreach ($this->violations as $violation) {
      $lines[] = sprintf('- %s: %s', $violation->getPropertyPath(), $violation->getMessage());
    }
    return implode("\n", $lines);
  }

}