_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9300 | ContainerAbstract.setRevisions | train | public function setRevisions(array $revisions)
{
$this->revisions = new ArrayCollection();
/** @var \Rcm\Entity\Revision $revision */
foreach ($revisions as $revision) {
if (!$revision instanceof Revision) {
throw new InvalidArgumentException(
"Invalid Revision passed in. Unable to set array"
);
}
$this->revisions->set($revision->getRevisionId(), $revision);
}
} | php | {
"resource": ""
} |
q9301 | ContainerAbstract.getLastSavedDraftRevision | train | public function getLastSavedDraftRevision()
{
if (!empty($this->lastSavedDraft)) {
return $this->lastSavedDraft;
}
$published = $this->publishedRevision;
$staged = $this->stagedRevision;
$arrayCollection = $this->revisions->toArray();
/** @var \Rcm\Entity\Revision $revision */
$revision = end($arrayCollection);
if (empty($revision)) {
return null;
}
$found = false;
while (!$found) {
if (empty($revision)) {
break;
} elseif (!empty($published)
&& $published->getRevisionId() == $revision->getRevisionId()
) {
$found = false;
} elseif (!empty($staged)
&& $staged->getRevisionId() == $revision->getRevisionId()
) {
$found = false;
} elseif ($revision->wasPublished()) {
$found = false;
} else {
$found = true;
}
if (!$found) {
$revision = prev($arrayCollection);
}
}
return $this->lastSavedDraft = $revision;
} | php | {
"resource": ""
} |
q9302 | ContainerAbstract.getRevisionById | train | public function getRevisionById($revisionId)
{
$revision = $this->revisions->get($revisionId);
if ($revision !== null) {
return $revision; //We get here when rendering an unpublished page version
}
foreach ($this->revisions as $revision) {
if ($revision->getRevisionId() === $revisionId) {
return $revision; //We get here when publishing a new page version
}
}
return null;
} | php | {
"resource": ""
} |
q9303 | IntrusionDetection.run | train | public function run()
{
$guard = $this->getMonitoringInputs();
if (empty($guard)) {
throw new \RuntimeException("Nothing to monitor ! Either configure the IDS to monitor at least one input or
completely deactivate this feature.");
}
$this->manager->run($guard);
if ($this->manager->getImpact() > 0) {
$data = $this->getDetectionData($this->manager->getReports());
throw new IntrusionDetectionException($data);
}
} | php | {
"resource": ""
} |
q9304 | IntrusionDetection.getMonitoringInputs | train | private function getMonitoringInputs(): array
{
$guard = [];
if ($this->surveillance & self::REQUEST) {
$guard['REQUEST'] = $_REQUEST;
}
if ($this->surveillance & self::GET) {
$guard['GET'] = $_GET;
}
if ($this->surveillance & self::POST) {
$guard['POST'] = $_POST;
}
if ($this->surveillance & self::COOKIE) {
$guard['COOKIE'] = $_COOKIE;
}
return $guard;
} | php | {
"resource": ""
} |
q9305 | IntrusionDetection.getDetectionData | train | private function getDetectionData($reports): array
{
$data = [
'impact' => 0,
'detections' => []
];
foreach ($reports as $report) {
$variableName = $report->getVarName();
$filters = $report->getFilterMatch();
if (!isset($data['detections'][$variableName])) {
$data['detections'][$variableName] = [
'value' => $report->getVarValue(),
'events' => []
];
}
foreach ($filters as $filter) {
$data['detections'][$variableName]['events'][] = [
'description' => $filter->getDescription(),
'impact' => $filter->getImpact()
];
$data['impact'] += $filter->getImpact();
}
}
return $data;
} | php | {
"resource": ""
} |
q9306 | SessionDecoy.throwDecoys | train | public function throwDecoys()
{
$params = session_get_cookie_params();
$len = strlen(session_id());
foreach ($this->decoys as $decoy) {
$value = Cryptography::randomString($len);
setcookie(
$decoy,
$value,
$params['lifetime'],
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
$_COOKIE[$decoy] = $value;
}
} | php | {
"resource": ""
} |
q9307 | SessionDecoy.addRandomDecoys | train | public function addRandomDecoys($count)
{
for ($i = 0; $i < $count; ++$i) {
$this->addDecoy(Cryptography::randomString(20));
}
} | php | {
"resource": ""
} |
q9308 | SessionDecoy.destroyDecoys | train | public function destroyDecoys()
{
foreach ($this->decoys as $decoy) {
setcookie($decoy, '', 1);
setcookie($decoy, false);
unset($_COOKIE[$decoy]);
}
} | php | {
"resource": ""
} |
q9309 | DefaultErrorHandler.OnUncaughtErrorTriggered | train | public function OnUncaughtErrorTriggered($errSeverity, $errMessage, $errFile, $errLine, array $errContext)
{
//@call
if (0 === error_reporting()) {
return false;
}
throw new PHPTriggerErrorException($errMessage, $errLine, $errFile, $errSeverity);
} | php | {
"resource": ""
} |
q9310 | DefaultErrorHandler.OnErrorMessageReachParent | train | public function OnErrorMessageReachParent($result)
{
if ($result instanceof SerializableException) {
if ($result instanceof SerializableFatalException) {
//Fatal exception should be handled separate
//This should be tracked on parent
throw new ThreadFatalException($result->getMessage() . PHP_EOL . PHP_EOL . $result->getTraceAsString(), $result->getCode());
}
//best is to log all the exception information here
//you can also inject the variables into normal exception using reflection
throw new \Exception($result->getMessage() . PHP_EOL . PHP_EOL . $result->getTraceAsString(), $result->getCode());
}
//if it is an error object created from another handler just return it.
//this only applies to usage of distinct ErrorHandlers
return $result;
} | php | {
"resource": ""
} |
q9311 | Admin.registerRoutes | train | public function registerRoutes(Router $router)
{
// We will need to throw an exception if a ModelAdmin manages a Model which conflicts with an internal flare endpoint
// such as (create, edit, view, delete etc)
$router->group(['prefix' => $this->urlPrefix(), 'namespace' => get_called_class(), 'as' => $this->urlPrefix()], function ($router) {
$this->registerSubRoutes();
$this->registerController($this->getController());
});
} | php | {
"resource": ""
} |
q9312 | Admin.registerSubRoutes | train | public function registerSubRoutes()
{
if (!is_array($this->subAdmin)) {
return;
}
foreach ($this->subAdmin as $adminItem) {
$this->registerRoute($adminItem->getController(), $adminItem->routeParameters());
}
} | php | {
"resource": ""
} |
q9313 | Admin.registerRoute | train | public static function registerRoute($controller, $parameters = [])
{
\Route::group($parameters, function ($controller) {
\Route::registerController($controller);
});
} | php | {
"resource": ""
} |
q9314 | Admin.getRequested | train | public static function getRequested($key = 'namespace')
{
if (!\Route::current()) {
return;
}
$currentAction = \Route::current()->getAction();
if (isset($currentAction[$key])) {
return $currentAction[$key];
}
return;
} | php | {
"resource": ""
} |
q9315 | Admin.getTitle | train | public function getTitle()
{
if (!isset($this->title) || !$this->title) {
return Str::title(str_replace('_', ' ', snake_case(preg_replace('/'.static::CLASS_SUFFIX.'$/', '', static::shortName()))));
}
return $this->title;
} | php | {
"resource": ""
} |
q9316 | Admin.getPluralTitle | train | public function getPluralTitle()
{
if (!isset($this->pluralTitle) || !$this->pluralTitle) {
return Str::plural($this->getTitle());
}
return $this->pluralTitle;
} | php | {
"resource": ""
} |
q9317 | Admin.urlPrefix | train | public function urlPrefix()
{
if (!isset($this->urlPrefix) || !$this->urlPrefix) {
return str_slug($this->getPluralTitle());
}
return $this->urlPrefix;
} | php | {
"resource": ""
} |
q9318 | Url.fromString | train | public static function fromString($url, Url $root = null)
{
$instance = new static();
$components = static::parseUrl($url);
foreach ($components as $component => $value) {
$method = 'set' . Inflector::camelize($component);
call_user_func(array($instance, $method), $value);
}
$instance->setOriginal($url);
$instance->setRoot($root);
return $instance;
} | php | {
"resource": ""
} |
q9319 | Url.toArray | train | public function toArray()
{
return array(
'scheme' => $this->scheme,
'host' => $this->host,
'port' => $this->port,
'user' => $this->user,
'pass' => $this->pass,
'path' => $this->path,
'query' => $this->query,
'fragment' => $this->fragment
);
} | php | {
"resource": ""
} |
q9320 | Url.toAbsoluteUrl | train | public function toAbsoluteUrl(Url $root = null)
{
$root = $this->getRoot() ?: $root;
if (!$root->isUrlAbsolute()) {
throw new \InvalidArgumentException();
}
if (!$this->isUrlAbsolute()) {
$this->setScheme($root->getScheme());
$this->setHost($root->getHost());
if (!$this->isPathAbsolute()) {
$path = $root->getPath();
$path = substr($path, 0, strrpos($path, '/') + 1);
$this->setPath($path . $this->getPath());
}
}
return $this;
} | php | {
"resource": ""
} |
q9321 | Logger.sendMessageToBrowser | train | public function sendMessageToBrowser($message)
{
if (!$this->outputStarted) {
ob_start();
echo '<!DOCTYPE html><html lang="en"><head></head><body>';
$this->outputStarted = true;
}
echo strip_tags($message, '<h1><p><br><hr>');
echo '<br />';
echo str_repeat(" ", 6024), "\n";
ob_flush();
flush();
} | php | {
"resource": ""
} |
q9322 | Util.getExceptionInfo | train | public static function getExceptionInfo(Throwable $t) : array
{
return [
'type' => get_class($t),
'message' => $t->getMessage(),
'code' => $t->getCode(),
'file' => $t->getFile(),
'line' => $t->getLine(),
'trace' => $t->getTraceAsString(),
];
} | php | {
"resource": ""
} |
q9323 | Util.throwIfNotType | train | public static function throwIfNotType(
array $typesToVariables,
bool $failOnWhitespace = false,
bool $allowNulls = false
) {
foreach ($typesToVariables as $type => $variablesOrVariable) {
self::handleTypesToVariables($failOnWhitespace, $allowNulls, $variablesOrVariable, $type);
}
} | php | {
"resource": ""
} |
q9324 | DataCollectionTrait.set | train | public function set($index, $value = null)
{
if (is_array($index)) {
$this->data = array_merge($this->data, $index);
} else {
$this->data[$index] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q9325 | DataCollectionTrait.get | train | public function get($index, $default = null)
{
if (isset($this->data[$index])) {
return $this->data[$index];
}
return $default;
} | php | {
"resource": ""
} |
q9326 | Client.setBody | train | public function setBody($body)
{
$body = json_encode($body);
if ($error = json_last_error()) {
throw new \ErrorException($error);
}
curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS, $body);
return $this;
} | php | {
"resource": ""
} |
q9327 | FromFileObservable.cut | train | public function cut(string $lineEnd = PHP_EOL): Observable
{
return $this->lift(function () use ($lineEnd) {
return new CutOperator($lineEnd);
});
} | php | {
"resource": ""
} |
q9328 | Flare.compatibility | train | public function compatibility()
{
if (strpos($this->app->version(), '5.1.') !== false && strpos($this->app->version(), '(LTS)') !== false) {
return 'LTS';
}
return 'Edge';
} | php | {
"resource": ""
} |
q9329 | Flare.registerHelper | train | public function registerHelper($helper, $class)
{
if (array_key_exists($helper, $this->helpers)) {
throw new Exception("Helper method `$helper` has already been defined");
}
$this->helpers[$helper] = $class;
} | php | {
"resource": ""
} |
q9330 | Flare.callHelperMethod | train | protected function callHelperMethod($method, $parameters)
{
return $this->app->make($this->helpers[$method], $parameters);
} | php | {
"resource": ""
} |
q9331 | DomainRedirectService.getPrimaryRedirectUrl | train | public function getPrimaryRedirectUrl(Site $site)
{
$currentDomain = $site->getDomain()->getDomainName();
$ipValidator = new Ip();
$isIp = $ipValidator->isValid($currentDomain);
if ($isIp) {
return null;
}
$primaryDomain = $site->getDomain()->getPrimary();
if (empty($primaryDomain)) {
return null;
}
if ($primaryDomain->getDomainName() == $currentDomain) {
return null;
}
return $primaryDomain->getDomainName();
} | php | {
"resource": ""
} |
q9332 | ChainEventAbstract.init | train | public function init(ChainManagerInterface $chainManager, array $params = [])
{
$this->in($chainManager->getAssetManager());
if ($chainManager->hasEvents()) {
$event = $chainManager->getNextEvent();
if (is_object($event)) {
$event->init($chainManager);
}
}
$this->out($chainManager->getAssetManager());
return $this;
} | php | {
"resource": ""
} |
q9333 | ImpersonationPolicy.canBeImpersonatedPolicy | train | public function canBeImpersonatedPolicy(Impersonatable $impersonater, Impersonatable $impersonated)
{
return $this->canImpersonatePolicy($impersonater) && $impersonated->canBeImpersonated();
} | php | {
"resource": ""
} |
q9334 | ApiAdminPageTypesController.getList | train | public function getList()
{
/** @var RcmUserService $rcmUserService */
$rcmUserService = $this->serviceLocator->get(RcmUserService::class);
//ACCESS CHECK
if (!$rcmUserService->isAllowed(
ResourceName::RESOURCE_SITES,
'admin'
)
) {
$this->getResponse()->setStatusCode(Response::STATUS_CODE_401);
return $this->getResponse();
}
$config = $this->getConfig();
$pageTypes = $config['Rcm']['pageTypes'];
return new ApiJsonModel($pageTypes, 0, 'Success');
} | php | {
"resource": ""
} |
q9335 | PageName.isValid | train | public function isValid($value)
{
$this->setValue($value);
$pattern = '/^[a-z0-9_\-]*[a-z0-9]$/i';
$this->pageNameOk = true;
if (!preg_match($pattern, $value)) {
$this->error(self::PAGE_NAME);
$this->pageNameOk = false;
}
return $this->pageNameOk;
} | php | {
"resource": ""
} |
q9336 | Session.getInstance | train | final public static function getInstance(?array $configurations = null): self
{
if (is_null(self::$instance)) {
self::$instance = new self($configurations);
}
return self::$instance;
} | php | {
"resource": ""
} |
q9337 | Session.has | train | public function has(string $key, $value = null): bool
{
return is_null($value)
? isset($_SESSION[$key])
: isset($_SESSION[$key]) && $_SESSION[$key] == $value;
} | php | {
"resource": ""
} |
q9338 | Session.remove | train | public function remove(string $key)
{
if (isset($_SESSION[$key])) {
$_SESSION[$key] = '';
unset($_SESSION[$key]);
}
} | php | {
"resource": ""
} |
q9339 | Session.initialize | train | private function initialize()
{
$this->name = (isset($this->configurations['name']))
? $this->configurations['name']
: self::DEFAULT_SESSION_NAME;
$this->assignSessionLifetime();
if (isset($this->configurations['encryption_enabled'])
&& $this->configurations['encryption_enabled']) {
$this->handler = new EncryptedSessionHandler();
}
$this->security = new SecuritySession($this->configurations);
} | php | {
"resource": ""
} |
q9340 | Session.assignSessionLifetime | train | private function assignSessionLifetime()
{
if (isset($this->configurations['lifetime'])) {
$lifetime = $this->configurations['lifetime'];
ini_set('session.gc_maxlifetime', $lifetime * 1.2);
session_set_cookie_params($lifetime);
}
} | php | {
"resource": ""
} |
q9341 | KernelEventListener.handleBadUserRoleException | train | protected function handleBadUserRoleException(GetResponseForExceptionEvent $event, BadUserRoleException $ex) {
if (null !== $ex->getRedirectUrl()) {
$event->setResponse(new RedirectResponse($ex->getRedirectUrl()));
}
return $event;
} | php | {
"resource": ""
} |
q9342 | KernelEventListener.handleRedirectResponseException | train | protected function handleRedirectResponseException(GetResponseForExceptionEvent $event, RedirectResponseException $ex) {
if (null !== $ex->getRedirectUrl()) {
$event->setResponse(new RedirectResponse($ex->getRedirectUrl()));
}
return $event;
} | php | {
"resource": ""
} |
q9343 | KernelEventListener.onKernelException | train | public function onKernelException(GetResponseForExceptionEvent $event) {
$ex = $event->getException();
// Handle the exception.
if (true === ($ex instanceof BadUserRoleException)) {
$this->handleBadUserRoleException($event, $ex);
}
if (true === ($ex instanceof RedirectResponseException)) {
$this->handleRedirectResponseException($event, $ex);
}
return $event;
} | php | {
"resource": ""
} |
q9344 | KernelEventListener.onKernelRequest | train | public function onKernelRequest(GetResponseEvent $event) {
$this->setRequest($event->getRequest());
// Register the theme providers.
$this->getThemeManager()->addGlobal();
return $event;
} | php | {
"resource": ""
} |
q9345 | RefreshTokenProvider.loadUserByUsername | train | public function loadUserByUsername($username)
{
$user = $this->userService->findUserByValidRefreshToken($username);
if (empty($user)) {
throw new UsernameNotFoundException('No user found with refresh token provided.');
}
// This adds time to the refresh token.
$this->userService->updateUserRefreshToken($user);
return $user;
} | php | {
"resource": ""
} |
q9346 | AdminNavigationFactory.shouldShowInNavigation | train | protected function shouldShowInNavigation(&$page)
{
if (isset($page['rcmOnly'])
&& $page['rcmOnly']
&& empty($this->page)
) {
return false;
}
if (isset($page['acl']) && is_array($page['acl'])
&& !empty($page['acl']['resource'])
) {
$privilege = null;
if (!empty($page['acl']['privilege'])) {
$privilege = $page['acl']['privilege'];
}
$resource = $page['acl']['resource'];
$resource = str_replace(
[
':siteId',
':pageName'
],
[
$this->currentSite->getSiteId(),
$this->page->getName()
],
$resource
);
if (!empty($this->page)) {
$resource = str_replace(
[
':siteId',
':pageName'
],
[
$this->currentSite->getSiteId(),
$this->page->getName()
],
$resource
);
} else {
$resource = str_replace(
[':siteId'],
[$this->currentSite->getSiteId()],
$resource
);
}
if (!$this->isAllowed->__invoke(
GetPsrRequest::invoke(),
$resource,
$privilege
)
) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q9347 | AdminNavigationFactory.updatePlaceHolders | train | protected function updatePlaceHolders(&$item, $key, $revisionNumber)
{
if (empty($this->page)) {
return;
}
$find = [
':rcmPageName',
':rcmPageType',
':rcmPageRevision'
];
$replace = [
$this->page->getName(),
$this->page->getPageType(),
$revisionNumber,
];
$item = str_replace($find, $replace, $item);
} | php | {
"resource": ""
} |
q9348 | Filterable.applyFilter | train | public function applyFilter(string $defaultSort = "", string $defaultOrder = "")
{
$this->filter = new Filter(RequestFactory::read(), $defaultSort, $defaultOrder);
} | php | {
"resource": ""
} |
q9349 | PageMutationService.createNewPage | train | public function createNewPage($user, int $siteId, string $name, string $pageType, $data)
{
if (empty($user)) {
throw new TrackingException('A valid user is required in ' . get_class($this));
}
$validatedData = $data;
$pageData = [
'name' => $name,
'siteId' => $siteId,
'pageTitle' => $validatedData['pageTitle'],
'pageType' => $pageType, // "n" means "normal"
'siteLayoutOverride' => (
isset($validatedData['siteLayoutOverride']) ? $validatedData['siteLayoutOverride'] : null
),
'createdByUserId' => $user->getId(),
'createdReason' => 'New page in ' . get_class($this),
'author' => $user->getName(),
];
$createdPage = $this->pageRepo->createPage(
$this->entityManager->find(Site::class, $siteId),
$pageData
);
$this->immuteblePageVersionRepo->createUnpublished(
new PageLocator(
$siteId,
$this->rcmPageNameToPathname->__invoke($createdPage->getName(), $createdPage->getPageType())
),
$this->immutablePageContentFactory->__invoke(
$createdPage->getPageTitle(),
$createdPage->getDescription(),
$createdPage->getKeywords(),
$this->revisionRepo->find($createdPage->getStagedRevision())->getPluginWrappers()->toArray()
),
$user->getId(),
__CLASS__ . '::' . __FUNCTION__
);
return $createdPage;
} | php | {
"resource": ""
} |
q9350 | PageMutationService.createNewPageFromTemplate | train | public function createNewPageFromTemplate($user, $data)
{
if (empty($user)) {
throw new TrackingException('A valid user is required in ' . get_class($this));
}
$validatedData = $data;
/** @var \Rcm\Entity\Page $page */
$page = $this->pageRepo->findOneBy(
[
'pageId' => $validatedData['page-template'],
'pageType' => 't'
]
);
if (empty($page)) {
throw new PageNotFoundException(
'No template found for page id: '
. $validatedData['page-template']
);
}
$pageData = [
'name' => $validatedData['name'],
'pageTitle' => $validatedData['pageTitle'],
'pageType' => 'n', // "n" means "normal"
'createdByUserId' => $user->getId(),
'createdReason' => 'New page from template in ' . get_class($this),
'author' => $user->getName(),
];
$createdPage = $resultRevisionId = $this->pageRepo->copyPage(
$this->currentSite,
$page,
$pageData
);
$this->immuteblePageVersionRepo->createUnpublished(
new PageLocator(
$this->currentSite->getSiteId(),
$this->rcmPageNameToPathname->__invoke($createdPage->getName(), $createdPage->getPageType())
),
$this->immutablePageContentFactory->__invoke(
$createdPage->getPageTitle(),
$createdPage->getDescription(),
$createdPage->getKeywords(),
$this->revisionRepo->find($resultRevisionId)->getPluginWrappers()->toArray()
),
$user->getId(),
__CLASS__ . '::' . __FUNCTION__
);
} | php | {
"resource": ""
} |
q9351 | PageMutationService.prepSaveData | train | protected function prepSaveData(&$data)
{
if (!is_array($data)) {
$data = [];
}
ksort($data);
$data['containers'] = [];
$data['pageContainer'] = [];
if (empty($data['plugins'])) {
throw new InvalidArgumentException(
'Save Data missing plugins .
Please make sure the data you\'re attempting to save is correctly formatted.
'
);
}
foreach ($data['plugins'] as &$plugin) {
$this->cleanSaveData($plugin['saveData']);
/* Patch for a Json Bug */
if (!empty($plugin['isSitewide'])
&& $plugin['isSitewide'] != 'false'
&& $plugin['isSitewide'] != '0'
) {
$plugin['isSitewide'] = 1;
} else {
$plugin['isSitewide'] = 0;
}
if (empty($plugin['sitewideName'])) {
$plugin['sitewideName'] = null;
}
$plugin['rank'] = (int)$plugin['rank'];
$plugin['rowNumber'] = (int)$plugin['rowNumber'];
$plugin['columnClass'] = (string)$plugin['columnClass'];
$plugin['containerName'] = $plugin['containerId'];
if ($plugin['containerType'] == 'layout') {
$data['containers'][$plugin['containerId']][] = &$plugin;
} else {
$data['pageContainer'][] = &$plugin;
}
}
} | php | {
"resource": ""
} |
q9352 | PageMutationService.cleanSaveData | train | protected function cleanSaveData(
&$data
) {
if (empty($data)) {
return;
}
if (is_array($data)) {
ksort($data);
foreach ($data as &$arrayData) {
$this->cleanSaveData($arrayData);
}
return;
}
if (is_string($data)) {
$data = trim(
str_replace(
[
"\n",
"\t",
"\r"
],
"",
$data
)
);
}
return;
} | php | {
"resource": ""
} |
q9353 | RouteServiceProvider.registerDefinedRoutes | train | protected function registerDefinedRoutes(Router $router)
{
$router->group(
[
'prefix' => \Flare::config('admin_url'),
'as' => 'flare::',
'middleware' => ['flare'],
],
function ($router) {
\Flare::admin()->registerRoutes($router);
$router->get('/', $this->adminController('getDashboard'))->name('dashboard');
}
);
} | php | {
"resource": ""
} |
q9354 | RouteServiceProvider.registerDefaultRoutes | train | protected function registerDefaultRoutes(Router $router)
{
$router->group(
[
'prefix' => \Flare::config('admin_url'),
'as' => 'flare::',
'middleware' => ['web', 'flarebase'],
],
function ($router) {
// Logout route...
$router->get('logout', $this->adminController('getLogout'))->name('logout');
if (\Flare::show('login')) {
// Login request reoutes...
$router->get('login', $this->adminController('getLogin'))->name('login');
$router->post('login', $this->adminController('postLogin'))->name('login');
// Password reset link request routes...
$router->get('email', $this->adminController('getEmail'))->name('email');
$router->post('email', $this->adminController('postEmail'))->name('email');
// Password reset routes...
$router->get('reset/{token}', $this->adminController('getReset'))->name('reset');
$router->post('reset', $this->adminController('postReset'))->name('reset');
}
}
);
} | php | {
"resource": ""
} |
q9355 | Setting.langUpdate | train | public function langUpdate()
{
$path = skin_path('lang'.DS.$this->module->name).DS.app_locale().'.json';
$data = file_exists($path) ? json_decode(file_get_contents($path), true) : [];
$data = array_filter(array_merge($data, [
$this->name => $this->title,
$this->name.'#descr' => $this->attributes['descr'],
'section.' . $this->section => request('section_lang', __('section.' . $this->section)),
'legend.' . $this->fieldset => request('legend_lang', __('legend.' . $this->fieldset)),
]));
ksort($data);
$data = json_encode($data, JSON_UNESCAPED_UNICODE);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \RuntimeException(sprintf(
'Translation file `%s` contains an invalid JSON structure.', $path
));
}
file_put_contents($path, $data);
return $this;
} | php | {
"resource": ""
} |
q9356 | Setting.generate_page | train | public static function generate_page(Module $module, string $action)
{
$settings = static::query()->where('module_name', $module->name)
->where('action', $action)->get()->makeFormFields();
return [
'module' => $module,
'sections' => $settings->pluck('section')->unique(),
'fieldsets' => $settings->pluck('fieldset')->unique(),
'fields' => $settings->groupBy(['section', 'fieldset']),
];
} | php | {
"resource": ""
} |
q9357 | AbstractNavigationNode.isDisplayable | train | public function isDisplayable() {
$displayable = $this->enable && $this->visible;
if (true === $displayable) {
return true;
}
foreach ($this->getNodes() as $current) {
if (false === ($current instanceof AbstractNavigationNode)) {
continue;
}
if (true === $current->isDisplayable()) {
return true;
}
}
return $displayable;
} | php | {
"resource": ""
} |
q9358 | WebsiteGuard.onAuthenticationFailure | train | public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$this->dispatcher->dispatch(self::WEBSItE_STATELESS_GUARD_AUTH_FAILED, new AuthFailedEvent($request, $exception));
return $this->removeAuthCookieFromResponse(new RedirectResponse($this->createLoginPath($request)));
} | php | {
"resource": ""
} |
q9359 | WebsiteGuard.start | train | public function start(Request $request, AuthenticationException $authException = null)
{
return new RedirectResponse($this->createLoginPath($request));
} | php | {
"resource": ""
} |
q9360 | WebsiteGuard.createLoginPath | train | protected function createLoginPath(Request $request)
{
$url = $this->loginPath;
$url .= $this->appendNextUrl($request) ? '?'. self::NEXT_URL_PARAMETER . '=' . $request->getPathInfo() : '';
return $url;
} | php | {
"resource": ""
} |
q9361 | WebsiteGuard.appendNextUrl | train | protected function appendNextUrl(Request $request)
{
return !empty($request->getPathInfo()) && strpos($request->getPathInfo(), $this->loginPath) == false;
} | php | {
"resource": ""
} |
q9362 | ModelTranslating.modelHasLanguage | train | public function modelHasLanguage($model, $key)
{
if ($this->isLanguage($key)) {
return true;
}
if ($model->translations->get($key)) {
return true;
}
return $this->model->language === $key;
} | php | {
"resource": ""
} |
q9363 | ModelTranslating.routeToViewModelTranslation | train | public function routeToViewModelTranslation($key, $model)
{
if ($translation = $model->translations->get($key)) {
return $this->currentUrl('view/'.$translation->id);
}
} | php | {
"resource": ""
} |
q9364 | ModelTranslating.applyTranslationFilter | train | protected function applyTranslationFilter()
{
if (!array_key_exists($lang = request()->get('lang'), $this->languages())) {
return;
}
return $this->query->whereLanguage($lang);
} | php | {
"resource": ""
} |
q9365 | Revision.getPluginWrappersByRow | train | public function getPluginWrappersByRow($refresh = false)
{
if ($this->pluginWrappers->count() < 1) {
return [];
}
// Per request caching
if (!empty($this->wrappersByRows) && !$refresh) {
return $this->wrappersByRows;
}
$this->wrappersByRows = $this->orderPluginWrappersByRow(
$this->pluginWrappers->toArray()
);
return $this->wrappersByRows;
} | php | {
"resource": ""
} |
q9366 | Revision.getPluginWrapper | train | public function getPluginWrapper($instanceId)
{
if ($this->pluginWrappers->count() < 1) {
return null;
}
/** @var PluginWrapper $pluginWrapper */
foreach ($this->pluginWrappers as $pluginWrapper) {
if ($pluginWrapper->getInstance()->getInstanceId() == $instanceId) {
return $pluginWrapper;
}
}
return null;
} | php | {
"resource": ""
} |
q9367 | Revision.orderPluginWrappersByRow | train | public function orderPluginWrappersByRow($pluginWrappers)
{
$wrappersByRows = [];
/** @var \Rcm\Entity\PluginWrapper $wrapper */
foreach ($pluginWrappers as $wrapper) {
$rowNumber = $wrapper->getRowNumber();
if (!isset($wrappersByRows[$rowNumber])) {
$wrappersByRows[$rowNumber] = [];
}
$wrappersByRows[$rowNumber][] = $wrapper;
}
ksort($wrappersByRows);
return $wrappersByRows;
} | php | {
"resource": ""
} |
q9368 | FlareServiceProvider.registerBindings | train | protected function registerBindings()
{
$this->app->bind(
\LaravelFlare\Flare\Contracts\Permissions\Permissionable::class,
\Flare::config('permissions')
);
} | php | {
"resource": ""
} |
q9369 | FlareServiceProvider.publishAssets | train | protected function publishAssets()
{
$assets = [];
foreach ($this->assets as $location => $asset) {
$assets[$this->basePath($location)] = base_path($asset);
}
$this->publishes($assets);
} | php | {
"resource": ""
} |
q9370 | FlareServiceProvider.publishViews | train | protected function publishViews()
{
$this->loadViewsFrom($this->basePath('resources/views'), 'flare');
$this->publishes([
$this->basePath('resources/views') => base_path('resources/views/vendor/flare'),
]);
} | php | {
"resource": ""
} |
q9371 | ModelAdmin.getManagedModel | train | public function getManagedModel()
{
if (!isset($this->managedModel) || $this->managedModel === null) {
throw new ModelAdminException('You have a ModelAdmin which does not have a model assigned to it. ModelAdmins must include a model to manage.', 1);
}
return $this->managedModel;
} | php | {
"resource": ""
} |
q9372 | ModelAdmin.getEntityTitle | train | public function getEntityTitle()
{
if (!isset($this->entityTitle) || !$this->entityTitle) {
return $this->getTitle();
}
return $this->entityTitle;
} | php | {
"resource": ""
} |
q9373 | ModelAdmin.getPluralEntityTitle | train | public function getPluralEntityTitle()
{
if (!isset($this->pluralEntityTitle) || !$this->pluralEntityTitle) {
return Str::plural($this->getEntityTitle());
}
return $this->pluralEntityTitle;
} | php | {
"resource": ""
} |
q9374 | ModelAdmin.getColumns | train | public function getColumns()
{
$columns = [];
foreach ($this->columns as $field => $fieldTitle) {
if (in_array($field, $this->model->getFillable())) {
if (!$field) {
$field = $fieldTitle;
$fieldTitle = Str::title($fieldTitle);
}
$columns[$field] = $fieldTitle;
continue;
}
// We can replace this with data_get() I believe.
if (($methodBreaker = strpos($field, '.')) !== false) {
$method = substr($field, 0, $methodBreaker);
if (method_exists($this->model, $method)) {
if (method_exists($this->model->$method(), $submethod = str_replace($method.'.', '', $field))) {
$this->model->$method()->$submethod();
$columns[$field] = $fieldTitle;
continue;
}
}
}
if (is_numeric($field)) {
$field = $fieldTitle;
$fieldTitle = Str::title($fieldTitle);
}
$columns[$field] = $fieldTitle;
}
if (count($columns)) {
return $columns;
}
return [$this->model->getKeyName() => $this->model->getKeyName()];
} | php | {
"resource": ""
} |
q9375 | ModelAdmin.getAttribute | train | public function getAttribute($key, $model = false)
{
if (!$key) {
return;
}
if (!$model) {
$model = $this->model;
}
$formattedKey = str_replace('.', '_', $key);
if ($this->hasGetAccessor($formattedKey)) {
$method = 'get'.Str::studly($formattedKey).'Attribute';
return $this->{$method}($model);
}
if ($this->hasGetAccessor($key)) {
$method = 'get'.Str::studly($key).'Attribute';
return $this->{$method}($model);
}
if ($this->hasRelatedKey($key, $model)) {
return $this->relatedKey($key, $model);
}
return $model->getAttribute($key);
} | php | {
"resource": ""
} |
q9376 | ModelAdmin.hasRelatedKey | train | public function hasRelatedKey($key, $model = false)
{
if (!$model) {
$model = $this->model;
}
if (($methodBreaker = strpos($key, '.')) !== false) {
$method = substr($key, 0, $methodBreaker);
if (method_exists($model, $method)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q9377 | ModelAdmin.relatedKey | train | public function relatedKey($key, $model = false)
{
if (!$model) {
$model = $this->model;
}
if (($methodBreaker = strpos($key, '.')) !== false) {
$method = substr($key, 0, $methodBreaker);
if (method_exists($model, $method)) {
if (method_exists($model->$method, $submethod = str_replace($method.'.', '', $key))) {
return $model->$method->$submethod();
}
if (isset($model->$method->$submethod)) {
return $model->$method->$submethod;
}
return $model->getRelationValue($method);
}
}
return false;
} | php | {
"resource": ""
} |
q9378 | ModelAdmin.formatFields | train | protected function formatFields()
{
$fields = $this->fields;
if (!$fields instanceof AttributeCollection) {
$fields = new AttributeCollection($fields, $this);
}
return $this->fields = $fields->formatFields();
} | php | {
"resource": ""
} |
q9379 | ModelAdmin.hasSoftDeleting | train | public function hasSoftDeleting()
{
if (!$this->hasDeleting()) {
return false;
}
$managedModelClass = $this->getManagedModel();
return in_array(
SoftDeletes::class, class_uses_recursive(get_class(new $managedModelClass()))
) && $this->hasDeleting();
} | php | {
"resource": ""
} |
q9380 | Module.init | train | public function init()
{
parent::init();
\Yii::$app->getI18n()->translations['core.*'] = [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => __DIR__.'/messages',
];
$this->setAliases([
'@core' => __DIR__
]);
} | php | {
"resource": ""
} |
q9381 | SeoBehavior.getSeoTags | train | public function getSeoTags() {
if($this->owner->seo) {
$seo = $this->owner->seo->attributes;
return array_filter(array_intersect_key($seo, array_flip(['meta_title', 'meta_keywords', 'meta_description'])));
} else {
return [];
}
} | php | {
"resource": ""
} |
q9382 | WidgetAdmin.getView | train | public function getView()
{
if (view()->exists(static::$view)) {
return static::$view;
}
if (view()->exists('admin.widgets.'.static::safeTitle().'.widget')) {
return 'admin.widgets.'.static::safeTitle().'.widget';
}
if (view()->exists('admin.widgets.'.static::safeTitle())) {
return 'admin.widgets.'.static::safeTitle();
}
if (view()->exists('admin.'.static::safeTitle())) {
return 'admin.'.static::safeTitle();
}
if (view()->exists('flare::'.self::$view)) {
return 'flare::'.self::$view;
}
} | php | {
"resource": ""
} |
q9383 | SecureHeader.send | train | public function send()
{
$this->sendContentOptions();
$this->sendFrameOptions();
$this->sendXssProtection();
$this->sendStrictTransport();
$this->sendAccessControlAllowOrigin();
$this->sendContentSecurity();
} | php | {
"resource": ""
} |
q9384 | BaseTrait.putItem | train | public function putItem($name, $value = null)
{
if (is_null($name) || is_int($name)) {
$this->_items[] = $value;
} else {
$this->_items[$name] = $value;
}
} | php | {
"resource": ""
} |
q9385 | BaseTrait.rawItem | train | public function rawItem($name, $default = null)
{
return isset($this->_items[$name]) ? $this->_items[$name] : $default;
} | php | {
"resource": ""
} |
q9386 | BaseTrait.addItem | train | public function addItem($name, $value = null, $where = '')
{
if (!$this->hasItem($name)) {
$this->setItem($name, $value, $where);
}
return $this;
} | php | {
"resource": ""
} |
q9387 | BaseTrait.setItem | train | public function setItem($name, $value = null, $where = '')
{
if ($name === null || $where === '') {
$this->putItem($name, $value);
} else {
$this->setItems([$name => $value], $where);
}
} | php | {
"resource": ""
} |
q9388 | BaseTrait.putItems | train | public function putItems(array $items)
{
foreach ($items as $k => $v) {
$this->putItem($k, $v);
}
} | php | {
"resource": ""
} |
q9389 | BaseTrait.setItems | train | public function setItems($items, $where = '')
{
if (empty($items)) {
return;
}
if (empty($where)) {
$this->putItems($items);
} elseif ($where === 'last') {
$this->_items = ArrayHelper::insertLast($this->_items, $items);
} elseif ($where === 'first') {
$this->_items = ArrayHelper::insertFirst($this->_items, $items);
} else {
$this->_items = ArrayHelper::insertInside($this->_items, $items, $where);
}
} | php | {
"resource": ""
} |
q9390 | BaseTrait.addItems | train | public function addItems(array $items, $where = '')
{
foreach (array_keys($items) as $k) {
if (!is_int($k) && $this->hasItem($k)) {
unset($items[$k]);
}
}
if (!empty($items)) {
$this->setItems($items, $where);
}
return $this;
} | php | {
"resource": ""
} |
q9391 | BaseTrait.unsetItems | train | public function unsetItems($keys = null)
{
if (is_null($keys)) {
$this->_items = [];
} elseif (is_scalar($keys)) {
unset($this->_items[$keys]);
} else {
foreach ($keys as $k) {
unset($this->_items[$k]);
}
}
} | php | {
"resource": ""
} |
q9392 | PageCheckController.getList | train | public function getList()
{
$pageType = $this->params('pageType', PageTypes::NORMAL);
$pageId = $this->params('pageId', null);
/** @var \Rcm\Validator\Page $validator */
$validator = clone($this->getServiceLocator()->get(\Rcm\Validator\Page::class));
$validator->setPageType($pageType);
$return = [
'valid' => true
];
if (!$validator->isValid($pageId)) {
$return['valid'] = false;
$return['error'] = $validator->getMessages();
/** @var \Zend\Http\Response $response */
$response = $this->response;
$errorCodes = array_keys($return['error']);
foreach ($errorCodes as &$errorCode) {
if ($errorCode == $validator::PAGE_EXISTS) {
$response->setStatusCode(409);
break;
} elseif ($errorCode == $validator::PAGE_NAME) {
$response->setStatusCode(417);
}
}
}
return new JsonModel($return);
} | php | {
"resource": ""
} |
q9393 | AssetManager.attach | train | public function attach($name, $resolver = null, $single = false, $override = false)
{
if (is_array($name)) {
$resolver = current($name);
$name = key($name);
$this->alias($resolver, $name, $override);
}
if ($name instanceof Asset) {
$this->setParam('assets', $name->is(), $name, $override);
} elseif ($resolver instanceof \Closure && $single) {
$this->setParam('assets', $name, function($params) use ($resolver) {
static $obj;
if ($obj === null) {
$obj = $resolver($params, $this);
}
return $obj;
}, $override);
} elseif ($resolver instanceof \Closure || $resolver instanceof Asset) {
$this->setParam('assets', $name, $resolver, $override);
} elseif (is_object($resolver)) {
$this->setParam('instances', $name, $resolver, $override);
} elseif (($resolver === null) && $single) {
$this->setParam('instances', $name, $name, $override);
} elseif ($single) {
$this->setParam('instances', $name, $resolver, $override);
} elseif ($resolver === null) {
$this->setParam('assets', $name, $name, $override);
}
// If we have a singleton, make sure it is only in
// the *instances* array and not within *aliases*.
if ($single && isset($this->aliases[$name])) {
unset($this->aliases[$name]);
}
return $this;
} | php | {
"resource": ""
} |
q9394 | AssetManager.singleton | train | public function singleton($name, $resolver = null, $override = false)
{
return $this->attach($name, $resolver, true, $override);
} | php | {
"resource": ""
} |
q9395 | AssetManager.overrideAsSingleton | train | public function overrideAsSingleton($name, $resolver = null)
{
return $this->singleton($name, $resolver, true, true);
} | php | {
"resource": ""
} |
q9396 | AssetManager.resolve | train | public function resolve($name, $params = [])
{
// Allow hot resolving. eg; pass a closure to the resolve() method.
if (isset($params['resolver']) && $params['resolver'] instanceof \Closure) {
return $params['resolver']();
}
// Allow custom reflection resolutions.
if (isset($params['reflector']) && $params['reflector'] instanceof \Closure) {
$reflection = new \ReflectionClass($name);
if ($reflection->isInstantiable()) {
return $params['reflector']($reflection, $name);
}
}
// Assets are simple.
if (isset($this->assets[$name])) {
if ($this->assets[$name] instanceof Asset || $this->assets[$name] instanceof \Closure) {
return $this->assets[$name]($params, $this);
}
}
// Singletons are more complex if they haven't been instantiated as yet.
if (isset($this->instances[$name])) {
// If we have a resolver (closure or asset) that hasn't been
// instantiated into an actual instance of our asset yet, do so.
if ($this->instances[$name] instanceof Asset || $this->instances[$name] instanceof \Closure) {
$object = $this->instances[$name]($params, $this);
$this->setParam('instances', $name, $object, true);
// If we have an instance, return it.
} else if (is_object($this->instances[$name])) {
return $this->instances[$name];
// Do what ever we can to resolve this asset.
} else {
try {
// Attempt to resolve by name.
$object = $this->autoResolve($name, $params);
$this->setParam('instances', $name, $object, true);
return $this->resolve($name);
} catch (\LogicException $e) {
try {
$object = $this->autoResolve($this->instances[$name], $params);
$this->setParam('instances', $name, $object, true);
return $this->resolve($name);
} catch (\LogicException $e) {
throw $e;
}
}
}
}
// Recurse back through resolve().
// This allows complex alias mappings.
if (isset($this->aliases[$name])) {
return $this->resolve($this->aliases[$name]);
}
// At this point, we still haven't resolved anything.
// Try resolving by name alone.
return $this->autoResolve($name, $params);
} | php | {
"resource": ""
} |
q9397 | AssetManager.getDependencies | train | public function getDependencies($params)
{
$deps = [];
foreach ($params as $param) {
$dependency = $param->getClass();
if ($dependency !== null) {
if ($dependency->name == 'Proem\Service\AssetManager' || $dependency->name == 'Proem\Service\AssetManagerInterface') {
$deps[] = $this;
} else {
$deps[] = $this->resolve($dependency->name);
}
} else {
if ($param->isDefaultValueAvailable()) {
$deps[] = $param->getDefaultValue();
}
}
}
return $deps;
} | php | {
"resource": ""
} |
q9398 | AssetManager.setParam | train | protected function setParam($type, $index, $value, $override = false) {
if ($override) {
$this->{$type}[$index] = $value;
} else if (!isset($this->{$type}[$index])) {
$this->{$type}[$index] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q9399 | AssetManager.autoResolve | train | protected function autoResolve($name, $params)
{
try {
$reflection = new \ReflectionClass($name);
if ($reflection->isInstantiable()) {
$construct = $reflection->getConstructor();
if ($construct === null) {
$object = new $name;
} else {
$dependencies = $this->getDependencies($construct->getParameters());
$object = $reflection->newInstanceArgs($dependencies);
}
try {
$method = $reflection->getMethod('setParams');
$method->invokeArgs($object, $params);
// Do nothing. This method may very well not exist.
} catch (\ReflectionException $e) {}
// Allow a list of methods to be executed.
if (isset($params['methods'])) {
foreach ($params['methods'] as $method) {
$method = $reflection->getMethod($method);
$method->invokeArgs($object, $this->getDependencies($method->getParameters()));
}
}
// If this single method is invoked, its results will be returned.
if (isset($params['invoke'])) {
$method = $params['invoke'];
$method = $reflection->getMethod($method);
return $method->invokeArgs($object, $this->getDependencies($method->getParameters()));
}
return $object;
}
} catch (\ReflectionException $e) {
throw new \LogicException("Unable to resolve '{$name}'");
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.