4
0

AttributesTrait.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. /** @param non-empty-string $key */
  16. public function hasAttribute(string $key): bool {
  17. return isset($this->attributes[$key]);
  18. }
  19. /**
  20. * @param non-empty-string $key
  21. * @return array<int|string,mixed>|null
  22. */
  23. public function attributeArray(string $key): ?array {
  24. $a = $this->attributes[$key] ?? null;
  25. return is_array($a) ? $a : null;
  26. }
  27. /** @param non-empty-string $key */
  28. public function attributeBoolean(string $key): ?bool {
  29. $a = $this->attributes[$key] ?? null;
  30. return is_bool($a) ? $a : null;
  31. }
  32. /** @param non-empty-string $key */
  33. public function attributeInt(string $key): ?int {
  34. $a = $this->attributes[$key] ?? null;
  35. return is_int($a) ? $a : null;
  36. }
  37. /** @param non-empty-string $key */
  38. public function attributeString(string $key): ?string {
  39. $a = $this->attributes[$key] ?? null;
  40. return is_string($a) ? $a : null;
  41. }
  42. /** @param string|array<string,mixed> $values Values, not HTML-encoded */
  43. public function _attributes($values): void {
  44. if (is_string($values)) {
  45. $values = json_decode($values, true);
  46. }
  47. if (is_array($values)) {
  48. $this->attributes = $values;
  49. }
  50. }
  51. /**
  52. * @param non-empty-string $key
  53. * @param array<string,mixed>|mixed|null $value Value, not HTML-encoded
  54. */
  55. public function _attribute(string $key, $value = null): void {
  56. if ($value === null) {
  57. unset($this->attributes[$key]);
  58. } else {
  59. $this->attributes[$key] = $value;
  60. }
  61. }
  62. }