_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5200 | CrudAbstract.editAction | train | public function editAction($id)
{
$this->initializeScaffolding();
$this->beforeRead();
$this->view->record = $this->scaffolding->doRead($id);
$this->afterRead();
$this->beforeEdit();
$this->view->form = $this->scaffolding->getForm($this->view->record);
$this->afterEdit();
} | php | {
"resource": ""
} |
q5201 | CrudAbstract.updateAction | train | public function updateAction($id)
{
$this->initializeScaffolding();
$this->checkRequest();
try {
$this->beforeRead();
$this->view->record = $this->scaffolding->doRead($id);
$this->afterRead();
$this->beforeUpdate();
$this->scaffolding->doUpdate($id, $this->request->getPost());
$this->flash->success($this->successMessage);
return $this->afterUpdate();
} catch (Exception $e) {
$this->flash->error($e->getMessage());
$this->afterUpdateException();
}
return $this->dispatcher->forward(['action' => 'edit']);
} | php | {
"resource": ""
} |
q5202 | CrudAbstract.deleteAction | train | public function deleteAction($id)
{
$this->initializeScaffolding();
try {
$this->beforeRead();
$this->view->record = $this->scaffolding->doRead($id);
$this->afterRead();
$this->beforeDelete();
$this->scaffolding->doDelete($id);
$this->flash->success($this->successMessage);
return $this->afterDelete();
} catch (Exception $e) {
$this->flash->error($e->getMessage());
return $this->afterDeleteException();
}
} | php | {
"resource": ""
} |
q5203 | DbRef.create | train | public static function create($collection, $id = null, $database = null)
{
if ($collection instanceof \Phalcon\Mvc\Collection) {
$id = $collection->getId();
$collection = $collection->getSource();
}
if ($id instanceof \Phalcon\Mvc\Collection) {
$id = $id->getId();
}
if (!$id instanceof \MongoId && $id !== null) {
$id = new \MongoId($id);
}
return parent::create($collection, $id, $database);
} | php | {
"resource": ""
} |
q5204 | Env.usePath | train | public static function usePath($path)
{
# Use the document root normally set via apache
if ($path === self::PATH_DOCUMENT_ROOT) {
if (empty($_SERVER["DOCUMENT_ROOT"]) || !is_dir($_SERVER["DOCUMENT_ROOT"])) {
throw new \InvalidArgumentException("DOCUMENT_ROOT not defined");
}
static::$path = $_SERVER["DOCUMENT_ROOT"];
return;
}
# Get the full path of the running script and use it's directory
if ($path === self::PATH_PHP_SELF) {
if (empty($_SERVER["PHP_SELF"]) || !$path = realpath($_SERVER["PHP_SELF"])) {
throw new \InvalidArgumentException("PHP_SELF not defined");
}
static::$path = pathinfo($path, PATHINFO_DIRNAME);
return;
}
# Calculate the parent of the vendor directory and use that
if ($path === self::PATH_VENDOR_PARENT) {
static::$path = realpath(__DIR__ . "/../../../..");
return;
}
if (is_dir($path)) {
static::$path = $path;
} else {
throw new \InvalidArgumentException("Invalid path specified");
}
} | php | {
"resource": ""
} |
q5205 | Env.getRevision | train | public static function getRevision($length = 10)
{
$revision = Cache::call("revision", function() {
$path = static::path(".git");
if (!is_dir($path)) {
return;
}
$head = $path . "/HEAD";
if (!file_exists($head)) {
return;
}
$data = File::getContents($head);
if (!preg_match("/ref: ([^\s]+)\s/", $data, $matches)) {
return;
}
$ref = $path . "/" . $matches[1];
if (!file_exists($ref)) {
return;
}
return File::getContents($ref);
});
if ($length > 0) {
return substr($revision, 0, $length);
} else {
return $revision;
}
} | php | {
"resource": ""
} |
q5206 | Env.getVars | train | public static function getVars()
{
if (!is_array(static::$vars)) {
$path = static::path("data/env.json");
try {
$vars = Json::decodeFromFile($path);
} catch(\Exception $e) {
$vars = [];
}
static::$vars = Helper::toArray($vars);
}
return static::$vars;
} | php | {
"resource": ""
} |
q5207 | CmsAuthServiceProvider.registerAuthRepository | train | protected function registerAuthRepository()
{
$this->app->singleton(AuthRepositoryInterface::class, function (Application $app) {
return $app->make(AuthRepository::class);
});
return $this;
} | php | {
"resource": ""
} |
q5208 | CmsAuthServiceProvider.registerCommands | train | protected function registerCommands()
{
$this->app->singleton('cms.commands.user-create', CreateUser::class);
$this->app->singleton('cms.commands.user-delete', DeleteUser::class);
$this->commands([
'cms.commands.user-create',
'cms.commands.user-delete',
]);
return $this;
} | php | {
"resource": ""
} |
q5209 | Validation.is_valid | train | public static function is_valid(array $data, array $validators) {
$gump = self::get_instance();
$gump->validation_rules($validators);
if ($gump->run($data) === false) {
return $gump->get_errors_array(false);
} else {
return true;
}
} | php | {
"resource": ""
} |
q5210 | Libraries.load | train | public static function load($path = BASE_DIR) {
$librariesDir = dirname(dirname($path)) . DS . 'libraries';
foreach (glob($librariesDir . DS . "*.php") as $filename) {
require_once $filename;
}
} | php | {
"resource": ""
} |
q5211 | AuthRepository.getAllUsers | train | public function getAllUsers($withAdmin = false)
{
$query = $this->userModel->query()
->orderBy('email');
if ( ! $withAdmin) {
$query->where('is_superadmin', false);
}
return $query->get();
} | php | {
"resource": ""
} |
q5212 | AuthRepository.getUsersForRole | train | public function getUsersForRole($role, $withAdmin = false)
{
$query = $this->userModel->query()
->orderBy('email')
->whereHas('roles', function ($query) use ($role) {
$query->where('slug', $role);
});
if ( ! $withAdmin) {
$query->where('is_superadmin', false);
}
return $query->get();
} | php | {
"resource": ""
} |
q5213 | AuthRepository.getAllPermissions | train | public function getAllPermissions()
{
$permissions = [];
// Gather and combine all permissions for roles
foreach ($this->roleModel->all() as $role) {
$permissions = array_merge(
$permissions,
array_keys(array_filter($role->getPermissions()))
);
}
// Gather permissions set specifically for users
foreach ($this->userModel->all() as $user) {
$permissions = array_merge(
$permissions,
array_keys(array_filter($user->getPermissions()))
);
}
sort($permissions);
return array_unique($permissions);
} | php | {
"resource": ""
} |
q5214 | AuthRepository.getAllPermissionsForRole | train | public function getAllPermissionsForRole($role)
{
/** @var EloquentRole $role */
$role = $this->getRole($role);
if ( ! $role) {
return [];
}
$permissions = array_keys(array_filter($role->getPermissions()));
sort($permissions);
return $permissions;
} | php | {
"resource": ""
} |
q5215 | AuthRepository.getAllPermissionsForUser | train | public function getAllPermissionsForUser($user)
{
$user = $this->resolveUser($user);
if ( ! $user) {
return [];
}
$permissions = [];
// Get all permissions for the roles this user belongs to
foreach ($user->getRoles() as $role) {
/** @var EloquentRole $role */
$permissions = array_merge(
$permissions,
array_keys(array_filter($role->getPermissions()))
);
}
// Add permissions set specifically for the user
$permissions = array_merge(
$permissions,
array_keys(array_filter($user->getPermissions()))
);
sort($permissions);
return array_unique($permissions);
} | php | {
"resource": ""
} |
q5216 | AuthRepository.resolveUser | train | protected function resolveUser($user)
{
if ($user instanceof UserInterface) {
return $user;
}
if (is_integer($user)) {
$user = $this->sentinel->findById($user);
} else {
$user = $this->sentinel->findByCredentials([
'email' => $user
]);
}
return $user ?: false;
} | php | {
"resource": ""
} |
q5217 | User.signUp | train | public static function signUp(UserId $anId, UserEmail $anEmail, UserPassword $aPassword, array $userRoles)
{
$user = new static($anId, $anEmail, $userRoles, $aPassword);
$user->confirmationToken = new UserToken();
$user->publish(
new UserRegistered(
$user->id(),
$user->email(),
$user->confirmationToken()
)
);
return $user;
} | php | {
"resource": ""
} |
q5218 | User.invite | train | public static function invite(UserId $anId, UserEmail $anEmail, array $userRoles)
{
$user = new static($anId, $anEmail, $userRoles);
$user->invitationToken = new UserToken();
$user->publish(
new UserInvited(
$user->id(),
$user->email(),
$user->invitationToken()
)
);
return $user;
} | php | {
"resource": ""
} |
q5219 | User.acceptInvitation | train | public function acceptInvitation()
{
if ($this->isInvitationTokenAccepted()) {
throw new UserInvitationAlreadyAcceptedException();
}
if ($this->isInvitationTokenExpired()) {
throw new UserTokenExpiredException();
}
$this->invitationToken = null;
$this->updatedOn = new \DateTimeImmutable();
$this->publish(
new UserRegistered(
$this->id(),
$this->email()
)
);
} | php | {
"resource": ""
} |
q5220 | User.changePassword | train | public function changePassword(UserPassword $aPassword)
{
$this->password = $aPassword;
$this->rememberPasswordToken = null;
$this->updatedOn = new \DateTimeImmutable();
} | php | {
"resource": ""
} |
q5221 | User.confirmationToken | train | public function confirmationToken()
{
// This ternary is a hack that avoids the
// DoctrineORM limitation with nullable embeddables
return $this->confirmationToken instanceof UserToken
&& null === $this->confirmationToken->token()
? null
: $this->confirmationToken;
} | php | {
"resource": ""
} |
q5222 | User.enableAccount | train | public function enableAccount()
{
$this->confirmationToken = null;
$this->updatedOn = new \DateTimeImmutable();
$this->publish(
new UserEnabled(
$this->id,
$this->email
)
);
} | php | {
"resource": ""
} |
q5223 | User.grant | train | public function grant(UserRole $aRole)
{
if (false === $this->isRoleAllowed($aRole)) {
throw new UserRoleInvalidException();
}
if (true === $this->isGranted($aRole)) {
throw new UserRoleAlreadyGrantedException();
}
$this->roles[] = $aRole;
$this->updatedOn = new \DateTimeImmutable();
$this->publish(
new UserRoleGranted(
$this->id,
$this->email,
$aRole
)
);
} | php | {
"resource": ""
} |
q5224 | User.invitationToken | train | public function invitationToken()
{
// This ternary is a hack that avoids the
// DoctrineORM limitation with nullable embeddables
return $this->invitationToken instanceof UserToken
&& null === $this->invitationToken->token()
? null
: $this->invitationToken;
} | php | {
"resource": ""
} |
q5225 | User.isInvitationTokenExpired | train | public function isInvitationTokenExpired()
{
if (!$this->invitationToken() instanceof UserToken) {
throw new UserTokenNotFoundException();
}
return $this->invitationToken->isExpired(
$this->invitationTokenLifetime()
);
} | php | {
"resource": ""
} |
q5226 | User.isRememberPasswordTokenExpired | train | public function isRememberPasswordTokenExpired()
{
if (!$this->rememberPasswordToken() instanceof UserToken) {
throw new UserTokenNotFoundException();
}
return $this->rememberPasswordToken->isExpired(
$this->rememberPasswordTokenLifetime()
);
} | php | {
"resource": ""
} |
q5227 | User.login | train | public function login($aPlainPassword, UserPasswordEncoder $anEncoder)
{
if (false === $this->isEnabled()) {
throw new UserInactiveException();
}
if (false === $this->password()->equals($aPlainPassword, $anEncoder)) {
throw new UserPasswordInvalidException();
}
$this->lastLogin = new \DateTimeImmutable();
$this->publish(
new UserLoggedIn(
$this->id,
$this->email
)
);
} | php | {
"resource": ""
} |
q5228 | User.logout | train | public function logout()
{
if (false === $this->isEnabled()) {
throw new UserInactiveException();
}
$this->publish(
new UserLoggedOut(
$this->id,
$this->email
)
);
} | php | {
"resource": ""
} |
q5229 | User.regenerateInvitationToken | train | public function regenerateInvitationToken()
{
if (null === $this->invitationToken()) {
throw new UserInvitationAlreadyAcceptedException();
}
$this->invitationToken = new UserToken();
$this->publish(
new UserInvitationTokenRegenerated(
$this->id,
$this->email,
$this->invitationToken
)
);
} | php | {
"resource": ""
} |
q5230 | User.rememberPasswordToken | train | public function rememberPasswordToken()
{
// This ternary is a hack that avoids the
// DoctrineORM limitation with nullable embeddables
return $this->rememberPasswordToken instanceof UserToken
&& null === $this->rememberPasswordToken->token()
? null
: $this->rememberPasswordToken;
} | php | {
"resource": ""
} |
q5231 | User.rememberPassword | train | public function rememberPassword()
{
$this->rememberPasswordToken = new UserToken();
$this->publish(
new UserRememberPasswordRequested(
$this->id,
$this->email,
$this->rememberPasswordToken
)
);
} | php | {
"resource": ""
} |
q5232 | ElectronicAddressValidator.isValid | train | public function isValid($value)
{
if ($value instanceof ElectronicAddress) {
$addressType = $value->getType();
switch ($addressType) {
case 'Email':
$addressValidator = $this->validatorResolver->createValidator('EmailAddress');
break;
default:
$addressValidator = $this->validatorResolver->createValidator('Neos.Party:' . $addressType . 'Address');
}
if ($addressValidator === null) {
$this->addError('No validator found for electronic address of type "' . $addressType . '".', 1268676030);
} else {
$result = $addressValidator->validate($value->getIdentifier());
if ($result->hasErrors()) {
$this->result = $result;
}
}
}
} | php | {
"resource": ""
} |
q5233 | CompletePurchaseResponse.isSuccessful | train | public function isSuccessful()
{
return $this->data->getStatus() === InvoiceInterface::STATUS_CONFIRMED || $this->data->getStatus() === InvoiceInterface::STATUS_COMPLETE;
} | php | {
"resource": ""
} |
q5234 | CompletePurchaseResponse.getTime | train | public function getTime()
{
$time = $this->data->getInvoiceTime();
if ($time instanceof \DateTime) {
return $time->format('c');
}
return date('c', $time/1000); // time in ms
} | php | {
"resource": ""
} |
q5235 | SentinelServiceProvider.registerSentinel | train | protected function registerSentinel()
{
$this->app->singleton('sentinel', function ($app) {
// @codeCoverageIgnoreStart
$sentinel = new Sentinel(
$app['sentinel.persistence'],
$app['sentinel.users'],
$app['sentinel.roles'],
$app['sentinel.activations'],
$app['events']
);
if (isset($app['sentinel.checkpoints'])) {
foreach ($app['sentinel.checkpoints'] as $key => $checkpoint) {
$sentinel->addCheckpoint($key, $checkpoint);
}
}
$sentinel->setActivationRepository($app['sentinel.activations']);
$sentinel->setReminderRepository($app['sentinel.reminders']);
$sentinel->setRequestCredentials(function () use ($app) {
$request = $app['request'];
$login = $request->getUser();
$password = $request->getPassword();
if ($login === null && $password === null) {
return null;
}
return compact('login', 'password');
});
$sentinel->creatingBasicResponse(function () {
$headers = ['WWW-Authenticate' => 'Basic'];
return response('Invalid credentials.', 401, $headers);
});
return $sentinel;
// @codeCoverageIgnoreEnd
});
// no alias
} | php | {
"resource": ""
} |
q5236 | SentinelServiceProvider.registerUsers | train | protected function registerUsers()
{
$this->registerHasher();
$this->app->singleton('sentinel.users', function ($app) {
$config = $app['config']->get('cartalyst.sentinel');
$users = array_get($config, 'users.model');
$roles = array_get($config, 'roles.model');
$persistences = array_get($config, 'persistences.model');
$permissions = array_get($config, 'permissions.class');
if (class_exists($roles) && method_exists($roles, 'setUsersModel')) {
forward_static_call_array([$roles, 'setUsersModel'], [$users]);
}
if (class_exists($persistences) && method_exists($persistences, 'setUsersModel')) {
forward_static_call_array([$persistences, 'setUsersModel'], [$users]);
}
if (class_exists($users) && method_exists($users, 'setPermissionsClass')) {
forward_static_call_array([$users, 'setPermissionsClass'], [$permissions]);
}
return new IlluminateUserRepository($app['sentinel.hasher'], $app['events'], $users);
});
} | php | {
"resource": ""
} |
q5237 | StagedQueryBuilder.withAddedStep | train | protected function withAddedStep(string $stage, callable $step, bool $replace = false)
{
$clone = clone $this;
if ($replace) {
$clone->stages[$stage] = [];
}
$clone->stages[$stage][] = $step;
return $clone;
} | php | {
"resource": ""
} |
q5238 | StagedQueryBuilder.withFilteredSteps | train | public function withFilteredSteps(callable $matcher)
{
$clone = clone $this;
foreach ($clone->stages as $stage => &$steps) {
$steps = array_filter($steps, function ($step) use ($matcher, $stage) {
return $matcher($stage, $step);
});
}
return $clone;
} | php | {
"resource": ""
} |
q5239 | StagedQueryBuilder.buildQuery | train | public function buildQuery(iterable $filter, array $opts = [])
{
return Pipeline::with($this->stages)
->flatten()
->reduce(function($data, callable $step) use ($opts) {
return $step($data, $opts);
}, $filter);
} | php | {
"resource": ""
} |
q5240 | AppFactory.buildFromContainer | train | public static function buildFromContainer(ContainerInterface $container): App
{
return new App(
self::request($container),
self::response($container),
self::processor($container),
self::matchableRequest($container),
self::errorHandler($container),
self::invalidRequestHandler($container),
self::streamReadLength($container)
);
} | php | {
"resource": ""
} |
q5241 | AppFactory.request | train | private static function request(ContainerInterface $container): ServerRequestInterface
{
if (!$container->has(ServerRequestInterface::class)) {
throw new InvalidArgumentException('Moon received an invalid request instance from the container');
}
return $container->get(ServerRequestInterface::class);
} | php | {
"resource": ""
} |
q5242 | AppFactory.response | train | private static function response(ContainerInterface $container): ResponseInterface
{
if (!$container->has(ResponseInterface::class)) {
throw new InvalidArgumentException('Moon received an invalid response instance from the container');
}
return $container->get(ResponseInterface::class);
} | php | {
"resource": ""
} |
q5243 | AppFactory.processor | train | private static function processor(ContainerInterface $container): ProcessorInterface
{
if (!$container->has(ProcessorInterface::class)) {
return new WebProcessor($container);
}
return $container->get(ProcessorInterface::class);
} | php | {
"resource": ""
} |
q5244 | AppFactory.errorHandler | train | private static function errorHandler(ContainerInterface $container): ErrorHandlerInterface
{
if (!$container->has(ErrorHandlerInterface::class)) {
return new ErrorHandler();
}
return $container->get(ErrorHandlerInterface::class);
} | php | {
"resource": ""
} |
q5245 | AppFactory.invalidRequestHandler | train | private static function invalidRequestHandler(ContainerInterface $container): InvalidRequestHandlerInterface
{
if (!$container->has(InvalidRequestHandlerInterface::class)) {
return new InvalidRequestHandler();
}
return $container->get(InvalidRequestHandlerInterface::class);
} | php | {
"resource": ""
} |
q5246 | AppFactory.matchableRequest | train | private static function matchableRequest(ContainerInterface $container): MatchableRequestInterface
{
if (!$container->has(MatchableRequestInterface::class)) {
return new MatchableRequest($container->get(ServerRequestInterface::class));
}
return $container->get(MatchableRequestInterface::class);
} | php | {
"resource": ""
} |
q5247 | AppFactory.streamReadLength | train | private static function streamReadLength(ContainerInterface $container): ? int
{
return $container->has(self::STREAM_READ_LENGTH) ? $container->get(self::STREAM_READ_LENGTH) : null;
} | php | {
"resource": ""
} |
q5248 | SelfInitializingFixtureTrait.getFixtureFingerprintArguments | train | protected function getFixtureFingerprintArguments(array $arguments)
{
$fingerprintArguments = array();
foreach ($arguments as $arg) {
if (is_object($arg) && method_exists($arg, '__toString')) {
$fingerprintArg = (string)$arg;
} else {
$fingerprintArg = $arg;
}
$fingerprintArguments[] = $fingerprintArg;
}
return $fingerprintArguments;
} | php | {
"resource": ""
} |
q5249 | LdapClient.bind | train | public function bind($bindUser = null, $bindPass = null)
{
if (false === ldap_bind($this->ldapResource, $bindUser, $bindPass)) {
throw new LdapClientException(
sprintf(
'LDAP error: (%d) %s',
ldap_errno($this->ldapResource),
ldap_error($this->ldapResource)
)
);
}
} | php | {
"resource": ""
} |
q5250 | Session.getFlash | train | public function getFlash($key) {
if ($this->has($key)) {
$flashData = $_SESSION[$key];
$this->delete($key);
return $flashData;
}
} | php | {
"resource": ""
} |
q5251 | LoaderInitializerTrait.initLoader | train | public function initLoader(Config $config)
{
$loader = new Loader();
$loader->registerDirs(
[
$config->application->libraryDir,
$config->application->pluginDir,
$config->application->taskDir
]
)->register();
} | php | {
"resource": ""
} |
q5252 | PartyRepository.findOneHavingAccount | train | public function findOneHavingAccount(Account $account)
{
$query = $this->createQuery();
return $query->matching($query->contains('accounts', $account))->execute()->getFirst();
} | php | {
"resource": ""
} |
q5253 | ConfiguredFieldMap.apply | train | protected function apply(iterable $iterable): iterable
{
return Pipeline::with($iterable)
->mapKeys(function($_, $info) {
$field = is_array($info) ? ($info['field'] ?? null) : $info;
$newField = $this->map[$field] ?? ($this->dynamic ? $field : null);
return isset($newField) && is_array($info) ? ['field' => $newField] + $info : $newField;
})
->filter(function($_, $info) {
return $info !== null;
});
} | php | {
"resource": ""
} |
q5254 | Router.addRoute | train | public function addRoute(array $routeArray)
{
$routeKeys = array_keys($routeArray);
$routeValues = array_values($routeArray);
$routeName = reset($routeKeys);
$route = reset($routeValues);
$this->routes[$routeName] = $route;
return $this;
} | php | {
"resource": ""
} |
q5255 | Router.addModuleRoutes | train | public function addModuleRoutes(array $module)
{
$routeArray = $this->getRouteArrayFromModulePath($module['path']);
$this->addRoutes($routeArray);
return $this;
} | php | {
"resource": ""
} |
q5256 | Router.getRouteArrayFromModulePath | train | private function getRouteArrayFromModulePath($path)
{
$path = dirname($path).'/config/routes.php';
if (file_exists($path) && is_file($path)) {
return require $path;
}
return array();
} | php | {
"resource": ""
} |
q5257 | Router.groupRoutes | train | private function groupRoutes()
{
$routes = array();
foreach ($this->routeTypes as $type => $typeName) {
$routes[$type] = array();
}
foreach ($this->routes as $routePattern => $route) {
if (!isset($route['type'])) {
$route['type'] = Router::BASE_ROUTE;
}
$this->validateRouteType($route['type']);
$routes[$route['type']][$routePattern] = $route;
}
$this->routes = $routes;
} | php | {
"resource": ""
} |
q5258 | Router.setup | train | public function setup()
{
$this->groupRoutes();
foreach ($this->routes as $type => $routes) {
foreach ($routes as $name => $route) {
$newRoute = new Route($name, $route);
if (!$newRoute->hasParam('hostname')) {
$newRoute->setParam('hostname', $this->resolveDefaultHostName());
}
$routeType = $this->resolveRouteType($type);
$routeType->add($this->getRouter(), $newRoute);
}
}
} | php | {
"resource": ""
} |
q5259 | Router.resolveRouteType | train | private function resolveRouteType($routeType)
{
$typeClassName = sprintf('%sRoute', ucfirst($routeType));
$classNamespace = __NAMESPACE__ . '\\Router\\Route\\' . $typeClassName;
if (!array_key_exists($classNamespace, $this->resolvedTypes)) {
$reflectionClass = new \ReflectionClass($classNamespace);
$this->resolvedTypes[$classNamespace] = $reflectionClass->newInstance();
}
return $this->resolvedTypes[$classNamespace];
} | php | {
"resource": ""
} |
q5260 | Cookie.get | train | public static function get($key) {
return self::has($key) ? self::decode($_COOKIE[$key]) : NULL;
} | php | {
"resource": ""
} |
q5261 | Cookie.set | train | public static function set($key, $value = '', $time = 0, $path = '/', $domain = '', $secure = FALSE, $httponly = FALSE) {
return setcookie($key, self::encode($value), time() + $time, $path, $domain, $secure, $httponly);
} | php | {
"resource": ""
} |
q5262 | Cookie.delete | train | public static function delete($key, $path = '/') {
if (self::has($key)) {
setcookie($key, '', time() - 3600, $path);
}
} | php | {
"resource": ""
} |
q5263 | Cookie.flush | train | public static function flush() {
if (count($_COOKIE) > 0) {
foreach ($_COOKIE as $key => $value) {
self::delete($key, '/');
}
}
} | php | {
"resource": ""
} |
q5264 | App.run | train | public function run(MatchablePipelineCollectionInterface $pipelines): ResponseInterface
{
try {
// If a pipeline match print the response and return
if ($handledResponse = $this->handlePipeline($pipelines)) {
return $handledResponse;
}
// If a route pattern matched but the http verbs was different, print a '405 response'
// If no route pattern matched, print a '404 response'
$statusCode = $this->matchableRequest->isPatternMatched() ? StatusCodeInterface::STATUS_METHOD_NOT_ALLOWED : StatusCodeInterface::STATUS_NOT_FOUND;
return $this->invalidRequestHandler->__invoke($this->matchableRequest->request(), $this->response->withStatus($statusCode));
} catch (Throwable $e) {
return $this->errorHandler->__invoke($e, $this->request, $this->response);
}
} | php | {
"resource": ""
} |
q5265 | App.handlePipeline | train | private function handlePipeline(MatchablePipelineCollectionInterface $pipelines): ?ResponseInterface
{
/** @var MatchablePipelineInterface $pipeline */
foreach ($pipelines as $pipeline) {
if ($pipeline->matchBy($this->matchableRequest)) {
$stages = \array_merge($this->stages(), $pipeline->stages());
$pipelineResponse = $this->processor->processStages($stages, $this->matchableRequest->request());
if ($pipelineResponse instanceof ResponseInterface) {
return $pipelineResponse;
}
$body = $this->response->getBody();
$body->write($pipelineResponse);
return $this->response->withBody($body);
}
}
return null;
} | php | {
"resource": ""
} |
q5266 | App.sendResponse | train | public function sendResponse(ResponseInterface $response): void
{
// Send all the headers
\http_response_code($response->getStatusCode());
foreach ($response->getHeaders() as $headerName => $headerValues) {
/** @var string[] $headerValues */
foreach ($headerValues as $headerValue) {
\header("$headerName: $headerValue", false);
}
}
// Get the body, rewind it if possible
$body = $response->getBody();
if ($body->isSeekable()) {
$body->rewind();
}
// If the body is not readable do not send any body to the client
if (!$body->isReadable()) {
return;
}
// Send the body (by chunk if specified in the container using streamReadLength value)
if (null === $this->streamReadLength) {
echo $body->__toString();
return;
}
while (!$body->eof()) {
echo $body->read($this->streamReadLength);
}
} | php | {
"resource": ""
} |
q5267 | Qt_Model.fillObjectProps | train | public function fillObjectProps($arguments) {
foreach ($arguments as $key => $value) {
if (!in_array($key, $this->fillable)) {
throw new \Exception(_message(ExceptionMessages::INAPPROPRIATE_PROPERTY, $key));
}
$this->$key = $value;
}
} | php | {
"resource": ""
} |
q5268 | Debug.output | train | public static function output($message, $data = null)
{
if (static::$mode == "html") {
static::html($message, $data);
} else {
static::text($message, $data);
}
} | php | {
"resource": ""
} |
q5269 | Debug.indent | train | protected static function indent()
{
$char = (static::$mode == "html") ? " " : " ";
for ($i = 0; $i < static::$indent; $i++) {
for ($y = 0; $y < 4; $y++) {
echo $char;
}
}
} | php | {
"resource": ""
} |
q5270 | Debug.text | train | public static function text($message, $data = null)
{
if (!static::$on) {
return;
}
echo "--------------------------------------------------------------------------------\n";
static::indent();
echo static::getTime() . " - " . $message . "\n";
if (is_array($data)) {
print_r($data);
} elseif ($data) {
static::indent();
echo " " . $data . "\n";
}
} | php | {
"resource": ""
} |
q5271 | Debug.html | train | public static function html($message, $data = null)
{
if (!static::$on) {
return;
}
echo "<hr>";
echo "<i>";
static::indent();
echo "<b>" . static::getTime() . " - " . $message . "</b>";
if (is_array($data)) {
Html::print_r($data);
} elseif ($data) {
static::indent();
echo " " . $data . "<br>";
}
echo "</i>";
} | php | {
"resource": ""
} |
q5272 | Debug.call | train | public static function call($message, callable $func)
{
$time = microtime(true);
static::output($message . " [START]");
static::$indent++;
$func();
static::$indent--;
static::output($message . " [END] (" . number_format(microtime(true) - $time, 3) . ")");
} | php | {
"resource": ""
} |
q5273 | UserToken.isExpired | train | public function isExpired($lifetime)
{
$interval = $this->createdOn->diff(new \DateTimeImmutable());
return $interval->s >= (int) $lifetime;
} | php | {
"resource": ""
} |
q5274 | Result.resolveMeta | train | protected function resolveMeta(): void
{
expect_type($this->meta, 'callable', \BadMethodCallException::class);
$meta = i\function_call($this->meta);
expect_type($meta, 'array', \UnexpectedValueException::class, "Failed to get meta: Expected %2\$s, got %1\$s");
$this->meta = $meta;
} | php | {
"resource": ""
} |
q5275 | LocaleSubscriber.getLocaleFromTypo3 | train | private function getLocaleFromTypo3(Request $request): ?string
{
$locale = null;
if ((bool) $language = $request->attributes->get('language')) {
/* @var SiteLanguage $language */
[$locale] = \explode('.', $language->getLocale());
} elseif ((bool) $site = $request->attributes->get('site')) {
/* @var Site $site */
[$locale] = \explode('.', $site->getDefaultLanguage()->getLocale());
}
return $locale;
} | php | {
"resource": ""
} |
q5276 | LocaleSubscriber.getDenormalizedLocaleFromTypo3 | train | private function getDenormalizedLocaleFromTypo3(Request $request): ?string
{
if ((bool) $language = $request->attributes->get('language')) {
/* @var SiteLanguage $language */
return \trim($language->getBase()->getPath(), '/');
}
if ((bool) $site = $request->attributes->get('site')) {
/* @var Site $site */
return \trim($site->getDefaultLanguage()->getBase()->getPath(), '/');
}
return null;
} | php | {
"resource": ""
} |
q5277 | W3CMarkupValidator.getValidationData | train | private function getValidationData($markup)
{
$this->httpRequestParameters['body'] = $markup;
$reponse = $this->httpClient->post(
$this->configuration[self::ENDPOINT_CONFIG_KEY],
$this->httpRequestParameters
);
$responseData = $reponse->getBody()->getContents();
$validationData = json_decode($responseData, true);
if ($validationData === null) {
throw new Exception('Unable to parse W3C Markup Validation Service response.');
}
return $validationData;
} | php | {
"resource": ""
} |
q5278 | W3CMarkupValidator.getValidationMessages | train | private function getValidationMessages(array $validationData)
{
$messages = array();
$messagesData = $validationData['messages'];
foreach ($messagesData as $messageData) {
$message = new W3CMarkupValidatorMessage($messageData);
$messages[] = $message;
}
return $messages;
} | php | {
"resource": ""
} |
q5279 | EloquentUser.can | train | public function can($permission, $allowAny = false)
{
if ($allowAny) {
return $this->hasAnyAccess(
is_array($permission) ? $permission : [ $permission ]
);
}
return $this->hasAccess(
is_array($permission) ? $permission : [ $permission ]
);
} | php | {
"resource": ""
} |
q5280 | PersonNameValidator.isValid | train | public function isValid($value)
{
if ($value instanceof PersonName) {
if (strlen(trim($value->getFullName())) === 0) {
$this->addError('The person name cannot be empty.', 1268676765);
}
}
} | php | {
"resource": ""
} |
q5281 | RegisterHelpersTrait.registerHelpers | train | public function registerHelpers()
{
foreach (glob($this->getHelpersDirectoryPath() . '*.php') as $file) {
$helperName = pathinfo($file, PATHINFO_FILENAME);
$this->registerHelper(lcfirst($helperName));
}
} | php | {
"resource": ""
} |
q5282 | EnvironmentInitializerTrait.initEnvironment | train | public function initEnvironment(Config $config)
{
if (isset($config->application) && isset($config->application->environment)) {
$env = $config->application->environment;
} else {
$env = Constants::DEFAULT_ENV;
}
if (!defined('APPLICATION_ENV')) {
define('APPLICATION_ENV', $env);
}
$this->getDI()->set('environment', function() use ($env) {
return $env;
}, true);
} | php | {
"resource": ""
} |
q5283 | Loader.dump | train | public function dump($inputDirectory, $outputDirectory, $dumpVendorModules = true)
{
$modulesList = [];
//extracts list of modules from module directory
$directoryIterator = new \DirectoryIterator($inputDirectory);
foreach ($directoryIterator as $moduleDir) {
if ($moduleDir->isDot()) {
continue;
}
$moduleSettingsFile = $moduleDir->getPathname()
. DIRECTORY_SEPARATOR
. self::MODULE_SETTINGS_FILE;
if (!file_exists($moduleSettingsFile)) {
continue;
}
$modulesList[$moduleDir->getBasename()] = [
'className' => $moduleDir->getBasename()
. '\\'
. pathinfo(self::MODULE_SETTINGS_FILE, PATHINFO_FILENAME),
'path' => $moduleSettingsFile
];
}
if ($dumpVendorModules) {
$this->dumpModulesFromVendor($modulesList);
}
//saves generated array to php source file
FileWriter::writeObject(
$outputDirectory . self::MODULE_STATIC_FILE,
$modulesList,
true
);
return $modulesList;
} | php | {
"resource": ""
} |
q5284 | Loader.dumpModulesFromVendor | train | public function dumpModulesFromVendor(array &$modulesList)
{
if (!file_exists(APP_ROOT.'/composer.json')) {
return $modulesList;
}
$fileContent = file_get_contents(APP_ROOT . DIRECTORY_SEPARATOR . 'composer.json');
$json = json_decode($fileContent, true);
$vendorDir = realpath(APP_ROOT .
(
isset($json['config']['vendor-dir'])
? DIRECTORY_SEPARATOR . $json['config']['vendor-dir']
: DIRECTORY_SEPARATOR.'vendor'
)
);
foreach ($this->getModuleProviders() as $provider) {
$providerDir = $vendorDir . DIRECTORY_SEPARATOR . $provider;
$this->dumpSingleProviderModulesFromVendor($modulesList, $providerDir);
}
return $modulesList;
} | php | {
"resource": ""
} |
q5285 | Loader.dumpSingleProviderModulesFromVendor | train | private function dumpSingleProviderModulesFromVendor(array &$modulesList, $providerDir)
{
$directoryIterator = new \DirectoryIterator($providerDir);
foreach ($directoryIterator as $libDir) {
if ($libDir->isDot()) {
continue;
}
//creates path to Module.php file
$moduleSettingsFile = implode(DIRECTORY_SEPARATOR, [
$providerDir, $libDir, 'module', self::MODULE_SETTINGS_FILE
]);
if (!file_exists($moduleSettingsFile)) {
continue;
}
$baseName = Text::camelize($libDir->getBasename());
if (!isset($modulesList[$baseName])) {
$modulesList[$baseName] = [
'className' => $baseName
. '\\'
. pathinfo(self::MODULE_SETTINGS_FILE, PATHINFO_FILENAME),
'path' => $moduleSettingsFile
];
}
}
} | php | {
"resource": ""
} |
q5286 | Loader.getModuleProviders | train | private function getModuleProviders()
{
$defaultProviders = [
'vegas-cmf'
];
$appConfig = $this->di->get('config')->application;
if (!isset($appConfig->vendorModuleProvider)) {
$providerNames = [];
} else if (is_string($appConfig->vendorModuleProvider)) {
$providerNames = [$appConfig->vendorModuleProvider];
} else {
$providerNames = $appConfig->vendorModuleProvider->toArray();
}
return array_unique(array_merge($defaultProviders, $providerNames));
} | php | {
"resource": ""
} |
q5287 | Curl.getResponseHeaders | train | public function getResponseHeaders() {
$requestHeaders = [];
if ($this->headers instanceof \ArrayAccess) {
while ($this->headers->valid()) {
$requestHeaders[$this->headers->key()] = $this->headers->current();
$this->headers->next();
}
}
return $requestHeaders;
} | php | {
"resource": ""
} |
q5288 | Debugger.runDebuger | train | public static function runDebuger($view = null) {
self::$debugbar = new Debugger();
self::$assets_url = base_url() . '/assets/DebugBar/Resources';
self::addQueries();
self::addMessages();
self::addRoute($view);
self::$debugbarRenderer = self::$debugbar->getJavascriptRenderer()->setBaseUrl(self::$assets_url);
return self::$debugbarRenderer;
} | php | {
"resource": ""
} |
q5289 | Debugger.addQueries | train | private static function addQueries() {
self::$debugbar->addCollector(new MessagesCollector('queries'));
self::$queries = ORM::get_query_log();
if (self::$queries) {
foreach (self::$queries as $query) {
self::$debugbar['queries']->info($query);
}
}
} | php | {
"resource": ""
} |
q5290 | Debugger.addRoute | train | private static function addRoute($view) {
$uri = RouteController::$currentRoute['uri'];
$method = RouteController::$currentRoute['method'];
$module = RouteController::$currentRoute['module'];
$current_controller = 'modules' . DS . $module . DS . RouteController::$currentRoute['controller'];
$current_action = RouteController::$currentRoute['action'];
$args = RouteController::$currentRoute['args'];
$route = [
'Route' => $uri,
'Method' => $method,
'Module' => $module,
'Controller' => $current_controller,
'Action' => $current_action,
'View' => '',
'Args' => $args,
];
if ($view) {
$route['View'] = 'modules/' . RouteController::$currentRoute['module'] . '/Views/' . $view;
}
self::$debugbar->addCollector(new MessagesCollector('routes'));
self::$debugbar['routes']->info($route);
} | php | {
"resource": ""
} |
q5291 | Debugger.addMessages | train | private static function addMessages() {
$out_data = session()->get('output');
if ($out_data) {
foreach ($out_data as $data) {
self::$debugbar['messages']->debug($data);
}
session()->delete('output');
}
} | php | {
"resource": ""
} |
q5292 | ExecuteCommand.execute | train | public function execute(Input $input): void
{
$this->bus->handle(
$this->messageCreator->create($this->command, $input)
);
} | php | {
"resource": ""
} |
q5293 | Scaffolding.processForm | train | private function processForm($values)
{
$form = $this->getForm($this->record);
$form->bind($values, $this->record);
if ($form->isValid()) {
return $this->record->save();
}
$this->form = $form;
throw new InvalidFormException();
} | php | {
"resource": ""
} |
q5294 | Image.resize | train | public static function resize($options = null)
{
$options = Helper::getOptions($options, [
"fromPath" => null,
"toPath" => null,
"width" => null,
"height" => null,
]);
if (!$fromPath = trim($options["fromPath"])) {
throw new \Exception("No from path specified to read from");
}
if (!$toPath = trim($options["toPath"])) {
throw new \Exception("No to path specified to save to");
}
$maxWidth = round($options["width"]);
$maxHeight = round($options["height"]);
list($width, $height, $format) = getimagesize($fromPath);
if ($width < 1 || $height < 1) {
copy($fromPath, $toPath);
return;
}
if ($maxWidth < 1 && $maxHeight < 1) {
copy($fromPath, $toPath);
return;
}
if ($width < $maxWidth && $height < $maxHeight) {
copy($fromPath, $toPath);
return;
}
$newWidth = $width;
$newHeight = $height;
if ($maxHeight && $newHeight > $maxHeight) {
$ratio = $newWidth / $newHeight;
$newHeight = $maxHeight;
$newWidth = $newHeight * $ratio;
}
if ($maxWidth && $newWidth > $maxWidth) {
$ratio = $newHeight / $newWidth;
$newWidth = $maxWidth;
$newHeight = $newWidth * $ratio;
}
$image = static::create($fromPath, $format);
$newImage = imagecreatetruecolor($newWidth, $newHeight);
if ($format != IMAGETYPE_JPEG) {
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$background = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagecolortransparent($newImage, $background);
}
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
static::save($newImage, $toPath, $format);
imagedestroy($image);
imagedestroy($newImage);
} | php | {
"resource": ""
} |
q5295 | Image.img | train | public static function img($options = null)
{
$options = Helper::getOptions($options, [
"path" => "images/img",
"basename" => null,
"filename" => null,
"width" => null,
"height" => null,
]);
$path = $options["path"];
if ($path[0] == "/") {
$fullpath = $path;
} else {
$fullpath = Env::path($path, Env::PATH_DOCUMENT_ROOT);
}
$filename = $options["filename"];
if ($basename = $options["basename"]) {
$original = $fullpath . "/original/" . $basename;
if (file_exists($original)) {
if ($ext = static::getExtension($original)) {
$filename = $basename . "." . $ext;
copy($original, $fullpath . "/original/" . $filename);
}
}
}
if (!$filename) {
throw new \Exception("No image filename provided to use");
}
$original = $fullpath . "/original/" . $filename;
if (!file_exists($original)) {
throw new \Exception("Original image file does not exist (" . $original . ")");
}
$w = $options["width"];
$h = $options["height"];
if (!$w && !$h) {
return $path . "/original/" . $filename;
}
if ($w && $h) {
$dir = "max" . $w . "x" . $h;
} elseif ($w) {
$dir = "width" . $w;
} elseif ($h) {
$dir = "height" . $h;
}
$fullpath .= "/" . $dir;
$newfile = $fullpath . "/" . $filename;
$newpath = $path . "/" . $dir . "/" . $filename;
if (file_exists($newfile)) {
return $newpath;
}
if (!is_dir($fullpath)) {
mkdir($fullpath, 0777, true);
}
static::resize([
"fromPath" => $original,
"toPath" => $newfile,
"width" => $w,
"height" => $h,
]);
return $newpath;
} | php | {
"resource": ""
} |
q5296 | Image.create | train | public static function create($path, $format)
{
switch ($format) {
case IMAGETYPE_JPEG:
$result = imagecreatefromjpeg($path);
break;
case IMAGETYPE_PNG:
$result = imagecreatefrompng($path);
break;
case IMAGETYPE_GIF:
$result = imagecreatefromgif($path);
break;
}
if (!$result) {
throw new \Exception("Failing to create image (" . $path . ")");
}
return $result;
} | php | {
"resource": ""
} |
q5297 | Image.save | train | public static function save($image, $path, $format)
{
switch ($format) {
case IMAGETYPE_JPEG:
$result = imagejpeg($image, $path, 100);
break;
case IMAGETYPE_PNG:
$result = imagepng($image, $path, 9);
break;
case IMAGETYPE_GIF:
$result = imagegif($image, $path);
break;
}
if (!$result) {
throw new \Exception("Failed to save image (" . $path . ")");
}
} | php | {
"resource": ""
} |
q5298 | Image.rotate | train | public static function rotate($path, $rotate = null)
{
if ($rotate === null) {
$exif = exif_read_data($path);
switch ($exif["Orientation"]) {
case 3:
$rotate = 180;
break;
case 6:
$rotate = 90;
break;
case 8:
$rotate = -90;
break;
}
}
if (!$rotate) {
return;
}
$format = getimagesize($path)[2];
$image = static::create($path, $format);
$rotate = imagerotate($image, $rotate * -1, 0);
static::save($rotate, $path, $format);
} | php | {
"resource": ""
} |
q5299 | View._engineRender | train | protected function _engineRender($engines, $viewPath, $silence, $mustClean, $cache)
{
$basePath = $this->_basePath;
$notExists = true;
if (is_object($cache)) {
$renderLevel = intval($this->_renderLevel);
$cacheLevel = intval($this->_cacheLevel);
if ($renderLevel >= $cacheLevel) {
if ($cache->isStarted() === false) {
$viewOptions = $this->_options;
if (is_array($viewOptions)) {
if (isset($viewOptions['cache'])) {
$cacheOptions = $viewOptions['cache'];
if (is_array($cacheOptions)) {
if (isset($cacheOptions['key'])) {
$key = $cacheOptions['key'];
}
if (isset($cacheOptions['lifetime'])) {
$lifeTime = $cacheOptions['lifetime'];
}
}
if (!isset($key) || !$key) {
$key = md5($viewPath);
}
if (!isset($lifeTime)) {
$lifeTime = 0;
}
$cachedView = $cache->start($key, $lifeTime);
if (!$cachedView) {
$this->_content = $cachedView;
return null;
}
}
if (!$cache->isFresh()) {
return null;
}
}
}
}
}
$viewParams = $this->_viewParams;
$eventsManager = $this->_eventsManager;
foreach ($engines as $extension => $engine) {
$viewEnginePath = $basePath . $this->resolveFullViewPath($viewPath) . $extension;
if (file_exists($viewEnginePath)) {
if (is_object($eventsManager)) {
$this->_activeRenderPath = $viewEnginePath;
if ($eventsManager->fire("view:beforeRenderView", $this, $viewEnginePath) === false) {
continue;
}
}
$engine->render($viewEnginePath, $viewParams, $mustClean);
$notExists = false;
if (is_object($eventsManager)) {
$eventsManager->fire("view:afterRenderView", $this);
}
break;
}
}
if ($notExists) {
if (is_object($eventsManager)) {
$this->_activeRenderPath = $viewEnginePath;
$eventsManager->fire("view:notFoundView", $this, $viewEnginePath);
}
if (!$silence) {
throw new Exception(sprintf("View %s was not found in the views directory", $viewEnginePath));
}
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.