1<?php 2 3 4namespace ComboStrap\Meta\Api; 5 6use ComboStrap\DataType; 7use ComboStrap\ExceptionBadArgument; 8use ComboStrap\ExceptionCompile; 9use ComboStrap\ExceptionNotFound; 10use ComboStrap\LogUtility; 11 12/** 13 * Implement all default method for a text metadata (ie small string without any paragraph such as name, title, ...) 14 * Class MetadataText 15 * @package ComboStrap 16 */ 17abstract class MetadataText extends Metadata 18{ 19 20 /** 21 * @var string|null 22 */ 23 protected $value; 24 25 26 public static function getDataType(): string 27 { 28 return DataType::TEXT_TYPE_VALUE; 29 } 30 31 public function getValue(): string 32 { 33 $this->buildCheck(); 34 /** 35 * null or empty string is considered not found 36 */ 37 if ($this->value === null || trim($this->value) === "") { 38 throw new ExceptionNotFound("The value was not found for the metadata ($this)"); 39 } 40 return $this->value; 41 } 42 43 public function valueIsNotNull(): bool 44 { 45 return $this->value !== null; 46 } 47 48 49 /** 50 * @param null|string $value 51 * @return $this 52 * @throws ExceptionBadArgument 53 */ 54 public function setValue($value): Metadata 55 { 56 if ($value !== null && !is_string($value)) { 57 throw new ExceptionBadArgument("The value of the metadata ($this) is not a string", $this->getCanonical()); 58 } 59 $value = trim($value); 60 if ($value === "") { 61 /** 62 * TODO: move this into the function {@link MetadataText::setFromStoreValueWithoutException()} ?? 63 * form don't return null only empty string 64 * equivalent to null 65 */ 66 return $this; 67 } 68 $possibleValues = $this->getPossibleValues(); 69 if ($possibleValues !== null) { 70 if (!in_array($value, $possibleValues)) { 71 throw new ExceptionBadArgument("The value ($value) for the metadata ({$this->getName()}) is not one of the possible following values: " . implode(", ", $possibleValues) . "."); 72 } 73 } 74 $this->value = $value; 75 return $this; 76 77 } 78 79 /** 80 * @throws ExceptionCompile 81 */ 82 public function setFromStoreValue($value): Metadata 83 { 84 return $this->setValue($value); 85 } 86 87 public function setFromStoreValueWithoutException($value): Metadata 88 { 89 if (empty($value)) { 90 $this->value = null; 91 return $this; 92 } 93 if (!is_string($value)) { 94 LogUtility::msg("This value of a text metadata is not a string. " . var_export($value, true)); 95 return $this; 96 } 97 $this->value = $value; 98 return $this; 99 } 100 101 public function getDefaultValue() 102 { 103 return null; 104 } 105 106 107} 108