本文整理汇总了PHP中Symfony\Component\Serializer\SerializerInterface类的典型用法代码示例。如果您正苦于以下问题:PHP SerializerInterface类的具体用法?PHP SerializerInterface怎么用?PHP SerializerInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SerializerInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: let
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');
}
示例2: processRequest
/**
* {@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 [];
}
示例3: testNormalize
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')
);
}
示例4: collect
/**
* {@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));
}
示例5: normalizeDecimal
/**
* 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);
}
示例6: __invoke
/**
* 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;
}
示例7: onKernelView
/**
* 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);
}
示例8: __invoke
/**
* 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;
}
示例9: normalize
/**
* {@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;
}
示例10: get
/**
* @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);
}
示例11: normalize
/**
* {@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;
}
示例12: current
/**
* {@inheritdoc}
*/
public function current()
{
$result = parent::current();
if ($result !== null && $this->serializer) {
$result = $this->serializer->deserialize($result, $this->itemType, null, $this->deserializeContext);
}
return $result;
}
示例13: testCircularNormalize
/**
* @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()));
}
示例14: normalize
/**
* {@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;
}
示例15: __invoke
/**
* 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;
}