コード例 #1
0
 /**
  * Extract values from an object
  *
  * @param  object $object
  * @throws \Zf2Libs\Stdlib\Extractor\Exception\InvalidArgumentException
  * @return array
  */
 public function extract($object)
 {
     if (!$object instanceof ImageInterface) {
         throw new InvalidArgumentException("Invalid object must be instance of ImageInterface");
     }
     return $this->hydrator->extract($object);
 }
コード例 #2
0
ファイル: ZendDbSqlMapper.php プロジェクト: conor123/ZF2Demo
 /**
  * @param PostInterface $postObject
  * @return PostInterface
  * @throws \Exception
  */
 public function save(PostInterface $postObject)
 {
     //
     $postData = $this->hydrator->extract($postObject);
     unset($postData['id']);
     if ($postObject->getId()) {
         # code...
         $action = new Update('posts');
         $action->set($postData);
         $action->where(array('id = ?' => $postObject->getId()));
     } else {
         $action = new Insert('posts');
         $action->values($postData);
     }
     $sql = new Sql($this->dbAdapter);
     $stmt = $sql->prepareStatementForSqlObject($action);
     $result = $stmt->execute();
     if ($result instanceof ResultInterface) {
         # code...
         if ($newId = $result->getGeneratedValue()) {
             # code...
             $postObject->setId($newId);
         }
         return $postObject;
     }
     throw new \Exception("Database eror");
 }
コード例 #3
0
 /**
  * @param PostInterface $postObject
  *
  * @return PostInterface
  * @throws \Exception
  */
 public function save(PostInterface $postObject)
 {
     $postData = $this->hydrator->extract($postObject);
     unset($postData['id']);
     //Neither Insert nor Update needs the ID in the array
     if ($postObject->getId()) {
         //ID present, it's an update
         $action = new Update('post');
         $action->set($postData);
         $action->where(array('id = ?' => $postObject->getId()));
     } else {
         // ID not present, it's an Insert
         $action = new Insert('post');
         $action->values($postData);
     }
     $sql = new Sql($this->dbAdapter);
     $stmt = $sql->prepateStatementForSqlObject($action);
     $result = $stmt->execute();
     if ($result instanceof ResultInterface) {
         if ($newId = $result->getGeneratedValue()) {
             //when a value has been generated, set it on the object
             $postObject->setId($newId);
         }
         return $postObject;
     }
     throw new \Exception("Database error");
 }
コード例 #4
0
 /**
  * @return object Returns hydrated clone of $prototype
  */
 public function current()
 {
     $currentValue = parent::current();
     $object = clone $this->prototype;
     $this->hydrator->hydrate($currentValue, $object);
     return $object;
 }
コード例 #5
0
 /**
  * Получает данные о курсе через gateway и возвращает гидрированную entity
  * @param AbstractGateway $gateway
  * @param string $entityClass
  * @return Currency
  */
 private function get(AbstractGateway $gateway, $entityClass)
 {
     $result = $gateway->get();
     $entity = new $entityClass();
     $this->hydrator->hydrate($result, $entity);
     return $entity;
 }
コード例 #6
0
 /**
  * Hydrate $object with the provided $data.
  *
  * @param array  $data
  * @param object $object
  *
  * @return object
  */
 public function hydrate(array $data, $object)
 {
     // Zend hydrator:
     if ($this->hydrateService instanceof HydratorInterface) {
         return $this->hydrateService->hydrate($data, $object);
     }
     // Doctrine hydrator: (parameters switched)
     return $this->hydrateService->hydrate($object, $data);
 }
コード例 #7
0
 /**
  * Hydrate $object with the provided $data.
  *
  * @param  array $data
  * @param  object $object
  * @return object
  */
 public function hydrate(array $data, $object)
 {
     $customer = null;
     $this->hydrator->hydrate($data, $object);
     if (isset($data['customer']) && isset($data['customer']['id'])) {
         $data['customer'] = $this->customerRepository->getById($data['customer']['id']);
     }
     return $this->hydrator->hydrate($data, $object);
 }
コード例 #8
0
 /**
  * @param \Doctrine\Common\Persistence\ObjectManager $objectManager
  * @param \Zend\Stdlib\Hydrator\HydratorInterface $hydrator
  * @param \Phpro\Apigility\Doctrine\Bulk\Event\BulkEvent $event
  */
 public function it_should_handle_create_events($objectManager, $hydrator, $event)
 {
     $this->mockSaveEntity($objectManager);
     $event->getParams()->willReturn([]);
     $hydrator->hydrate([], Argument::type('stdClass'))->shouldBeCalled();
     $event->stopPropagation(true)->shouldBeCalled();
     $result = $this->create($event);
     $result->shouldBeAnInstanceOf('Phpro\\Apigility\\Doctrine\\Bulk\\Model\\Result');
 }
コード例 #9
0
 /**
  * @covers \Zend\Stdlib\Hydrator\Aggregate\HydratorListener::onExtract
  */
 public function testOnExtract()
 {
     $object = new stdClass();
     $data = array('foo' => 'bar');
     $event = $this->getMockBuilder('Zend\\Stdlib\\Hydrator\\Aggregate\\ExtractEvent')->disableOriginalConstructor()->getMock();
     $event->expects($this->any())->method('getExtractionObject')->will($this->returnValue($object));
     $this->hydrator->expects($this->once())->method('extract')->with($object)->will($this->returnValue($data));
     $event->expects($this->once())->method('mergeExtractedData')->with($data);
     $this->assertSame($data, $this->listener->onExtract($event));
 }
コード例 #10
0
 /**
  * @param AbstractEntity $entity
  * @return $this
  */
 public function persist(AbstractEntity $entity)
 {
     $data = $this->hydrator->extract($entity);
     if ($this->hasIdentity($entity)) {
         $this->gateway->update($data, ['id' => $entity->getId()]);
     } else {
         $this->gateway->insert($data);
         $entity->setId($this->gateway->getLastInsertValue());
     }
     return $this;
 }
コード例 #11
0
 /**
  * @param array $data
  * @param Order $order
  * @return Order
  */
 public function hydrate(array $data, $order)
 {
     if (isset($data['customer']) && isset($data['customer']['id'])) {
         if (empty($data['customer']['id'])) {
             unset($data['customer']);
         } else {
             $data['customer'] = $this->customerRepository->getById($data['customer']['id']);
         }
     }
     return $this->wrappedHydrator->hydrate($data, $order);
 }
コード例 #12
0
 /**
  * Override getItems()
  *
  * Overrides getItems() to return a collection of entities based on the
  * provided Hydrator and entity prototype, if available.
  *
  * @param int $offset
  * @param int $itemCountPerPage
  * @return array
  */
 public function getItems($offset, $itemCountPerPage)
 {
     $set = parent::getItems($offset, $itemCountPerPage);
     if (!$this->hydrator instanceof HydratorInterface) {
         return $set;
     }
     $collection = array();
     foreach ($set as $item) {
         $collection[] = $this->hydrator->hydrate($item, clone $this->entityPrototype);
     }
     return $collection;
 }
コード例 #13
0
 /**
  * @param $command
  * @param $entity
  * @param bool $addExtractedEntity
  *
  * @return Result
  */
 protected function createResult($command, $entity, $addExtractedEntity = true)
 {
     $meta = $this->objectManager->getClassMetadata($this->className);
     $identifiers = $meta->getIdentifierValues($entity);
     $result = new Result($command, current($identifiers));
     if (!$addExtractedEntity) {
         return $result;
     }
     $data = $this->hydrator->extract($entity);
     $result->addParams(['item' => $data]);
     return $result;
 }
コード例 #14
0
 /**
  * @param int|string $id
  * @return PostInterface
  * @throws \InvalidArgumentException
  */
 public function find($id)
 {
     $sql = new Sql($this->dbAdapter);
     $select = $sql->select('posts');
     $select->where(array('id = ?' => $id));
     $stmt = $sql->prepareStatementForSqlObject($select);
     $result = $stmt->execute();
     if ($result instanceof ResultInterface && $result->isQueryResult() && $result->getAffectedRows()) {
         return $this->hydrator->hydrate($result->current(), $this->postPrototype);
     }
     throw new \InvalidArgumentException("Blog with given ID: {$id} not found");
 }
コード例 #15
0
 public function testHydratingObjects()
 {
     $this->hydrator->addStrategy('entities', new TestAsset\HydratorStrategy());
     $entityA = new TestAsset\HydratorStrategyEntityA();
     $entityA->addEntity(new TestAsset\HydratorStrategyEntityB(111, 'AAA'));
     $entityA->addEntity(new TestAsset\HydratorStrategyEntityB(222, 'BBB'));
     $attributes = $this->hydrator->extract($entityA);
     $attributes['entities'][] = 333;
     $this->hydrator->hydrate($attributes, $entityA);
     $entities = $entityA->getEntities();
     $this->assertCount(3, $entities);
 }
コード例 #16
0
 /**
  * (non-PHPdoc)
  * @see Zend\Stdlib\Hydrator.HydratorInterface::hydrate()
  */
 public function hydrate(array $data, $object)
 {
     if (!$object instanceof ItemInterface) {
         throw new InvalidArgumentException('Can only extract ItemInterface.');
     }
     if (isset($data[self::KEY_ITEM])) {
         $this->itemHydrator->hydrate($data[self::KEY_ITEM], $object);
     }
     if (isset($data[self::KEY_META])) {
         $this->metaHydrator->hydrate($data[self::KEY_META], $object);
     }
     return $object;
 }
コード例 #17
0
ファイル: HydratingResultSet.php プロジェクト: tillk/vufind
 /**
  * Iterator: get current item
  *
  * @return object
  */
 public function current()
 {
     if ($this->buffer === null) {
         $this->buffer = -2;
         // implicitly disable buffering from here on
     } elseif (is_array($this->buffer) && isset($this->buffer[$this->position])) {
         return $this->buffer[$this->position];
     }
     $data = $this->dataSource->current();
     $object = is_array($data) ? $this->hydrator->hydrate($data, clone $this->objectPrototype) : false;
     if (is_array($this->buffer)) {
         $this->buffer[$this->position] = $object;
     }
     return $object;
 }
コード例 #18
0
ファイル: Course.php プロジェクト: Mesoptier/gewisweb
 /**
  * Get more information from a course.
  *
  * @param SimpleXMLElement $course
  *
  * @return SimpleXMLElement Course info
  */
 protected function getCourseInfo($course)
 {
     $year = $course->LaatsteStudiejaarGegeven->__toString();
     $year = empty($year) ? '2013' : $year;
     $code = $course->ActCode->__toString();
     $course = $this->client->GeefVakGegevens($code, $year, 'NL');
     $studies = [];
     // first check if it actually is a study we want
     foreach ($course->DoelgroepBlokken->DoelgroepBlok as $blok) {
         foreach ($blok->Doelgroepen->Doelgroep as $doelgroep) {
             $name = $doelgroep->DoelgroepOmschr->__toString();
             if (isset($this->map[$name])) {
                 $studies[] = $this->map[$name];
             }
         }
     }
     if (empty($studies)) {
         return null;
     }
     // create the course
     $data = ['code' => $course->VakCode->__toString(), 'name' => $course->VakOmschr->__toString(), 'url' => $course->UrlStudiewijzer->__toString(), 'quartile' => 'q1', 'year' => $year, 'studies' => $studies];
     // get the children course codes
     $children = [];
     foreach ($course->VakOnderdelen->VakOnderdeel as $child) {
         $children[] = $child->OnderdeelVakcode->__toString();
     }
     return ['course' => $this->hydrator->hydrate($data, new CourseModel()), 'children' => $children];
 }
コード例 #19
0
 /**
  * Hydrate $object with the provided $data.
  *
  * @param  array $data
  * @param  object $object
  * @return object
  */
 public function hydrate(array $data, $object)
 {
     $order = null;
     if (isset($data['order'])) {
         $order = $this->wrappedHydrator->hydrate($data['order'], new Order());
         unset($data['order']);
     }
     if (isset($data['order_id'])) {
         $order = $this->orderRepository->getById($data['order_id']);
     }
     $object = $this->wrappedHydrator->hydrate($data, $object);
     if ($object) {
         $object->setOrder($order);
     }
     return $object;
 }
コード例 #20
0
 /**
  * Hydrate $object with the provided $data.
  *
  * @param  array  $data
  * @param  object $object
  * @throws \Exception
  * @return object
  */
 public function hydrate(array $data, $object)
 {
     $this->metadata = $this->objectManager->getClassMetadata(get_class($object));
     $object = $this->tryConvertArrayToObject($data, $object);
     foreach ($data as $field => &$value) {
         $value = $this->hydrateValue($field, $value);
         if ($value === null) {
             continue;
         }
         // @todo DateTime (and other types) conversion should be handled by doctrine itself in future
         if (in_array($this->metadata->getTypeOfField($field), array('datetime', 'time', 'date'))) {
             if (is_int($value)) {
                 $dt = new DateTime();
                 $dt->setTimestamp($value);
                 $value = $dt;
             } elseif (is_string($value)) {
                 $value = new DateTime($value);
             }
         }
         if ($this->metadata->hasAssociation($field)) {
             $target = $this->metadata->getAssociationTargetClass($field);
             if ($this->metadata->isSingleValuedAssociation($field)) {
                 $value = $this->toOne($value, $target);
             } elseif ($this->metadata->isCollectionValuedAssociation($field)) {
                 $value = $this->toMany($value, $target);
                 // Automatically merge collections using helper utility
                 $propertyRefl = $this->metadata->getReflectionClass()->getProperty($field);
                 $propertyRefl->setAccessible(true);
                 $previousValue = $propertyRefl->getValue($object);
                 $value = CollectionUtils::intersectUnion($previousValue, $value);
             }
         }
     }
     return $this->hydrator->hydrate($data, $object);
 }
コード例 #21
0
 public function testContextAwarenessHydrate()
 {
     $strategy = new TestAsset\HydratorStrategyContextAware();
     $this->hydrator->addStrategy('field2', $strategy);
     $entityB = new TestAsset\HydratorStrategyEntityB('X', 'Y');
     $data = array('field1' => 'A', 'field2' => 'B');
     $attributes = $this->hydrator->hydrate($data, $entityB);
     $this->assertEquals($data, $strategy->data);
 }
コード例 #22
0
 /**
  * @param Request $request
  * @param string $id
  * @return RedirectResponse|\Illuminate\View\View
  */
 public function newOrEditAction(Request $request, $id = '')
 {
     $viewModel = [];
     $customer = $id ? $this->customerRepository->getById($id) : new Customer();
     if ($request->getMethod() == 'POST') {
         $this->inputFilter->setData($request->request->all());
         if ($this->inputFilter->isValid()) {
             $this->hydrator->hydrate($this->inputFilter->getValues(), $customer);
             $this->customerRepository->begin()->persist($customer)->commit();
             Session::flash('success', 'Customer Saved');
             return new RedirectResponse('/customers/edit/' . $customer->getId());
         } else {
             $this->hydrator->hydrate($request->request->all(), $customer);
             $viewModel['error'] = $this->inputFilter->getMessages();
         }
     }
     $viewModel['customer'] = $customer;
     return view('customers/new-or-edit', $viewModel);
 }
コード例 #23
0
 public function newOrEditAction()
 {
     $id = $this->params()->fromRoute('id');
     $viewModel = new ViewModel();
     $customer = $id ? $this->customerRepository->getById($id) : new Customer();
     if ($this->getRequest()->isPost()) {
         $this->inputFilter->setData($this->params()->fromPost());
         if ($this->inputFilter->isValid()) {
             $customer = $this->hydrator->hydrate($this->inputFilter->getValues(), $customer);
             $this->customerRepository->begin()->persist($customer)->commit();
             $this->flashMessenger()->addSuccessMessage('Customer saved.');
             $this->redirect()->toUrl('/customers/edit/' . $customer->getId());
         } else {
             $this->hydrator->hydrate($this->params()->fromPost(), $customer);
             $viewModel->setVariable('errors', $this->inputFilter->getMessages());
         }
     }
     $viewModel->setVariable('customer', $customer);
     return $viewModel;
 }
コード例 #24
0
ファイル: PostMapper.php プロジェクト: qbonaventure/blog
 public function updatePost($values, $postId)
 {
     $values = $this->hydrator->extract($values);
     $encodedValue = json_encode($values);
     $sql = 'SELECT * FROM blog.post_update(:data::json)';
     $stmt = $this->dbAdapter->createStatement($sql);
     $result = $stmt->execute(array('data' => $encodedValue));
     $resultRow = $result->current();
     $newPostArray = json_decode($resultRow['post_update'], true);
     $newPostObject = $this->hydrator->hydrate($newPostArray, new Post());
     // 		$newPostObject	= $this->hydrator->hydrate($values, $this->postPrototype);
     return $newPostObject;
 }
コード例 #25
0
 /**
  * @param object|array $values
  * @return bool
  * @throws \Exception
  */
 public function update($values)
 {
     if (is_object($values)) {
         $values = $this->_hydrator->extract($values);
     }
     $values = array_intersect_key($values, $this->_class->getFields());
     $identifier = $this->_class->getIdentifier();
     $identifiers = array_intersect_key($values, $identifier);
     $result = $this->_em->getConnexionDriver()->updateItem($identifiers, $values, $this->_class);
     if (!$result) {
         throw new \Exception('Something wrong.');
     }
     return $this->_hydrator->hydrate($values, new $this->_entityName());
 }
コード例 #26
0
 /**
  * 
  * {@inheritDoc}
  */
 public function find($id)
 {
     $sql = new Sql($this->dbAdapter);
     $select = $sql->select($this->table);
     $select->where(array("{$this->idFieldName} = ?" => $id));
     $result = $this->fetch($sql, $select);
     if ($result && $result->getAffectedRows()) {
         return $this->hydrator->hydrate($result->current(), clone $this->objectPrototype);
     }
     try {
         return $this->fetchObject($sql, $select);
     } catch (\InvalidArgumentException $ex) {
         throw new \InvalidArgumentException("Object of table {$this->table} with id = {$id} not found");
     }
 }
コード例 #27
0
 /**
  * Hydrate $object with the provided $data.
  *
  * @param  array  $data
  * @param  object $object
  * @throws \Exception
  * @return object
  */
 public function hydrate(array $data, $object)
 {
     $this->metadata = $this->objectManager->getClassMetadata(get_class($object));
     foreach ($data as $field => &$value) {
         if ($this->metadata->hasAssociation($field)) {
             $target = $this->metadata->getAssociationTargetClass($field);
             if ($this->metadata->isSingleValuedAssociation($field)) {
                 $value = $this->toOne($value, $target);
             } elseif ($this->metadata->isCollectionValuedAssociation($field)) {
                 $value = $this->toMany($value, $target);
             }
         }
     }
     return $this->hydrator->hydrate($data, $object);
 }
コード例 #28
0
 /**
  * Iterator: get current item
  *
  * @return object
  */
 public function current()
 {
     $data = $this->dataSource->current();
     if (is_array($data)) {
         foreach ($data as $k => $v) {
             if (preg_match('/^(?<name>\\w+)ID$/', $k, $matches)) {
                 if (!property_exists($this->objectPrototype, $k)) {
                     $data[$matches['name']] = $v;
                     unset($data[$k]);
                 }
             }
         }
     }
     if ($this->objectPrototype instanceof ArrayObject) {
         if (is_array($data)) {
             return new ArrayObject($data);
         } elseif ($data instanceof ArrayObject) {
             return $data;
         }
     }
     $object = is_array($data) ? $this->hydrator->hydrate($data, clone $this->objectPrototype) : false;
     return $object;
 }
コード例 #29
0
ファイル: HydratingResultSet.php プロジェクト: haoyanfei/zf2
 /**
  * Iterator: get current item
  *
  * @return object
  */
 public function current()
 {
     $data = $this->dataSource->current();
     $object = clone $this->objectPrototype;
     return is_array($data) ? $this->hydrator->hydrate($data, $object) : false;
 }
コード例 #30
0
 /**
  * Callback to be used when {@see \Zend\Stdlib\Hydrator\Aggregate\ExtractEvent::EVENT_EXTRACT} is triggered
  *
  * @param \Zend\Stdlib\Hydrator\Aggregate\ExtractEvent $event
  *
  * @return array
  *
  * @internal
  */
 public function onExtract(ExtractEvent $event)
 {
     $data = $this->hydrator->extract($event->getExtractionObject());
     $event->mergeExtractedData($data);
     return $data;
 }