CollectionManager.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace Muzich\CoreBundle\lib\Collection;
  3. use \Doctrine\Common\Collections\ArrayCollection;
  4. abstract class CollectionManager
  5. {
  6. protected $content;
  7. protected $schema = array();
  8. protected $object_reference_attribute;
  9. protected $allow_duplicates = false;
  10. public function __construct($content)
  11. {
  12. if (!is_array($content))
  13. throw new \Exception('Content must be array type !');
  14. if (!count($this->schema))
  15. throw new \Exception('Schema must be defined in child class !');
  16. if (!count($this->object_reference_attribute))
  17. throw new \Exception('Object reference attribute must be defined in child class !');
  18. $this->content = $content;
  19. }
  20. public function add($object)
  21. {
  22. if (!$this->have($object) || $this->allow_duplicates)
  23. {
  24. $content_line = array();
  25. foreach ($this->schema as $attribute)
  26. {
  27. $method_name = 'get' . $attribute;
  28. $content_line[lcfirst($attribute)] = (string)$object->$method_name();
  29. }
  30. $this->content[] = $content_line;
  31. }
  32. }
  33. public function have($object)
  34. {
  35. $method_name = 'get' . $this->object_reference_attribute;
  36. foreach ($this->content as $content_line)
  37. {
  38. if ($object->$method_name() == $content_line[lcfirst($this->object_reference_attribute)])
  39. {
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. public function remove($object)
  46. {
  47. $new_content = array();
  48. $method_name = 'get' . $this->object_reference_attribute;
  49. foreach ($this->content as $content_line)
  50. {
  51. if ($object->$method_name() != $content_line[lcfirst($this->object_reference_attribute)])
  52. {
  53. $new_content[] = $content_line;
  54. }
  55. }
  56. $this->content = $new_content;
  57. }
  58. public function removeWithReference($reference)
  59. {
  60. $new_content = array();
  61. foreach ($this->content as $content_line)
  62. {
  63. if ($reference != $content_line[lcfirst($this->object_reference_attribute)])
  64. {
  65. $new_content[] = $content_line;
  66. }
  67. }
  68. $this->content = $new_content;
  69. }
  70. public function getAttributes($attribute)
  71. {
  72. if (!in_array($attribute, $this->schema))
  73. throw new \Exception('This attribute is unknow !');
  74. $attributes = array();
  75. foreach ($this->content as $content_line)
  76. {
  77. $attributes[] = $content_line[lcfirst($attribute)];
  78. }
  79. return $attributes;
  80. }
  81. public function getContent()
  82. {
  83. return $this->content;
  84. }
  85. }