AttributesTrait.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Logic to work with (JSON) attributes (for entries, feeds, categories, tags...).
  5. */
  6. trait FreshRSS_AttributesTrait {
  7. /**
  8. * @var array<string,mixed>
  9. */
  10. private array $attributes = [];
  11. /** @return array<string,mixed> */
  12. public function attributes(): array {
  13. return $this->attributes;
  14. }
  15. /**
  16. * @param non-empty-string $key
  17. * @return array<int|string,mixed>|null
  18. */
  19. public function attributeArray(string $key): ?array {
  20. $a = $this->attributes[$key] ?? null;
  21. return is_array($a) ? $a : null;
  22. }
  23. /** @param non-empty-string $key */
  24. public function attributeBoolean(string $key): ?bool {
  25. $a = $this->attributes[$key] ?? null;
  26. return is_bool($a) ? $a : null;
  27. }
  28. /** @param non-empty-string $key */
  29. public function attributeInt(string $key): ?int {
  30. $a = $this->attributes[$key] ?? null;
  31. return is_int($a) ? $a : null;
  32. }
  33. /** @param non-empty-string $key */
  34. public function attributeString(string $key): ?string {
  35. $a = $this->attributes[$key] ?? null;
  36. return is_string($a) ? $a : null;
  37. }
  38. /** @param string|array<string,mixed> $values Values, not HTML-encoded */
  39. public function _attributes($values): void {
  40. if (is_string($values)) {
  41. $values = json_decode($values, true);
  42. }
  43. if (is_array($values)) {
  44. $this->attributes = $values;
  45. }
  46. }
  47. /**
  48. * @param non-empty-string $key
  49. * @param array<string,mixed>|mixed|null $value Value, not HTML-encoded
  50. */
  51. public function _attribute(string $key, $value = null): void {
  52. if ($value === null) {
  53. unset($this->attributes[$key]);
  54. } else {
  55. $this->attributes[$key] = $value;
  56. }
  57. }
  58. }