PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/library/vendors/doctrine/odm/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php

https://bitbucket.org/paulscott56/c4-framework
PHP | 402 lines | 303 code | 15 blank | 84 comment | 5 complexity | 9a8e2de261fd4c742ba18fa99901a8d3 MD5 | raw file
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ODM\MongoDB\Hydrator;
  20. use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
  21. use Doctrine\ODM\MongoDB\DocumentManager;
  22. use Doctrine\ODM\MongoDB\Mapping\Types\Type;
  23. use Doctrine\ODM\MongoDB\UnitOfWork;
  24. use Doctrine\ODM\MongoDB\Events;
  25. use Doctrine\Common\EventManager;
  26. use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
  27. use Doctrine\ODM\MongoDB\Event\PreLoadEventArgs;
  28. use Doctrine\ODM\MongoDB\PersistentCollection;
  29. use Doctrine\Common\Collections\ArrayCollection;
  30. use Doctrine\ODM\MongoDB\Proxy\Proxy;
  31. /**
  32. * The HydratorFactory class is responsible for instantiating a correct hydrator
  33. * type based on document's ClassMetadata
  34. *
  35. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  36. * @link www.doctrine-project.com
  37. * @since 1.0
  38. * @author Jonathan H. Wage <jonwage@gmail.com>
  39. */
  40. class HydratorFactory
  41. {
  42. /**
  43. * The DocumentManager this factory is bound to.
  44. *
  45. * @var Doctrine\ODM\MongoDB\DocumentManager
  46. */
  47. private $dm;
  48. /**
  49. * The UnitOfWork used to coordinate object-level transactions.
  50. *
  51. * @var Doctrine\ODM\MongoDB\UnitOfWork
  52. */
  53. private $unitOfWork;
  54. /**
  55. * The EventManager associated with this Hydrator
  56. *
  57. * @var Doctrine\Common\EventManager
  58. */
  59. private $evm;
  60. /**
  61. * Whether to automatically (re)generate hydrator classes.
  62. *
  63. * @var boolean
  64. */
  65. private $autoGenerate;
  66. /**
  67. * The namespace that contains all hydrator classes.
  68. *
  69. * @var string
  70. */
  71. private $hydratorNamespace;
  72. /**
  73. * The directory that contains all hydrator classes.
  74. *
  75. * @var string
  76. */
  77. private $hydratorDir;
  78. /**
  79. * Array of instantiated document hydrators.
  80. *
  81. * @var array
  82. */
  83. private $hydrators = array();
  84. /**
  85. * Mongo command prefix
  86. * @var string
  87. */
  88. private $cmd;
  89. public function __construct(DocumentManager $dm, EventManager $evm, $hydratorDir, $hydratorNs, $autoGenerate, $cmd)
  90. {
  91. if ( ! $hydratorDir) {
  92. throw HydratorException::hydratorDirectoryRequired();
  93. }
  94. if ( ! $hydratorNs) {
  95. throw HydratorException::hydratorNamespaceRequired();
  96. }
  97. $this->dm = $dm;
  98. $this->evm = $evm;
  99. $this->hydratorDir = $hydratorDir;
  100. $this->hydratorNamespace = $hydratorNs;
  101. $this->autoGenerate = $autoGenerate;
  102. $this->cmd = $cmd;
  103. }
  104. /**
  105. * Sets the UnitOfWork instance.
  106. *
  107. * @param UnitOfWork $uow
  108. */
  109. public function setUnitOfWork(UnitOfWork $uow)
  110. {
  111. $this->unitOfWork = $uow;
  112. }
  113. /**
  114. * Gets the hydrator object for the given document class.
  115. *
  116. * @param string $className
  117. * @return Doctrine\ODM\MongoDB\Hydrator\HydratorInterface $hydrator
  118. */
  119. public function getHydratorFor($className)
  120. {
  121. if (isset($this->hydrators[$className])) {
  122. return $this->hydrators[$className];
  123. }
  124. $hydratorClassName = str_replace('\\', '', $className) . 'Hydrator';
  125. $fqn = $this->hydratorNamespace . '\\' . $hydratorClassName;
  126. $class = $this->dm->getClassMetadata($className);
  127. if (! class_exists($fqn, false)) {
  128. $fileName = $this->hydratorDir . DIRECTORY_SEPARATOR . $hydratorClassName . '.php';
  129. if ($this->autoGenerate) {
  130. $this->generateHydratorClass($class, $hydratorClassName, $fileName);
  131. }
  132. require $fileName;
  133. }
  134. $this->hydrators[$className] = new $fqn($this->dm, $this->unitOfWork, $class);
  135. return $this->hydrators[$className];
  136. }
  137. /**
  138. * Generates hydrator classes for all given classes.
  139. *
  140. * @param array $classes The classes (ClassMetadata instances) for which to generate hydrators.
  141. * @param string $toDir The target directory of the hydrator classes. If not specified, the
  142. * directory configured on the Configuration of the DocumentManager used
  143. * by this factory is used.
  144. */
  145. public function generateHydratorClasses(array $classes, $toDir = null)
  146. {
  147. $hydratorDir = $toDir ?: $this->hydratorDir;
  148. $hydratorDir = rtrim($hydratorDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
  149. foreach ($classes as $class) {
  150. $hydratorClassName = str_replace('\\', '', $class->name) . 'Hydrator';
  151. $hydratorFileName = $hydratorDir . $hydratorClassName . '.php';
  152. $this->generateHydratorClass($class, $hydratorClassName, $hydratorFileName);
  153. }
  154. }
  155. private function generateHydratorClass(ClassMetadata $class, $hydratorClassName, $fileName)
  156. {
  157. $code = '';
  158. foreach ($class->fieldMappings as $fieldName => $mapping) {
  159. if (isset($mapping['alsoLoadFields'])) {
  160. foreach ($mapping['alsoLoadFields'] as $name) {
  161. $code .= sprintf(<<<EOF
  162. /** @AlsoLoad("$name") */
  163. if (isset(\$data['$name'])) {
  164. \$data['$fieldName'] = \$data['$name'];
  165. }
  166. EOF
  167. );
  168. }
  169. }
  170. if ( ! isset($mapping['association'])) {
  171. $code .= sprintf(<<<EOF
  172. /** @Field(type="{$mapping['type']}") */
  173. if (isset(\$data['%1\$s'])) {
  174. \$value = \$data['%1\$s'];
  175. %3\$s
  176. \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
  177. \$hydratedData['%2\$s'] = \$return;
  178. }
  179. EOF
  180. ,
  181. $mapping['name'],
  182. $mapping['fieldName'],
  183. Type::getType($mapping['type'])->closureToPHP()
  184. );
  185. } elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isOwningSide']) {
  186. $code .= sprintf(<<<EOF
  187. /** @ReferenceOne */
  188. if (isset(\$data['%1\$s'])) {
  189. \$reference = \$data['%1\$s'];
  190. if (isset(\$this->class->fieldMappings['%2\$s']['simple']) && \$this->class->fieldMappings['%2\$s']['simple']) {
  191. \$className = \$this->class->fieldMappings['%2\$s']['targetDocument'];
  192. \$mongoId = \$reference;
  193. } else {
  194. \$className = \$this->dm->getClassNameFromDiscriminatorValue(\$this->class->fieldMappings['%2\$s'], \$reference);
  195. \$mongoId = \$reference['\$id'];
  196. }
  197. \$targetMetadata = \$this->dm->getClassMetadata(\$className);
  198. \$id = \$targetMetadata->getPHPIdentifierValue(\$mongoId);
  199. \$return = \$this->dm->getReference(\$className, \$id);
  200. \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
  201. \$hydratedData['%2\$s'] = \$return;
  202. }
  203. EOF
  204. ,
  205. $mapping['name'],
  206. $mapping['fieldName']
  207. );
  208. } elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isInverseSide']) {
  209. if (isset($mapping['repositoryMethod']) && $mapping['repositoryMethod']) {
  210. $code .= sprintf(<<<EOF
  211. \$className = \$this->class->fieldMappings['%2\$s']['targetDocument'];
  212. \$return = \$this->dm->getRepository(\$className)->%3\$s(\$document);
  213. \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
  214. \$hydratedData['%2\$s'] = \$return;
  215. EOF
  216. ,
  217. $mapping['name'],
  218. $mapping['fieldName'],
  219. $mapping['repositoryMethod']
  220. );
  221. } else {
  222. $code .= sprintf(<<<EOF
  223. \$mapping = \$this->class->fieldMappings['%2\$s'];
  224. \$className = \$mapping['targetDocument'];
  225. \$targetClass = \$this->dm->getClassMetadata(\$mapping['targetDocument']);
  226. \$mappedByMapping = \$targetClass->fieldMappings[\$mapping['mappedBy']];
  227. \$mappedByFieldName = isset(\$mappedByMapping['simple']) && \$mappedByMapping['simple'] ? \$mapping['mappedBy'] : \$mapping['mappedBy'].'.id';
  228. \$criteria = array_merge(
  229. array(\$mappedByFieldName => \$data['_id']),
  230. isset(\$this->class->fieldMappings['%2\$s']['criteria']) ? \$this->class->fieldMappings['%2\$s']['criteria'] : array()
  231. );
  232. \$sort = isset(\$this->class->fieldMappings['%2\$s']['sort']) ? \$this->class->fieldMappings['%2\$s']['sort'] : array();
  233. \$return = \$this->unitOfWork->getDocumentPersister(\$className)->load(\$criteria, null, array(), 0, \$sort);
  234. \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
  235. \$hydratedData['%2\$s'] = \$return;
  236. EOF
  237. ,
  238. $mapping['name'],
  239. $mapping['fieldName']
  240. );
  241. }
  242. } elseif ($mapping['association'] === ClassMetadata::REFERENCE_MANY || $mapping['association'] === ClassMetadata::EMBED_MANY) {
  243. $code .= sprintf(<<<EOF
  244. /** @Many */
  245. \$mongoData = isset(\$data['%1\$s']) ? \$data['%1\$s'] : null;
  246. \$return = new \Doctrine\ODM\MongoDB\PersistentCollection(new \Doctrine\Common\Collections\ArrayCollection(), \$this->dm, \$this->unitOfWork, '$');
  247. \$return->setHints(\$hints);
  248. \$return->setOwner(\$document, \$this->class->fieldMappings['%2\$s']);
  249. \$return->setInitialized(false);
  250. if (\$mongoData) {
  251. \$return->setMongoData(\$mongoData);
  252. }
  253. \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
  254. \$hydratedData['%2\$s'] = \$return;
  255. EOF
  256. ,
  257. $mapping['name'],
  258. $mapping['fieldName']
  259. );
  260. } elseif ($mapping['association'] === ClassMetadata::EMBED_ONE) {
  261. $code .= sprintf(<<<EOF
  262. /** @EmbedOne */
  263. if (isset(\$data['%1\$s'])) {
  264. \$embeddedDocument = \$data['%1\$s'];
  265. \$className = \$this->dm->getClassNameFromDiscriminatorValue(\$this->class->fieldMappings['%2\$s'], \$embeddedDocument);
  266. \$embeddedMetadata = \$this->dm->getClassMetadata(\$className);
  267. \$return = \$embeddedMetadata->newInstance();
  268. \$embeddedData = \$this->dm->getHydratorFactory()->hydrate(\$return, \$embeddedDocument, \$hints);
  269. \$this->unitOfWork->registerManaged(\$return, null, \$embeddedData);
  270. \$this->unitOfWork->setParentAssociation(\$return, \$this->class->fieldMappings['%2\$s'], \$document, '%1\$s');
  271. \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
  272. \$hydratedData['%2\$s'] = \$return;
  273. }
  274. EOF
  275. ,
  276. $mapping['name'],
  277. $mapping['fieldName']
  278. );
  279. }
  280. }
  281. $className = $class->name;
  282. $namespace = $this->hydratorNamespace;
  283. $code = sprintf(<<<EOF
  284. <?php
  285. namespace $namespace;
  286. use Doctrine\ODM\MongoDB\DocumentManager;
  287. use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
  288. use Doctrine\ODM\MongoDB\Hydrator\HydratorInterface;
  289. use Doctrine\ODM\MongoDB\UnitOfWork;
  290. /**
  291. * THIS CLASS WAS GENERATED BY THE DOCTRINE ODM. DO NOT EDIT THIS FILE.
  292. */
  293. class $hydratorClassName implements HydratorInterface
  294. {
  295. private \$dm;
  296. private \$unitOfWork;
  297. private \$class;
  298. public function __construct(DocumentManager \$dm, UnitOfWork \$uow, ClassMetadata \$class)
  299. {
  300. \$this->dm = \$dm;
  301. \$this->unitOfWork = \$uow;
  302. \$this->class = \$class;
  303. }
  304. public function hydrate(\$document, \$data, array \$hints = array())
  305. {
  306. \$hydratedData = array();
  307. %s return \$hydratedData;
  308. }
  309. }
  310. EOF
  311. ,
  312. $code
  313. );
  314. file_put_contents($fileName, $code);
  315. }
  316. /**
  317. * Hydrate array of MongoDB document data into the given document object.
  318. *
  319. * @param object $document The document object to hydrate the data into.
  320. * @param array $data The array of document data.
  321. * @param array $hints Any hints to account for during reconstitution/lookup of the document.
  322. * @return array $values The array of hydrated values.
  323. */
  324. public function hydrate($document, $data, array $hints = array())
  325. {
  326. $metadata = $this->dm->getClassMetadata(get_class($document));
  327. // Invoke preLoad lifecycle events and listeners
  328. if (isset($metadata->lifecycleCallbacks[Events::preLoad])) {
  329. $args = array(&$data);
  330. $metadata->invokeLifecycleCallbacks(Events::preLoad, $document, $args);
  331. }
  332. if ($this->evm->hasListeners(Events::preLoad)) {
  333. $this->evm->dispatchEvent(Events::preLoad, new PreLoadEventArgs($document, $this->dm, $data));
  334. }
  335. // Use the alsoLoadMethods on the document object to transform the data before hydration
  336. if (isset($metadata->alsoLoadMethods)) {
  337. foreach ($metadata->alsoLoadMethods as $fieldName => $method) {
  338. if (isset($data[$fieldName])) {
  339. $document->$method($data[$fieldName]);
  340. }
  341. }
  342. }
  343. $data = $this->getHydratorFor($metadata->name)->hydrate($document, $data, $hints);
  344. if ($document instanceof Proxy) {
  345. $document->__isInitialized__ = true;
  346. }
  347. // Invoke the postLoad lifecycle callbacks and listeners
  348. if (isset($metadata->lifecycleCallbacks[Events::postLoad])) {
  349. $metadata->invokeLifecycleCallbacks(Events::postLoad, $document);
  350. }
  351. if ($this->evm->hasListeners(Events::postLoad)) {
  352. $this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($document, $this->dm));
  353. }
  354. return $data;
  355. }
  356. }