_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q267700 | Reflection.setPropertyValue | test | public static function setPropertyValue($object, $property, $value)
{
$ref = self::loadClassReflection($object);
$refProperty = $ref->getProperty($property);
if (!$refProperty->isPublic()) {
$refProperty->setAccessible(true);
}
if ($refProperty->isStatic()) {
$refProperty->setValue($value);
} else {
$refProperty->setValue($object, $value);
}
} | php | {
"resource": ""
} |
q267701 | Reflection.setPropertiesValue | test | public static function setPropertiesValue($object, array $properties)
{
foreach ($properties as $name => $value) {
self::setPropertyValue($object, $name, $value);
}
} | php | {
"resource": ""
} |
q267702 | Reflection.loadClassAnnotations | test | public static function loadClassAnnotations(Reader $reader, $class, $inParents = false)
{
$reflection = self::loadClassReflection($class);
if (!$inParents) {
return $reader->getClassAnnotations($reflection);
}
$annotations = [];
do {
$classAnnotations = $reader->getClassAnnotations($reflection);
foreach ($classAnnotations as $classAnnotation) {
if (!isset($annotations[get_class($classAnnotation)])) {
$annotations[get_class($classAnnotation)] = $classAnnotation;
}
}
} while ($reflection = $reflection->getParentClass());
return array_values($annotations);
} | php | {
"resource": ""
} |
q267703 | Reflection.clear | test | public static function clear($mode = null)
{
if (is_numeric($mode)) {
$mode = self::TYPE_CLASS | self::TYPE_OBJECT;
}
if ($mode & self::TYPE_CLASS) {
self::$classReflections = array();
}
if ($mode & self::TYPE_OBJECT) {
self::$objectReflections = array();
}
} | php | {
"resource": ""
} |
q267704 | ReflectionHelper.isInstantiable | test | public static function isInstantiable($className)
{
$reflection = static::getClassReflection($className);
if ($reflection === null) {
return false;
}
return $reflection->isInstantiable();
} | php | {
"resource": ""
} |
q267705 | ReflectionHelper.getMethodReflection | test | public static function getMethodReflection($objectOrName, $methodName)
{
$cached = static::getReflectionFromCache(static::REFLECTION_METHOD, $objectOrName, $methodName);
if ($cached !== null) {
return $cached;
}
try {
$reflection = new \ReflectionMethod($objectOrName, $methodName);
return static::setReflectionToCache($reflection, static::REFLECTION_METHOD, $objectOrName, $methodName);
} catch (\ReflectionException $exception) {
$reflection = null;
}
return $reflection;
} | php | {
"resource": ""
} |
q267706 | ReflectionHelper.getClassReflection | test | public static function getClassReflection($objectOrName)
{
$cached = static::getReflectionFromCache(static::REFLECTION_CLASS, $objectOrName);
if ($cached !== null) {
return $cached;
}
try {
$reflection = new \ReflectionClass($objectOrName);
return static::setReflectionToCache($reflection, static::REFLECTION_CLASS, $objectOrName);
} catch (\ReflectionException $exception) {
$reflection = null;
}
return $reflection;
} | php | {
"resource": ""
} |
q267707 | ReflectionHelper.checkMethodArguments | test | public static function checkMethodArguments($arguments = [], $method, $objectOrName = null, $returnType = self::ARG_CHECK_RETURN_DATA)
{
if ($method instanceof \ReflectionMethod) {
$reflection = $method;
} elseif ($objectOrName !== null) {
$reflection = static::getMethodReflection($objectOrName, $method);
} else {
return null;
}
if ($reflection->getNumberOfRequiredParameters() === 0) {
return $returnType === static::ARG_CHECK_RETURN_DATA ? [] : true;
}
$methodParams = $reflection->getParameters();
$data = [];
foreach ($methodParams as $param) {
if (!$param->isOptional() && empty($arguments)) {
$data[$param->name] = static::ARG_REQUIRED_MISSING;
} elseif(!empty($arguments) && ($type = $param->getType()) !== null) {
$arg = reset($arguments);
$typeName = $type->getName();
$stdTypes = ['bool', 'int', 'string', 'array', 'object', 'float', 'callable'];
if (!in_array($typeName, $stdTypes) && !$arg instanceof $typeName) {
$data[$param->name] = static::ARG_TYPE_MISMATCH;
}
}
array_shift($arguments);
}
return $returnType === static::ARG_CHECK_RETURN_DATA ? $data : empty($data);
} | php | {
"resource": ""
} |
q267708 | ReflectionHelper.getReflectionFromCache | test | protected static function getReflectionFromCache($type = self::REFLECTION_CLASS, $objectOrName, ...$params)
{
$cache = &static::$_reflections[$type];
$key = static::getCacheKey($type, $objectOrName, ...$params);
return isset($cache[$key]) ? $cache[$key] : null;
} | php | {
"resource": ""
} |
q267709 | ReflectionHelper.setReflectionToCache | test | protected static function setReflectionToCache($reflection, $type = self::REFLECTION_CLASS, $objectOrName = null, ...$params)
{
if (null === $reflection || null === $objectOrName) {
return null;
}
$key = static::getCacheKey($type, $objectOrName, ...$params);
static::$_reflections[$type][$key] = $reflection;
return $reflection;
} | php | {
"resource": ""
} |
q267710 | ReflectionHelper.getCacheKey | test | protected static function getCacheKey($type = self::REFLECTION_CLASS, $objectOrName, ...$params)
{
if (is_object($objectOrName)) {
$className = static::getObjectClassName($objectOrName);
} else {
$className = $objectOrName;
}
$key = $className;
switch ($type) {
case static::REFLECTION_METHOD:
case static::REFLECTION_PROPERTY:
$methodOrProperty = $params[0];
$key .= '::' . $methodOrProperty;
break;
}
return $key;
} | php | {
"resource": ""
} |
q267711 | ReflectionHelper.getObjectClassName | test | protected static function getObjectClassName($object)
{
$nameGetters = [
\ReflectionClass::class => 'getName()',
\ReflectionMethod::class => 'class',
\ReflectionProperty::class => 'class',
];
foreach ($nameGetters as $class => $getter) {
if ($object instanceof $class) {
$isMethod = substr($getter, -2) === '()';
if ($isMethod) {
$getter = substr($getter, 0, -2);
return call_user_func([$object, $getter]);
}
return $object->$getter;
}
}
return get_class($object);
} | php | {
"resource": ""
} |
q267712 | ReflectionHelper.parseDocCommentSummary | test | protected static function parseDocCommentSummary($reflection)
{
$docLines = preg_split('~\R~u', $reflection->getDocComment());
if (isset($docLines[1])) {
return trim($docLines[1], "\t *");
}
return '';
} | php | {
"resource": ""
} |
q267713 | ReflectionHelper.getClassDoc | test | protected static function getClassDoc($object, $parseMethod = 'parseDocCommentSummary')
{
try {
$reflection = new \ReflectionClass($object);
$docData = static::$parseMethod($reflection);
} catch (\ReflectionException $exception) {
$docData = null;
}
return $docData;
} | php | {
"resource": ""
} |
q267714 | ReflectionHelper.getMethodPropertyDoc | test | protected static function getMethodPropertyDoc($method, $object = null, $type = self::REFLECTION_METHOD, $parseMethod = self::DOC_COMMENT_SHORT)
{
try {
//Method is already a \ReflectionMethod|\ReflectionProperty
if ($method instanceof \ReflectionMethod || $method instanceof \ReflectionProperty) {
$reflection = $method;
//Method is string
} else {
//Check that object is not a \ReflectionClass
$object = $object instanceof \ReflectionClass ? $object->getName() : $object;
$reflection = $type === static::REFLECTION_METHOD
? new \ReflectionMethod($object, $method)
: new \ReflectionProperty($object, $method);
}
$docData = static::$parseMethod($reflection);
} catch (\ReflectionException $exception) {
$docData = null;
}
return $docData;
} | php | {
"resource": ""
} |
q267715 | Db.initByConfig | test | public function initByConfig($key, $config)
{
if(empty($config))
{
throw new Exception('db config is empty');
}
$driver = 'Li\\'.ucfirst($config['driver']);
if(!(isset($this->$key) && $this->$key instanceof $driver))
{
$this->$key = new $driver($config);
}
} | php | {
"resource": ""
} |
q267716 | FlashMessages._mapNameSpace | test | private function _mapNameSpace($foundationClass)
{
if (isset($this->_nsMap[$foundationClass])) {
return $this->_nsMap[$foundationClass];
}
return reset($this->_nsMap);
} | php | {
"resource": ""
} |
q267717 | PEAR_PackageFile_Parser_v2._unIndent | test | function _unIndent($str)
{
// remove leading newlines
$str = preg_replace('/^[\r\n]+/', '', $str);
// find whitespace at the beginning of the first line
$indent_len = strspn($str, " \t");
$indent = substr($str, 0, $indent_len);
$data = '';
// remove the same amount of whitespace from following lines
foreach (explode("\n", $str) as $line) {
if (substr($line, 0, $indent_len) == $indent) {
$data .= substr($line, $indent_len) . "\n";
} else {
$data .= $line . "\n";
}
}
return $data;
} | php | {
"resource": ""
} |
q267718 | PEAR_PackageFile_Parser_v2.postProcess | test | function postProcess($data, $element)
{
if ($element == 'notes') {
return trim($this->_unIndent($data));
}
return trim($data);
} | php | {
"resource": ""
} |
q267719 | Photo.extractPhotoArray | test | private function extractPhotoArray($source)
{
if ($source->stat == 'fail') {
return;
}
$data = &$source->photo;
$photo = [];
$photo['id'] = $data->id;
$photo['title'] = $data->title->_content;
$photo['description'] = $data->description->_content;
$photo['url'] = $data->urls->url[0]->_content;
$photo['created'] = (string) $data->dates->posted;
$photo['views'] = $data->views;
$images = $this->fetchImages($photo['id']);
$photo['source'] = $images[1];
$photo['source_thumbnail'] = $images[0];
return $photo;
} | php | {
"resource": ""
} |
q267720 | Photo.fetchImages | test | private function fetchImages($photoId)
{
$query = array_merge(
$this->defaultQuery,
[
'method' => 'flickr.photos.getSizes',
'photo_id' => $photoId,
]
);
$body = $this->newRequest()
->setQuery($query)
->GET()
->getBody('array');
return $this->extractImagesArray($body);
} | php | {
"resource": ""
} |
q267721 | Photo.extractImagesArray | test | private function extractImagesArray($source)
{
$sizes = array_get($source, 'sizes.size');
$images = array_where($sizes, function ($key, $value) {
return in_array($value['label'], ['Original', 'Small 320']);
});
return array_fetch($images, 'source');
} | php | {
"resource": ""
} |
q267722 | UrlManager.findPlaceholderStartPos | test | protected function findPlaceholderStartPos($path) {
$brFgPos = strpos($path, '{');
$brSqPos = strpos($path, '[');
if ($brFgPos === false && $brSqPos === false) {
return false;
}
$len = strlen($path);
$positions = [
$brFgPos !== false ? $brFgPos : $len,
$brSqPos !== false ? $brSqPos : $len,
];
return min($positions);
} | php | {
"resource": ""
} |
q267723 | UrlManager.buildRoutePath | test | protected function buildRoutePath($path, &$params) {
$path = $this->replacePlaceholders($path, $params);
$path = $this->searchInRouter($path, $params);
return $path;
} | php | {
"resource": ""
} |
q267724 | UrlManager.searchInRouter | test | protected function searchInRouter($path, &$params) {
if (isset(\Reaction::$app->router->routePaths[$path])) {
$paramsKeys = array_keys($params);
$routes = \Reaction::$app->router->routePaths[$path];
foreach ($routes as $routeData) {
$intersect = array_intersect($paramsKeys, $routeData['params']);
if (count($intersect) === count($routeData['params'])) {
$path = $this->replacePlaceholders($routeData['exp'], $params);
break;
}
}
return $path;
}
return $path;
} | php | {
"resource": ""
} |
q267725 | UrlManager.replacePlaceholders | test | protected function replacePlaceholders($path, &$params) {
if (strpos($path, '{') === false) {
return $path;
}
$path = preg_replace_callback('/(\{([a-zA-Z0-9]+)\})/i', function($matches) use (&$params) {
$match = $matches[1];
$key = $matches[2];
if (!isset($params[$key])) {
return $match;
}
$replace = $params[$key];
unset($params[$key]);
return $replace;
}, $path);
return $path;
} | php | {
"resource": ""
} |
q267726 | MessageSource.init | test | public function init()
{
parent::init();
if ($this->sourceLanguage === null) {
$this->sourceLanguage = Reaction::$app->sourceLanguage;
}
} | php | {
"resource": ""
} |
q267727 | MessageSource.preloadMessages | test | public function preloadMessages($category, $languages = [])
{
if ($category === '*') {
$categoriesFind = $this->findAllCategories();
} else {
$categoriesFind = strpos($category, '*') > 0 ? $this->findCategoriesByPattern($category) : resolve([$category]);
}
return $categoriesFind
->otherwise(function() { return []; })
->then(function($categories) use ($languages) {
$promises = [];
foreach ($categories as $category) {
foreach ($languages as $language) {
$key = $language . '/' . $category;
$promises[$key] = $this->loadMessages($category, $language);
}
}
if (empty($promises)) {
return [];
}
return all($promises)
->then(function($results) {
$this->_messages = Reaction\Helpers\ArrayHelper::merge($this->_messages, $results);
return $results;
});
});
} | php | {
"resource": ""
} |
q267728 | MessageSource.findCategoriesByPattern | test | protected function findCategoriesByPattern($pattern)
{
return $this->findAllCategories()
->then(function($categories) use ($pattern) {
$matches = [];
foreach ($categories as $category) {
if (Reaction\Helpers\StringHelper::matchWildcard($pattern, $category)) {
$matches[] = $category;
}
}
return $matches;
});
} | php | {
"resource": ""
} |
q267729 | Model.__isset | test | public function __isset(string $name): bool
{
$methodName = str_replace('_', '', ucwords($name, '_'));
$methodName = 'isset' . $methodName;
if (method_exists($this, $methodName)) {
return $this->$methodName();
}
return property_exists($this, $name);
} | php | {
"resource": ""
} |
q267730 | ExceptionHandler.sendExceptionResponse | test | public function sendExceptionResponse($exception): void
{
if (! headers_sent()) {
if ($exception instanceof HttpException) {
header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
foreach ($exception->getHeaders() as $name => $value) {
header($name . ': ' . $value, false);
}
}
header('Content-Type: text/html; charset=' . $this->charset);
}
echo $this->html($this->getContent($exception), $this->getStylesheet());
} | php | {
"resource": ""
} |
q267731 | ExceptionHandler.getContent | test | public function getContent(Throwable $exception): string
{
$title = 'Whoops, looks like something went wrong.';
if (
$exception instanceof HttpException
&& $exception->getStatusCode() === 404
) {
$title = 'Sorry, the page you are looking for could not be found.';
}
$content = '';
if ($this->displayErrors) {
try {
$exceptions = [
$exception,
];
$e = $exception;
while ($e = $e->getPrevious()) {
$exceptions[] = $e;
}
$count = \count($exceptions);
$total = $count;
/**
* @var int
* @var \Throwable $e
*/
foreach ($exceptions as $position => $e) {
$ind = $count - $position;
$class = $this->formatClass(\get_class($e));
$message = nl2br($this->escapeHtml($e->getMessage()));
$content .= sprintf(
<<<'EOF'
<h2 class="block_exception clear_fix">
<span class="exception_counter">%d/%d</span>
<span class="exception_title">%s%s:</span>
<span class="exception_message">%s</span>
</h2>
<div class="block">
<ol class="traces list_exception">
EOF
,
$ind,
$total,
$class,
$this->formatPath(
$e->getTrace()[0]['file'] ?? 'Unknown file',
$e->getTrace()[0]['line'] ?? 0
),
$message
);
foreach ($e->getTrace() as $trace) {
$traceClass = $trace['class'] ?? '';
$traceArgs = $trace['args'] ?? [];
$traceType = $trace['type'] ?? '';
$traceFunction = $trace['function'] ?? '';
$content .= ' <li>';
if ($trace['function']) {
$content .= sprintf(
'at %s%s%s(%s)',
$this->formatClass($traceClass),
$traceType,
$traceFunction,
$this->formatArgs($traceArgs)
);
}
if (isset($trace['file'], $trace['line'])) {
$content .= $this->formatPath(
$trace['file'],
$trace['line']
);
}
$content .= "</li>\n";
}
$content .= " </ol>\n</div>\n";
}
} catch (Exception $e) {
// Something nasty happened and we cannot throw an exception anymore
$title = sprintf(
'Exception thrown when handling an exception (%s: %s)',
\get_class($e),
$this->escapeHtml($e->getMessage())
);
}
}
return <<<EOF
<div id="sf-resetcontent" class="sf-reset">
<h1>$title</h1>
$content
</div>
EOF;
} | php | {
"resource": ""
} |
q267732 | ExceptionHandler.formatPath | test | protected function formatPath(string $path, int $line): string
{
$path = $this->escapeHtml($path);
$file = preg_match('#[^/\\\\]*$#', $path, $file)
? $file[0]
: $path;
if ($linkFormat = $this->fileLinkFormat) {
$link = strtr(
$this->escapeHtml($linkFormat),
['%f' => $path, '%l' => $line]
);
return sprintf(
' in <a href="%s" title="Go to source">%s line %d</a>',
$link,
$file,
$line
);
}
return sprintf(
' in <a title="%s line %3$d" ondblclick="let f=this.innerHTML;this.innerHTML=this.title;this.title=f;">%s line %d</a>',
$path,
$file,
$line
);
} | php | {
"resource": ""
} |
q267733 | ExceptionHandler.formatArgs | test | protected function formatArgs(array $args): string
{
$result = [];
foreach ($args as $key => $item) {
if (\is_object($item)) {
$formattedValue = sprintf(
'<em>object</em>(%s)',
$this->formatClass(\get_class($item))
);
} elseif (\is_array($item)) {
$formattedValue = sprintf(
'<em>array</em>(%s)',
$this->formatArgs($item)
);
} elseif (\is_string($item)) {
$formattedValue = sprintf("'%s'", $this->escapeHtml($item));
} elseif (null === $item) {
$formattedValue = '<em>null</em>';
} elseif (\is_bool($item)) {
$formattedValue = '<em>'
. strtolower(var_export($item, true))
. '</em>';
} elseif (\is_resource($item)) {
$formattedValue = '<em>resource</em>';
} else {
$formattedValue = str_replace(
"\n",
'',
var_export($this->escapeHtml((string) $item), true)
);
}
$result[] = \is_int($key)
? $formattedValue
: sprintf("'%s' => %s", $key, $formattedValue);
}
return implode(', ', $result);
} | php | {
"resource": ""
} |
q267734 | ExceptionHandler.escapeHtml | test | protected function escapeHtml(string $str): string
{
return htmlspecialchars(
$str,
ENT_QUOTES | ENT_SUBSTITUTE,
$this->charset
);
} | php | {
"resource": ""
} |
q267735 | LaravelValidationService.with | test | public function with(array $data, array $rules) {
$this->validator = $this->factory->make($data, $rules);
} | php | {
"resource": ""
} |
q267736 | InputParser.transforms | test | public function transforms($string)
{
if (!is_string($string)) {
throw new InvalidArgumentException('A string is required');
}
if (false == preg_match('#^[a-zA-Z0-9]+$#', $string)) {
throw new InvalidArgumentException('A valid string is required');
}
$inputs = [];
$splitted = str_split($string);
foreach ($splitted as $value) {
$inputs[] = new Input($value);
}
return $inputs;
} | php | {
"resource": ""
} |
q267737 | Plugin.handleDisconnect | test | public function handleDisconnect(ConnectionInterface $connection, LoggerInterface $logger)
{
$timers = $this->getTimers();
if ($timers->contains($connection)) {
$this->getLogger()->debug('Detaching activity listener for disconnected connection');
$timers->offsetGet($connection)->cancel();
$timers->detach($connection);
}
} | php | {
"resource": ""
} |
q267738 | Plugin.handleReceived | test | public function handleReceived(Event $event, Queue $queue)
{
$connection = $event->getConnection();
$timers = $this->getTimers();
if ($timers->contains($connection)) {
$timers->offsetGet($connection)->cancel();
} else {
$this->getLogger()->debug('Attaching activity listener for connection');
}
$timer = $this->getLoop()->addTimer($this->wait, array($this, 'callbackPhoneHome'));
$timer->setData($connection);
$timers->attach($connection, $timer);
} | php | {
"resource": ""
} |
q267739 | Plugin.callbackPhoneHome | test | public function callbackPhoneHome(TimerInterface $caller)
{
$connection = $caller->getData();
$this->getLogger()->debug('Inactivity period reached, sending CTCP PING');
$this->getEventQueueFactory()->getEventQueue($connection)->ctcpPing($connection->getNickname(), time());
$timer = $this->getLoop()->addTimer($this->timeout, array($this, 'callbackGrimReaper'));
$timer->setData($connection);
$this->getTimers()->attach($connection, $timer);
} | php | {
"resource": ""
} |
q267740 | Plugin.callbackGrimReaper | test | public function callbackGrimReaper(TimerInterface $caller)
{
$connection = $caller->getData();
$this->getLogger()->debug('CTCP PING timeout reached, closing connection');
$this->getEventQueueFactory()->getEventQueue($connection)->ircQuit();
} | php | {
"resource": ""
} |
q267741 | CommandDispatcherFactory.getProxyCommandHandler | test | protected function getProxyCommandHandler(ServiceLocatorInterface $serviceLocator, string $key): object
{
$eventStore = $serviceLocator->getService(EventStoreInterface::class);
$eventPublisher = $serviceLocator->getService(EventPublisherInterface::class);
$aggregate = $serviceLocator->getService($key);
/**
* @var EventStoreInterface $eventStore
* @var EventPublisherInterface $eventPublisher
* @var EventSourcedAggregateInterface $aggregate
*/
return new ProxyCommandHandler(
new EventStoreRepository($eventStore, $eventPublisher, $aggregate)
);
} | php | {
"resource": ""
} |
q267742 | Dev.cb_configAction | test | public function cb_configAction()
{
$config = $this->getContainer()->get('config')->dump();
$reflection_cb = new \ReflectionClass('\CarteBlanche\App\Kernel');
$constants = $reflection_cb->getConstants();
$mode_data = \CarteBlanche\CarteBlanche::getKernelMode(true);
return array(self::$views_dir.'app_config', array(
'title' => $this->trans('Application full config'),
'debug' => isset($mode_data['debug']) ? $mode_data['debug'] : false,
'constants'=>$constants,
'config' => $config,
));
} | php | {
"resource": ""
} |
q267743 | ConfigLoader.loadBundles | test | final public function loadBundles()
{
$projectBundleConfig = [];
if (is_readable($this->getConfigDir() . '/bundles.yml')) {
$projectBundleConfig = Yaml::parse(
file_get_contents($this->getConfigDir() . '/bundles.yml')
);
return $projectBundleConfig;
}
return $projectBundleConfig;
} | php | {
"resource": ""
} |
q267744 | JsonCache.loadMessages | test | protected function loadMessages() {
if ( $this->messages === null ) {
$this->messages = array();
foreach ( glob( "{$this->messageDirectory}/*.json" ) as $file ) {
$lang = strtolower( substr( basename( $file ), 0, -5 ) );
if ( $lang === 'qqq' ) {
// Ignore message documentation
continue;
}
if ( is_readable( $file ) ) {
$json = file_get_contents( $file );
if ( $json === false ) {
$this->logger->error( 'Error reading file', array(
'method' => __METHOD__,
'file' => $file,
) );
continue;
}
$data = json_decode( $json, true );
if ( $data === null ) {
$this->logger->error( 'Error parsing json', array(
'method' => __METHOD__,
'file' => $file,
'json_error' => json_last_error(),
) );
continue;
}
// Discard metadata
unset( $data['@metadata'] );
if ( empty( $data ) ) {
// Ignore empty languages
continue;
}
$this->messages[$lang] = $data;
}
}
}
} | php | {
"resource": ""
} |
q267745 | Requester.setHttpHeaders | test | public function setHttpHeaders(array $inHttpHeaders, $inMerge=false) {
if ($inMerge) {
$this->__httpHeaders = array_merge($this->__httpHeaders, $inHttpHeaders);
} else {
$this->__httpHeaders = $inHttpHeaders;
}
return $this;
} | php | {
"resource": ""
} |
q267746 | Requester.setServerCgiEnvironmentVariables | test | public function setServerCgiEnvironmentVariables(array $inServerCgiEnvironmentVariables, $inMerge=false) {
if ($inMerge) {
$this->__serverCgiEnvironmentVariables = array_merge($this->__serverCgiEnvironmentVariables, $inServerCgiEnvironmentVariables);
} else {
$this->__serverCgiEnvironmentVariables = $inServerCgiEnvironmentVariables;
}
return $this;
} | php | {
"resource": ""
} |
q267747 | Requester.post | test | public function post($inRequestUri, $inPostParameters=[]) {
// Prepare the content of the request's body.
$bodyContent = [];
foreach ($inPostParameters as $_name => $_value) {
$bodyContent[] = $_name . '=' . urlencode($_value);
}
$bodyContent = implode('&', $bodyContent);
// Prepare the request's headers.
if (! array_key_exists('Content-Type', $this->__httpHeaders)) {
$this->__httpHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (! array_key_exists('Content-Length', $this->__httpHeaders)) {
$this->__httpHeaders['Content-Length'] = strlen($bodyContent);
}
return $this->request('POST', $inRequestUri, '', $bodyContent);
} | php | {
"resource": ""
} |
q267748 | Requester.jsonRpc | test | public function jsonRpc($inRequestUri, $inParameters=[]) {
$bodyContent = json_encode($inParameters);
// Prepare the request's headers.
if (! array_key_exists('Content-Type', $this->__httpHeaders)) {
$this->__httpHeaders['Content-Type'] = 'application/jsonrequest';
}
if (! array_key_exists('Accept', $this->__httpHeaders)) {
$this->__httpHeaders['Accept'] = 'application/jsonrequest';
}
if (! array_key_exists('Content-Length', $this->__httpHeaders)) {
$this->__httpHeaders['Content-Length'] = strlen($bodyContent);
}
return $this->request('POST', $inRequestUri, '', $bodyContent);
} | php | {
"resource": ""
} |
q267749 | SqliteDriver.connect | test | public function connect()
{
/*
$this->db = new \SQLiteDatabase(
$this->db_name,
isset($this->db_options['chmod']) ? $this->db_options['chmod'] : 0644,
$err
);
if ($err) throw new ErrorException(
sprintf('Can not connect or create SQLite database "%s" [%s]!', $this->db_name, $err)
);
*/
try {
$this->db = new \SQLite3($this->db_name);
} catch (\Exception $e) {
throw $e;
}
$this->db_name = str_replace(array(
CarteBlanche::getPath('root_path'),
CarteBlanche::getPath('db_dir')
), '', $this->db_name);
return $this->db;
} | php | {
"resource": ""
} |
q267750 | SqliteDriver.escape | test | static function escape($str = null, $double_quotes = false)
{
return sqlite_escape_string(
true===$double_quotes ? str_replace('"', '""', $str) : $str
);
} | php | {
"resource": ""
} |
q267751 | AssetBundle.init | test | public function init()
{
if ($this->sourcePath !== null) {
$this->sourcePath = rtrim(Reaction::$app->getAlias($this->sourcePath), '/\\');
}
if ($this->basePath !== null) {
$this->basePath = rtrim(Reaction::$app->getAlias($this->basePath), '/\\');
}
if ($this->baseUrl !== null) {
$this->baseUrl = rtrim(Reaction::$app->getAlias($this->baseUrl), '/');
}
} | php | {
"resource": ""
} |
q267752 | AbstractModel.hasSlugField | test | public function hasSlugField()
{
foreach($this->_table_structure as $_field=>$field_structure) {
if (isset($field_structure['slug']) && $field_structure['slug']===true) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q267753 | AbstractModel.getSpecialFields | test | public function getSpecialFields($field, $value = true)
{
$fields = array();
foreach($this->_table_structure as $_field=>$field_structure) {
if (isset($field_structure[$field]) && $field_structure[$field]===$value) {
$fields[] = $_field;
}
}
return $fields;
} | php | {
"resource": ""
} |
q267754 | AbstractModel.getFieldsByType | test | public function getFieldsByType($type)
{
$fields = array();
foreach($this->_table_structure as $_field=>$field_structure) {
if (isset($field_structure['type']) && $field_structure['type']==$type) {
$fields[] = $_field;
}
}
return $fields;
} | php | {
"resource": ""
} |
q267755 | HTTP2.date | test | public function date($time = null)
{
if (!isset($time)) {
$time = time();
} elseif (!is_numeric($time) && (-1 === $time = strtotime($time))) {
return false;
}
// RFC822 or RFC850
$format = ini_get('y2k_compliance') ? 'D, d M Y' : 'l, d-M-y';
return gmdate($format .' H:i:s \G\M\T', $time);
} | php | {
"resource": ""
} |
q267756 | HTTP2.negotiateLanguage | test | public function negotiateLanguage($supported, $default = 'en-US')
{
$supp = array();
foreach ($supported as $lang => $isSupported) {
if ($isSupported) {
$supp[strtolower($lang)] = $lang;
}
}
if (!count($supp)) {
return $default;
}
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$match = $this->matchAccept(
$_SERVER['HTTP_ACCEPT_LANGUAGE'],
$supp
);
if (!is_null($match)) {
return $match;
}
}
if (isset($_SERVER['REMOTE_HOST'])) {
$lang = strtolower(end($h = explode('.', $_SERVER['REMOTE_HOST'])));
if (isset($supp[$lang])) {
return $supp[$lang];
}
}
return $default;
} | php | {
"resource": ""
} |
q267757 | HTTP2.negotiateCharset | test | public function negotiateCharset($supported, $default = 'ISO-8859-1')
{
$supp = array();
foreach ($supported as $charset) {
$supp[strtolower($charset)] = $charset;
}
if (!count($supp)) {
return $default;
}
if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
$match = $this->matchAccept(
$_SERVER['HTTP_ACCEPT_CHARSET'],
$supp
);
if (!is_null($match)) {
return $match;
}
}
return $default;
} | php | {
"resource": ""
} |
q267758 | HTTP2.negotiateMimeType | test | public function negotiateMimeType($supported, $default)
{
$supp = array();
foreach ($supported as $type) {
$supp[strtolower($type)] = $type;
}
if (!count($supp)) {
return $default;
}
if (isset($_SERVER['HTTP_ACCEPT'])) {
$accepts = $this->sortAccept($_SERVER['HTTP_ACCEPT']);
foreach ($accepts as $type => $q) {
if (substr($type, -2) != '/*') {
if (isset($supp[$type])) {
return $supp[$type];
}
continue;
}
if ($type == '*/*') {
return array_shift($supp);
}
list($general, $specific) = explode('/', $type);
$general .= '/';
$len = strlen($general);
foreach ($supp as $mime => $t) {
if (strncasecmp($general, $mime, $len) == 0) {
return $t;
}
}
}
}
return $default;
} | php | {
"resource": ""
} |
q267759 | HTTP2.matchAccept | test | protected function matchAccept($header, $supported)
{
$matches = $this->sortAccept($header);
foreach ($matches as $key => $q) {
if (isset($supported[$key])) {
return $supported[$key];
}
}
// If any (i.e. "*") is acceptable, return the first supported format
if (isset($matches['*'])) {
return array_shift($supported);
}
return null;
} | php | {
"resource": ""
} |
q267760 | HTTP2.sortAccept | test | protected function sortAccept($header)
{
$matches = array();
foreach (explode(',', $header) as $option) {
$option = array_map('trim', explode(';', $option));
$l = strtolower($option[0]);
if (isset($option[1])) {
$q = (float) str_replace('q=', '', $option[1]);
} else {
$q = null;
// Assign default low weight for generic values
if ($l == '*/*') {
$q = 0.01;
} elseif (substr($l, -1) == '*') {
$q = 0.02;
}
}
// Unweighted values, get high weight by their position in the
// list
$matches[$l] = isset($q) ? $q : 1000 - count($matches);
}
arsort($matches, SORT_NUMERIC);
return $matches;
} | php | {
"resource": ""
} |
q267761 | HTTP2.head | test | public function head($url, $timeout = 10)
{
$p = parse_url($url);
if (!isset($p['scheme'])) {
$p = parse_url($this->absoluteURI($url));
} elseif ($p['scheme'] != 'http') {
throw new InvalidArgumentException(
'Unsupported protocol: '. $p['scheme']
);
}
$port = isset($p['port']) ? $p['port'] : 80;
if (!$fp = @fsockopen($p['host'], $port, $eno, $estr, $timeout)) {
throw new HTTP2_Exception("Connection error: $estr ($eno)");
}
$path = !empty($p['path']) ? $p['path'] : '/';
$path .= !empty($p['query']) ? '?' . $p['query'] : '';
fputs($fp, "HEAD $path HTTP/1.0\r\n");
fputs($fp, 'Host: ' . $p['host'] . ':' . $port . "\r\n");
fputs($fp, "Connection: close\r\n\r\n");
$response = rtrim(fgets($fp, 4096));
if (preg_match("|^HTTP/[^\s]*\s(.*?)\s|", $response, $status)) {
$headers['response_code'] = $status[1];
}
$headers['response'] = $response;
while ($line = fgets($fp, 4096)) {
if (!trim($line)) {
break;
}
if (($pos = strpos($line, ':')) !== false) {
$header = substr($line, 0, $pos);
$value = trim(substr($line, $pos + 1));
$headers[$header] = $value;
}
}
fclose($fp);
return $headers;
} | php | {
"resource": ""
} |
q267762 | HTTP2.convertCharset | test | protected function convertCharset($from, $to, $str)
{
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($str, $to, $from);
} else if (function_exists('iconv')) {
return iconv($from, $to, $str);
}
return $str;
} | php | {
"resource": ""
} |
q267763 | AutoObjectMapper.getEntityManager | test | static function getEntityManager($emname)
{
$_this = self::getInstance();
$emname = $_this->buildEntityName($emname);
$known_manager = $_this->registry->getEntry($emname, 'entityManager');
if ($known_manager) {
return $known_manager;
} else {
// $manager = $_this->buildEntityManager($emname);
$manager = CarteBlanche::getContainer()->get('entity_manager')
->getStorageEngine($emname);
$_this->registry->setEntry($emname, $manager, 'entityManager');
return $manager;
}
} | php | {
"resource": ""
} |
q267764 | AutoObjectMapper.getObjectsStructure | test | static function getObjectsStructure($dbname = null)
{
$_this = self::getInstance();
$dbname = $_this->buildEntityName($dbname);
$known_structure = $_this->registry->getEntry($dbname, 'objectStructure');
if ($known_structure) {
return $known_structure;
} else {
$structure = $_this->buildObjectsStructure($dbname);
$_this->registry->setEntry($dbname, $structure, 'objectStructure');
return $structure;
}
} | php | {
"resource": ""
} |
q267765 | AutoObjectMapper.getAutoObject | test | static function getAutoObject($tablename = null, $dbname = null)
{
if (empty($tablename)) return false;
$tables = self::getObjectsStructure( $dbname );
if ($tables) {
foreach ($tables as $_tbl_name=>$_tbl_obj) {
if ($_tbl_obj->getTableName()==$tablename) {
return $_tbl_obj;
}
}
}
return false;
} | php | {
"resource": ""
} |
q267766 | AutoObjectMapper.getTableStructure | test | static function getTableStructure($tablename = null, $dbname = null)
{
$_tbl_obj = self::getAutoObject( $tablename, $dbname );
if (!empty($_tbl_obj)) {
return $_tbl_obj->getStructureEntry('structure');
}
return false;
} | php | {
"resource": ""
} |
q267767 | AutoObjectMapper.getModel | test | static function getModel($tablename = null, $dbname = null)
{
$_tbl_obj = self::getAutoObject( $tablename, $dbname );
if (!empty($_tbl_obj)) {
return $_tbl_obj->getModel();
}
return false;
} | php | {
"resource": ""
} |
q267768 | AutoObjectMapper.buildObjectsStructure | test | protected function buildObjectsStructure($dbname = null)
{
$dbname = str_replace(array(CarteBlanche::getPath('root_path'), CarteBlanche::getPath('config_dir')), '', $dbname);
$tables_def = CarteBlanche::getConfig($dbname.'_database.db_structure');
$tables_def_file = Locator::locateConfig($tables_def);
if ($tables_def_file && @file_exists($tables_def_file) && @is_file($tables_def_file)) {
$table = array();
include $tables_def_file;
if (!empty($tables)) {
$tables_stacks=array();
foreach ($tables as $_tbl) {
$_t_n = $_tbl['table'];
$tables_stacks[$_t_n] = new \CarteBlanche\Library\AutoObject\AutoObject( $_t_n, $_tbl, $_t_n, $dbname );
$this->registry->setEntry(
$_tbl['table'],
$tables_stacks[$_t_n],
$dbname
);
}
return $tables_stacks;
} else
throw new \RuntimeException(
sprintf('Tables definition can\'t be found in file "%s"!', $tables_def)
);
} else
throw new \RuntimeException(
sprintf('Tables definition file "%s" can\'t be found!', $tables_def)
);
} | php | {
"resource": ""
} |
q267769 | Length.prepareError | test | protected function prepareError($code)
{
$min = $this->getArgValue('min');
$max = $this->getArgValue('max');
$error = Translation::get($code);
$error = str_replace('%min%', $min, $error);
$error = str_replace('%max%', $max, $error);
return $error;
} | php | {
"resource": ""
} |
q267770 | BudgetMonthMapper.check | test | public function check($budgets, \DateTimeImmutable $date)
{
foreach ($budgets as $budget) {
$this->checkBudget($budget, $date);
if ($budget->hasChildren()) {
foreach ($budget->getChildren() as $child) {
$this->checkBudget($child, $date);
}
}
}
} | php | {
"resource": ""
} |
q267771 | BudgetMonthMapper.checkBudget | test | protected function checkBudget(Budget $budget, \DateTimeImmutable $date)
{
try {
$this->addWhere('budget_id', $budget->getId());
$this->addWhere('budget_month_date', $date->format('Y-m-d'));
$this->selectOne();
} catch (ExceptionNoData $exception) {
//~ If not exist, create this budget month
//$dateNow = new \DateTimeImmutable();
$dateStart = new \DateTimeImmutable($budget->getDateStart());
$dateEnd = null;
if (!empty($budget->getDateEnd())) {
$dateEnd = new \DateTimeImmutable($budget->getDateEnd());
}
$isInRecurrence = $budget->isRecurrent() && $dateStart < $date && ($dateEnd === null || $dateEnd >= $date) && $budget->hasMonth((int) $date->format('m'));
$isFirstMonth = ($dateStart == $date);
if ($isInRecurrence || $isFirstMonth) {
$budgetMonth = $this->newDataInstance();
$budgetMonth->setBudgetId($budget->getId());
$budgetMonth->setDate($date->format('Y-m-d'));
$budgetMonth->setAmount($budget->getAmountDefault());
$this->insert($budgetMonth);
}
}
} | php | {
"resource": ""
} |
q267772 | BudgetMonthMapper.findByBudgetId | test | public function findByBudgetId($budgetId, \DateTimeImmutable $date)
{
$this->addWhere('budget_id', $budgetId);
$this->addWhere('budget_month_date', $date->format('Y-m-d'));
$result = $this->selectOne();
return $result;
} | php | {
"resource": ""
} |
q267773 | AccountAbstract.setIdParent | test | public function setIdParent($idParent)
{
$idParent = (int) $idParent;
if ($this->idParent < 0) {
throw new \UnderflowException('Value of "idParent" must be greater than 0');
}
if ($this->exists() && $this->idParent !== $idParent) {
$this->updated['idParent'] = true;
}
$this->idParent = $idParent;
return $this;
} | php | {
"resource": ""
} |
q267774 | AccountAbstract.setIsMain | test | public function setIsMain($isMain)
{
$isMain = (bool) $isMain;
if ($this->exists() && $this->isMain !== $isMain) {
$this->updated['isMain'] = true;
}
$this->isMain = $isMain;
return $this;
} | php | {
"resource": ""
} |
q267775 | AccountAbstract.getAccountUser | test | public function getAccountUser($isForceReload = false)
{
if ($isForceReload || null === $this->joinOneCacheAccountUser) {
$mapper = new AccountUserMapper($this->dependencyContainer->getDatabase('money'));
$this->joinOneCacheAccountUser = $mapper->findByKeys(array(
'account_id' => $this->getId(),
));
}
return $this->joinOneCacheAccountUser;
} | php | {
"resource": ""
} |
q267776 | AccountAbstract.getBank | test | public function getBank($isForceReload = false)
{
if ($isForceReload || null === $this->joinOneCacheBank) {
$mapper = new BankMapper($this->dependencyContainer->getDatabase('money'));
$this->joinOneCacheBank = $mapper->findByKeys(array(
'bank_id' => $this->getBankId(),
));
}
return $this->joinOneCacheBank;
} | php | {
"resource": ""
} |
q267777 | ParserAbstract.parse | test | public function parse(Account $account, $file)
{
$file = new \SplFileObject($file);
$file->setCsvControl($this->csvDelimiter, $this->csvEnclosure, $this->csvEscape);
$file->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_CSV);
$transactionMapper = new TransactionMapper(Database::get('money'));
$transactions = array();
$file->seek($this->startAtLine);
while (!$file->eof()) {
$this->setLine($file->current());
$transactions[] = $this->createTransaction($transactionMapper, $account);
$file->next();
}
if ($this->dropNbLastLines > 0) {
$transactions = array_slice($transactions, 0, -$this->dropNbLastLines);
}
return $transactions;
} | php | {
"resource": ""
} |
q267778 | Transaction.getTypeIcon | test | public function getTypeIcon()
{
switch ($this->getType()) {
case 'CB':
$icon = 'credit-card';
break;
case 'VIR':
$icon = 'arrow-circle-o-' . ($this->isNegativeAmount() ? 'up' : 'down');
break;
case 'PRE':
$icon = 'arrow-circle-up';
break;
case 'CHQ':
$icon = 'money';
break;
case 'PPL':
$icon = 'paypal';
break;
default:
$icon = 'money';
}
return $icon;
} | php | {
"resource": ""
} |
q267779 | MysqlDBAdapter.buildQuery | test | public function buildQuery(QC $qc, $type = null) {
if (!$type) $type = $qc->getType();
$methodName = 'build' . ucfirst($type);
if (method_exists($this, $methodName)) {
$result = $this->$methodName($qc);
} else {
throw new MysqlDBAdapterException('Invalid method specified: '.$type);
}
return $result;
} | php | {
"resource": ""
} |
q267780 | MysqlDBAdapter.escapeOne | test | protected function escapeOne($value, $type = false) {
if ($type === false) {
$type = gettype($value);
}
if (strpos($value, '#sql#') !== false) {
return substr($value, 5);
}
if (in_array($type, array('integer'))) {
return $value;
} elseif ($type == 'boolean') {
return intval($value);
} elseif ($type == 'NULL') {
return 'null';
} else {
return $this->_dbh->quote($value);
}
} | php | {
"resource": ""
} |
q267781 | NativeRedirectResponse.createRedirect | test | public static function createRedirect(
string $uri = null,
int $status = StatusCode::FOUND,
array $headers = []
): RedirectResponse {
return new static('', $status, $headers, $uri);
} | php | {
"resource": ""
} |
q267782 | NativeRedirectResponse.secure | test | public function secure(string $path = null): RedirectResponse
{
// If not path was set
if (null === $path) {
// If the uri is already set
if (null !== $this->uri) {
// Set the path to it
$path = $this->uri;
} else {
// Otherwise set the path to the current path w/ query string
$path = request()->getPath();
}
}
// If the path doesn't start with a /
if ('/' !== $path[0]) {
// Set the uri as the path
$this->setUri($path);
// Return out of the method
return $this;
}
// Set the uri to https with the host and path
$this->setUri('https://' . request()->getHttpHost() . $path);
return $this;
} | php | {
"resource": ""
} |
q267783 | NativeRedirectResponse.back | test | public function back(): RedirectResponse
{
$refererUri = request()->headers()->get('Referer');
// Ensure the route being redirected to is a valid internal route
if (! router()->isInternalUri($refererUri)) {
// If not set as the index
$refererUri = '/';
}
$this->setUri($refererUri ?: '/');
return $this;
} | php | {
"resource": ""
} |
q267784 | NativeRedirectResponse.throw | test | public function throw(): void
{
throw new HttpRedirectException(
$this->statusCode,
$this->uri,
null,
$this->headers->all()
);
} | php | {
"resource": ""
} |
q267785 | CommandsListCommand.filterCommands | test | protected function filterCommands(array &$commands, int &$longestLength, string $namespace = null): void
{
$globalCommands = [];
/** @var \Valkyrja\Console\Command $command */
foreach ($commands as $key => $command) {
$parts = explode(':', $command->getName());
$commandName = $parts[1] ?? null;
$commandNamespace = $commandName ? $parts[0] : 'global';
// If there was a namespace passed to the command (commands
// namespace) and the namespace for this command doesn't match
// what was passed then get rid of it so only commands in the
// namespace are shown.
if ($commandNamespace !== $namespace && null !== $namespace) {
unset($commands[$key]);
continue;
}
$longestLength = max(\strlen($command->getName()), $longestLength);
// If this is a global namespaced command
if ('global' === $commandNamespace) {
// Set it in the global commands array so when we show the list
// of commands global commands will be at the top
$globalCommands[] = $command;
// Unset from the commands list to avoid duplicates
unset($commands[$key]);
}
}
// Sort the global commands by name
$this->sortCommands($globalCommands);
// Sort the rest of the commands by name
$this->sortCommands($commands);
// Set the commands as the merged results of the global and other
// commands with the global commands at the top of the list
$commands = array_merge($globalCommands, $commands);
} | php | {
"resource": ""
} |
q267786 | CommandsListCommand.sortCommands | test | protected function sortCommands(array &$commands): void
{
usort(
$commands,
function (Command $item1, Command $item2) {
return $item1->getName() <=> $item2->getName();
}
);
} | php | {
"resource": ""
} |
q267787 | CommandsListCommand.commandSection | test | protected function commandSection(Command $command, string &$previousSection): void
{
$parts = explode(':', $command->getName());
$commandName = $parts[1] ?? null;
$currentSection = $commandName ? $parts[0] : 'global';
if ($previousSection !== $currentSection) {
output()->formatter()->cyan();
output()->writeMessage(static::TAB);
output()->writeMessage($currentSection, true);
$previousSection = $currentSection;
}
} | php | {
"resource": ""
} |
q267788 | Session.initSession | test | function initSession() {
static $initSessionCalled = false;
if($initSessionCalled == true){
return;
}
$initSessionCalled = true;
$currentCookieParams = session_get_cookie_params();
$domainInfo = $this->domain->getDomainInfo();
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
'.'.$domainInfo->rootCanonicalDomain, //leading dot according to http://www.faqs.org/rfcs/rfc2109.html
$currentCookieParams["secure"],
$currentCookieParams["httponly"]
);
session_name($this->sessionName);
if (isset($_COOKIE[$this->sessionName])) {
//Only start the session automatically, if the user sent us a cookie.
$this->startSession();
}
} | php | {
"resource": ""
} |
q267789 | Timer.start | test | public static function start($name = null)
{
if (null === $name) {
static::$time = -static::getTime();
} else {
static::$times[$name] = -static::getTime();
}
} | php | {
"resource": ""
} |
q267790 | Timer.get | test | public static function get($name = null)
{
if (null === $name) {
$time = static::$time;
} elseif (isset(static::$times[$name])) {
$time = static::$times[$name];
} else {
throw new \LogicException('Timer with given name does not exist!');
}
return ($time + static::getTime());
} | php | {
"resource": ""
} |
q267791 | Timer.display | test | public static function display($name = null, $round = 3)
{
$time = round(static::get($name), $round);
$name = ($name === null ? 'GLOBAL' : $name);
if (PHP_SAPI !== 'cli') {
echo '
<div style="background-color: #99CCCC">
<strong>Timer[' . $name . ']: </strong> ' . $time . ' s
</div>';
} else {
echo ' ### Timer[' . $name . ']: ' . $time . 's ###' . PHP_EOL;
}
} | php | {
"resource": ""
} |
q267792 | ProvidersAwareTrait.initializeProvided | test | public function initializeProvided(string $itemId): void
{
/** @var \Valkyrja\Support\Providers\Provides $provider */
$provider = self::$provided[$itemId];
// Register the provider
$this->register($provider, true);
} | php | {
"resource": ""
} |
q267793 | Reaction.init | test | public static function init(Composer\Autoload\ClassLoader $composer = null, $configsPath = null, $appType = StaticApplicationInterface::APP_TYPE_WEB)
{
static::initBasic($composer, $configsPath, $appType);
static::initStaticApp();
} | php | {
"resource": ""
} |
q267794 | Reaction.initBasic | test | public static function initBasic(Composer\Autoload\ClassLoader $composer = null, $configsPath = null, $appType = StaticApplicationInterface::APP_TYPE_WEB)
{
if (!isset($composer)) {
$composer = static::locateClassLoader();
}
if (!isset($configsPath)) {
$configsPath = static::locateConfigsPath();
}
if (!isset($composer)) {
throw new \Reaction\Exceptions\InvalidArgumentException("Missing \$composer option");
}
if (!isset($configsPath)) {
throw new \Reaction\Exceptions\InvalidArgumentException("Missing \$configsPath option");
}
static::$composer = $composer;
static::$configsPath = $configsPath;
static::$appType = $appType;
static::initConfigReader();
static::initAnnotationReader();
static::initContainer();
} | php | {
"resource": ""
} |
q267795 | Reaction.locateConfigsPath | test | protected static function locateConfigsPath()
{
$cwd = getcwd();
$defaultDir = DIRECTORY_SEPARATOR . 'Config';
$path = $cwd . $defaultDir;
if (!file_exists($path) || !is_dir($path)) {
return null;
}
return $path;
} | php | {
"resource": ""
} |
q267796 | Reaction.locateClassLoader | test | protected static function locateClassLoader()
{
$cwd = getcwd();
$path = $cwd . DIRECTORY_SEPARATOR . 'vendor/autoload.php';
if (!file_exists($path) || !is_file($path)) {
return null;
}
return include $path;
} | php | {
"resource": ""
} |
q267797 | Reaction.create | test | public static function create($type, array $params = [])
{
if (is_string($type)) {
return static::$di->getOrCreate($type, $params);
} elseif (is_array($type) && isset($type['class'])) {
$class = $type['class'];
unset($type['class']);
return static::$di->getOrCreate($class, $params, $type);
} elseif (is_callable($type, true)) {
return static::$di->invoke($type, $params);
} elseif (is_array($type)) {
throw new \Reaction\DI\Exceptions\InvalidConfigException('Object configuration must be an array containing a "class" element.');
}
throw new \Reaction\DI\Exceptions\InvalidConfigException('Unsupported configuration type: ' . gettype($type));
} | php | {
"resource": ""
} |
q267798 | Reaction.getConfigReader | test | protected static function getConfigReader($flush = false)
{
if ($flush || !isset(static::$config)) {
$conf = [
'path' => static::$configsPath,
'appType' => static::$appType,
];
static::$config = new \Reaction\Base\ConfigReader($conf);
}
return static::$config;
} | php | {
"resource": ""
} |
q267799 | Reaction.initContainer | test | protected static function initContainer()
{
$config = static::getConfigReader()->get('container');
Container::setDefaultContainer(new Container($config));
static::$di = Container::getDefaultContainer();
} | php | {
"resource": ""
} |
Subsets and Splits