You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.0 KiB

  1. <?php
  2. namespace dimti\Image;
  3. abstract class ImageCollection extends ArrayIterator
  4. {
  5. /**
  6. * @var string
  7. */
  8. protected $class;
  9. /**
  10. * @param array|null $data
  11. * @param mixed $owner
  12. * @throws ErrorException
  13. * TODO: рефакторить этот метод
  14. */
  15. public function __construct($data = null, $owner = null)
  16. {
  17. /**
  18. * @var $class Image
  19. */
  20. $class = $this->class;
  21. Image::checkSubClass($class);
  22. if (!is_null($data) && $data != '') {
  23. if (!is_array($data)) {
  24. $data = json_decode($data, true);
  25. if (json_last_error() != JSON_ERROR_NONE) {
  26. ErrorMessage::log('Unable to convert json-string to array.');
  27. return;
  28. }
  29. }
  30. if (!isset($data['order']) || !isset($data['files'])) {
  31. ErrorMessage::log('Incorrect format for create ImageCollection.');
  32. return;
  33. }
  34. foreach ($data['order'] as $original_filename) {
  35. if (!isset($data['files'][$original_filename])) {
  36. ErrorMessage::log('Unable to fetch image "' . $original_filename . '" from ImageCollection.');
  37. continue;
  38. }
  39. $image_instance = $class::getInstance($data['files'][$original_filename]);
  40. if ($owner) {
  41. $image_instance->setOwner($owner);
  42. }
  43. $this->append($image_instance);
  44. }
  45. }
  46. return;
  47. }
  48. public function __toString()
  49. {
  50. $image_collection = array(
  51. 'order' => array(),
  52. 'files' => array()
  53. );
  54. foreach ((array)$this as $image) {
  55. $image_collection['order'][] = $image->original_filename;
  56. $image_collection['files'][$image->original_filename] = (string)$image;
  57. }
  58. return json_encode($image_collection);
  59. }
  60. }