_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q300
Issue.addComment
train
public function addComment($issue, $body, $visibilityType = null, $visibilityName = null, $expand = false) { $path = "/issue/{$issue}/comment" . ($expand ? '?expand' : ''); $data = array( 'body' => $body ); if ($visibilityType !== null && $visibilityName !== null) { $data['visibility'] = array( 'type' => $visibilityType, 'value' => $visibilityName ); } try { $result = $this->client->callPost($path, $data); return new Comment($this->client, $result->getData()); } catch (Exception $e) { throw new JiraException("Failed to add comment", $e); } }
php
{ "resource": "" }
q301
Issue.deleteComment
train
public function deleteComment($issue, $commentId) { $path = "/issue/{$issue}/comment/{$commentId}"; try { $this->client->callDelete($path); } catch (Exception $e) { throw new JiraException("Failed to delete comment", $e); } }
php
{ "resource": "" }
q302
Issue.getEditMetadata
train
public function getEditMetadata($issue) { $path = "/issue/{$issue}/editmeta"; try { $data = $this->client->callGet($path)->getData(); if (!isset($data['fields'])) { throw new JiraException("Bad metadata"); } return $data; } catch (Exception $e) { throw new JiraException("Failed to retrieve issue metadata", $e); } }
php
{ "resource": "" }
q303
Issue.addWatcher
train
public function addWatcher($issue, $login) { $path = "/issue/{$issue}/watchers"; try { $this->client->callPost($path, $login); } catch (Exception $e) { throw new JiraException("Failed to add watcher '{$login}' to issue '{$issue}'", $e); } return $this; }
php
{ "resource": "" }
q304
Issue.deleteWatcher
train
public function deleteWatcher($issue, $login) { $path = "/issue/{$issue}/watchers?username={$login}"; try { $this->client->callDelete($path); } catch (Exception $e) { throw new JiraException("Failed to delete watcher '{$login}' to issue '{$issue}'", $e); } }
php
{ "resource": "" }
q305
Issue.get
train
public function get($issue, $includedFields = null, $expandFields = false) { $params = array(); if ($includedFields !== null) { $params['fields'] = $includedFields; } if ($expandFields) { $params['expand'] = ''; } $path = "/issue/{$issue}?" . http_build_query($params); $result = $this->client->callGet($path)->getData(); return new \JiraClient\Resource\Issue($this->client, $result); }
php
{ "resource": "" }
q306
Packetizer.findall
train
protected function findall(string $haystack, $needle): array { $lastPos = 0; $positions = []; while (($lastPos = strpos($haystack, $needle, $lastPos)) !== false) { $positions[] = $lastPos; $lastPos = $lastPos + 1; } return $positions; }
php
{ "resource": "" }
q307
Packetizer.findFirstPacketOffset
train
protected function findFirstPacketOffset() { // This is quite ugly because it will parse the entire buffer whatever it's size is // TODO Rewrite this in a more clever way $positions = $this->findall($this->buffer, 'G'); while (count($positions) > 0) { $position = array_shift($positions); for ($i = 1; $i <= $this->consecutivePacketsBeforeLock; $i++) { if (!in_array($position + 188 * $i, $positions)) { break; } return $position; } } return false; }
php
{ "resource": "" }
q308
BaseCollector.extGetLL
train
protected function extGetLL($key, $convertWithHtmlspecialchars = true) { $labelStr = $this->getLanguageService()->getLL($key); if ($convertWithHtmlspecialchars) { $labelStr = htmlspecialchars($labelStr); } return $labelStr; }
php
{ "resource": "" }
q309
BaseCollector.extGetFeAdminValue
train
public function extGetFeAdminValue($sectionName, $val = '') { $beUser = $this->getBackendUser(); // Override all settings with user TSconfig if ($val && isset($beUser->extAdminConfig['override.'][$sectionName . '.'][$val])) { return $beUser->extAdminConfig['override.'][$sectionName . '.'][$val]; } if (!$val && isset($beUser->extAdminConfig['override.'][$sectionName])) { return $beUser->extAdminConfig['override.'][$sectionName]; } $returnValue = $val ? $beUser->uc['TSFE_adminConfig'][$sectionName . '_' . $val] : 1; // Exception for preview return !$val ? true : $returnValue; }
php
{ "resource": "" }
q310
CollectionBlockService.loadCollection
train
protected function loadCollection(BlockInterface $block) { $properties = $block->getProperties(); $conditions = (isset($properties['conditions'])) ? $properties['conditions'] : '[]'; $conditions = $this->expressionEngine->deserialize($conditions); if (empty($conditions)) { return; } $site = $this->siteManager->getSite(); $qb = $this->expressionEngine->toQueryBuilder($conditions, $this->contentManager->getClass()); $qb->andWhere('a.publishAt < :now OR a.publishAt IS NULL') ->andWhere('a.active = :active') ->andWhere('a.layout = :layout'); if ($site == null) { $qb->andWhere('a.site IS NULL'); } else { $qb->andWhere('a.site = :site') ->setParameter('site', $site); } $qb->setParameter('active', true) ->setParameter('layout', false) ->setParameter('now', new \DateTime()); if (isset($properties['order_by'])) { $direction = (isset($properties['order_direction'])) ? $properties['order_direction'] : 'ASC'; $qb->orderBy('a.'.$properties['order_by'], $direction); } $limit = (isset($properties['limit'])) ? $properties['limit'] : 10; $qb->setMaxResults($limit); $collection = $qb->getQuery()->getResult(); if ($collection) { $block->setCollection($collection); } }
php
{ "resource": "" }
q311
PointerBlockService.setResponseHeaders
train
protected function setResponseHeaders(BlockInterface $block, Response $response) { if ($block && $block->getReference()) { if ($this->getReferenceService($block)->isEsiEnabled($block->getReference())) { $this->getReferenceService($block)->setResponseHeaders($block->getReference(), $response); } else { $response->setLastModified($block->getReference()->getUpdatedAt()); $response->setPublic(); } } }
php
{ "resource": "" }
q312
PostController.listAction
train
public function listAction() { $source = new Entity($this->get('opifer.form.post_manager')->getClass()); $formColumn = new TextColumn(['id' => 'posts', 'title' => 'Form', 'source' => false, 'filterable' => false, 'sortable' => false, 'safe' => false]); $formColumn->manipulateRenderCell(function ($value, $row, $router) { return '<a href="'.$this->generateUrl('opifer_form_form_edit', ['id'=> $row->getEntity()->getForm()->getId()]).'">'.$row->getEntity()->getForm()->getName().'</a>'; }); $viewAction = new RowAction('view', 'opifer_form_post_view'); $viewAction->setRouteParameters(['id']); $deleteAction = new RowAction('delete', 'opifer_form_post_delete'); $deleteAction->setRouteParameters(['id']); $grid = $this->get('grid'); $grid->setId('posts') ->setSource($source) ->setDefaultOrder('id', 'desc') ->addColumn($formColumn, 2) ->addRowAction($viewAction) ->addRowAction($deleteAction); return $grid->getGridResponse('OpiferCmsBundle:Backend/Post:list.html.twig'); }
php
{ "resource": "" }
q313
plgSystemBasicAuth.onAfterRoute
train
public function onAfterRoute() { $app = JFactory::getApplication(); $username = $app->input->server->get('PHP_AUTH_USER', null, 'string'); $password = $app->input->server->get('PHP_AUTH_PW', null, 'string'); if ($username && $password) { if (!$this->_login($username, $password, $app)) { throw new Exception('Login failed', 401); } } }
php
{ "resource": "" }
q314
plgSystemBasicAuth._login
train
protected function _login($username, $password, $application) { // If we did receive the user credentials from the user, try to login if($application->login(array('username' => $username, 'password' => $password)) !== true) { return false; } // If we have logged in succesfully, make sure to fullfil // Koowa's CSRF authenticator checks if the framework is loaded. if (class_exists('Koowa')) { $manager = KObjectManager::getInstance(); $request = $manager->getInstance()->getObject('com:koowa.dispatcher.request'); $user = $manager->getInstance()->getObject('user'); $token = $user->getSession()->getToken(); $request->setReferrer(JUri::root()); $request->getHeaders()->add(array('X-Xsrf-Token' => $token)); $request->getCookies()->add(array('csrf_token' => $token)); } return true; }
php
{ "resource": "" }
q315
Media.getReadableFilesize
train
public function getReadableFilesize() { $size = $this->filesize; if ($size < 1) { return $size; } if ($size < 1024) { return $size.'b'; } else { $help = $size / 1024; if ($help < 1024) { return round($help, 1).'kb'; } else { return round(($help / 1024), 1).'mb'; } } }
php
{ "resource": "" }
q316
MediaRepository.createQueryBuilderFromRequest
train
public function createQueryBuilderFromRequest(Request $request) { $qb = $this->createQueryBuilder('m'); if ($request->get('ids')) { $ids = explode(',', $request->get('ids')); $qb->andWhere('m.id IN (:ids)')->setParameter('ids', $ids); } $qb->andWhere('m.status = :status')->setParameter('status', Media::STATUS_ENABLED); if ($request->get('search')) { $qb->andWhere('m.name LIKE :term')->setParameter('term', '%'.$request->get('search').'%'); } if ($request->get('order')) { $direction = ($request->get('orderdir')) ? $request->get('orderdir') : 'asc'; $qb->orderBy('m.'.$request->get('order'), $direction); } return $qb; }
php
{ "resource": "" }
q317
MediaRepository.search
train
public function search($term, $limit, $offset, $orderBy = null) { $qb = $this->createQueryBuilder('m'); $qb->where('m.name LIKE :term') ->andWhere('m.status IN (:statuses)') ->setParameters(array( 'term' => '%'.$term.'%', 'statuses' => array(0, 1), ) ); if ($limit) { $qb->setMaxResults($limit); } if ($offset) { $qb->setFirstResult($offset); } return $qb->getQuery()->getResult(); }
php
{ "resource": "" }
q318
FilterableTrait.setQuerystring
train
public function setQuerystring(array $str = array(), $append = true, $default = true) { if ( is_null($this->filterable) ) { $this->resetFilterableOptions(); } if ( sizeof($str) == 0 && $default ) { // Default to PHP query string parse_str($_SERVER['QUERY_STRING'], $this->filterable['qstring']); } else { $this->filterable['qstring'] = $str; } if ( sizeof($this->filterable['qstring']) > 0 ) { if ( !$append ) { // Overwrite data $this->filterable['filters'] = array(); } foreach ( $this->filterable['qstring'] as $k => $v ) { if ( $v == '' ) { continue; } $thisColumn = isset($this->filterable['columns'][$k]) ? $this->filterable['columns'][$k] : false; if ( $thisColumn ) { // Query string part matches column (or alias) $this->filterable['filters'][$thisColumn]['val'] = $v; // Evaluate boolean parameter in query string $thisBoolData = isset($this->filterable['qstring']['bool'][$k]) ? $this->filterable['qstring']['bool'][$k] : false; $thisBoolAvailable = $thisBoolData && isset($this->filterable['bools'][$thisBoolData]) ? $this->filterable['bools'][$thisBoolData] : false; if ( $thisBoolData && $thisBoolAvailable ) { $this->filterable['filters'][$thisColumn]['boolean'] = $thisBoolAvailable; } else { $this->filterable['filters'][$thisColumn]['boolean'] = $this->filterable['defaultWhere']; } // Evaluate operator parameters in the query string if ( isset($this->filterable['qstring']['operator'][$k]) && in_array($this->filterable['qstring']['operator'][$k], $this->filterable['operators']) ) { $this->filterable['filters'][$thisColumn]['operator'] = $this->filterable['qstring']['operator'][$k]; } else { // Default operator $this->filterable['filters'][$thisColumn]['operator'] = $this->filterable['defaultOperator']; } } } } return $this; }
php
{ "resource": "" }
q319
FilterableTrait.scopeFilterColumns
train
public function scopeFilterColumns($query, $columns = array(), $validate = false) { if ( sizeof($columns) > 0 ) { // Set columns that can be filtered $this->setColumns($columns); } // Validate columns if ( $validate ) { $this->validateColumns(); } // Ensure that query string is parsed at least once if ( sizeof($this->filterable['filters']) == 0 ) { $this->setQuerystring(); } // Apply conditions to Eloquent query object if ( sizeof($this->filterable['filters']) > 0 ) { foreach ( $this->filterable['filters'] as $k => $v ) { $where = $v['boolean']; if ( is_array($v['val']) ) { if ( isset($v['val']['start']) && isset($v['val']['end']) ) { // BETWEEN a AND b $query->whereBetween($k, array($v['val']['start'], $v['val']['end'])); } else { // a = b OR c = d OR... $query->{$where}(function($q) use ($k, $v, $query) { foreach ( $v['val'] as $key => $val ) { $q->orWhere($k, $v['operator'], $val); } }); } } else { // a = b $query->{$where}($k, $v['operator'], $v['val']); } } } // Apply callbacks if ( sizeof($this->filterable['callbacks']) > 0 ) { foreach ( $this->filterable['callbacks'] as $v ) { $v($query); } } // Sorting if ( isset($this->filterable['qstring'][$this->filterable['orderby']]) && isset($this->filterable['columns'][$this->filterable['qstring'][$this->filterable['orderby']]]) ) { $order = isset($this->filterable['qstring'][$this->filterable['order']]) ? $this->filterable['qstring'][$this->filterable['order']] : 'asc'; $query->orderBy($this->filterable['columns'][$this->filterable['qstring'][$this->filterable['orderby']]], $order); } return $query; }
php
{ "resource": "" }
q320
Environment.getAllBlocks
train
public function getAllBlocks() { $this->load(); $blocks = []; foreach ($this->blockCache as $blockCache) { $blocks = array_merge($blocks, $blockCache); } return $blocks; }
php
{ "resource": "" }
q321
Signature.verify
train
public function verify(Signer $signer, $payload, $key) { return $signer->verify($this->hash, $payload, $key); }
php
{ "resource": "" }
q322
FileProvider.buildCreateForm
train
public function buildCreateForm(FormBuilderInterface $builder, array $options) { $builder ->add('files', DropzoneType::class, [ 'mapped' => false, 'path' => $this->router->generate('opifer_api_media_upload'), 'form_action' => $this->router->generate('opifer_media_media_updateall'), 'label' => '', ]) ; }
php
{ "resource": "" }
q323
MailingListRepository.findByIds
train
public function findByIds($ids) { if (!is_array($ids)) { $ids = explode(',', $ids); } return $this->createQueryBuilder('ml') ->andWhere('ml.id IN (:ids)') ->setParameter('ids', $ids) ->getQuery() ->getResult(); }
php
{ "resource": "" }
q324
BlockDiscriminatorListener.getDiscriminatorMap
train
public function getDiscriminatorMap() { $map = array(); foreach ($this->blockManager->getValues() as $alias => $value) { $map[$alias] = $value->getEntity(); } return $map; }
php
{ "resource": "" }
q325
ValidJsonValidator.validate
train
public function validate($value, Constraint $constraint) { if (is_array($value)) { $value = json_encode($value); } if (!json_decode($value, true)) { $this->context->addViolation( $constraint->message, array() ); } }
php
{ "resource": "" }
q326
ContentManager.createMissingValueSet
train
public function createMissingValueSet(Content $content) { if ($content->getContentType() !== null && $content->getValueSet() === null) { $valueSet = new ValueSet(); $this->em->persist($valueSet); $valueSet->setSchema($content->getContentType()->getSchema()); $content->setValueSet($valueSet); $content = $this->save($content); } return $content; }
php
{ "resource": "" }
q327
ContentTreePickerType.stripMetadata
train
protected function stripMetadata(array $array, $stripped = []) { $allowed = ['id', '__children']; foreach ($array as $item) { if (count($item['__children'])) { $item['__children'] = $this->stripMetadata($item['__children'], $stripped); } $stripped[] = array_intersect_key($item, array_flip($allowed)); } return $stripped; }
php
{ "resource": "" }
q328
Typo3DebugBar.var_dump
train
public function var_dump($item) { if ($this->hasCollector('vardump')) { /** @var VarDumpCollector $collector */ $collector = $this->getCollector('vardump'); $collector->addVarDump($item); } }
php
{ "resource": "" }
q329
ValuesSubscriber.preSetData
train
public function preSetData(FormEvent $event) { $data = $event->getData(); $form = $event->getForm(); $fields = $form->getConfig()->getOption('fields'); if (null === $data || '' === $data) { $data = []; } if (!is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) { throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)'); } // Sorting values so that they display in sorted order of the attributes uasort($data, function ($a, $b) { return $a->getAttribute()->getSort() > $b->getAttribute()->getSort(); }); /** * @var string $name * @var Value $value */ foreach ($data as $name => $value) { //Do not add fields when there not in fields value when giving. if (!empty($fields) && !in_array($name, $fields)) { continue; } // Do not add fields dynamically if they've already been set statically. // This allows us to override the formtypes from inside the form type // that's calling this subscriber. if ($form->has($name)) { continue; } $form->add($name, ValueType::class, [ 'label' => $value->getAttribute()->getDisplayName(), 'required' => $value->getAttribute()->getRequired(), 'attribute' => $value->getAttribute(), 'entity' => get_class($value), 'value' => $value, 'attr' => ['help_text' => $value->getAttribute()->getDescription()] ]); } }
php
{ "resource": "" }
q330
Api.verifyHash
train
public function verifyHash(array $params) { $result = false; try { $this->sdk->CheckOutFeedback($params); $result = true; } catch (Exception $e) { } return $result; }
php
{ "resource": "" }
q331
RedirectController.editAction
train
public function editAction(Request $request, $id) { $manager = $this->get('opifer.redirect.redirect_manager'); $redirect = $manager->getRepository()->find($id); $form = $this->createForm(RedirectType::class, $redirect); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $manager->save($redirect); $this->addFlash('success', $this->get('translator')->trans('opifer_redirect.flash.updated')); return $this->redirectToRoute('opifer_redirect_redirect_edit', ['id' => $redirect->getId()]); } return $this->render($this->container->getParameter('opifer_redirect.redirect_edit_view'), [ 'form' => $form->createView(), 'redirect' => $redirect ]); }
php
{ "resource": "" }
q332
RedirectController.deleteAction
train
public function deleteAction($id) { $manager = $this->get('opifer.redirect.redirect_manager'); $redirect = $manager->getRepository()->find($id); $manager->remove($redirect); $this->addFlash('success', $this->get('translator')->trans('opifer_redirect.flash.deleted')); return $this->redirectToRoute('opifer_redirect_redirect_index'); }
php
{ "resource": "" }
q333
ContentManager.getContentByReference
train
public function getContentByReference($reference) { if (is_numeric($reference)) { // If the reference is numeric, it must be the content ID from an existing // content item, which has to be updated. $nestedContent = $this->getRepository()->find($reference); } else { // If not, $reference is a template name for a to-be-created content item. $template = $this->em->getRepository($this->templateClass)->findOneByName($reference); $nestedContent = $this->eavManager->initializeEntity($template); $nestedContent->setNestedDefaults(); } return $nestedContent; }
php
{ "resource": "" }
q334
ContentManager.detachAndPersist
train
private function detachAndPersist($entity) { $this->em->detach($entity); $this->em->persist($entity); }
php
{ "resource": "" }
q335
RelativeSlugHandler.hasChangedParent
train
private function hasChangedParent(SluggableAdapter $ea, $object, $getter) { $relation = $object->$getter(); if (!$relation) { return false; } $changeSet = $ea->getObjectChangeSet($this->om->getUnitOfWork(), $relation); if (isset($changeSet[$this->usedOptions['relationField']])) { return true; } return $this->hasChangedParent($ea, $relation, $getter); }
php
{ "resource": "" }
q336
ContentController.typeAction
train
public function typeAction($type) { $contentType = $this->get('opifer.content.content_type_manager')->getRepository()->find($type); if (!$contentType) { throw $this->createNotFoundException(sprintf('Content Type with ID %d could not be found.', $type)); } $queryBuilder = $this->get('opifer.content.content_manager')->getRepository()->createQueryBuilder('c') ->select('c', 'vs', 'v', 'a') ->leftJoin('c.valueSet', 'vs') ->leftJoin('vs.values', 'v') ->leftJoin('v.attribute', 'a'); $source = new Entity($this->getParameter('opifer_content.content_class')); $source->initQueryBuilder($queryBuilder); $tableAlias = $source->getTableAlias(); $source->manipulateQuery(function ($query) use ($tableAlias, $contentType) { $query->andWhere($tableAlias . '.contentType = :contentType')->setParameter('contentType', $contentType); $query->andWhere($tableAlias . '.layout = :layout')->setParameter('layout', false); }); $designAction = new RowAction('button.design', 'opifer_content_contenteditor_design'); $designAction->setRouteParameters(['id', 'owner' => 'content']); $designAction->setRouteParametersMapping(['id' => 'ownerId']); $detailsAction = new RowAction('button.details', 'opifer_content_content_edit'); $detailsAction->setRouteParameters(['id']); //$deleteAction = new RowAction('button.delete', 'opifer_content_content_delete'); //$deleteAction->setRouteParameters(['id']); /* @var $grid \APY\DataGridBundle\Grid\Grid */ $grid = $this->get('grid'); $grid->setId('content') ->setSource($source) ->addRowAction($detailsAction) ->addRowAction($designAction); //->addRowAction($deleteAction) foreach ($contentType->getSchema()->getAttributes() as $attribute) { $name = $attribute->getName(); $column = new AttributeColumn([ 'id' => $name, 'field' => 'valueSet.values.value', 'title' => $attribute->getDisplayName(), 'visible' => false, 'attribute' => $name, 'source' => true ]); $column->manipulateRenderCell( function ($value, $row, $router) use ($name) { $value = $row->getEntity()->getAttributes()[$name]; return $value; } ); $grid->addColumn($column); } return $grid->getGridResponse($this->getParameter('opifer_content.content_type_view'), [ 'content_type' => $contentType, 'grid' => $grid, ]); }
php
{ "resource": "" }
q337
YahooWeatherAPI.getTemperature
train
public function getTemperature($withUnit = false) { if (!$this->lastResponse || !isset($this->lastResponse['item']['condition']['temp'])) { return ''; } $return = $this->lastResponse['item']['condition']['temp']; if ($withUnit) { $return .= ' '.$this->lastResponse['units']['temperature']; } return $return; }
php
{ "resource": "" }
q338
YahooWeatherAPI.getWind
train
public function getWind($withUnit = false) { if (!$this->lastResponse || !isset($this->lastResponse['wind']['speed'])) { return array(); } $response = array( 'chill' => $this->lastResponse['wind']['chill'], 'direction' => $this->lastResponse['wind']['direction'], 'speed' => $this->lastResponse['wind']['speed'], ); if ($withUnit) { $response['speed'] .= ' '.$this->lastResponse['units']['speed']; } return $response; }
php
{ "resource": "" }
q339
SubscribeBlockService.subscribeAction
train
public function subscribeAction(Block $block) { $response = $this->execute($block); $properties = $block->getProperties(); if ($this->subscribed && isset($properties['responseType']) && $properties['responseType'] == 'redirect') { $content = $this->contentManager->getRepository()->find($properties['responseContent']); $response = new RedirectResponse($this->router->generate('_content', ['slug' => $content->getSlug()])); } return $response; }
php
{ "resource": "" }
q340
SlugTransformer.transform
train
public function transform($slug) { if (null === $slug) { return; } // If the slug ends with a slash, return just a slash // so the item is used as the index page of that directory if (substr($slug, -1) == '/') { return '/'; } $array = explode('/', $slug); $slug = end($array); return $slug; }
php
{ "resource": "" }
q341
ContentTypeManager.create
train
public function create() { $class = $this->getClass(); $contentType = new $class(); $schema = $this->schemaManager->create(); $schema->setObjectClass($this->contentManager->getClass()); $contentType->setSchema($schema); return $contentType; }
php
{ "resource": "" }
q342
Ecdsa.createSignatureHash
train
private function createSignatureHash(Signature $signature) { $length = $this->getSignatureLength(); return pack( 'H*', sprintf( '%s%s', str_pad($this->adapter->decHex($signature->getR()), $length, '0', STR_PAD_LEFT), str_pad($this->adapter->decHex($signature->getS()), $length, '0', STR_PAD_LEFT) ) ); }
php
{ "resource": "" }
q343
Ecdsa.extractSignature
train
private function extractSignature($value) { $length = $this->getSignatureLength(); $value = unpack('H*', $value)[1]; return new Signature( $this->adapter->hexDec(substr($value, 0, $length)), $this->adapter->hexDec(substr($value, $length)) ); }
php
{ "resource": "" }
q344
KeyParser.getKeyContent
train
private function getKeyContent(Key $key, $header) { $match = null; preg_match( '/^[\-]{5}BEGIN ' . $header . '[\-]{5}(.*)[\-]{5}END ' . $header . '[\-]{5}$/', str_replace([PHP_EOL, "\n", "\r"], '', $key->getContent()), $match ); if (isset($match[1])) { return $match[1]; } throw new \InvalidArgumentException('This is not a valid ECDSA key.'); }
php
{ "resource": "" }
q345
MediaExtension.sourceUrl
train
public function sourceUrl($media) { return new \Twig_Markup( $this->pool->getProvider($media->getProvider())->getUrl($media), 'utf8' ); }
php
{ "resource": "" }
q346
SearchResultsBlockService.getSearchResults
train
public function getSearchResults() { $term = $this->getRequest()->get('search', null); // Avoid querying ALL content when no search value is provided if (!$term) { return []; } $host = $this->getRequest()->getHost(); $locale = $this->getRequest()->attributes->get('content')->getLocale(); return $this->contentManager->getRepository()->search($term, $host, $locale); }
php
{ "resource": "" }
q347
InstallController.index
train
public function index() { Session::forget('install-module'); $result = []; foreach ($this->extensions as $ext) { if (extension_loaded($ext)) { $result [$ext] = 'true'; } else { $result [$ext] = false; } } return view('avored-install::install.extension')->with('result', $result); }
php
{ "resource": "" }
q348
OpiferCmsBundle.build
train
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new ConfigurationCompilerPass()); $container->addCompilerPass(new VendorCompilerPass()); }
php
{ "resource": "" }
q349
UserFormType.flattenRoles
train
public function flattenRoles($data) { $result = array(); foreach ($data as $key => $value) { if (substr($key, 0, 4) === 'ROLE') { $result[$key] = $key; } if (is_array($value)) { $tmpresult = $this->flattenRoles($value); if (count($tmpresult) > 0) { $result = array_merge($result, $tmpresult); } } else { $result[$value] = $value; } } return array_unique($result); }
php
{ "resource": "" }
q350
Configuration.addBlocksSection
train
private function addBlocksSection(ArrayNodeDefinition $node) { $node ->children() ->arrayNode('blocks') ->addDefaultsIfNotSet() ->children() ->arrayNode('subscribe') ->addDefaultsIfNotSet() ->children() ->scalarNode('view')->defaultValue('OpiferMailingListBundle:Block:subscribe.html.twig')->end() ->arrayNode('templates') ->prototype('scalar')->end() ->normalizeKeys(false) ->useAttributeAsKey('name') ->defaultValue([]) ->end() ->end() ->end() ->end() ->end() ->end() ; }
php
{ "resource": "" }
q351
MailingListController.createAction
train
public function createAction(Request $request) { $mailingList = new MailingList(); $form = $this->createForm(MailingListType::class, $mailingList, [ 'action' => $this->generateUrl('opifer_mailing_list_mailing_list_create'), ]); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($mailingList); $em->flush(); return $this->redirectToRoute('opifer_mailing_list_mailing_list_index'); } return $this->render('OpiferMailingListBundle:MailingList:create.html.twig', [ 'form' => $form->createView(), ]); }
php
{ "resource": "" }
q352
MailingListController.editAction
train
public function editAction(Request $request, $id) { $mailingList = $this->getDoctrine()->getRepository('OpiferMailingListBundle:MailingList')->find($id); $form = $this->createForm(MailingListType::class, $mailingList); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->flush(); return $this->redirectToRoute('opifer_mailing_list_mailing_list_index'); } return $this->render('OpiferMailingListBundle:MailingList:edit.html.twig', [ 'form' => $form->createView(), 'mailing_list' => $mailingList, ]); }
php
{ "resource": "" }
q353
MailingListController.deleteAction
train
public function deleteAction($id) { $mailingList = $this->getDoctrine()->getRepository('OpiferMailingListBundle:MailingList')->find($id); if (!empty($mailingList)) { $em = $this->getDoctrine()->getManager(); $em->remove($mailingList); $em->flush(); } return $this->redirectToRoute('opifer_mailing_list_mailing_list_index'); }
php
{ "resource": "" }
q354
ContentController.idsAction
train
public function idsAction($ids) { $items = $this->get('opifer.content.content_manager') ->getRepository() ->findOrderedByIds($ids); $stringHelper = $this->container->get('opifer.content.string_helper'); $contents = $this->get('jms_serializer')->serialize($items, 'json', SerializationContext::create()->setGroups(['list'])->enableMaxDepthChecks()); $contents = $stringHelper->replaceLinks($contents); $data = [ 'results' => json_decode($contents, true), 'total_results' => count($items), ]; return new JsonResponse($data); }
php
{ "resource": "" }
q355
ContentController.viewAction
train
public function viewAction(Request $request, $id, $structure = 'tree') { $response = new JsonResponse(); /** @var ContentRepository $contentRepository */ $contentRepository = $this->get('opifer.content.content_manager')->getRepository(); $content = $contentRepository->findOneByIdOrSlug($id, true); if ($content->getSlug() === '404') { // If the original content was not found and the 404 page was returned, set the correct status code $response->setStatusCode(404); } $version = $request->query->get('_version'); $debug = $this->getParameter('kernel.debug'); $response->setLastModified($content->getLastUpdateDate()); $response->setPublic(); if (null === $version && false == $debug && $response->isNotModified($request)) { // return the 304 Response immediately return $response; } /** @var Environment $environment */ $environment = $this->get('opifer.content.block_environment'); $environment->setObject($content); if (null !== $version && $this->isGranted('ROLE_ADMIN')) { $environment->setDraft(true); } $environment->load(); $context = SerializationContext::create() ->addExclusionStrategy(new BlockExclusionStrategy($content)) // ->setGroups(['Default', 'detail']) ; if ($structure == 'tree') { $blocks = $environment->getRootBlocks(); $context->setGroups(['Default', 'tree', 'detail']); } else { $blocks = $environment->getBlocks(); $context->setGroups(['Default', 'detail']) ->enableMaxDepthChecks(); } $contentItem = [ 'id' => $content->getId(), 'created_at' => $content->getCreatedAt(), 'updated_at' => $content->getUpdatedAt(), 'published_at' => $content->getPublishAt(), 'title' => $content->getTitle(), 'shortTitle' => $content->getShortTitle(), 'description' => $content->getDescription(), 'slug' => $content->getSlug(), 'alias' => $content->getAlias(), 'blocks' => $blocks, 'attributes' => $content->getPivotedAttributes(), 'medias' => $content->getMedias(), ]; $stringHelper = $this->container->get('opifer.content.string_helper'); $json = $this->get('jms_serializer')->serialize($contentItem, 'json', $context); $json = $stringHelper->replaceLinks($json); $response->setData(json_decode($json, true)); return $response; }
php
{ "resource": "" }
q356
ContentController.deleteAction
train
public function deleteAction($id) { /** @var ContentManager $manager */ $manager = $this->get('opifer.content.content_manager'); $content = $manager->getRepository()->find($id); //generate new slug so deleted slug can be used again $hashedSlug = $content->getSlug().'-'.sha1(date('Y-m-d H:i:s')); $content->setSlug($hashedSlug); $manager->save($content); $manager->remove($content); return new JsonResponse(['success' => true]); }
php
{ "resource": "" }
q357
ValidationData.setCurrentTime
train
public function setCurrentTime($currentTime) { $this->items['iat'] = (int) $currentTime; $this->items['nbf'] = (int) $currentTime; $this->items['exp'] = (int) $currentTime; }
php
{ "resource": "" }
q358
ValidationData.get
train
public function get($name) { return isset($this->items[$name]) ? $this->items[$name] : null; }
php
{ "resource": "" }
q359
LocaleController.createAction
train
public function createAction(Request $request) { $this->denyAccessUnlessGranted('ROLE_ADMIN'); $locale = new Locale(); $form = $this->createForm(new LocaleType(), $locale); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($locale); $em->flush(); $this->addFlash('success', 'Locale has been created successfully'); return $this->redirectToRoute('opifer_cms_locale_edit', ['id' => $locale->getId()]); } return $this->render('OpiferCmsBundle:Backend/Locale:create.html.twig', [ 'locale' => $locale, 'form' => $form->createView() ]); }
php
{ "resource": "" }
q360
LocaleController.editAction
train
public function editAction(Request $request, $id = null) { $this->denyAccessUnlessGranted('ROLE_ADMIN'); $em = $this->getDoctrine()->getManager(); if (is_numeric($id)) { $locale = $em->getRepository(Locale::class)->find($id); } else { $locale = $em->getRepository(Locale::class)->findOneByLocale($id); } $form = $this->createForm(new LocaleType(), $locale); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em->persist($locale); $em->flush(); $this->addFlash('success', 'Locale has been updated successfully'); return $this->redirectToRoute('opifer_cms_locale_edit', ['id' => $locale->getId()]); } return $this->render('OpiferCmsBundle:Backend/Locale:edit.html.twig', [ 'locale' => $locale, 'form' => $form->createView() ]); }
php
{ "resource": "" }
q361
ContentListValue.getOrdered
train
public function getOrdered() { if (!$this->sort) { return $this->content; } $unordered = []; foreach ($this->content as $content) { $unordered[$content->getId()] = $content; } $ordered = []; $sort = json_decode($this->sort, true); $order = $sort['order']; foreach ($order as $id) { if (isset($unordered[$id])) { $ordered[] = $unordered[$id]; } } return $ordered; }
php
{ "resource": "" }
q362
OpiferContentExtension.prepend
train
public function prepend(ContainerBuilder $container) { $configs = $container->getExtensionConfig($this->getAlias()); $config = $this->processConfiguration(new Configuration(), $configs); $container->setAlias('opifer.content.content_manager', $config['content_manager']); $container->setDefinition('opifer.content.cache_provider', new Definition($config['cache_provider'])); $parameters = $this->getParameters($config); foreach ($parameters as $key => $value) { $container->setParameter($key, $value); } $this->prependExtensionConfig($container, $config); }
php
{ "resource": "" }
q363
CollectionToStringTransformer.transform
train
public function transform($value) { if (null === $value || !($value instanceof Collection)) { return ''; } $string = ''; foreach ($value as $item) { $string .= $item->getId(); if ($value->last() != $item) { $string .= ','; } } return $string; }
php
{ "resource": "" }
q364
BlockExclusionStrategy.shouldSkipClass
train
public function shouldSkipClass(ClassMetadata $metadata, Context $context) { $obj = null; // Get the last item of the visiting set foreach ($context->getVisitingSet() as $item) { $obj = $item; } if ($obj && $obj instanceof Block && $obj->getParent() && $obj->getParent()->getTemplate() && $obj->getContent() && $obj->getContentId() != $this->content->getId()) { return true; } return false; }
php
{ "resource": "" }
q365
PrototypeCollection.add
train
public function add(Prototype $prototype) { if ($this->has($prototype->getKey())) { throw new \Exception(sprintf('A prototype with the key %s already exists', $prototype->getKey())); } $this->collection[] = $prototype; }
php
{ "resource": "" }
q366
PrototypeCollection.has
train
public function has($key) { foreach ($this->collection as $prototype) { if ($key == $prototype->getKey()) { return true; } } return false; }
php
{ "resource": "" }
q367
Schema.getAttribute
train
public function getAttribute($name) { foreach ($this->attributes as $attribute) { if ($attribute->getName() == $name) { return $attribute; } } return false; }
php
{ "resource": "" }
q368
ContentRepository.findLastUpdated
train
public function findLastUpdated($limit = 5) { $query = $this->createQueryBuilder('c') ->orderBy('c.updatedAt', 'DESC') ->where('c.layout = :layout') ->setParameter(':layout', false) ->setMaxResults($limit) ->getQuery(); return $query->getResult(); }
php
{ "resource": "" }
q369
ContentRepository.findLastCreated
train
public function findLastCreated($limit = 5) { $query = $this->createQueryBuilder('c') ->orderBy('c.createdAt', 'DESC') ->setMaxResults($limit) ->getQuery(); return $query->getResult(); }
php
{ "resource": "" }
q370
ContentRepository.findIndexable
train
public function findIndexable() { return $this->createQueryBuilder('c') ->where('c.indexable = :indexable') ->Andwhere('c.active = :active') ->Andwhere('c.layout = :layout') ->setParameters([ 'active' => true, 'layout' => false, 'indexable' => true ]) ->orderBy('c.slug', 'ASC') ->getQuery() ->getResult(); }
php
{ "resource": "" }
q371
Info.summary
train
protected function summary($signal, $time_start, $time_end, $query_exec_time, $exec_queries) { $this->newLine(); $this->text(sprintf( '<info>%s</info> query process (%s s)', $signal, number_format($query_exec_time, 4) )); $this->newLine(); $this->text(sprintf('<comment>%s</comment>', str_repeat('-', 30))); $this->newLine(); $this->text(sprintf( '<info>++</info> finished in %s s', number_format(($time_end - $time_start), 4) )); $this->text(sprintf('<info>++</info> %s sql queries', $exec_queries)); }
php
{ "resource": "" }
q372
CollectionToObjectTransformer.reverseTransform
train
public function reverseTransform($value) { if ($value instanceof Collection) { return $value; } $collection = new ArrayCollection(); if(null !== $value) { $collection->add($value); } return $collection; }
php
{ "resource": "" }
q373
Serve.configure
train
protected function configure() { parent::configure(); $this ->addOption( 'host', NULL, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost' ) ->addOption( 'docroot', NULL, InputOption::VALUE_OPTIONAL, 'Specify an explicit document root.', FALSE ) ->addOption( 'port', NULL, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000 ); }
php
{ "resource": "" }
q374
SitemapController.sitemapAction
train
public function sitemapAction() { /* @var ContentInterface[] $content */ $contents = $this->get('opifer.content.content_manager')->getRepository()->findIndexable(); $event = new SitemapEvent(); foreach ($contents as $content) { $event->addUrl($this->generateUrl('_content', ['slug' => $content->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL), $content->getUpdatedAt()); } $dispatcher = $this->get('event_dispatcher'); $dispatcher->dispatch(Events::POPULATE_SITEMAP, $event); return $this->render('OpiferCmsBundle:Sitemap:sitemap.xml.twig', [ 'urls' => $event->getUrls(), ]); }
php
{ "resource": "" }
q375
PointerBlock.getChildren
train
public function getChildren() { $children = new ArrayCollection(); if ($this->reference) { $children->add($this->reference); } return $children; }
php
{ "resource": "" }
q376
YoutubeProvider.getUrl
train
public function getUrl(MediaInterface $media) { $metadata = $media->getMetaData(); return sprintf('%s?v=%s', self::WATCH_URL, $metadata['id']); }
php
{ "resource": "" }
q377
Command.configure
train
protected function configure() { $this ->setName($this->name) ->setDescription($this->description) ->setAliases($this->aliases) ->addOption( 'env', null, InputOption::VALUE_REQUIRED, 'Set the environment variable file', sprintf('%s/%s', getcwd(), '.craftsman') ); }
php
{ "resource": "" }
q378
Command.initialize
train
protected function initialize(InputInterface $input, OutputInterface $output) { try { $this->input = $input; $this->output = $output; $this->style = new SymfonyStyle($input, $output); $file = new \SplFileInfo($this->getOption('env')); // Create an environment instance $this->env = new Dotenv( $file->getPathInfo()->getRealPath(), $file->getFilename() ); $this->env->load(); $this->env->required(['BASEPATH','APPPATH'])->notEmpty(); } catch (Exception $e) { throw new \RuntimeException($e->getMessage()); } }
php
{ "resource": "" }
q379
ContentRepository.createValuedQueryBuilder
train
public function createValuedQueryBuilder($entityAlias) { return $this->createQueryBuilder($entityAlias) ->select($entityAlias, 'vs', 'v', 'a', 'p', 's') ->leftJoin($entityAlias.'.valueSet', 'vs') ->leftJoin('vs.schema', 's') ->leftJoin('vs.values', 'v') ->leftJoin('s.attributes', 'a') ->leftJoin('v.options', 'p'); }
php
{ "resource": "" }
q380
ContentRepository.getContentFromRequest
train
public function getContentFromRequest(Request $request) { $qb = $this->createValuedQueryBuilder('c'); if ($request->get('q')) { $qb->leftJoin('c.template', 't'); $qb->andWhere('c.title LIKE :query OR c.alias LIKE :query OR c.slug LIKE :query OR t.displayName LIKE :query'); $qb->setParameter('query', '%'.$request->get('q').'%'); } if ($ids = $request->get('ids')) { $ids = explode(',', $ids); $qb->andWhere('c.id IN (:ids)')->setParameter('ids', $ids); } $qb->andWhere('c.deletedAt IS NULL AND c.layout = :layout'); // @TODO fix SoftDeleteAble & layout filter $qb->setParameter('layout', false); $qb->orderBy('c.slug'); return $qb->getQuery() ->getResult(); }
php
{ "resource": "" }
q381
ContentRepository.findOneById
train
public function findOneById($id) { $query = $this->createValuedQueryBuilder('c') ->where('c.id = :id') ->setParameter('id', $id) ->getQuery(); return $query->useResultCache(true, self::CACHE_TTL)->getSingleResult(); }
php
{ "resource": "" }
q382
ContentRepository.findOneBySlug
train
public function findOneBySlug($slug) { $query = $this->createQueryBuilder('c') ->where('c.slug = :slug') ->setParameter('slug', $slug) ->andWhere('c.publishAt < :now OR c.publishAt IS NULL') ->andWhere('c.active = :active') ->andWhere('c.layout = :layout') ->setParameter('now', new \DateTime()) ->setParameter('active', true) ->setParameter('layout', false) ->setMaxResults(1) ->getQuery(); return $query->useResultCache(true, self::CACHE_TTL)->getOneOrNullResult(); }
php
{ "resource": "" }
q383
ContentRepository.findOneByIdOrSlug
train
public function findOneByIdOrSlug($idOrSlug, $allow404 = false) { if (is_numeric($idOrSlug)) { $content = $this->find($idOrSlug); } else { $content = $this->findOneBySlug($idOrSlug); } // If no content was found for the passed id, return the 404 page if (!$content && $allow404 == true) { $content = $this->findOneBySlug('404'); } return $content; }
php
{ "resource": "" }
q384
ContentRepository.findActiveBySlug
train
public function findActiveBySlug($slug, $host) { $query = $this->createValuedQueryBuilder('c') ->leftJoin('c.site', 'os') ->leftJoin('os.domains', 'd') ->where('c.slug = :slug') ->andWhere('c.active = :active') ->andWhere('c.layout = :layout') ->andWhere('c.publishAt < :now OR c.publishAt IS NULL') ->andWhere('d.domain = :host OR c.site IS NULL') ->setParameters([ 'slug' => $slug, 'active' => true, 'layout' => false, 'now' => new \DateTime(), 'host' => $host ]) ->getQuery(); return $query->getSingleResult(); }
php
{ "resource": "" }
q385
ContentRepository.findActiveByAlias
train
public function findActiveByAlias($alias, $host) { $query = $this->createValuedQueryBuilder('c') ->leftJoin('c.site', 'os') ->leftJoin('os.domains', 'd') ->where('c.alias = :alias') ->andWhere('c.active = :active') ->andWhere('c.layout = :layout') ->andWhere('(c.publishAt < :now OR c.publishAt IS NULL)') ->andWhere('d.domain = :host OR c.site IS NULL') ->setParameters([ 'alias' => $alias, 'active' => true, 'layout' => false, 'now' => new \DateTime(), 'host' => $host ]) ->getQuery(); return $query->getSingleResult(); }
php
{ "resource": "" }
q386
ContentRepository.findByIds
train
public function findByIds($ids) { if (!is_array($ids)) { $ids = explode(',', $ids); } if (!$ids) { return []; } return $this->createValuedQueryBuilder('c') ->andWhere('c.id IN (:ids)')->setParameter('ids', $ids) ->andWhere('c.deletedAt IS NULL') ->andWhere('c.active = :active') ->andWhere('c.layout = :layout') ->andWhere('c.publishAt < :now OR c.publishAt IS NULL')->setParameter('now', new \DateTime()) ->setParameter('active', true) ->setParameter('layout', false) ->getQuery() ->useResultCache(true, self::CACHE_TTL) ->getResult(); }
php
{ "resource": "" }
q387
ContentRepository.sortByArray
train
private function sortByArray($items, array $order) { $unordered = []; foreach ($items as $content) { $unordered[$content->getId()] = $content; } $ordered = []; foreach ($order as $id) { if (isset($unordered[$id])) { $ordered[] = $unordered[$id]; } } return $ordered; }
php
{ "resource": "" }
q388
ContentRepository.findByLevels
train
public function findByLevels($levels = 1, $ids = array()) { $query = $this->createQueryBuilder('c'); if ($levels > 0) { $selects = ['c']; for ($i = 1; $i <= $levels; ++$i) { $selects[] = 'c'.$i; } $query->select($selects); for ($i = 1; $i <= $levels; ++$i) { $previous = ($i - 1 == 0) ? '' : ($i - 1); $query->leftJoin('c'.$previous.'.children', 'c'.$i, 'WITH', 'c'.$i.'.active = :active AND c'.$i.'.showInNavigation = :show'); } } if ($ids) { $query->andWhere('c.id IN (:ids)')->setParameter('ids', $ids); } else { $query->andWhere('c.parent IS NULL'); } $query->andWhere('c.active = :active')->setParameter('active', true); $query->andWhere('c.layout = :layout')->setParameter('layout', false); $query->andWhere('c.showInNavigation = :show')->setParameter('show', true); return $query->getQuery()->getResult(); }
php
{ "resource": "" }
q389
ContentRepository.sortSearchResults
train
public function sortSearchResults($results, $term) { $sortedResults = []; if (!empty($results)) { foreach ($results as $result) { if (stripos($result->getTitle(), $term) !== false) { array_unshift($sortedResults, $result); } else { $sortedResults[] = $result; } } } return $sortedResults; }
php
{ "resource": "" }
q390
Cron.setState
train
public function setState($newState) { if ($newState === $this->state) { return; } switch ($newState) { case self::STATE_RUNNING: $this->startedAt = new \DateTime(); break; case self::STATE_FINISHED: case self::STATE_FAILED: case self::STATE_TERMINATED: $this->endedAt = new \DateTime(); break; default: break; } $this->state = $newState; return $this; }
php
{ "resource": "" }
q391
Cron.getNextRunDate
train
public function getNextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false) { return $this->getCronExpression()->getNextRunDate($currentTime, $nth, $allowCurrentDate); }
php
{ "resource": "" }
q392
Cron.getPreviousRunDate
train
public function getPreviousRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false) { return $this->getCronExpression()->getPreviousRunDate($currentTime, $nth, $allowCurrentDate); }
php
{ "resource": "" }
q393
Cron.getMultipleRunDates
train
public function getMultipleRunDates($total, $currentTime = 'now', $invert = false, $allowCurrentDate = false) { return $this->getCronExpression()->getMultipleRunDates($total, $currentTime, $invert, $allowCurrentDate); }
php
{ "resource": "" }
q394
SelectValue.getValue
train
public function getValue() { $options = parent::getValue(); if (count($options)) { if (empty( $options[0] )) { $collection = $options->getValues(); return $collection[0]->getName(); } return $options[0]->getName(); } return ''; }
php
{ "resource": "" }
q395
UserController.editAction
train
public function editAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $user = $em->getRepository('OpiferCmsBundle:User')->find($id); $form = $this->createForm(UserFormType::class, $user); $form->handleRequest($request); if ($form->isValid()) { if ($user->isTwoFactorEnabled() == false) { $user->setGoogleAuthenticatorSecret(null); } $this->get('fos_user.user_manager')->updateUser($user, true); $this->addFlash('success', $this->get('translator')->trans('user.edit.success', [ '%username%' => ucfirst($user->getUsername()), ])); return $this->redirectToRoute('opifer_cms_user_index'); } return $this->render('OpiferCmsBundle:Backend/User:edit.html.twig', [ 'form' => $form->createView(), 'user' => $user, ]); }
php
{ "resource": "" }
q396
UserController.profileAction
train
public function profileAction(Request $request) { $user = $this->getUser(); $form = $this->createForm(ProfileType::class, $user); $form->handleRequest($request); if ($form->isValid()) { if ($user->isTwoFactorEnabled() == false) { $user->setGoogleAuthenticatorSecret(null); } $this->get('fos_user.user_manager')->updateUser($user, true); if ($user->isTwoFactorEnabled() == true && empty($user->getGoogleAuthenticatorSecret())) { return $this->redirectToRoute('opifer_cms_user_activate_2fa'); } $this->addFlash('success', 'Your profile was updated successfully!'); return $this->redirectToRoute('opifer_cms_user_profile'); } return $this->render('OpiferCmsBundle:Backend/User:profile.html.twig', [ 'form' => $form->createView(), 'user' => $user, ]); }
php
{ "resource": "" }
q397
UserController.activateGoogleAuthAction
train
public function activateGoogleAuthAction(Request $request) { $user = $this->getUser(); $secret = $this->container->get("scheb_two_factor.security.google_authenticator")->generateSecret(); $user->setGoogleAuthenticatorSecret($secret); //Generate QR url $qrUrl = $this->container->get("scheb_two_factor.security.google_authenticator")->getUrl($user); $form = $this->createForm(GoogleAuthType::class, $user); $form->handleRequest($request); if ($form->isValid()) { $this->get('fos_user.user_manager')->updateUser($user, true); $this->addFlash('success', 'Your profile was updated successfully!'); return $this->redirectToRoute('opifer_cms_user_profile'); } return $this->render('OpiferCmsBundle:Backend/User:google_auth.html.twig', [ 'form' => $form->createView(), 'secret' => $secret, 'user' => $user, 'qrUrl' => $qrUrl, ]); }
php
{ "resource": "" }
q398
BlockManager.getService
train
public function getService($block) { $blockType = ($block instanceof BlockInterface) ? $block->getBlockType() : $block; if (!isset($this->services[$blockType])) { throw new \Exception(sprintf("No BlockService available by the alias %s, available: %s", $blockType, implode(', ', array_keys($this->services)))); } return $this->services[$blockType]; }
php
{ "resource": "" }
q399
BlockManager.find
train
public function find($id, $draft = false) { if ($draft) { $this->setDraftVersionFilter(! $draft); } $block = $this->getRepository()->find($id); if ($draft) { if (null !== $revision = $this->revisionManager->getDraftRevision($block)) { $this->revisionManager->revert($block, $revision); } } return $block; }
php
{ "resource": "" }