/**
  * @inheritdoc
  */
 function hydrate($document, $data, array $hints = [])
 {
     $hydratedData = [];
     foreach ($this->metadata->fieldMappings as $fieldName => $mapping) {
         $name = $mapping['name'];
         $propertyValue = isset($data[$name]) ? $data[$name] : null;
         if (!isset($mapping['association'])) {
             if ($propertyValue === null) {
                 continue;
             }
             $type = Type::getType($mapping['type']);
             $value = $type->convertToPHPValue($propertyValue);
             $this->metadata->reflFields[$fieldName]->setValue($document, $value);
             $hydratedData[$fieldName] = $value;
             continue;
         }
         if ($mapping['association'] & ClassMetadata::TO_MANY) {
             $coll = new PersistentCollection(new ArrayCollection(), $this->dm, $this->uow);
             $coll->setOwner($document, $mapping);
             $coll->setInitialized(false);
             if ($propertyValue) {
                 $coll->setData($propertyValue);
             }
             $this->metadata->reflFields[$fieldName]->setValue($document, $coll);
             $hydratedData[$fieldName] = $coll;
             continue;
         }
         if ($propertyValue === null) {
             continue;
         }
         if ($mapping['association'] === ClassMetadata::LINK) {
             if (is_string($propertyValue)) {
                 $link = $this->dm->getReference($propertyValue);
             } else {
                 $link = $this->uow->getOrCreateDocument($propertyValue);
             }
             $this->metadata->reflFields[$fieldName]->setValue($document, $link);
             $hydratedData[$fieldName] = $link;
             continue;
         }
         if ($mapping['association'] === ClassMetadata::EMBED) {
             // an embed one must have @class, we would support generic JSON properties via another mapping type
             if (!isset($propertyValue[self::ORIENT_PROPERTY_CLASS])) {
                 throw new HydratorException(sprintf("missing @class for embedded property '%s'", $name));
             }
             $oclass = $propertyValue[self::ORIENT_PROPERTY_CLASS];
             $embeddedMetadata = $this->dm->getMetadataFactory()->getMetadataForOClass($oclass);
             $doc = $embeddedMetadata->newInstance();
             $embeddedData = $this->dm->getHydratorFactory()->hydrate($doc, $propertyValue, $hints);
             $this->uow->registerManaged($doc, null, $embeddedData);
             $this->metadata->reflFields[$fieldName]->setValue($document, $doc);
             $hydratedData[$fieldName] = $doc;
             continue;
         }
     }
     return $hydratedData;
 }
Esempio n. 2
0
 /**
  * Initializes a new instance of the <tt>ProxyFactory</tt> class that is
  * connected to the given <tt>DocumentManager</tt>.
  *
  * @param DocumentManager $manager
  * @param string          $proxyDir                              The directory to use for the proxy classes. It
  *                                                               must exist.
  * @param string          $proxyNamespace                        The namespace to use for the proxy classes.
  * @param int             $autoGenerate                          Whether to automatically generate proxy classes.
  */
 public function __construct(DocumentManager $manager, $proxyDir, $proxyNamespace, $autoGenerate = AbstractProxyFactory::AUTOGENERATE_NEVER)
 {
     $this->metadataFactory = $manager->getMetadataFactory();
     $this->uow = $manager->getUnitOfWork();
     $this->proxyNamespace = $proxyNamespace;
     $proxyGenerator = new ProxyGenerator($proxyDir, $proxyNamespace);
     $proxyGenerator->setPlaceholder('baseProxyInterface', 'Doctrine\\ODM\\OrientDB\\Proxy\\Proxy');
     parent::__construct($proxyGenerator, $this->metadataFactory, $autoGenerate);
 }
    /**
     * @test
     */
    public function hydrate_contact_with_link_list()
    {
        $md = $this->manager->getClassMetadata(Stub\Linked\Contact::class);
        $dh = new DynamicHydrator($this->manager, $this->manager->getUnitOfWork(), $md);
        $c = new Stub\Linked\Contact();
        $d = json_decode(<<<JSON
{
    "@rid": "#1:1",
    "name": "Sydney",
    "phones": [ "#3:1", "#3:2" ]
}
JSON
, true);
        $hd = $dh->hydrate($c, $d);
        $this->assertEquals(['rid', 'name', 'phones'], array_keys($hd));
        $this->assertEquals('#1:1', $hd['rid']);
        $this->assertEquals('Sydney', $hd['name']);
        /** @var Stub\Linked\Phone[] $phones */
        $phones = $c->getPhones()->toArray();
        $this->assertCount(2, $phones);
        $phone = $phones[0];
        $this->assertEquals('work', $phone->type);
        $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->uow->getDocumentState($phone));
        $this->assertTrue($this->uow->isInIdentityMap($phone));
        $phone = $phones[1];
        $this->assertEquals('home', $phone->type);
        $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->uow->getDocumentState($phone));
        $this->assertTrue($this->uow->isInIdentityMap($phone));
    }
Esempio n. 4
0
 private function gatherProperties(ClassMetadata $class, OClass $oclass)
 {
     foreach ($class->fieldMappings as $mapping) {
         if (isset($mapping['inherited'])) {
             continue;
         }
         $name = $mapping['name'];
         if (OSchema::isSystemProperty($name)) {
             continue;
         }
         if (isset($mapping['association'])) {
             continue;
         }
         $options = ['readonly' => $mapping['readonly'], 'mandatory' => $mapping['mandatory'], 'min' => $mapping['min'], 'max' => $mapping['max'], 'regexp' => $mapping['regexp'], 'notNull' => !$mapping['nullable']];
         $oclass->addProperty($name, $mapping['type'], $options);
     }
     foreach ($class->associationMappings as $mapping) {
         if (isset($mapping['inherited'])) {
             continue;
         }
         if (isset($mapping['direction'])) {
             // no in / outgoing references
             continue;
         }
         $name = $mapping['name'];
         if (isset($mapping['targetDoc'])) {
             $linkedClass = $this->_dm->getClassMetadata($mapping['targetDoc'])->orientClass;
         } else {
             $linkedClass = null;
         }
         $options = ['notNull' => !$mapping['nullable'], 'linkedClass' => $linkedClass];
         $oclass->addProperty($name, $mapping['type'], $options);
     }
 }
 /**
  * Finds objects by a set of criteria.
  *
  * Optionally sorting and limiting details can be passed. An implementation may throw
  * an UnexpectedValueException if certain values of the sorting or limiting details are
  * not supported.
  *
  * @param array      $criteria
  * @param array|null $orderBy
  * @param int|null   $limit
  * @param int|null   $offset
  * @param string     $fetchPlan
  *
  * @return ArrayCollection The objects.
  * @throws OrientDBException
  */
 public function findBy(array $criteria, array $orderBy = [], $limit = null, $offset = null, $fetchPlan = '*:0')
 {
     $parts[] = sprintf('SELECT FROM %s', $this->metadata->getOrientClass());
     if ($criteria) {
         $where = [];
         foreach ($criteria as $key => $value) {
             $value = json_encode($value);
             $where[] = "{$key} = {$value}";
         }
         $parts[] = sprintf('WHERE %s', implode(' AND ', $where));
     }
     if ($orderBy) {
         $orders = [];
         foreach ($orderBy as $key => $order) {
             $orders[] = "{$key} {$order}";
         }
         $parts[] = sprintf('ORDER BY %s', implode(', ', $orders));
     }
     if ($limit) {
         $parts[] = "LIMIT " . $limit;
     }
     $select = implode(' ', $parts);
     $collection = $this->dm->query($select, $fetchPlan);
     if (!$collection instanceof ArrayCollection) {
         throw new OrientDBException("Problems executing the query \"{$select}\". " . "The server returned {$collection} instead of ArrayCollection.");
     }
     return $collection;
 }
 /**
  * Creates a connection to the test database, if there is none yet, and
  * creates the necessary tables.
  */
 protected function setUp()
 {
     if (!$this->dm) {
         $this->dm = $this->createDocumentManager(['binding' => self::$_b]);
         $this->schemaTool = new SchemaTool($this->dm);
     }
     $prime = [];
     $classes = [];
     foreach ($this->usedModelSets as $setName => $bool) {
         foreach (static::$_modelSets[$setName] as $className) {
             $prime[$setName][] = $this->dm->getClassMetadata($className);
         }
         if (!isset(static::$_classesCreated[$setName])) {
             $classes = array_merge($classes, $prime[$setName]);
             static::$_classesCreated[$setName] = true;
         }
     }
     if ($classes) {
         $this->schemaTool->createSchema($classes);
     }
 }
 /**
  * @depends detach_will_remove_existing_managed_document
  * @test
  */
 public function getDocumentState_returns_STATE_DETACHED_for_existing_document()
 {
     $uow = $this->manager->getUnitOfWork();
     $c = new Contact();
     $c->rid = "#1:1";
     $c->name = "Sydney";
     $uow->registerManaged($c, $c->rid, $uow->getDocumentActualData($c));
     $dp = $this->prophesize(DocumentPersister::class);
     $dp->exists($c)->willReturn(true);
     $uow->setDocumentPersister(Contact::class, $dp->reveal());
     $uow->detach($c);
     $this->assertEquals($uow::STATE_DETACHED, $uow->getDocumentState($c));
 }
 /**
  * @test
  */
 public function getDocumentChangeSet_includes_embedded_list_for_new()
 {
     $uow = $this->manager->getUnitOfWork();
     $c = new Contact();
     $this->manager->persist($c);
     $c->name = "Sydney";
     $phone = new Phone();
     $phone->type = "work";
     $phone->phoneNumber = "4804441919";
     $c->phones[] = $phone;
     $md = $this->manager->getClassMetadata(Contact::class);
     $uow->computeChangeSet($md, $c);
     $cs = $uow->getDocumentChangeSet($c);
     $this->assertEquals(['name', 'email', 'phones'], array_keys($cs));
 }
 /**
  * @inheritdoc
  */
 public function hydrate($document, $data, array $hints = [])
 {
     $metadata = $this->dm->getClassMetadata(get_class($document));
     // Invoke preLoad lifecycle events and listeners
     //        if ( ! empty($metadata->lifecycleCallbacks[Events::preLoad])) {
     //            $args = array(&$data);
     //            $metadata->invokeLifecycleCallbacks(Events::preLoad, $document, $args);
     //        }
     //        if ($this->evm->hasListeners(Events::preLoad)) {
     //            $this->evm->dispatchEvent(Events::preLoad, new PreLoadEventArgs($document, $this->dm, $data));
     //        }
     $data = $this->getHydratorFor($metadata->name)->hydrate($document, $data, $hints);
     if ($document instanceof Proxy) {
         $document->__isInitialized__ = true;
     }
     // Invoke the postLoad lifecycle callbacks and listeners
     //        if ( ! empty($metadata->lifecycleCallbacks[Events::postLoad])) {
     //            $metadata->invokeLifecycleCallbacks(Events::postLoad, $document);
     //        }
     //        if ($this->evm->hasListeners(Events::postLoad)) {
     //            $this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($document, $this->dm));
     //        }
     return $data;
 }
 /**
  * @test
  */
 public function getDocumentChangeSet_update_nulls_linked()
 {
     $c = new Contact();
     $c->name = "Sydney";
     $c->rid = "#1:1";
     $e = new EmailAddress();
     $e->rid = "#2:1";
     $e->type = "work";
     $e->email = "*****@*****.**";
     $c->setEmail($e);
     $e->contact = $c;
     $uow = $this->manager->getUnitOfWork();
     $uow->registerManaged($c, $c->rid, ['rid' => $c->rid, 'name' => 'Sydney', 'email' => $e]);
     $uow->registerManaged($e, $e->rid, ['rid' => $e->rid, 'type' => 'home', 'email' => '*****@*****.**', 'contact' => $c]);
     $c->setEmail(null);
     $uow->computeChangeSets();
     $cs = $uow->getDocumentChangeSet($c);
     $this->assertEquals(['email'], array_keys($cs));
     $this->assertEquals([$e, null], $cs['email']);
 }
 private function loadEmbedCollection(PersistentCollection $collection)
 {
     $data = $collection->getData();
     if (count($data) === 0) {
         return;
     }
     if (is_array($data)) {
         $mapping = $collection->getMapping();
         $useKey = boolval($mapping['association'] & ClassMetadata::ASSOCIATION_USE_KEY);
         $metadata = $this->dm->getClassMetadata($mapping['targetDoc']);
         foreach ($data as $key => $v) {
             $document = $metadata->newInstance();
             $data = $this->hydratorFactory->hydrate($document, $v);
             $this->uow->registerManaged($document, null, $data);
             if ($useKey) {
                 $collection->set($key, $document);
             } else {
                 $collection->add($document);
             }
         }
     }
 }
 /**
  * @before
  */
 public function before()
 {
     $this->manager = $this->createDocumentManager([], ['test/Doctrine/ODM/OrientDB/Tests/Document/Stub/Simple']);
     $this->metadataFactory = $this->manager->getMetadataFactory();
 }
Esempio n. 13
0
<?php

use Symfony\Component\ClassLoader\UniversalClassLoader;
use Doctrine\OrientDB\Binding\HttpBinding;
use Doctrine\OrientDB\Binding\BindingParameters;
use Doctrine\ODM\OrientDB as ODM;
require __DIR__ . '/../autoload.php';
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array('Domain' => __DIR__ . '/../examples/'));
$loader->register();
$parameters = BindingParameters::create('http://*****:*****@127.0.0.1:2480/menu');
$binding = new HttpBinding($parameters);
$mapper = new ODM\Mapper(__DIR__ . '/../examples/proxies');
$mapper->setDocumentDirectories(array(__DIR__ . '/../examples/' => 'Domain'));
$manager = new ODM\DocumentManager($mapper, $binding);
$menus = $manager->getRepository('Domain\\Menu');
foreach ($menus->findAll() as $menu) {
    echo "Menu: ", $menu->getTitle(), "\n";
    foreach ($menu->getLinks() as $link) {
        // object inheriting from Link
        echo "Link \"{$link->getTitle()}\" ====>>> {$link->getLink()}\n";
    }
}
Esempio n. 14
0
 /**
  * @return PersisterInterface
  * @throws \Exception
  */
 private function createPersister()
 {
     return new SQLBatchPersister($this->dm->getMetadataFactory(), $this->dm->getBinding());
 }