_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q9400
AbstractColorManager.registerProvider
train
public function registerProvider(ColorProviderInterface $colorProvider) { $key = ColorHelper::getIdentifier($colorProvider); if (true === array_key_exists($key, $this->index)) { throw new AlreadyRegisteredProviderException($colorProvider); } $this->index[$key] = $this->size(); return $this->addProvider($colorProvider); }
php
{ "resource": "" }
q9401
Domain.setDomainName
train
public function setDomainName($domain) { $domain = strtolower($domain); if (!$this->getDomainValidator()->isValid($domain)) { throw new InvalidArgumentException( 'Domain name is invalid: ' . $domain ); } $this->domain = $domain; }
php
{ "resource": "" }
q9402
Domain.setPrimaryDomain
train
public function setPrimaryDomain($primaryDomain) { if (empty($primaryDomain)) { $this->primaryDomain = null; $this->primaryId = null; return; } $this->primaryDomain = $primaryDomain; $this->primaryId = $primaryDomain->getDomainId(); }
php
{ "resource": "" }
q9403
MenuController.isSortable
train
public function isSortable() { $this->getSearchCriteria(); $sortable = new \stdClass; if($this->searchModel->Menu_id > 0) { $sortable->sortable = true; $sortable->link = Url::toRoute(['sort', 'Menu_id' => $this->searchModel->Menu_id]); } else { $sortable->sortable = false; $sortable->message = 'Filter on a menu first'; } return $sortable; }
php
{ "resource": "" }
q9404
MenuController.actionSort
train
public function actionSort() { $this->layout = static::FORM_LAYOUT; $modelName = $this->getCompatibilityId(); if(isset($_POST[$modelName]) && count($_POST[$modelName])) { //If we are changing the main categories then use a different algorithm if($_GET['Menu_id']==-1) { foreach($_POST[$modelName] as $key => $id) { $record = $this->findModel($id); $record->sort_order = $key+1; $record->save(); } } else { $parent = $this->findModel($_GET['Menu_id']); foreach($_POST[$modelName] as $key => $id) { $record = $this->findModel($id); $record->appendTo($parent); } } return $this->redirect(['index']); } else { $this->getSearchCriteria(); $searchCriteria = ['MenuSearch' => ['Menu_id' => $this->searchModel->Menu_id]]; $this->searchModel = new $this->MainModelSearch; $this->dataProvider = $this->searchModel->search($searchCriteria); $this->dataProvider->pagination = false; return $this->render('sort', [ 'searchModel' => $this->searchModel, 'dataProvider' => $this->dataProvider, ]); } }
php
{ "resource": "" }
q9405
MenuController.actionStatus
train
public function actionStatus($id) { $model = $this->findModel($id); if($model->status == "active") { $model->status = "inactive"; } else { $model->status = "active"; } $model->save(false); if(Yii::$app->request->getIsAjax()) { Yii::$app->response->format = 'json'; return ['success' => true]; } else { return $this->redirect(['index']); } }
php
{ "resource": "" }
q9406
MenuController.actionCreate
train
public function actionCreate() { $this->layout = static::FORM_LAYOUT; $model = new $this->MainModel; if ($model->load(Yii::$app->request->post()) && $model->validate()) { if(empty($model->Menu_id)) { Yii::info('Making the new node as root'); $model->makeRoot(); } else { $parent_node = Menu::findOne($model->Menu_id); $model->appendTo($parent_node); Yii::info('Making the new node as a child of ' . $parent_node->id); } $this->saveHistory($model, $this->historyField); return $this->redirect(['index']); } else { return $this->render('create', [ 'model' => $model, ]); } }
php
{ "resource": "" }
q9407
ImageUploader.validateImageMimeType
train
private function validateImageMimeType() { $imageType = exif_imagetype($this->uploadFile->getTemporaryFilename()); $mime = image_type_to_mime_type($imageType); if (!$imageType || !in_array($mime, parent::getAllowedMimeTypes())) { throw new \Exception("Uploaded image appears to be corrupt"); // @codeCoverageIgnore } }
php
{ "resource": "" }
q9408
ChainManager.attach
train
public function attach(ChainEventInterface $event, $priority = 0) { $this->queue->insert($event, $priority); return $this; }
php
{ "resource": "" }
q9409
Parser.parsePathParts
train
private function parsePathParts(Request $request) { if (empty($this->apiUrlPath)) { throw new \Exception(self::ERROR_NO_API_BASE_PATH); } // Resolving not knowing whether the base contains a domain. $base = explode('/', $this->apiUrlPath); $path = explode('/', $request->getPathInfo()); return array_values(array_diff($path, $base)); }
php
{ "resource": "" }
q9410
ArrayHelper.getItems
train
public static function getItems($array, $keys = null) { if (is_null($keys)) { return $array; } elseif (is_scalar($keys)) { $keys = [$keys => $array[$keys]]; } $res = []; foreach ($keys as $k) { if (array_key_exists($k, $array)) { $res[$k] = $array[$k]; } } return $res; }
php
{ "resource": "" }
q9411
ArrayHelper.prepareWhere
train
protected static function prepareWhere(array $array, $list) { if (!is_array($list)) { $list = [$list]; } foreach ($list as $v) { if (array_key_exists($v, $array)) { return $v; } } return null; }
php
{ "resource": "" }
q9412
ArrayHelper.unique
train
public static function unique($array) { $suitable = true; foreach ($array as $k => &$v) { if (is_array($v)) { $v = self::unique($v); } elseif (!is_int($k)) { $suitable = false; } } return $suitable ? self::uniqueFlat($array) : $array; }
php
{ "resource": "" }
q9413
ArrayHelper.uniqueFlat
train
public static function uniqueFlat($array) { $uniqs = []; $res = []; foreach ($array as $k => $v) { $uv = var_export($v, true); if (array_key_exists($uv, $uniqs)) { continue; } $uniqs[$uv] = 1; $res[$k] = $v; } return $res; }
php
{ "resource": "" }
q9414
Module.onBootstrap
train
public function onBootstrap(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); // Don't break console routes if ($e->getRequest() instanceof Request) { return; } //Add Domain Checker $onDispatchListener = $serviceManager->get( \RcmAdmin\EventListener\DispatchListener::class ); /** @var \Zend\EventManager\EventManager $eventManager */ $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach( MvcEvent::EVENT_DISPATCH, [ $onDispatchListener, 'getAdminPanel' ], 10001 ); }
php
{ "resource": "" }
q9415
RouteManager.group
train
public function group(array $attributes, callable $callback) { $this->groupAttributes = $attributes; $callback(); $this->groupAttributes = null; return $this; }
php
{ "resource": "" }
q9416
EmailGuard.supports
train
public function supports(Request $request) { $post = json_decode($request->getContent(), true); return !empty($post[self::EMAIL_FIELD]) && !empty($post[self::PASSWORD_FIELD]); }
php
{ "resource": "" }
q9417
EmailGuard.getCredentials
train
public function getCredentials(Request $request) { $post = json_decode($request->getContent(), true); return new CredentialEmailModel($post[self::EMAIL_FIELD], $post[self::PASSWORD_FIELD]); }
php
{ "resource": "" }
q9418
EmailGuard.checkCredentials
train
public function checkCredentials($credentials, UserInterface $user) { return $this->userPasswordEncoderFactory->isPasswordValid($user, $credentials->getPassword()); }
php
{ "resource": "" }
q9419
NotificationEventListener.onNotify
train
public function onNotify(NotificationEvent $event) { if (true === ($this->getSession() instanceof Session)) { $this->getSession()->getFlashBag()->add($event->getNotification()->getType(), $event->getNotification()->getContent()); } return $event; }
php
{ "resource": "" }
q9420
PluginInstance.setInstanceConfig
train
public function setInstanceConfig($instanceConfig) { $this->instanceConfig = json_encode($instanceConfig); if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception(json_last_error_msg()); } }
php
{ "resource": "" }
q9421
CacheFile.created
train
public function created(string $key) { $path = $this->path($key); return $this->files->exists($path) ? \Carbon\Carbon::createFromTimestamp( $this->files->lastModified($path) ) : null; }
php
{ "resource": "" }
q9422
CacheFile.expired
train
public function expired(string $key) { $path = $this->path($key); return $this->files->exists($path) ? \Carbon\Carbon::createFromTimestamp( substr($this->files->get($path), 0, 10) ) : null; }
php
{ "resource": "" }
q9423
ConfigureMenuListener.onMenuConfigure
train
public function onMenuConfigure(ConfigureMenuEvent $event) { if (!$this->permissionResolver->hasAccess('uicron', 'list')) { return; } $menu = $event->getMenu(); $cronsMenu = $menu->getChild(MainMenuBuilder::ITEM_ADMIN); $cronsMenu->addChild(self::ITEM_CRONS, ['route' => 'edgar.ezuicron.list']); }
php
{ "resource": "" }
q9424
AuthResponseService.createJsonAuthResponse
train
public function createJsonAuthResponse(BaseUser $user) { $responseModel = $this->createResponseAuthModel($user); $response = new JsonResponse($responseModel->getBody(), Response::HTTP_CREATED); return $this->setCookieForResponse($response, $responseModel); }
php
{ "resource": "" }
q9425
AuthResponseService.authenticateResponse
train
public function authenticateResponse(BaseUser $user, Response $response) { return $this->setCookieForResponse($response, $this->createResponseAuthModel($user)); }
php
{ "resource": "" }
q9426
AuthResponseService.setCookieForResponse
train
protected function setCookieForResponse(Response $response, ResponseAuthenticationModel $responseModel) { $response->headers->setCookie( new Cookie( self::AUTH_COOKIE, $responseModel->getAuthToken(), $responseModel->getTokenExpirationTimeStamp(), null, false, false ) ); return $response; }
php
{ "resource": "" }
q9427
AuthResponseService.createResponseAuthModel
train
protected function createResponseAuthModel(BaseUser $user) { $user = $this->userService->updateUserRefreshToken($user); $authTokenModel = $this->authTokenService->createAuthTokenModel($user); return new ResponseAuthenticationModel($user, $authTokenModel, $user->getAuthRefreshModel()); }
php
{ "resource": "" }
q9428
ModelSoftDeleting.doDelete
train
private function doDelete() { if (!$this->model->trashed()) { $this->model->delete(); event(new ModelSoftDelete($this)); return; } $this->model->forceDelete(); event(new ModelDelete($this)); }
php
{ "resource": "" }
q9429
ModelSoftDeleting.restore
train
public function restore($modelitemId) { event(new BeforeRestore($this)); $this->findOnlyTrashed($modelitemId); $this->beforeRestore(); $this->doRestore(); $this->afterRestore(); event(new AfterRestore($this)); }
php
{ "resource": "" }
q9430
CachingReflector.getClass
train
public function getClass($class) { $cacheKey = self::CACHE_KEY_CLASSES . strtolower($class); if (! $reflectionClass = $this->cache->fetch($cacheKey)) { $reflectionClass = new ReflectionClass($class); $this->cache->store($cacheKey, $reflectionClass); } return $reflectionClass; }
php
{ "resource": "" }
q9431
CachingReflector.getConstructorParams
train
public function getConstructorParams($class) { $cacheKey = self::CACHE_KEY_CTOR_PARAMS . strtolower($class); $reflectedConstructorParams = $this->cache->fetch($cacheKey); if (false !== $reflectedConstructorParams) { return $reflectedConstructorParams; } elseif ($reflectedConstructor = $this->getConstructor($class)) { $reflectedConstructorParams = $reflectedConstructor->getParameters(); } else { $reflectedConstructorParams = null; } $this->cache->store($cacheKey, $reflectedConstructorParams); return $reflectedConstructorParams; }
php
{ "resource": "" }
q9432
CachingReflector.getFunction
train
public function getFunction($functionName) { $lowFunc = strtolower($functionName); $cacheKey = self::CACHE_KEY_FUNCS . $lowFunc; $reflectedFunc = $this->cache->fetch($cacheKey); if (false === $reflectedFunc) { $reflectedFunc = new ReflectionFunction($functionName); $this->cache->store($cacheKey, $reflectedFunc); } return $reflectedFunc; }
php
{ "resource": "" }
q9433
CachingReflector.getMethod
train
public function getMethod($classNameOrInstance, $methodName) { $className = is_string($classNameOrInstance) ? $classNameOrInstance : get_class($classNameOrInstance); $cacheKey = self::CACHE_KEY_METHODS . strtolower($className) . '.' . strtolower($methodName); if (! $reflectedMethod = $this->cache->fetch($cacheKey)) { $reflectedMethod = new ReflectionMethod($className, $methodName); $this->cache->store($cacheKey, $reflectedMethod); } return $reflectedMethod; }
php
{ "resource": "" }
q9434
ImplementServices.getServiceConfig
train
private function getServiceConfig(string $name) { $config = $this->services()[$name] ?? null; if ($config === null) { return null; } if (\is_string($config)) { return [ 'class' => $config, ]; } if (\is_array($config) && array_key_exists('class', $config)) { return $config; } throw new InvalidConfigException('Config must be either type of string (class name) or array (with `class` element'); }
php
{ "resource": "" }
q9435
ApiAdminManageSitesController.create
train
public function create($data) { /* ACCESS CHECK */ if (!$this->isAllowed(ResourceName::RESOURCE_SITES, 'admin')) { $this->getResponse()->setStatusCode(Response::STATUS_CODE_401); return $this->getResponse(); } /* */ $inputFilter = new SiteInputFilter(); $inputFilter->setData($data); if (!$inputFilter->isValid()) { return new ApiJsonModel( [], 1, 'Some values are missing or invalid.', $inputFilter->getMessages() ); } $data = $inputFilter->getValues(); $siteManager = $this->getSiteManager(); $userId = $this->getCurrentUserId(); $data = $siteManager->prepareSiteData($data); /** @var \Rcm\Repository\Domain $domainRepo */ $domainRepo = $this->getEntityManager()->getRepository( \Rcm\Entity\Domain::class ); $data['domain'] = $domainRepo->createDomain( $data['domainName'], $userId, 'Create new domain in ' . get_class($this) ); /** @var \Rcm\Entity\Site $newSite */ $newSite = new Site( $userId, 'Create new site in ' . get_class($this) ); $newSite->populate($data); // make sure we don't have a siteId $newSite->setSiteId(null); $newSite = $siteManager->createSite($newSite); return new ApiJsonModel($newSite, 0, 'Success'); }
php
{ "resource": "" }
q9436
PhantomJSHelper.getCommand
train
public function getCommand() { // Initialize the command. $command = $this->getBinaryPath(); $command .= true === OSHelper::isWindows() ? ".exe" : ""; // Return the command. return realpath($command); }
php
{ "resource": "" }
q9437
ContentProvider.getContent
train
public function getContent(string $namespace, string $locale, string $name): string { $nKey = self::getNKey($namespace, $locale); // L1 read $content = $this->loadedData[$nKey][$name] ?? false; if (is_string($content)) { // L1 hit return $content; } // L2 read + L1 write $this->loadedData[$nKey] = $this->loadedData[$nKey] ?? $this->loadNspaceFromCache($namespace, $locale); $fallbackLocale = $this->config['fallback'] ?? ''; $content = $this->loadedData[$nKey][$name] ?? false; if (is_string($content)) { return $content; } if ($fallbackLocale === false || $locale === $fallbackLocale) { return ''; } return $this->getContent($namespace, $fallbackLocale, $name); }
php
{ "resource": "" }
q9438
ControllerReflector.getReflectionMethod
train
public function getReflectionMethod(string $controller) { $callable = $this->getClassAndMethod($controller); if (null === $callable) { return null; } list($class, $method) = $callable; try { return new \ReflectionMethod($class, $method); } catch (\ReflectionException $e) { // In case we can't reflect the controller, we just // ignore the route } }
php
{ "resource": "" }
q9439
AbstractDependencyHandler.maybe_enqueue
train
public function maybe_enqueue( $handle ) { if ( $this->is_registered( $handle ) ) { $enqueue = $this->get_enqueue_function(); $enqueue( $handle ); return true; } return false; }
php
{ "resource": "" }
q9440
ClassFactory.createWithConstructorParams
train
public function createWithConstructorParams(array $params, $config = []) { $definition = $this->prepareObjectDefinitionFromConfig($config); return $this->getContainer()->create($definition, $params); }
php
{ "resource": "" }
q9441
LayoutManager.getThemesConfig
train
public function getThemesConfig() { if (empty($this->config['Rcm']) || empty($this->config['Rcm']['themes']) ) { throw new RuntimeException( 'No Themes found defined in configuration. Please report the issue with the themes author.' ); } return $this->config['Rcm']['themes']; }
php
{ "resource": "" }
q9442
LayoutManager.getThemeConfig
train
public function getThemeConfig($theme) { $themesConfig = $this->getThemesConfig(); if (!empty($themesConfig[$theme])) { return $themesConfig[$theme]; } elseif (!empty($themesConfig['generic'])) { return $themesConfig['generic']; } throw new RuntimeException( 'No theme config found for ' . $theme . ' and no default theme found' ); }
php
{ "resource": "" }
q9443
LayoutManager.getSiteLayout
train
public function getSiteLayout(Site $site, $layout = null) { $themeLayoutConfig = $this->getSiteThemeLayoutsConfig($site->getTheme()); if (empty($layout)) { $layout = $site->getSiteLayout(); } if (!empty($themeLayoutConfig[$layout]) && !empty($themeLayoutConfig[$layout]['file']) ) { return $themeLayoutConfig[$layout]['file']; } elseif (!empty($themeLayoutConfig['default']) && !empty($themeLayoutConfig['default']['file']) ) { return $themeLayoutConfig['default']['file']; } throw new RuntimeException('No Layouts Found in config'); }
php
{ "resource": "" }
q9444
LayoutManager.getSitePageTemplateConfig
train
public function getSitePageTemplateConfig(Site $site, $template = null) { $themePageConfig = $this->getSiteThemePagesTemplateConfig($site); if (!empty($themePageConfig[$template])) { return $themePageConfig[$template]; } elseif (!empty($themePageConfig['default'])) { return $themePageConfig['default']; } throw new RuntimeException('No Page Template Found in config'); }
php
{ "resource": "" }
q9445
LayoutManager.getSitePageTemplate
train
public function getSitePageTemplate(Site $site, $template = null) { $themePageConfig = $this->getSitePageTemplateConfig($site, $template); if (empty($themePageConfig['file'])) { throw new RuntimeException('No Page Template Found in config'); } return $themePageConfig['file']; }
php
{ "resource": "" }
q9446
LayoutManager.isLayoutValid
train
public function isLayoutValid(Site $site, $layoutKey) { $themesConfig = $this->getSiteThemeLayoutsConfig($site->getTheme()); if (!empty($themesConfig[$layoutKey])) { return true; } return false; }
php
{ "resource": "" }
q9447
ResourceEntityCollection.canAdd
train
public function canAdd(ResourceEntityInterface $entity) { return empty($this->className) || get_class($entity) == $this->className; }
php
{ "resource": "" }
q9448
RendererTwigExtension.coreScriptFilter
train
public function coreScriptFilter($content) { $attributes = []; $attributes["type"] = "text/javascript"; $innerHTML = null !== $content ? implode("", ["\n", $content, "\n"]) : ""; return static::coreHTMLElement("script", $innerHTML, $attributes); }
php
{ "resource": "" }
q9449
FileUploader.setDestinationDirectory
train
final public function setDestinationDirectory(string $destinationDirectory) { if ($destinationDirectory[strlen($destinationDirectory) - 1] != DIRECTORY_SEPARATOR) { $destinationDirectory .= DIRECTORY_SEPARATOR; } $this->destinationDirectory = $destinationDirectory; }
php
{ "resource": "" }
q9450
FileUploader.setDestinationFilename
train
final public function setDestinationFilename(string $filename) { $extension = pathinfo($filename, PATHINFO_EXTENSION); if (empty($extension) && !empty($this->uploadFile->getExtension())) { $filename .= '.' . $this->uploadFile->getExtension(); } $this->destinationFilename = $filename; }
php
{ "resource": "" }
q9451
BinaryBuffer.receiveHeader
train
protected function receiveHeader() { if(strlen($this->bufferData) > 8) { $header = substr($this->bufferData,0,8); $this->waitingFor = intval($header); $this->bufferData = substr($this->bufferData,8); $this->headerReceived = true; return strlen($this->bufferData) > 0; } return false; }
php
{ "resource": "" }
q9452
BinaryBuffer.receiveBody
train
protected function receiveBody() { if(strlen($this->bufferData) >= $this->waitingFor) { $this->messages[] = substr($this->bufferData,0,$this->waitingFor); $this->bufferData = substr($this->bufferData,$this->waitingFor); $this->headerReceived = false; return strlen($this->bufferData) > 0; } return false; }
php
{ "resource": "" }
q9453
BinaryBuffer.encodeMessage
train
public static function encodeMessage($message) { $waitingData = strlen($message); $header = str_pad((string)$waitingData,8,'0',STR_PAD_LEFT); return $header.$message; }
php
{ "resource": "" }
q9454
FOSUserBreadcrumbNodes.getFontAwesomeBreadcrumbNodes
train
public static function getFontAwesomeBreadcrumbNodes() { $breadcrumbNodes = []; $breadcrumbNodes[] = new BreadcrumbNode("label.edit_profile", "fa:user", "fos_user_profile_edit", NavigationInterface::NAVIGATION_MATCHER_ROUTER); $breadcrumbNodes[] = new BreadcrumbNode("label.show_profile", "fa:user", "fos_user_profile_show", NavigationInterface::NAVIGATION_MATCHER_ROUTER); $breadcrumbNodes[] = new BreadcrumbNode("label.change_password", "fa:lock", "fos_user_change_password", NavigationInterface::NAVIGATION_MATCHER_ROUTER); return $breadcrumbNodes; }
php
{ "resource": "" }
q9455
FOSUserBreadcrumbNodes.getMaterialDesignIconicFontBreadcrumbNodes
train
public static function getMaterialDesignIconicFontBreadcrumbNodes() { $breadcrumbNodes = []; $breadcrumbNodes[] = new BreadcrumbNode("label.edit_profile", "zmdi:account", "fos_user_profile_edit", NavigationInterface::NAVIGATION_MATCHER_ROUTER); $breadcrumbNodes[] = new BreadcrumbNode("label.show_profile", "zmdi:account", "fos_user_profile_show", NavigationInterface::NAVIGATION_MATCHER_ROUTER); $breadcrumbNodes[] = new BreadcrumbNode("label.change_password", "zmdi:lock", "fos_user_change_password", NavigationInterface::NAVIGATION_MATCHER_ROUTER); return $breadcrumbNodes; }
php
{ "resource": "" }
q9456
PageInfo.scriptVariables
train
public function scriptVariables() { $data = json_encode([ 'locale' => $this->get('locale'), 'app_name' => $this->get('app_name'), 'app_skin' => $this->get('app_skin'), 'app_theme' => $this->get('app_theme'), 'app_url' => $this->get('app_url'), ]); if (JSON_ERROR_NONE !== json_last_error()) { throw new \RuntimeException(json_last_error_msg()); } return $data; }
php
{ "resource": "" }
q9457
AbstractTwigExtension.coreHTMLElement
train
public static function coreHTMLElement($element, $content, array $attrs = []) { $template = "<%element%%attributes%>%innerHTML%</%element%>"; $attributes = trim(StringHelper::parseArray($attrs)); if (0 < strlen($attributes)) { $attributes = " " . $attributes; } $innerHTML = null !== $content ? trim($content, " ") : ""; return StringHelper::replace($template, ["%element%", "%attributes%", "%innerHTML%"], [trim($element), $attributes, $innerHTML]); }
php
{ "resource": "" }
q9458
TimerHelper.start
train
public static function start($alias) { if (isset(self::$timers[$alias])) { throw new \RuntimeException('Timer has already been started.'); } self::$timers[$alias] = microtime(); }
php
{ "resource": "" }
q9459
TimerHelper.getDifference
train
public static function getDifference($alias) { if (!isset(self::$timers[$alias])) { throw new \RuntimeException('Timer has not been started'); } return microtime() - self::$timers[$alias]; }
php
{ "resource": "" }
q9460
FileObserver.originalPath
train
protected function originalPath(File $file, string $thumbSize = null) { return $file->getOriginal('type') .DS.$file->getOriginal('category') .($thumbSize ? DS.$thumbSize : '') .DS.$file->getOriginal('name').'.'.$file->getOriginal('extension'); }
php
{ "resource": "" }
q9461
DateTimeRenderer.renderAge
train
public static function renderAge(DateTime $birthDate, DateTime $refDate = null) { // Use the current date/time. if (null === $refDate) { $refDate = new DateTime(); } $diff = $refDate->getTimestamp() - $birthDate->getTimestamp(); $years = new DateTime("@" . $diff); return intval($years->format("Y")) - 1970; }
php
{ "resource": "" }
q9462
CacheForgetByKeys.cacheForgetByKeys
train
protected function cacheForgetByKeys($entity = null) { $keys = $this->keysToForgetCache; if (is_array($keys) and array_diff_key($keys, array_keys(array_keys($keys)))) { foreach ($keys as $key => $method) { cache()->forget($key); if (is_subclass_of($entity, ParentModel::class)) { if (method_exists($model = $entity->getModel(), $method)) { $model->$method(); } } } } }
php
{ "resource": "" }
q9463
Site.setDomain
train
public function setDomain(Domain $domain) { $this->domain = $domain; $this->domainId = $domain->getDomainId(); }
php
{ "resource": "" }
q9464
Site.setLanguage
train
public function setLanguage(Language $language) { $this->language = $language; $this->languageId = $language->getLanguageId(); }
php
{ "resource": "" }
q9465
Site.getContainer
train
public function getContainer($name) { $container = $this->containers->get($name); if (empty($container)) { return null; } return $container; }
php
{ "resource": "" }
q9466
PhpDocFullyQualifiedParamHintFixer.getMatches
train
private function getMatches($line, $matchCommentOnly = false) { if (preg_match($this->regex, $line, $matches)) { if (!empty($matches['tag2'])) { $matches['tag'] = $matches['tag2']; $matches['hint'] = $matches['hint2']; } return $matches; } if ($matchCommentOnly && preg_match($this->regexCommentLine, $line, $matches)) { $matches['tag'] = null; $matches['var'] = ''; $matches['hint'] = ''; return $matches; } }
php
{ "resource": "" }
q9467
Page.getPageByName
train
public function getPageByName( SiteEntity $site, $pageName, $pageType = PageTypes::NORMAL ) { $results = $this->getPagesByName( $site, $pageName, $pageType ); if (empty($results)) { return null; } return $results[0]; }
php
{ "resource": "" }
q9468
Page.getPublishedRevisionId
train
public function getPublishedRevisionId($siteId, $name, $type = PageTypes::NORMAL) { /** @var \Doctrine\ORM\QueryBuilder $queryBuilder */ $queryBuilder = $this->_em->createQueryBuilder(); $queryBuilder->select('publishedRevision.revisionId') ->from(\Rcm\Entity\Page::class, 'page') ->join('page.publishedRevision', 'publishedRevision') ->join('page.site', 'site') ->where('site.siteId = :siteId') ->andWhere('page.name = :pageName') ->andWhere('page.pageType = :pageType') ->setParameter('siteId', $siteId) ->setParameter('pageName', $name) ->setParameter('pageType', $type); try { return $queryBuilder->getQuery()->getSingleScalarResult(); } catch (NoResultException $e) { return null; } }
php
{ "resource": "" }
q9469
Page.getAllPageIdsAndNamesBySiteThenType
train
public function getAllPageIdsAndNamesBySiteThenType($siteId, $type) { $queryBuilder = $this->_em->createQueryBuilder(); $queryBuilder->select('page.name, page.pageId') ->from(\Rcm\Entity\Page::class, 'page') ->join('page.site', 'site') ->where('page.pageType = :pageType') ->andWhere('site.siteId = :siteId') ->setParameter('pageType', $type) ->setParameter('siteId', $siteId); $result = $queryBuilder->getQuery()->getArrayResult(); if (empty($result)) { return null; } $return = []; foreach ($result as &$page) { $return[$page['pageId']] = $page['name']; } return $return; }
php
{ "resource": "" }
q9470
Page.setPageDeleted
train
public function setPageDeleted( PageEntity $page, string $modifiedByUserId, string $modifiedReason = Tracking::UNKNOWN_REASON ) { $pageType = $page->getPageType(); if (strpos($pageType, self::PAGE_TYPE_DELETED) !== false) { return;//This page is already deleted so we don't need to do anything further } $page->setPageType(self::PAGE_TYPE_DELETED . $pageType); $page->setModifiedByUserId( $modifiedByUserId, $modifiedReason ); $this->_em->persist($page); $this->_em->flush($page); }
php
{ "resource": "" }
q9471
Page.copyPage
train
public function copyPage( SiteEntity $destinationSite, PageEntity $pageToCopy, $pageData, $pageRevisionId = null, $publishNewPage = false, $doFlush = true ) { if (empty($pageData['name'])) { throw new InvalidArgumentException( 'Missing needed information (name) to create page copy.' ); } if (empty($pageData['createdByUserId'])) { throw new InvalidArgumentException( 'Missing needed information (createdByUserId) to create page copy.' ); } if (empty($pageData['createdReason'])) { $pageData['createdReason'] = 'Copy page in ' . get_class($this); } if (empty($pageData['author'])) { throw new InvalidArgumentException( 'Missing needed information (author) to create page copy.' ); } // Values cannot be changed unset($pageData['pageId']); unset($pageData['createdDate']); unset($pageData['lastPublished']); $pageData['site'] = $destinationSite; $clonedPage = $pageToCopy->newInstance( $pageData['createdByUserId'], $pageData['createdReason'] ); $clonedPage->populate($pageData); $this->assertCanCreateSitePage( $clonedPage->getSite(), $clonedPage->getName(), $clonedPage->getPageType() ); $revisionToUse = $clonedPage->getStagedRevision(); if (!empty($pageRevisionId)) { $sourceRevision = $pageToCopy->getRevisionById($pageRevisionId); if (empty($sourceRevision)) { throw new PageNotFoundException( 'Page revision not found.' ); } $revisionToUse = $sourceRevision->newInstance( $pageData['createdByUserId'], $pageData['createdReason'] ); $clonedPage->setRevisions([]); $clonedPage->addRevision($revisionToUse); } if (empty($revisionToUse)) { throw new RuntimeException( 'Page revision not found.' ); } if ($publishNewPage) { $clonedPage->setPublishedRevision($revisionToUse); } else { $clonedPage->setStagedRevision($revisionToUse); } $destinationSite->addPage($clonedPage); $this->_em->persist($clonedPage); if ($doFlush) { $this->_em->flush($clonedPage); } return $clonedPage; }
php
{ "resource": "" }
q9472
Page.publishPageRevision
train
public function publishPageRevision( $siteId, $pageName, $pageType, $revisionId, string $modifiedByUserId, string $modifiedReason = Tracking::UNKNOWN_REASON ) { //Query is needed to ensure revision belongs to the page in question $pageQueryBuilder = $this->_em->createQueryBuilder(); $pageQueryBuilder->select('page, revision') ->from(\Rcm\Entity\Page::class, 'page') ->join('page.revisions', 'revision') ->where('page.name = :pageName') ->andWhere('page.pageType = :pageType') ->andWhere('page.site = :siteId') ->andWhere('revision.revisionId = :revisionId') ->setParameter('pageName', $pageName) ->setParameter('pageType', $pageType) ->setParameter('siteId', $siteId) ->setParameter('revisionId', $revisionId); try { /** @var \Rcm\Entity\Page $page */ $page = $pageQueryBuilder->getQuery()->getSingleResult(); } catch (NoResultException $e) { throw new PageNotFoundException( 'Unable to locate page by revision. ' . json_encode([ 'revisionId' => $revisionId, 'siteId' => $siteId, 'pageName' => $pageName, 'pageType' => $pageType, ]) ); } $revision = $page->getRevisionById($revisionId); if (empty($revision)) { throw new RuntimeException( 'Revision not found. ' . json_encode([ 'revisionId' => $revisionId, 'pageId' => $page->getPageId() ]) ); } $page->setPublishedRevision($revision); $page->setModifiedByUserId( $modifiedByUserId, $modifiedReason ); $revision->setModifiedByUserId( $modifiedByUserId, $modifiedReason ); $this->_em->flush( [ $revision, $page ] ); return $page; }
php
{ "resource": "" }
q9473
Page.getSitePage
train
public function getSitePage( SiteEntity $site, $pageId ) { try { /** @var \Rcm\Entity\Page $page */ $page = $this->findOneBy( [ 'site' => $site, 'pageId' => $pageId ] ); } catch (\Exception $e) { $page = null; } return $page; }
php
{ "resource": "" }
q9474
Page.sitePageExists
train
public function sitePageExists( SiteEntity $site, $pageName, $pageType ) { try { $page = $this->getPageByName( $site, $pageName, $pageType ); } catch (\Exception $e) { $page = null; } return !empty($page); }
php
{ "resource": "" }
q9475
MainLayout.isValid
train
public function isValid($value) { $this->setValue($value); if (!$this->layoutManager->isLayoutValid($this->currentSite, $value)) { $this->error(self::MAIN_LAYOUT); return false; } return true; }
php
{ "resource": "" }
q9476
PluginManager.getPluginViewData
train
public function getPluginViewData( $pluginName, $pluginInstanceId, $forcedAlternativeInstanceConfig = null ) { $request = ServerRequestFactory::fromGlobals(); $blockConfig = $this->blockConfigRepository->findById($pluginName); if ($pluginInstanceId < 0) { $instanceWithData = new InstanceWithDataBasic( $pluginInstanceId, $pluginName, $blockConfig->getDefaultConfig(), null //@TODO run the dataprovider here instead of returning null ); } else { $instanceWithData = $this->instanceWithDataService->__invoke($pluginInstanceId, $request); } if ($forcedAlternativeInstanceConfig !== null) { $instanceWithData = new InstanceWithDataBasic( $instanceWithData->getId(), $instanceWithData->getName(), $forcedAlternativeInstanceConfig, //@TODO we should have got the data from the data provider with the forced instance config as an input $instanceWithData->getData() ); } $html = $this->blockRendererService->__invoke($instanceWithData); /** * @var $blockConfig Config */ $return = [ 'html' => $html, 'css' => [], 'js' => [], 'editJs' => '', 'editCss' => '', 'displayName' => $blockConfig->getLabel(), 'tooltip' => $blockConfig->getDescription(), 'icon' => $blockConfig->getIcon(), 'siteWide' => false, // @deprecated <deprecated-site-wide-plugin> 'md5' => '', 'fromCache' => false, 'canCache' => $blockConfig->getCache(), 'pluginName' => $blockConfig->getName(), 'pluginInstanceId' => $pluginInstanceId, ]; return $return; }
php
{ "resource": "" }
q9477
PluginManager.getDefaultInstanceConfig
train
public function getDefaultInstanceConfig($pluginName) { $blockConfig = $this->blockConfigRepository->findById($pluginName); if (empty($blockConfig)) { throw new \Exception('Block config not found for ' . $pluginName); //@TODO throw custom exception class } return $blockConfig->getDefaultConfig(); }
php
{ "resource": "" }
q9478
PluginManager.listAvailablePluginsByType
train
public function listAvailablePluginsByType() { $list = []; foreach ($this->config['rcmPlugin'] as $name => $data) { $displayName = $name; $type = 'Misc'; $icon = $this->config['Rcm']['defaultPluginIcon']; if (isset($data['type'])) { $type = $data['type']; } if (isset($data['display'])) { $displayName = $data['display']; } if (isset($data['icon']) && !empty($data['icon'])) { $icon = $data['icon']; } $list[$type][$name] = [ 'name' => $name, 'displayName' => $displayName, 'icon' => $icon, 'siteWide' => false // @deprecated <deprecated-site-wide-plugin> ]; } return $list; }
php
{ "resource": "" }
q9479
GoogleProvider.loadUserByUsername
train
public function loadUserByUsername($username) { try { $payload = $this->googleClient->verifyIdToken($username); $email = $payload['email']; $googleUserId = $payload['sub']; $user = $this->userService->findByGoogleUserId($googleUserId); if (!empty($user)) { return $user; } $user = $this->userService->findUserByEmail($email); // This means that the user is registering for the first time if (!empty($user)) { $this->updateUserWithGoogleUserId($user, $googleUserId); return $user; } return $this->registerUser($email, $googleUserId); } catch (\LogicException $ex) { throw new UsernameNotFoundException("Google AuthToken Did Not validate, ERROR MESSAGE " . $ex->getMessage(), ProgrammerException::GOOGLE_USER_PROVIDER_LOGIC_EXCEPTION); } catch (\Exception $ex) { throw new UsernameNotFoundException("Google AuthToken Did Not validate, ERROR MESSAGE " . $ex->getMessage(), ProgrammerException::GOOGLE_USER_PROVIDER_EXCEPTION); } }
php
{ "resource": "" }
q9480
GoogleProvider.updateUserWithGoogleUserId
train
protected function updateUserWithGoogleUserId(BaseUser $user, $googleUserId) { $user->setGoogleUserId($googleUserId); $this->userService->save($user); }
php
{ "resource": "" }
q9481
Journey.setUrl
train
public function setUrl($url): self { if (\is_string($url)) { $this->options['url'] = $url; return $this; } if ($url instanceof Leg) { $this->setUrlFromLeg($url); return $this; } if ($url instanceof BoardData) { $this->setUrlFromBoardData($url); return $this; } throw new \InvalidArgumentException( sprintf('setUrl must be a string, Leg or BoardData object') ); }
php
{ "resource": "" }
q9482
CommentsController.massUpdate
train
public function massUpdate(CommentsRequest $request) { $this->authorize('otherUpdate', $this->model); $comments = $this->model->whereIn('id', $request->comments); $messages = []; switch ($request->mass_action) { case 'published': if (! $comments->update(['is_approved' => true])) { $messages[] = 'unable to published'; } break; case 'unpublished': if (! $comments->update(['is_approved' => false])) { $messages[] = 'unable to unpublished'; } break; case 'delete': if (! $comments->get()->each->delete()) { $messages[] = 'unable to delete'; } break; } $message = empty($messages) ? 'msg.complete' : 'msg.complete_but_null'; return $this->makeRedirect(true, 'admin.comments.index', $message); }
php
{ "resource": "" }
q9483
TimeMachine.find
train
public function find(string $id, array $headers = []) { $url = $this->url('time_machines/%s', $id); return $this->get($url, [], $headers); }
php
{ "resource": "" }
q9484
TimeMachine.startAfresh
train
public function startAfresh(string $id, array $data, array $headers = []) { $url = $this->url('time_machines/%s/start_afresh', $id); return $this->post($url, $data, $headers); }
php
{ "resource": "" }
q9485
TimeMachine.travelForward
train
public function travelForward(string $id, array $data, array $headers = []) { $url = $this->url('time_machines/%s/travel_forward', $id); return $this->post($url, $data, $headers); }
php
{ "resource": "" }
q9486
ContentSecurityPolicy.send
train
public function send() { $header = $this->buildCompleteHeader(); $reportOnly = ($this->reportOnly) ? "-Report-Only" : ""; header("Content-Security-Policy$reportOnly: " . $header); if ($this->compatible) { header("X-Content-Security-Policy$reportOnly: " . $header); } }
php
{ "resource": "" }
q9487
ContentSecurityPolicy.buildCompleteHeader
train
private function buildCompleteHeader(): string { $header = ""; foreach ($this->headers as $sourceType => $value) { $header .= $this->buildHeaderLine($sourceType, $value); } if (!empty($this->reportUri)) { $header .= 'report-uri ' . $this->reportUri . ';'; } return $header; }
php
{ "resource": "" }
q9488
ContentSecurityPolicy.buildHeaderLine
train
private function buildHeaderLine(string $name, array $sources): string { $header = ''; if (!empty($sources)) { $value = ""; foreach ($sources as $source) { if (!empty($value)) { $value .= ' '; } $value .= $source; } $header = ($name == "script-src" && !empty(self::$nonce)) ? "$name $value 'nonce-" . self::$nonce . "';" : "$name $value;"; } return $header; }
php
{ "resource": "" }
q9489
ApiAdminSitesCloneController.create
train
public function create($data) { /* ACCESS CHECK */ if (!$this->isAllowed(ResourceName::RESOURCE_SITES, 'admin')) { $this->getResponse()->setStatusCode(Response::STATUS_CODE_401); return $this->getResponse(); } /* */ $inputFilter = new SiteDuplicateInputFilter(); $inputFilter->setData($data); if (!$inputFilter->isValid()) { return new ApiJsonModel( [], 1, 'Some values are missing or invalid.', $inputFilter->getMessages() ); } $data = $inputFilter->getValues(); $siteManager = $this->getSiteManager(); try { $data = $siteManager->prepareSiteData($data); /** @var \Rcm\Repository\Domain $domainRepo */ $domainRepo = $this->getEntityManager()->getRepository( \Rcm\Entity\Domain::class ); $domain = $domainRepo->createDomain( $data['domainName'], $this->getCurrentUserId(), 'Create new domain in ' . get_class($this), null, true ); } catch (\Exception $e) { return new ApiJsonModel(null, 1, $e->getMessage()); } $entityManager = $this->getEntityManager(); /** @var \Rcm\Repository\Site $siteRepo */ $siteRepo = $entityManager->getRepository(\Rcm\Entity\Site::class); /** @var \Rcm\Entity\Site $existingSite */ $existingSite = $siteRepo->find($data['siteId']); if (empty($existingSite)) { return new ApiJsonModel(null, 1, "Site {$data['siteId']} not found."); } try { $copySite = $siteManager->copySiteAndPopulate( $existingSite, $domain, $data ); } catch (\Exception $exception) { // Remove domain if error occurs if ($entityManager->contains($domain)) { $entityManager->remove($domain); } throw $exception; } return new ApiJsonModel($copySite, 0, 'Success'); }
php
{ "resource": "" }
q9490
Route.compileRegex
train
protected function compileRegex($rule) { $regex = '^' . preg_replace_callback( '@\{[\w]+\??\}@', function ($matches) { $optional = false; $key = str_replace(['{', '}'], '', $matches[0]); if (substr($key, -1) == '?') { // Flag this token as optional. $optional = true; } if (isset($this->customFilters[$key])) { if (isset($this->defaultFilters[$this->customFilters[$key]])) { return '(' . $this->defaultFilters[$this->customFilters[$key]] . ')' . (($optional) ? '?' : ''); } else { if ( substr($this->customFilters[$key], 0, 1) == '{' && substr($this->customFilters[$key], -1) == '}' ) { throw new \RuntimeException( "The custom filter named \"{$key}\" references a non-existent builtin filter named \"{$this->customFilters[$key]}\"." ); } else { return '(' . $this->customFilters[$key] . ')' . (($optional) ? '?' : ''); } } } elseif (isset($this->defaultTokens[$key])) { return '(' . $this->defaultTokens[$key] . ')' . (($optional) ? '?' : ''); } else { return '(' . $this->defaultFilters['{default}'] . ')' . (($optional) ? '?' : ''); } }, $rule ) . '$'; // Fix slash delimeters in regards to optional handling. $regex = str_replace(['?/', '??'], ['?/?', '?'], $regex); return $regex; }
php
{ "resource": "" }
q9491
Route.process
train
public function process(Request $request) { $results = []; // Test hostname rule. if (isset($this->options['hostname'])) { $regex = $this->compileRegex($this->options['hostname']); $tokens = $this->compileTokens($this->options['hostname']); $hostnameResults = $this->compileResults($regex, $tokens, $request->getHttpHost()); if ($hostnameResults === false) { return false; } else { $results = array_merge($results, $hostnameResults); } } // Test the main url rule. $regex = $this->compileRegex($this->rule); $tokens = $this->compileTokens($this->rule); $urlResults = $this->compileResults($regex, $tokens, $request->getRequestUri()); if ($urlResults === false) { return false; } else { $results = array_merge($results, $urlResults); } if (isset($this->options['targets'])) { $results = array_merge($results, $this->options['targets']); } $this->payload = $results; return true; }
php
{ "resource": "" }
q9492
SecuritySession.start
train
public function start(): bool { if (!is_null($this->expiration)) { $this->expiration->start(); } if (!is_null($this->fingerprint)) { $this->fingerprint->start(); } if (!isset($_SESSION['__HANDLER_INITIATED'])) { return $this->initialSessionStart(); } else { return $this->laterSessionStart(); } }
php
{ "resource": "" }
q9493
SecuritySession.laterSessionStart
train
private function laterSessionStart() { if (!is_null($this->fingerprint) && !$this->fingerprint->hasValidFingerprint()) { throw new \Exception("Session fingerprint doesn't match"); // @codeCoverageIgnore } if (!is_null($this->expiration) && $this->expiration->isObsolete()) { return true; } return false; }
php
{ "resource": "" }
q9494
StringHelper.hideEmail
train
public static function hideEmail($email) { $character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; $key = str_shuffle($character_set); $cipher_text = ''; $id = 'e'.rand(1,999999999); for ($i=0;$i<strlen($email);$i+=1) $cipher_text.= $key[strpos($character_set,$email[$i])]; $script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";'; $script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));'; $script.= 'document.getElementById("'.$id.'").innerHTML="<a href=\\"mailto:"+d+"\\">"+d+"</a>"'; $script = "eval(\"".str_replace(["\\",'"'],["\\\\",'\"'], $script)."\")"; $script = '<script type="text/javascript">/*<![CDATA[*/'.$script.'/*]]>*/</script>'; return '<span id="'.$id.'">[javascript protected email address]</span>'.$script; }
php
{ "resource": "" }
q9495
StringHelper.summary
train
public static function summary($str, $limit=100, $strip = false) { $str = ($strip == true) ? strip_tags($str) : $str; return static::truncate($str, $limit - 3, '...'); }
php
{ "resource": "" }
q9496
ModelQuerying.find
train
public function find($modelitemId) { $this->model = $this->model->findOrFail($modelitemId); return $this->model; }
php
{ "resource": "" }
q9497
ModelQuerying.query
train
private function query($count) { $this->applyQueryFilters(); if ($this->hasTranslating()) { $this->applyTranslationFilter(); } if ($this->orderBy()) { $this->query = $this->query->orderBy( $this->orderBy(), $this->sortBy() ); } if ($count) { return $this->query->count(); } if ($this->perPage > 0) { return $this->query->paginate($this->perPage); } return $this->query->get(); }
php
{ "resource": "" }
q9498
ModelQuerying.totals
train
public function totals() { if ($this->hasSoftDeleting()) { return [ 'all' => $this->items($count = true), 'with_trashed' => $this->allItems($count = true), 'only_trashed' => $this->onlyTrashedItems($count = true), ]; } return ['all' => $this->items($count = true)]; }
php
{ "resource": "" }
q9499
ModelQuerying.orderBy
train
public function orderBy() { if (Request::input('order')) { return Request::input('order'); } if ($this->orderBy) { return $this->orderBy; } return $this->model->getKeyName(); }
php
{ "resource": "" }