_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q253500
CompilerContext.compile
validation
public function compile(callable $validator = NULL) { if(!($project = $this->getProject())) { $project = CC::get($this->getConfiguration(), CC::COMPILER_PROJECT); if(!$project) throw new CompilerException("Compilation without project settings is not possible"); } $this->project = $project; try { set_error_handler(function($code, $msg, $file, $line) { switch(AbstractErrorHandlerService::detectErrorLevel($code)) { case AbstractErrorHandlerService::NOTICE_ERROR_LEVEL: return $this->getLogger()->logNotice($msg, [$file, $line]); case AbstractErrorHandlerService::DEPRECATED_ERROR_LEVEL: case AbstractErrorHandlerService::WARNING_ERROR_LEVEL: return $this->getLogger()->logWarning($msg, [$file, $line]); default: return $this->getLogger()->logError($msg, [$file, $line]); } }); /** @var CompilerInterface $compiler */ foreach($this->getOrganizedCompilers() as $compiler) { if(!$validator || $validator($compiler)) $compiler->compile($this); } } catch (Throwable $throwable) { $this->getLogger()->logException($throwable); } finally { restore_error_handler(); } }
php
{ "resource": "" }
q253501
CustomFieldsHelper._cacheCustomFields
validation
private function _cacheCustomFields($class) { $customFieldsGroups = $this->em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup') ->findBy(array('entity' => (is_string($class)) ? $class : get_class($class))); if (!$customFieldsGroups) { throw CustomFieldsHelperException::customFieldsGroupNotFound((is_string($class)) ? $class : get_class($class)); } foreach ($customFieldsGroup as $cfGroup) { $this->_cacheCustomFields($cfGroup); } }
php
{ "resource": "" }
q253502
CustomFieldsHelper._cacheCustomFieldsGroup
validation
private function _cacheCustomFieldsGroup(CustomFieldsGroup $group) { foreach ($group->getCustomFields() as $field) { $this->cache[$group->getEntity()][$field->getSlug()] = $field; } }
php
{ "resource": "" }
q253503
CustomFieldsHelper.getCustomField
validation
public function getCustomField($class, $slug = null) { if (!$slug) { throw CustomFieldsHelperException::slugIsMissing(); } $resolveClass = (is_string($class)) ? $class : get_class($class); if (!$this->cache[$resolveClass][$slug]) { $this->_cacheCustomFields($resolveClass); } return $this->cache[$resolveClass][$slug]; }
php
{ "resource": "" }
q253504
CustomFieldsHelper.renderCustomField
validation
public function renderCustomField(array $fields, $classOrCustomField, $documentType='html', $slug = null, $showIfEmpty = true) { $customField = ($classOrCustomField instanceof CustomField) ? $classOrCustomField : $this->getCustomField($classOrCustomField, $slug); $slug = $customField->getSlug(); $rawValue = (isset($fields[$slug])) ? $fields[$slug] : null; $customFieldType = $this->provider->getCustomFieldByType($customField->getType()); return $customFieldType->render($rawValue, $customField, $documentType); }
php
{ "resource": "" }
q253505
SourceDirectoryAwareTrait.addSource
validation
public function addSource($sourcePath, $useStrict=true) { if (is_link($sourcePath)) { return $this->addSource(realpath($sourcePath), $useStrict); } if (is_dir($sourcePath)) { $this->sourceDirs[] = $sourcePath; } elseif (true === $useStrict) { throw new \Exception(sprintf('Path {%s} is not a readable directory', $sourcePath)); } return $this; }
php
{ "resource": "" }
q253506
SourceDirectoryAwareTrait.findInSourceDirs
validation
public function findInSourceDirs(Finder $finder) { foreach ($this->sourceDirs as $dir) { $finder->in($dir); } return $finder; }
php
{ "resource": "" }
q253507
PageRendererBackend.renderCmsBlocks
validation
public function renderCmsBlocks(array $blocks, $username, array $options = array()) { $tmp = array(); foreach ($blocks as $block) { $tmp[] = $this->renderCmsBlock($block, $username, $options); } return implode("\n", $tmp); }
php
{ "resource": "" }
q253508
PageRendererBackend.renderCmsBlock
validation
public function renderCmsBlock(BaseBlock $block, $username, array $options = array()) { $blockTemplate = $this->fetchTemplateBlock($block); if ($blockTemplate == "") { return ""; } $permalinks = $this->pagesParser ->contributor($username) ->parse() ->permalinksByLanguage(); $options = array_merge( array( 'block' => $block, 'permalinks' => $permalinks, ), $options ); return $this->templating->render($blockTemplate, $options); }
php
{ "resource": "" }
q253509
PageRendererBackend.renderSlots
validation
protected function renderSlots(Page $page, array $slots, array $options = array()) { $renderedSlots = array(); $slots = $this->dispatchSlotsEvent(RenderEvents::SLOTS_RENDERING, $page, $slots); foreach ($slots as $slotName => $slot) { if (is_string($slot)) { $renderedSlots[$slotName] = $slot; continue; } if (!$slot instanceof Slot) { continue; } $blocks = $slot->getEntitiesInUse(); $renderedSlots[$slotName] = $this->templating->render( 'RedKiteCms/Resources/views/Slot/slot.html.twig', array( 'options' => $options, 'slotname' => $slotName, 'data' => rawurlencode("[" . implode(",", $blocks)) . "]", 'next' => $slot->getNext(), ) ); } return $slots = $this->dispatchSlotsEvent(RenderEvents::SLOTS_RENDERED, $page, $renderedSlots); }
php
{ "resource": "" }
q253510
PageRendererBackend.generateEventNames
validation
protected function generateEventNames($baseEventName, Page $page) { $pageName = $page->getPageName(); $language = $page->getCurrentLanguage(); return array( $baseEventName, $baseEventName . '.' . $language, $baseEventName . '.' . $pageName, $baseEventName . '.' . $language . '.' . $pageName, ); }
php
{ "resource": "" }
q253511
PageRendererBackend.dispatchSlotsEvent
validation
protected function dispatchSlotsEvent($baseEventName, Page $page, array $slots) { $eventNames = $this->generateEventNames($baseEventName, $page); $event = new SlotsRenderingEvent($slots); foreach($eventNames as $eventName) { $event = Dispatcher::dispatch($eventName, $event); } return $event->getSlots(); }
php
{ "resource": "" }
q253512
Router.getRoute
validation
public function getRoute(): string { $uri = $_SERVER['REQUEST_URI']; // Extraigo la URI base si esta es diferente a / if ($this->uriBase != '/') { $uri = str_replace($this->uriBase, '/', $uri); } // Busco el caracter ? por si se pasaron parametros por GET $pos = strpos($uri, '?'); if ($pos !== false) { $uri = substr($uri, 0, $pos); } // Agrega un slash a uri para evitar error en la busqueda de ultimo slash //$uri = $this->addSlash($uri); // Retorno la ruta correcta return $uri; }
php
{ "resource": "" }
q253513
Calc.exec
validation
public function exec($calcId) { $result = []; /* collect additional data */ $dwnlCompress = $this->daoBonDwnl->getByCalcId($calcId); /* create maps to access data */ $mapById = $this->hlpDwnlTree->mapById($dwnlCompress, EBonDwnl::A_CUST_REF); $mapDepth = $this->hlpDwnlTree->mapByTreeDepthDesc($dwnlCompress, EBonDwnl::A_CUST_REF, EBonDwnl::A_DEPTH); $mapTeams = $this->hlpDwnlTree->mapByTeams($dwnlCompress, EBonDwnl::A_CUST_REF, EBonDwnl::A_PARENT_REF); $signupDebitCustomers = $this->hlpSignUpDebitCust->exec(); /** * Scan downline by level from bottom to top */ foreach ($mapDepth as $depth => $levelCustomers) { $this->logger->debug("Process level #$depth of the downline tree."); /* ... then scan customers on each level */ foreach ($levelCustomers as $custId) { /** @var EBonDwnl $entity */ $entity = $mapById[$custId]; $ov = $entity->getPv(); // initial OV equals to customer's own PV $isSignUpDebit = in_array($custId, $signupDebitCustomers); if ($isSignUpDebit) { /* add written-off PV if customer was qualified to Sign Up Debit bonus */ $ov += Cfg::SIGNUP_DEBIT_PV; } if (isset($mapTeams[$custId])) { /* add OV from front team members */ $team = $mapTeams[$custId]; foreach ($team as $memberId) { /** @var EBonDwnl $member */ $member = $result[$memberId]; $memberOv = $member->getOv(); $ov += $memberOv; } } $entity->setOv($ov); $result[$custId] = $entity; } } unset($mapPv); unset($mapTeams); unset($mapDepth); return $result; }
php
{ "resource": "" }
q253514
Date.cast
validation
public static function cast($date) { return $date instanceof self ? $date : new self($date->format(self::ISO8601), $date->getTimezone()); }
php
{ "resource": "" }
q253515
Date.createFromFormat
validation
public static function createFromFormat($format, $time, $object = null) { if (empty($object)) { $object = new DateTimeZone('America/Sao_Paulo'); } return self::cast(parent::createFromFormat($format, $time, $object)); }
php
{ "resource": "" }
q253516
FileBasedFactory.getTemplatePath
validation
private function getTemplatePath($template) { if (strpos($template, '@') === false && !empty($this->defaultNamespace)) { $template .= '@' . $this->defaultNamespace; } $map = $this->buildTemplatesMap(); if (!array_key_exists($template, $map)) { throw new \RuntimeException("A template by the name '$template' does not exist. The following templates are available: " . join(', ', array_keys($map))); } return $map[$template]; }
php
{ "resource": "" }
q253517
FileBasedFactory.buildTemplatesMap
validation
private function buildTemplatesMap() { if (!empty($this->templatesMap)) { return $this->templatesMap; } $this->templatesMap = []; foreach ($this->templatesPaths as $templatesPath => $templatesNamespace) { if (!is_readable($templatesPath)) { throw new \RuntimeException("Templates path '$templatesPath' does not exist or is not readable."); } foreach (glob($templatesPath . '/*.phtml') as $templatePath) { $template = pathinfo($templatePath, PATHINFO_FILENAME); if ($templatesNamespace !== null) { $template .= '@' . $templatesNamespace; } if (array_key_exists($template, $this->templatesMap)) { throw new \OverflowException("Can't import template '$template' from '$templatePath' as a template with the same name already exists at '{$this->templatesMap[$template]}'. You may want to use namespaces."); } $this->templatesMap[$template] = $templatePath; } } return $this->templatesMap; }
php
{ "resource": "" }
q253518
Group.update
validation
public function update($groupId, $name) { $params = [ 'group' => [ 'id' => $groupId, 'name' => $name, ], ]; return $this->parseJSON('json', [self::API_UPDATE, $params]); }
php
{ "resource": "" }
q253519
Group.moveUser
validation
public function moveUser($openId, $groupId) { $params = [ 'openid' => $openId, 'to_groupid' => $groupId, ]; return $this->parseJSON('json', [self::API_MEMBER_UPDATE, $params]); }
php
{ "resource": "" }
q253520
Group.moveUsers
validation
public function moveUsers(array $openIds, $groupId) { $params = [ 'openid_list' => $openIds, 'to_groupid' => $groupId, ]; return $this->parseJSON('json', [self::API_MEMBER_BATCH_UPDATE, $params]); }
php
{ "resource": "" }
q253521
BackendController.initTemplateAssetsManager
validation
protected function initTemplateAssetsManager() { $templateAssetsManager = $this->options["template_assets"]; $pluginManager = $this->options["plugin_manager"]; $templateAssetsManager ->backend() ->add($pluginManager->getAssets()) ; return $templateAssetsManager; }
php
{ "resource": "" }
q253522
PreAuthorization.getCode
validation
public function getCode() { $data = [ 'component_appid' => $this->getAppId(), ]; $result = $this->parseJSON('json', [self::CREATE_PRE_AUTH_CODE, $data]); if (empty($result['pre_auth_code'])) { throw new InvalidArgumentException('Invalid response.'); } return $result['pre_auth_code']; }
php
{ "resource": "" }
q253523
AbstractApp.stopCustomProcess
validation
private function stopCustomProcess(): void { if ($this->isCustomProcessSet()) { $this->getCustomProcess()->stop(); } elseif (class_exists('\extensions\core\Process')) { \extensions\core\Process::getInstance()->stop(); } }
php
{ "resource": "" }
q253524
AbstractTemplate.render
validation
public function render(array $data = null): string { $this->init($data ?? []); return trim($this->make(static::LAYOUT_NAME)) . PHP_EOL; }
php
{ "resource": "" }
q253525
AbstractTemplate.head
validation
public function head(): string { $property = static::HEAD_ASSETS_NAME . static::BLOCK_PROPERTY_SUFFIX; return isset($this->$property) ? trim($this->make(static::HEAD_ASSETS_NAME)) . PHP_EOL : PHP_EOL; }
php
{ "resource": "" }
q253526
AbstractTemplate.end
validation
public function end(): string { $property = static::END_ASSETS_NAME . static::BLOCK_PROPERTY_SUFFIX; return isset($this->$property) ? trim($this->make(static::END_ASSETS_NAME)) . PHP_EOL : PHP_EOL; }
php
{ "resource": "" }
q253527
AbstractTemplate.inset
validation
public function inset(string $block, array $vars = null): string { return trim($this->make($block, $vars)) . PHP_EOL; }
php
{ "resource": "" }
q253528
AbstractTemplate.insetIf
validation
public function insetIf(bool $condition, string $block, array $vars = null): string { return $condition ? trim($this->make($block, $vars)) . PHP_EOL : PHP_EOL; }
php
{ "resource": "" }
q253529
AbstractTemplate.loop
validation
public function loop(array $collection, string $block, string $emptyBlock = null): string { if (empty($collection)) { return isset($emptyBlock) ? trim($this->make($emptyBlock)) . PHP_EOL : PHP_EOL; } else { $items = ''; foreach ($collection as $key => $item) { $items .= rtrim($this->make($block, ['key' => $key, 'item' => $item])); } return ltrim($items) . PHP_EOL; } }
php
{ "resource": "" }
q253530
AbstractTemplate.make
validation
private function make(string $block, array $vars = null): string { $commonVars = static::COMMON_NAME . static::VARS_PROPERTY_SUFFIX; $blockVars = $block . static::VARS_PROPERTY_SUFFIX; $allVars = []; if (isset($this->$commonVars) && is_array($this->$commonVars)) { $allVars = $this->$commonVars; } if (isset($this->$blockVars) && is_array($this->$blockVars)) { $allVars += $this->$blockVars; } if (isset($vars)) { $allVars += $vars; } $file = $this->path . $this->{$block . static::BLOCK_PROPERTY_SUFFIX} . '.' . static::FILE_EXTENSION; $localScope = function ($vars, $file) { ob_start(); extract($vars); try { require $file; } catch (\Exception $exception) { ob_end_clean(); throw $exception; } $_ = isset($_) ? str_pad('', $_) : ''; return str_replace(PHP_EOL, PHP_EOL . $_, PHP_EOL . ob_get_clean()); }; return $localScope($allVars, $file); }
php
{ "resource": "" }
q253531
PostRepository.countTotal
validation
public function countTotal($categoryId=null) { $qb = $this->getQueryBuilder() ->select('COUNT(p)'); if(!is_null($categoryId)){ $qb->join('p.categories', 'c') ->where('c.id = :categoryId') ->setParameter('categoryId', $categoryId); } return $qb->getQuery()->getSingleScalarResult(); }
php
{ "resource": "" }
q253532
PostRepository.findPost
validation
public function findPost($search) { // select $qb = $this->getQueryBuilder() ->select('p, pTrans') ->join('p.translations', 'pTrans') ; // search if (!empty($search)) { $qb->where('pTrans.title LIKE :search') ->orWhere('pTrans.description LIKE :search') ->setParameter('search', '%'.$search.'%'); } $qb->orderBy('p.published', 'DESC'); return $qb->getQuery()->getResult(); }
php
{ "resource": "" }
q253533
PostRepository.findOneLastPost
validation
public function findOneLastPost($site) { // select $qb = $this->getQueryBuilder() ->select('p.id, p.title, p.description, p.slug, p.published, i.path as image_path') ->leftJoin('p.images', 'i') ->andWhere('p.highlighted=1') ->setMaxResults(1) ->orderBy('p.published', 'DESC'); return $qb->getQuery()->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); }
php
{ "resource": "" }
q253534
Repository.update
validation
public function update(array $data, $id) { $resource = $this->model->find($id); if (! $resource) { return ''; } $resource->update($data); return $resource; }
php
{ "resource": "" }
q253535
Repository.delete
validation
public function delete($id) { $resource = $this->model->find($id); if (! $resource) { return ''; } return $resource->delete(); }
php
{ "resource": "" }
q253536
Repository.findBy
validation
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, $include = null, $fields = null) { $this->builder = $this->model; if (count($criteria) == count($criteria, COUNT_RECURSIVE)) { if (count($criteria) > 0) { $this->builder = $this->builder->where($criteria[0], $criteria[1], $criteria[2]); } } else { foreach ($criteria as $c) { if($c[1] == 'between') { $this->builder = $this->builder->whereBetween($c[0], explode(',', $c[2])); continue; } $this->builder = $this->builder->where($c[0], $c[1], $c[2]); } } if ($orderBy !== null) { foreach ($orderBy as $order) { $this->builder = $this->builder->orderBy($order[0], $order[1]); } } if ($limit !== null) { $this->builder = $this->builder->take((int) $limit); } if ($offset !== null) { $this->builder = $this->builder->skip((int) $offset); } if ($include !== null) { $this->builder = $this->builder->with($include); } if ($fields !== null) { $this->builder = $this->builder->select($fields); } return $this->builder->get(); }
php
{ "resource": "" }
q253537
Repository.filter
validation
public function filter(FilterRequest $filters) { $search = new Search($this->model, $filters); $this->builder = $search->getBuilder(); return $this; }
php
{ "resource": "" }
q253538
Repository.getRules
validation
public function getRules(array $fields = []) { $default_rules = $this->model->getRules(); if (count($fields) < 1) { return $default_rules; } foreach ($fields as $field => $rule) { if (is_int($field)) { $rules[$rule] = $default_rules[$rule]; continue; } if (! key_exists($field, $default_rules)) { continue; } $default_rules[$field] .= '|' . $rule; } $rules = []; $transformation = $this->model->getTransformation(); foreach ($transformation as $original => $transformed) { $rules[$transformed] = $default_rules[$original]; } foreach ($fields as $field => $rule) { if (! key_exists($field, $rules)) { continue; } $rules[$field] .= '|' . $rule; } return $rules; }
php
{ "resource": "" }
q253539
Repository.onlyFillablePivot
validation
public function onlyFillablePivot($pivotRelation, $data) { $fillable = $this->getPivotFields($pivotRelation, 'pivotColumns'); return array_only($data, $fillable); }
php
{ "resource": "" }
q253540
Repository.getPivotFields
validation
public function getPivotFields($obj, $prop) { $reflection = new \ReflectionClass($obj); $property = $reflection->getProperty($prop); $property->setAccessible(true); $value = $property->getValue($obj); $property->setAccessible(false); /* Remove timestamp from pivot */ return array_diff($value, [ 'deleted_at', 'created_at', 'updated_at' ]); }
php
{ "resource": "" }
q253541
Repository.storeChild
validation
public function storeChild($id, $relation, array $data) { $parent = $this->model->find($id); if (! $parent) { return null; } $resource = $parent->$relation()->create($data); return $resource; }
php
{ "resource": "" }
q253542
Repository.getChilds
validation
public function getChilds($id, $relation, $filters = null) { $parent = $this->model->find($id); if (! $parent) { return null; } if (count($filters->request->all()) > 0) { $child = $parent->$relation()->getRelated(); $search = new Search($child, $filters, $parent->$relation()); $this->builder = $search->getBuilder(); /* Retorna os dados apenas da table/resource atual */ $this->builder->select("{$child->getTable()}.*"); return $this->builder->get(); } $resource = $parent->$relation; return $resource; }
php
{ "resource": "" }
q253543
Repository.getChild
validation
public function getChild($id, $relation, $idChild, $filters = null) { $parent = $this->model->find($id); if (! $parent) { return null; } if (count($filters->request->all()) > 0) { $child = $parent->$relation()->getRelated(); $search = new Search($child, $filters, $parent->$relation()); $this->builder = $search->getBuilder(); /* Retorna os dados apenas da table/resource atual */ $this->builder->select("{$child->getTable()}.*"); /* N:N precisa add o id da outra tabela */ if ($parent->$relation() instanceof \Illuminate\Database\Eloquent\Relations\BelongsToMany) { $this->builder->where($parent->$relation() ->getOtherKey(), $idChild); } $resource = $this->builder->get(); } else { $resource = $parent->$relation()->find($idChild); } return $resource; }
php
{ "resource": "" }
q253544
SitemapGenerator.generateSiteMap
validation
protected function generateSiteMap() { $urls = array(); $siteName = $this->configurationHandler->siteName(); foreach ($this->pagesCollectionParser->pages() as $page) { foreach($page["seo"] as $seo) { $urls[] = array( 'href' => $siteName . '/' . $seo["permalink"], 'frequency' => $seo["sitemap_frequency"], 'priority' => $seo["sitemap_priority"], ); } } return $this->twig->render('RedKiteCms/Resources/views/Sitemap/sitemap.html.twig', array('urls' => $urls)); }
php
{ "resource": "" }
q253545
HCLanguagesController.adminIndex
validation
public function adminIndex() { $config = [ 'title' => trans('HCLanguages::languages.page_title'), 'listURL' => route('admin.api.languages'), 'newFormUrl' => route('admin.api.form-manager', ['languages-new']), 'editFormUrl' => route('admin.api.form-manager', ['languages-edit']), 'imagesUrl' => route('resource.get', ['/']), 'headers' => $this->getAdminListHeader(), ]; $config['actions'][] = 'search'; return hcview('HCCoreUI::admin.content.list', ['config' => $config]); }
php
{ "resource": "" }
q253546
HCLanguagesController.getAdminListHeader
validation
public function getAdminListHeader() { return [ 'language_family' => [ "type" => "text", "label" => trans('HCLanguages::languages.language_family'), ], 'language' => [ "type" => "text", "label" => trans('HCLanguages::languages.language'), ], 'native_name' => [ "type" => "text", "label" => trans('HCLanguages::languages.native_name'), ], 'iso_639_1' => [ "type" => "text", "label" => trans('HCLanguages::languages.iso_639_1'), ], 'iso_639_2' => [ "type" => "text", "label" => trans('HCLanguages::languages.iso_639_2'), ], 'front_end' => [ "type" => "checkbox", "label" => trans('HCLanguages::languages.front_end'), "url" => route('admin.api.languages.update.strict', 'id') ], 'back_end' => [ "type" => "checkbox", "label" => trans('HCLanguages::languages.back_end'), "url" => route('admin.api.languages.update.strict', 'id') ], 'content' => [ "type" => "checkbox", "label" => trans('HCLanguages::languages.content'), "url" => route('admin.api.languages.update.strict', 'id') ], ]; }
php
{ "resource": "" }
q253547
HCLanguagesController.__apiUpdateStrict
validation
protected function __apiUpdateStrict(string $id) { HCLanguages::where('id', $id)->update($this->getStrictRequestParameters()); return $this->apiShow($id); }
php
{ "resource": "" }
q253548
DateRange.getDatePeriod
validation
public function getDatePeriod() { $intervaloDiario = DateInterval::createFromDateString('1 day'); $dataFim = clone $this->endDate; $dataFim->add($intervaloDiario); return new DatePeriod($this->startDate, $intervaloDiario, $dataFim); }
php
{ "resource": "" }
q253549
BackendController.showAction
validation
public function showAction(Request $request, Application $app) { $options = $this->options($request, $app); return parent::show($options); }
php
{ "resource": "" }
q253550
AuthenticationController.resetPasswordAction
validation
public function resetPasswordAction() { // if the user is logged in, we can't reset password if ($this->cmsAuthentication()->hasIdentity()) { // redirect to the defualt user route return $this->redirect()->toRoute($this->getOptions()->getDefaultUserRoute()); } if ($token = $this->params()->fromRoute('token')) { $identity = $this->getUserService()->confirmPasswordReset($token); if ($identity instanceof ResponseInterface) { return $identity; } elseif ($identity) { $viewModel = new ViewModel(compact('identity')); $viewModel->setTemplate('cms-user/authentication/reset-password-success'); return $viewModel; } return $this->redirect()->toRoute(); } $url = $this->url()->fromRoute(); $prg = $this->prg($url, true); if ($prg instanceof ResponseInterface) { return $prg; } $post = $prg; $form = $this->getUserService()->getResetPasswordForm(); $form->setAttribute('action', $url); if ($post && $form->setData($post)->isValid()) { $identity = $this->getUserService()->resetPassword($form->get('identity')->getValue()); // Return early if an user service returned a response if ($identity instanceof ResponseInterface) { return $identity; } elseif ($identity) { // Password reset successfully $viewModel = new ViewModel(compact('identity')); $viewModel->setTemplate('cms-user/authentication/reset-password-warning'); return $viewModel; } } return new ViewModel(compact('form')); }
php
{ "resource": "" }
q253551
AssetsManager.findFile
validation
private function findFile($uriPath) { return array_reduce($this->paths, function ($file, $path) use ($uriPath) { if (false !== $file) { return $file; } $file = $path . $uriPath; if (is_file($file) && is_readable($file)) { return $file; } return false; }, false); }
php
{ "resource": "" }
q253552
AssetsManager.detectMimeType
validation
private function detectMimeType($file) { $fileParts = explode('.', $file); $extension = array_pop($fileParts); $extension = strtolower($extension); if (array_key_exists($extension, $this->mimeTypes)) { return $this->mimeTypes[$extension]; } if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $file); finfo_close($finfo); return $mimeType; } return 'application/octet-stream'; }
php
{ "resource": "" }
q253553
AssetsManager.writeToWebDir
validation
private function writeToWebDir($file, $contents) { if (!$this->webDir) { return; } if (!is_writable($this->webDir)) { trigger_error(sprintf('Directory %s is not writeable', $this->webDir)); return; } $destFile = $this->webDir . $file; $destDir = dirname($destFile); if (!is_dir($destDir)) { mkdir($destDir, 0777, true); } file_put_contents($destFile, $contents); }
php
{ "resource": "" }
q253554
CreateJob.toArray
validation
public function toArray() { $data = [ "uuid" => $this->uuid, "code" => $this->code, "modules" => $this->modules, "vars" => $this->vars, ]; foreach (['modules', 'vars'] as $key) { if (!array_key_exists($key, $data)) { continue; } if (empty($data[$key])) { $data[$key] = new \stdClass(); } } return $data; }
php
{ "resource": "" }
q253555
CategoryController.newAction
validation
public function newAction(Request $request) { $category = new Category(); $form = $this->createForm('BlogBundle\Form\CategoryType', $category); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($category); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'category.created'); return $this->redirectToRoute('blog_category_index'); } return array( 'category' => $category, 'form' => $form->createView(), ); }
php
{ "resource": "" }
q253556
CategoryController.sortAction
validation
public function sortAction(Request $request) { $em = $this->getDoctrine()->getManager(); if ($request->isXmlHttpRequest()) { $this->get('admin_manager')->sort('BlogBundle:Category', $request->get('values')); return new Response(0, 200); } $categories = $em->getRepository('BlogBundle:Category')->findBy( array('parentCategory' => NULL), array('order' => 'asc') ); return array( 'categories' => $categories ); }
php
{ "resource": "" }
q253557
CategoryController.editAction
validation
public function editAction(Request $request, Category $category) { $deleteForm = $this->createDeleteForm($category); $editForm = $this->createForm('BlogBundle\Form\CategoryType', $category); $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($category); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'category.edited'); return $this->redirectToRoute('blog_category_index'); } return array( 'entity' => $category, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q253558
YamlCollectionLoader.load
validation
public function load($name) { foreach ($this->sourceDirs as $dir) { if (0 === strpos($name, DIRECTORY_SEPARATOR)) { $yamlFile = $name; } else { $yamlFile = $dir . '/' . $name; } if (false === strstr($yamlFile, self::EXT_YML)) { $yamlFile .= self::EXT_YML; } if (is_file($yamlFile)) { return new ArrayCollection(Yaml::parse($yamlFile)); } } throw new \Exception(sprintf('No Yaml file found for {%s}', $name)); }
php
{ "resource": "" }
q253559
HCURLShortenerController.searchQuery
validation
protected function searchQuery(Builder $query, string $phrase) { return $query->where (function (Builder $query) use ($phrase) { $query->where('url', 'LIKE', '%' . $phrase . '%') ->orWhere('short_url_key', 'LIKE', '%' . $phrase . '%') ->orWhere('clicks', 'LIKE', '%' . $phrase . '%') ->orWhere('url', 'LIKE', '%' . $phrase . '%'); }); }
php
{ "resource": "" }
q253560
HCURLShortenerController.redirect
validation
public function redirect(string $shortURLKey) { $record = HCShortURL::where('short_url_key', $shortURLKey)->first(); if (!$record) abort(404); $record->increment('clicks'); return redirect($record->url); }
php
{ "resource": "" }
q253561
Config.getBundleLocationName
validation
public static function getBundleLocationName(string $sName): string { $oConfig = self::get($sName, null, true); if (isset($oConfig->redirect)) { return $oConfig->redirect; } else { return PORTAL; } }
php
{ "resource": "" }
q253562
CliCommand.prepareData
validation
protected function prepareData(InputInterface $input) { $return = []; foreach ($this->validators as $validator) { $result = $validator->validate($input); if (isset($result) && is_array($result)) { $return = NestedArray::mergeDeep($return, $result); } elseif (isset($result)) { $return[] = $result; } } return $return; }
php
{ "resource": "" }
q253563
CliCommand.run
validation
public function run(InputInterface $input, OutputInterface $output) { $this->doPreRun($input, $output); $code = parent::run($input, $output); $this->doPostRun($input, $output, $code); return $code; }
php
{ "resource": "" }
q253564
CliCommand.askQuestions
validation
protected function askQuestions(InputInterface $input, OutputInterface $output) { foreach ($this->questions as $question) { if (!$question->ask($input, $output)) { return static::RETURN_ERROR; } } return static::RETURN_SUCCESS; }
php
{ "resource": "" }
q253565
CliCommand.doExecute
validation
protected function doExecute(InputInterface $input, OutputInterface $output) { // Ask questions. if ($this->askQuestions($input, $output) == static::RETURN_ERROR) { return static::RETURN_ERROR; } // Prepare data. $data = $this->prepareData($input); // Pre-execute $this->doPreExecuteTasks($input, $output, $data); // Execute. $return = $this->executeTasks($input, $output, $data); // Post execute. $this->doPostExecuteTasks($input, $output, $data, $return); return $return; }
php
{ "resource": "" }
q253566
CliCommand.execute
validation
protected function execute(InputInterface $input, OutputInterface $output) { try { $this->doPreExecute($input, $output); $this->returnCode = $this->doExecute($input, $output); $this->doPostExecute($input, $output); } catch(Exception $e) { $this->returnCode = static::RETURN_ERROR; throw $e; } return $this->returnCode; }
php
{ "resource": "" }
q253567
Material.uploadImage
validation
public function uploadImage($path, $type = 'icon') { if (!file_exists($path) || !is_readable($path)) { throw new InvalidArgumentException("File does not exist, or the file is unreadable: '$path'"); } $type = strtolower($type); return $this->parseJSON('upload', [self::API_MATERIAL_ADD, ['media' => $path], [], ['type' => $type]]); }
php
{ "resource": "" }
q253568
ParamBehavior.getParam
validation
protected function getParam($param) { if (isset($_POST[$param])) { return $_POST[$param]; } elseif (isset($_GET[$param])) { return $_GET[$param]; } return; }
php
{ "resource": "" }
q253569
WP_Enqueue_Util.enqueue_script
validation
public function enqueue_script( WP_Enqueue_Options $options ) { if ( ! $options->have_required_properties() ) { trigger_error( 'Trying to enqueue script, but required properties are missing.' ); return; } // Required options. $handle = $options->get_handle(); $relative_path = $options->get_relative_path(); $filename = $options->get_filename(); // Optional options. $filename_debug = $options->get_filename_debug(); $dependencies = $options->get_dependencies(); $version = $options->get_version(); $in_footer = $options->get_in_footer(); // Localization options. $localization_name = $options->get_localization_name(); $data = $options->get_data(); $source = $this->get_source_to_enqueue( $relative_path, $filename, $filename_debug ); wp_register_script( $handle, $source, $dependencies, $version, $in_footer ); if ( ! empty( $localization_name ) && ! empty( $data ) ) { wp_localize_script( $handle, $localization_name, $data ); } wp_enqueue_script( $handle ); }
php
{ "resource": "" }
q253570
WP_Enqueue_Util.enqueue_style
validation
public function enqueue_style( WP_Enqueue_Options $options ) { if ( ! $options->have_required_properties() ) { trigger_error( 'Trying to enqueue style, but required properties are missing.' ); return; } // Required options. $handle = $options->get_handle(); $relative_path = $options->get_relative_path(); $filename = $options->get_filename(); // Optional options. $filename_debug = $options->get_filename_debug(); $dependencies = $options->get_dependencies(); $version = $options->get_version(); $media = $options->get_media(); $source = $this->get_source_to_enqueue( $relative_path, $filename, $filename_debug ); wp_enqueue_style( $handle, $source, $dependencies, $version, $media ); }
php
{ "resource": "" }
q253571
WP_Enqueue_Util.get_source_to_enqueue
validation
public function get_source_to_enqueue( $relative_path, $filename, $filename_debug = null ) { $source_file = $filename; if ( defined( 'SCRIPT_DEBUG' ) && true === SCRIPT_DEBUG && !empty( $filename_debug ) ) { $source_file = $filename_debug; } $path = realpath( trailingslashit( $relative_path ) . $source_file ); return WP_Url_Util::get_instance()->convert_absolute_path_to_url( $path ); }
php
{ "resource": "" }
q253572
ReferenceRepository.get
validation
public function get($key) { if (!$this->repository->containsKey($key)) throw new ReferenceDoesNotExistException(); return $this->repository->get($key); }
php
{ "resource": "" }
q253573
ReferenceRepository.add
validation
public function add($key, $object) { if ($this->repository->containsKey($key)) throw new ReferenceExistsException(); $this->repository->set($key, $object); }
php
{ "resource": "" }
q253574
Security._checkBlackListIps
validation
private function _checkBlackListIps() : bool { $oSecurity = Config::get('security'); if (isset($oSecurity->blacklist_ips)) { foreach ($oSecurity->blacklist_ips as $sIp) { if ($_SERVER['REMOTE_ADDR'] == $sIp) { return false; } } } return true; }
php
{ "resource": "" }
q253575
Security._checkPasswordIsGood
validation
private function _checkPasswordIsGood() : bool { $sLogin = self::$_sLogin; $sPassword = Config::get('security')->users->$sLogin->password; if ($sPassword == self::$_sPassword) { return true; } else if ($sPassword == md5(self::$_sPassword)) { return true; } else { return false; } }
php
{ "resource": "" }
q253576
IndexController.editProfileAction
validation
public function editProfileAction() { // if the user is not logged in, we can't edit profile if (!$this->cmsAuthentication()->hasIdentity()) { // redirect to the login redirect route return $this->redirect()->toRoute($this->getOptions()->getLoginRoute()); } $url = $this->url()->fromRoute(null, ['action' => 'edit-profile']); $prg = $this->prg($url, true); if ($prg instanceof ResponseInterface) { return $prg; } $post = $prg; $form = $this->getUserService()->getEditProfileForm(); $identity = $this->cmsAuthentication()->getIdentity(); $form->bind($identity); $form->setAttribute('action', $url); if ($post && $form->setData($post)->isValid()) { $result = $this->getUserService()->editProfile($identity); // Return early if an user service returned a response if ($result instanceof ResponseInterface) { return $result; } elseif ($result) { $fm = $this->flashMessenger(); $fm->setNamespace($form->getName() . '-' . $fm::NAMESPACE_SUCCESS) ->addMessage($this->translate('Data has been successfully saved')); } } return new ViewModel(compact('form')); }
php
{ "resource": "" }
q253577
IndexController.changePasswordAction
validation
public function changePasswordAction() { // if the user is not logged in, we can't change password if (!$this->cmsAuthentication()->hasIdentity()) { // redirect to the login redirect route return $this->redirect()->toRoute($this->getOptions()->getLoginRoute()); } $url = $this->url()->fromRoute(null, ['action' => 'change-password']); $prg = $this->prg($url, true); if ($prg instanceof ResponseInterface) { return $prg; } $post = $prg; $form = $this->getUserService()->getChangePasswordForm(); $form->setObject($this->cmsAuthentication()->getIdentity()); $form->setAttribute('action', $url); if ($post && $form->setData($post)->isValid()) { $identity = $this->getUserService()->changePassword($post); // Return early if an user service returned a response if ($identity instanceof ResponseInterface) { return $identity; } elseif ($identity) { // Password changed successfully $viewModel = new ViewModel(compact('identity')); $viewModel->setTemplate('cms-user/index/change-password-success'); return $viewModel; } } return new ViewModel(compact('form')); }
php
{ "resource": "" }
q253578
IndexController.confirmEmailAction
validation
public function confirmEmailAction() { $token = $this->params()->fromRoute('token'); if ($token) { $identity = $this->getUserService()->confirmEmail($token); if ($identity instanceof ResponseInterface) { return $identity; } elseif ($identity) { $viewModel = new ViewModel(compact('identity')); $viewModel->setTemplate('cms-user/index/confirm-email'); return $viewModel; } } return $this->redirect()->toRoute($this->getOptions()->getDefaultUserRoute()); }
php
{ "resource": "" }
q253579
IndexController.changeSecurityQuestionAction
validation
public function changeSecurityQuestionAction() { // if the user is not logged in, we can't change security question if (!$this->cmsAuthentication()->hasIdentity()) { // redirect to the login redirect route return $this->redirect()->toRoute($this->getOptions()->getLoginRoute()); } $url = $this->url()->fromRoute(null, ['action' => 'change-security-question']); $prg = $this->prg($url, true); if ($prg instanceof ResponseInterface) { return $prg; } $post = $prg; $form = $this->getUserService()->getChangeSecurityQuestionForm(); $form->setObject($this->cmsAuthentication()->getIdentity()); $form->setAttribute('action', $url); if ($post) { $identity = $this->getUserService()->changeSecurityQuestion($post); // Return early if an user service returned a response if ($identity instanceof ResponseInterface) { return $identity; } elseif ($identity) { // Security question changed successfully $viewModel = new ViewModel(compact('identity')); $viewModel->setTemplate('cms-user/index/change-security-question-success'); return $viewModel; } } return new ViewModel(compact('form')); }
php
{ "resource": "" }
q253580
AbstractCliCtrl.getColoredMsg
validation
private function getColoredMsg( string $msg, ?string $fontColor, ?string $bgColor ): string { $res = ''; if (!is_null($fontColor)) { $res .= "\033[{$fontColor}m"; } if (!is_null($bgColor)) { $res .= "\033[{$bgColor}m"; } if (!is_null($fontColor) || !is_null($bgColor)) { return "{$res}{$msg}\033[0m"; } return $msg; }
php
{ "resource": "" }
q253581
AbstractCliCtrl.print
validation
protected function print(string $msg, bool $withTime = true): void { $preMsg = ''; if ($withTime) { $preMsg = (new \DateTime('now'))->format('H:i:s')."\t"; } echo "{$preMsg}{$msg}".\PHP_EOL; }
php
{ "resource": "" }
q253582
AbstractCliCtrl.printError
validation
protected function printError( \Throwable $error, bool $withTime = true, ?string $fontColor = null, ?string $bgColor = self::BG_COLOR_MAP['red'] ): void { $shift = $withTime ? "\t\t" : ''; $this->print( $this->getColoredMsg( 'Error: '.$error->getMessage(), $fontColor, $bgColor ).\PHP_EOL .$shift.$this->getColoredMsg( 'File: '.$error->getFile(), $fontColor, $bgColor ).\PHP_EOL .$shift.$this->getColoredMsg( 'Line: '.$error->getLine(), $fontColor, $bgColor ), $withTime ); }
php
{ "resource": "" }
q253583
AbstractCliCtrl.printInfo
validation
protected function printInfo( $msg, bool $withTime = true, ?string $fontColor = self::FONT_COLOR_MAP['lightGreen'], ?string $bgColor = null ): void { $this->print($this->getColoredMsg($msg, $fontColor, $bgColor), $withTime); }
php
{ "resource": "" }
q253584
PostController.newAction
validation
public function newAction(Request $request) { $post = new Post(); $form = $this->createForm('BlogBundle\Form\PostType', $post, array('translator' => $this->get('translator') )); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user = $this->container->get('security.token_storage')->getToken()->getUser(); $post->setActor($user); $em = $this->getDoctrine()->getManager(); $em->persist($post); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'post.created'); return $this->redirectToRoute('blog_post_index'); } return array( 'category' => $post, 'form' => $form->createView(), ); }
php
{ "resource": "" }
q253585
PostController.showAction
validation
public function showAction(Post $post) { $deleteForm = $this->createDeleteForm($post); return array( 'entity' => $post, 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q253586
PostController.editAction
validation
public function editAction(Request $request, Post $post) { if(is_object($post->getPublished()) && $post->getPublished()->format('dmY') == '3011-0001'){ $post->setPublished(null); } $deleteForm = $this->createDeleteForm($post); $editForm = $this->createForm('BlogBundle\Form\PostType', $post, array('translator' => $this->get('translator') )); $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($post); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'post.edited'); return $this->redirectToRoute('blog_post_index'); } return array( 'entity' => $post, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q253587
PostController.createDeleteForm
validation
private function createDeleteForm(Post $post) { return $this->createFormBuilder() ->setAction($this->generateUrl('blog_category_delete', array('id' => $post->getId()))) ->setMethod('DELETE') ->getForm() ; }
php
{ "resource": "" }
q253588
TemplateAssetsManager.add
validation
public function add(array $assets) { foreach ($assets as $type => $asset) { if ($asset instanceof Plugin) { $this->parse($asset); continue; } $this->assets[$type] = array_merge($this->assets[$type], $asset); } }
php
{ "resource": "" }
q253589
Aggregate.getConnectionInitializer
validation
protected function getConnectionInitializer(OptionsInterface $options, $callable) { if (!is_callable($callable)) { $class = get_called_class(); throw new \InvalidArgumentException("$class expects a valid callable"); } $option = $this; return function ($parameters = null) use ($callable, $options, $option) { $connection = call_user_func($callable, $options, $parameters); if (!$connection instanceof AggregateConnectionInterface) { $class = get_class($option); throw new \InvalidArgumentException("$class expects a valid connection type returned by callable initializer"); } return $connection; }; }
php
{ "resource": "" }
q253590
Item.getTaxonomy
validation
public function getTaxonomy($system_id) { foreach ($this->getTaxonomies() as $taxonomy) { if ($taxonomy->system_id === $system_id) { return $taxonomy; } } return false; }
php
{ "resource": "" }
q253591
Auth.validate
validation
public function validate(string $api_session = null) { $this->details = false; if (empty($api_session) === false && is_string($api_session) === true) { $session = Model\Session::with('user')->where('code', $api_session)->first(); if ($session !== null) { if (strtotime($session->updated_at) < strtotime("-1 hour") || $session->user === null) { $this->invalidate($api_session); } else { $session->updated_at = date('Y-m-d H:i:s'); $session->save(); $this->details = $session->user; } } else { $_SESSION['api_session'] = null; } } }
php
{ "resource": "" }
q253592
Auth.invalidate
validation
public function invalidate(string $api_session = null) { if (empty($api_session) === false && is_string($api_session) === true) { $session = Model\Session::where('code', $api_session)->first(); if ($session !== null) { $session->delete(); } } elseif (empty($_SESSION['api_session']) === false && is_string($_SESSION['api_session']) === true) { $session = Model\Session::where('code', $_SESSION['api_session'])->first(); if ($session !== null) { $session->delete(); } } elseif (empty($_GET['api_session']) === false && is_string($_GET['api_session']) === true) { $session = Model\Session::where('code', $_GET['api_session'])->first(); if ($session !== null) { $session->delete(); } } $this->details = false; $_SESSION['api_session'] = null; $_GET['api_session'] = null; }
php
{ "resource": "" }
q253593
Auth.allow
validation
public function allow(array $level_select = ["min" => 4,"max" => 4]): bool { if ($this->details !== false) { if (is_array($level_select) === true && isset($level_select["min"]) === true && isset($level_select["max"]) === true) { $level_select["min"] = Model\Role::find($level_select["min"])->priority; $level_select["max"] = Model\Role::find($level_select["max"])->priority; $level_select = ["min" => $level_select["min"], "max" => $level_select["max"]]; } else { return false; } $current_priority = $this->details->role->priority; if (is_numeric($level_select["min"]) === true && is_numeric($level_select["max"]) === true) { if ($level_select["min"] >= $current_priority && $level_select["max"] <= $current_priority) { return true; } else { return false; } } else { return false; } } else { return false; } }
php
{ "resource": "" }
q253594
ViewModel.save
validation
public function save() { try { $autenticacao = new Autenticacao(); $autenticacao->exchangeArray($this->form->getData()); $perfilDefault = $this->autenticacaoManager->getPerfilManager()->obterPerfilByNome(Acesso::getDefaultRole()); $autenticacao = $this->autenticacaoManager->salvar( $autenticacao->setPerfilId($perfilDefault->getId()) ->setPerfil($perfilDefault) ); $this->addNotificacao(new Notificacao(Notificacao::TIPO_SUCESSO, self::MESSAGE_INSERT_SUCCESS)); } catch (\Exception $e) { $this->addNotificacao(new Notificacao(Notificacao::TIPO_ERRO, self::MESSAGE_INTERNAL_ERROR)); } return true; }
php
{ "resource": "" }
q253595
AbstractView.setFilePath
validation
public function setFilePath(string $viewFilePath): void { if (!is_readable($viewFilePath)) { throw new Exception("The View file {$viewFilePath} isn't readable."); } $this->filePath = $viewFilePath; }
php
{ "resource": "" }
q253596
AbstractView.setVariables
validation
public function setVariables(array $data): void { foreach ($data as $key => $value) { $this->$key = $value; } }
php
{ "resource": "" }
q253597
ThemeGenerator.generate
validation
public function generate() { if (!$this->configurationHandler->isTheme() || $this->theme->getName() != $this->configurationHandler->handledTheme()) { return; } $templates = array_keys($this->templates["template"]); $homepage = json_decode(file_get_contents($this->configurationHandler->pagesDir() . '/' .$this->configurationHandler->homepage() . '/page.json'), true); $homepageTemplate = $homepage["template"]; if (!in_array($homepageTemplate, $templates)) { $homepageTemplate = $templates[0]; } $themeDefinition = array( "home_template" => $homepageTemplate, "templates" => $templates, ); $this->synchronizeThemeSlots(); FilesystemTools::writeFile($this->themeDir . '/theme.json', json_encode($themeDefinition)); }
php
{ "resource": "" }
q253598
ContentfulContentType.updateEntryName
validation
public function updateEntryName(ContentfulEntry $entry) { $displayField = $this->getDisplayField(); $values = array_values((array)$entry->{$displayField}); $entry->setName(isset($values[0]) ? $values[0] : 'Untitled'); }
php
{ "resource": "" }
q253599
Compress.registerCalc
validation
private function registerCalc($period) { $ctx = new \Praxigento\Core\Data(); $ctx->set(PCalcReg::IN_CALC_TYPE_CODE, Cfg::CODE_TYPE_CALC_FORECAST_PHASE1); $ctx->set(PCalcReg::IN_PERIOD, $period); /** @var \Praxigento\Core\Data $res */ $res = $this->zCalcReg->exec($ctx); $result = $res->get(PCalcReg::OUT_CALC_ID); return $result; }
php
{ "resource": "" }