/**
  * @throws \Doctrine\ORM\ORMException
  */
 public function boot()
 {
     $this->serializer = SerializerBuilder::create()->setDebug($this->devMode)->build();
     $this->entityFolder->create();
     AnnotationRegistry::registerAutoloadNamespace('JMS\\Serializer\\Annotation', __DIR__ . '/../../../../vendor/jms/serializer/src');
     $proxyDoctrineFolder = new Folder(sys_get_temp_dir() . '/doctrine');
     $config = Setup::createAnnotationMetadataConfiguration([$this->entityFolder->absolute()], $this->isDevMode(), $proxyDoctrineFolder->absolute());
     if ($this->cache !== null) {
         $config->setQueryCacheImpl($this->getCache());
         $config->setResultCacheImpl($this->getCache());
     }
     $this->entityManager = $this->createEntityManager($config);
     $debugStack = new DebugStack();
     $this->entityManager->getConnection()->getConfiguration()->setSQLLogger($debugStack);
     if ($this->getFileCreation()->getContent() == 1) {
         return;
     }
     if ($proxyDoctrineFolder->isFolder()) {
         $proxyDoctrineFolder->removeFiles();
     }
     $tool = new SchemaTool($this->entityManager);
     $metadatas = $this->entityManager->getMetadataFactory()->getAllMetadata();
     $proxyDoctrineFolder->create();
     $this->entityManager->getProxyFactory()->generateProxyClasses($metadatas, $proxyDoctrineFolder->absolute());
     if ($this->cloudFoundryBoot->isInCloudFoundry()) {
         $tool->updateSchema($metadatas);
     } else {
         $tool->createSchema($metadatas);
     }
     $this->getFileCreation()->setContent(1);
 }
 /**
  * Test hydrate single entity
  */
 public function testHydrateEntity()
 {
     $serializer = SerializerBuilder::create()->build();
     $service = new HydratorService($serializer, $this->getTransformer());
     $result = $service->hydrateEntity(json_encode($this->testData), 'MJanssen\\Assets\\Entity\\Test');
     $this->assertEquals($this->createEntity($this->testData), $result);
 }
 /**
  * @return \JMS\Serializer\Serializer
  */
 private function serializer()
 {
     if (null === $this->serializer) {
         $this->serializer = SerializerBuilder::create()->addMetadataDir(__DIR__ . '/../../Infrastructure/Application/Serialization/JMS/Config')->setCacheDir(__DIR__ . '/../../../var/cache/jms-serializer')->build();
     }
     return $this->serializer;
 }
 /**
  * Instantiate a SerpPageSerializer
  * @param string $cacheDir
  */
 public function __construct($cacheDir = self::DEFAULT_SERIALIZER_CACHE_DIR)
 {
     if (!SerpPageSerializerHelper::validateDir($cacheDir)) {
         throw new \Franzip\SerpPageSerializer\Exceptions\InvalidArgumentException('Invalid SerpPageSerializer $cacheDir: please supply a valid non-empty string.');
     }
     $this->serializer = SerializerBuilder::create()->setCacheDir($cacheDir)->build();
 }
Esempio n. 5
0
 /**
  * @param string $username
  * @param string $apiKey
  */
 public function __construct($username, $apiKey)
 {
     $this->username = $username;
     $this->apiKey = $apiKey;
     $this->serializer = SerializerBuilder::create()->setCacheDir(__DIR__ . '/../../../cache')->setDebug(true)->build();
     $this->client = new Client(new SerializerWrapper($this->serializer));
 }
Esempio n. 6
0
 /**
  *  RPC url action
  *
  * @param $bundle
  * @param $service
  * @param $method
  * @param Request $request
  *
  * @Route("/{bundle}/{service}/{method}" , defaults={"_format": "json"})
  * @Method("POST")
  *
  * @return Response
  */
 public function rpcAction($bundle, $service, $method, Request $request)
 {
     $response = new Response();
     $translator = $this->get('translator');
     try {
         $prefix = 'Hazu.Service';
         $serviceObject = $this->get("{$prefix}.{$bundle}.{$service}");
         if (true === method_exists($serviceObject, $method)) {
             $params = json_decode($request->getContent(), true);
             if (null === $params) {
                 throw new \Exception('$params não é um JSON valido');
             }
             $rService = $serviceObject->{$method}($params);
         } else {
             throw new \Exception($translator->trans('Metodo não encontrado'));
         }
     } catch (ServiceNotFoundException $e) {
         $rService = new HazuException($e->getMessage());
         $response->setStatusCode(500);
     } catch (\Exception $e) {
         $rService = new HazuException($e->getMessage());
         $response->setStatusCode(500);
     } finally {
         $serializer = SerializerBuilder::create()->build();
         $rJson = $serializer->serialize($rService, 'json', SerializationContext::create()->enableMaxDepthChecks());
         $response->headers->set('x-hazu-type', gettype($rService));
         if (gettype($rService) == 'object') {
             $response->headers->set('x-hazu-class', get_class($rService));
         }
         $response->setContent($rJson);
     }
     return $response;
 }
Esempio n. 7
0
 /**
  * Constructor
  *
  * By Default if a JMS Serializer isn't provided, one will be created.
  * Providing a JMS Serializer instance allows for additional event handling,
  * caching and extensions to be loaded
  *
  * @param Serializer $serializer
  */
 public function __construct(Serializer $serializer = null)
 {
     if (is_null($serializer)) {
         $serializer = SerializerBuilder::create()->build();
     }
     $this->serializer = $serializer;
 }
Esempio n. 8
0
 public function testDeserialization()
 {
     $serializer = SerializerBuilder::create()->build();
     $serialized = file_get_contents(__DIR__ . '/../mock/SetHostsResponse.xml');
     $responseObj = $serializer->deserialize($serialized, 'SMH\\Enom\\Response\\BaseResponse', 'xml');
     $this->assertInstanceOf('SMH\\Enom\\Response\\SetHostsResponse', $responseObj);
 }
 public function register()
 {
     \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists');
     $this->app->singleton('serializer', function ($app) {
         return SerializerBuilder::create()->setObjectConstructor(new DoctrineObjectConstructor($app->make('registry'), new UnserializeObjectConstructor()))->build();
     });
 }
 public function register(Application $app)
 {
     $app['serializer.cache-directory'] = $app->share(function () use($app) {
         return $app['cache.path'] . '/serializer/';
     });
     $app['serializer.metadata_dirs'] = $app->share(function () {
         return [];
     });
     $app['serializer.handlers'] = $app->share(function () {
         return [];
     });
     $app['serializer'] = $app->share(function (Application $app) {
         // Register JMS annotation into Doctrine's registry
         AnnotationRegistry::registerAutoloadNamespace('JMS\\Serializer\\Annotation', $app['root.path'] . '/vendor/jms/serializer/src/');
         $builder = SerializerBuilder::create()->setCacheDir($app['serializer.cache-directory'])->setDebug($app['debug']);
         if (!empty($app['serializer.metadata_dirs'])) {
             $builder->addMetadataDirs($app['serializer.metadata_dirs']);
         }
         if (!empty($app['serializer.handlers'])) {
             $builder->configureHandlers(function (HandlerRegistryInterface $registry) use($app) {
                 foreach ($app['serializer.handlers'] as $handler) {
                     $registry->registerSubscribingHandler($handler);
                 }
             });
         }
         return $builder->build();
     });
 }
 protected function setUp()
 {
     parent::setUp();
     $this->serializer = SerializerBuilder::create()->build();
     $this->validator = Validation::createValidator();
     $this->action->setSerializer($this->serializer)->setValidator($this->validator);
 }
Esempio n. 12
0
 public function setUp()
 {
     AnnotationRegistry::registerLoader('class_exists');
     $this->serializer = SerializerBuilder::create()->configureHandlers(function (HandlerRegistry $registry) {
         $registry->registerSubscribingHandler(new RamseyUuidHandler());
     })->build();
 }
 public function testIfDataIsDecodedFromJsonToArray()
 {
     $transformer = $this->getTransformerMock();
     $transformer->expects($this->once())->method('transformHydrateData')->with($this->testData);
     $service = new HydratorService(SerializerBuilder::create()->build(), $transformer);
     $service->hydrateEntity(json_encode($this->testData), 'MJanssen\\Assets\\Entity\\Test');
 }
 protected function registerSerializers()
 {
     /*
      * Main serializer
      */
     $this->app->bind('bernard.serializer', function (Container $app) {
         $serializerName = config('bernard.default_serializer');
         return $app->make('bernard.serializer.' . $serializerName);
     });
     /*
      * Simple
      */
     $this->app->bind('bernard.serializer.simple', function (Container $app) {
         return new \Bernard\Serializer\SimpleSerializer();
     });
     /*
      * Symfony
      */
     $this->app->bind('bernard.serializer.symfony', function (Container $app) {
         $symfonySerializer = new \Symfony\Component\Serializer\Serializer([new \Bernard\Symfony\EnvelopeNormalizer()], [new \Symfony\Component\Serializer\Encoder\JsonEncoder()]);
         return new \Bernard\Serializer\SymfonySerializer($symfonySerializer);
     });
     /*
      * JMS Serializer
      */
     $this->app->bind('bernard.serializer.jms', function (Container $app) {
         $jmsSerializer = \JMS\Serializer\SerializerBuilder::create()->configureHandlers(function ($registry) {
             $registry->registerSubscribingHandler(new \Bernard\JMSSerializer\EnvelopeHandler());
         })->build();
         return new \Bernard\Serializer\JMSSerializer($jmsSerializer);
     });
 }
Esempio n. 15
0
 /**
  * Exclusion strategy by JMS group name
  *
  * @author Huong Le <*****@*****.**>
  *
  * @param  Entity|Collection $data     Entity or array collection of entity
  * @param  string            $JMSGroup Name of JMS group
  *
  * @return array                       Array after the exclusion was done
  */
 public function getFinalResultByJMSGroup($data, $JMSGroup)
 {
     $serializer = SerializerBuilder::create()->build();
     $json = $serializer->serialize($data, 'json', SerializationContext::create()->setGroups([$JMSGroup])->setSerializeNull(true)->enableMaxDepthChecks());
     $arr = json_decode($json, true);
     return $arr;
 }
Esempio n. 16
0
 /**
  * @param string $key
  * @param mixed $value
  */
 public function store($key, $value)
 {
     $serializer = SerializerBuilder::create()->build();
     $jsonContent = $serializer->serialize($value, 'json');
     apc_store($this->getCacheKey() . $key, $jsonContent);
     $this->cacheDriver->store($this->getCacheKey() . $key, $jsonContent);
 }
 public function testDeserialization()
 {
     $serializer = SerializerBuilder::create()->build();
     $serialized = file_get_contents(__DIR__ . '/../mock/GetAllDomainsResponse.xml');
     $responseObj = $serializer->deserialize($serialized, 'SMH\\Enom\\Response\\BaseResponse', 'xml');
     $this->assertInstanceOf('SMH\\Enom\\Response\\GetAllDomainsResponse', $responseObj);
     $collection = $responseObj->getAllDomains;
     $this->assertCount(2, $collection);
     $domain1 = $collection[0];
     $this->assertEquals('sesame.com', $domain1->domainName);
     $this->assertEquals('0000000001', $domain1->domainNameId);
     $this->assertInstanceOf('\\DateTime', $domain1->expiration);
     $this->assertEquals('2016-01-28T22:19:26+00:00', $domain1->expiration->format(\DateTime::ATOM));
     $this->assertEquals('Locked', $domain1->lockStatus);
     $this->assertEquals('No', $domain1->autoRenew);
     $this->assertTrue($domain1->isLocked());
     $this->assertFalse($domain1->isAutoRenew());
     $domain2 = $collection[1];
     $this->assertEquals('sesameexample.com', $domain2->domainName);
     $this->assertEquals('0000000002', $domain2->domainNameId);
     $this->assertInstanceOf('\\DateTime', $domain2->expiration);
     $this->assertEquals('2016-03-11T16:10:07+00:00', $domain2->expiration->format(\DateTime::ATOM));
     $this->assertEquals('Not Locked', $domain2->lockStatus);
     $this->assertEquals('Yes', $domain2->autoRenew);
     $this->assertFalse($domain2->isLocked());
     $this->assertTrue($domain2->isAutoRenew());
 }
Esempio n. 18
0
 public function __construct(array $config)
 {
     $config = array_replace($defaults = ['subscribers' => [], 'listeners' => [], 'extraHandlers' => []], $config);
     $serializerBuilder = SerializerBuilder::create();
     if (isset($config['cacheDir'])) {
         $serializerBuilder->setCacheDir($config['cacheDir']);
     }
     if (isset($config['propertyNamingStrategy'])) {
         $serializerBuilder->setPropertyNamingStrategy($config['propertyNamingStrategy']);
     }
     if (isset($config['objectConstructor'])) {
         $serializerBuilder->setObjectConstructor($config['objectConstructor']);
     }
     if (isset($config['debug'])) {
         $serializerBuilder->setDebug((bool) $config['objectConstructor']);
     }
     $serializerBuilder->addDefaultHandlers();
     $extraHandlers = $config['extraHandlers'];
     $serializerBuilder->configureHandlers(function (HandlerRegistry $handlerRegistry) use($extraHandlers) {
         array_walk($extraHandlers, [$handlerRegistry, 'registerSubscribingHandler']);
     });
     $subscribers = $config['subscribers'];
     $listeners = $config['listeners'];
     $serializerBuilder->configureListeners(function (EventDispatcher $dispatcher) use($subscribers, $listeners) {
         array_walk($subscribers, [$dispatcher, 'addSubscriber']);
         foreach ($listeners as $event => $callables) {
             foreach ($callables as $cb) {
                 $dispatcher->addListener($event, $cb);
             }
         }
     });
     $this->serializer = $serializerBuilder->build();
 }
Esempio n. 19
0
 /**
  * Constructor.
  *
  * @param \net\authorize\api\contract\v1\AnetApiRequestType $request ApiRequest to send
  * @param string $responseType response type expected
  * @throws InvalidArgumentException if invalid request
  */
 public function __construct(\net\authorize\api\contract\v1\AnetApiRequestType $request, $responseType)
 {
     date_default_timezone_set('UTC');
     $this->logger = LogFactory::getLog(get_class($this));
     if (null == $request) {
         throw new InvalidArgumentException("request cannot be null");
     }
     if (null == $responseType || '' == $responseType) {
         throw new InvalidArgumentException("responseType cannot be null or empty");
     }
     if (null != $this->apiResponse) {
         throw new InvalidArgumentException("response has to be null");
     }
     $this->apiRequest = $request;
     $this->validate();
     $this->apiResponseType = $responseType;
     $this->httpClient = new HttpClient();
     $serializerBuilder = SerializerBuilder::create();
     $serializerBuilder->addMetadataDir(__DIR__ . '/../../yml/v1', 'net\\authorize\\api\\contract\\v1');
     //..\..\yml\v1\ //'/../lib/net/authorize/api/yml/v1'
     $serializerBuilder->configureHandlers(function (HandlerRegistryInterface $h) use($serializerBuilder) {
         $serializerBuilder->addDefaultHandlers();
         $h->registerSubscribingHandler(new BaseTypesHandler());
         // XMLSchema List handling
         $h->registerSubscribingHandler(new XmlSchemaDateHandler());
         // XMLSchema date handling
     });
     $this->serializer = $serializerBuilder->build();
 }
 /**
  * Set up all the mocks and the serializer class
  *
  * @return void
  */
 public function setUp()
 {
     $this->serializer = SerializerBuilder::create()->build();
     $this->setupPheanstalkConnectionMock();
     $this->generateFakeParams();
     $this->setupEntityManagerMock();
 }
Esempio n. 21
0
 protected function toXml($oObject)
 {
     $oSerializer = SerializerBuilder::create()->build();
     $sXml = $oSerializer->serialize($oObject, 'xml');
     $this->_sXml = $sXml;
     return $this;
 }
Esempio n. 22
0
 private function getSerializer()
 {
     if (is_null($this->serializer)) {
         $this->serializer = SerializerBuilder::create()->addMetadataDir(dirname(__DIR__) . '/V1_1_1/Metadata/Cdm', 'CdmFr\\Model\\V1_1_1\\Cdm')->addMetadataDir(dirname(__DIR__) . '/V1_1_1/Metadata/CdmFr', 'CdmFr\\Model\\V1_1_1\\CdmFr')->addMetadataDir(dirname(__DIR__) . '/V1_1_1/Metadata/Lheo', 'CdmFr\\Model\\V1_1_1\\Lheo')->build();
     }
     return $this->serializer;
 }
 /**
  * Registers services on the given app.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  *
  * @param Application $app
  */
 public function register(Application $app)
 {
     $app['serializer.metadata_dirs'] = [];
     $app['serializer.stopwatch_subscriber'] = $app->share(function () use($app) {
         return new StopwatchEventSubscriber($app['stopwatch']);
     });
     $app['serializer.doctrine_object_deserialize_listener'] = $app->share(function () use($app) {
         return new DoctrineObjectDeserializeListener($app['doctrine']);
     });
     $app['serializer.builder'] = $app->share(function () use($app) {
         $builder = SerializerBuilder::create();
         $builder->setDebug($app['debug']);
         $builder->setObjectConstructor(new DoctrineObjectConstructor($app['doctrine'], new UnserializeObjectConstructor()));
         if (isset($app['serializer.cache_dir'])) {
             $builder->setCacheDir($app['serializer.cache_dir']);
         }
         if (isset($app['serializer.metadata_dirs'])) {
             $builder->setMetadataDirs($app['serializer.metadata_dirs']);
         }
         $builder->configureListeners(function (EventDispatcher $dispatcher) use($app) {
             $dispatcher->addSubscriber($app['serializer.doctrine_object_deserialize_listener']);
         });
         if (isset($app['stopwatch'])) {
             $builder->configureListeners(function (EventDispatcher $dispatcher) use($app) {
                 $dispatcher->addSubscriber($app['serializer.stopwatch_subscriber']);
             });
         }
         return $builder;
     });
     $app['serializer'] = $app->share(function () use($app) {
         return $app['serializer.builder']->build();
     });
 }
Esempio n. 24
0
 /**
  * @return mixed
  */
 public static function getSerializer()
 {
     if (!self::$serializer) {
         self::$serializer = SerializerBuilder::create()->build();
     }
     return self::$serializer;
 }
 public function testSerialization()
 {
     $element1 = new ProductImage('MOB_12543');
     $element1->add(new ImageUri('http://host.com/img1.jpg'));
     $element2 = new ProductImage('ASM_A8012');
     $element2->add(new ImageUri('http://host.com/img2.jpg'));
     $collection = new ProductImageCollection();
     $collection->add($element1);
     $collection->add($element2);
     \SellerCenter\SDK\Common\AnnotationRegistry::registerAutoloadNamespace();
     $serializer = \JMS\Serializer\SerializerBuilder::create()->build();
     $xml = '
         <Request>
             <ProductImage>
                 <SellerSku>MOB_12543</SellerSku>
                 <Images>
                     <Image>http://host.com/img1.jpg</Image>
                 </Images>
             </ProductImage>
             <ProductImage>
                 <SellerSku>ASM_A8012</SellerSku>
                 <Images>
                     <Image>http://host.com/img2.jpg</Image>
                 </Images>
             </ProductImage>
         </Request>
     ';
     $this->assertXmlStringEqualsXmlString($xml, $serializer->serialize($collection, 'xml'));
 }
Esempio n. 26
0
 public function editAction(Request $request, $id)
 {
     $serializer = SerializerBuilder::create()->build();
     $data = array('success' => false, 'error' => 'Ошибка обновления книги');
     if ($request->getMethod() == 'POST') {
         $requestData = $request->request->all();
         if (empty($requestData['apiKey']) || !$this->checkApiKey($requestData['apiKey'])) {
             $data['error'] = 'Неверный ключ';
             $jsonContent = $serializer->serialize($data, 'json');
             return new Response($jsonContent);
         }
         $book = $this->getDoctrine()->getManager()->getRepository('IntaroBookStoreBundle:Book')->find($id);
         if (!$book) {
             $data['error'] = 'Книга не найдена';
             $jsonContent = $serializer->serialize($data, 'json');
             return new Response($jsonContent);
         }
         if (!empty($requestData['name']) && !empty($requestData['author']) && !empty($requestData['readingDate']) && isset($requestData['download'])) {
             $book->setName($requestData['name']);
             $book->setAuthor($requestData['author']);
             $book->setReadingDate(new \DateTime($requestData['readingDate']));
             $book->setDownload($requestData['download']);
         } else {
             $data['error'] = 'Заданы не все необходимые поля';
             $jsonContent = $serializer->serialize($data, 'json');
             return new Response($jsonContent);
         }
         $em = $this->getDoctrine()->getManager();
         $em->persist($book);
         $em->flush();
         $data = array('success' => true, 'message' => 'Книга успешно обновлена');
     }
     $jsonContent = $serializer->serialize($data, 'json');
     return new Response($jsonContent);
 }
Esempio n. 27
0
 /**
  * @param mixed $value
  * @return $this
  */
 public function set($value)
 {
     $serializer = SerializerBuilder::create()->build();
     $jsonContent = $serializer->serialize($value, 'json');
     $this->value = $jsonContent;
     return $this;
 }
Esempio n. 28
0
 /**
  * MxToolbox constructor.
  * @param ApiToken|null $apiToken
  * @param $secure
  */
 public function __construct(ApiToken $apiToken, bool $secure = true)
 {
     $this->apiToken = $apiToken;
     $this->httpClient = new Client(['base_uri' => $this->getURL($secure), 'headers' => ['Authorization' => $this->apiToken->get()]]);
     $this->buildAnnotationRegistry();
     $this->serializer = $serializer = SerializerBuilder::create()->build();
 }
 public function getFakedApiResponse($class)
 {
     AnnotationRegistry::registerLoader('class_exists');
     $serializer = SerializerBuilder::create()->build();
     $response = new $class();
     return $serializer->serialize($response, 'json');
 }
Esempio n. 30
0
 public function register(Container $app)
 {
     if (!$app['resolver'] instanceof ServiceControllerResolver) {
         throw new \RuntimeException('Register ServiceControllerServiceProvider first.');
     }
     foreach (array('all', 'post', 'get', 'put', 'patch', 'delete') as $method) {
         $app['rest.methods.' . $method] = $method;
     }
     $app['rest.annotation_loader'] = function () use($app) {
         return new AnnotationDirectoryLoader(new FileLocator($app['controllers_path']), new AnnotationClassLoader($app['annotation.reader'], $app['rest.rm']));
     };
     $app['rest'] = function () use($app) {
         return new RestService($app['rest.serializer']);
     };
     $app['rest.rm'] = function () use($app) {
         Resource::$defaultMethods = array('all' => $app['rest.methods.all'], 'post' => $app['rest.methods.post'], 'get' => $app['rest.methods.get'], 'put' => $app['rest.methods.put'], 'patch' => $app['rest.methods.patch'], 'delete' => $app['rest.methods.delete']);
         return new ResourceManager($app['routes'], $app, $app['route_class']);
     };
     $app['rest.listener'] = function () use($app) {
         return new RestResponseListener($app['rest'], $app['rest.annotation_loader']);
     };
     $app['rest.serializer'] = function () use($app) {
         $builder = SerializerBuilder::create()->setObjectConstructor(NaturalObjectConstructor::create($app));
         if (isset($app['annotation.reader'])) {
             $builder->setAnnotationReader($app['annotation.reader']);
         }
         return $builder->build();
     };
 }