CollectionManager.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. public function __construct($content)
  10. {
  11. if (!is_array($content))
  12. throw new \Exception('Content must be array type !');
  13. if (!count($this->schema))
  14. throw new \Exception('Schema must be defined in child class !');
  15. if (!count($this->object_reference_attribute))
  16. throw new \Exception('Object reference attribute must be defined in child class !');
  17. $this->content = $content;
  18. }
  19. public function add($object)
  20. {
  21. if (!$this->have($object))
  22. {
  23. $content_line = array();
  24. foreach ($this->schema as $attribute)
  25. {
  26. $method_name = 'get' . $attribute;
  27. $content_line[$attribute] = (string)$object->$method_name();
  28. }
  29. $this->content[] = $content_line;
  30. }
  31. }
  32. public function have($object)
  33. {
  34. $method_name = 'get' . $this->object_reference_attribute;
  35. foreach ($this->content as $content_line)
  36. {
  37. if ($object->$method_name() == $content_line[$this->object_reference_attribute])
  38. {
  39. return true;
  40. }
  41. }
  42. return false;
  43. }
  44. public function remove($object)
  45. {
  46. $new_content = array();
  47. $method_name = 'get' . $this->object_reference_attribute;
  48. foreach ($this->content as $content_line)
  49. {
  50. if ($object->$method_name() != $content_line[$this->object_reference_attribute])
  51. {
  52. $new_content[] = $content_line;
  53. }
  54. }
  55. $this->content = $new_content;
  56. }
  57. public function getAttributes($attribute)
  58. {
  59. if (!in_array($attribute, $this->schema))
  60. throw new \Exception('This attribute is unknow !');
  61. $attributes = array();
  62. foreach ($this->content as $content_line)
  63. {
  64. $attributes[] = $content_line[$attribute];
  65. }
  66. return $attributes;
  67. }
  68. public function getContent()
  69. {
  70. return $this->content;
  71. }
  72. }