AbstractWrapper.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. * @package Gedmo.Tool.Wrapper
  14. * @subpackage EntityWrapper
  15. * @link http://www.gediminasm.org
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. abstract class AbstractWrapper implements WrapperInterface
  19. {
  20. /**
  21. * Object metadata
  22. *
  23. * @var object
  24. */
  25. protected $meta;
  26. /**
  27. * Wrapped object
  28. *
  29. * @var object
  30. */
  31. protected $object;
  32. /**
  33. * Object manager instance
  34. *
  35. * @var \Doctrine\Common\Persistence\ObjectManager
  36. */
  37. protected $om;
  38. /**
  39. * List of wrapped object references
  40. *
  41. * @var array
  42. */
  43. private static $wrappedObjectReferences;
  44. /**
  45. * Wrapp object factory method
  46. *
  47. * @param object $object
  48. * @param \Doctrine\Common\Persistence\ObjectManager $om
  49. * @return \Gedmo\Tool\WrapperInterface
  50. */
  51. public static function wrap($object, ObjectManager $om)
  52. {
  53. $oid = spl_object_hash($object);
  54. if (!isset(self::$wrappedObjectReferences[$oid])) {
  55. if ($om instanceof EntityManager) {
  56. self::$wrappedObjectReferences[$oid] = new EntityWrapper($object, $om);
  57. } elseif ($om instanceof DocumentManager) {
  58. self::$wrappedObjectReferences[$oid] = new MongoDocumentWrapper($object, $om);
  59. } else {
  60. throw new UnsupportedObjectManager('Given object manager is not managed by wrapper');
  61. }
  62. }
  63. return self::$wrappedObjectReferences[$oid];
  64. }
  65. /**
  66. * {@inheritDoc}
  67. */
  68. public function getObject()
  69. {
  70. return $this->object;
  71. }
  72. /**
  73. * {@inheritDoc}
  74. */
  75. public function getMetadata()
  76. {
  77. return $this->meta;
  78. }
  79. /**
  80. * {@inheritDoc}
  81. */
  82. public function populate(array $data)
  83. {
  84. foreach ($data as $field => $value) {
  85. $this->setPropertyValue($field, $value);
  86. }
  87. return $this;
  88. }
  89. }