_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q264000 | ActiveRecord.listTypes | test | public function listTypes($type)
{
$data = [];
// create a reflection class to get constants
$refl = new ReflectionClass(get_called_class());
$constants = $refl->getConstants();
foreach ($constants as $constantName => $constantValue) {
// add prettified name to dropdown
if (strpos($constantName, $type) === 0) {
$prettyName = preg_replace('/' . $type . '/', "", $constantName, 1);
$prettyName = Inflector::humanize(strtolower($prettyName));
$data[$constantValue] = trim(ucwords($prettyName));
}
}
return $data;
} | php | {
"resource": ""
} |
q264001 | ActiveRecord.getTypeLabel | test | public function getTypeLabel($type, $constId)
{
if (!is_null($type)) {
$array = $this->listTypes($constId);
if (isset($array[$type])) {
return $array[$type];
}
}
return false;
} | php | {
"resource": ""
} |
q264002 | ActiveRecord.getListingOrderArray | test | public function getListingOrderArray()
{
$count = static::find()
->count();
$array = [];
for ($i = 1; $i <= $count; $i++) {
$array[$i] = $i;
}
return $array;
} | php | {
"resource": ""
} |
q264003 | FindReplace.findReplaceValue | test | public function findReplaceValue()
{
if (is_array($this->findText)) {
//can be array
$searchReplaceArray = [];
foreach ($this->findText as $key => $value) {
$searchReplaceArray[$value] = $this->replaceText;
}
} else {
$searchReplaceArray = [
$this->findText => $this->replaceText,
];
}
$this->owner->{$this->attribute} = str_replace(
array_keys($searchReplaceArray),
array_values($searchReplaceArray),
$this->owner->{$this->attribute}
);
} | php | {
"resource": ""
} |
q264004 | NavigationIterator.next | test | public function next(): void
{
if ($this->currentItem instanceof Dropdown) {
$this->currentDropdownItem = next($this->dropdownItems) ?: null;
if ($this->currentDropdownItem) {
return;
}
}
$this->currentItem = next($this->items) ?: null;
if ($this->currentItem instanceof Dropdown) {
$this->dropdownItems = $this->currentItem->items();
$this->currentDropdownItem = current($this->dropdownItems);
} else {
$this->dropdownItems = [];
$this->currentDropdownItem = null;
}
} | php | {
"resource": ""
} |
q264005 | NavigationIterator.currentTitle | test | public function currentTitle(): array
{
if (!$this->currentItem) {
return [];
}
$title = [$this->currentItem->title()];
if ($this->currentItem instanceof Dropdown && $this->currentDropdownItem) {
$title[] = $this->currentDropdownItem->title();
}
return $title;
} | php | {
"resource": ""
} |
q264006 | Generator.generateActiveField | test | public function generateActiveField($attribute)
{
$tableSchema = $this->getTableSchema();
if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
return "\$form->field(\$model, '$attribute')->passwordInput()";
} else {
return "\$form->field(\$model, '$attribute')";
}
}
$column = $tableSchema->columns[$attribute];
if ($column->name === 'tags') {
return "\$form->field(\$model, '$attribute')->widget(Select2::classname(), [
'language' => 'en',
'options' => [
'multiple' => true,
'placeholder' => 'Select a tag ...'
],
'pluginOptions' => [
'allowClear' => true,
'tags' => \$tag->listTags(\$model->className()),
],
])";
} elseif ($column->type === 'timestamp') {
return "\$form->field(\$model, '$attribute')->widget(DatePicker::classname(), [
'options' => [
'placeholder' => 'Select date ...',
],
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'todayHighlight' => true
],
])";
} elseif ($column->phpType === 'boolean' || $column->name === 'active' || $column->name === 'deleted') {
return "\$form->field(\$model, '$attribute')->widget(SwitchInput::classname(), [
'pluginOptions' => [
'size' => 'small'
],
])";
} elseif ($column->type === 'text') {
return "\$form->field(\$model, '$attribute')->widget(ImperaviWidget::classname())";
} else {
if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
$input = 'passwordInput';
} else {
$input = 'textInput';
}
if ($column->phpType !== 'string' || $column->size === null) {
return "\$form->field(\$model, '$attribute')->$input()";
} else {
return "\$form->field(\$model, '$attribute')->$input(['maxlength' => $column->size])";
}
}
} | php | {
"resource": ""
} |
q264007 | Factory.make | test | public function make($name, $attributes)
{
if (Str::contains($name, '.') || Str::contains($name, '/')) {
throw new InvalidArgumentException("Invalid character in resource name [{$name}].");
}
return $this->drivers[$name] = new Router($name, $attributes);
} | php | {
"resource": ""
} |
q264008 | Factory.of | test | public function of($name, $attributes = null)
{
if (! isset($this->drivers[$name])) {
return $this->make($name, $attributes);
}
return $this->drivers[$name];
} | php | {
"resource": ""
} |
q264009 | Factory.call | test | public function call($name, $parameters = [])
{
$child = null;
// Available drivers does not include childs, we should split the
// name into two (parent.child) where parent would be the name of
// the resource.
if (false !== strpos($name, '.')) {
list($name, $child) = explode('.', $name, 2);
}
// When the resources is not available, or register we should
// return false to indicate this status. This would allow the callee
// to return 404 abort status.
if (! isset($this->drivers[$name])) {
return false;
}
return $this->dispatcher->call($this->drivers[$name], $child, $parameters);
} | php | {
"resource": ""
} |
q264010 | Dispatcher.call | test | public function call(Router $driver, $name = null, array $parameters = [])
{
$resolver = $this->resolveDispatchDependencies($driver, $name, $parameters);
// This would cater request to valid resource but pointing to an
// invalid child. We should show a 404 response to the user on this
// case.
if (! $resolver->isValid()) {
return false;
}
return $this->dispatch($driver, $name, $resolver);
} | php | {
"resource": ""
} |
q264011 | Dispatcher.resolveDispatchDependencies | test | public function resolveDispatchDependencies(Router $driver, $name, array $parameters)
{
$segments = $this->getNestedParameters($name, $parameters);
$key = implode('.', array_keys($segments));
$uses = $driver->get('uses');
if (! is_null($name)) {
if (isset($driver[$key]) && Str::startsWith($driver[$key], 'resource:')) {
$uses = $driver[$key];
} else {
$uses = (isset($driver[$name]) ? $driver[$name] : null);
}
}
return new Resolver($uses, $this->request->getMethod(), $parameters, $segments);
} | php | {
"resource": ""
} |
q264012 | Dispatcher.getNestedParameters | test | protected function getNestedParameters($name, array $parameters)
{
$reserved = ['create', 'show', 'index', 'delete', 'destroy', 'edit'];
$nested = [];
if (($nestedCount = count($parameters)) > 0) {
$nested = [$name => $parameters[0]];
for ($index = 1; $index < $nestedCount; $index += 2) {
$value = null;
if (($index + 1) < $nestedCount) {
$value = $parameters[($index + 1)];
}
$key = $parameters[$index];
! in_array($key, $reserved) && $nested[$key] = $value;
}
}
return $nested;
} | php | {
"resource": ""
} |
q264013 | Dispatcher.findRoutableAttributes | test | protected function findRoutableAttributes(Resolver $resolver)
{
$type = $resolver->getType();
if (in_array($type, ['restful', 'resource'])) {
$method = 'find'.Str::studly($type).'Routable';
list($action, $parameters) = call_user_func([$this, $method], $resolver);
} else {
throw new InvalidArgumentException("Type [{$type}] not implemented.");
}
return [$action, $parameters];
} | php | {
"resource": ""
} |
q264014 | Dispatcher.findRestfulRoutable | test | protected function findRestfulRoutable(Resolver $resolver)
{
$parameters = $resolver->getParameters();
$verb = $resolver->getVerb();
$action = (count($parameters) > 0 ? array_shift($parameters) : 'index');
$action = Str::camel("{$verb}_{$action}");
return [$action, $parameters];
} | php | {
"resource": ""
} |
q264015 | Dispatcher.findResourceRoutable | test | protected function findResourceRoutable(Resolver $resolver)
{
$verb = $resolver->getVerb();
$swappable = [
'post' => 'store',
'put' => 'update',
'patch' => 'update',
'delete' => 'destroy',
];
if (! isset($swappable[$verb])) {
$action = $this->getAlternativeResourceAction($resolver);
} else {
$action = $swappable[$verb];
}
$parameters = array_values($resolver->getSegments());
return [$action, $parameters];
} | php | {
"resource": ""
} |
q264016 | Dispatcher.getAlternativeResourceAction | test | protected function getAlternativeResourceAction(Resolver $resolver)
{
$parameters = $resolver->getParameters();
$segments = $resolver->getSegments();
$last = array_pop($parameters);
$resources = array_keys($segments);
if (in_array($last, ['edit', 'create', 'delete'])) {
// Handle all possible GET routing.
return $last;
} elseif (! in_array($last, $resources) && ! empty($segments)) {
return 'show';
}
return 'index';
} | php | {
"resource": ""
} |
q264017 | Dispatcher.dispatch | test | protected function dispatch(Router $driver, $name, Resolver $resolver)
{
// Next we need to the action and parameters before we can call
// the destination controller, the resolver would determine both
// restful and resource controller.
list($action, $parameters) = $this->findRoutableAttributes($resolver);
$route = new Route((array) $resolver->getVerb(), "{$driver->get('id')}/{$name}", [
'uses' => $resolver->getController()."@{$action}",
]);
$route->overrideParameters($parameters);
// Resolve the controller from container.
$dispatcher = new ControllerDispatcher($this->router, $this->app);
return $dispatcher->dispatch($route, $this->request, $resolver->getController(), $action);
} | php | {
"resource": ""
} |
q264018 | PickupController.listAction | test | public function listAction(Request $request, ?string $method): Response
{
$calculator = $this->getCalculator($method);
$params = $request->request->all();
$pickupTemplate = $this->getDefaultTemplate();
$pickupCurrentId = null;
$pickupList = [];
$currentAddress = null;
/** @var PickupCalculatorInterface $calculator */
if ($calculator instanceof PickupCalculatorInterface) {
if (!empty($calculator->getPickupTemplate())) {
$pickupTemplate = $calculator->getPickupTemplate();
}
$cart = $this->getCurrentCart();
if (null !== $cart->getId()) {
$cart = $this->getOrderRepository()->findCartForSummary($cart->getId());
$address = $cart->getShippingAddress();
$shipment = $cart->getShipments()->current();
$pickupCurrentId = $shipment->getPickupId();
foreach ($params as $field => $value) {
$setter = 'set' . preg_replace('/_/', '', ucwords($field, '_'));
if (method_exists($address, $setter)) {
$address->$setter($value);
}
}
$currentAddress = $address;
$pickupList = $calculator->getPickupList($address, $cart, $this->getMethod($method));
}
}
$pickup = [
'pickup' => [
'current_id' => $pickupCurrentId,
'list' => $pickupList,
],
'address' => $currentAddress,
'countries' => $this->getAvailableCountries(),
'index' => $request->get('index', 0),
'code' => $method,
];
return $this->render($pickupTemplate, ['method' => $pickup]);
} | php | {
"resource": ""
} |
q264019 | PickupController.getCalculator | test | protected function getCalculator(string $shippingMethod): CalculatorInterface
{
$method = $this->getMethod($shippingMethod);
if ($method === null) {
return false;
}
/** @var CalculatorInterface $calculator */
$calculator = $this->calculatorRegistry->get($method->getCalculator());
return $calculator;
} | php | {
"resource": ""
} |
q264020 | PickupController.getMethod | test | protected function getMethod(?string $shippingMethod): ShippingMethod
{
/** @var ShippingMethod|null $method */
$method = $this->getShippingMethodRepository()->findOneBy(['code' => $shippingMethod]);
if ($method === null) {
return false;
}
return $method;
} | php | {
"resource": ""
} |
q264021 | Router.route | test | public function route($name, $uses)
{
if (in_array($name, $this->reserved)) {
throw new InvalidArgumentException("Unable to use reserved keyword [{$name}].");
} elseif (Str::contains($name, '/')) {
throw new InvalidArgumentException("Invalid character in resource name [{$name}].");
}
$this->attributes['routes'][$name] = $uses;
return $this;
} | php | {
"resource": ""
} |
q264022 | Router.buildResourceSchema | test | protected function buildResourceSchema($name, $attributes)
{
$schema = [
'name' => '',
'uses' => '',
'routes' => [],
'visible' => true,
];
if (! is_array($attributes)) {
$uses = $attributes;
$attributes = [
'name' => Str::title($name),
'uses' => $uses,
];
}
$attributes['id'] = $name;
return array_merge($schema, $attributes);
} | php | {
"resource": ""
} |
q264023 | OrderInitializeCompleteListener.updateShippingAddress | test | public function updateShippingAddress(ResourceControllerEvent $event): void
{
/** @var Order $order */
$order = $event->getSubject();
$pickup = $this->getPickupAddress($order);
if (!empty($pickup)) {
$shipping = clone $order->getShippingAddress();
$shipping->setCompany($pickup['company']);
$shipping->setStreet($pickup['street_1']);
$shipping->setCity($pickup['city']);
$shipping->setPostcode($pickup['postcode']);
$shipping->setCountryCode($pickup['country']);
$order->setShippingAddress($shipping);
}
} | php | {
"resource": ""
} |
q264024 | ControllerDispatcher.call | test | protected function call($instance, $route, $method)
{
$controller = get_class($instance);
if (! method_exists($instance, $method)) {
throw new NotFoundHttpException("Unable to call [{$controller}@{$method}].");
}
return parent::call($instance, $route, $method);
} | php | {
"resource": ""
} |
q264025 | Response.handleIlluminateResponse | test | protected function handleIlluminateResponse(IlluminateResponse $content, Closure $callback = null)
{
$code = $content->getStatusCode();
$response = $content->getContent();
if ($this->isRenderableResponse($response)) {
return $response->render();
} elseif ($this->isNoneHtmlResponse($content)) {
return $content;
} elseif ($content->isSuccessful()) {
return $this->handleResponseCallback($response, $callback);
}
return $this->abort($code);
} | php | {
"resource": ""
} |
q264026 | Response.handleResponseCallback | test | protected function handleResponseCallback($content, Closure $callback = null)
{
if ($callback instanceof Closure) {
$content = call_user_func($callback, $content);
}
if (false === $content) {
return $this->abort(404);
} elseif (is_null($content)) {
return new IlluminateResponse($content, 200);
}
return $content;
} | php | {
"resource": ""
} |
q264027 | Response.abort | test | protected function abort($code, $message = '', array $headers = [])
{
if ($code == 404) {
throw new NotFoundHttpException($message);
}
throw new HttpException($code, $message, null, $headers);
} | php | {
"resource": ""
} |
q264028 | Response.isNoneHtmlResponse | test | protected function isNoneHtmlResponse(IlluminateResponse $content)
{
$contentType = $content->headers->get('Content-Type');
$isHtml = Str::startsWith($contentType, 'text/html');
return ! is_null($content) && ! $isHtml;
} | php | {
"resource": ""
} |
q264029 | Commands.register | test | public static function register(string $prefix, array $actions = [], array $options = [])
{
$handler = new ErrorHandler();
$handler->register();
Yii::$app->set('errorHandler', $handler);
Yii::$app->controllerMap[$prefix] = [
'class' => get_called_class(),
'actions' => $actions,
'optionAliases' => $options
];
} | php | {
"resource": ""
} |
q264030 | Commands.options | test | public function options($actionID)
{
$actionClass = $this->actions()[$actionID] ?? null;
$action = new \ReflectionClass($actionClass);
$actionOptions = [];
foreach ($action->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
if (in_array($property->getName(), array_values($this->optionAliases()))) {
$actionOptions[] = $property->getName();
}
}
return $actionOptions;
} | php | {
"resource": ""
} |
q264031 | Psr6MemoryCache.deleteItem | test | public function deleteItem($key)
{
\WildWolf\Cache\Validator::validateKey($key);
unset($this->cache[$key]);
return true;
} | php | {
"resource": ""
} |
q264032 | Psr6MemoryCache.save | test | public function save(\Psr\Cache\CacheItemInterface $item)
{
$key = $item->getKey();
$val = $item->get();
if (is_object($val)) {
$val = clone $val;
}
if (!($item instanceof \WildWolf\Cache\CacheItem)) {
$expires = null;
} else {
$expires = $item->expires();
}
$this->cache[$key] = [$val, $expires];
return true;
} | php | {
"resource": ""
} |
q264033 | BlockOutputTrait.block | test | public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = true, $escape = true)
{
$this->output->block($messages, $type, $style, $prefix, $padding, $escape);
} | php | {
"resource": ""
} |
q264034 | Psr16MemoryCache.get | test | public function get($key, $default = null)
{
\WildWolf\Cache\Validator::validateKey($key);
if (isset($this->cache[$key])) {
list($data, $expires) = $this->cache[$key];
if (null === $expires || (new \DateTime()) < $expires) {
return $data;
}
unset($this->cache[$key]);
}
return $default;
} | php | {
"resource": ""
} |
q264035 | Psr16MemoryCache.set | test | public function set($key, $value, $ttl = null)
{
\WildWolf\Cache\Validator::validateKey($key);
\WildWolf\Cache\Validator::validateTtl($ttl);
if ($ttl instanceof \DateInterval) {
$expires = new \DateTime();
$expires->add($ttl);
} elseif (is_numeric($ttl)) {
$expires = new \DateTime('now +' . $ttl . ' seconds');
} else {
$expires = null;
}
if (is_object($value)) {
$value = clone $value;
}
$this->cache[$key] = [$value, $expires];
return true;
} | php | {
"resource": ""
} |
q264036 | Psr16MemoryCache.setMultiple | test | public function setMultiple($values, $ttl = null)
{
\WildWolf\Cache\Validator::validateIterable($values);
\WildWolf\Cache\Validator::validateTtl($ttl);
$result = true;
foreach ($values as $key => $value) {
if (is_int($key)) {
$key = (string)$key;
}
$result = $this->set($key, $value, $ttl) && $result;
}
return $result;
} | php | {
"resource": ""
} |
q264037 | Psr16MemoryCache.deleteMultiple | test | public function deleteMultiple($keys)
{
\WildWolf\Cache\Validator::validateIterable($keys);
$result = true;
foreach ($keys as $key) {
$result = $this->delete($key) && $result;
}
return $result;
} | php | {
"resource": ""
} |
q264038 | Psr16MemoryCache.has | test | public function has($key)
{
\WildWolf\Cache\Validator::validateKey($key);
if (isset($this->cache[$key])) {
list(, $expires) = $this->cache[$key];
if (null === $expires || (new \DateTime()) < $expires) {
return true;
}
unset($this->cache[$key]);
}
return false;
} | php | {
"resource": ""
} |
q264039 | TextInputCustomLabel.getLabel | test | public function getLabel($caption = NULL)
{
$label = clone $this->label;
$label->for = $this->getHtmlId();
if (!$label->getHtml()) {
$label->setText($this->translate($caption === NULL ? $this->caption : $caption));
}
return $label;
} | php | {
"resource": ""
} |
q264040 | NodeCategoryTrait.fullPathName | test | public function fullPathName($delimiter = '/')
{
$parents = $this->parents();
return implode($delimiter, $parents->pluck('name')->toArray()) . $delimiter . $this->name;
} | php | {
"resource": ""
} |
q264041 | NodeCategoryTrait.makeTree | test | public static function makeTree(\Illuminate\Database\Eloquent\Collection $collection, \Closure $map = null)
{
if (is_callable($map)) {
$collection->map($map);
}
$categories = $collection->keyBy('id')->toArray();
$nodesKey = (new static)->getNodesKey();
foreach($categories as $cate) {
$categories[$cate['parent_id']][$nodesKey][] = & $categories[$cate['id']];
}
return isset($categories[0][$nodesKey]) ? $categories[0][$nodesKey] : [];
} | php | {
"resource": ""
} |
q264042 | OutputStyle.type | test | public function type(string $command, string $style = "fg=white", $speed = 5, string $prepend = "$ ")
{
if (!is_null($prepend)) {
$this->write($prepend);
}
$chars = str_split($command);
foreach ($chars as $char) {
$this->write(sprintf("<%s>%s</>", $style, $char));
if (is_int($speed) && $speed > 0) {
$delay = rand(10000, 1000000) / $speed;
usleep($delay);
}
}
// delay before new line
usleep(1000000 / $speed);
$this->newLine();
} | php | {
"resource": ""
} |
q264043 | SnsEndpoint.setResourceMembers | test | protected function setResourceMembers($resourcePath = null)
{
parent::setResourceMembers($resourcePath);
$this->resource = array_get($this->resourceArray, 0);
$pos = 1;
$more = array_get($this->resourceArray, $pos);
if (!empty($more)) {
// This will be the full resource path
do {
$this->resource .= '/' . $more;
$pos++;
$more = array_get($this->resourceArray, $pos);
} while (!empty($more));
}
return $this;
} | php | {
"resource": ""
} |
q264044 | Loader.loadPSRClass | test | private function loadPSRClass($class)
{
$prefix = $class;
while (false !== $pos = strrpos($prefix, '\\')) {
$prefix = substr($class, 0, $pos + 1);
$relative_class = substr($class, $pos + 1);
$mapped_file = $this->loadMappedFile($prefix, $relative_class);
if ($mapped_file) {
return $mapped_file;
}
$prefix = rtrim($prefix, '\\');
}
return false;
} | php | {
"resource": ""
} |
q264045 | Sns.setAccountId | test | protected function setAccountId($config)
{
$config['version'] = '2010-05-08';
$iam = new IamClient($config);
$user = $iam->getUser()->get('User');
$arn = explode(':', array_get($user, 'Arn'));
$this->accountId = array_get($arn, 4);
} | php | {
"resource": ""
} |
q264046 | Sns.translateException | test | static public function translateException(\Exception $exception, $add_msg = null)
{
$msg = strval($add_msg) . $exception->getMessage();
switch (get_class($exception)) {
case 'Aws\Sns\Exception\AuthorizationErrorException':
case 'Aws\Sns\Exception\EndpointDisabledException':
case 'Aws\Sns\Exception\InvalidParameterException':
case 'Aws\Sns\Exception\PlatformApplicationDisabledException':
case 'Aws\Sns\Exception\SubscriptionLimitExceededException':
case 'Aws\Sns\Exception\TopicLimitExceededException':
return new BadRequestException($msg, $exception->getCode());
case 'Aws\Sns\Exception\NotFoundException':
return new NotFoundException($msg, $exception->getCode());
case 'Aws\Sns\Exception\SnsException':
case 'Aws\Sns\Exception\InternalErrorException':
return new InternalServerErrorException($msg, $exception->getCode());
default:
return null;
}
} | php | {
"resource": ""
} |
q264047 | DoctrineMigrationsProvider.getConsole | test | public function getConsole(Container $app = null)
{
return $this->console ?: (isset($app['console']) ? $app['console'] : new Console());
} | php | {
"resource": ""
} |
q264048 | Client.execute | test | function execute() {
$data_to_post = array(
'apikey' => $this->apikey,
'command' => $this->command,
'params' => json_encode($this->params)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PayPro::$apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_to_post);
curl_setopt($ch, CURLOPT_CAINFO, $this->caBundleFile());
$body = curl_exec($ch);
if ($body === false) {
$errno = curl_errno($ch);
$message = curl_error($ch);
curl_close($ch);
$msg = "Could not connect to the PayPro API - [errno: $errno]: $message";
throw new Error\Connection($msg);
}
curl_close($ch);
$decodedResponse = json_decode($body, true);
if (is_null($decodedResponse)) {
$msg = "The API request returned an error or is invalid: $body";
throw new Error\InvalidResponse($msg);
}
$params = array();
return $decodedResponse;
} | php | {
"resource": ""
} |
q264049 | Enum.values | test | public static function values()
{
$class = get_called_class();
if (!isset(self::$cache[$class])) {
$reflected = new \ReflectionClass($class);
self::$cache[$class] = $reflected->getConstants();
}
return self::$cache[$class];
} | php | {
"resource": ""
} |
q264050 | S3FileSystem.listContainers | test | public function listContainers($include_properties = false)
{
$this->checkConnection();
if (!empty($this->container)) {
return $this->listResource($include_properties);
}
/** @noinspection PhpUndefinedMethodInspection */
$buckets = $this->blobConn->listBuckets()->get('Buckets');
$out = [];
foreach ($buckets as $bucket) {
$name = rtrim($bucket['Name']);
$out[] = ['name' => $name, 'path' => $name];
}
return $out;
} | php | {
"resource": ""
} |
q264051 | S3FileSystem.updateContainerProperties | test | public function updateContainerProperties($container, $properties = [])
{
$this->checkConnection();
try {
if ($this->blobConn->doesBucketExist($container)) {
throw new \Exception("No container named '$container'");
}
} catch (\Exception $ex) {
throw new DfException("Failed to update container '$container': " . $ex->getMessage());
}
} | php | {
"resource": ""
} |
q264052 | S3FileSystem.blobExists | test | public function blobExists($container = '', $name = '')
{
try {
$this->checkConnection();
return $this->blobConn->doesObjectExist($container, $name);
} catch (\Exception $ex) {
return false;
}
} | php | {
"resource": ""
} |
q264053 | JWT.encode | test | public function encode(string $iss, string $aud, string $sub, string $expires = null, array $claims = []): string
{
$now = new DateTimeImmutable();
$claims = array_merge($claims, [
'iss' => $iss,
'aud' => $aud,
'sub' => $sub,
'iat' => $now->getTimestamp(),
'exp' => $this->expires($now, $expires)
]);
return FirebaseJWT::encode($claims, $this->privateKey, self::ALGO);
} | php | {
"resource": ""
} |
q264054 | JWT.decode | test | public function decode(string $token, bool $ignoreExceptions = false): ?array
{
try {
$payload = FirebaseJWT::decode($token, $this->publicKey, [self::ALGO]);
return json_decode(json_encode($payload), true);
} catch (Exception $exception) {
$this->exceptionHandler($exception, $ignoreExceptions);
return null;
}
} | php | {
"resource": ""
} |
q264055 | JWT.payload | test | public function payload(string $token): array
{
$segments = $this->segments($token);
return json_decode(
FirebaseJWT::urlsafeB64Decode($segments[1]), true
);
} | php | {
"resource": ""
} |
q264056 | JWT.segments | test | protected function segments(string $token): array
{
$segments = explode('.', $token);
if (3 !== count($segments)) {
throw new Exception("Malformed jwt received.");
}
return $segments;
} | php | {
"resource": ""
} |
q264057 | JWT.expires | test | protected function expires(DateTimeImmutable $now, string $expires = null)
{
return !$expires ? null : $now->modify($expires)->getTimestamp();
} | php | {
"resource": ""
} |
q264058 | RedshiftSchema.createIndex | test | public function createIndex($name, $table, $columns, $unique = false)
{
$cols = [];
if (is_string($columns)) {
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $col) {
if (strpos($col, '(') !== false) {
$cols[] = $col;
} else {
$cols[] = $this->quoteColumnName($col);
}
}
if ($unique) {
return
'ALTER TABLE ' .
$this->quoteTableName($table) .
' ADD CONSTRAINT ' .
$this->quoteTableName($name) .
' UNIQUE (' .
implode(', ', $cols) .
')';
} else {
throw new BadRequestException('Indexes not supported.');
}
} | php | {
"resource": ""
} |
q264059 | RedshiftSchema.extractDefault | test | public function extractDefault(ColumnSchema $field, $defaultValue)
{
if ($defaultValue === 'true') {
$field->defaultValue = true;
} elseif ($defaultValue === 'false') {
$field->defaultValue = false;
} elseif (0 === stripos($defaultValue, '"identity"')) {
$field->autoIncrement = true;
} elseif (preg_match('/^\'(.*)\'::/', $defaultValue, $matches)) {
parent::extractDefault($field, str_replace("''", "'", $matches[1]));
} elseif (preg_match('/^(-?\d+(\.\d*)?)(::.*)?$/', $defaultValue, $matches)) {
parent::extractDefault($field, $matches[1]);
} else {
// could be a internal function call like setting uuids
$field->defaultValue = $defaultValue;
}
} | php | {
"resource": ""
} |
q264060 | PaginationHelper.addPrevButton | test | protected static function addPrevButton($sCode) {
if(self::$iCurrentPage <= self::$arSettings[$sCode.'_button_limit']) {
return;
}
//Get button value
$sValue = self::getValue($sCode);
//Get button name
$sName = self::$arSettings[$sCode.'_button_name'];
if(isset(self::$arSettings[$sCode.'_button_number']) && self::$arSettings[$sCode.'_button_number']) {
$sName = $sValue;
}
self::$arResult[] = [
'name' => $sName,
'value' => $sValue,
'class' => self::$arSettings[$sCode.'_button_class'],
'code' => $sCode,
];
} | php | {
"resource": ""
} |
q264061 | PaginationHelper.addNextButton | test | protected static function addNextButton($sCode) {
if(self::$iCurrentPage + self::$arSettings[$sCode.'_button_limit'] > self::$iTotalCountPages) {
return;
}
//Get button value
$sValue = self::getValue($sCode);
//Get button name
$sName = self::$arSettings[$sCode.'_button_name'];
if(isset(self::$arSettings[$sCode.'_button_number']) && self::$arSettings[$sCode.'_button_number']) {
$sName = $sValue;
}
self::$arResult[] = [
'name' => $sName,
'value' => $sValue,
'class' => self::$arSettings[$sCode.'_button_class'],
'code' => $sCode,
];
} | php | {
"resource": ""
} |
q264062 | PaginationHelper.getValue | test | protected static function getValue($sCode) {
switch($sCode) {
case self::FIRST_BUTTON_CODE:
return 1;
case self::FIRST_MORE_BUTTON_CODE:
return null;
case self::PREV_BUTTON_CODE:
$iValue = self::$iCurrentPage - 1;
if($iValue < 1) {
$iValue = 1;
}
return $iValue;
case self::PREV_MORE_BUTTON_CODE:
return null;
case self::NEXT_MORE_BUTTON_CODE:
return null;
case self::NEXT_BUTTON_CODE:
$iValue = self::$iCurrentPage + 1;
if($iValue > self::$iTotalCountPages) {
$iValue = self::$iTotalCountPages;
}
return $iValue;
case self::LAST_MORE_BUTTON_CODE:
return null;
case self::LAST_BUTTON_CODE:
return self::$iTotalCountPages;
}
return null;
} | php | {
"resource": ""
} |
q264063 | GraphTraverser.reveal | test | public static function reveal($object)
{
if ($object instanceof RecordInterface) {
return $object;
} elseif ($object instanceof JsonSerializable) {
return $object->jsonSerialize();
} elseif ($object instanceof ArrayObject) {
return $object->getArrayCopy();
} elseif ($object instanceof Traversable) {
return iterator_to_array($object);
}
return $object;
} | php | {
"resource": ""
} |
q264064 | GraphTraverser.isObject | test | public static function isObject($value)
{
return $value instanceof RecordInterface || $value instanceof \stdClass || (is_array($value) && CurveArray::isAssoc($value));
} | php | {
"resource": ""
} |
q264065 | GraphTraverser.isEmpty | test | public static function isEmpty($value)
{
if (empty($value)) {
return true;
} elseif ($value instanceof \stdClass) {
return count((array) $value) === 0;
} elseif ($value instanceof RecordInterface) {
return count($value->getProperties()) === 0;
}
return false;
} | php | {
"resource": ""
} |
q264066 | Transformer.toRecord | test | public static function toRecord($data, RecordInterface $root = null)
{
$visitor = new RecordSerializeVisitor($root);
$traverser = new GraphTraverser();
$traverser->traverse($data, $visitor);
return $visitor->getObject();
} | php | {
"resource": ""
} |
q264067 | Response.parseResponse | test | private function parseResponse($data, $op)
{
$arr = array();
$xml = new \SimpleXMLElement($data);
$xml = $xml->xpath('/soap:Envelope/soap:Body');
$xml = $xml[0];
$data = json_decode(json_encode($xml));
$opResponse = $op . 'Response';
$opResult = $op . 'Result';
$arr = $this->object2array($data->$opResponse->$opResult);
return $arr;
} | php | {
"resource": ""
} |
q264068 | DatagridRegistry.getConfigurator | test | public function getConfigurator(string $name): DatagridConfiguratorInterface
{
if (!isset($this->configurators[$name])) {
$configurator = null;
if (isset($this->lazyConfigurators[$name])) {
$configurator = $this->lazyConfigurators[$name]();
}
if (!$configurator) {
// Support fully-qualified class names.
if (!class_exists($name) || !in_array(DatagridConfiguratorInterface::class, class_implements($name), true)) {
throw new InvalidArgumentException(sprintf('Could not load datagrid configurator "%s"', $name));
}
$configurator = new $name();
}
$this->configurators[$name] = $configurator;
}
return $this->configurators[$name];
} | php | {
"resource": ""
} |
q264069 | DatagridRegistry.hasConfigurator | test | public function hasConfigurator(string $name): bool
{
if (isset($this->configurators[$name])) {
return true;
}
if (isset($this->lazyConfigurators[$name])) {
return true;
}
return class_exists($name) && in_array(DatagridConfiguratorInterface::class, class_implements($name), true);
} | php | {
"resource": ""
} |
q264070 | WriterFactory.getWriterClassNameByFormat | test | public function getWriterClassNameByFormat($format)
{
$format = strtolower($format);
foreach ($this->writers as $writer) {
$class = get_class($writer);
$name = strtolower(substr($class, strrpos($class, '\\') + 1));
if ($name == $format) {
return $class;
}
}
return null;
} | php | {
"resource": ""
} |
q264071 | WriterFactory.getWriterFromContentNegotiation | test | protected function getWriterFromContentNegotiation(MediaType $contentType, array $supportedWriter = null)
{
if (empty($this->contentNegotiation)) {
return null;
}
foreach ($this->contentNegotiation as $acceptedContentType => $writerClass) {
if ($supportedWriter !== null && !in_array($writerClass, $supportedWriter)) {
continue;
}
$acceptedContentType = new MediaType($acceptedContentType);
if ($acceptedContentType->match($contentType)) {
$writer = $this->getWriterByInstance($writerClass);
if ($writer !== null) {
return $writer;
}
}
}
return null;
} | php | {
"resource": ""
} |
q264072 | DateTimeToLocalizedStringTransformer.transform | test | public function transform($dateTime)
{
if (null === $dateTime) {
return '';
}
if (!$dateTime instanceof \DateTime) {
throw new TransformationFailedException('Expected a \DateTime.');
}
// convert time to UTC before passing it to the formatter
$dateTime = clone $dateTime;
if ('UTC' !== $this->inputTimezone) {
$dateTime->setTimezone(new \DateTimeZone('UTC'));
}
$value = $this->getIntlDateFormatter()->format((int) $dateTime->format('U'));
if (intl_get_error_code() != 0) {
throw new TransformationFailedException(intl_get_error_message());
}
return $value;
} | php | {
"resource": ""
} |
q264073 | DatagridView.init | test | public function init(DatagridInterface $datagrid)
{
if (null === $data = $datagrid->getData()) {
throw new InvalidArgumentException('No data provided for the view.');
}
$columns = $datagrid->getColumns();
foreach ($columns as $column) {
$this->columns[$column->getName()] = $column->createHeaderView($this);
}
if (!isset($this->vars['row_vars'])) {
$this->vars['row_vars'] = [];
}
foreach ($data as $id => $value) {
$this->rows[$id] = $row = new DatagridRowView($this, $columns, $value, $id);
$row->vars = $this->vars['row_vars'];
}
} | php | {
"resource": ""
} |
q264074 | Processor.read | test | public function read($schema, Payload $payload, SchemaVisitorInterface $visitor = null)
{
$data = $this->parse($payload);
$schema = $this->getSchema($schema);
if ($visitor === null) {
$visitor = new TypeVisitor();
}
return $this->traverser->traverse(
$data,
$schema,
$visitor
);
} | php | {
"resource": ""
} |
q264075 | Processor.parse | test | public function parse(Payload $payload)
{
$reader = $this->getReader($payload->getContentType(), $payload->getRwType(), $payload->getRwSupported());
$data = $reader->read($payload->getData());
$transformer = $payload->getTransformer();
if ($transformer === null) {
$transformer = $this->getDefaultTransformer($payload->getContentType());
}
if ($transformer instanceof TransformerInterface) {
$data = $transformer->transform($data);
}
return $data;
} | php | {
"resource": ""
} |
q264076 | Processor.write | test | public function write(Payload $payload)
{
$data = $payload->getData();
$data = $this->transform($data);
$writer = $this->getWriter($payload->getContentType(), $payload->getRwType(), $payload->getRwSupported());
return $writer->write($data);
} | php | {
"resource": ""
} |
q264077 | Processor.getReader | test | public function getReader($contentType, $readerType = null, array $supportedReader = null)
{
if ($readerType === null) {
$reader = $this->config->getReaderFactory()->getReaderByContentType($contentType, $supportedReader);
} else {
$reader = $this->config->getReaderFactory()->getReaderByInstance($readerType);
}
if ($reader === null) {
$reader = $this->config->getReaderFactory()->getDefaultReader($supportedReader);
}
if (!$reader instanceof ReaderInterface) {
throw new StatusCode\UnsupportedMediaTypeException('Could not find fitting data reader');
}
return $reader;
} | php | {
"resource": ""
} |
q264078 | Processor.getWriter | test | public function getWriter($contentType, $writerType = null, array $supportedWriter = null)
{
if ($writerType === null) {
$writer = $this->config->getWriterFactory()->getWriterByContentType($contentType, $supportedWriter);
} else {
$writer = $this->config->getWriterFactory()->getWriterByInstance($writerType);
}
if ($writer === null) {
$writer = $this->config->getWriterFactory()->getDefaultWriter($supportedWriter);
}
if (!$writer instanceof WriterInterface) {
throw new StatusCode\NotAcceptableException('Could not find fitting data writer');
}
return $writer;
} | php | {
"resource": ""
} |
q264079 | Laravel5._before | test | public function _before(\Codeception\TestCase $test)
{
$this->initializeLaravel();
if ($this->app['db'] && $this->config['cleanup']) {
$this->app['db']->beginTransaction();
}
} | php | {
"resource": ""
} |
q264080 | Laravel5._after | test | public function _after(\Codeception\TestCase $test)
{
if ($this->app['db'] && $this->config['cleanup']) {
$this->app['db']->rollback();
}
if ($this->app['auth']) {
$this->app['auth']->logout();
}
if ($this->app['cache']) {
$this->app['cache']->flush();
}
if ($this->app['session']) {
$this->app['session']->flush();
}
// disconnect from DB to prevent "Too many connections" issue
if ($this->app['db']) {
$this->app['db']->disconnect();
}
} | php | {
"resource": ""
} |
q264081 | Laravel5._afterStep | test | public function _afterStep(\Codeception\Step $step)
{
\Illuminate\Support\Facades\Facade::clearResolvedInstances();
parent::_afterStep($step);
} | php | {
"resource": ""
} |
q264082 | Laravel5.initializeLaravel | test | protected function initializeLaravel()
{
$this->app = $this->bootApplication();
$this->app->instance('request', new Request());
$this->client = new LaravelConnector($this->app);
$this->client->followRedirects(true);
} | php | {
"resource": ""
} |
q264083 | Laravel5.bootApplication | test | protected function bootApplication()
{
$projectDir = explode($this->config['packages'], \Codeception\Configuration::projectDir())[0];
$projectDir .= $this->config['root'];
require $projectDir . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
\Illuminate\Support\ClassLoader::register();
$bootstrapFile = $projectDir . $this->config['bootstrap'];
if (! file_exists($bootstrapFile)) {
throw new ModuleConfig(
$this, "Laravel bootstrap file not found in $bootstrapFile.\nPlease provide a valid path to it using 'bootstrap' config param. "
);
}
$app = require $bootstrapFile;
$app->loadEnvironmentFrom($this->config['environment_file']);
return $app;
} | php | {
"resource": ""
} |
q264084 | Laravel5.amOnRoute | test | public function amOnRoute($route, $params = [])
{
$domain = $this->app['routes']->getByName($route)->domain();
$absolute = ! is_null($domain);
$url = $this->app['url']->route($route, $params, $absolute);
$this->amOnPage($url);
} | php | {
"resource": ""
} |
q264085 | Laravel5.amOnAction | test | public function amOnAction($action, $params = [])
{
$namespacedAction = $this->actionWithNamespace($action);
$domain = $this->app['routes']->getByAction($namespacedAction)->domain();
$absolute = ! is_null($domain);
$url = $this->app['url']->action($action, $params, $absolute);
$this->amOnPage($url);
} | php | {
"resource": ""
} |
q264086 | Laravel5.actionWithNamespace | test | protected function actionWithNamespace($action)
{
$rootNamespace = $this->getRootControllerNamespace();
if ($rootNamespace && ! (strpos($action, '\\') === 0)) {
return $rootNamespace . '\\' . $action;
} else {
return trim($action, '\\');
}
} | php | {
"resource": ""
} |
q264087 | Laravel5.seeCurrentRouteIs | test | public function seeCurrentRouteIs($route, $params = array())
{
$this->seeCurrentUrlEquals($this->app['url']->route($route, $params, false));
} | php | {
"resource": ""
} |
q264088 | Laravel5.seeCurrentActionIs | test | public function seeCurrentActionIs($action, $params = array())
{
$this->seeCurrentUrlEquals($this->app['url']->action($action, $params, false));
} | php | {
"resource": ""
} |
q264089 | Laravel5.seeInSession | test | public function seeInSession($key, $value = null)
{
if (is_array($key)) {
$this->seeSessionHasValues($key);
return;
}
if (is_null($value)) {
$this->assertTrue($this->app['session']->has($key));
} else {
$this->assertEquals($value, $this->app['session']->get($key));
}
} | php | {
"resource": ""
} |
q264090 | Laravel5.seeFormHasErrors | test | public function seeFormHasErrors()
{
$viewErrorBag = $this->app->make('view')->shared('errors');
$this->assertTrue(count($viewErrorBag) > 0);
} | php | {
"resource": ""
} |
q264091 | Laravel5.seeFormErrorMessage | test | public function seeFormErrorMessage($key, $errorMessage)
{
$viewErrorBag = $this->app['view']->shared('errors');
$this->assertEquals($errorMessage, $viewErrorBag->first($key));
} | php | {
"resource": ""
} |
q264092 | Laravel5.amLoggedAs | test | public function amLoggedAs($user, $driver = null)
{
if ($user instanceof Authenticatable) {
$this->app['auth']->driver($driver)->setUser($user);
} else {
$this->app['auth']->driver($driver)->attempt($user);
}
} | php | {
"resource": ""
} |
q264093 | Laravel5.haveRecord | test | public function haveRecord($model, $attributes = array())
{
$id = $this->app['db']->table($model)->insertGetId($attributes);
if (!$id) {
$this->fail("Couldn't insert record into table $model");
}
return $id;
} | php | {
"resource": ""
} |
q264094 | NumberToLocalizedStringTransformer.transform | test | public function transform($value)
{
if (null === $value) {
return '';
}
if (!is_numeric($value)) {
throw new TransformationFailedException('Expected a numeric.');
}
$formatter = $this->getNumberFormatter();
$value = $formatter->format($value);
if (intl_is_failure($formatter->getErrorCode())) {
throw new TransformationFailedException($formatter->getErrorMessage());
}
// Convert fixed spaces to normal ones
$value = str_replace("\xc2\xa0", ' ', $value);
return $value;
} | php | {
"resource": ""
} |
q264095 | NumberToLocalizedStringTransformer.getNumberFormatter | test | protected function getNumberFormatter($type = \NumberFormatter::DECIMAL)
{
$formatter = new \NumberFormatter(\Locale::getDefault(), $type);
if (null !== $this->precision) {
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->precision);
$formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, $this->roundingMode);
}
$formatter->setAttribute(\NumberFormatter::GROUPING_USED, $this->grouping);
return $formatter;
} | php | {
"resource": ""
} |
q264096 | CurveArray.nest | test | public static function nest(array $data, $seperator = '_')
{
if (self::isAssoc($data)) {
$result = new \stdClass();
foreach ($data as $key => $value) {
if (($pos = strpos($key, $seperator)) !== false) {
$subKey = substr($key, 0, $pos);
$name = substr($key, $pos + 1);
if (!isset($result->{$subKey})) {
$result->{$subKey} = self::nest(self::getParts($data, $subKey . $seperator), $seperator);
}
} else {
$result->{$key} = $value;
}
}
return $result;
} else {
$result = [];
foreach ($data as $value) {
$result[] = self::nest($value, $seperator);
}
return $result;
}
} | php | {
"resource": ""
} |
q264097 | CurveArray.flatten | test | public static function flatten($data, $seperator = '_', $prefix = null, array &$result = null)
{
if ($result === null) {
$result = array();
}
if ($data instanceof \stdClass) {
$data = (array) $data;
} elseif (!is_array($data)) {
throw new InvalidArgumentException('Data must be either an stdClass or array');
}
foreach ($data as $key => $value) {
if ($value instanceof \stdClass || is_array($value)) {
self::flatten($value, $seperator, $prefix . $key . $seperator, $result);
} else {
$result[$prefix . $key] = $value;
}
}
return $result;
} | php | {
"resource": ""
} |
q264098 | CurveArray.objectify | test | public static function objectify(array $data)
{
if (self::isAssoc($data)) {
$result = new \stdClass();
foreach ($data as $key => $value) {
$result->{$key} = is_array($value) ? self::objectify($value) : $value;
}
return $result;
} else {
$result = [];
foreach ($data as $value) {
$result[] = is_array($value) ? self::objectify($value) : $value;
}
return $result;
}
} | php | {
"resource": ""
} |
q264099 | ResolvedColumnType.createColumn | test | public function createColumn(string $name, array $options = []): ColumnInterface
{
$options = $this->getOptionsResolver()->resolve($options);
return $this->newColumn($name, $options);
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.