Passed
Push — main ( b29b0b...aea47e )
by Roberto
12:37
created

Field::validate()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 7
rs 8.4444
cc 8
nc 5
nop 1
1
<?php
2
namespace Lepton\Boson\DataTypes;
3
4
5
class Field{
6
7
  protected array $default_error_messages = array(
8
    "invalid_choice"  => "Value %value is not a valid choice.",
9
    "null"            => "This field cannot be null.",
10
    "blank"           => "This field cannot be blank.",
11
    "unique"          => "A %model_name with this %field_label already exists.",
12
    "unique_for"      => "Field %field_label must be unique for fields with same %unique_for."
13
  );
14
15
  protected array $validation_errors = array();
16
17
  public function __construct(
18
     protected bool   $null             = false,
19
     protected bool   $blank            = true,
20
     protected array  $choices          = array(),
21
     protected string $db_column        = "",
22
     protected mixed  $default          = "",
23
     protected bool   $editable         = true,
24
     protected array  $error_messages   = array(),
25
     protected string $help_text        = "",
26
     protected bool   $primary_key      = false,
27
     protected bool   $unique           = false,
28
     protected string $verbose_name     = "",
29
     protected array  $validators       = array()
30
    )
31
  {
32
    return;
33
  }
34
35
36
  protected function validate($value){
37
    if (is_null($value) && (!$this->null)) return false;
38
    if (empty($value) && (!$this->blank)) return false;
39
    if (!empty($this->choices) && !in_array($value, $this->choices)) return false;
40
    if (!empty($this->validators)) return $this->validate_with_validators($value);
41
42
    return true;
43
  }
44
45
46
  private function validate_with_validators($value){
47
    foreach($this->validators as $validator){
48
      if (!$validator($value)) return false;
49
    }
50
    return true;
51
  }
52
53
54
55
  public function db_column(): string{
56
    return $this->db_column;
57
  }
58
59
  public function set_db_column(string $column_name): void{
60
    $this->db_column = $column_name;
61
  }
62
}