_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9500 | ModelQuerying.applyQueryFilters | train | private function applyQueryFilters()
{
if (is_array($this->queryFilter())) {
$this->createQueryFilter();
} else {
$this->queryFilter();
}
$this->queryFilterRequest();
} | php | {
"resource": ""
} |
q9501 | ModelQuerying.queryFilterRequest | train | private function queryFilterRequest()
{
if (!$safeFilter = Request::get('filter')) {
return false;
}
if (!isset($this->safeFilters()[$safeFilter])) {
return false;
}
return $this->query = $this->filters()[$this->safeFilters()[$safeFilter]];
} | php | {
"resource": ""
} |
q9502 | ModelQuerying.createQueryFilter | train | private function createQueryFilter()
{
if (count($this->queryFilter()) > 0) {
foreach ($this->queryFilter() as $filter => $parameters) {
if (!is_array($parameters)) {
$parameters = [$parameters];
}
$this->query = call_user_func_array([$this->query, $filter], $parameters);
}
}
} | php | {
"resource": ""
} |
q9503 | ModelQuerying.safeFilters | train | public function safeFilters()
{
$filters = [];
foreach ($this->filters() as $filterName => $query) {
$filters[str_slug($filterName)] = $filterName;
}
return $filters;
} | php | {
"resource": ""
} |
q9504 | SessionManagerFactory.getSessionConfig | train | protected function getSessionConfig(
ServiceLocatorInterface $serviceLocator,
$sessionConfig
) {
if (empty($sessionConfig)
|| empty($sessionConfig['config'])
) {
return new SessionConfig();
}
$class = '\Zend\Session\Config\SessionConfig';
$options = [];
if (isset($sessionConfig['config']['class'])
) {
$class = $sessionConfig['config']['class'];
}
if (isset($sessionConfig['config']['options'])
) {
$options = $sessionConfig['config']['options'];
}
/** @var \Zend\Session\Config\ConfigInterface $sessionConfigObject */
if ($serviceLocator->has($class)) {
$sessionConfigObject = $serviceLocator->get($class);
} else {
$sessionConfigObject = new $class();
}
if (!$sessionConfigObject instanceof ConfigInterface) {
throw new InvalidArgumentException(
'Session Config class must implement '
. '\Zend\Session\Config\ConfigInterface'
);
}
$sessionConfigObject->setOptions($options);
return $sessionConfigObject;
} | php | {
"resource": ""
} |
q9505 | SessionManagerFactory.getSessionSaveHandler | train | protected function getSessionSaveHandler(
ServiceLocatorInterface $serviceLocator,
$sessionConfig
) {
if (!isset($sessionConfig['save_handler'])) {
return null;
}
// Setting with invokable currently not implemented. No session
// Save handler available in ZF2 that's currently invokable is available
// for testing.
/** @var SaveHandlerInterface $sessionSaveHandler */
$saveHandler = $serviceLocator->get($sessionConfig['save_handler']);
if (!$saveHandler instanceof SaveHandlerInterface) {
throw new InvalidArgumentException(
'Session Save Handler class must implement '
. 'Zend\Session\Storage\StorageInterface'
);
}
return $saveHandler;
} | php | {
"resource": ""
} |
q9506 | SessionManagerFactory.setValidatorChain | train | protected function setValidatorChain(
SessionManager $sessionManager,
ServiceLocatorInterface $serviceLocator,
$sessionConfig
) {
if (!isset($sessionConfig['validators'])
|| !is_array($sessionConfig['validators'])
) {
return;
}
$chain = $sessionManager->getValidatorChain();
foreach ($sessionConfig['validators'] as &$validator) {
if ($serviceLocator->has($validator)) {
$validator = $serviceLocator->get($validator);
} else {
$validator = new $validator();
}
if (!$validator instanceof ValidatorInterface) {
throw new InvalidArgumentException(
'Session Save Handler class must implement '
. 'Zend\Session\Validator\ValidatorInterface'
);
}
$chain->attach(
'session.validate',
[$validator, 'isValid']
);
}
} | php | {
"resource": ""
} |
q9507 | EntityAwareParamConverterTrait.callRepositoryMethod | train | protected function callRepositoryMethod(string $method, ...$args)
{
$om = $this->getManager();
$repo = $om->getRepository($this->getEntity());
if (!method_exists($repo, $method) || !is_callable([$repo, $method])) {
throw new \InvalidArgumentException(
sprintf(
'Method "%s" doesn\'t exist or isn\'t callable in EntityRepository "%s"',
$method,
get_class($repo)
)
);
}
return $repo->$method(...$args);
} | php | {
"resource": ""
} |
q9508 | AccessTokenGuard.supports | train | public function supports(Request $request)
{
$post = json_decode($request->getContent(), true);
return !empty($post[self::TOKEN_FIELD]);
} | php | {
"resource": ""
} |
q9509 | AccessTokenGuard.getCredentials | train | public function getCredentials(Request $request)
{
$post = json_decode($request->getContent(), true);
return new CredentialTokenModel($post[self::TOKEN_FIELD]);
} | php | {
"resource": ""
} |
q9510 | RouterEngine.run | train | final public function run(Request $request)
{
$this->request = $request;
$path = $this->request->getUri()->getPath();
$this->requestedUri = ($path != "/") ? rtrim($path, "/") : "/";
$this->requestedMethod = strtoupper($this->request->getMethod());
$this->requestedRepresentation = $this->request->getAccept();
$this->verifyRequestMethod();
$route = $this->findRouteFromRequest();
$this->prepareResponse($route);
} | php | {
"resource": ""
} |
q9511 | RouterEngine.addRoute | train | final protected function addRoute($method, $uri, $callback, $acceptedFormats)
{
$this->routes[$method][] = [
'route' => new Route($uri),
'callback' => $callback,
'acceptedRequestFormats' => $acceptedFormats
];
} | php | {
"resource": ""
} |
q9512 | RouterEngine.createResponse | train | private function createResponse($route): ?Response
{
$controller = $this->getRouteControllerInstance($route);
if (!is_null($controller)) {
$responseBefore = $controller->before();
if ($responseBefore instanceof Response) {
return $responseBefore;
}
}
$values = $route['route']->getArguments($this->requestedUri);
$this->loadRequestParameters($values);
$callback = new Callback($route['callback']);
$arguments = $this->getFunctionArguments($callback->getReflection(), array_values($values));
$response = $callback->executeArray($arguments);
if (!is_null($controller)) {
$responseAfter = $controller->after($response);
if ($responseAfter instanceof Response) {
return $responseAfter;
}
}
return $response;
} | php | {
"resource": ""
} |
q9513 | RouterEngine.loadRequestParameters | train | private function loadRequestParameters($values)
{
foreach ($values as $param => $value) {
$this->request->prependParameter($param, $value);
}
} | php | {
"resource": ""
} |
q9514 | RouteListener.checkDomain | train | public function checkDomain(MvcEvent $event)
{
if ($this->isConsoleRequest()) {
return null;
}
$currentDomain = $this->siteService->getCurrentDomain();
$site = $this->siteService->getCurrentSite($currentDomain);
$redirectUrl = $this->domainRedirectService->getSiteNotAvailableRedirectUrl($site);
if (!$site->isSiteAvailable() && empty($redirectUrl)) {
$response = new Response();
$response->setStatusCode(404);
$event->stopPropagation(true);
return $response;
}
if ($redirectUrl) {
$response = new Response();
$response->setStatusCode(302);
$response->getHeaders()->addHeaderLine('Location', '//' . $redirectUrl);
$event->stopPropagation(true);
return $response;
}
$redirectUrl = $this->domainRedirectService->getPrimaryRedirectUrl($site);
if ($redirectUrl) {
$response = new Response();
$response->setStatusCode(302);
$response->getHeaders()->addHeaderLine('Location', '//' . $redirectUrl);
$event->stopPropagation(true);
return $response;
}
return null;
} | php | {
"resource": ""
} |
q9515 | RouteListener.checkRedirect | train | public function checkRedirect(MvcEvent $event)
{
if ($this->isConsoleRequest()) {
return null;
}
// User defaults
$redirectUrl = $this->redirectService->getRedirectUrl();
if (empty($redirectUrl)) {
return null;
}
$queryParams = $event->getRequest()->getQuery()->toArray();
header(
'Location: ' . $redirectUrl . (count($queryParams) ? '?' . http_build_query($queryParams) : null),
true,
302
);
exit;
/* Below is the ZF2 way but Response is not short-circuiting the event like it should *
$response = new Response();
$response->setStatusCode(302);
$response->getHeaders()
->addHeaderLine(
'Location',
$redirect->getRedirectUrl()
);
$event->stopPropagation(true);
return $response;
*/
} | php | {
"resource": ""
} |
q9516 | RouteListener.addLocale | train | public function addLocale(MvcEvent $event)
{
$locale = $this->siteService->getCurrentSite()->getLocale();
$this->localeService->setLocale($locale);
return null;
} | php | {
"resource": ""
} |
q9517 | SavantPHP.getConfigList | train | public function getConfigList($key = null)
{
if (is_null($key)) {
return $this->configList; // no key requested, return the entire configuration bag
} elseif (empty($this->configList[$key])) {
return null; // no such key
} else {
return $this->configList[$key]; // return the requested key
}
} | php | {
"resource": ""
} |
q9518 | SavantPHP.setPath | train | public function setPath($path)
{
// clear out the prior search dirs
$this->configList[self::TPL_PATH_LIST] = [];
// always add the fallback directories as last resort
$this->addPath('.');
// actually add the user-specified directory
$this->addPath($path);
} | php | {
"resource": ""
} |
q9519 | SavantPHP.fetch | train | public function fetch($tpl = null)
{
// make sure we have a template source to work with
if (is_null($tpl)) {
$tpl = $this->configList[self::TPL_FILE];
}
$result = $this->getPathToTemplate($tpl);
if (! $result || $this->isError($result)) { //if no path
return $result;
} else {
$this->configList[self::FETCHED_TPL_FILE] = $result;
unset($result);
unset($tpl);
// buffer output so we can return it instead of displaying.
ob_start();
include $this->configList[self::FETCHED_TPL_FILE];
$this->configList[self::FETCHED_TPL_FILE] = null; //flush fetched script value
return ob_get_clean();
}
} | php | {
"resource": ""
} |
q9520 | SavantPHP.error | train | public function error($code, $info = [], $level = E_USER_ERROR, $trace = true)
{
if ($this->configList[self::EXCEPTIONS]) {
throw new SavantPHPexception($code);
}
// the error config array
$config = [
'code' => $code,
'info' => (array) $info,
'level' => $level,
'trace' => $trace
];
return new SavantPHPerror($config);
} | php | {
"resource": ""
} |
q9521 | SavantPHP.isError | train | public function isError($obj)
{
// is it even an object?
if (! is_object($obj)) { // if not an object, can't even be a SavantPHPerror object
return false;
} else {
// now compare the parentage
$is = $obj instanceof SavantPHPerror;
$sub = is_subclass_of($obj, 'SavantPHPerror');
return ($is || $sub);
}
} | php | {
"resource": ""
} |
q9522 | ResourceCollection.buildFromArray | train | public static function buildFromArray(array $resources)
{
$resource = @$resources[0];
if (!$resource instanceof EntityResource) {
throw new LogicException(self::ERROR_EMPTY_ARRAY);
}
return new static($resources, $resource->getMetadata());
} | php | {
"resource": ""
} |
q9523 | Commentable.getComments | train | public function getComments(bool $nested = false)
{
$comments = $this->comments()->get();
// If at least one comment is left by a registered user
if ($comments->firstWhere('user_id', '>', 'null')) {
$comments->load(['user:users.id,users.name,users.email,users.avatar']);
}
return $comments->treated($nested, $this->getAttributes());
} | php | {
"resource": ""
} |
q9524 | ResponseHandler.processResponse | train | public function processResponse(ResponseInterface $response)
{
if (!$response instanceof Response
|| !$this->getRequest()
) {
return;
}
$response = $this->handleResponse($response);
$this->renderResponse($response);
$this->terminateApp();
} | php | {
"resource": ""
} |
q9525 | ResponseHandler.handleResponse | train | protected function handleResponse(Response $response)
{
$statusCode = $response->getStatusCode();
switch ($statusCode) {
case 401:
$response = $this->processNotAuthorized();
break;
}
return $response;
} | php | {
"resource": ""
} |
q9526 | ResponseHandler.processNotAuthorized | train | protected function processNotAuthorized()
{
$loginPage = $this->currentSite->getLoginPage();
$notAuthorized = $this->currentSite->getNotAuthorizedPage();
$returnToUrl = urlencode($this->request->getServer('REQUEST_URI'));
$newResponse = new Response();
$newResponse->setStatusCode('302');
if (!$this->userService->hasIdentity()) {
$newResponse->getHeaders()
->addHeaderLine(
'Location: ' . $loginPage . '?redirect=' . $returnToUrl
);
} else {
$newResponse->getHeaders()
->addHeaderLine(
'Location: ' . $notAuthorized
);
}
return $newResponse;
} | php | {
"resource": ""
} |
q9527 | ResponseHandler.renderResponse | train | protected function renderResponse(Response $response)
{
$sendEvent = new SendResponseEvent();
$sendEvent->setResponse($response);
$this->responseSender->__invoke($sendEvent);
} | php | {
"resource": ""
} |
q9528 | AbstractFontAwesomeTwigExtension.fontAwesomeIcon | train | protected function fontAwesomeIcon(FontAwesomeIconInterface $icon) {
$attributes = [];
$attributes["class"][] = FontAwesomeIconRenderer::renderFont($icon);
$attributes["class"][] = FontAwesomeIconRenderer::renderName($icon);
$attributes["class"][] = FontAwesomeIconRenderer::renderSize($icon);
$attributes["class"][] = FontAwesomeIconRenderer::renderFixedWidth($icon);
$attributes["class"][] = FontAwesomeIconRenderer::renderBordered($icon);
$attributes["class"][] = FontAwesomeIconRenderer::renderPull($icon);
$attributes["class"][] = FontAwesomeIconRenderer::renderAnimation($icon);
$attributes["style"] = FontAwesomeIconRenderer::renderStyle($icon);
return static::coreHTMLElement("i", null, $attributes);
} | php | {
"resource": ""
} |
q9529 | AbstractFontAwesomeTwigExtension.fontAwesomeList | train | protected function fontAwesomeList($items) {
$innerHTML = true === is_array($items) ? implode("\n", $items) : $items;
return static::coreHTMLElement("ul", $innerHTML, ["class" => "fa-ul"]);
} | php | {
"resource": ""
} |
q9530 | AbstractFontAwesomeTwigExtension.fontAwesomeListIcon | train | protected function fontAwesomeListIcon($icon, $content) {
$glyphicon = static::coreHTMLElement("span", $icon, ["class" => "fa-li"]);
$innerHTML = null !== $content ? $content : "";
return static::coreHTMLElement("li", $glyphicon . $innerHTML);
} | php | {
"resource": ""
} |
q9531 | UnzipAssetsCommand.displayFooter | train | protected function displayFooter(StyleInterface $io, $exitCode, $count) {
if (0 < $exitCode) {
$io->error("Some errors occurred while unzipping assets");
return;
}
if (0 === $count) {
$io->success("No assets were provided by any bundle");
return;
}
$io->success("All assets were successfully unzipped");
} | php | {
"resource": ""
} |
q9532 | UnzipAssetsCommand.displayResult | train | protected function displayResult(StyleInterface $io, array $results) {
$exitCode = 0;
$rows = [];
$success = $this->getCheckbox(true);
$warning = $this->getCheckbox(false);
// Handle each result.
foreach ($results as $bundle => $assets) {
foreach ($assets as $asset => $result) {
$rows[] = [
true === $result ? $success : $warning,
$bundle,
basename($asset),
];
$exitCode += true === $result ? 0 : 1;
}
}
// Displays a table.
$io->table(["", "Bundle", "Asset"], $rows);
return $exitCode;
} | php | {
"resource": ""
} |
q9533 | AbstractStateLessGuard.supports | train | public function supports(Request $request)
{
return !empty($request->headers->get(self::AUTHORIZATION_HEADER)) || !empty($request->cookies->get(AuthResponseService::AUTH_COOKIE));
} | php | {
"resource": ""
} |
q9534 | AbstractStateLessGuard.getCredentials | train | public function getCredentials(Request $request)
{
$token = !empty($request->headers->get(self::AUTHORIZATION_HEADER)) ?
$request->headers->get(self::AUTHORIZATION_HEADER) :
$request->cookies->get(AuthResponseService::AUTH_COOKIE);
return new CredentialTokenModel(str_replace(self::BEARER, '', $token));
} | php | {
"resource": ""
} |
q9535 | AdminPanelController.getAdminWrapperAction | train | public function getAdminWrapperAction()
{
$allowed = $this->cmsPermissionChecks->siteAdminCheck($this->currentSite);
if (!$allowed) {
return null;
}
/** @var RouteMatch $routeMatch */
$routeMatch = $this->getEvent()->getRouteMatch();
$siteId = $this->currentSite->getSiteId();
$sourcePageName = $routeMatch->getParam('page', 'index');
if ($sourcePageName instanceof Page) {
$sourcePageName = $sourcePageName->getName();
}
$pageType = $routeMatch->getParam('pageType', 'n');
$view = new ViewModel();
$view->setVariable('restrictions', false);
if ($this->cmsPermissionChecks->isPageRestricted($siteId, $pageType, $sourcePageName, 'read') == true) {
$view->setVariable('restrictions', true);
}
$view->setVariable('adminMenu', $this->adminPanelConfig);
$view->setTemplate('rcm-admin/admin/admin');
return $view;
} | php | {
"resource": ""
} |
q9536 | Page.setName | train | public function setName($name)
{
$name = strtolower($name);
//Check for everything except letters and dashes. Throw exception if any are found.
if (preg_match("/[^a-z\-0-9\.]/", $name)) {
throw new InvalidArgumentException(
'Page names can only contain letters, numbers, dots, and dashes.'
. ' No spaces. This page name is invalid: ' . $name
);
}
$this->name = $name;
} | php | {
"resource": ""
} |
q9537 | Page.setParent | train | public function setParent(Page $parent)
{
$this->parent = $parent;
$this->parentId = $parent->getPageId();
} | php | {
"resource": ""
} |
q9538 | Rule.isValid | train | public function isValid($value, array $fields = []): bool
{
$callback = new Callback($this->validation);
$arguments = $this->getFunctionArguments($callback->getReflection(), $value, $fields);
return $callback->executeArray($arguments);
} | php | {
"resource": ""
} |
q9539 | AbstractServiceCall.getRequest | train | public function getRequest(): RequestInterface
{
if (!$this->request) {
$this->resolveOptions();
$this->request = $this->createRequest();
}
return parent::getRequest();
} | php | {
"resource": ""
} |
q9540 | AbstractServiceCall.doCall | train | protected function doCall()
{
$this->resolveOptions();
$this->request = $this->createRequest();
$this->response = $this->client->send($this->request);
return $this->generateResponse($this->response);
} | php | {
"resource": ""
} |
q9541 | AbstractServiceCall.resolveOptions | train | protected function resolveOptions(): void
{
$resolver = new OptionsResolver();
$this->configureOptions($resolver);
$this->options = $resolver->resolve($this->options);
} | php | {
"resource": ""
} |
q9542 | AbstractServiceCall.validateJson | train | protected function validateJson(ResponseInterface $response): array
{
try {
return \GuzzleHttp\json_decode((string) $response->getBody(), true);
} catch (\Exception $e) {
return [];
}
} | php | {
"resource": ""
} |
q9543 | AbstractThemeManager.addGlobal | train | public function addGlobal() {
foreach ($this->getIndex() as $k => $v) {
if (null === $v) {
continue;
}
$this->getTwigEnvironment()->addGlobal(str_replace("Interface", "", $k), $this->getProviders()[$v]);
}
} | php | {
"resource": ""
} |
q9544 | AbstractThemeManager.setProvider | train | protected function setProvider($name, ThemeProviderInterface $provider) {
$k = ObjectHelper::getShortName($name);
$v = $this->getIndex()[$k];
if (null !== $v) {
$this->getProviders()[$v] = $provider;
return $this;
}
$this->index[$k] = count($this->getProviders());
return $this->addProvider($provider);
} | php | {
"resource": ""
} |
q9545 | UploadFile.getRealMimeType | train | private function getRealMimeType()
{
$info = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($info, $this->temporaryFilename);
finfo_close($info);
return $mime;
} | php | {
"resource": ""
} |
q9546 | Trip.setWalkingDistance | train | public function setWalkingDistance(int $originDistance = 2000, int $destinationDistance = 2000): self
{
$this->options['maxWalkingDistanceDep'] = $originDistance;
$this->options['maxWalkingDistanceDest'] = $destinationDistance;
return $this;
} | php | {
"resource": ""
} |
q9547 | Trip.getUrl | train | protected function getUrl(array $options): string
{
$urlOptions = [];
$this->setOriginAndDestinationOption($urlOptions, $options);
$this->setViaOption($urlOptions, $options);
$this->setDateOption($urlOptions, $options);
$urlOptions = array_merge($urlOptions, $options);
return sprintf('trip?%s&format=json', http_build_query($urlOptions));
} | php | {
"resource": ""
} |
q9548 | Callback.executeMethod | train | private function executeMethod(array $arguments)
{
if ($this->reflection->isStatic()) {
return $this->reflection->invokeArgs(null, $arguments);
} elseif (is_object($this->callback[0])) {
return $this->reflection->invokeArgs($this->callback[0], $arguments);
}
$instance = new $this->callback[0]();
return $this->reflection->invokeArgs($instance, $arguments);
} | php | {
"resource": ""
} |
q9549 | AdminManager.getAdminClasses | train | public function getAdminClasses()
{
$classCollection = [];
if (!defined('static::ADMIN_KEY')) {
return $classCollection;
}
$classCollection = $this->getSubAdminClasses(\Flare::config(static::ADMIN_KEY));
return $classCollection;
} | php | {
"resource": ""
} |
q9550 | AdminManager.registerSubRoutes | train | public function registerSubRoutes(array $classes)
{
foreach ($classes as $key => $class) {
if (is_array($class)) {
if ($this->usableClass($key)) {
$this->registerAdminRoutes($key);
}
$this->registerSubRoutes($class);
continue;
}
$this->registerAdminRoutes($class);
}
} | php | {
"resource": ""
} |
q9551 | Cryptography.randomHex | train | public static function randomHex(int $length = 128): string
{
$bytes = ceil($length / 2);
$hex = bin2hex(self::randomBytes($bytes));
return $hex;
} | php | {
"resource": ""
} |
q9552 | Cryptography.randomInt | train | public static function randomInt(int $min, int $max): int
{
if ($max <= $min) {
throw new \Exception('Minimum equal or greater than maximum!');
}
if ($max < 0 || $min < 0) {
throw new \Exception('Only positive integers supported for now!');
}
$difference = $max - $min;
for ($power = 8; pow(2, $power) < $difference; $power = $power * 2) {
}
$powerExp = $power / 8;
do {
$randDiff = hexdec(bin2hex(self::randomBytes($powerExp)));
} while ($randDiff > $difference);
return $min + $randDiff;
} | php | {
"resource": ""
} |
q9553 | Cryptography.encrypt | train | public static function encrypt(string $data, string $key): string
{
$method = Configuration::getSecurityConfiguration('encryption_algorithm');
$initializationVector = self::randomBytes(openssl_cipher_iv_length($method));
$cipher = openssl_encrypt($data, $method, $key, 0, $initializationVector);
return base64_encode($initializationVector) . ':' . base64_encode($cipher);
} | php | {
"resource": ""
} |
q9554 | JWSTokenService.createAuthTokenModel | train | public function createAuthTokenModel(BaseUser $user)
{
$privateKey = openssl_pkey_get_private(
file_get_contents($this->projectDir . '/var/jwt/private.pem'),
$this->passPhrase
);
$jws = new SimpleJWS([
'alg' => self::ALG
]);
$expirationDate = new \DateTime();
$expirationDate->modify('+' . $this->authTokenTTL . ' seconds');
$expirationTimestamp = $expirationDate->getTimestamp();
$jws->setPayload(array_merge([
self::USER_ID_KEY => $user->getId(),
self::EXP_KEY => $expirationTimestamp,
self::IAT_KEY => (new \DateTime())->getTimestamp()
], $user->getJWTPayload()));
$jws->sign($privateKey);
return new AuthTokenModel($jws->getTokenString(), $expirationTimestamp);
} | php | {
"resource": ""
} |
q9555 | JWSTokenService.isValid | train | public function isValid($token)
{
try {
$publicKey = openssl_pkey_get_public(file_get_contents($this->projectDir . '/var/jwt/public.pem'));
$jws = SimpleJWS::load($token);
return $jws->verify($publicKey, self::ALG) && $this->isTokenNotExpired($token);
} catch (\InvalidArgumentException $ex) {
return false;
}
} | php | {
"resource": ""
} |
q9556 | JWSTokenService.getUser | train | public function getUser($token)
{
$payload = $this->getPayload($token);
if (empty($payload[JWSTokenService::USER_ID_KEY])) {
throw new ProgrammerException("No user_id in token payload", ProgrammerException::AUTH_TOKEN_NO_USER_ID);
}
$userId = $payload[JWSTokenService::USER_ID_KEY];
$user = $this->userService->findUserById($userId);
if (empty($user)) {
throw new ProgrammerException(
"Unknown user id in token, " . $userId,
ProgrammerException::AUTH_TOKEN_NO_USER_WITH_ID_FOUND
);
}
return $user;
} | php | {
"resource": ""
} |
q9557 | JWSTokenService.getPayload | train | public function getPayload($token)
{
try {
$jws = SimpleJWS::load($token);
return $jws->getPayload();
} catch (\InvalidArgumentException $ex) {
throw new ProgrammerException('Unable to read jws token.', ProgrammerException::JWS_INVALID_TOKEN_FORMAT);
}
} | php | {
"resource": ""
} |
q9558 | JWSTokenService.isTokenNotExpired | train | private function isTokenNotExpired($token)
{
$payload = $this->getPayload($token);
return isset($payload[self::EXP_KEY]) && $payload[self::EXP_KEY] > (new \DateTime())->getTimestamp();
} | php | {
"resource": ""
} |
q9559 | PriorityQueue.insert | train | public function insert($data, $priority = 0)
{
$this->data[] = [
'data' => $data,
'priority' => $priority,
];
$priority = array($priority, $this->max--);
$this->getSplQueue()->insert($data, $priority);
return $this;
} | php | {
"resource": ""
} |
q9560 | Migration.getController | train | public function getController() {
if(!empty($this->controller)) {
return $this->controller;
} else {
preg_match('@(?:m[a-zA-Z0-9]{1,})_([a-zA-Z0-9]{1,})_(?:create)_([^/]+)_(?:table)@i', get_class($this), $matches);
return $matches[2];
}
} | php | {
"resource": ""
} |
q9561 | Migration.createAuthItems | train | public function createAuthItems() {
foreach($this->privileges as $privilege) {
$this->insert('AuthItem', [
"name" => $privilege.'::'.$this->getController(),
"type" => 0,
"description" => $privilege.' '.$this->getController(),
"bizrule" => null,
"data" => 'a:2:{s:6:"module";s:'.strlen($this->menu).':"'.$this->menu.'";s:10:"controller";s:'.strlen($this->friendly($this->getController())).':"'.$this->friendly($this->getController()).'";}',
]);
$this->insert('AuthItemChild', [
"parent" => 1,
"child" => $privilege.'::'.$this->getController(),
]);
}
} | php | {
"resource": ""
} |
q9562 | Migration.deleteAuthItems | train | public function deleteAuthItems() {
foreach($this->privileges as $privilege) {
$this->delete(
'AuthItem',"name = '".$privilege.'::'.$this->getController()."'"
);
}
} | php | {
"resource": ""
} |
q9563 | Migration.createAdminMenu | train | public function createAdminMenu() {
$connection = \Yii::$app->db;
$query = new Query;
if(!$this->singleMenu) {
$menu_name = $this->friendly($this->getController());
$menu = $query->from('AdminMenu')
->where('internal=:internal', [':internal'=>$this->menu])
->one();
if(!$menu) {
$query = new Query;
// compose the query
$last_main_menu = $query->from('AdminMenu')
->where('AdminMenu_id IS NULL')
->orderby('order DESC')
->one();
$this->insert('AdminMenu', [
"name" => $this->menu,
"internal" => $this->menu,
"url" => '',
"ap" => 'read::'.$this->getController(),
"order" => $last_main_menu ? $last_main_menu['order'] + 1 : 1
]);
$menu_id = $connection->getLastInsertID();
} else {
$menu_id = $menu['id'];
}
} else {
$menu_id = NULL;
$menu_name = $this->menu;
}
$query = new Query;
$last_menu = $query->from('AdminMenu')
->from('AdminMenu')
->where('AdminMenu_id=:AdminMenu_id', [':AdminMenu_id'=>$menu_id])
->orderby('order DESC')
->one();
$this->insert('AdminMenu', [
"AdminMenu_id" => $menu_id,
"name" => $menu_name,
"internal" => $this->getController() . 'Controller',
"url" => ($this->module ? '/' . $this->module : '' ) . '/'. strtolower(trim(preg_replace("([A-Z])", "-$0", $this->getController()), '-')).'/',
"ap" => 'read::'.$this->getController(),
"order" => $last_menu ? $last_menu['order'] + 1 : 1
]);
} | php | {
"resource": ""
} |
q9564 | ModelCreating.create | train | public function create()
{
event(new BeforeCreate($this));
$this->beforeCreate();
$this->doCreate();
$this->afterCreate();
event(new AfterCreate($this));
} | php | {
"resource": ""
} |
q9565 | Module.onBootstrap | train | public function onBootstrap(MvcEvent $event)
{
$serviceManager = $event->getApplication()->getServiceManager();
$request = $serviceManager->get('request');
if ($request instanceof ConsoleRequest) {
return;
}
//Add Domain Checker
$eventWrapper = $serviceManager->get(
\Rcm\EventListener\EventWrapper::class
);
/** @var \Zend\EventManager\EventManager $eventManager */
$eventManager = $event->getApplication()->getEventManager();
// Check for redirects from the CMS
$eventManager->attach(
MvcEvent::EVENT_ROUTE,
[$eventWrapper, 'routeEvent'],
10000
);
// Set the sites layout.
$eventManager->attach(
MvcEvent::EVENT_DISPATCH,
[$eventWrapper, 'dispatchEvent'],
10000
);
// Set the custom http response checker
$eventManager->attach(
MvcEvent::EVENT_FINISH,
[$eventWrapper, 'finishEvent'],
10000
);
$viewEventManager = $serviceManager->get('ViewManager')
->getView()
->getEventManager();
// Set the plugin response over-ride
$viewEventManager->attach(
ViewEvent::EVENT_RESPONSE,
[$eventWrapper, 'viewResponseEvent'],
-10000
);
// Use the configured session handler.
// Should we really boot this for every request though?
$serviceManager->get(\Rcm\Service\SessionManager::class)->start();
} | php | {
"resource": ""
} |
q9566 | Controller.getCompatibilityId | train | public function getCompatibilityId()
{
$controller = $this->getUniqueId();
if (strpos($controller, "/")) {
$controller = substr($controller, strpos($controller, "/") + 1);
}
return str_replace(' ', '', ucwords(str_replace('-', ' ', $controller)));
} | php | {
"resource": ""
} |
q9567 | Controller.actionIndex | train | public function actionIndex()
{
$this->getSearchCriteria();
$this->layout = static::TABLE_LAYOUT;
return $this->render('index', [
'searchModel' => $this->searchModel,
'dataProvider' => $this->dataProvider,
]);
} | php | {
"resource": ""
} |
q9568 | Controller.getSearchCriteria | train | public function getSearchCriteria()
{
/* setting the default pagination for the page */
if (!Yii::$app->session->get($this->MainModel . 'Pagination')) {
Yii::$app->session->set($this->MainModel . 'Pagination', Yii::$app->getModule('core')->recordsPerPage);
}
$savedQueryParams = Yii::$app->session->get($this->MainModel . 'QueryParams');
if (count($savedQueryParams)) {
$queryParams = $savedQueryParams;
} else {
$queryParams = [substr($this->MainModelSearch, strrpos($this->MainModelSearch, "\\") + 1) => $this->defaultQueryParams];
}
/* use the same filters as before */
if (count(Yii::$app->request->queryParams)) {
$queryParams = array_merge($queryParams, Yii::$app->request->queryParams);
}
if (isset($queryParams['page'])) {
$_GET['page'] = $queryParams['page'];
}
if (Yii::$app->request->getIsPjax()) {
$this->layout = false;
}
Yii::$app->session->set($this->MainModel . 'QueryParams', $queryParams);
$this->searchModel = new $this->MainModelSearch;
$this->dataProvider = $this->searchModel->search($queryParams);
} | php | {
"resource": ""
} |
q9569 | Controller.actionPdf | train | public function actionPdf()
{
$this->getSearchCriteria();
$this->layout = static::BLANK_LAYOUT;
$this->dataProvider->pagination = false;
$content = $this->render('pdf', [
'dataProvider' => $this->dataProvider,
]);
if (isset($_GET['test'])) {
return $content;
} else {
$mpdf = new \mPDF();
$mpdf->WriteHTML($content);
Yii::$app->response->getHeaders()->set('Content-Type', 'application/pdf');
Yii::$app->response->getHeaders()->set('Content-Disposition', 'attachment; filename="' . $this->getCompatibilityId() . '.pdf"');
return $mpdf->Output($this->getCompatibilityId() . '.pdf', 'S');
}
} | php | {
"resource": ""
} |
q9570 | Controller.actionPagination | train | public function actionPagination()
{
Yii::$app->session->set($this->MainModel . 'Pagination', Yii::$app->request->queryParams['records']);
$this->redirect(['index']);
} | php | {
"resource": ""
} |
q9571 | Controller.actionCreate | train | public function actionCreate()
{
$this->layout = static::FORM_LAYOUT;
$model = new $this->MainModel;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$this->afterCreate($model);
if ($this->hasView) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->redirect(['index']);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
} | php | {
"resource": ""
} |
q9572 | Controller.saveHistory | train | public function saveHistory($model, $historyField)
{
if (isset($model->{$historyField})) {
$url_components = explode("\\", get_class($model));
$url_components[2] = trim(preg_replace("([A-Z])", " $0", $url_components[2]), " ");
$history = new History;
$history->name = $model->{$historyField};
$history->type = $url_components[2];
$history->url = Url::toRoute(['update', 'id' => $model->id]);
$history->save();
}
} | php | {
"resource": ""
} |
q9573 | Controller.actionUpdate | train | public function actionUpdate($id)
{
$this->layout = static::FORM_LAYOUT;
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$this->afterUpdate($model);
if ($this->hasView) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->redirect(['index']);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
} | php | {
"resource": ""
} |
q9574 | Controller.allButtons | train | public function allButtons()
{
$buttons = [];
if (\Yii::$app->user->checkAccess('read::' . $this->getCompatibilityId())) {
$buttons['pdf'] = [
'text' => 'Download PDF',
'url' => Url::toRoute(['pdf']),
'options' => [
'target' => '_blank',
]
];
$buttons['csv'] = [
'text' => 'Download CSV',
'url' => Url::toRoute(['csv']),
'options' => [
'target' => '_blank',
]
];
}
return $buttons;
} | php | {
"resource": ""
} |
q9575 | DispatchListener.setSiteLayout | train | public function setSiteLayout(MvcEvent $event)
{
/** @var \Zend\View\Model\ViewModel $viewModel */
$viewModel = $event->getViewModel();
/* Add on for non CMS pages */
$fakePage = new Page(
Tracking::UNKNOWN_USER_ID,
'Fake page for non CMS pages in ' . get_class($this)
);
$fakeRevision = new Revision(
Tracking::UNKNOWN_USER_ID,
'Fake revision for non CMS pages in ' . get_class($this)
);
$fakePage->setCurrentRevision($fakeRevision);
$currentSite = $this->getCurrentSite();
$viewModel->setVariable('page', $fakePage);
$viewModel->setVariable('site', $currentSite);
$template = $this->getSiteLayoutTemplate();
$viewModel->setTemplate('layout/' . $template);
return null;
} | php | {
"resource": ""
} |
q9576 | UserController.getUserById | train | private function getUserById($id)
{
$user = $this->userService->findUserById($id);
if (empty($user)) {
throw $this->createNotFoundException('user not found');
}
return $user;
} | php | {
"resource": ""
} |
q9577 | Asset.getAsset | train | public function getAsset($asset)
{
if (!isset($this->assetCache[$asset])) {
$this->assetCache[$asset] = $this->assetRepository->createAsset($asset);
}
return $this->assetCache[$asset];
} | php | {
"resource": ""
} |
q9578 | Formatter.formatSeoUrl | train | public static function formatSeoUrl($name)
{
$url = mb_strtolower($name);
$url = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $url);
$url = preg_replace("/[^a-z0-9_\s-]/", "", $url);
$url = preg_replace("/[\s-]+/", " ", $url);
$url = trim($url);
return preg_replace("/[\s_]/", "-", $url);
} | php | {
"resource": ""
} |
q9579 | UserEmailTransformer.transform | train | public function transform($user)
{
if (empty($user)) {
$className = $this->userService->getUserClass();
return new $className();
}
return $user;
} | php | {
"resource": ""
} |
q9580 | ForkableExtEventLoop.subscribeStreamEvent | train | private function subscribeStreamEvent($stream, $flag)
{
$key = (int) $stream;
if (isset($this->streamEvents[$key])) {
$event = $this->streamEvents[$key];
$flags = ($this->streamFlags[$key] |= $flag);
$event->del();
$event->set($this->eventBase, $stream, Event::PERSIST | $flags, $this->streamCallback);
} else {
$event = new Event($this->eventBase, $stream, Event::PERSIST | $flag, $this->streamCallback);
$this->streamEvents[$key] = $event;
$this->streamFlags[$key] = $flag;
}
$event->add();
} | php | {
"resource": ""
} |
q9581 | ForkableExtEventLoop.unsubscribeStreamEvent | train | private function unsubscribeStreamEvent($stream, $flag)
{
$key = (int) $stream;
$flags = $this->streamFlags[$key] &= ~$flag;
if (0 === $flags) {
$this->removeStream($stream);
return;
}
$event = $this->streamEvents[$key];
$event->del();
$event->set($this->eventBase, $stream, Event::PERSIST | $flags, $this->streamCallback);
$event->add();
} | php | {
"resource": ""
} |
q9582 | FontAwesomeIconEnumerator.enumFonts | train | public static function enumFonts() {
return [
FontAwesomeIconInterface::FONT_AWESOME_FONT,
FontAwesomeIconInterface::FONT_AWESOME_FONT_BOLD,
FontAwesomeIconInterface::FONT_AWESOME_FONT_LIGHT,
FontAwesomeIconInterface::FONT_AWESOME_FONT_REGULAR,
FontAwesomeIconInterface::FONT_AWESOME_FONT_SOLID,
];
} | php | {
"resource": ""
} |
q9583 | ActiveRecord.deleteInternal | train | public function deleteInternal()
{
$result = false;
if ($this->beforeDelete()) {
// we do not check the return value of deleteAll() because it's possible
// the record is already deleted in the database and thus the method will return 0
$condition = $this->getOldPrimaryKey(true);
$lock = $this->optimisticLock();
if ($lock !== null) {
$condition[$lock] = $this->$lock;
}
$this->status = self::STATUS_DELETED;
$result = $this->save(false);
if ($lock !== null && !$result) {
throw new StaleObjectException('The object being deleted is outdated.');
}
$this->setOldAttributes(null);
$this->afterDelete();
}
return $result;
} | php | {
"resource": ""
} |
q9584 | CommentMutators.getAuthorAttribute | train | public function getAuthorAttribute()
{
return (object) [
'name' => is_int($this->user_id) ? $this->user->name : $this->name,
'profile' => is_int($this->user_id) ? $this->user->profile : $this->name,
'avatar' => is_int($this->user_id) ? $this->user->avatar : get_avatar($this->email),
'isOnline' => is_int($this->user_id) ? $this->user->isOnline() : false,
];
} | php | {
"resource": ""
} |
q9585 | NearbyStops.setCoordinate | train | public function setCoordinate(Coordinate $coordinate): self
{
$this->options['coordX'] = $coordinate->getLatitude();
$this->options['coordY'] = $coordinate->getLongitude();
return $this;
} | php | {
"resource": ""
} |
q9586 | OAuthGuard.onAuthenticationSuccess | train | public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$user = $token->getUser();
$this->dispatcher->dispatch(self::OAUTH_LOGIN_SUCCESS, new UserEvent($user));
return $this->authResponseService->authenticateResponse($user,
new Response($this->twig->render('@StarterKitStart/oauth-success.html.twig')));
} | php | {
"resource": ""
} |
q9587 | OAuthGuard.onAuthenticationFailure | train | public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$this->dispatcher->dispatch(self::OAUTH_LOGIN_FAILURE, new AuthFailedEvent($request, $exception));
return $this->removeAuthCookieFromResponse(new Response(
$this->twig->render('@StarterKitStart/oauth-failure.html.twig', ['login_path' => $this->loginPath])
));
} | php | {
"resource": ""
} |
q9588 | OAuthGuard.start | train | public function start(Request $request, AuthenticationException $authException = null)
{
return new Response(
$this->twig->render('@StarterKitStart/oauth-start.html.twig', ['login_path' => $this->loginPath])
);
} | php | {
"resource": ""
} |
q9589 | DefaultController.actionLogin | train | public function actionLogin()
{
$model = new LoginForm();
//make the captcha required if the unsuccessful attempts are more of thee
if ($this->getLoginAttempts() >= $this->module->attemptsBeforeCaptcha) {
$model->scenario = 'withCaptcha';
}
if(Yii::$app->request->post()) {
if($model->load($_POST) && $model->login()) {
$this->setLoginAttempts(0); //if login is successful, reset the attempts
return $this->goBack();
} else {
//if login is not successful, increase the attempts
$this->setLoginAttempts($this->getLoginAttempts() + 1);
}
}
return $this->render('login', [
'model' => $model,
]);
} | php | {
"resource": ""
} |
q9590 | PagePermissionsController.pagePermissionsAction | train | public function pagePermissionsAction()
{
$view = new ViewModel();
//fixes rendering site's header and footer in the dialog
$view->setTerminal(true);
/** @var \Rcm\Entity\Site $currentSite */
$currentSite = $this->getServiceLocator()->get(
\Rcm\Service\CurrentSite::class
);
$currentSiteId = $currentSite->getSiteId();
$sourcePageName = $this->getEvent()
->getRouteMatch()
->getParam(
'rcmPageName',
'index'
);
$pageType = $this->getEvent()
->getRouteMatch()
->getParam(
'rcmPageType',
'n'
);
/** @var ResourceName $resourceName */
$resourceName = $this->getServiceLocator()->get(
ResourceName::class
);
$resourceId = $resourceName->get(
ResourceName::RESOURCE_SITES,
$currentSiteId,
ResourceName::RESOURCE_PAGES,
$pageType,
$sourcePageName
);
/** @var \RcmUser\Acl\Service\AclDataService $aclDataService */
$aclDataService = $this->getServiceLocator()->get(
\RcmUser\Acl\Service\AclDataService::class
);
//getting all set rules by resource Id
$rules = $aclDataService->getRulesByResource($resourceId)->getData();
//getting list of all dynamically created roles
$allRoles = $aclDataService->getNamespacedRoles()->getData();
$rolesHasRules = [];
foreach ($rules as $setRuleFor) {
//getting only the ones that are allow
if ($setRuleFor->getRule() == 'allow') {
$rolesHasRules[] = $setRuleFor->getRoleId();
}
}
$selectedRoles = [];
foreach ($allRoles as $key => $role) {
$roleId = $role->getRoleId();
if (in_array($roleId, $rolesHasRules)) {
$selectedRoles[$roleId] = $role;
}
}
$data = [
'siteId' => $currentSiteId,
'pageType' => $pageType,
'pageName' => $sourcePageName,
'roles' => $allRoles,
'selectedRoles' => $selectedRoles,
];
$view->setVariable('data', $data);
$view->setVariable(
'rcmPageName',
$sourcePageName
);
$view->setVariable(
'rcmPageType',
$pageType
);
return $view;
} | php | {
"resource": ""
} |
q9591 | BaseUser.singleView | train | public function singleView()
{
return [
'id' => $this->getId(),
'displayName' => $this->getDisplayName(),
'roles' => $this->getRoles(),
'email' => $this->getEmail(),
'bio' => $this->getBio()
];
} | php | {
"resource": ""
} |
q9592 | FormFactory.updateCron | train | public function updateCron(
EdgarEzCron $data,
?string $name = null
): ?FormInterface {
$name = $name ?: sprintf('update-cron-%s', $data->getAlias());
return $this->formFactory->createNamed(
$name,
CronType::class,
$data,
[
'method' => Request::METHOD_POST,
'csrf_protection' => true,
]
);
} | php | {
"resource": ""
} |
q9593 | EntityMetadataMiner.isLinkOnlyRelation | train | private static function isLinkOnlyRelation(
\ReflectionClass $class,
$name
)
{
$getterName = 'get' . Inflector::camelize($name);
return !$class->hasMethod($getterName)
|| !Reflection::isMethodGetter($class->getMethod($getterName));
} | php | {
"resource": ""
} |
q9594 | Autoloader.attachNamespace | train | public function attachNamespace($namespace, $paths)
{
if (isset($this->namespaces[$namespace])) {
if (is_array($paths)) {
$this->namespaces[$namespace] = array_merge($this->namespaces[$namespace], $paths);
} else {
$this->namespaces[$namespace][] = $paths;
}
} else {
$this->namespaces[$namespace] = (array) $paths;
}
return $this;
} | php | {
"resource": ""
} |
q9595 | Autoloader.attachPearPrefixes | train | public function attachPearPrefixes(array $classes)
{
foreach ($classes as $prefix => $paths) {
$this->attachPearPrefix($prefix, $paths);
}
return $this;
} | php | {
"resource": ""
} |
q9596 | Container.setValue | train | public function setValue($name, $value)
{
unset($this->factories[$name]);
$this->cache[$name] = $value;
} | php | {
"resource": ""
} |
q9597 | Container.extend | train | public function extend($name, $extender)
{
if (!is_callable($extender, true)) {
throw new FactoryUncallableException('$extender must appear callable');
}
if (!array_key_exists($name, $this->factories)) {
throw new NotFoundException("No factory available for: $name");
}
$factory = $this->factories[$name];
$newFactory = function (Container $c) use ($extender, $factory) {
return call_user_func($extender, call_user_func($factory, $c), $c);
};
$this->setFactory($name, $newFactory);
return $newFactory;
} | php | {
"resource": ""
} |
q9598 | Container.getKeys | train | public function getKeys()
{
$keys = array_keys($this->cache) + array_keys($this->factories);
return array_unique($keys);
} | php | {
"resource": ""
} |
q9599 | JsonHelper.isValid | train | public static function isValid($string)
{
if (is_int($string) || is_float($string)) {
return true;
}
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.