php Symfony-Component-Serializer-SerializerInterface类(方法)实例源码

下面列出了php Symfony-Component-Serializer-SerializerInterface 类(方法)源码代码实例,从而了解它的用法。

作者:javiersanto    项目:pim-community-de   
function let(SerializerInterface $serializer, AbstractAttribute $simpleAttribute)
 {
     $serializer->implement('Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface');
     $this->setSerializer($serializer);
     $simpleAttribute->isLocalizable()->willReturn(false);
     $simpleAttribute->isScopable()->willReturn(false);
     $simpleAttribute->getCode()->willReturn('simple');
 }

作者:Jbartsc    项目:travelbruh-ap   
/**
  * {@inheritdoc}
  */
 public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer)
 {
     if ($serializer instanceof DecoderInterface) {
         $content = $serializer->decode($request->getContent(), $request->getContentType());
     } else {
         throw new HttpException(500, $this->t("The appropriate DecoderInterface was not found."));
     }
     if (!isset($content)) {
         throw new HttpException(500, $this->t("The content of the request was empty."));
     }
     $flood_config = $this->configFactory->get('user.flood');
     $username = $content['username'];
     $password = $content['password'];
     // Flood protection: this is very similar to the user login form code.
     // @see \Drupal\user\Form\UserLoginForm::validateAuthentication()
     // Do not allow any login from the current user's IP if the limit has been
     // reached. Default is 50 failed attempts allowed in one hour. This is
     // independent of the per-user limit to catch attempts from one IP to log
     // in to many different user accounts.  We have a reasonably high limit
     // since there may be only one apparent IP for all users at an institution.
     if ($this->flood->isAllowed('services.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
         $accounts = $this->entityManager->getStorage('user')->loadByProperties(array('name' => $username, 'status' => 1));
         $account = reset($accounts);
         if ($account) {
             if ($flood_config->get('uid_only')) {
                 // Register flood events based on the uid only, so they apply for any
                 // IP address. This is the most secure option.
                 $identifier = $account->id();
             } else {
                 // The default identifier is a combination of uid and IP address. This
                 // is less secure but more resistant to denial-of-service attacks that
                 // could lock out all users with public user names.
                 $identifier = $account->id() . '-' . $request->getClientIP();
             }
             // Don't allow login if the limit for this user has been reached.
             // Default is to allow 5 failed attempts every 6 hours.
             if ($this->flood->isAllowed('services.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
                 $uid = $this->userAuth->authenticate($username, $password);
                 if ($uid) {
                     $this->flood->clear('services.failed_login_user', $identifier);
                     $this->session->start();
                     user_login_finalize($account);
                     drupal_set_message(t('User succesffully logged in'), 'status', FALSE);
                     return ['id' => $this->session->getId(), 'name' => $this->session->getName()];
                     //return $this->entityManager->getStorage('user')->load($uid);
                 } else {
                     // Register a per-user failed login event.
                     $this->flood->register('services.failed_login_user', $flood_config->get('user_window'), $identifier);
                 }
             }
         }
     }
     // Always register an IP-based failed login event.
     $this->flood->register('services.failed_login_ip', $flood_config->get('ip_window'));
     return [];
 }

作者:Jbartsc    项目:travelbruh-ap   
/**
  * {@inheritdoc}
  *
  * @return \Drupal\Core\Entity\EntityInterface|array
  */
 public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer)
 {
     // Unserialize the content of the request if there is any.
     $content = $request->getContent();
     if (!empty($content)) {
         $entity_type_id = $this->getDerivativeId();
         /** @var $entity_type \Drupal\Core\Entity\EntityTypeInterface */
         $entity_type = $this->manager->getDefinition($entity_type_id);
         return $serializer->deserialize($content, $entity_type->getClass(), $request->getContentType(), ['entity_type' => $entity_type_id]);
     }
     return [];
 }

作者:ninvfen    项目:symfon   
public function testNormalize()
    {
        $obj = new GetSetDummy();
        $object = new \stdClass();
        $obj->setFoo('foo');
        $obj->setBar('bar');
        $obj->setBaz(true);
        $obj->setCamelCase('camelcase');
        $obj->setObject($object);

        $this->serializer
            ->expects($this->once())
            ->method('normalize')
            ->with($object, 'any')
            ->will($this->returnValue('string_object'))
        ;

        $this->assertEquals(
            array(
                'foo' => 'foo',
                'bar' => 'bar',
                'baz' => true,
                'fooBar' => 'foobar',
                'camelCase' => 'camelcase',
                'object' => 'string_object',
            ),
            $this->normalizer->normalize($obj, 'any')
        );
    }

作者:deuz    项目:request-collector-bundl   
/**
  * {@inheritdoc}
  */
 public function collect(RequestObject $requestObject, array $parameters = [])
 {
     $parameters = $this->resolveCollectorParameters($parameters);
     $logFile = sprintf('%s/%s.%s', $this->logFolder, $this->kernelEnvironment, $parameters['logFile']);
     $this->logger->pushHandler(new StreamHandler($logFile));
     $this->logger->info('request_collector.collect', $this->serializer->normalize($requestObject));
 }

作者:alexisfroge    项目:pim-community-de   
/**
  * Normalize a decimal attribute value
  *
  * @param mixed  $data
  * @param string $format
  * @param array  $context
  *
  * @return mixed|null
  */
 protected function normalizeDecimal($data, $format, $context)
 {
     if (false === is_numeric($data)) {
         return $this->serializer->normalize($data, $format, $context);
     }
     return floatval($data);
 }

作者:partkeep    项目:PartKeep   
/**
  * Create a new item.
  *
  * @param Request    $request
  * @param string|int $id
  *
  * @throws NotFoundHttpException
  * @throws RuntimeException
  * @throws UserProtectedException
  * @throws UserLimitReachedException
  *
  * @return mixed
  */
 public function __invoke(Request $request, $id)
 {
     /**
      * @var $resourceType ResourceInterface
      */
     list($resourceType, $format) = $this->extractAttributes($request);
     /*
      * Workaround to ensure stockLevels are not overwritten in a PUT request.
      * @see https://github.com/partkeepr/PartKeepr/issues/551
      */
     $data = json_decode($request->getContent(), true);
     if (array_key_exists('stockLevels', $data)) {
         unset($data['stockLevels']);
     }
     $requestData = json_encode($data);
     $data = $this->getItem($this->dataProvider, $resourceType, $id);
     $context = $resourceType->getDenormalizationContext();
     $context['object_to_populate'] = $data;
     /**
      * @var $part Part
      */
     $part = $this->serializer->deserialize($requestData, $resourceType->getEntityClass(), $format, $context);
     if (!$this->partService->isInternalPartNumberUnique($part->getInternalPartNumber(), $part)) {
         throw new InternalPartNumberNotUniqueException();
     }
     return $part;
 }

作者:akom    项目:DunglasApiBundl   
/**
  * In an API context, converts any data to a XML response.
  *
  * @param GetResponseForControllerResultEvent $event
  *
  * @return Response|mixed
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $controllerResult = $event->getControllerResult();
     if ($controllerResult instanceof Response) {
         return $controllerResult;
     }
     $request = $event->getRequest();
     $format = $request->attributes->get('_api_format');
     if (self::FORMAT !== $format) {
         return $controllerResult;
     }
     switch ($request->getMethod()) {
         case Request::METHOD_POST:
             $status = 201;
             break;
         case Request::METHOD_DELETE:
             $status = 204;
             break;
         default:
             $status = 200;
             break;
     }
     $resourceType = $request->attributes->get('_resource_type');
     $response = new Response($this->serializer->serialize($controllerResult, self::FORMAT, $resourceType->getNormalizationContext()), $status, ['Content-Type' => 'application/xml']);
     $event->setResponse($response);
 }

作者:partkeep    项目:PartKeep   
/**
  * Create a new item.
  *
  * @param Request    $request
  * @param string|int $id
  *
  * @throws NotFoundHttpException
  * @throws RuntimeException
  * @throws UserProtectedException
  * @throws UserLimitReachedException
  *
  * @return mixed
  */
 public function __invoke(Request $request, $id)
 {
     /**
      * @var ResourceInterface
      */
     list($resourceType, $format) = $this->extractAttributes($request);
     /**
      * @var User
      */
     $data = $this->getItem($this->dataProvider, $resourceType, $id);
     $context = $resourceType->getDenormalizationContext();
     $context['object_to_populate'] = $data;
     if ($data->isProtected()) {
         throw new UserProtectedException();
     }
     $data = $this->serializer->deserialize($request->getContent(), $resourceType->getEntityClass(), $format, $context);
     if ($data->isActive()) {
         if ($this->userService->checkUserLimit()) {
             throw new UserLimitReachedException();
         }
     }
     $this->userService->syncData($data);
     $data->setNewPassword('');
     $data->setPassword('');
     $data->setLegacy(false);
     return $data;
 }

作者:javiersanto    项目:pim-community-de   
/**
  * {@inheritdoc}
  */
 public function normalize($entity, $format = null, array $context = [])
 {
     $data = $entity->getData();
     $fieldName = $this->getFieldValue($entity);
     $result = null;
     if (is_array($data)) {
         $data = new ArrayCollection($data);
     }
     if (is_null($data)) {
         $result = [$fieldName => ''];
     } elseif (is_int($data)) {
         $result = [$fieldName => (string) $data];
     } elseif (is_float($data)) {
         $result = [$fieldName => sprintf(sprintf('%%.%sF', $this->precision), $data)];
     } elseif (is_string($data)) {
         $result = [$fieldName => $data];
     } elseif (is_bool($data)) {
         $result = [$fieldName => (string) (int) $data];
     } elseif (is_object($data)) {
         $context['field_name'] = $fieldName;
         $result = $this->serializer->normalize($data, $format, $context);
     }
     if (null === $result) {
         throw new \RuntimeException(sprintf('Cannot normalize product value "%s" which data is a(n) "%s"', $fieldName, is_object($data) ? get_class($data) : gettype($data)));
     }
     return $result;
 }

作者:bangpoun    项目:oembe   
/**
  * @param $url
  * @param array $params
  *
  * @return array
  */
 public function get($url, $params = array())
 {
     $request = $this->provider->request($url, $params);
     $response = $this->client->send($request);
     $data = $response->getBody()->getContents();
     $format = $this->getFormat($params, $response);
     return $this->serializer->deserialize($data, null, $format);
 }

作者:noglitchy    项目:pim-community-de   
/**
  * {@inheritdoc}
  */
 public function normalize($object, $format = null, array $context = array())
 {
     $normalizedItems = [];
     foreach ($object as $item) {
         $normalizedItems[$item->getLocale()] = $this->serializer->normalize($item, $format, $context);
     }
     return $normalizedItems;
 }

作者:florinmatthe    项目:zoho-integration-bundl   
/**
  * {@inheritdoc}
  */
 public function current()
 {
     $result = parent::current();
     if ($result !== null && $this->serializer) {
         $result = $this->serializer->deserialize($result, $this->itemType, null, $this->deserializeContext);
     }
     return $result;
 }

作者:symfon    项目:symfon   
/**
  * @expectedException \Symfony\Component\Serializer\Exception\CircularReferenceException
  */
 public function testCircularNormalize()
 {
     $this->normalizer->setCircularReferenceLimit(1);
     $this->serializer->expects($this->once())->method('normalize')->will($this->returnCallback(function ($data, $format, $context) {
         $this->normalizer->normalize($data['qux'], $format, $context);
         return 'string_object';
     }));
     $this->assertEquals('string_object', $this->normalizer->normalize(new JsonSerializableDummy()));
 }

作者:a2xchi    项目:pim-community-de   
/**
  * {@inheritdoc}
  */
 public function normalize($entity, $format = null, array $context = [])
 {
     $data = $entity->getData();
     $fieldName = $this->getFieldName($entity);
     if ($this->filterLocaleSpecific($entity)) {
         return [];
     }
     $result = null;
     if (is_array($data)) {
         $data = new ArrayCollection($data);
     }
     $type = $entity->getAttribute()->getAttributeType();
     $backendType = $entity->getAttribute()->getBackendType();
     if (AttributeTypes::BOOLEAN === $type) {
         $result = [$fieldName => (string) (int) $data];
     } elseif (is_null($data)) {
         $result = [$fieldName => ''];
         if ('metric' === $backendType) {
             $result[$fieldName . '-unit'] = '';
         }
     } elseif (is_int($data)) {
         $result = [$fieldName => (string) $data];
     } elseif (is_float($data) || 'decimal' === $entity->getAttribute()->getBackendType()) {
         $pattern = $entity->getAttribute()->isDecimalsAllowed() ? sprintf('%%.%sF', $this->precision) : '%d';
         $result = [$fieldName => sprintf($pattern, $data)];
     } elseif (is_string($data)) {
         $result = [$fieldName => $data];
     } elseif (is_object($data)) {
         // TODO: Find a way to have proper currency-suffixed keys for normalized price data
         // even when an empty collection is passed
         if ('prices' === $backendType && $data instanceof Collection && $data->isEmpty()) {
             $result = [];
         } elseif ('options' === $backendType && $data instanceof Collection && $data->isEmpty() === false) {
             $data = $this->sortOptions($data);
             $context['field_name'] = $fieldName;
             $result = $this->serializer->normalize($data, $format, $context);
         } else {
             $context['field_name'] = $fieldName;
             if ('metric' === $backendType) {
                 $context['decimals_allowed'] = $entity->getAttribute()->isDecimalsAllowed();
             } elseif ('media' === $backendType) {
                 $context['value'] = $entity;
             }
             $result = $this->serializer->normalize($data, $format, $context);
         }
     }
     if (null === $result) {
         throw new \RuntimeException(sprintf('Cannot normalize product value "%s" which data is a(n) "%s"', $fieldName, is_object($data) ? get_class($data) : gettype($data)));
     }
     $localizer = $this->localizerRegistry->getLocalizer($type);
     if (null !== $localizer) {
         foreach ($result as $field => $data) {
             $result[$field] = $localizer->localize($data, $context);
         }
     }
     return $result;
 }

作者:Pask    项目:DunglasApiBundl   
/**
  * Create a new item.
  *
  * @param Request    $request
  * @param string|int $id
  *
  * @return mixed
  *
  * @throws NotFoundHttpException
  * @throws RuntimeException
  */
 public function __invoke(Request $request, $id)
 {
     list($resourceType, $format) = $this->extractAttributes($request);
     $data = $this->getItem($this->dataProvider, $resourceType, $id);
     $context = $resourceType->getDenormalizationContext();
     $context['object_to_populate'] = $data;
     $data = $this->serializer->deserialize($request->getContent(), $resourceType->getEntityClass(), $format, $context);
     return $data;
 }

作者:aWEBoLab    项目:tax   
/**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     $this->normalizer = new EntityReferenceFieldItemNormalizer();
     $this->serializer = $this->prophesize(Serializer::class);
     // Set up the serializer to return an entity property.
     $this->serializer->normalize(Argument::cetera())->willReturn(['value' => 'test']);
     $this->normalizer->setSerializer($this->serializer->reveal());
     $this->fieldItem = $this->prophesize(EntityReferenceItem::class);
     $this->fieldItem->getIterator()->willReturn(new \ArrayIterator(['target_id' => []]));
 }

作者:koala-framewor    项目:koala-framewor   
public function normalize(Kwf_Model_Row_Interface $row, $column, array $settings, $format = null, array $context = array())
 {
     if (!isset($settings['rule'])) {
         throw new \Exception("rule setting is required");
     }
     $rows = $row->getChildRows($settings['rule']);
     if (isset($settings['groups'])) {
         $context['groups'] = $settings['groups'];
     }
     return $this->serializer->normalize($rows, $format, $context);
 }

作者:ashutosh-srija    项目:findit_akene   
/**
  * {@inheritdoc}
  */
 public function process($item)
 {
     if ($this->converter) {
         $item = $this->converter->convertToImportFormat($item);
     }
     $object = $this->serializer->deserialize($item, $this->context->getOption('entityName'), null);
     if ($this->strategy) {
         $object = $this->strategy->process($object);
     }
     return $object ?: null;
 }

作者:fulcrum3    项目:PartKeep   
/**
  * Injects the specific root node ID if "@local-tree-root" was specified
  *
  * @param Request $request
  *
  * @return mixed
  *
  * @throws RuntimeException
  * @throws PartLimitExceededException
  */
 public function __invoke(Request $request)
 {
     /**
      * @var $resourceType ResourceInterface
      */
     if ($this->partService->checkPartLimit()) {
         throw new PartLimitExceededException();
     }
     list($resourceType, $format) = $this->extractAttributes($request);
     return $this->serializer->deserialize($request->getContent(), $resourceType->getEntityClass(), $format, $resourceType->getDenormalizationContext());
 }


问题


面经


文章

微信
公众号

扫码关注公众号