AttributesTrait.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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(string|array $values): void {
  44. if (is_string($values)) {
  45. $values = json_decode($values, true);
  46. }
  47. if (is_array($values)) {
  48. $values = array_filter($values, 'is_string', ARRAY_FILTER_USE_KEY);
  49. $this->attributes = $values;
  50. }
  51. }
  52. /**
  53. * @param non-empty-string $key
  54. * @param array<string,mixed>|mixed|null $value Value, not HTML-encoded
  55. */
  56. public function _attribute(string $key, $value = null): void {
  57. if ($value === null) {
  58. unset($this->attributes[$key]);
  59. } else {
  60. $this->attributes[$key] = $value;
  61. }
  62. }
  63. }