_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q268100 | RequestApplication.handleRequest | test | public function handleRequest()
{
//Wait for static application initialization
$staticInitPromise = !Reaction::$app->initialized ? Reaction::$app->initPromise : Reaction\Promise\resolve(true);
return $staticInitPromise
//Load Request app components
->then(function() {
return $this->loadComponents();
//Try to resolve request action
})->then(function() {
return $this->resolveAction();
//Handle exceptions
})->otherwise(function($exception) {
if (Reaction::isConsoleApp() && $exception instanceof Reaction\Exceptions\Http\NotFoundException) {
$exception = new Reaction\Console\UnknownCommandException($this->reqHelper->getUrl(), $this, $exception->getCode(), $exception);
}
return $this->errorHandler->handleException($exception);
//Emit EVENT_REQUEST_END event
})->always(function() {
return $this->emitAndWait(static::EVENT_REQUEST_END, [$this]);
});
} | php | {
"resource": ""
} |
q268101 | RequestApplication.resolveAction | test | public function resolveAction($routePath = null, $method = null, $params = null)
{
$route = $this->createRoute($routePath, $method, $params);
return $route->resolve();
} | php | {
"resource": ""
} |
q268102 | RequestApplication.getHomeUrl | test | public function getHomeUrl()
{
return isset($this->homeUrl) ? $this->homeUrl : Reaction::$app->urlManager->getHomeUrl();
} | php | {
"resource": ""
} |
q268103 | RequestApplication.set | test | public function set($id, $definition)
{
unset($this->_components[$id]);
if ($definition === null) {
unset($this->_definitions[$id]);
return;
}
//Extract definition from DI Definition
if ($definition instanceof \Reaction\DI\Definition) {
$definition = $definition->dumpArrayDefinition();
}
if (is_string($definition)) {
$config = ['class' => $definition];
} elseif (ArrayHelper::isIndexed($definition) && count($definition) === 2) {
$config = $definition[0];
$params = $definition[1];
} else {
$config = $definition;
}
if (is_array($config)) {
$config = ArrayHelper::merge(['app' => $this], $config);
$definition = isset($params) ? [$config, $params] : $config;
}
if (is_object($definition) || is_callable($definition, true)) {
// an object, a class name, or a PHP callable
$this->_definitions[$id] = $definition;
} elseif (is_array($definition)) {
// a configuration array
if (isset($definition['class'])) {
$this->_definitions[$id] = $definition;
} else {
throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
}
} else {
throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
}
} | php | {
"resource": ""
} |
q268104 | ParamUsersRepository.restaureUtilisateur | test | public function restaureUtilisateur($idUser) {
$oQb = $this->createQueryBuilder('U');
$oQb->update()
->set('U.dateSuppression', 'NULL')
->where($oQb->expr()->eq('U.id', $idUser));
$iReturn = $oQb->getQuery()->execute();
return $iReturn;
} | php | {
"resource": ""
} |
q268105 | ParamUsersRepository.getUserById | test | public function getUserById($id) {
$oQB = $this->createQueryBuilder('U');
$oQB->select()
->where($oQB->expr()->eq('U.id', ':id'))
->setParameter(':id', $id);
$aResult = $oQB->getQuery()->getOneOrNullResult();
return $aResult;
} | php | {
"resource": ""
} |
q268106 | ParamUsersRepository.getActive | test | public function getActive() {
$oDelay = new \DateTime('now');
$oDelay->setTimestamp(strtotime('2 minutes ago'));
$oQb = $this->createQueryBuilder('U');
$oQb->select()
->where($oQb->expr()->gt('U.lastActivityAt', ':delay'))
->setParameter(':delay', $oDelay);
return $oQb->getQuery()->getArrayResult();
} | php | {
"resource": ""
} |
q268107 | GettextMoFile.save | test | public function save($messages, $filePath = null)
{
if (false === ($fileHandle = @fopen($filePath, 'wb'))) {
throw new Exception('Unable to write file "' . $filePath . '".');
}
if (false === @flock($fileHandle, LOCK_EX)) {
throw new Exception('Unable to lock file "' . $filePath . '" for reading.');
}
// magic
if ($this->useBigEndian) {
$this->writeBytes($fileHandle, pack('c*', 0x95, 0x04, 0x12, 0xde)); // -107
} else {
$this->writeBytes($fileHandle, pack('c*', 0xde, 0x12, 0x04, 0x95)); // -34
}
// revision
$this->writeInteger($fileHandle, 0);
// message count
$messageCount = count($messages);
$this->writeInteger($fileHandle, $messageCount);
// offset of source message table
$offset = 28;
$this->writeInteger($fileHandle, $offset);
$offset += $messageCount * 8;
$this->writeInteger($fileHandle, $offset);
// hashtable size, omitted
$this->writeInteger($fileHandle, 0);
$offset += $messageCount * 8;
$this->writeInteger($fileHandle, $offset);
// length and offsets for source messages
foreach (array_keys($messages) as $id) {
$length = strlen($id);
$this->writeInteger($fileHandle, $length);
$this->writeInteger($fileHandle, $offset);
$offset += $length + 1;
}
// length and offsets for target messages
foreach ($messages as $message) {
$length = strlen($message);
$this->writeInteger($fileHandle, $length);
$this->writeInteger($fileHandle, $offset);
$offset += $length + 1;
}
// source messages
foreach (array_keys($messages) as $id) {
$this->writeString($fileHandle, $id);
}
// target messages
foreach ($messages as $message) {
$this->writeString($fileHandle, $message);
}
@flock($fileHandle, LOCK_UN);
@fclose($fileHandle);
} | php | {
"resource": ""
} |
q268108 | ListTools.find | test | public static function find($list, $value, $delimiter = ',')
{
return ArrayTools::find(static::toArray($list, $delimiter), $value);
} | php | {
"resource": ""
} |
q268109 | ActiveQueryTrait.findWith | test | public function findWith($with, &$models)
{
$primaryModel = reset($models);
if (!$primaryModel instanceof ActiveRecordInterface) {
/* @var $modelClass ActiveRecordInterface */
$modelClass = $this->modelClass;
$primaryModel = $modelClass::instance();
}
$relations = $this->normalizeRelations($primaryModel, $with);
/* @var $relation ActiveQuery */
$promises = [];
foreach ($relations as $name => $relation) {
if ($relation->asArray === null) {
// inherit asArray from primary query
$relation->asArray($this->asArray);
}
$promises[] = $relation->populateRelation($name, $models);
}
return !empty($promises) ? all($promises) : resolve(true);
} | php | {
"resource": ""
} |
q268110 | DataReader.read | test | public function read()
{
$this->next();
if (!$this->valid()) {
return false;
}
/** @var array|false $fetched */
$fetched = $this->_command->fetchResultsRow($this->_row, CommandInterface::FETCH_ROW, $this->_fetchMode);
return $fetched;
} | php | {
"resource": ""
} |
q268111 | DataReader.readColumn | test | public function readColumn($columnIndex)
{
$this->next();
if (!$this->valid()) {
return false;
}
return $this->_command->fetchResultsRow($this->_row, CommandInterface::FETCH_FIELD, CommandInterface::FETCH_MODE_ASSOC, $columnIndex);
} | php | {
"resource": ""
} |
q268112 | DataReader.readObject | test | public function readObject($className = 'stdClass', $fields = [])
{
$this->next();
if (!$this->valid()) {
return false;
}
$obj = new $className($fields);
foreach ($this->_row as $key => $value) {
$obj->{$key} = $value;
}
return $obj;
} | php | {
"resource": ""
} |
q268113 | DataReader.readAll | test | public function readAll()
{
/** @var array $fetched */
$fetched = $this->_command->fetchResults($this->_results, CommandInterface::FETCH_ALL, $this->_fetchMode);
return $fetched;
} | php | {
"resource": ""
} |
q268114 | DataReader.getColumnCount | test | public function getColumnCount()
{
if (empty($this->_results)) {
return 0;
}
$results = $this->_results;
$firstRow = reset($results);
return count($firstRow);
} | php | {
"resource": ""
} |
q268115 | Schema.findConstraints | test | protected function findConstraints(&$table)
{
$tableName = $this->quoteValue($table->name);
$tableSchema = $this->quoteValue($table->schemaName);
//We need to extract the constraints de hard way since:
//http://www.postgresql.org/message-id/26677.1086673982@sss.pgh.pa.us
$sql = <<<SQL
select
ct.conname as constraint_name,
a.attname as column_name,
fc.relname as foreign_table_name,
fns.nspname as foreign_table_schema,
fa.attname as foreign_column_name
from
(SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, generate_subscripts(ct.conkey, 1) AS s
FROM pg_constraint ct
) AS ct
inner join pg_class c on c.oid=ct.conrelid
inner join pg_namespace ns on c.relnamespace=ns.oid
inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
left join pg_class fc on fc.oid=ct.confrelid
left join pg_namespace fns on fc.relnamespace=fns.oid
left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
where
ct.contype='f'
and c.relname={$tableName}
and ns.nspname={$tableSchema}
order by
fns.nspname, fc.relname, a.attnum
SQL;
return $this->db->createCommand($sql)->queryAll()->then(
function($_constraints) use (&$table) {
$constraints = [];
foreach ($_constraints as $constraint) {
if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
$foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
} else {
$foreignTable = $constraint['foreign_table_name'];
}
$name = $constraint['constraint_name'];
if (!isset($constraints[$name])) {
$constraints[$name] = [
'tableName' => $foreignTable,
'columns' => [],
];
}
$constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name'];
}
foreach ($constraints as $name => $constraint) {
$table->foreignKeys[$name] = array_merge([$constraint['tableName']], $constraint['columns']);
}
return $table;
}
);
} | php | {
"resource": ""
} |
q268116 | Schema.getServerVersionPromised | test | protected function getServerVersionPromised() {
$sql = "SELECT VERSION()";
return $this->db->createCommand($sql)->queryScalar()->then(
function($result) {
$version = preg_match('/PostgreSQL\s?([\d\.\w]+)/', $result, $matches) ? $matches[1] : null;
$this->_serverVersion = $version;
return $version;
}
);
} | php | {
"resource": ""
} |
q268117 | Router.publishRoutes | test | protected function publishRoutes() {
$routes = $this->routes;
$this->parseRoutesData();
$this->dispatcher = $this->createDispatcher(function(\FastRoute\RouteCollector $r) use ($routes) {
foreach ($routes as $routeRow) {
$r->addRoute($routeRow['httpMethod'], $routeRow['route'], $routeRow['handler']);
}
});
} | php | {
"resource": ""
} |
q268118 | Router.parseRoutesData | test | protected function parseRoutesData() {
$routes = $this->routes;
foreach ($routes as $routeData) {
$path = $routeData['route'];
$this->buildPathExpressions($path, true);
}
foreach ($this->_routePaths as &$routePaths) {
$prevCnt = 0;
ArrayHelper::multisort($routePaths, function($row) use (&$prevCnt) {
return count($row['params']);
}, SORT_DESC);
}
} | php | {
"resource": ""
} |
q268119 | Router.buildPathExpressions | test | protected function buildPathExpressions($path, $store = false) {
$segments = $this->routeParser->parse($path);
$expressions = [];
foreach ($segments as $segmentGroup) {
$expression = '';
$params = [];
$staticPart = '/';
$staticPartEnded = false;
foreach ($segmentGroup as $segment) {
if (is_string($segment)) {
$expression .= $segment;
if (!$staticPartEnded) {
$staticPart .= $segment;
}
} elseif (is_array($segment)) {
$staticPartEnded = true;
$expression .= '{' . $segment[0] . '}';
$params[] = $segment[0];
}
}
$staticPart = '/' . trim($staticPart, '/');
if ($store && !empty($params)) {
$row = [
'exp' => $expression,
'params' => $params,
];
$this->_routePaths[$staticPart] = isset($this->_routePaths[$staticPart]) ? $this->_routePaths[$staticPart] : [];
$this->_routePaths[$staticPart][] = $row;
}
$expressions[$expression] = [
'expression' => $expression,
'prefix' => $staticPart,
'params' => $params,
];
}
return $expressions;
} | php | {
"resource": ""
} |
q268120 | NativeContainer.alias | test | public function alias(string $alias, string $serviceId): void
{
self::$aliases[$alias] = $serviceId;
} | php | {
"resource": ""
} |
q268121 | NativeContainer.bind | test | public function bind(Service $service, bool $verify = true): void
{
// If there is no id
if (null === $service->getId()) {
// Throw a new exception
throw new InvalidServiceIdException('Invalid service id provided.');
}
// If we should verify the dispatch
if ($verify) {
// Then verify it
$this->app->dispatcher()->verifyDispatch($service);
}
self::$services[$service->getId()] = $service;
} | php | {
"resource": ""
} |
q268122 | NativeContainer.context | test | public function context(ServiceContext $serviceContext): void
{
$context = $serviceContext->getClass()
?? $serviceContext->getFunction();
$member = $serviceContext->getMethod()
?? $serviceContext->getProperty();
$contextContext = $serviceContext->getContextClass()
?? $serviceContext->getContextFunction();
// If the context index is null then there's no context
if (null === $context || null === $serviceContext->getId()) {
throw new InvalidContextException('Invalid context.');
}
// If the context is the same as the end service dispatch and the
// dispatch isn't static throw an error to disallow this kind of
// context as it will create an endless loop where the dispatcher
// will attempt to create the callable with the dependencies and the
// hasContext check in Container::get() will keep catching it
if ($context === $contextContext && ! $serviceContext->isStatic()) {
throw new EndlessContextLoopException(
'This kind of context will create'
. 'an endless loop where the dispatcher will attempt to create the '
. 'callable with the dependencies and the hasContext check in '
. 'Container::get() will keep catching it: '
. $this->contextServiceId(
$serviceContext->getId(),
$context,
$member
)
);
}
$service = $this->getServiceFromContext(
$serviceContext,
$context,
$member
);
$this->bind($service);
} | php | {
"resource": ""
} |
q268123 | NativeContainer.getServiceFromContext | test | protected function getServiceFromContext(
ServiceContext $serviceContext,
string $context = null,
string $member = null
): Service {
$service = new Service();
$serviceId = $this->contextServiceId(
$serviceContext->getId(),
$context,
$member
);
$service
->setId($serviceId)
->setSingleton($serviceContext->isSingleton())
->setDefaults($serviceContext->getDefaults())
->setName($serviceContext->getName())
->setClass($serviceContext->getContextClass())
->setProperty($serviceContext->getContextProperty())
->setMethod($serviceContext->getContextMethod())
->setFunction($serviceContext->getContextFunction())
->setClosure($serviceContext->getContextClosure())
->setArguments($serviceContext->getArguments())
->setDependencies($serviceContext->getDependencies())
->setStatic($serviceContext->isStatic());
return $service;
} | php | {
"resource": ""
} |
q268124 | NativeContainer.has | test | public function has(string $serviceId): bool
{
return isset(self::$services[$serviceId]) || isset(self::$aliases[$serviceId]);
} | php | {
"resource": ""
} |
q268125 | NativeContainer.hasContext | test | public function hasContext(string $serviceId, string $context, string $member = null): bool
{
$contextIndex = $this->contextServiceId($serviceId, $context, $member);
return isset(self::$services[$contextIndex]);
} | php | {
"resource": ""
} |
q268126 | NativeContainer.get | test | public function get(string $serviceId, array $arguments = null, string $context = null, string $member = null)
{
// If there is a context set for this context and member combination
if (
null !== $context
&& $this->hasContext(
$serviceId,
$context,
$member
)
) {
// Return that context
return $this->get(
$this->contextServiceId($serviceId, $context, $member),
$arguments
);
}
// If there is a context set for this context only
if (null !== $context && $this->hasContext($serviceId, $context)) {
// Return that context
return $this->get(
$this->contextServiceId($serviceId, $context),
$arguments
);
}
// If the service is a singleton
if ($this->isSingleton($serviceId)) {
// Return the singleton
return $this->getSingleton($serviceId);
}
// If this service is an alias
if ($this->isAlias($serviceId)) {
// Return the appropriate service
return $this->get(
self::$aliases[$serviceId],
$arguments,
$context,
$member
);
}
// If the service is in the container
if ($this->has($serviceId)) {
// Return the made service
return $this->make($serviceId, $arguments);
}
// Check if the service id is provided by a deferred service provider
if ($this->isProvided($serviceId)) {
return $this->getProvided(
$serviceId,
$arguments,
$context,
$member
);
}
// If there are no argument return a new object
if (null === $arguments) {
return new $serviceId();
}
// Return a new object with the arguments
return new $serviceId(...$arguments);
} | php | {
"resource": ""
} |
q268127 | NativeContainer.make | test | public function make(string $serviceId, array $arguments = null)
{
$service = self::$services[$serviceId];
$arguments = $service->getDefaults() ?? $arguments;
// Dispatch before make event
$this->app->events()->trigger(
ServiceMake::class,
[$serviceId, $service, $arguments]
);
// Make the object by dispatching the service
$made =
$this->app->dispatcher()->dispatchCallable($service, $arguments);
// Dispatch after make event
$this->app->events()->trigger(ServiceMade::class, [$serviceId, $made]);
// If the service is a singleton
if ($service->isSingleton()) {
$this->app->events()->trigger(
ServiceMadeSingleton::class,
[$serviceId, $made]
);
// Set singleton
$this->singleton($serviceId, $made);
}
return $made;
} | php | {
"resource": ""
} |
q268128 | NativeContainer.getSingleton | test | public function getSingleton(string $serviceId)
{
// If the service isn't a singleton but is provided
if (! $this->isSingleton($serviceId) && $this->isProvided($serviceId)) {
// Initialize the provided service
$this->initializeProvided($serviceId);
}
return self::$singletons[$serviceId];
} | php | {
"resource": ""
} |
q268129 | NativeContainer.getProvided | test | public function getProvided(
string $serviceId,
array $arguments = null,
string $context = null,
string $member = null
) {
$this->initializeProvided($serviceId);
return $this->get($serviceId, $arguments, $context, $member);
} | php | {
"resource": ""
} |
q268130 | NativeContainer.contextServiceId | test | public function contextServiceId(string $serviceId, string $context = null, string $member = null): string
{
$index = $serviceId . '@' . ($context ?? '');
// If there is a method
if (null !== $member) {
// If there is a class
if (null !== $context) {
// Add the double colon to separate the method name and class
$index .= '::';
}
// Append the method/function to the string
$index .= $member;
}
// service@class
// service@method
// service@class::method
return $index;
} | php | {
"resource": ""
} |
q268131 | NativeContainer.setup | test | public function setup(bool $force = false, bool $useCache = true): void
{
if (self::$setup && ! $force) {
return;
}
self::$setup = true;
// If the application should use the container cache files
if ($useCache && $this->app->config()['container']['useCache']) {
$this->setupFromCache();
// Then return out of setup
return;
}
self::$registered = [];
self::$services = [];
self::$provided = [];
$useAnnotations = $this->app->config(
'container.useAnnotations',
false
);
$annotationsEnabled = $this->app->config(
'annotations.enabled',
false
);
$onlyAnnotations = $this->app->config(
'container.useAnnotationsExclusively',
false
);
// Setup service providers
$this->setupServiceProviders();
// If annotations are enabled and the container should use annotations
if ($useAnnotations && $annotationsEnabled) {
// Setup annotated services, contexts, and aliases
$this->setupAnnotations();
// If only annotations should be used
if ($onlyAnnotations) {
// Return to avoid loading container file
return;
}
}
// Include the container file
// NOTE: Included if annotations are set or not due to possibility of
// container items being defined within the classes as well as within
// the container file
require $this->app->config()['container']['filePath'];
} | php | {
"resource": ""
} |
q268132 | NativeContainer.setupFromCache | test | protected function setupFromCache(): void
{
// Set the application container with said file
$cache = $this->app->config()['cache']['container']
?? require $this->app->config()['container']['cacheFilePath'];
self::$services = unserialize(
base64_decode($cache['services'], true),
[
'allowed_classes' => [
Service::class,
],
]
);
self::$provided = $cache['provided'];
self::$aliases = $cache['aliases'];
} | php | {
"resource": ""
} |
q268133 | NativeContainer.setupServiceProviders | test | protected function setupServiceProviders(): void
{
/** @var array $providers */
$providers = $this->app->config()['container']['providers'];
// Iterate through all the providers
foreach ($providers as $provider) {
$this->register($provider);
}
// If this is not a dev environment
if (! $this->app->debug()) {
return;
}
/** @var array $devProviders */
$devProviders = $this->app->config()['container']['devProviders'];
// Iterate through all the providers
foreach ($devProviders as $provider) {
$this->register($provider);
}
} | php | {
"resource": ""
} |
q268134 | NativeContainer.getCacheable | test | public function getCacheable(): array
{
$this->setup(true, false);
return [
'services' => base64_encode(serialize(self::$services)),
'aliases' => self::$aliases,
'provided' => self::$provided,
];
} | php | {
"resource": ""
} |
q268135 | Address.getAddressLines | test | public function getAddressLines()
{
return array_filter([
$this->getComplex(),
implode(' ', array_filter([$this->getStreetNumber(), $this->getStreetName()])),
$this->getSuburb(),
$this->getCity(),
$this->getPostalCode()
]);
} | php | {
"resource": ""
} |
q268136 | Zend_Filter_Compress_Gz.setLevel | test | public function setLevel($level)
{
if (($level < 0) || ($level > 9)) {
throw new Zend_Filter_Exception('Level must be between 0 and 9');
}
$this->_options['level'] = (int) $level;
return $this;
} | php | {
"resource": ""
} |
q268137 | Controller.getUniqueId | test | public function getUniqueId()
{
$group = $this->group();
if ($group !== "") {
return $group;
}
$classNameArray = explode('\\', static::class);
$className = substr(array_pop($classNameArray), 0, -10);
return Inflector::camel2id($className);
} | php | {
"resource": ""
} |
q268138 | Controller.registerInRouter | test | public function registerInRouter(Router $router)
{
$routes = $this->routes();
$group = $this->group();
if (empty($routes)) {
return;
}
foreach ($routes as $row) {
$method = $row['method'];
$route = $group . $row['route'];
$handlerName = $row['handler'];
$router->addRoute($method, $route, [$this, $handlerName]);
}
} | php | {
"resource": ""
} |
q268139 | Controller.resolveAction | test | public function resolveAction(RequestApplicationInterface $app, string $action, ...$params)
{
$action = $this->normalizeActionName($action);
$actionId = static::getActionId($action);
if (!in_array($app, $params)) {
array_unshift($params, $app);
}
$self = $this;
return $this->validateAction($action, $app)->then(
function() use (&$app, &$self, $action, $actionId, $params) {
if ($this->beforeAction($actionId)) {
$app->view->context = $self;
return Reaction::$di->invoke([$self, $action], $params);
} else {
throw new Exception("Before action error");
}
},
function($error) {
if (!$error instanceof \Throwable) {
$error = new ForbiddenException('You can not perform this action');
}
throw $error;
}
)->then(
function($result = null) use ($actionId) {
return $this->afterAction($actionId, $result);
}
);
} | php | {
"resource": ""
} |
q268140 | Controller.beforeAction | test | public function beforeAction($actionId)
{
$isValid = true;
$this->emit(self::EVENT_BEFORE_ACTION, [&$this, $actionId, &$isValid]);
return $isValid;
} | php | {
"resource": ""
} |
q268141 | Controller.afterAction | test | public function afterAction($actionId, $result = null)
{
$this->emit(self::EVENT_AFTER_ACTION, [&$this, $actionId, &$result]);
return $result;
} | php | {
"resource": ""
} |
q268142 | Controller.renderPartial | test | public function renderPartial(RequestApplicationInterface $app, $viewName, $params = [], $asResponse = false)
{
return $this->renderInternal($app, $viewName, $params, false, $asResponse);
} | php | {
"resource": ""
} |
q268143 | Controller.renderAjax | test | public function renderAjax(RequestApplicationInterface $app, $viewName, $params = [], $asResponse = false)
{
return $this->renderInternal($app, $viewName, $params, true, $asResponse);
} | php | {
"resource": ""
} |
q268144 | Controller.actions | test | public function actions()
{
if (!isset($this->_actions)) {
$reflection = ReflectionHelper::getClassReflection($this);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
$actions = [];
foreach ($methods as $method) {
$name = $method->getName();
if ($name !== 'actions' && !$method->isStatic() && strncmp($name, 'action', 6) === 0) {
$actions[] = static::getActionId($name);
}
}
$this->_actions = $actions;
}
return $this->_actions;
} | php | {
"resource": ""
} |
q268145 | Controller.renderInLayout | test | protected function renderInLayout(RequestApplicationInterface $app, $viewName, $params = [], $asResponse = false)
{
$view = $app->view;
if (isset($this->layout)) {
$layoutFile = $view->findViewFile($this->layout, $this);
} else {
$layoutFile = $view->findViewFile($view->layout, $this);
}
$content = $this->renderInternal($app, $viewName, $params, false, false);
$rendered = $this->renderFile($app, $layoutFile, ['content' => $content]);
if (!$asResponse) {
return $rendered;
}
$app->response->setBody($rendered);
return $app->response;
} | php | {
"resource": ""
} |
q268146 | Controller.renderInternal | test | protected function renderInternal(RequestApplicationInterface $app, $viewName, $params = [], $ajax = false, $asResponse = false)
{
$view = $app->view;
$rendered = $ajax ? $view->renderAjax($viewName, $params, $this) : $view->render($viewName, $params, $this);
if (!$asResponse) {
return $rendered;
}
$app->response->setBody($rendered);
return $app->response;
} | php | {
"resource": ""
} |
q268147 | Controller.normalizeActionName | test | protected function normalizeActionName($actionMethod, $throwException = true)
{
if (!StringHelper::startsWith($actionMethod, 'action')) {
$actionMethod = static::getActionMethod($actionMethod);
}
if (!method_exists($this, $actionMethod)) {
if ($throwException) {
throw new NotFoundException('Page not found');
} else {
return null;
}
}
return $actionMethod;
} | php | {
"resource": ""
} |
q268148 | Controller.resolveErrorAsHtml | test | protected function resolveErrorAsHtml(RequestApplicationInterface $app, \Throwable $exception)
{
$actions = ['actionError'];
if ($exception instanceof HttpException) {
$actions[] = 'actionErrorHttp';
$actions[] = 'actionErrorHttp' . $exception->statusCode;
}
$action = null;
foreach ($actions as $possibleAction) {
$action = $this->normalizeActionName($possibleAction, false);
if (isset($action)) {
break;
}
}
if (!isset($action)) {
return $this->resolveErrorAsPlainText($app, $exception);
}
return Reaction::$di->invoke([$this, $action], [$app, $exception]);
} | php | {
"resource": ""
} |
q268149 | Controller.resolveErrorAsArray | test | protected function resolveErrorAsArray(RequestApplicationInterface $app, \Throwable $exception)
{
$data = $this->getErrorData($exception);
$responseData = ['error' => $data];
$app->response->setBody($responseData)->setStatusCodeByException($exception);
return $app->response;
} | php | {
"resource": ""
} |
q268150 | Controller.getErrorData | test | protected function getErrorData(\Throwable $exception)
{
$data = [
'message' => $exception->getMessage(),
'code' => $exception instanceof HttpExceptionInterface ? $exception->statusCode : $exception->getCode(),
'name' => $this->getExceptionName($exception),
];
if (Reaction::isDebug() || Reaction::isDev()) {
$data['file'] = $exception->getFile();
$data['line'] = $exception->getLine();
$data['trace'] = $exception->getTraceAsString();
}
return $data;
} | php | {
"resource": ""
} |
q268151 | Controller.getExceptionName | test | protected function getExceptionName($exception)
{
if ($exception instanceof Exception) {
return $exception->getName();
} else {
$classNameExp = explode('\\', get_class($exception));
return end($classNameExp);
}
} | php | {
"resource": ""
} |
q268152 | Controller.validateAction | test | protected function validateAction($action, RequestApplicationInterface $app)
{
$annotationsCtrl = Reaction::$annotations->getClass($this);
$annotationsAction = Reaction::$annotations->getMethod($action, $this);
$annotations = ArrayHelper::merge(array_values($annotationsCtrl), array_values($annotationsAction));
$promises = [];
if (!empty($annotations)) {
foreach ($annotations as $annotation) {
if (!$annotation instanceof CtrlActionValidatorInterface) {
continue;
}
$promise = $annotation->validate($app);
if (!$promise instanceof PromiseInterface) {
$promise = !empty($promise) ? resolve(true) : reject(false);
Reaction::warning("Controller validator '{class}' returned NOT a promise", [
'class' => get_class($annotation),
]);
}
$promises[] = $promise;
$promises[] = \Reaction\Promise\resolve(true);
}
}
if (empty($promises)) {
return resolve(true);
}
$all = \Reaction\Promise\all($promises);
return $all;
} | php | {
"resource": ""
} |
q268153 | Controller.getActionId | test | public static function getActionId($actionMethod)
{
if (strpos($actionMethod, 'action') === 0) {
$actionMethod = substr($actionMethod, 6);
}
return Inflector::camel2id($actionMethod, '-');
} | php | {
"resource": ""
} |
q268154 | Controller.getActionMethod | test | public static function getActionMethod($actionId = '')
{
if ($actionId === '') {
$actionId = static::$_defaultAction;
}
$actionMethod = Inflector::id2camel($actionId, '-');
return 'action' . $actionMethod;
} | php | {
"resource": ""
} |
q268155 | ColorTools.toHex | test | public static function toHex($color)
{
// Check it it's a RGB color
if (is_array($color)) {
if ((count($color) == 3 && array_keys($color) === range(0, 2))
|| (count($color) == 4 && array_keys($color) === range(0, 3))) {
$red = $color[0];
$green = $color[1];
$blue = $color[2];
} else {
$red = isset($color['red']) ?: (isset($color['r']) ?: 0);
$red = isset($color['red'])
? $color['red']
: (isset($color['r']) ? $color['r'] : 0);
$green = isset($color['green'])
? $color['green']
: (isset($color['g']) ? $color['g'] : 0);
$blue = isset($color['blue'])
? $color['blue']
: (isset($color['b']) ? $color['b'] : 0);
}
return '#'
.substr('00' . dechex($red), -2)
.substr('00' . dechex($green), -2)
.substr('00' . dechex($blue), -2);
}
if (is_string($color)) {
$color = strtolower($color);
// Check if it's a X11 color
if (array_key_exists($color, self::$x11) !== false) {
return static::toHex(self::$x11[$color]);
}
// Check if it's an 3-hexadecimal color
if (preg_match('/^#[\da-f]{3}$/i', $color)) {
$color = preg_replace('/([\da-f])/i', '$1$1', $color);
}
if (preg_match('/^#[\da-f]{6}$/i', $color)) {
return $color;
}
}
return '#000000';
} | php | {
"resource": ""
} |
q268156 | ColorTools.toRGBA | test | public static function toRGBA($color)
{
// Check it it's already a RGB color
if (is_array($color)) {
if (count($color) == 3 && array_keys($color) === range(0, 2)) {
return array(
'red' => $color[0],
'green' => $color[1],
'blue' => $color[2],
'alpha' => 1
);
}
if (count($color) == 4 && array_keys($color) === range(0, 3)) {
return array(
'red' => $color[0],
'green' => $color[1],
'blue' => $color[2],
'alpha' => $color[3]
);
}
return array(
'red' => isset($color['red'])
? $color['red']
: (isset($color['r']) ? $color['r'] : 0),
'green' => isset($color['green'])
? $color['green']
: (isset($color['g']) ? $color['g'] : 0),
'blue' => isset($color['blue'])
? $color['blue']
: (isset($color['b']) ? $color['b'] : 0),
'alpha' => isset($color['alpha'])
? $color['alpha']
: 1
);
}
if (is_string($color)) {
$color = strtolower($color);
// Check if it's a X11 color
if (array_key_exists($color, self::$x11) !== false) {
$color = self::$x11[$color];
$color['alpha'] = 1;
return $color;
}
// Check if it's an hexadecimal color
if (preg_match('/^#[\da-f]{3}$/i', $color)) {
$color = preg_replace('/([\da-f])/i', '$1$1', $color);
}
if (preg_match('/^#[\da-f]{6}$/i', $color)) {
list($red, $green, $blue) = sscanf($color, "#%02x%02x%02x");
return array(
'red' => $red,
'green' => $green,
'blue' => $blue,
'alpha' => 1
);
}
}
return array('red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 1);
} | php | {
"resource": ""
} |
q268157 | ColorTools.imageDominant | test | public static function imageDominant($src, $granularity = 1)
{
$granularity = max(1, abs((int)$granularity));
$channels = array(
'red' => 0,
'green' => 0,
'blue' => 0
);
$size = @getimagesize($src);
if ($size === false) {
user_error("Unable to get image size data: ".$src);
return false;
}
$img = @imagecreatefromstring(@file_get_contents($src));
if (!$img) {
user_error("Unable to open image file: ".$src);
return false;
}
for($x = 0; $x < $size[0]; $x += $granularity) {
for($y = 0; $y < $size[1]; $y += $granularity) {
$thisColor = imagecolorat($img, $x, $y);
$rgb = imagecolorsforindex($img, $thisColor);
$channels['red'] += $rgb['red'];
$channels['green'] += $rgb['green'];
$channels['blue'] += $rgb['blue'];
}
}
$nbPixels = ceil($size[0] / $granularity) * ceil($size[1] / $granularity);
$channels['red'] = round($channels['red'] / $nbPixels);
$channels['green'] = round($channels['green'] / $nbPixels);
$channels['blue'] = round($channels['blue'] / $nbPixels);
return $channels;
} | php | {
"resource": ""
} |
q268158 | Console.stdin | test | public static function stdin($raw = false)
{
$promise = new Promise(function($r, $c) use ($raw) {
static::getStdInStream()->once('data', function($chunk) use ($r, $raw) {
if (!$raw) {
$chunk = rtrim($chunk, PHP_EOL);
}
$r($chunk);
});
});
return $promise;
} | php | {
"resource": ""
} |
q268159 | Console.select | test | public static function select($prompt, $options = [])
{
$helpText = '';
foreach ($options as $key => $value) {
$helpText .= " $key - $value\n";
}
$helpText .= ' ? - Show help';
$promptText = "$prompt [" . implode(',', array_keys($options)) . ',?]: ';
$promptOptions = [
'required' => true,
'validator' => function($input, &$error) use($options, $helpText) {
$input = trim($input);
if ($input === '?') {
$error = $helpText;
return false;
}
if (array_key_exists($input, $options)) {
return true;
}
$error = "Invalid input, please enter '?' for help";
return false;
}
];
return static::prompt($promptText, $promptOptions);
} | php | {
"resource": ""
} |
q268160 | FileAppenderTrait._appendFileToPaths | test | protected function _appendFileToPaths(array $paths, $file)
{
if (!$this->_isAtom($file)) {
return [$file];
}
$appendFile = function($path) use($file) {
return $this->_joinPaths($path, $file);
};
return array_map($appendFile, $paths);
} | php | {
"resource": ""
} |
q268161 | Database.getPgClient | test | protected function getPgClient() {
if (!isset($this->_pgClient)) {
$config = [
'dbCredentials' => [
'host' => $this->host,
'port' => $this->port,
'user' => $this->username,
'password' => $this->password,
'database' => $this->database,
],
//'autoDisconnect' => true,
//'maxConnections' => 5,
'loop' => Reaction::$app->loop
];
$this->_pgClient = new PgClient($config);
}
return $this->_pgClient;
} | php | {
"resource": ""
} |
q268162 | Database.executeSql | test | public function executeSql($sql, $params = [], $lazy = true) {
list($sql, $params) = $this->convertSqlToIndexed($sql, $params);
$promiseResolver = function($r, $c) use ($sql, $params) {
$result = [];
$this->getPgClient()->executeStatement($sql, $params)->subscribe(
function($row) use (&$result) {
$result[] = $row;
},
function($error = null) use (&$c) {
$c($error);
},
function() use (&$r, &$result) {
$r($result);
}
);
};
if (!$lazy) {
return new Promise($promiseResolver);
}
$promiseCreator = function() use (&$promiseResolver) {
return new Promise($promiseResolver);
};
return new LazyPromise($promiseCreator);
} | php | {
"resource": ""
} |
q268163 | NativeUploadedFile.writeStream | test | protected function writeStream(string $path): void
{
// Attempt to open the path specified
$handle = fopen($path, 'wb+');
// If the handler failed to open
if (false === $handle) {
// Throw a runtime exception
throw new RuntimeException(
'Unable to write to designated path'
);
}
// Get the stream
$stream = $this->getStream();
// Rewind the stream
$stream->rewind();
// While the end of file hasn't been reached
while (! $stream->eof()) {
// Write the stream's contents to the handler
fwrite($handle, $stream->read(4096));
}
// Close the file path
fclose($handle);
} | php | {
"resource": ""
} |
q268164 | ServerRequestFactory.fromGlobals | test | public static function fromGlobals(
array $server = null,
array $query = null,
array $body = null,
array $cookies = null,
array $files = null
): ServerRequest {
$server = static::normalizeServer($server ?: $_SERVER);
$files = static::normalizeFiles($files ?: $_FILES);
$headers = static::marshalHeaders($server);
if (null === $cookies && array_key_exists('cookie', $headers)) {
$cookies = self::parseCookieHeader($headers['cookie']);
}
return new NativeServerRequest(
static::marshalUriFromServer($server, $headers),
static::get('REQUEST_METHOD', $server, RequestMethod::GET),
new NativeStream('php://input'),
$headers,
$server,
$cookies ?? $_COOKIE,
$query ?? $_GET,
$body ?? $_POST,
$files,
static::marshalProtocolVersion($server)
);
} | php | {
"resource": ""
} |
q268165 | ServerRequestFactory.getHeader | test | public static function getHeader(string $header, array $headers, $default = null): string
{
$header = strtolower($header);
$headers = array_change_key_case($headers, CASE_LOWER);
if (array_key_exists($header, $headers)) {
$value = \is_array($headers[$header]) ? implode(', ', $headers[$header]) : $headers[$header];
return $value;
}
return $default;
} | php | {
"resource": ""
} |
q268166 | ServerRequestFactory.stripQueryString | test | public static function stripQueryString(string $path): string
{
if (($queryPos = strpos($path, '?')) !== false) {
return substr($path, 0, $queryPos);
}
return $path;
} | php | {
"resource": ""
} |
q268167 | ServerRequestFactory.marshalHostAndPortFromHeader | test | private static function marshalHostAndPortFromHeader(stdClass $accumulator, $host): void
{
if (\is_array($host)) {
$host = implode(', ', $host);
}
$accumulator->host = $host;
$accumulator->port = null;
// Works for regname, IPv4 & IPv6
if (preg_match('|\:(\d+)$|', $accumulator->host, $matches)) {
$accumulator->host = substr($accumulator->host, 0, -1 * (\strlen($matches[1]) + 1));
$accumulator->port = (int) $matches[1];
}
} | php | {
"resource": ""
} |
q268168 | ServerRequestFactory.normalizeNestedFileSpec | test | private static function normalizeNestedFileSpec(array $files = []): array
{
$normalizedFiles = [];
foreach (array_keys($files['tmp_name']) as $key) {
$spec = [
'tmp_name' => $files['tmp_name'][$key],
'size' => $files['size'][$key],
'error' => $files['error'][$key],
'name' => $files['name'][$key],
'type' => $files['type'][$key],
];
$normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
}
return $normalizedFiles;
} | php | {
"resource": ""
} |
q268169 | Str.endsWith | test | public static function endsWith($needle, $str)
{
$end = substr($str, -1*strlen($needle));
return $end == $needle;
} | php | {
"resource": ""
} |
q268170 | Str.random | test | public static function random($charsAmount, $chars = array())
{
if (!$chars) {
$chars = array(
'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8',
'9', '_'
);
}
$str = '';
for ($i=1; $i<=$charsAmount; $i++) {
$str .= $chars[array_rand($chars)];
}
return $str;
} | php | {
"resource": ""
} |
q268171 | VersionPathSearch.createEdges | test | private function createEdges(Graph $graph, $className)
{
$migrationsAnnotations = $this->reader->getClassMigrationMethodInfo($className);
$parentVertex = $graph->hasVertex($className) ? $graph->getVertex($className) : $graph->createVertex(
$className
);
foreach ($migrationsAnnotations as $migrationsAnnotation) {
if ($migrationsAnnotation->annotation->from) {
$fromClass = $migrationsAnnotation->annotation->from;
$fromVertex = $graph->hasVertex($fromClass) ? $graph->getVertex($fromClass) : $graph->createVertex(
$fromClass
);
if (!$parentVertex->hasEdgeTo($fromVertex)) {
$edge = $fromVertex->createEdgeTo($parentVertex);
$this->annotations[$this->getEdgeId($edge)] = $migrationsAnnotation;
$this->createEdges($graph, $fromClass);
}
}
if ($migrationsAnnotation->annotation->to) {
$toClass = $migrationsAnnotation->annotation->to;
$fromVertex = $graph->hasVertex($toClass) ? $graph->getVertex($toClass) : $graph->createVertex(
$toClass
);
if (!$parentVertex->hasEdgeTo($fromVertex)) {
$edge = $parentVertex->createEdgeTo($fromVertex);
$this->annotations[$this->getEdgeId($edge)] = $migrationsAnnotation;
$this->createEdges($graph, $toClass);
}
}
}
} | php | {
"resource": ""
} |
q268172 | VersionPathSearch.find | test | public function find($fromClassName, $toClassName)
{
$annotations = array();
$graph = new Graph();
$this->createEdges($graph, $fromClassName);
$this->createEdges($graph, $toClassName);
try {
$breadFirst = new BreadthFirst($graph->getVertex($fromClassName));
$edges = $breadFirst->getEdgesTo($graph->getVertex($toClassName));
/** @var Directed $edge */
foreach ($edges as $edge) {
$annotations[] = $this->annotations[$this->getEdgeId($edge)];
}
} catch (OutOfBoundsException $e) {
return null;
}
return $annotations;
} | php | {
"resource": ""
} |
q268173 | EntityRepositoryResource.create | test | public function create($data)
{
$data = $this->sanitizeData((array)$data);
return $this->getRepository()->create($data);
} | php | {
"resource": ""
} |
q268174 | EntityRepositoryResource.fetchAll | test | public function fetchAll($params = array())
{
$criteria = $params->get('query', []);
$orderBy = $params->get('order_by', []);
$adapter = $this->getRepository()->getPaginatorAdapter($criteria, $orderBy);
return new $this->collectionClass($adapter);
} | php | {
"resource": ""
} |
q268175 | EntityRepositoryResource.update | test | public function update($id, $data)
{
$data = $this->sanitizeData((array)$data);
return $this->getRepository()->update($id, $data);
} | php | {
"resource": ""
} |
q268176 | NativeResponse.setStatusCode | test | public function setStatusCode(int $code, string $text = null): Response
{
$this->statusCode = $code;
// Check if the status code is valid
if ($this->isInvalid()) {
throw new InvalidStatusCodeException(
sprintf('The HTTP status code "%s" is not valid.', $code)
);
}
// If no text was supplied
if (null === $text) {
// Set the status text from the status texts array
$this->statusText = StatusCode::TEXTS[$code] ?? 'unknown status';
return $this;
}
$this->statusText = $text;
return $this;
} | php | {
"resource": ""
} |
q268177 | NativeResponse.setHeaders | test | public function setHeaders(array $headers = []): Response
{
// If the headers have no been set yet
if (null === $this->headers) {
// Set them to a new Headers collection
$this->headers = new Headers();
}
// Set all the headers with the array provided
$this->headers->setAll($headers);
// If there is no cache control header
if (! $this->headers->has('Cache-Control')) {
// Set it to an empty string
$this->headers->set('Cache-Control', '');
}
return $this;
} | php | {
"resource": ""
} |
q268178 | NativeResponse.getDateHeader | test | public function getDateHeader(): DateTime
{
if (! $this->headers->has('Date')) {
$this->setDateHeader(DateTime::createFromFormat('U', time()));
}
return $this->headers->get('Date');
} | php | {
"resource": ""
} |
q268179 | NativeResponse.setDateHeader | test | public function setDateHeader(DateTime $date): Response
{
$date->setTimezone(new DateTimeZone('UTC'));
$this->headers->set('Date', $date->format('D, d M Y H:i:s') . ' GMT');
return $this;
} | php | {
"resource": ""
} |
q268180 | NativeResponse.addCacheControl | test | public function addCacheControl(string $name, string $value = null): Response
{
$this->cacheControl[$name] = $value;
return $this;
} | php | {
"resource": ""
} |
q268181 | NativeResponse.getCacheControl | test | public function getCacheControl(string $name): string
{
return $this->hasCacheControl($name)
? $this->cacheControl[$name]
: false;
} | php | {
"resource": ""
} |
q268182 | NativeResponse.removeCacheControl | test | public function removeCacheControl(string $name): Response
{
if (! $this->hasCacheControl($name)) {
return $this;
}
unset($this->cacheControl[$name]);
return $this;
} | php | {
"resource": ""
} |
q268183 | NativeResponse.isCacheable | test | public function isCacheable(): bool
{
if (! \in_array(
$this->statusCode,
[
StatusCode::OK,
StatusCode::NON_AUTHORITATIVE_INFORMATION,
StatusCode::MULTIPLE_CHOICES,
StatusCode::MOVED_PERMANENTLY,
StatusCode::FOUND,
StatusCode::NOT_FOUND,
StatusCode::GONE,
],
true
)
) {
return false;
}
if (
$this->hasCacheControl('no-store')
|| $this->hasCacheControl('private')
) {
return false;
}
return $this->isValidateable() || $this->isFresh();
} | php | {
"resource": ""
} |
q268184 | NativeResponse.getAge | test | public function getAge(): int
{
if (null !== $age = $this->headers->get('Age')) {
return $age;
}
return max(
time() - date('U', strtotime($this->getDateHeader())),
0
);
} | php | {
"resource": ""
} |
q268185 | NativeResponse.expire | test | public function expire(): Response
{
if ($this->isFresh()) {
$this->headers->set('Age', $this->getMaxAge());
}
return $this;
} | php | {
"resource": ""
} |
q268186 | NativeResponse.getExpires | test | public function getExpires(): DateTime
{
try {
return $this->headers->get('Expires');
} catch (\RuntimeException $e) {
// according to RFC 2616 invalid date formats (e.g. "0" and "-1")
// must be treated as in the past
return DateTime::createFromFormat(
DATE_RFC2822,
'Sat, 01 Jan 00 00:00:00 +0000'
);
}
} | php | {
"resource": ""
} |
q268187 | NativeResponse.getMaxAge | test | public function getMaxAge(): int
{
if ($this->hasCacheControl('s-maxage')) {
return $this->getCacheControl('s-maxage');
}
if ($this->hasCacheControl('max-age')) {
return $this->getCacheControl('max-age');
}
if (null !== $this->getExpires()) {
return date('U', strtotime($this->getExpires())) - date(
'U',
strtotime(
$this->getDateHeader()
)
);
}
return 0;
} | php | {
"resource": ""
} |
q268188 | NativeResponse.setSharedMaxAge | test | public function setSharedMaxAge(int $value): Response
{
$this->setPublic();
$this->addCacheControl('s-maxage', $value);
return $this;
} | php | {
"resource": ""
} |
q268189 | NativeResponse.setTtl | test | public function setTtl(int $seconds): Response
{
$this->setSharedMaxAge($this->getAge() + $seconds);
return $this;
} | php | {
"resource": ""
} |
q268190 | NativeResponse.setNotModified | test | public function setNotModified(): Response
{
$this->setStatusCode(StatusCode::NOT_MODIFIED);
$this->setContent(null);
$this->headers
->remove('Allow')
->remove('Content-Encoding')
->remove('Content-Language')
->remove('Content-Length')
->remove('Content-MD5')
->remove('Content-Type')
->remove('Last-Modified');
return $this;
} | php | {
"resource": ""
} |
q268191 | NativeResponse.isInvalid | test | public function isInvalid(): bool
{
return $this->statusCode < StatusCode::CONTINUE
|| $this->statusCode >= StatusCode::NETWORK_AUTHENTICATION_REQUIRED;
} | php | {
"resource": ""
} |
q268192 | NativeResponse.isInformational | test | public function isInformational(): bool
{
return $this->statusCode >= StatusCode::CONTINUE
&& $this->statusCode < StatusCode::OK;
} | php | {
"resource": ""
} |
q268193 | NativeResponse.isSuccessful | test | public function isSuccessful(): bool
{
return $this->statusCode >= StatusCode::OK
&& $this->statusCode < StatusCode::MULTIPLE_CHOICES;
} | php | {
"resource": ""
} |
q268194 | NativeResponse.isRedirection | test | public function isRedirection(): bool
{
return $this->statusCode >= StatusCode::MULTIPLE_CHOICES
&& $this->statusCode < StatusCode::BAD_REQUEST;
} | php | {
"resource": ""
} |
q268195 | NativeResponse.isClientError | test | public function isClientError(): bool
{
return $this->statusCode >= StatusCode::BAD_REQUEST
&& $this->statusCode < StatusCode::INTERNAL_SERVER_ERROR;
} | php | {
"resource": ""
} |
q268196 | NativeResponse.isRedirect | test | public function isRedirect(string $location = null): bool
{
return \in_array(
$this->statusCode,
[
StatusCode::CREATED,
StatusCode::MOVED_PERMANENTLY,
StatusCode::FOUND,
StatusCode::SEE_OTHER,
StatusCode::TEMPORARY_REDIRECT,
StatusCode::PERMANENT_REDIRECT,
],
true
)
&& (null === $location
?: $location === $this->headers->get('Location'));
} | php | {
"resource": ""
} |
q268197 | NativeResponse.isEmpty | test | public function isEmpty(): bool
{
return \in_array(
$this->statusCode,
[
StatusCode::NO_CONTENT,
StatusCode::NOT_MODIFIED,
],
true
);
} | php | {
"resource": ""
} |
q268198 | NativeResponse.closeOutputBuffers | test | public static function closeOutputBuffers(int $targetLevel, bool $flush): void
{
$status = ob_get_status(true);
$level = \count($status);
// PHP_OUTPUT_HANDLER_* are not defined on HHVM 3.3
$flags = \defined('PHP_OUTPUT_HANDLER_REMOVABLE')
? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush
? PHP_OUTPUT_HANDLER_FLUSHABLE
: PHP_OUTPUT_HANDLER_CLEANABLE)
: -1;
while (
$level-- > $targetLevel && ($s = $status[$level]) &&
($s['del'] ?? ! isset($s['flags']) || $flags === ($s['flags'] & $flags))
) {
if ($flush) {
ob_end_flush();
} else {
ob_end_clean();
}
}
} | php | {
"resource": ""
} |
q268199 | RequestTrait.initialize | test | protected function initialize(
Uri $uri = null,
string $method = null,
Stream $body = null,
array $headers = null
): void {
$this->uri = $uri ?? new NativeUri();
$this->method = $method ?? RequestMethod::GET;
$this->body = $body ?? new NativeStream('php://input');
$this->headers = $headers ?? [];
$this->setHeaders($headers);
$this->validateMethod($this->method);
$this->validateProtocolVersion($this->protocol);
if ($this->hasHeader(static::$HOST_NAME) && $this->uri->getHost()) {
$this->headerNames[static::$HOST_NAME_NORM] = static::$HOST_NAME;
$this->headers[static::$HOST_NAME] = [
$this->uri->getHost(),
];
}
} | php | {
"resource": ""
} |