_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q265700 | QueryBuilder.having | test | public function having($having)
{
if (!(func_num_args() == 1 && $having instanceof CompositeExpression)) {
$having = new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
}
return $this->add('having', $having);
} | php | {
"resource": ""
} |
q265701 | QueryBuilder.getSQLForDelete | test | private function getSQLForDelete()
{
$table = $this->sqlParts['from']['table'] . ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
$query = 'DELETE FROM ' . $table . ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string)$this->sqlParts['where']) : '');
return $query;
} | php | {
"resource": ""
} |
q265702 | QueryBuilder.createPositionalParameter | test | public function createPositionalParameter($value, $type = \PDO::PARAM_STR)
{
$this->boundCounter++;
$this->setParameter($this->boundCounter, $value, $type);
return "?";
} | php | {
"resource": ""
} |
q265703 | LoggerServiceProvider.bindLoggerInterface | test | protected static function bindLoggerInterface(Application $app): void
{
$handler = new StreamHandler(
$app->config()['logger']['filePath'],
LogLevel::DEBUG
);
$app->container()->singleton(
LoggerInterface::class,
new Monolog(
$app->config()['logger']['name'],
[
$handler,
]
)
);
} | php | {
"resource": ""
} |
q265704 | LoggerServiceProvider.bindLogger | test | protected static function bindLogger(Application $app): void
{
$app->container()->singleton(
Logger::class,
new MonologLogger(
$app->container()->getSingleton(LoggerInterface::class)
)
);
} | php | {
"resource": ""
} |
q265705 | ResponseBuilder.setStatusCode | test | public function setStatusCode($code = 200) {
$this->_statusCode = $code;
$this->_statusText = isset(Response::$httpStatuses[$this->_statusCode]) ? Response::$httpStatuses[$this->_statusCode] : '';
return $this;
} | php | {
"resource": ""
} |
q265706 | ResponseBuilder.getFormattedBody | test | public function getFormattedBody() {
$body = $this->getRawBody();
$bodyFormatted = null;
if ($body instanceof StreamInterface) {
return $body;
} elseif (isset($this->formatters[$this->format])) {
$formatter = $this->formatters[$this->format];
if (!is_object($formatter)) {
$this->formatters[$this->format] = $formatter = \Reaction::create($formatter);
}
if ($formatter instanceof ResponseFormatterInterface) {
$bodyFormatted = $formatter->format($this);
} else {
throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
}
} elseif ($this->format === Response::FORMAT_RAW) {
$bodyFormatted = $body;
} else {
throw new InvalidConfigException("Unsupported response format: {$this->format}");
}
if (is_array($bodyFormatted)) {
throw new InvalidArgumentException('Response content must not be an array.');
} elseif (is_object($bodyFormatted)) {
if (method_exists($bodyFormatted, '__toString')) {
$bodyFormatted = $bodyFormatted->__toString();
} else {
throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
}
}
return $bodyFormatted;
} | php | {
"resource": ""
} |
q265707 | ResponseBuilder.redirect | test | public function redirect($url, $statusCode = 302, $checkAjax = true)
{
if (is_array($url) && isset($url[0])) {
// ensure the route is absolute
$url[0] = '/' . ltrim($url[0], '/');
}
$url = $this->app->helpers->url->to($url);
if (strncmp($url, '/', 1) === 0 && strncmp($url, '//', 2) !== 0) {
$url = $this->app->reqHelper->getHostInfo() . $url;
}
if ($checkAjax) {
if ($this->app->reqHelper->getIsAjax()) {
if ($this->app->reqHelper->getHeaders()->get('X-Ie-Redirect-Compatibility') !== null && $statusCode === 302) {
// Ajax 302 redirect in IE does not work. Change status code to 200. See https://github.com/yiisoft/yii2/issues/9670
$statusCode = 200;
}
$this->getHeaders()->set('X-Redirect', $url);
} else {
$this->getHeaders()->set('Location', $url);
}
} else {
$this->getHeaders()->set('Location', $url);
}
$this->setBody(null);
$this->setStatusCode($statusCode);
return $this;
} | php | {
"resource": ""
} |
q265708 | ResponseBuilder.createEmptyResponse | test | protected function createEmptyResponse() {
$config = [];
$body = $this->getFormattedBody();
$params = [
$this->statusCode,
$this->getHeadersPrepared(),
$body,
$this->version,
$this->_statusText
];
if (is_array($this->responseClass)) {
$config = ArrayHelper::merge($config, $this->responseClass);
} else {
$config['class'] = $this->responseClass;
}
/** @var Response $response */
$response = \Reaction::create($config, $params);
return $response;
} | php | {
"resource": ""
} |
q265709 | ResponseBuilder.getHeadersPrepared | test | protected function getHeadersPrepared() {
$cookiesData = $this->getCookiesPrepared();
foreach ($cookiesData as $cookieStr) {
$this->headers->add('Set-Cookie', $cookieStr);
}
$headersArray = [];
if ($this->_headers) {
foreach ($this->getHeaders() as $name => $values) {
$name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
if (!isset($headersArray[$name])) {
$headersArray[$name] = [];
}
foreach ($values as $value) {
$headersArray[$name][] = $value;
}
}
}
return $headersArray;
} | php | {
"resource": ""
} |
q265710 | ResponseBuilder.getCookiesPrepared | test | protected function getCookiesPrepared() {
$cookies = [];
if ($this->_cookies) {
$request = $this->app->reqHelper;
if ($request->enableCookieValidation) {
if ($request->cookieValidationKey == '') {
throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
}
$validationKey = $request->cookieValidationKey;
} else {
$validationKey = null;
}
foreach ($this->getCookies() as $name => $cookie) {
/** @var Cookie $cookie */
$cookies[] = $cookie->getForHeader($validationKey);
}
}
return $cookies;
} | php | {
"resource": ""
} |
q265711 | ResponseBuilder.defaultFormatters | test | protected function defaultFormatters()
{
return [
Response::FORMAT_HTML => [
'class' => 'Reaction\Web\Formatters\HtmlResponseFormatter',
],
Response::FORMAT_XML => [
'class' => 'Reaction\Web\Formatters\XmlResponseFormatter',
],
Response::FORMAT_JSON => [
'class' => 'Reaction\Web\Formatters\JsonResponseFormatter',
],
Response::FORMAT_JSONP => [
'class' => 'Reaction\Web\Formatters\JsonResponseFormatter',
'useJsonp' => true,
],
];
} | php | {
"resource": ""
} |
q265712 | BasicAuthentication.extractAuthUserPass | test | private static function extractAuthUserPass($encodedString)
{
if (0 >= strlen($encodedString)) {
return false;
}
$decodedString = base64_decode($encodedString, true);
if (false === $decodedString) {
return false;
}
$firstColonPos = strpos($decodedString, ':');
if (false === $firstColonPos) {
return false;
}
return array(
'authUser' => substr($decodedString, 0, $firstColonPos),
'authPass' => substr($decodedString, $firstColonPos + 1),
);
} | php | {
"resource": ""
} |
q265713 | Model.scenarios | test | public function scenarios()
{
$scenarios = [self::SCENARIO_DEFAULT => []];
$this->fillScenariosKeys($scenarios);
$this->fillScenariosAttributes($scenarios);
foreach ($scenarios as $scenario => $attributes) {
if (!empty($attributes)) {
$scenarios[$scenario] = array_keys($attributes);
}
}
return $scenarios;
} | php | {
"resource": ""
} |
q265714 | Model.fillScenariosAttributes | test | protected function fillScenariosAttributes(array &$scenarios) {
$names = array_keys($scenarios);
foreach ($this->getValidators() as $validator) {
if (empty($validator->on) && empty($validator->except)) {
foreach ($names as $name) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
} elseif (empty($validator->on)) {
foreach ($names as $name) {
if (!in_array($name, $validator->except, true)) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
} else {
foreach ($validator->on as $name) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
}
} | php | {
"resource": ""
} |
q265715 | Model.formName | test | public function formName()
{
try {
$reflector = new ReflectionClass($this);
if (PHP_VERSION_ID >= 70000 && $reflector->isAnonymous()) {
throw new InvalidConfigException('The "formName()" method should be explicitly defined for anonymous models');
}
return $reflector->getShortName();
} catch (\ReflectionException $exception) {
$className = explode('\\', static::class);
return end($className);
}
} | php | {
"resource": ""
} |
q265716 | Model.attributes | test | public function attributes()
{
try {
$class = new ReflectionClass($this);
$names = [];
foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
if (!$property->isStatic()) {
$names[] = $property->getName();
}
}
} catch (\ReflectionException $exception) {
Reaction::error($exception);
$names = [];
}
return $names;
} | php | {
"resource": ""
} |
q265717 | Model.validate | test | public function validate($attributeNames = null, $clearErrors = true)
{
if ($clearErrors) {
$this->clearErrors();
}
if (!$this->beforeValidate()) {
return reject(new ValidationError("Before validate error"));
}
$scenarios = $this->scenarios();
$scenario = $this->getScenario();
if (!isset($scenarios[$scenario])) {
throw new InvalidArgumentException("Unknown scenario: $scenario");
}
if ($attributeNames === null) {
$attributeNames = $this->activeAttributes();
}
$attributeNames = (array)$attributeNames;
$validationPromises = [];
foreach ($this->getActiveValidators() as $validator) {
$validationPromises[] = $validator->validateAttributes($this, $attributeNames);
}
return Reaction\Promise\allInOrder($validationPromises)
->always(function() {
$this->afterValidate();
})->then(function() {
return !$this->hasErrors() ? true : reject(new ValidationError("Validation error"));
});
} | php | {
"resource": ""
} |
q265718 | Model.validateMultiple | test | public static function validateMultiple($models, $attributeNames = null)
{
$promises = [];
/* @var $model Model */
foreach ($models as $model) {
$promises[] = new Reaction\Promise\LazyPromise(function() use(&$model, $attributeNames) {
return $model->validate($attributeNames);
});
}
return Reaction\Promise\allInOrder($promises);
} | php | {
"resource": ""
} |
q265719 | Model.t | test | public function t($category, $message, $params = [], $language = null)
{
if (!isset($language) && isset($this->app)) {
$language = $this->app->language;
}
return isset($language)
? Reaction::t($category, $message, $params, $language)
: Reaction::tp($category, $message, $params, $language);
} | php | {
"resource": ""
} |
q265720 | AlternativeMail.addAttachment | test | public function addAttachment($file, $forceFileName = '', $forceMimeType = '')
{
$this->attachments[] = array(
'file' => $file,
'fileName' => $forceFileName,
'mimeType' => $forceMimeType,
);
return $this;
} | php | {
"resource": ""
} |
q265721 | GuzzleRequest.addPlugin | test | public function addPlugin(RequestPluginAdapter $plugin)
{
$subscriber = $plugin->add();
$this->request->addSubscriber($subscriber);
return $this;
} | php | {
"resource": ""
} |
q265722 | GuzzleRequest.sendRequest | test | public function sendRequest($method = 'GET', $endPoint = '')
{
$options = array_filter([
'query' => $this->getQuery(),
'headers' => $this->getHeaders(),
'body' => $this->getBody()
]);
$url = $this->url . $endPoint;
$request = $this->request->createRequest($method, $url, $options);
$rawResponse = $this->request->send($request);
return $this->newResponse($rawResponse);
} | php | {
"resource": ""
} |
q265723 | Loader.loadClass | test | public static function loadClass($classname, $type = null, $silent = false)
{
// search in bundles
$bundles = CarteBlanche::getContainer()->get('bundles');
$full_classname = $type.$classname;
$classfile = ucfirst($classname).'.php';
if (!empty($bundles)) {
foreach($bundles as $_n=>$_bundle) {
$_namespace = $_bundle->getNamespace();
if (!empty($type)) {
$bundle_file = rtrim($_bundle->getDirectory(), '/').'/'
.rtrim($type, '/').'/'
.$classfile;
$full_namespace = '\\'.$_namespace.'\\'.$type.'\\'.ucfirst($classname);
if ($_ce = self::classExists($full_namespace)) {
return $full_namespace;
} elseif ($_f = Locator::locate($bundle_file)) {
if (true===self::load($_f)) {
return $full_namespace;
}
}
} else {
if ($_namespace == substr(trim($classname, '\\'), 0, strlen($_namespace))) {
$bundle_file = str_replace('\\', DIRECTORY_SEPARATOR,
rtrim($_bundle->getDirectory(), '/')
.substr(trim($classname, '\\'), strlen($_namespace))
.'.php'
);
$full_namespace = $classname;
if ($_ce = self::classExists($full_namespace)) {
return $full_namespace;
} elseif ($_f = Locator::locate($bundle_file)) {
if (true===self::load($_f)) {
return $classname;
}
}
}
}
}
}
// silently return if the class has not been found
if (0!==error_reporting() && true!==$silent) {
throw new ErrorException("Class '$classname' not found!");
}
return false;
} | php | {
"resource": ""
} |
q265724 | NativeListenerAnnotations.getListeners | test | public function getListeners(string ...$classes): array
{
$annotations = [];
// Iterate through all the classes
foreach ($classes as $class) {
$listeners = $this->methodsAnnotationsType('Listener', $class);
// Get all the annotations for each class and iterate through them
/** @var \Valkyrja\Events\Annotations\Listener $annotation */
foreach ($listeners as $annotation) {
$this->setListenerProperties($annotation);
// Set the annotation in the annotations list
$annotations[] = $this->getListenerFromAnnotation($annotation);
}
}
return $annotations;
} | php | {
"resource": ""
} |
q265725 | NativeListenerAnnotations.setListenerProperties | test | protected function setListenerProperties(Listener $listener): void
{
$classReflection = $this->getClassReflection($listener->getClass());
if (
$listener->getMethod()
|| $classReflection->hasMethod('__construct')
) {
$methodReflection = $this->getMethodReflection(
$listener->getClass(),
$listener->getMethod() ?? '__construct'
);
$parameters = $methodReflection->getParameters();
// Set the dependencies
$listener->setDependencies($this->getDependencies(...$parameters));
}
$listener->setMatches();
} | php | {
"resource": ""
} |
q265726 | NativeListenerAnnotations.getListenerFromAnnotation | test | protected function getListenerFromAnnotation(Listener $listener): EventListener
{
$eventListener = new EventListener();
$eventListener
->setEvent($listener->getEvent())
->setId($listener->getId())
->setName($listener->getName())
->setClass($listener->getClass())
->setProperty($listener->getProperty())
->setMethod($listener->getMethod())
->setStatic($listener->isStatic())
->setFunction($listener->getFunction())
->setMatches($listener->getMatches())
->setDependencies($listener->getDependencies())
->setArguments($listener->getArguments());
return $eventListener;
} | php | {
"resource": ""
} |
q265727 | Zend_Filter_Compress_CompressAbstract.getOptions | test | public function getOptions($option = null)
{
if ($option === null) {
return $this->_options;
}
if (!array_key_exists($option, $this->_options)) {
return null;
}
return $this->_options[$option];
} | php | {
"resource": ""
} |
q265728 | Zend_Filter_Compress_CompressAbstract.setOptions | test | public function setOptions(array $options)
{
foreach ($options as $key => $option) {
$method = 'set' . $key;
if (method_exists($this, $method)) {
$this->$method($option);
}
}
return $this;
} | php | {
"resource": ""
} |
q265729 | KeylistsService.getKeyValue | test | public function getKeyValue($keyType, $keyValue)
{
$list = Keyvalue::getKeyvaluesByKeyType($keyType);
if (isset($list[$keyValue])) {
return $list[$keyValue];
}
return null;
} | php | {
"resource": ""
} |
q265730 | Fillable.fromArray | test | public function fromArray(array $input) {
$fillable = $this->getFillableFields();
foreach($input as $key => $value) {
if(in_array($key, $fillable)) {
$this->{'set' . ucfirst($key)}($value);
} else {
throw new MassAssignmentException($key);
}
}
} | php | {
"resource": ""
} |
q265731 | BaseServiceProvider.loadEntitiesFrom | test | public function loadEntitiesFrom($directory) {
$metadata = $this->app['config']['doctrine.managers.default.paths'];
$metadata[] = $directory;
$this->app['config']->set('doctrine.managers.default.paths', $metadata);
} | php | {
"resource": ""
} |
q265732 | BaseServiceProvider.extendEntityManager | test | public function extendEntityManager(callable $closure) {
// use 'em' instead of full class name to get around bug: https://github.com/laravel/framework/issues/11226
if($this->app->resolved('em')) {
$closure($this->app[EntityManager::class]);
} else {
$this->app->resolving(EntityManager::class, $closure);
}
} | php | {
"resource": ""
} |
q265733 | Prophet.checkPredictions | test | public function checkPredictions()
{
$exception = new AggregateException("Some predictions failed:\n");
foreach ($this->prophecies as $prophecy) {
try {
$prophecy->checkPredictions();
} catch (PredictionException $e) {
$exception->append($e);
}
}
$this->prophecies = [];
MockRegistry::getInstance()->unregisterAll();
if (count($exception->getExceptions())) {
throw $exception;
}
} | php | {
"resource": ""
} |
q265734 | Zend_Config_Xml._processExtends | test | protected function _processExtends(SimpleXMLElement $element, $section, array $config = array())
{
if (!isset($element->$section)) {
throw new Zend_Config_Exception("Section '$section' cannot be found");
}
$thisSection = $element->$section;
$nsAttributes = $thisSection->attributes(self::XML_NAMESPACE);
if (isset($thisSection['extends']) || isset($nsAttributes['extends'])) {
$extendedSection = (string) (isset($nsAttributes['extends']) ? $nsAttributes['extends'] : $thisSection['extends']);
$this->_assertValidExtend($section, $extendedSection);
if (!$this->_skipExtends) {
$config = $this->_processExtends($element, $extendedSection, $config);
}
}
$config = $this->_arrayMergeRecursive($config, $this->_toArray($thisSection));
return $config;
} | php | {
"resource": ""
} |
q265735 | NativeDispatcher.verifyClassMethod | test | public function verifyClassMethod(Dispatch $dispatch): void
{
// If a class and method are set and not callable
if (
null !== $dispatch->getClass()
&& null !== $dispatch->getMethod()
&& ! method_exists(
$dispatch->getClass(),
$dispatch->getMethod()
)
) {
// Throw a new invalid method exception
throw new InvalidMethodException(
'Method does not exist in class : '
. $dispatch->getName() . ' '
. $dispatch->getClass()
. '@'
. $dispatch->getMethod()
);
}
} | php | {
"resource": ""
} |
q265736 | NativeDispatcher.verifyClassProperty | test | public function verifyClassProperty(Dispatch $dispatch): void
{
// If a class and method are set and not callable
if (
null !== $dispatch->getClass()
&& null !== $dispatch->getProperty()
&& ! property_exists(
$dispatch->getClass(),
$dispatch->getProperty()
)
) {
// Throw a new invalid property exception
throw new InvalidPropertyException(
'Property does not exist in class : '
. $dispatch->getName() . ' '
. $dispatch->getClass()
. '@'
. $dispatch->getProperty()
);
}
} | php | {
"resource": ""
} |
q265737 | NativeDispatcher.verifyFunction | test | public function verifyFunction(Dispatch $dispatch): void
{
// If a function is set and is not callable
if (
null !== $dispatch->getFunction()
&& ! \is_callable($dispatch->getFunction())
) {
// Throw a new invalid function exception
throw new InvalidFunctionException(
'Function is not callable for : '
. $dispatch->getName() . ' '
. $dispatch->getFunction()
);
}
} | php | {
"resource": ""
} |
q265738 | NativeDispatcher.verifyClosure | test | public function verifyClosure(Dispatch $dispatch): void
{
// If a closure is set and is not callable
if (
null === $dispatch->getFunction()
&& null === $dispatch->getClass()
&& null === $dispatch->getMethod()
&& null === $dispatch->getProperty()
&& null === $dispatch->getClosure()
) {
// Throw a new invalid closure exception
throw new InvalidClosureException(
'Closure is not valid for : '
. $dispatch->getName()
);
}
} | php | {
"resource": ""
} |
q265739 | NativeDispatcher.verifyDispatch | test | public function verifyDispatch(Dispatch $dispatch): void
{
// If a function, closure, and class or method are not set
if (
null === $dispatch->getFunction()
&& null === $dispatch->getClosure()
&& null === $dispatch->getClass()
&& null === $dispatch->getMethod()
&& null === $dispatch->getProperty()
) {
// Throw a new invalid dispatch capability exception
throw new InvalidDispatchCapabilityException(
'Dispatch capability is not valid for : '
. $dispatch->getName()
);
}
$this->verifyClassMethod($dispatch);
$this->verifyClassProperty($dispatch);
$this->verifyFunction($dispatch);
$this->verifyClosure($dispatch);
} | php | {
"resource": ""
} |
q265740 | NativeDispatcher.getDependencies | test | protected function getDependencies(Dispatch $dispatch): ? array
{
$dependencies = null;
// If the dispatch is static it doesn't need dependencies
if ($dispatch->isStatic()) {
return $dependencies;
}
$dependencies = [];
$context = $dispatch->getClass() ?? $dispatch->getFunction();
$member = $dispatch->getProperty() ?? $dispatch->getMethod();
// If there are dependencies
if ($dispatch->getDependencies()) {
// Iterate through all the dependencies
foreach ($dispatch->getDependencies() as $dependency) {
// Set the dependency in the list
$dependencies[] = $this->app->container()->get(
$dependency,
null,
$context,
$member
);
}
}
return $dependencies;
} | php | {
"resource": ""
} |
q265741 | NativeDispatcher.getArguments | test | protected function getArguments(Dispatch $dispatch, array $arguments = null): ? array
{
// Get either the arguments passed or from the dispatch model
$arguments = $arguments ?? $dispatch->getArguments();
$context = $dispatch->getClass() ?? $dispatch->getFunction();
$member = $dispatch->getProperty() ?? $dispatch->getMethod();
// Set the listener arguments to a new blank array
$dependencies = $this->getDependencies($dispatch);
// If there are no arguments
if (null === $arguments) {
// Return the dependencies only
return $dependencies;
}
// Iterate through the arguments
foreach ($arguments as $argument) {
// If the argument is a service
if ($argument instanceof Service) {
// Dispatch the argument and set the results to the argument
$argument = $this->app->container()->get(
$argument->getId(),
null,
$context,
$member
);
} // If the argument is a dispatch
elseif ($argument instanceof Dispatch) {
// Dispatch the argument and set the results to the argument
$argument = $this->dispatchCallable($argument);
}
// Append the argument to the arguments list
$dependencies[] = $argument;
}
return $dependencies;
} | php | {
"resource": ""
} |
q265742 | NativeDispatcher.dispatchClassMethod | test | public function dispatchClassMethod(Dispatch $dispatch, array $arguments = null)
{
$response = null;
// Ensure a class and method exist before continuing
if (null === $dispatch->getClass() || null === $dispatch->getMethod()) {
return $response;
}
// Set the class through the container if this isn't a static method
$class = $dispatch->isStatic()
? $dispatch->getClass()
: $this->app->container()->get($dispatch->getClass());
$method = $dispatch->getMethod();
$response = null;
// If there are arguments
if (null !== $arguments) {
// Unpack arguments and dispatch
if ($dispatch->isStatic()) {
$response = $class::$method(...$arguments);
} else {
$response = $class->$method(...$arguments);
}
} else {
// Dispatch without unpacking
if ($dispatch->isStatic()) {
$response = $class::$method();
} else {
$response = $class->$method();
}
}
return $response ?? $this->DISPATCHED;
} | php | {
"resource": ""
} |
q265743 | NativeDispatcher.dispatchClassProperty | test | public function dispatchClassProperty(Dispatch $dispatch)
{
$response = null;
// Ensure a class and property exist before continuing
if (
null === $dispatch->getClass()
|| null === $dispatch->getProperty()
) {
return $response;
}
$class = $dispatch->getClass();
$property = $dispatch->getProperty();
// If this is a static property
if ($dispatch->isStatic()) {
$response = $class::$$property;
} else {
// Get the class from the container
$class = $this->app->container()->get($dispatch->getClass());
$response = $class->{$property};
}
return $response ?? $this->DISPATCHED;
} | php | {
"resource": ""
} |
q265744 | NativeDispatcher.dispatchClass | test | public function dispatchClass(Dispatch $dispatch, array $arguments = null)
{
// Ensure a class exists before continuing
if (null === $dispatch->getClass()) {
return $dispatch->getClass();
}
// If the class is the id then this item is not yet set
// in the service container yet so it needs a new
// instance returned
if ($dispatch->getClass() === $dispatch->getId()) {
// Get the class from the dispatcher
$class = $dispatch->getClass();
// If there are argument
if (null !== $arguments) {
// Get a new class instance with the arguments
$class = new $class(...$arguments);
} else {
// Otherwise just get a new class instance
$class = new $class();
}
} else {
// Set the class through the container
$class = $this->app->container()->get(
$dispatch->getClass(),
$arguments
);
}
return $class ?? $this->DISPATCHED;
} | php | {
"resource": ""
} |
q265745 | NativeDispatcher.dispatchFunction | test | public function dispatchFunction(Dispatch $dispatch, array $arguments = null)
{
// Ensure a function exists before continuing
if (null === $dispatch->getFunction()) {
return $dispatch->getFunction();
}
$function = $dispatch->getFunction();
$response = null;
// If there are arguments
if (null !== $arguments) {
// Unpack arguments and dispatch
$response = $function(...$arguments);
} else {
// Dispatch without unpacking
$response = $function();
}
return $response ?? $this->DISPATCHED;
} | php | {
"resource": ""
} |
q265746 | NativeDispatcher.dispatchClosure | test | public function dispatchClosure(Dispatch $dispatch, array $arguments = null)
{
// Ensure a closure exists before continuing
if (null === $dispatch->getClosure()) {
return $dispatch->getClosure();
}
$closure = $dispatch->getClosure();
$response = null;
// If there are arguments
if (null !== $arguments) {
// Unpack arguments and dispatch
$response = $closure(...$arguments);
} else {
// Dispatch without unpacking
$response = $closure();
}
return $response ?? $this->DISPATCHED;
} | php | {
"resource": ""
} |
q265747 | NativeDispatcher.dispatchCallable | test | public function dispatchCallable(Dispatch $dispatch, array $arguments = null)
{
// Get the arguments with dependencies
$arguments = $this->getArguments($dispatch, $arguments);
// Attempt to dispatch the dispatch
$response = $this->dispatchClassMethod($dispatch, $arguments)
?? $this->dispatchClassProperty($dispatch)
?? $this->dispatchClass($dispatch, $arguments)
?? $this->dispatchFunction($dispatch, $arguments)
?? $this->dispatchClosure($dispatch, $arguments);
// TODO: Add Constant and Variable ability
// If the response was initially null and we added the dispatched
// text to avoid calling each subsequent dispatcher thereafter
if ($response === $this->DISPATCHED) {
// Reset the response to null
$response = null;
}
return $response;
} | php | {
"resource": ""
} |
q265748 | NativeInput.getStringArguments | test | public function getStringArguments(): string
{
$arguments = $this->getRequestArguments();
$globalArguments = $this->getGlobalOptionsFlat();
foreach ($arguments as $key => $argument) {
if (\in_array($argument, $globalArguments, true)) {
unset($arguments[$key]);
}
}
return implode(' ', $arguments);
} | php | {
"resource": ""
} |
q265749 | NativeInput.getRequestArguments | test | public function getRequestArguments(): array
{
if (null !== $this->requestArguments) {
return $this->requestArguments;
}
$arguments = $this->request->server()->get('argv');
// strip the application name
array_shift($arguments);
return $this->requestArguments = $arguments;
} | php | {
"resource": ""
} |
q265750 | NativeInput.parseRequestArguments | test | protected function parseRequestArguments(): void
{
// Iterate through the request arguments
foreach ($this->getRequestArguments() as $argument) {
// Split the string on an equal sign
$exploded = explode('=', $argument);
$key = $exploded[0];
$value = $exploded[1] ?? true;
$type = 'arguments';
// If the key has double dash it is a long option
if (strpos($key, '--') !== false) {
$type = 'longOptions';
} // If the key has a single dash it is a short option
elseif (strpos($key, '-') !== false) {
$type = 'shortOptions';
}
// If the key is already set
if (isset($this->{$type}[$key])) {
// If the key isn't already an array
if (! \is_array($this->{$type}[$key])) {
// Make it an array with the current value
$this->{$type}[$key] = [$this->{$type}[$key]];
}
// Add the next value to the array
$this->{$type}[$key][] = $value;
continue;
}
// Set the key value pair
$this->{$type}[$key] = $value;
}
} | php | {
"resource": ""
} |
q265751 | Router.link | test | public function link($name, array $params = array())
{
if ($this->has($name)) {
$route = $this->routes[$name];
$url = $route['url'];
foreach ($params as $key => $val) {
$url = str_replace('{'.$key.'}', $val, $url);
}
$url = preg_replace("/\{\w+\}/", '', $url);
$name = ltrim(str_replace(AUTO_ROUTE, '', $url), '/');
}
return $this->asset($name);
} | php | {
"resource": ""
} |
q265752 | MessageTrait.withProtocolVersion | test | public function withProtocolVersion(string $version)
{
$this->validateProtocolVersion($version);
$this->protocol = $version;
return $this;
} | php | {
"resource": ""
} |
q265753 | MessageTrait.assertHeaderValues | test | protected function assertHeaderValues(string ...$values): array
{
foreach ($values as $value) {
HeaderSecurity::assertValid($value);
}
return $values;
} | php | {
"resource": ""
} |
q265754 | MessageTrait.injectHeader | test | protected function injectHeader(string $header, string $value, array $headers = null, bool $override = false): array
{
// The headers
$headers = $headers ?? [];
// Normalize the content type header
$normalized = strtolower($header);
// The original value for the header (if it exists in the headers array)
// Defaults to the value passed in
$originalValue = $value;
// Iterate through all the headers
foreach ($headers as $headerIndex => $headerValue) {
// Normalize the header name and check if it matches the normalized
// passed in header
if (strtolower($headerIndex) === $normalized) {
// Set the original value as this header value
$originalValue = $headerValue;
// Unset the header as we want to use the header string that was
// passed in as the header
unset($headers[$headerIndex]);
}
}
// Set the header in the headers list
$headers[$header] = [$override ? $originalValue : $value];
return $headers;
} | php | {
"resource": ""
} |
q265755 | HTTP_Request2_CookieJar.now | test | protected function now()
{
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('UTC'));
return $dt->format(DateTime::ISO8601);
} | php | {
"resource": ""
} |
q265756 | HTTP_Request2_CookieJar.checkAndUpdateFields | test | protected function checkAndUpdateFields(array $cookie, Net_URL2 $setter = null)
{
if ($missing = array_diff(array('name', 'value'), array_keys($cookie))) {
throw new HTTP_Request2_LogicException(
"Cookie array should contain 'name' and 'value' fields",
HTTP_Request2_Exception::MISSING_VALUE
);
}
if (preg_match(HTTP_Request2::REGEXP_INVALID_COOKIE, $cookie['name'])) {
throw new HTTP_Request2_LogicException(
"Invalid cookie name: '{$cookie['name']}'",
HTTP_Request2_Exception::INVALID_ARGUMENT
);
}
if (preg_match(HTTP_Request2::REGEXP_INVALID_COOKIE, $cookie['value'])) {
throw new HTTP_Request2_LogicException(
"Invalid cookie value: '{$cookie['value']}'",
HTTP_Request2_Exception::INVALID_ARGUMENT
);
}
$cookie += array('domain' => '', 'path' => '', 'expires' => null, 'secure' => false);
// Need ISO-8601 date @ UTC timezone
if (!empty($cookie['expires'])
&& !preg_match('/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\+0000$/', $cookie['expires'])
) {
try {
$dt = new DateTime($cookie['expires']);
$dt->setTimezone(new DateTimeZone('UTC'));
$cookie['expires'] = $dt->format(DateTime::ISO8601);
} catch (Exception $e) {
throw new HTTP_Request2_LogicException($e->getMessage());
}
}
if (empty($cookie['domain']) || empty($cookie['path'])) {
if (!$setter) {
throw new HTTP_Request2_LogicException(
'Cookie misses domain and/or path component, cookie setter URL needed',
HTTP_Request2_Exception::MISSING_VALUE
);
}
if (empty($cookie['domain'])) {
if ($host = $setter->getHost()) {
$cookie['domain'] = $host;
} else {
throw new HTTP_Request2_LogicException(
'Setter URL does not contain host part, can\'t set cookie domain',
HTTP_Request2_Exception::MISSING_VALUE
);
}
}
if (empty($cookie['path'])) {
$path = $setter->getPath();
$cookie['path'] = empty($path)? '/': substr($path, 0, strrpos($path, '/') + 1);
}
}
if ($setter && !$this->domainMatch($setter->getHost(), $cookie['domain'])) {
throw new HTTP_Request2_MessageException(
"Domain " . $setter->getHost() . " cannot set cookies for "
. $cookie['domain']
);
}
return $cookie;
} | php | {
"resource": ""
} |
q265757 | HTTP_Request2_CookieJar.store | test | public function store(array $cookie, Net_URL2 $setter = null)
{
$cookie = $this->checkAndUpdateFields($cookie, $setter);
if (strlen($cookie['value'])
&& (is_null($cookie['expires']) || $cookie['expires'] > $this->now())
) {
if (!isset($this->cookies[$cookie['domain']])) {
$this->cookies[$cookie['domain']] = array();
}
if (!isset($this->cookies[$cookie['domain']][$cookie['path']])) {
$this->cookies[$cookie['domain']][$cookie['path']] = array();
}
$this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']] = $cookie;
} elseif (isset($this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']])) {
unset($this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']]);
}
} | php | {
"resource": ""
} |
q265758 | HTTP_Request2_CookieJar.addCookiesFromResponse | test | public function addCookiesFromResponse(HTTP_Request2_Response $response, Net_URL2 $setter)
{
foreach ($response->getCookies() as $cookie) {
$this->store($cookie, $setter);
}
} | php | {
"resource": ""
} |
q265759 | HTTP_Request2_CookieJar.getMatching | test | public function getMatching(Net_URL2 $url, $asString = false)
{
$host = $url->getHost();
$path = $url->getPath();
$secure = 0 == strcasecmp($url->getScheme(), 'https');
$matched = $ret = array();
foreach (array_keys($this->cookies) as $domain) {
if ($this->domainMatch($host, $domain)) {
foreach (array_keys($this->cookies[$domain]) as $cPath) {
if (0 === strpos($path, $cPath)) {
foreach ($this->cookies[$domain][$cPath] as $name => $cookie) {
if (!$cookie['secure'] || $secure) {
$matched[$name][strlen($cookie['path'])] = $cookie;
}
}
}
}
}
}
foreach ($matched as $cookies) {
krsort($cookies);
$ret = array_merge($ret, $cookies);
}
if (!$asString) {
return $ret;
} else {
$str = '';
foreach ($ret as $c) {
$str .= (empty($str)? '': '; ') . $c['name'] . '=' . $c['value'];
}
return $str;
}
} | php | {
"resource": ""
} |
q265760 | HTTP_Request2_CookieJar.getAll | test | public function getAll()
{
$cookies = array();
foreach (array_keys($this->cookies) as $domain) {
foreach (array_keys($this->cookies[$domain]) as $path) {
foreach ($this->cookies[$domain][$path] as $name => $cookie) {
$cookies[] = $cookie;
}
}
}
return $cookies;
} | php | {
"resource": ""
} |
q265761 | HTTP_Request2_CookieJar.serialize | test | public function serialize()
{
$cookies = $this->getAll();
if (!$this->serializeSession) {
for ($i = count($cookies) - 1; $i >= 0; $i--) {
if (empty($cookies[$i]['expires'])) {
unset($cookies[$i]);
}
}
}
return serialize(array(
'cookies' => $cookies,
'serializeSession' => $this->serializeSession,
'useList' => $this->useList
));
} | php | {
"resource": ""
} |
q265762 | HTTP_Request2_CookieJar.unserialize | test | public function unserialize($serialized)
{
$data = unserialize($serialized);
$now = $this->now();
$this->serializeSessionCookies($data['serializeSession']);
$this->usePublicSuffixList($data['useList']);
foreach ($data['cookies'] as $cookie) {
if (!empty($cookie['expires']) && $cookie['expires'] <= $now) {
continue;
}
if (!isset($this->cookies[$cookie['domain']])) {
$this->cookies[$cookie['domain']] = array();
}
if (!isset($this->cookies[$cookie['domain']][$cookie['path']])) {
$this->cookies[$cookie['domain']][$cookie['path']] = array();
}
$this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']] = $cookie;
}
} | php | {
"resource": ""
} |
q265763 | HTTP_Request2_CookieJar.domainMatch | test | public function domainMatch($requestHost, $cookieDomain)
{
if ($requestHost == $cookieDomain) {
return true;
}
// IP address, we require exact match
if (preg_match('/^(?:\d{1,3}\.){3}\d{1,3}$/', $requestHost)) {
return false;
}
if ('.' != $cookieDomain[0]) {
$cookieDomain = '.' . $cookieDomain;
}
// prevents setting cookies for '.com' and similar domains
if (!$this->useList && substr_count($cookieDomain, '.') < 2
|| $this->useList && !self::getRegisteredDomain($cookieDomain)
) {
return false;
}
return substr('.' . $requestHost, -strlen($cookieDomain)) == $cookieDomain;
} | php | {
"resource": ""
} |
q265764 | PEAR_Command.& | test | function &factory($command, &$config)
{
if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
PEAR_Command::registerCommands();
}
if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
$command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
}
if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
$a = PEAR::raiseError("unknown command `$command'");
return $a;
}
$class = $GLOBALS['_PEAR_Command_commandlist'][$command];
if (!class_exists($class)) {
require_once $GLOBALS['_PEAR_Command_objects'][$class];
}
if (!class_exists($class)) {
$a = PEAR::raiseError("unknown command `$command'");
return $a;
}
$ui =& PEAR_Command::getFrontendObject();
$obj = &new $class($ui, $config);
return $obj;
} | php | {
"resource": ""
} |
q265765 | PEAR_Command.getGetoptArgs | test | function getGetoptArgs($command, &$short_args, &$long_args)
{
if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
PEAR_Command::registerCommands();
}
if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
$command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
}
if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
return null;
}
$obj = &PEAR_Command::getObject($command);
return $obj->getGetoptArgs($command, $short_args, $long_args);
} | php | {
"resource": ""
} |
q265766 | PEAR_Command.getHelp | test | function getHelp($command)
{
$cmds = PEAR_Command::getCommands();
if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
$command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
}
if (isset($cmds[$command])) {
$obj = &PEAR_Command::getObject($command);
return $obj->getHelp($command);
}
return false;
} | php | {
"resource": ""
} |
q265767 | PEAR_Frontend.& | test | function &singleton($type = null)
{
if ($type === null) {
if (!isset($GLOBALS['_PEAR_FRONTEND_SINGLETON'])) {
$a = false;
return $a;
}
return $GLOBALS['_PEAR_FRONTEND_SINGLETON'];
}
$a = PEAR_Frontend::setFrontendClass($type);
return $a;
} | php | {
"resource": ""
} |
q265768 | ExpressionConverter.convert | test | public function convert(Expression $expression, NumberSystem $targetSystem)
{
$parsingResult = $expression->value();
$expressionParts = $this->getExpressionParts($expression);
foreach ($expressionParts as $part) {
$parsedPart = $this->parseExpressionPart($part, $expression->getNumberSystem(), $targetSystem);
if ($parsedPart !== $part) {
$parsingResult = preg_replace('/'.$part.'/', $parsedPart, $parsingResult, 1);
}
}
return new Expression($parsingResult, $targetSystem);
} | php | {
"resource": ""
} |
q265769 | ExpressionConverter.parseExpressionPart | test | protected function parseExpressionPart($part, NumberSystem $sourceSystem, NumberSystem $targetSystem)
{
try {
// if it is a valid number of the source-system convert it
$sourceNumber = new Number($part, $sourceSystem);
return $sourceNumber->convert($targetSystem)->value();
} catch (NumberParseException $e) {
return $part;
}
} | php | {
"resource": ""
} |
q265770 | Zend_Config_Ini._processKey | test | protected function _processKey($config, $key, $value)
{
if (strpos($key, $this->_nestSeparator) !== false) {
$pieces = explode($this->_nestSeparator, $key, 2);
if (strlen($pieces[0]) && strlen($pieces[1])) {
if (!isset($config[$pieces[0]])) {
if ($pieces[0] === '0' && !empty($config)) {
// convert the current values in $config into an array
$config = array($pieces[0] => $config);
} else {
$config[$pieces[0]] = array();
}
} elseif (!is_array($config[$pieces[0]])) {
/**
* @see Zend_Config_Exception
*/
throw new Zend_Config_Exception("Cannot create sub-key for '{$pieces[0]}' as key already exists");
}
$config[$pieces[0]] = $this->_processKey($config[$pieces[0]], $pieces[1], $value);
} else {
/**
* @see Zend_Config_Exception
*/
throw new Zend_Config_Exception("Invalid key '$key'");
}
} else {
$config[$key] = $value;
}
return $config;
} | php | {
"resource": ""
} |
q265771 | Zend_Filter_StringTrim._unicodeTrim | test | protected function _unicodeTrim($value, $charlist = '\\\\s')
{
$chars = preg_replace(
array( '/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'),
array( '\\\\\\0', '\\', '\/' ),
$charlist
);
$pattern = '^[' . $chars . ']*|[' . $chars . ']*$';
return preg_replace("/$pattern/sSD", '', $value);
} | php | {
"resource": ""
} |
q265772 | Zend_Filter_StringToUpper.setEncoding | test | public function setEncoding($encoding = null)
{
if ($encoding !== null) {
if (!function_exists('mb_strtoupper')) {
throw new Zend_Filter_Exception('mbstring is required for this feature');
}
$encoding = (string) $encoding;
if (!in_array(strtolower($encoding), array_map('strtolower', mb_list_encodings()))) {
throw new Zend_Filter_Exception("The given encoding '$encoding' is not supported by mbstring");
}
}
$this->_encoding = $encoding;
return $this;
} | php | {
"resource": ""
} |
q265773 | CreateIteratorExceptionCapableTrait._createIteratorException | test | protected function _createIteratorException(
$message = null,
$code = null,
RootException $previous = null,
IteratorInterface $iterator
) {
return new IteratorException($message, $code, $previous, $iterator);
} | php | {
"resource": ""
} |
q265774 | I18N.init | test | public function init()
{
parent::init();
if (empty($this->languages)) {
$this->languages = [Reaction::$app->language];
}
$this->initUrlLanguagePrefixes();
if (!isset($this->translations['rct']) && !isset($this->translations['rct*'])) {
$this->translations['rct'] = [
'class' => 'Reaction\I18n\PhpMessageSource',
'sourceLanguage' => 'en-US',
'basePath' => '@reaction/Messages',
];
}
if (!isset($this->translations['app']) && !isset($this->translations['app*']) && !isset($this->translations['*'])) {
$this->translations['app'] = [
'class' => 'Reaction\I18n\PhpMessageSource',
'sourceLanguage' => Reaction::$app->sourceLanguage,
'basePath' => '@app/Messages',
];
}
} | php | {
"resource": ""
} |
q265775 | I18N.initUrlLanguagePrefixes | test | protected function initUrlLanguagePrefixes()
{
$prefixes = $this->languagePrefixes;
$defaultLanguage = isset($prefixes['']) ? $prefixes[''] : reset($this->languages);
$prefixes[''] = $defaultLanguage;
foreach ($this->languages as $language) {
if (in_array($language, $prefixes)) {
continue;
}
$prefix = Reaction\Helpers\Inflector::slug($language);
$prefixes[$prefix] = $language;
}
$this->languagePrefixes = $prefixes;
} | php | {
"resource": ""
} |
q265776 | I18N.getMessageFormatter | test | public function getMessageFormatter()
{
if ($this->_messageFormatter === null) {
$this->_messageFormatter = new MessageFormatter();
} elseif (is_array($this->_messageFormatter) || is_string($this->_messageFormatter)) {
$this->_messageFormatter = Reaction::create($this->_messageFormatter);
}
return $this->_messageFormatter;
} | php | {
"resource": ""
} |
q265777 | Transaction.start | test | public function start()
{
try {
if ($this->state == self::STATE_STARTED) {
throw new Exception\TransactionException(__METHOD__ . " Starting transaction on an already started one is not permitted.");
}
$this->adapter->getDriver()->getConnection()->beginTransaction();
$this->state = self::STATE_STARTED;
} catch (\Exception $e) {
throw new Exception\TransactionException(__METHOD__ . ". Cannot start transaction '{$e->getMessage()}'.");
}
return $this;
} | php | {
"resource": ""
} |
q265778 | Lastfm.getApiRequestUrl | test | public function getApiRequestUrl(Event $event)
{
return sprintf("%s?%s", $this->apiUrl, http_build_query($this->getApiRequestParams($event)));
} | php | {
"resource": ""
} |
q265779 | Lastfm.getApiRequestParams | test | protected function getApiRequestParams(Event $event)
{
$params = $event->getCustomParams();
$user = $params[0];
return array(
'format' => 'json',
'api_key' => $this->apiKey,
'method' => 'user.getrecenttracks',
'user' => $user,
'limit' => '1'
);
} | php | {
"resource": ""
} |
q265780 | Lastfm.getSuccessLines | test | public function getSuccessLines(Event $event, $apiResponse)
{
$response = json_decode($apiResponse);
if (isset($response->recenttracks)) {
$messages = array($this->getSuccessMessage($response));
} else {
$messages = $this->getNoResultsLines($event);
}
return $messages;
} | php | {
"resource": ""
} |
q265781 | Lastfm.getSuccessMessage | test | protected function getSuccessMessage($response)
{
$track = (is_array($response->recenttracks->track))
? $response->recenttracks->track[0]
: $response->recenttracks->track;
return sprintf(
"%s %s listening to %s by %s %s[ %s ]",
$response->recenttracks->{'@attr'}->user,
(isset($track->{'@attr'}->nowplaying)) ? "is" : "was",
$track->name,
$track->artist->{'#text'},
(!isset($track->{'@attr'}->nowplaying)) ? age($track->date->uts) . "ago " : "",
$track->url
);
} | php | {
"resource": ""
} |
q265782 | BudgetMapper.findAllByAccountId | test | public function findAllByAccountId($accountId)
{
$this->addWhere('account_id', $accountId);
$this->addOrder('budget_parent_id', 'ASC');
$this->addOrder('budget_name', 'ASC');
$budgets = array();
foreach ($this->select() as $budget) {
if ($budget->getParentId() === 0) {
$budgets[$budget->getId()] = $budget;
} else {
$budgets[$budget->getParentId()]->addChild($budget);
}
}
return $budgets;
} | php | {
"resource": ""
} |
q265783 | I18nContext.getCurrentLanguage | test | public function getCurrentLanguage() {
if ( $this->currentLang === null ) {
$lang = $this->defaultLanguage;
if ( isset( $_REQUEST['uselang'] ) ) {
$lang = $_REQUEST['uselang'];
} elseif ( isset( $_SESSION['uselang'] ) ) {
$lang = $_SESSION['uselang'];
} else {
$wants = self::parseAcceptLanguage();
$bestMatches = array_intersect(
$wants, $this->getAvailableLanguages()
);
if ( $bestMatches ) {
$lang = current( $bestMatches );
}
}
$this->setCurrentLanguage( $lang );
}
return $this->currentLang;
} | php | {
"resource": ""
} |
q265784 | I18nContext.parseAcceptLanguage | test | public static function parseAcceptLanguage() {
if ( !isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
return array();
}
$weighted = array();
// Strip any whitespace in the header value
$hdr = preg_replace( '/\s+/', '', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
// Split on commas
$parts = explode( ',', $hdr );
foreach ( $parts as $idx => $part ) {
if ( strpos( $part, ';q=' ) ) {
// Extract relative weight from component
list( $lang, $weight ) = explode( ';q=', $part );
$weight = (float)$weight;
} else {
$lang = $part;
$weight = 1;
}
if ( $lang != '*' && $weight > 0 ) {
// Decorate the weight with the original position to make sort
// stable
$weighted[strtolower( $lang )] = array( $weight, -$idx );
}
}
arsort( $weighted );
return array_keys( $weighted );
} | php | {
"resource": ""
} |
q265785 | Container.bind | test | public function bind($binding, $value)
{
$callback = function() use($value) {
return $this->make($value);
};
$callback->bindTo($this);
$this->bindings[$binding] = $callback;
} | php | {
"resource": ""
} |
q265786 | Container.make | test | public function make($class, array $dependencies = [])
{
if ($class instanceof Raw) {
return $class->getValue();
}
if ( ! is_string($class)) {
return $class;
}
if (array_key_exists($class, $this->bindings)) {
return $this->bindings[$class]();
}
if ( ! class_exists($class)) {
throw new Exceptions\ClassDoesNotExistException($class);
}
$reflector = new ReflectionClass($class);
$isInstantiable =
is_null($reflector->getConstructor()) ?: $reflector->getConstructor()->isPublic();
if ($reflector->isAbstract() or ! $isInstantiable) {
throw new Exceptions\ClassIsNotInstantiableException($class);
}
if (count($dependencies) > 0) {
return $reflector->newInstanceArgs(array_map([$this, "make"], $dependencies));
}
if ( ! $resolved = $this->attemptToResolve($reflector)) {
throw new Exceptions\ResolutionException($class);
}
return $resolved;
} | php | {
"resource": ""
} |
q265787 | Url.validate | test | private function validate(string $url): void {
if(filter_var($url, FILTER_VALIDATE_URL) === false) {
throw new InvalidArgumentException('Expected URL, but got [' . var_export($url, true) . '] instead');
}
} | php | {
"resource": ""
} |
q265788 | ViewableWrapper.isLiveVar | test | public function isLiveVar($fieldName)
{
return $this->liveVars && (!is_array($this->liveVars) || in_array($fieldName, $this->liveVars));
} | php | {
"resource": ""
} |
q265789 | ViewableWrapper.obj | test | public function obj($fieldName, $arguments = null, $forceReturnedObject = true, $cache = false, $cacheName = null)
{
$value = parent::obj($fieldName, $arguments, $forceReturnedObject, $cache, $cacheName);
// if we're publishing and this variable is qualified, output php code instead
if (
$this->failover
&& $this->liveVars
&& isset($this->varName)
&& LivePubHelper::is_publishing()
&& $this->isLiveVar($fieldName)
) {
$accessor = "get{$fieldName}";
$php = '';
// find out how we got the data
if ($this->failover instanceof ArrayData) {
$php = '$' . $this->varName . '["' . $fieldName . '"]';
} elseif (is_callable(array($this->failover, $fieldName))) {
// !@TODO respect arguments
$php = '$' . $this->varName . '->' . $fieldName . '()';
} elseif (is_callable(array($this->failover, $accessor))) {
// !@TODO respect arguments
$php = '$' . $this->varName . '->' . $accessor . '()';
} elseif (isset($this->failover, $fieldName)) {
$php = '$' . $this->varName . '->' . $fieldName;
}
// return the appropriate php
if ($php) {
if (is_object($value)) {
if ($value instanceof ViewableWrapper) {
LivePubHelper::$init_code[] = '<?php $' . $value->getVar() . ' = ' . $php . ' ?>';
}
// !@TODO: only other option is DataObjectSet - check that this is handled right
} else {
$value = in_array($fieldName, $this->liveVarsUnescaped)
? '<?php echo ' . $php . '; ?>'
: '<?php echo htmlentities(' . $php . '); ?>';
if ($forceReturnedObject) {
$value = new HTMLText($value);
}
}
}
}
return $value;
} | php | {
"resource": ""
} |
q265790 | ViewableWrapper.wrapObject | test | protected function wrapObject($obj)
{
if (is_object($obj)) {
// if it's an object, just check the type and wrap if needed
if ($obj instanceof ViewableWrapper) {
return $obj;
} else {
return new ViewableWrapper($obj);
}
} elseif (is_array($obj)) {
// if it's an assoc array just wrap it, otherwise make a dataobjectset
if (ArrayLib::is_associative($obj)) {
return new ViewableWrapper($obj);
} else {
$set = new ArrayList();
foreach ($obj as $i => $item) {
$wrap = $this->wrapObject($item);
$set->push($wrap);
}
return $set;
}
} else {
// it's a simple type, just return it
return $obj;
}
} | php | {
"resource": ""
} |
q265791 | ViewableWrapper.AsDate | test | public function AsDate($field)
{
$d = $this->$field;
return DBField::create('Date', is_numeric($d) ? date('Y-m-d H:i:s', $d) : $d);
} | php | {
"resource": ""
} |
q265792 | OpenSSLEncryption.makeSessionIdentifier | test | public function makeSessionIdentifier(string $sessionId): string
{
return (string) openssl_digest($sessionId . $this->appKey, $this->hashAlgorithm);
} | php | {
"resource": ""
} |
q265793 | OpenSSLEncryption.encryptSessionData | test | public function encryptSessionData(string $sessionId, string $sessionData): string
{
$ivLength = (int) openssl_cipher_iv_length($this->encryptionAlgorithm);
$initVector = (string) openssl_random_pseudo_bytes($ivLength);
$encryptionKey = $this->getEncryptionKey($sessionId);
$encryptedData = openssl_encrypt($sessionData, $this->encryptionAlgorithm, $encryptionKey, 0, $initVector);
return (string) json_encode(
[
'data' => $encryptedData,
'initVector' => base64_encode($initVector)
]
);
} | php | {
"resource": ""
} |
q265794 | OpenSSLEncryption.decryptSessionData | test | public function decryptSessionData(string $sessionId, string $sessionData): string
{
if (!$sessionData) {
return '';
}
$encryptedData = json_decode($sessionData);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new UnableToDecryptException();
}
$initVector = base64_decode($encryptedData->initVector, true);
if ($initVector === false) {
throw new UnableToDecryptException();
}
$encryptionKey = $this->getEncryptionKey($sessionId);
$decryptedData = @openssl_decrypt($encryptedData->data, $this->encryptionAlgorithm, $encryptionKey, 0, $initVector);
if ($decryptedData === false) {
throw new UnableToDecryptException();
}
return $decryptedData;
} | php | {
"resource": ""
} |
q265795 | OpenSSLEncryption.getEncryptionKey | test | private function getEncryptionKey(string $sessionId): string
{
return (string) openssl_digest($this->appKey . $sessionId, $this->hashAlgorithm);
} | php | {
"resource": ""
} |
q265796 | OpenSSLEncryption.setEncryptionAlgorithm | test | public function setEncryptionAlgorithm(string $algorithm): void
{
$knownAlgorithms = openssl_get_cipher_methods(true);
if (!in_array($algorithm, $knownAlgorithms)) {
$errorMessage = "The encryption algorithm \"$algorithm\" is unknow. " .
'For a list of valid algorithms, see openssl_get_cipher_methods(true).';
throw new UnableToEncryptException($errorMessage);
}
$this->encryptionAlgorithm = $algorithm;
} | php | {
"resource": ""
} |
q265797 | OpenSSLEncryption.setHashAlgorithm | test | public function setHashAlgorithm(string $algorithm): void
{
$knownAlgorithms = openssl_get_md_methods(true);
if (!in_array($algorithm, $knownAlgorithms)) {
$errorMessage = "The hash algorithm \"$algorithm\" is unknown." .
'For a list of valid algorithms, see openssl_get_md_methods(true).';
throw new UnableToHashException($errorMessage);
}
$this->hashAlgorithm = $algorithm;
} | php | {
"resource": ""
} |
q265798 | QueryBuilder.prepareUpdateSets | test | protected function prepareUpdateSets($table, $columns, $params = [])
{
$tableSchema = $this->db->getSchema()->getTableSchema($table);
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
$sets = [];
foreach ($columns as $name => $value) {
$value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
if ($value instanceof ExpressionInterface) {
$placeholder = $this->buildExpression($value, $params);
} else {
$placeholder = $this->bindParam($value, $params);
}
$sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
}
return [$sets, $params];
} | php | {
"resource": ""
} |
q265799 | jSoapRequest.initService | test | function initService(){
if(isset($_GET["service"]) && $_GET['service'] != ''){
list($module, $action) = explode('~',$_GET["service"]);
}else{
throw new jException('jsoap~errors.service.param.required');
}
$this->params['module'] = $module;
$this->params['action'] = $action;
$this->soapMsg = file_get_contents("php://input");
$this->_initUrlData(); //Need to be called manually before coordinator call of init because needed for the WSDL generation
} | php | {
"resource": ""
} |
Subsets and Splits