Passed
Push — 6.0 ( 7ab78c...8e0f01 )
by Olivier
01:35
created

lib/ActiveRecord/RecordNotValid.php (2 issues)

1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\ActiveRecord;
13
14
use ICanBoogie\Accessor\AccessorTrait;
15
use ICanBoogie\ActiveRecord;
16
use ICanBoogie\Validate\ValidationErrors;
17
use LogicException;
18
use Throwable;
19
20
/**
21
 * Exception thrown when the validation of a record failed.
22
 *
23
 * @property-read ActiveRecord $record
24
 * @property-read ValidationErrors $errors
25
 */
26
class RecordNotValid extends LogicException implements Exception
27
{
28
    /**
29
     * @uses get_record
30
     * @uses get_errors
31
     */
32
    use AccessorTrait;
33
34
    public const DEFAULT_MESSAGE = "The record is not valid.";
35
36
    private function get_record(): ActiveRecord
0 ignored issues
show
The method get_record() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
37
    {
38
        return $this->record;
39
    }
40
41
    private function get_errors(): ValidationErrors
0 ignored issues
show
The method get_errors() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
42
    {
43
        return $this->errors;
44
    }
45
46
    public function __construct(
47
        private ActiveRecord $record,
48
        private ValidationErrors $errors,
49
        Throwable $previous = null
50
    ) {
51
        parent::__construct($this->format_message($errors), 500, $previous);
52
    }
53
54
    private function format_message(ValidationErrors $errors): string
55
    {
56
        $message = self::DEFAULT_MESSAGE . "\n";
57
58
        foreach ($errors as $attribute => $attribute_errors) {
59
            foreach ($attribute_errors as $error) {
60
                $message .= "\n- $attribute: $error";
61
            }
62
        }
63
64
        return $message;
65
    }
66
}
67