AbstractWrapper.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Gedmo\Tool\Wrapper;
  3. use Doctrine\ORM\EntityManager;
  4. use Doctrine\ODM\MongoDB\DocumentManager;
  5. use Doctrine\Common\Persistence\ObjectManager;
  6. use Gedmo\Tool\WrapperInterface;
  7. use Gedmo\Exception\UnsupportedObjectManager;
  8. /**
  9. * Wraps entity or proxy for more convenient
  10. * manipulation
  11. *
  12. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. abstract class AbstractWrapper implements WrapperInterface
  16. {
  17. /**
  18. * Object metadata
  19. *
  20. * @var object
  21. */
  22. protected $meta;
  23. /**
  24. * Wrapped object
  25. *
  26. * @var object
  27. */
  28. protected $object;
  29. /**
  30. * Object manager instance
  31. *
  32. * @var \Doctrine\Common\Persistence\ObjectManager
  33. */
  34. protected $om;
  35. /**
  36. * List of wrapped object references
  37. *
  38. * @var array
  39. */
  40. private static $wrappedObjectReferences;
  41. /**
  42. * Wrap object factory method
  43. *
  44. * @param object $object
  45. * @param \Doctrine\Common\Persistence\ObjectManager $om
  46. * @throws \Gedmo\Exception\UnsupportedObjectManager
  47. * @return \Gedmo\Tool\WrapperInterface
  48. */
  49. public static function wrap($object, ObjectManager $om)
  50. {
  51. $oid = spl_object_hash($object);
  52. if (!isset(self::$wrappedObjectReferences[$oid])) {
  53. if ($om instanceof EntityManager) {
  54. self::$wrappedObjectReferences[$oid] = new EntityWrapper($object, $om);
  55. } elseif ($om instanceof DocumentManager) {
  56. self::$wrappedObjectReferences[$oid] = new MongoDocumentWrapper($object, $om);
  57. } else {
  58. throw new UnsupportedObjectManager('Given object manager is not managed by wrapper');
  59. }
  60. }
  61. return self::$wrappedObjectReferences[$oid];
  62. }
  63. public static function clear()
  64. {
  65. self::$wrappedObjectReferences = array();
  66. }
  67. /**
  68. * {@inheritDoc}
  69. */
  70. public function getObject()
  71. {
  72. return $this->object;
  73. }
  74. /**
  75. * {@inheritDoc}
  76. */
  77. public function getMetadata()
  78. {
  79. return $this->meta;
  80. }
  81. /**
  82. * {@inheritDoc}
  83. */
  84. public function populate(array $data)
  85. {
  86. foreach ($data as $field => $value) {
  87. $this->setPropertyValue($field, $value);
  88. }
  89. return $this;
  90. }
  91. }