_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q400
BlockManager.findById
train
public function findById($id, $draft = true) { if ($draft) { $this->setDraftVersionFilter(! $draft); } $blocks = $this->getRepository()->findById($id); if ($draft) { foreach ($blocks as $block) { if (null !== $revision = $this->revisionManager->getDraftRevision($block)) { $this->revisionManager->revert($block, $revision); } } } return $blocks; }
php
{ "resource": "" }
q401
BlockManager.findDescendants
train
public function findDescendants($parent, $draft = true) { $this->setDraftVersionFilter(! $draft); $iterator = new \RecursiveIteratorIterator( new RecursiveBlockIterator([$parent]), \RecursiveIteratorIterator::SELF_FIRST ); $blocks = []; foreach ($iterator as $descendant) { $blocks[] = $descendant; } if ($draft) { $this->revertToDraft($blocks); } return $blocks; }
php
{ "resource": "" }
q402
BlockManager.publish
train
public function publish($blocks) { if ($blocks instanceof PersistentCollection) { $blocks = $blocks->getValues(); } if (!$blocks || (is_array($blocks) && !count($blocks))) { return; } if (! is_array($blocks)) { $blocks = [$blocks]; } $this->disableRevisionListener(); $deletes = []; foreach ($blocks as $block) { if (null !== $revision = $this->revisionManager->getDraftRevision($block)) { try { $this->revisionManager->revert($block, $revision); } catch (DeletedException $e) { // $this->em->remove($block); $deletes[] = $block; } } } $this->em->flush(); // Cycle through all deleted blocks to perform cascades manually foreach ($deletes as $block) { if ($block instanceof CompositeBlock) { $descendants = $this->findDescendants($block, false); } else { $descendants = [$block]; } foreach ($descendants as $descendant) { $descendant->setDeletedAt(new \DateTime); $this->em->flush($descendant); } } $cacheDriver = $this->em->getConfiguration()->getResultCacheImpl(); $cacheDriver->deleteAll(); $this->enableRevisionListener(); }
php
{ "resource": "" }
q403
BlockManager.duplicate
train
public function duplicate($blocks, $owner = null) { if ($blocks instanceof BlockInterface) { $blocks = array($blocks); } $iterator = new \RecursiveIteratorIterator( new RecursiveBlockIterator($blocks), \RecursiveIteratorIterator::SELF_FIRST ); $originalIdMap = array(); $originalParentMap = array(); $clones = array(); // iterate over all owned blocks and disconnect parents keeping ids /** @var Block $block */ foreach ($iterator as $block) { $blockId = $block->getId(); $parentId = false; if (in_array($block->getId(), $originalIdMap)) { continue; } $clone = clone $block; $clone->setId(null); $clone->setParent(null); $clone->setOwner($owner); // if it has a parent we need to keep the id as reference for later if ($block->getParent()) { $parentId = $block->getParent()->getId(); } if ($clone instanceof BlockContainerInterface) { $clone->setChildren(null); } $this->em->persist($clone); $this->em->flush($clone); // the block gets a new id $originalIdMap[$clone->getId()] = $blockId; if ($parentId) { $originalParentMap[$clone->getId()] = $parentId; } $clones[] = $clone; } // iterate over all new blocks and reset their parents foreach ($clones as $clone) { if (isset($originalParentMap[$clone->getId()])) { foreach ($clones as $parent) { if (isset($originalParentMap[$clone->getId()]) && $originalParentMap[$clone->getId()] === $originalIdMap[$parent->getId()]) { $clone->setParent($parent); $parent->addChild($clone); $this->em->flush($clone); $this->em->flush($parent); } } } } return $clones; }
php
{ "resource": "" }
q404
BlockManager.setDraftVersionFilter
train
public function setDraftVersionFilter($enabled = true) { if ($this->em->getFilters()->isEnabled('draft') && ! $enabled) { $this->em->getFilters()->disable('draft'); } else if (! $this->em->getFilters()->isEnabled('draft') && $enabled) { $this->em->getFilters()->enable('draft'); } }
php
{ "resource": "" }
q405
BlockManager.disableRevisionListener
train
public function disableRevisionListener() { foreach ($this->em->getEventManager()->getListeners() as $event => $listeners) { foreach ($listeners as $hash => $listener) { if ($listener instanceof RevisionListener) { $this->revisionListener = $listener; break 2; } } } if ($this->revisionListener) { $this->revisionListener->setActive(false); } }
php
{ "resource": "" }
q406
BlockManager.getSiblings
train
public function getSiblings(BlockInterface $block, $version = false) { $owner = $block->getOwner(); $family = $this->findByOwner($owner, $version); $siblings = array(); foreach ($family as $member) { if ($member->getParent() && $member->getParent()->getId() == $block->getParent()->getId()) { array_push($siblings, $member); } } return $siblings; }
php
{ "resource": "" }
q407
ExceptionRouter.match
train
public function match($pathinfo) { $urlMatcher = new UrlMatcher($this->routeCollection, $this->getContext()); $result = $urlMatcher->match($pathinfo); return $result; }
php
{ "resource": "" }
q408
EmptyValueListener.postLoad
train
public function postLoad(LifeCycleEventArgs $args) { $entity = $args->getEntity(); if ($entity instanceof ValueSetInterface && $entity->getValues() !== null) { $this->eavManager->replaceEmptyValues($entity); } }
php
{ "resource": "" }
q409
EmptyValueListener.postPersist
train
public function postPersist(LifeCycleEventArgs $args) { $entity = $args->getEntity(); $entityManager = $args->getEntityManager(); if ($entity instanceof ValueInterface && $entity->isEmpty()) { $entityManager->remove($entity); } }
php
{ "resource": "" }
q410
SchemaRepository.findByRequest
train
public function findByRequest(Request $request) { $qb = $this->createQueryBuilder('s'); if ($request->get('attribute')) { $qb->join('s.allowedInAttributes', 'a') ->andWhere('a.id = :attributeId') ->setParameter('attributeId', $request->get('attribute')); } return $qb->getQuery()->getArrayResult(); }
php
{ "resource": "" }
q411
Pool.addValue
train
public function addValue(ValueProviderInterface $value, $alias) { if (false === $value->isEnabled()) { return; } $this->values[$alias] = $value; }
php
{ "resource": "" }
q412
Pool.getValueByEntity
train
public function getValueByEntity($entity) { if (is_object($entity)) { $entity = get_class($entity); } /** @var ValueProviderInterface $provider */ foreach ($this->getValues() as $provider) { if ($entity === $provider->getEntity()) { return $provider; } } return false; }
php
{ "resource": "" }
q413
CodemirrorAsset.registerAssetFiles
train
public function registerAssetFiles($view) { if (is_array(self::$_assets)) { $this->css = array_values(array_intersect_key(self::$_css, self::$_assets)); $this->js = array_values(array_intersect_key(self::$_js, self::$_assets)); } array_unshift($this->css, self::$_css['lib']); array_unshift($this->js, self::$_js['lib']); parent::registerAssetFiles($view); }
php
{ "resource": "" }
q414
Site.getDefaultDomain
train
public function getDefaultDomain() { if ($this->defaultDomain) { return $this->defaultDomain; } elseif ($first = $this->getDomains()->first()) { return $first->getDomain(); } else { return null; } }
php
{ "resource": "" }
q415
HttpBinding.request
train
public function request($name, array $arguments, array $options = null, $inputHeaders = null) { $soapRequest = $this->interpreter->request($name, $arguments, $options, $inputHeaders); if ($soapRequest->getSoapVersion() == '1') { $this->builder->isSOAP11(); } else { $this->builder->isSOAP12(); } $this->builder->setEndpoint($soapRequest->getEndpoint()); $this->builder->setSoapAction($soapRequest->getSoapAction()); $stream = new Stream('php://temp', 'r+'); $stream->write($soapRequest->getSoapMessage()); $stream->rewind(); $this->builder->setSoapMessage($stream); try { return $this->builder->getSoapHttpRequest(); } catch (RequestException $exception) { $stream->close(); throw $exception; } }
php
{ "resource": "" }
q416
HttpBinding.response
train
public function response(ResponseInterface $response, $name, array &$outputHeaders = null) { return $this->interpreter->response($response->getBody()->__toString(), $name, $outputHeaders); }
php
{ "resource": "" }
q417
Factory.create
train
public function create($name, $value) { if (!empty($this->callbacks[$name])) { return call_user_func($this->callbacks[$name], $name, $value); } return $this->createBasic($name, $value); }
php
{ "resource": "" }
q418
ContentEditorController.clipboardBlockAction
train
public function clipboardBlockAction($id) { /** @var BlockManager $manager */ $manager = $this->get('opifer.content.block_manager'); /** @var ClipboardBlockService $clipboardService */ $clipboardService = $this->get('opifer.content.clipboard_block'); $response = new JsonResponse; try { $block = $manager->find($id, true); $clipboardService->addToClipboard($block); $blockService = $manager->getService($block); $response->setData(['message' => sprintf('%s copied to clipboard', $blockService->getName())]); } catch (\Exception $e) { $response->setStatusCode(500); $response->setData(['error' => $e->getMessage()]); } return $response; }
php
{ "resource": "" }
q419
ContentEditorController.publishSharedAction
train
public function publishSharedAction(Request $request) { $this->getDoctrine()->getManager()->getFilters()->disable('draft'); /** @var BlockManager $manager */ $manager = $this->get('opifer.content.block_manager'); $response = new JsonResponse; $id = (int) $request->request->get('id'); try { $block = $manager->find($id, true); $block->setUpdatedAt(new \DateTime()); $manager->publish($block); if ($block instanceof CompositeBlock) { $manager->publish($manager->findDescendants($block)); } $response->setStatusCode(200); $response->setData(['state' => 'published']); } catch (\Exception $e) { $response->setStatusCode(500); $response->setData(['error' => $e->getMessage() . $e->getTraceAsString()]); } return $response; }
php
{ "resource": "" }
q420
ContentEditorController.discardBlockAction
train
public function discardBlockAction(Request $request) { $this->getDoctrine()->getManager()->getFilters()->disable('draft'); /** @var BlockManager $manager */ $manager = $this->get('opifer.content.block_manager'); $response = new JsonResponse; $id = (int) $request->request->get('id'); try { $manager->discardAll($id); $response->setStatusCode(200); $response->setData(['state' => 'discarded']); } catch (\Exception $e) { $response->setStatusCode(500); $response->setData(['error' => $e->getMessage()]); } return $response; }
php
{ "resource": "" }
q421
SubscriptionRepository.findPendingSynchronisation
train
public function findPendingSynchronisation() { return $this->createQueryBuilder('s') ->innerjoin('s.mailingList', 'm') ->andWhere('s.status = :pending OR s.status = :failed') ->setParameters([ 'pending' => Subscription::STATUS_PENDING, 'failed' => Subscription::STATUS_FAILED, ]) ->getQuery() ->getResult(); }
php
{ "resource": "" }
q422
SubscriptionRepository.findPendingSynchronisationList
train
public function findPendingSynchronisationList(MailingList $mailingList) { return $this->createQueryBuilder('s') ->innerjoin('s.mailingList', 'm') ->where('s.mailingList = :mailingList') ->andWhere('s.status = :pending OR s.status = :failed') ->setParameters([ 'mailingList' => $mailingList, 'pending' => Subscription::STATUS_PENDING, 'failed' => Subscription::STATUS_FAILED, ]) ->getQuery() ->getResult(); }
php
{ "resource": "" }
q423
Attribute.getOptionByName
train
public function getOptionByName($name) { foreach ($this->options as $option) { if ($option->getName() == $name) { return $option; } } return false; }
php
{ "resource": "" }
q424
Attribute.addAllowedSchema
train
public function addAllowedSchema(SchemaInterface $schema) { $exists = false; foreach ($this->allowedSchemas as $allowedSchema) { if ($allowedSchema->getId() == $schema->getId()) { $exists = true; } } if (!$exists) { $this->allowedSchemas[] = $schema; } return $this; }
php
{ "resource": "" }
q425
OpiferCmsExtension.mapClassParameters
train
protected function mapClassParameters(array $classes, ContainerBuilder $container) { foreach ($classes as $model => $serviceClasses) { foreach ($serviceClasses as $service => $class) { $container->setParameter( sprintf( 'opifer_cms.%s_%s', $model, $service ), $class ); } } }
php
{ "resource": "" }
q426
FormExtension.createFormView
train
public function createFormView(FormInterface $form) { $post = $this->eavManager->initializeEntity($form->getSchema()); $form = $this->formFactory->create(PostType::class, $post, ['form_id' => $form->getId()]); return $form->createView(); }
php
{ "resource": "" }
q427
BlockController.viewAction
train
public function viewAction($id) { /** @var BlockManager $manager */ $manager = $this->get('opifer.content.block_manager'); /** @var BlockInterface $block */ $block = $manager->getRepository()->find($id); if (!$block) { throw $this->createNotFoundException(); } $response = new Response(); /** @var Environment $environment */ $environment = $this->get('opifer.content.block_environment'); $environment->setObject($block->getOwner()); $service = $manager->getService($block); $response = $service->execute($block, $response, [ 'partial' => true, 'environment' => $environment ]); return $response; }
php
{ "resource": "" }
q428
BlockController.sharedAction
train
public function sharedAction() { $blocks = $this->get('opifer.content.block_manager')->getRepository() ->findBy(['shared' => true]); return $this->render($this->getParameter('opifer_content.block_shared_view'), [ 'blocks' => $blocks, ]); }
php
{ "resource": "" }
q429
BlockEventSubscriber.setChildren
train
protected function setChildren(Block $block) { if (method_exists($block, 'setChildren')) { $children = $this->environment->getBlockChildren($block); $block->setChildren($children); } }
php
{ "resource": "" }
q430
ContentTypeController.indexAction
train
public function indexAction() { $contentTypes = $this->get('opifer.content.content_type_manager')->getRepository() ->findAll(); return $this->render($this->getParameter('opifer_content.content_type_index_view'), [ 'content_types' => $contentTypes, ]); }
php
{ "resource": "" }
q431
ContentTypeController.createAction
train
public function createAction(Request $request) { $contentTypeManager = $this->get('opifer.content.content_type_manager'); $contentType = $contentTypeManager->create(); $form = $this->createForm(ContentTypeType::class, $contentType); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { foreach ($form->getData()->getSchema()->getAttributes() as $attribute) { $attribute->setSchema($contentType->getSchema()); foreach ($attribute->getOptions() as $option) { $option->setAttribute($attribute); } } $contentTypeManager->save($contentType); $this->addFlash('success', 'Content type has been created successfully'); return $this->redirectToRoute('opifer_content_contenttype_edit', ['id' => $contentType->getId()]); } return $this->render($this->getParameter('opifer_content.content_type_create_view'), [ 'content_type' => $contentType, 'form' => $form->createView(), ]); }
php
{ "resource": "" }
q432
CKEditorController.contentAction
train
public function contentAction(Request $request) { return $this->render('OpiferCmsBundle:CKEditor:content.html.twig', [ 'funcNum' => $request->get('CKEditorFuncNum'), 'CKEditor' => $request->get('CKEditor'), 'type' => $request->get('type'), ]); }
php
{ "resource": "" }
q433
CKEditorController.mediaAction
train
public function mediaAction(Request $request) { $providers = $this->get('opifer.media.provider.pool')->getProviders(); return $this->render('OpiferCmsBundle:CKEditor:media.html.twig', [ 'providers' => $providers, 'funcNum' => $request->get('CKEditorFuncNum'), 'CKEditor' => $request->get('CKEditor'), 'type' => $request->get('type'), ]); }
php
{ "resource": "" }
q434
CronRunCommand.isLocked
train
protected function isLocked(Cron $cron) { $hourAgo = new \DateTime('-65 minutes'); if ($cron->getState() === Cron::STATE_RUNNING && $cron->getStartedAt() > $hourAgo) { return true; } return false; }
php
{ "resource": "" }
q435
CronRunCommand.startCron
train
private function startCron(Cron $cron) { if ($this->isLocked($cron)) { return; } $this->output->writeln(sprintf('Started %s.', $cron)); $this->changeState($cron, Cron::STATE_RUNNING); $pb = $this->getCommandProcessBuilder(); $parts = explode(' ', $cron->getCommand()); foreach ($parts as $part) { $pb->add($part); } $process = $pb->getProcess(); $process->setTimeout(3600); try { $process->mustRun(); $this->output->writeln(' > '.$process->getOutput()); if (!$process->isSuccessful()) { $this->output->writeln(' > '.$process->getErrorOutput()); if(strpos($process->getErrorOutput(), 'timeout') !== false) { $this->changeState($cron, Cron::STATE_TERMINATED, $process->getErrorOutput()); } else { $this->changeState($cron, Cron::STATE_FAILED, $process->getErrorOutput()); } } else { $this->changeState($cron, Cron::STATE_FINISHED); } } catch (\Exception $e) { $message = $e->getMessage(); if(strpos($e->getMessage(), 'timeout') !== false) { $this->output->writeln(' > '.$e->getMessage()); $this->changeState($cron, Cron::STATE_TERMINATED, $e->getMessage()); } else { $this->output->writeln(' > '.$e->getMessage()); $this->changeState($cron, Cron::STATE_FAILED, $e->getMessage()); } } }
php
{ "resource": "" }
q436
CronRunCommand.changeState
train
private function changeState(Cron $cron, $state, $lastError = null) { $cron->setState($state); $cron->setLastError($lastError); $em = $this->getEntityManager(); $em->persist($cron); $em->flush($cron); }
php
{ "resource": "" }
q437
CronRunCommand.getCommandProcessBuilder
train
private function getCommandProcessBuilder() { $pb = new ProcessBuilder(); // PHP wraps the process in "sh -c" by default, but we need to control // the process directly. if (!defined('PHP_WINDOWS_VERSION_MAJOR')) { $pb->add('exec'); } $pb ->add('php') ->add($this->getContainer()->getParameter('kernel.root_dir').'/console') ->add('--env='.$this->env) ; return $pb; }
php
{ "resource": "" }
q438
OptionRepository.findByIds
train
public function findByIds($ids) { if (!is_array($ids)) { $ids = explode(',', trim($ids)); } return $this->createQueryBuilder('o') ->where('o.id IN (:ids)') ->setParameters([ 'ids' => $ids, ]) ->getQuery() ->getResult(); }
php
{ "resource": "" }
q439
SweetSubmitAsset.initOptions
train
protected function initOptions() { $view = Yii::$app->view; $opts = [ 'confirmButtonText' => Yii::t('sweetsubmit', 'Ok'), 'cancelButtonText' => Yii::t('sweetsubmit', 'Cancel'), ]; $opts = Json::encode($opts); $view->registerJs("yii.sweetSubmitOptions = $opts;", View::POS_END); }
php
{ "resource": "" }
q440
ExceptionController.error404Action
train
public function error404Action(Request $request) { $host = $request->getHost(); $slugParts = explode('/', $request->getPathInfo()); $locale = $this->getDoctrine()->getRepository(Locale::class) ->findOneByLocale($slugParts[1]); /** @var ContentRepository $contentRepository */ $contentRepository = $this->getDoctrine()->getRepository('OpiferCmsBundle:Content'); $content = $contentRepository->findActiveBySlug('404', $host); if(!$content) { $content = $contentRepository->findOneBySlug($locale->getLocale().'/404'); } if (!$content) { $content = $contentRepository->findOneBySlug('404'); } if ($content) { return $this->forward('OpiferContentBundle:Frontend/Content:view', [ 'content' => $content, 'statusCode' => 404, ]); } $response = new Response(); $response->setStatusCode(404); return $this->render('OpiferCmsBundle:Exception:error404.html.twig', [], $response); }
php
{ "resource": "" }
q441
ExpressionEngine.transform
train
protected function transform(Expression $expression) { $constraint = $expression->getConstraint(); $getter = 'get'.ucfirst($expression->getSelector()); return Expr::method($getter, new $constraint($expression->getValue())); }
php
{ "resource": "" }
q442
MediaController.deleteAction
train
public function deleteAction(Request $request, $id) { $mediaManager = $this->get('opifer.media.media_manager'); $media = $mediaManager->getRepository()->find($id); $dispatcher = $this->get('event_dispatcher'); $event = new MediaResponseEvent($media, $request); $dispatcher->dispatch(OpiferMediaEvents::MEDIA_CONTROLLER_DELETE, $event); if (null !== $event->getResponse()) { return $event->getResponse(); } $mediaManager->remove($media); return $this->redirectToRoute('opifer_media_media_index'); }
php
{ "resource": "" }
q443
ValueSet.getSortedValues
train
public function getSortedValues($order = 'asc') { $values = $this->values->toArray(); usort($values, function ($a, $b) use ($order) { $left = $a->getAttribute()->getSort(); $right = $b->getAttribute()->getSort(); if ($order == 'desc') { return ($left < $right) ? 1 : -1; } return ($left > $right) ? 1 : -1; }); return $values; }
php
{ "resource": "" }
q444
ValueSet.getNamedValues
train
public function getNamedValues($order = 'asc') { $values = $this->getSortedValues($order); $valueArray = []; foreach ($values as $value) { $valueArray[$value->getAttribute()->getName()] = $value; } return $valueArray; }
php
{ "resource": "" }
q445
ValueSet.has
train
public function has($value) { if (!is_string($value) && !is_array($value)) { throw new \InvalidArgumentException('The ValueSet\'s "has" method requires the argument to be of type string or array'); } if (is_string($value)) { return $this->__isset($value); } elseif (is_array($value)) { foreach ($value as $name) { if (!$this->__isset($value)) { return false; } } return true; } }
php
{ "resource": "" }
q446
ValueSet.getValueByAttributeId
train
public function getValueByAttributeId($attributeId) { foreach ($this->values as $valueObject) { if ($valueObject->getAttribute()->getId() == $attributeId) { return $valueObject; } } return null; }
php
{ "resource": "" }
q447
ContentEditorController.tocAction
train
public function tocAction($owner, $ownerId) { /** @var BlockProviderInterface $provider */ $provider = $this->get('opifer.content.block_provider_pool')->getProvider($owner); $object = $provider->getBlockOwner($ownerId); /** @var Environment $environment */ $environment = $this->get('opifer.content.block_environment'); $environment->setDraft(true)->setObject($object); $environment->setBlockMode('manage'); $twigAnalyzer = $this->get('opifer.content.twig_analyzer'); $parameters = [ 'environment' => $environment, 'analyzer' => $twigAnalyzer, 'object' => $environment->getObject(), ]; return $this->render('OpiferContentBundle:Content:toc.html.twig', $parameters); }
php
{ "resource": "" }
q448
CronRepository.findDue
train
public function findDue() { /** @var Cron[] $active */ $active = $this->createQueryBuilder('c') ->where('c.state <> :canceled') ->andWhere('c.state <> :running OR (c.state = :running AND c.startedAt < :hourAgo)') ->orderBy('c.priority', 'DESC') ->setParameters([ 'canceled' => Cron::STATE_CANCELED, 'running' => Cron::STATE_RUNNING, 'hourAgo' => new \DateTime('-67 minutes'), ]) ->getQuery() ->getResult() ; $due = []; foreach ($active as $cron) { if ($cron->isDue()) { $due[] = $cron; } } return new ArrayCollection($due); }
php
{ "resource": "" }
q449
FormController.getFormAction
train
public function getFormAction($id) { /** @var Form $form */ $form = $this->get('opifer.form.form_manager')->getRepository()->find($id); if (!$form) { throw $this->createNotFoundException('The form could not be found'); } /** @var Post $post */ $post = $this->get('opifer.eav.eav_manager')->initializeEntity($form->getSchema()); $postForm = $this->createForm(PostType::class, $post, ['form_id' => $id]); $definition = $this->get('liform')->transform($postForm); /** @var CsrfTokenManagerInterface $csrf */ $csrf = $this->get('security.csrf.token_manager'); $token = $csrf->refreshToken($form->getName()); // We're stuck with a legacy form structure here, which we'd like to hide on the API. $fields = $definition['properties']['valueset']['properties']['namedvalues']['properties']; $fields['_token'] = [ 'widget' => 'hidden', 'value' => $token->getValue() ]; return new JsonResponse($fields); }
php
{ "resource": "" }
q450
FormController.postFormPostAction
train
public function postFormPostAction(Request $request, $id) { /** @var Form $form */ $form = $this->get('opifer.form.form_manager')->getRepository()->find($id); if (!$form) { throw $this->createNotFoundException('The form could not be found'); } $data = json_decode($request->getContent(), true); $token = $data['_token']; if ($this->isCsrfTokenValid($form->getName(), $token)) { throw new InvalidCsrfTokenException(); } // Remove the token from the data array, since it's not part of the form. unset($data['_token']); // We're stuck with a legacy form structure here, which we'd like to hide on the API. $data = ['valueset' => ['namedvalues' => $data]]; /** @var Post $post */ $post = $this->get('opifer.eav.eav_manager')->initializeEntity($form->getSchema()); $post->setForm($form); $postForm = $this->createForm(PostType::class, $post, ['form_id' => $id, 'csrf_protection' => false]); $postForm->submit($data); if ($postForm->isSubmitted() && $postForm->isValid()) { $this->get('opifer.form.post_manager')->save($post); return new JsonResponse(['message' => 'Success'], 201); } return new JsonResponse([ 'errors' => (string) $postForm->getErrors() ], 400); }
php
{ "resource": "" }
q451
Builder.setRegisteredClaim
train
protected function setRegisteredClaim($name, $value, $replicate) { $this->set($name, $value); if ($replicate) { $this->headers[$name] = $this->claims[$name]; } return $this; }
php
{ "resource": "" }
q452
Builder.setHeader
train
public function setHeader($name, $value) { if ($this->signature) { throw new \BadMethodCallException('You must unsign before make changes'); } $this->headers[(string) $name] = $this->claimFactory->create($name, $value); return $this; }
php
{ "resource": "" }
q453
Builder.set
train
public function set($name, $value) { if ($this->signature) { throw new \BadMethodCallException('You must unsign before make changes'); } $this->claims[(string) $name] = $this->claimFactory->create($name, $value); return $this; }
php
{ "resource": "" }
q454
Builder.sign
train
public function sign(Signer $signer, $key) { $signer->modifyHeader($this->headers); $this->signature = $signer->sign( $this->getToken()->getPayload(), $key ); return $this; }
php
{ "resource": "" }
q455
Builder.getToken
train
public function getToken() { $payload = array( $this->serializer->toBase64URL($this->serializer->toJSON($this->headers)), $this->serializer->toBase64URL($this->serializer->toJSON($this->claims)) ); if ($this->signature !== null) { $payload[] = $this->serializer->toBase64URL($this->signature); } return new Token($this->headers, $this->claims, $this->signature, $payload); }
php
{ "resource": "" }
q456
EavManager.initializeEntity
train
public function initializeEntity(SchemaInterface $schema) { $valueSet = $this->createValueSet(); $valueSet->setSchema($schema); // To avoid persisting Value entities with no actual value to the database // we create empty ones, that will be removed on postPersist events. $this->replaceEmptyValues($valueSet); $entity = $schema->getObjectClass(); $entity = new $entity(); if (!$entity instanceof EntityInterface) { throw new \Exception(sprintf('The entity specified in schema "%d" schema must implement Opifer\EavBundle\Model\EntityInterface.', $schema->getId())); } $entity->setValueSet($valueSet); $entity->setSchema($schema); return $entity; }
php
{ "resource": "" }
q457
EavManager.replaceEmptyValues
train
public function replaceEmptyValues(ValueSetInterface $valueSet) { // collect persisted attributevalues $persistedAttributes = array(); foreach ($valueSet->getValues() as $value) { $persistedAttributes[] = $value->getAttribute(); } $newValues = array(); // Create empty entities for missing attributes $missingAttributes = array_diff($valueSet->getAttributes()->toArray(), $persistedAttributes); foreach ($missingAttributes as $attribute) { $provider = $this->providerPool->getValue($attribute->getValueType()); $valueClass = $provider->getEntity(); $value = new $valueClass(); $valueSet->addValue($value); $value->setValueSet($valueSet); $value->setAttribute($attribute); $newValues[] = $value; } return $newValues; }
php
{ "resource": "" }
q458
Hmac.hashEquals
train
public function hashEquals($expected, $generated) { $expectedLength = strlen($expected); if ($expectedLength !== strlen($generated)) { return false; } $res = 0; for ($i = 0; $i < $expectedLength; ++$i) { $res |= ord($expected[$i]) ^ ord($generated[$i]); } return $res === 0; }
php
{ "resource": "" }
q459
Generator.make
train
protected function make($filenames, $template = 'base.php.twig', array $options = array()) { foreach ((array) $filenames as $filename) { if (! $this->getOption('force') && $this->fs->exists($filename)) { throw new \RuntimeException(sprintf('Cannot duplicate %s', $filename)); } $reflection = new \ReflectionClass(get_class($this)); if ($reflection->getShortName() === 'Migration') { $this->twig->addFunction(new \Twig_SimpleFunction('argument', function ($field = "") { return array_combine(array('name','type'), explode(':', $field)); } )); foreach ($this->getArgument('options') as $option) { list($key, $value) = explode(':', $option); $options[$key] = $value; } } $output = $this->twig->loadTemplate($template)->render($options); $this->fs->dumpFile($filename, $output); } return true; }
php
{ "resource": "" }
q460
Generator.createDirectory
train
public function createDirectory($dirPath) { if (! $this->fs->exists($dirPath)) { $this->fs->mkdir($dirPath); } }
php
{ "resource": "" }
q461
MediaListener.getProvider
train
public function getProvider(LifecycleEventArgs $args) { $provider = $args->getObject()->getProvider(); if (!$provider) { throw new \Exception('Please set a provider on the entity before persisting any media'); } return $this->container->get('opifer.media.provider.pool')->getProvider($provider); }
php
{ "resource": "" }
q462
VimeoProvider.saveThumbnail
train
public function saveThumbnail(MediaInterface $media, $url) { $thumb = $this->mediaManager->createMedia(); $thumb ->setStatus(Media::STATUS_HASPARENT) ->setName($media->getName().'_thumb') ->setProvider('image') ; $filename = '/tmp/'.basename($url); $filesystem = new Filesystem(); $filesystem->dumpFile($filename, file_get_contents($url)); $thumb->temp = $filename; $thumb->setFile(new UploadedFile($filename, basename($url))); $this->mediaManager->save($thumb); return $thumb; }
php
{ "resource": "" }
q463
FormSubmitListener.postFormSubmit
train
public function postFormSubmit(FormSubmitEvent $event) { $post = $event->getPost(); $mailinglists = $email = null; foreach ($post->getValueSet()->getValues() as $value) { if ($value instanceof MailingListSubscribeValue && $value->getValue() == true) { $parameters = $value->getAttribute()->getParameters(); if (isset($parameters['mailingLists'])) { $mailinglists = $this->mailingListManager->getRepository()->findByIds($parameters['mailingLists']); } } elseif ($value instanceof EmailValue) { $email = $value->getValue(); } } if ($email && $mailinglists) { foreach ($mailinglists as $mailinglist) { $subscription = new Subscription(); $subscription->setEmail($email); $subscription->setMailingList($mailinglist); $this->subscriptionManager->save($subscription); } } }
php
{ "resource": "" }
q464
Ballot.initDefaultMentions
train
public function initDefaultMentions(): Ballot{ $this->mentions=[new Mention("Excellent"),new Mention("Good"),new Mention("Pretty good"),new Mention("Fair"),new Mention("Insufficient"),new Mention("To Reject")]; return $this; }
php
{ "resource": "" }
q465
Block.hasSharedParent
train
public function hasSharedParent() { $parent = $this->getParent(); if ($parent != null && ($parent->isShared() || $parent->hasSharedParent())) { return true; } return false; }
php
{ "resource": "" }
q466
StringHelper.replaceLinks
train
public function replaceLinks($string) { preg_match_all('/(\[content_url\](.*?)\[\/content_url\]|\[content_url\](.*?)\[\\\\\/content_url\])/', $string, $matches); if (!count($matches)) { return $string; } if (!empty($matches[3][0])) { $matches[1] = $matches[3]; } elseif (!empty($matches[2][0])) { $matches[1] = $matches[2]; } /** @var ContentInterface[] $contents */ $contents = $this->contentManager->getRepository()->findByIds($matches[1]); $array = []; foreach ($contents as $content) { $array[$content->getId()] = $content; } foreach ($matches[0] as $key => $match) { if (isset($array[$matches[1][$key]])) { $content = $array[$matches[1][$key]]; $url = $this->router->generate('_content', ['slug' => $content->getSlug()]); } else { $url = $this->router->generate('_content', ['slug' => '404']); } $string = str_replace($match, $url, $string); } return $string; }
php
{ "resource": "" }
q467
BoxModelDataTransformer.transform
train
public function transform($original) { if (!$original) { return $original; } $string = substr($original, 1); $split = explode('-', $string); return [ 'side' => $split[0], 'size' => $split[1], ]; }
php
{ "resource": "" }
q468
BlockListener.getService
train
public function getService(LifecycleEventArgs $args) { $service = $args->getObject(); if (!$service) { throw new \Exception('Please set a provider on the entity before persisting any media'); } return $this->getBlockManager()->getService($service); }
php
{ "resource": "" }
q469
ContentController.createAction
train
public function createAction(Request $request, $siteId = null, $type = 0, $layoutId = null) { /** @var ContentManager $manager */ $manager = $this->get('opifer.content.content_manager'); if ($type) { $contentType = $this->get('opifer.content.content_type_manager')->getRepository()->find($type); $content = $this->get('opifer.eav.eav_manager')->initializeEntity($contentType->getSchema()); $content->setContentType($contentType); } else { $content = $manager->initialize(); } if ($siteId) { $site = $this->getDoctrine()->getRepository(Site::class)->find($siteId); //set siteId on content item $content->setSite($site); if ($site->getDefaultLocale()) { $content->setLocale($site->getDefaultLocale()); } } $form = $this->createForm(ContentType::class, $content); $form->handleRequest($request); if ($form->isValid()) { if ($layoutId) { $duplicatedContent = $this->duplicateAction($layoutId, $content); return $this->redirectToRoute('opifer_content_contenteditor_design', [ 'owner' => 'content', 'ownerId' => $duplicatedContent->getId(), ]); } if (null === $content->getPublishAt()) { $content->setPublishAt(new \DateTime()); } $manager->save($content); return $this->redirectToRoute('opifer_content_contenteditor_design', [ 'owner' => 'content', 'ownerId' => $content->getId(), 'site_id' => $siteId ]); } return $this->render($this->getParameter('opifer_content.content_new_view'), [ 'form' => $form->createView(), ]); }
php
{ "resource": "" }
q470
ContentController.editAction
train
public function editAction(Request $request, $id) { /** @var ContentManager $manager */ $manager = $this->get('opifer.content.content_manager'); $em = $manager->getEntityManager(); $content = $manager->getRepository()->find($id); $content = $manager->createMissingValueSet($content); // Load the contentTranslations for the content group if ($content->getTranslationGroup() !== null) { $contentTranslations = $content->getTranslationGroup()->getContents()->filter(function($contentTranslation) use ($content) { return $contentTranslation->getId() !== $content->getId(); }); $content->setContentTranslations($contentTranslations); } $form = $this->createForm(ContentType::class, $content); $originalContentItems = new ArrayCollection(); foreach ($content->getContentTranslations() as $contentItem) { $originalContentItems->add($contentItem); } $form->handleRequest($request); if ($form->isValid()) { if (null === $content->getPublishAt()) { $content->setPublishAt($content->getCreatedAt()); } if ($content->getTranslationGroup() === null) { // Init new group $translationGroup = new TranslationGroup(); $content->setTranslationGroup($translationGroup); } // Make sure all the contentTranslations have the same group as content $contentTranslationIds = [$content->getId()]; foreach($content->getContentTranslations() as $contentTranslation) { if ($contentTranslation->getTranslationGroup() === null) { $contentTranslation->setTranslationGroup($content->getTranslationGroup()); $em->persist($contentTranslation); } $contentTranslationIds[] = $contentTranslation->getId(); } // Remove possible contentTranslations from the translationGroup $queryBuilder = $manager->getRepository()->createQueryBuilder('c'); $queryBuilder->update() ->set('c.translationGroup', 'NULL') ->where($queryBuilder->expr()->eq('c.translationGroup', $content->getTranslationGroup()->getId())) ->where($queryBuilder->expr()->notIn('c.id', $contentTranslationIds)) ->getQuery() ->execute(); $em->persist($content); $em->flush(); return $this->redirectToRoute('opifer_content_content_index'); } return $this->render($this->getParameter('opifer_content.content_edit_view'), [ 'content' => $content, 'form' => $form->createView(), ]); }
php
{ "resource": "" }
q471
MediaEventSubscriber.onPostSerialize
train
public function onPostSerialize(ObjectEvent $event) { // getSubscribedEvents doesn't seem to support parent classes if (!$event->getObject() instanceof MediaInterface) { return; } /** @var MediaInterface $media */ $media = $event->getObject(); $provider = $this->getProvider($media); if ($provider->getName() == 'image') { $images = $this->getImages($media, ['medialibrary']); $event->getVisitor()->addData('images', $images); } $event->getVisitor()->addData('original', $provider->getUrl($media)); }
php
{ "resource": "" }
q472
MediaEventSubscriber.getImages
train
public function getImages(MediaInterface $media, array $filters) { $key = $media->getImagesCacheKey(); if (!$images = $this->cache->fetch($key)) { $provider = $this->getProvider($media); $reference = $provider->getThumb($media); $images = []; foreach ($filters as $filter) { if ($media->getContentType() == 'image/svg+xml') { $images[$filter] = $provider->getUrl($media); } else { $images[$filter] = $this->cacheManager->getBrowserPath($reference, $filter); } } $this->cache->save($key, $images, 0); } return $images; }
php
{ "resource": "" }
q473
RelatedCollectionBlockService.getAttributes
train
protected function getAttributes(ContentInterface $owner) { /** @var AttributeInterface $attributes */ $attributes = $owner->getValueSet()->getAttributes(); $choices = []; foreach ($attributes as $attribute) { if (!in_array($attribute->getValueType(), ['select', 'radio', 'checklist'])) { continue; } $choices[$attribute->getDisplayName()] = $attribute->getName(); } return $choices; }
php
{ "resource": "" }
q474
PostController.viewAction
train
public function viewAction($id) { $post = $this->get('opifer.form.post_manager')->getRepository()->find($id); if (!$post) { return $this->createNotFoundException(); } return $this->render($this->getParameter('opifer_form.post_view_view'), [ 'post' => $post, ]); }
php
{ "resource": "" }
q475
PostController.notificationAction
train
public function notificationAction($id) { /** @var PostInterface $post */ $post = $this->get('opifer.form.post_manager')->getRepository()->find($id); if (!$post) { return $this->createNotFoundException(); } $form = $post->getForm(); /** @var Mailer $mailer */ $mailer = $this->get('opifer.form.mailer'); $mailer->sendNotificationMail($form, $post); $this->addFlash('success', 'Notification mail sent successfully'); return $this->redirectToRoute('opifer_form_post_index', ['formId' => $form->getId()]); }
php
{ "resource": "" }
q476
ConfigManager.keyValues
train
public function keyValues($form = null) { if (null === $this->configs) { $this->loadConfigs(); } $keys = ($form) ? call_user_func([$form, 'getFields']) : []; $array = []; foreach ($this->configs as $key => $config) { if ($form && !in_array($key, $keys)) { continue; } $array[$key] = $config->getValue(); } return $array; }
php
{ "resource": "" }
q477
ConfigManager.loadConfigs
train
public function loadConfigs() { $configs = []; foreach ($this->getRepository()->findAll() as $config) { $configs[$config->getName()] = $config; } $this->configs = $configs; return $configs; }
php
{ "resource": "" }
q478
FormController.indexAction
train
public function indexAction() { $forms = $this->get('opifer.form.form_manager')->getRepository() ->findAllWithPosts(); return $this->render($this->getParameter('opifer_form.form_index_view'), [ 'forms' => $forms, ]); }
php
{ "resource": "" }
q479
FormController.createAction
train
public function createAction(Request $request) { $formManager = $this->get('opifer.form.form_manager'); $form = $formManager->create(); $formType = $this->createForm(FormType::class, $form); $formType->handleRequest($request); if ($formType->isSubmitted() && $formType->isValid()) { foreach ($formType->getData()->getSchema()->getAttributes() as $attribute) { $attribute->setSchema($form->getSchema()); foreach ($attribute->getOptions() as $option) { $option->setAttribute($attribute); } } $formManager->save($form); $this->addFlash('success', 'Form has been created successfully'); return $this->redirectToRoute('opifer_form_form_edit', ['id' => $form->getId()]); } return $this->render($this->getParameter('opifer_form.form_create_view'), [ 'form' => $form, 'form_form' => $formType->createView(), ]); }
php
{ "resource": "" }
q480
FormController.editAction
train
public function editAction(Request $request, $id) { $formManager = $this->get('opifer.form.form_manager'); $em = $this->get('doctrine.orm.entity_manager'); $form = $formManager->getRepository()->find($id); if (!$form) { return $this->createNotFoundException(); } $originalAttributes = new ArrayCollection(); foreach ($form->getSchema()->getAttributes() as $attributes) { $originalAttributes->add($attributes); } $formType = $this->createForm(FormType::class, $form); $formType->handleRequest($request); if ($formType->isSubmitted() && $formType->isValid()) { // Remove deleted attributes foreach ($originalAttributes as $attribute) { if (false === $form->getSchema()->getAttributes()->contains($attribute)) { $em->remove($attribute); } } // Add new attributes foreach ($formType->getData()->getSchema()->getAttributes() as $attribute) { $attribute->setSchema($form->getSchema()); foreach ($attribute->getOptions() as $option) { $option->setAttribute($attribute); } } $formManager->save($form); $this->addFlash('success', 'Event has been updated successfully'); return $this->redirectToRoute('opifer_form_form_edit', ['id' => $form->getId()]); } return $this->render($this->getParameter('opifer_form.form_edit_view'), [ 'form' => $form, 'form_form' => $formType->createView(), ]); }
php
{ "resource": "" }
q481
ContentController.homeAction
train
public function homeAction(Request $request) { /** @var BlockManager $manager */ $manager = $this->get('opifer.content.content_manager'); $host = $request->getHost(); $em = $this->getDoctrine()->getManager(); $siteCount = $em->getRepository(Site::class)->createQueryBuilder('s') ->select('count(s.id)') ->getQuery() ->getSingleScalarResult(); $domain = $em->getRepository(Domain::class)->findOneByDomain($host); if ($siteCount && $domain->getSite()->getDefaultLocale()) { $request->setLocale($domain->getSite()->getDefaultLocale()->getLocale()); } if (!$domain && $siteCount > 1) { return $this->render('OpiferContentBundle:Content:domain_not_found.html.twig'); } $content = $manager->getRepository()->findActiveBySlug('index', $host); return $this->forward('OpiferContentBundle:Frontend/Content:view', [ 'content' => $content ]); }
php
{ "resource": "" }
q482
Parser.parse
train
public function parse($jwt) { $data = $this->splitJwt($jwt); $header = $this->parseHeader($data[0]); $claims = $this->parseClaims($data[1]); $signature = $this->parseSignature($header, $data[2]); foreach ($claims as $name => $value) { if (isset($header[$name])) { $header[$name] = $value; } } if ($signature === null) { unset($data[2]); } return new Token($header, $claims, $signature, $data); }
php
{ "resource": "" }
q483
Parser.splitJwt
train
protected function splitJwt($jwt) { if (!is_string($jwt)) { throw new \InvalidArgumentException('The JWT string must have two dots'); } $data = explode('.', $jwt); if (count($data) != 3) { throw new \InvalidArgumentException('The JWT string must have two dots'); } return $data; }
php
{ "resource": "" }
q484
Parser.parseHeader
train
protected function parseHeader($data) { $header = (array) $this->deserializer->fromJSON($this->deserializer->fromBase64URL($data)); if (isset($header['enc'])) { throw new \InvalidArgumentException('Encryption is not supported yet'); } return $header; }
php
{ "resource": "" }
q485
Parser.parseClaims
train
protected function parseClaims($data) { $claims = (array) $this->deserializer->fromJSON($this->deserializer->fromBase64URL($data)); foreach ($claims as $name => &$value) { $value = $this->claimFactory->create($name, $value); } return $claims; }
php
{ "resource": "" }
q486
Parser.parseSignature
train
protected function parseSignature(array $header, $data) { if ($data == '' || !isset($header['alg']) || $header['alg'] == 'none') { return null; } $hash = $this->deserializer->fromBase64URL($data); return new Signature($hash); }
php
{ "resource": "" }
q487
Content.getBaseSlug
train
public function getBaseSlug() { $slug = $this->slug; if (substr($slug, -6) == '/index') { $slug = rtrim($slug, 'index'); } return $slug; }
php
{ "resource": "" }
q488
Content.getBreadCrumbs
train
public function getBreadCrumbs() { $crumbs = []; if (null !== $this->parent) { $crumbs = $this->getParent()->getBreadCrumbs(); } $crumbs[$this->slug] = $this->getShortTitle(); return $crumbs; }
php
{ "resource": "" }
q489
Content.getParents
train
public function getParents($includeSelf = true) { $parents = []; if (null !== $this->parent) { $parents = $this->getParent()->getParents(); } if ($includeSelf) { $parents[] = $this; } return $parents; }
php
{ "resource": "" }
q490
Content.getCoverImage
train
public function getCoverImage() { if ($this->getValueSet() !== null) { foreach ($this->getValueSet()->getValues() as $value) { if ($value instanceof MediaValue && false !== $media = $value->getMedias()->first()) { return $media->getReference(); } } } foreach ($this->getBlocks() as $block) { $reflect = new \ReflectionClass($block); if ($reflect->hasProperty('media') && $block->getMedia()) { return $block->getMedia()->getReference(); } } return false; }
php
{ "resource": "" }
q491
Field.getCustomFieldOption
train
public static function getCustomFieldOption(JiraClient $client, $id) { $path = "/customFieldOption/{$id}"; try { $data = $client->callGet($path)->getData(); $data['id'] = $id; return new CustomFieldOption($client, $data); } catch (Exception $e) { throw new JiraException("Failed to get custom field option", $e); } }
php
{ "resource": "" }
q492
CmsKernel.registerBundles
train
public function registerBundles() { $bundles = [ // Symfony standard bundles new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new \Symfony\Bundle\SecurityBundle\SecurityBundle(), new \Symfony\Bundle\TwigBundle\TwigBundle(), new \Symfony\Bundle\MonologBundle\MonologBundle(), new \Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new \Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new \Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), // Added vendor bundles new \APY\DataGridBundle\APYDataGridBundle(), new \Bazinga\Bundle\JsTranslationBundle\BazingaJsTranslationBundle(), new \Braincrafted\Bundle\BootstrapBundle\BraincraftedBootstrapBundle(), new \Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(), new \FOS\JsRoutingBundle\FOSJsRoutingBundle(), new \FOS\RestBundle\FOSRestBundle(), new \FOS\UserBundle\FOSUserBundle(), new \JMS\SerializerBundle\JMSSerializerBundle(), new \Knp\Bundle\GaufretteBundle\KnpGaufretteBundle(), new \Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle(), new \Lexik\Bundle\TranslationBundle\LexikTranslationBundle(), new \Liip\ImagineBundle\LiipImagineBundle(), new \Limenius\LiformBundle\LimeniusLiformBundle(), new \Nelmio\ApiDocBundle\NelmioApiDocBundle(), new \Nelmio\CorsBundle\NelmioCorsBundle(), new \Scheb\TwoFactorBundle\SchebTwoFactorBundle(), new \Symfony\Cmf\Bundle\RoutingBundle\CmfRoutingBundle(), // Opifer bundles new \Opifer\CmsBundle\OpiferCmsBundle(), new \Opifer\ContentBundle\OpiferContentBundle(), new \Opifer\EavBundle\OpiferEavBundle(), new \Opifer\FormBundle\OpiferFormBundle(), new \Opifer\FormBlockBundle\OpiferFormBlockBundle(), new \Opifer\MediaBundle\OpiferMediaBundle(), new \Opifer\RedirectBundle\OpiferRedirectBundle(), new \Opifer\ReviewBundle\OpiferReviewBundle(), new \Opifer\MailingListBundle\OpiferMailingListBundle(), new \Opifer\Revisions\OpiferRevisionsBundle(), new \Opifer\BootstrapBlockBundle\OpiferBootstrapBlockBundle(), ]; if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new \Symfony\Bundle\DebugBundle\DebugBundle(); $bundles[] = new \Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new \Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new \Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; }
php
{ "resource": "" }
q493
FormManager.createForm
train
public function createForm(FormInterface $form, PostInterface $post) { return $this->formFactory->create(PostType::class, $post, ['form_id' => $form->getId()]); }
php
{ "resource": "" }
q494
PaymentMethods.toOptionArray
train
public function toOptionArray() { $return = []; $paymentMethodCodes = $this->_installmentsHelper->getAllInstallmentPaymentMethodCodes(); foreach ($paymentMethodCodes as $paymentMethodCode) { $return[] = [ 'value' => $paymentMethodCode, 'label' => ucfirst(str_replace('_', ' ', $paymentMethodCode)) ]; } return $return; }
php
{ "resource": "" }
q495
Image.appendTiff
train
public function appendTiff($appendFile = "") { //check whether file is set or not if ($appendFile == '') throw new Exception('No file name specified'); $strURI = Product::$baseProductUri . '/imaging/tiff/' . $this->getFileName() . '/appendTiff?appendFile=' . $appendFile; $signedURI = Utils::sign($strURI); $responseStream = Utils::processCommand($signedURI, 'POST', '', ''); $json = json_decode($responseStream); if ($json->Status == 'OK') { $folder = new Folder(); $outputStream = $folder->getFile($this->getFileName()); $outputPath = AsposeApp::$outPutLocation . $this->getFileName(); Utils::saveFile($outputStream, $outputPath); return $outputPath; } else { return false; } }
php
{ "resource": "" }
q496
Image.resizeImage
train
public function resizeImage($inputPath, $newWidth, $newHeight, $outputFormat) { //check whether files are set or not if ($inputPath == '') throw new Exception('Base file not specified'); if ($newWidth == '') throw new Exception('New image width not specified'); if ($newHeight == '') throw new Exception('New image height not specified'); if ($outputFormat == '') throw new Exception('Format not specified'); //build URI $strURI = Product::$baseProductUri . '/imaging/resize?newWidth=' . $newWidth . '&newHeight=' . $newHeight . '&format=' . $outputFormat; //sign URI $signedURI = Utils::sign($strURI); $responseStream = Utils::uploadFileBinary($signedURI, $inputPath, 'xml', 'POST'); $v_output = Utils::validateOutput($responseStream); if ($v_output === '') { if ($outputFormat == 'html') { $saveFormat = 'zip'; } else { $saveFormat = $outputFormat; } $outputFilename = Utils::getFileName($inputPath) . '.' . $saveFormat; Utils::saveFile($responseStream, AsposeApp::$outPutLocation . $outputFilename); return $outputFilename; } else return $v_output; }
php
{ "resource": "" }
q497
Image.cropImage
train
public function cropImage($x, $y, $width, $height, $outputFormat, $outPath) { //check whether files are set or not if ($this->getFileName() == '') throw new Exception('Base file not specified'); if ($x == '') throw new Exception('X position not specified'); if ($y == '') throw new Exception('Y position not specified'); if ($width == '') throw new Exception('Width not specified'); if ($height == '') throw new Exception('Height not specified'); if ($outputFormat == '') throw new Exception('Format not specified'); if ($outPath == '') throw new Exception('Output file name not specified'); //build URI $strURI = Product::$baseProductUri . '/imaging/' . $this->getFileName() . '/crop?x=' . $x . '&y=' . $y . '&width=' . $width . '&height=' . $height . '&format=' . $outputFormat . '&outPath=' . $outPath; //sign URI $signedURI = Utils::sign($strURI); $responseStream = Utils::processCommand($signedURI, 'GET', '', ''); $v_output = Utils::validateOutput($responseStream); if ($v_output === '') { if ($outputFormat == 'html') { $saveFormat = 'zip'; } else { $saveFormat = $outputFormat; } Utils::saveFile($responseStream, AsposeApp::$outPutLocation . $outPath); return $outPath; } else return $v_output; }
php
{ "resource": "" }
q498
Image.rotateImage
train
public function rotateImage($method, $outputFormat, $outPath) { if ($method == '') throw new Exception('RotateFlip method not specified'); if ($outputFormat == '') throw new Exception('Format not specified'); if ($outPath == '') throw new Exception('Output file name not specified'); //build URI $strURI = Product::$baseProductUri . '/imaging/' . $this->getFileName() . '/rotateflip?method=' . $method . '&format=' . $outputFormat . '&outPath=' . $outPath; //sign URI $signedURI = Utils::sign($strURI); $responseStream = Utils::processCommand($signedURI, 'GET', '', ''); $v_output = Utils::validateOutput($responseStream); if ($v_output === '') { if ($outputFormat == 'html') { $saveFormat = 'zip'; } else { $saveFormat = $outputFormat; } Utils::saveFile($responseStream, AsposeApp::$outPutLocation . $outPath); return $outPath; } else return $v_output; }
php
{ "resource": "" }
q499
Image.updateImage
train
public function updateImage($rotateFlipMethod, $newWidth, $newHeight, $xPosition, $yPosition, $rectWidth, $rectHeight, $saveFormat, $outPath) { if ($rotateFlipMethod == '') throw new Exception('Rotate Flip Method not specified'); if ($newWidth == '') throw new Exception('New width not specified'); if ($newHeight == '') throw new Exception('New Height not specified'); if ($xPosition == '') throw new Exception('X position not specified'); if ($yPosition == '') throw new Exception('Y position not specified'); if ($rectWidth == '') throw new Exception('Rectangle width not specified'); if ($rectHeight == '') throw new Exception('Rectangle Height not specified'); if ($saveFormat == '') throw new Exception('Format not specified'); if ($outPath == '') throw new Exception('Output file name not specified'); //build URI $strURI = Product::$baseProductUri . '/imaging/' . $this->getFileName() . '/updateimage?rotateFlipMethod=' . $rotateFlipMethod . '&newWidth=' . $newWidth . '&newHeight=' . $newHeight . '&x=' . $xPosition . '&y=' . $yPosition . '&rectWidth=' . $rectWidth . '&rectHeight=' . $rectHeight . '&format=' . $saveFormat . '&outPath=' . $outPath; //sign URI $signedURI = Utils::sign($strURI); $responseStream = Utils::processCommand($signedURI, 'GET', '', ''); //$json = json_decode($response); $v_output = Utils::validateOutput($responseStream); if ($v_output === '') { $outputPath = AsposeApp::$outPutLocation . $this->getFileName(); Utils::saveFile($responseStream, $outputPath); return $outputPath; } else return false; }
php
{ "resource": "" }