AttributesTrait.php 944 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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. /**
  12. * @phpstan-return ($key is non-empty-string ? mixed : array<string,mixed>)
  13. * @return array<string,mixed>|mixed|null
  14. */
  15. public function attributes(string $key = '') {
  16. if ($key === '') {
  17. return $this->attributes;
  18. } else {
  19. return $this->attributes[$key] ?? null;
  20. }
  21. }
  22. /** @param string|array<mixed>|bool|int|null $value Value, not HTML-encoded */
  23. public function _attributes(string $key, $value = null): void {
  24. if ($key == '') {
  25. if (is_string($value)) {
  26. $value = json_decode($value, true);
  27. }
  28. if (is_array($value)) {
  29. $this->attributes = $value;
  30. }
  31. } elseif ($value === null) {
  32. unset($this->attributes[$key]);
  33. } else {
  34. $this->attributes[$key] = $value;
  35. }
  36. }
  37. }