_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9700 | S3ClientFactory.getClient | train | public function getClient()
{
return new S3Client([
'version' => $this->apiVersion,
'region' => $this->region,
'credentials' => [
'key' => $this->key,
'secret' => $this->secret,
]
]);
} | php | {
"resource": ""
} |
q9701 | ImpersonatorServiceProvider.extendAuthDriver | train | private function extendAuthDriver()
{
/** @var \Illuminate\Auth\AuthManager $auth */
$auth = $this->app['auth'];
$this->app['auth']->extend('session', function (Application $app, $name, array $config) use ($auth) {
$provider = $auth->createUserProvider($config['provider']);
return tap(new Guard\SessionGuard($name, $provider, $app['session.store']), function ($guard) use ($app) {
if (method_exists($guard, 'setCookieJar'))
$guard->setCookieJar($app['cookie']);
if (method_exists($guard, 'setDispatcher'))
$guard->setDispatcher($app['events']);
if (method_exists($guard, 'setRequest'))
$guard->setRequest($app->refresh('request', $guard, 'setRequest'));
});
});
} | php | {
"resource": ""
} |
q9702 | HtmlDomParser.loadUrl | train | public function loadUrl($url, $curl = false) {
if ($curl) {
$content = self::loadContent($url);
if (empty($content)) {
throw new Exception("Can't get content from " . $url);
}
$this->loadString($content);
} else {
$this->load_file($url);
}
} | php | {
"resource": ""
} |
q9703 | HtmlDomParser.loadContent | train | private static function loadContent($url) {
//TODO: implement URL content load functionality with CURL and proxy
$ch = curl_init($url);
$options = array(
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
if ($content === false) {
throw new Exception("Can't get content from " . $url);
}
return $content;
} | php | {
"resource": ""
} |
q9704 | Asset.validate | train | protected function validate($object)
{
$object = (object) $object;
if ($object instanceof $this->is) {
return $object;
}
throw new \DomainException(
sprintf(
"The Asset advertised as being of type %s is actually of type %s",
$this->is,
get_class($object)
)
);
} | php | {
"resource": ""
} |
q9705 | Asset.is | train | public function is($type = null)
{
if ($type === null) {
return $this->is;
} else {
return $type == $this->is;
}
} | php | {
"resource": ""
} |
q9706 | Asset.single | train | public function single(\Closure $closure)
{
if ($this->asset === null) {
$this->asset = function ($asset = null, $assetManager = null) use ($closure) {
static $obj;
if ($obj === null) {
$obj = $this->validate($closure($asset, $assetManager));
}
return $obj;
};
}
return $this;
} | php | {
"resource": ""
} |
q9707 | Pager.createFullPages | train | private function createFullPages()
{
$pageStart = 1;
$pageEnd = $this->maxPage;
$tmp = $this->currentPage;
$pager = [];
while (($pageEnd - $tmp) < 4) {
$tmp--; // @codeCoverageIgnore
}
if ($tmp != $this->currentPage) {
$pageStart = 1 + ($tmp - 5); // @codeCoverageIgnore
}
if ($this->currentPage > 5 && $this->currentPage == $tmp) {
$pageStart = 1 + ($this->currentPage - 5);
}
$page = 0;
for ($i = $pageStart; $i < $tmp; $i++) {
$pager[$page] = '<a href="' . $this->buildHref($i) . '">' . $i . '</a>';
$page++;
}
for ($i = $tmp; $i <= $pageEnd && $page < 9; $i++) {
$pager[$page] = $this->buildAnchor($i);
$page++;
}
return $pager;
} | php | {
"resource": ""
} |
q9708 | Pager.createSimplePages | train | private function createSimplePages()
{
$pager = [];
for ($i = 1; $i <= $this->maxPage; $i++) {
$pager[$i - 1] = $this->buildAnchor($i);
}
return $pager;
} | php | {
"resource": ""
} |
q9709 | Pager.displayPager | train | private function displayPager()
{
$pager = ($this->maxPage > 9) ? $this->createFullPages() : $this->createSimplePages();
echo '<div class="pager">';
$this->displayLeftSide();
for ($i = 0; $i < count($pager); $i++) {
echo $pager[$i];
}
$this->displayRightSide();
echo "</div>";
} | php | {
"resource": ""
} |
q9710 | SaveService.save | train | public function save(SaveEntityInterface $entity)
{
$entity = $this->persist($entity);
$this->flush();
return $entity;
} | php | {
"resource": ""
} |
q9711 | InjectionChain.getByIndex | train | public function getByIndex($index)
{
if (! is_numeric($index)) {
throw new RuntimeException('Index needs to be a numeric value.');
}
$index = (int)$index;
if ($index < 0) {
$index += count($this->chain);
}
return isset($this->chain[$index])
? $this->chain[$index]
: false;
} | php | {
"resource": ""
} |
q9712 | DispatchListener.getAdminPanel | train | public function getAdminPanel(MvcEvent $event)
{
$matchRoute = $event->getRouteMatch();
if (empty($matchRoute)) {
return null;
}
/** @var \RcmAdmin\Controller\AdminPanelController $adminPanelController */
$adminPanelController = $this->serviceLocator->get(
\RcmAdmin\Controller\AdminPanelController::class
);
$adminPanelController->setEvent($event);
$adminWrapper = $adminPanelController->getAdminWrapperAction();
if (!$adminWrapper instanceof ViewModel) {
return;
}
/** @var \Zend\View\Model\ViewModel $viewModel */
$layout = $event->getViewModel();
$layout->addChild($adminWrapper, 'rcmAdminPanel');
} | php | {
"resource": ""
} |
q9713 | ModelCloning.clone | train | public function clone($modelitemId)
{
event(new BeforeClone($this));
$this->beforeClone();
$this->doClone();
$this->afterClone();
event(new AfterClone($this));
} | php | {
"resource": ""
} |
q9714 | ModelCloning.excludeOnClone | train | public function excludeOnClone()
{
return [
$this->model->getKeyName(),
$this->model->getCreatedAtColumn(),
$this->model->getUpdatedAtColumn(),
];
} | php | {
"resource": ""
} |
q9715 | AbstractMaterialDesignIconicFontTwigExtension.materialDesignIconicFontIcon | train | protected function materialDesignIconicFontIcon(MaterialDesignIconicFontIconInterface $icon) {
$attributes = [];
$attributes["class"][] = "zmdi";
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderName($icon);
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderSize($icon);
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderFixedWidth($icon);
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderBorder($icon);
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderPull($icon);
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderSpin($icon);
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderRotate($icon);
$attributes["class"][] = MaterialDesignIconicFontIconRenderer::renderFlip($icon);
$attributes["style"] = MaterialDesignIconicFontIconRenderer::renderStyle($icon);
return static::coreHTMLElement("i", null, $attributes);
} | php | {
"resource": ""
} |
q9716 | AbstractMaterialDesignIconicFontTwigExtension.materialDesignIconicFontList | train | protected function materialDesignIconicFontList($items) {
$innerHTML = true === is_array($items) ? implode("\n", $items) : $items;
return static::coreHTMLElement("ul", $innerHTML, ["class" => "zmdi-hc-ul"]);
} | php | {
"resource": ""
} |
q9717 | AbstractMaterialDesignIconicFontTwigExtension.materialDesignIconicFontListIcon | train | protected function materialDesignIconicFontListIcon($icon, $content) {
$glyphicon = null !== $icon ? StringHelper::replace($icon, ["class=\"zmdi"], ["class=\"zmdi-hc-li zmdi"]) : "";
$innerHTML = null !== $content ? $content : "";
return static::coreHTMLElement("li", $glyphicon . $innerHTML);
} | php | {
"resource": ""
} |
q9718 | S3Service.uploadFileWithFolderAndName | train | public function uploadFileWithFolderAndName(UploadedFile $file, $folderPath, $fileName)
{
$folderPath = !empty($folderPath) ? $folderPath . '/' : '';
$path = $this->env . '/' . $folderPath . $fileName . '.'. $file->guessClientExtension();
/** @var Result $result */
$result = $this->client->putObject([
'ACL' => 'public-read',
'Bucket' => $this->bucketName,
'SourceFile' => $file->getRealPath(),
'Key' => $path
]);
return new FileUploadedModel($path, $result->get('ObjectURL'), FileUploadedModel::VENDOR_S3);
} | php | {
"resource": ""
} |
q9719 | S3Service.uploadFile | train | public function uploadFile(UploadedFile $file)
{
$path = $this->env . '/' . md5(time() . random_int(1,100000)) . '.'. $file->guessClientExtension();
/** @var Result $result */
$result = $this->client->putObject([
'ACL' => 'public-read',
'Bucket' => $this->bucketName,
'SourceFile' => $file->getRealPath(),
'Key' => $path
]);
return new FileUploadedModel($path, $result->get('ObjectURL'), FileUploadedModel::VENDOR_S3);
} | php | {
"resource": ""
} |
q9720 | Cookie.send | train | public function send()
{
$args = [
$this->name,
$this->value,
time() + $this->lifetime,
$this->path,
$this->domain,
$this->secure,
$this->httpOnly
];
$function = (!$this->urlEncodedValue) ? 'setrawcookie' : 'setcookie';
call_user_func_array($function, $args);
$_COOKIE[$this->name] = $this->value;
} | php | {
"resource": ""
} |
q9721 | UserClass.extendClass | train | public function extendClass($className, $useAlias = true)
{
if ($className[0] === '\\' && $useAlias) {
$className = ltrim($className, '\\');
$this->useClass($className);
$_p = explode('\\', $className);
$shortClassName = end($_p);
$this->extends = new ClassName($shortClassName);
} else {
$this->extends = new ClassName($className);
}
} | php | {
"resource": ""
} |
q9722 | UserClass.generatePsr0ClassUnder | train | public function generatePsr0ClassUnder($directory, array $args = array())
{
$code = "<?php\n" . $this->render($args);
$classPath = $this->getPsr0ClassPath();
$path = $directory . DIRECTORY_SEPARATOR . $classPath;
if ($dir = dirname($path)) {
if (!file_exists($dir)) {
mkdir($dir, 0755, true);
}
}
if (file_put_contents($path, $code) === false) {
return false;
}
return $path;
} | php | {
"resource": ""
} |
q9723 | EzCronService.getCron | train | public function getCron(string $alias): ?EdgarEzCron
{
if ($cron = $this->repository->getCron($alias)) {
return $cron;
}
$crons = $this->getCrons();
if (isset($crons[$alias])) {
$cron = new EdgarEzCron();
$cron->setAlias($alias);
$cron->setExpression($crons[$alias]['expression']);
$cron->setArguments($crons[$alias]['arguments']);
$cron->setPriority($crons[$alias]['priority']);
$cron->setEnabled($crons[$alias]['enabled']);
return $cron;
}
return null;
} | php | {
"resource": ""
} |
q9724 | EzCronService.getCrons | train | public function getCrons(): array
{
/** @var CronInterface[] $crons */
$crons = $this->cronService->getCrons();
/** @var EdgarEzCron[] $ezCrons */
$ezCrons = $this->repository->listCrons();
$return = [];
foreach ($ezCrons as $ezCron) {
$return[$ezCron->getAlias()] = [
'alias' => $ezCron->getAlias(),
'expression' => $ezCron->getExpression(),
'arguments' => $ezCron->getArguments(),
'priority' => (int)$ezCron->getPriority(),
'enabled' => (int)$ezCron->getEnabled() == 1,
];
}
foreach ($crons as $cron) {
if (!isset($return[$cron->getAlias()])) {
$return[$cron->getAlias()] = [
'alias' => $cron->getAlias(),
'expression' => $cron->getExpression(),
'arguments' => $cron->getArguments(),
'priority' => (int)$cron->getPriority(),
'enabled' => true,
];
}
}
return $return;
} | php | {
"resource": ""
} |
q9725 | FormRenderer.renderOption | train | public static function renderOption($option, TranslatorInterface $translator = null) {
if (null === $option) {
return null !== $translator ? $translator->trans("label.empty_selection") : "Empty selection";
}
// Check the implementation.
if (true === ($option instanceof TranslatedChoiceLabelInterface)) {
$output = $option->getTranslatedChoiceLabel($translator);
} else if (true === ($option instanceof ChoiceLabelInterface)) {
$output = $option->getChoiceLabel();
} else {
$output = "This option must implements [Translated]ChoiceLabelInterface";
}
if (true === ($option instanceof AlphabeticalTreeNodeInterface)) {
$multiplier = AlphabeticalTreeNodeHelper::getLevel($option);
$nbsp = html_entity_decode(" ");
$symbol = html_entity_decode(0 === $multiplier ? "─" : "└");
$output = implode("", [str_repeat($nbsp, $multiplier * 3), $symbol, $nbsp, $output]);
}
return $output;
} | php | {
"resource": ""
} |
q9726 | FormFactory.newEntityType | train | public static function newEntityType($class, array $choices = [], array $options = []) {
// Check the options.
if (false === array_key_exists("empty", $options)) {
$options["empty"] = false;
}
if (false === array_key_exists("translator", $options)) {
$options["translator"] = null;
}
// Initialize the output.
$output = [
"class" => $class,
"choices" => [],
"choice_label" => function($entity) use ($options) {
return FormRenderer::renderOption($entity, $options["translator"]);
},
];
// Add an empty choice.
if (true === $options["empty"]) {
$output["choices"][] = null;
}
// Add all choices.
$output["choices"] = array_merge($output["choices"], $choices);
return $output;
} | php | {
"resource": ""
} |
q9727 | CronController.listAction | train | public function listAction(): Response
{
$this->permissionAccess('uicron', 'list');
$crons = $this->cronService->getCrons();
return $this->render('@EdgarEzUICron/cron/list.html.twig', [
'crons' => $crons,
]);
} | php | {
"resource": ""
} |
q9728 | CronController.permissionAccess | train | protected function permissionAccess(string $module, string $function): ?RedirectResponse
{
if (!$this->permissionResolver->hasAccess($module, $function)) {
$this->notificationHandler->error(
$this->translator->trans(
'edgar.ezuicron.permission.failed',
[],
'edgarezuicron'
)
);
return new RedirectResponse($this->generateUrl('ezplatform.dashboard', []));
}
return null;
} | php | {
"resource": ""
} |
q9729 | File.path | train | public function path(string $thumbSize = null)
{
return $this->attributes['type']
.DS.$this->attributes['category']
.($thumbSize ? DS.$thumbSize : '')
.DS.$this->attributes['name'].'.'.$this->attributes['extension'];
} | php | {
"resource": ""
} |
q9730 | File.storeAsZip | train | protected function storeAsZip(UploadedFile $file, array $data)
{
$disk = $this->storageDisk($data['disk']);
// Make zip archive name with full path.
$zipname = $disk->getDriver()->getAdapter()->getPathPrefix()
.$data['type'].DS.$data['category'].DS
.$data['name'].'.'.$data['extension'] . '.zip';
// Check if new file exists
if ($disk->exists($zipname)) {
throw new FileException(sprintf(
'File with name `%s` already exists!', $zipname
));
}
// Storing zip.
$zip = new \ZipArchive;
$zip->open($zipname, \ZipArchive::CREATE);
$zip->addFile($file->getRealPath(), $data['name'].'.'.$data['extension']);
$zip->close();
$this->attributes['name'] = $data['name'].'.'.$data['extension'];
$this->attributes['extension'] = 'zip';
$this->attributes['filesize'] = filesize($zipname);
} | php | {
"resource": ""
} |
q9731 | File.storeAsImage | train | protected function storeAsImage(UploadedFile $file, array $data)
{
// Store uploaded image, to work it.
$this->storeAsFile($file, $data);
// Prepare local variables.
$properties = [];
$disk = $this->storageDisk($data['disk']);
$path_prefix = $data['type'].DS.$data['category'].DS;
$path_suffix = DS.$data['name'].'.'.$data['extension'];
$quality = setting('files.images_quality', 75);
$is_convert = setting('files.images_is_convert', true);
// Resave original file.
$image = $this->imageResave(
$this->getAbsolutePathAttribute(),
$disk->path($path_prefix.trim($path_suffix, DS)),
setting('files.images_max_width', 3840),
setting('files.images_max_height', 2160),
$quality, $is_convert
);
if ($image) {
// If extension has changed, then delete original file.
if ($data['extension'] != $image['extension']) {
$disk->delete($this->path);
}
// Revision attributes.
$this->attributes['mime_type'] = $image['mime_type'];
$this->attributes['extension'] = $image['extension'];
$this->attributes['filesize'] = $image['filesize'];
$properties = [
'width' => $image['width'],
'height' => $image['height'],
];
$path_suffix = DS.$data['name'].'.'.$image['extension'];
}
// Cutting images.
foreach ($this->thumbSizes() as $key => $value) {
@$disk->makeDirectory($path_prefix.$key);
$image = $this->imageResave(
$this->getAbsolutePathAttribute(),
$disk->path($path_prefix.$key.$path_suffix),
setting('files.images_'.$key.'_width', $value),
setting('files.images_'.$key.'_height', $value),
$quality, $is_convert
);
if (! $image) break;
// Add to options.
$properties += [
$key => [
'width' => $image['width'],
'height' => $image['height'],
'filesize' => $image['filesize'],
]
];
}
return $this->setAttribute('properties', $properties);
} | php | {
"resource": ""
} |
q9732 | Sonarr.getCommand | train | public function getCommand($id = null)
{
$uri = ($id) ? 'command/' . $id : 'command';
$response = [
'uri' => $uri,
'type' => 'get',
'data' => []
];
return $this->processRequest($response);
} | php | {
"resource": ""
} |
q9733 | Sonarr.postCommand | train | public function postCommand($name, array $params = null)
{
$uri = 'command';
$uriData = [
'name' => $name
];
if (is_array($params)) {
foreach($params as $key=>$value) {
$uriData[$key] = $value;
}
}
$response = [
'uri' => $uri,
'type' => 'post',
'data' => $uriData
];
return $this->processRequest($response);
} | php | {
"resource": ""
} |
q9734 | Sonarr.getRelease | train | public function getRelease($episodeId)
{
$uri = 'release';
$uriData = [
'episodeId' => $episodeId
];
$response = [
'uri' => $uri,
'type' => 'get',
'data' => $uriData
];
return $this->processRequest($response);
} | php | {
"resource": ""
} |
q9735 | Sonarr.postReleasePush | train | public function postReleasePush($title, $downloadUrl, $downloadProtocol, $publishDate)
{
$uri = 'release';
$uriData = [
'title' => $title,
'downloadUrl' => $downloadUrl,
'downloadProtocol' => $downloadProtocol,
'publishDate' => $publishDate
];
$response = [
'uri' => $uri,
'type' => 'post',
'data' => $uriData
];
return $this->processRequest($response);
} | php | {
"resource": ""
} |
q9736 | Sonarr.postSeries | train | public function postSeries(array $data, $onlyFutureEpisodes = true)
{
$uri = 'series';
$uriData = [];
// Required
$uriData['tvdbId'] = $data['tvdbId'];
$uriData['title'] = $data['title'];
$uriData['qualityProfileId'] = $data['qualityProfileId'];
if ( array_key_exists('titleSlug', $data) ) { $uriData['titleSlug'] = $data['titleSlug']; }
if ( array_key_exists('seasons', $data) ) { $uriData['seasons'] = $data['seasons']; }
if ( array_key_exists('path', $data) ) { $uriData['path'] = $data['path']; }
if ( array_key_exists('rootFolderPath', $data) ) { $uriData['rootFolderPath'] = $data['rootFolderPath']; }
if ( array_key_exists('tvRageId', $data) ) { $uriData['tvRageId'] = $data['tvRageId']; }
$uriData['seasonFolder'] = ( array_key_exists('seasonFolder', $data) ) ? $data['seasonFolder'] : true;
if ( array_key_exists('monitored', $data) ) { $uriData['monitored'] = $data['monitored']; }
if ( $onlyFutureEpisodes ) {
$uriData['addOptions'] = [
'ignoreEpisodesWithFiles' => true,
'ignoreEpisodesWithoutFiles' => true
];
}
$response = [
'uri' => $uri,
'type' => 'post',
'data' => $uriData
];
return $this->processRequest($response);
} | php | {
"resource": ""
} |
q9737 | Sonarr.deleteSeries | train | public function deleteSeries($id, $deleteFiles = true)
{
$uri = 'series';
$uriData = [];
$uriData['deleteFiles'] = ($deleteFiles) ? 'true' : 'false';
$response = [
'uri' => $uri . '/' . $id,
'type' => 'delete',
'data' => $uriData
];
return $this->processRequest($response);
} | php | {
"resource": ""
} |
q9738 | Sonarr.processRequest | train | protected function processRequest(array $request)
{
try {
$response = $this->_request(
[
'uri' => $request['uri'],
'type' => $request['type'],
'data' => $request['data']
]
);
} catch ( \Exception $e ) {
echo json_encode(array(
'error' => array(
'msg' => $e->getMessage(),
'code' => $e->getCode(),
),
));
exit();
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q9739 | AttributeCollection.add | train | public function add($items = [])
{
if (!is_array($items) || func_num_args() > 1) {
$items = func_get_args();
}
$this->push($this->formatInnerField(null, $items));
} | php | {
"resource": ""
} |
q9740 | AttributeCollection.createField | train | private function createField($type, $name, $value, $inner)
{
if ($this->hasOptionsMethod($name)) {
$inner = array_merge($inner, ['options' => $this->getOptions($name)]);
}
return $this->fields->create($type, $name, $this->getValue($name), $inner);
} | php | {
"resource": ""
} |
q9741 | CommandHelper.getCheckbox | train | public static function getCheckbox($checked) {
if (true === $checked) {
return sprintf("<fg=green;options=bold>%s</>", OSHelper::isWindows() ? "OK" : "\xE2\x9C\x94");
}
return sprintf("<fg=yellow;options=bold>%s</>", OSHelper::isWindows() ? "KO" : "!");
} | php | {
"resource": ""
} |
q9742 | Redirect.setRedirectUrl | train | public function setRedirectUrl($redirectUrl)
{
if (!$this->getUrlValidator()->isValid($redirectUrl)) {
throw new InvalidArgumentException('URL provided is invalid');
}
$this->redirectUrl = $redirectUrl;
} | php | {
"resource": ""
} |
q9743 | Redirect.setRequestUrl | train | public function setRequestUrl($requestUrl)
{
if (!$this->getUrlValidator()->isValid($requestUrl)) {
throw new InvalidArgumentException('URL provided is invalid');
}
$this->requestUrl = $requestUrl;
} | php | {
"resource": ""
} |
q9744 | Redirect.setSite | train | public function setSite($site)
{
if ($site === null) {
$this->siteId = null;
$this->site = null;
return;
}
$this->siteId = $site->getSiteId();
$this->site = $site;
} | php | {
"resource": ""
} |
q9745 | Form.removeMemorizedValue | train | public static function removeMemorizedValue($fieldId = null)
{
if (isset($_SESSION['_FIELDS'])) {
if (is_null($fieldId)) {
$_SESSION['_FIELDS'] = null;
unset($_SESSION['_FIELDS']);
} else {
unset($_SESSION['_FIELDS'][$fieldId]);
}
}
} | php | {
"resource": ""
} |
q9746 | Form.buildObject | train | public function buildObject($instance = null)
{
if (is_null($instance)) {
return (object) $this->fields;
}
foreach ($this->fields as $property => $value) {
$method = 'set' . ucwords($property);
if (is_callable([$instance, $method])) {
$instance->{$method}($value);
}
}
} | php | {
"resource": ""
} |
q9747 | SlackProvider.loadUserByUsername | train | public function loadUserByUsername($username)
{
$slackUser = $this->client->getSlackUserFromOAuthCode($username);
if (!$slackUser->isValid()) {
throw new UsernameNotFoundException('No access token found.');
}
$user = $this->userService->findBySlackUserId($slackUser->getUserId());
if (!empty($user)) {
return $user;
}
$user = $this->userService->findUserByEmail($slackUser->getEmail());
if (!empty($user)) {
$user->setSlackUserId($slackUser->getUserId());
return $user;
}
return $this->registerUser($slackUser);
} | php | {
"resource": ""
} |
q9748 | MaterialDesignColorPaletteTwigExtension.materialDesignColorPaletteBackgroundFunction | train | public function materialDesignColorPaletteBackgroundFunction(array $args = []) {
return $this->materialDesignColorPalette("bg", ArrayHelper::get($args, "name"), ArrayHelper::get($args, "value"));
} | php | {
"resource": ""
} |
q9749 | MaterialDesignColorPaletteTwigExtension.materialDesignColorPaletteTextFunction | train | public function materialDesignColorPaletteTextFunction(array $args = []) {
return $this->materialDesignColorPalette("text", ArrayHelper::get($args, "name"), ArrayHelper::get($args, "value"));
} | php | {
"resource": ""
} |
q9750 | SessionGuard.silentLogin | train | public function silentLogin(Authenticatable $user)
{
$this->updateSession($user->getAuthIdentifier());
$this->setUser($user);
} | php | {
"resource": ""
} |
q9751 | ArticlesController.massUpdate | train | public function massUpdate(ArticlesRequest $request)
{
$this->authorize('otherUpdate', $this->model);
$articles = $this->model->whereIn('id', $request->articles);
$messages = [];
switch ($request->mass_action) {
case 'published':
if (! $articles->update(['state' => 'published'])) {
$messages[] = 'unable to published';
}
break;
case 'unpublished':
if (! $articles->update(['state' => 'unpublished'])) {
$messages[] = 'unable to unpublished';
}
break;
case 'draft':
if (! $articles->update(['state' => 'draft'])) {
$messages[] = 'unable to draft';
}
break;
case 'on_mainpage':
if (! $articles->update(['on_mainpage' => 1])) {
$messages[] = 'unable to mainpage';
}
break;
case 'not_on_mainpage':
if (! $articles->update(['on_mainpage' => 0])) {
$messages[] = 'unable to not_on_mainpage';
}
break;
case 'allow_com':
if (! $articles->update(['allow_com' => 1])) {
$messages[] = 'unable to allow_com';
}
break;
case 'disallow_com':
if (! $articles->update(['allow_com' => 0])) {
$messages[] = 'unable to disallow_com';
}
break;
case 'currdate':
$articles->timestamps = false;
if (! $articles->update(['created_at' => date('Y-m-d H:i:s'), 'updated_at' => null])) {
$messages[] = 'unable to currdate';
}
$articles->timestamps = true;
break;
case 'delete':
if (! $articles->get()->each->delete()) {
$messages[] = 'unable to delete';
}
break;
case 'delete_drafts':
if (! $articles->where('state', 'draft')->get()->each->delete()) {
$messages[] = 'unable to delete_drafts';
}
break;
}
$message = empty($messages) ? 'msg.complete' : 'msg.complete_but_null';
return $this->makeRedirect(true, 'admin.articles.index', $message);
} | php | {
"resource": ""
} |
q9752 | RepositoryHelper.findByRequestParams | train | public function findByRequestParams(Request\Params $params)
{
if (empty($params->pagination) &&
isset($params->resourceConfig) &&
isset($params->resourceConfig->defaults) &&
isset($params->resourceConfig->defaults->pagination) &&
!$params->resourceConfig->defaults->pagination
) {
return $this->findAll(
$params->primaryClass,
$params->filters,
$params->sorting,
$params->translatable
);
} else {
return $this->findPaginated(
$params->primaryClass,
$params->filters,
$params->sorting,
$params->getPageOffset(),
$params->getPageSize(),
$params->translatable
);
}
} | php | {
"resource": ""
} |
q9753 | RepositoryHelper.findPaginated | train | public function findPaginated(
$entityClass,
array $criteria,
$sorting = [],
$offset = Request\Params::DEFAULT_PAGE_OFFSET,
$limit = Request\Params::DEFAULT_PAGE_SIZE,
$translatable = false
)
{
$qb = $this->getQueryBuilder($entityClass, $criteria, $sorting, $translatable);
$qb->setFirstResult($offset)
->setMaxResults($limit);
$paginator = new Paginator($qb->getQuery());
$collection = new PaginatedCollection($paginator);
return $collection;
} | php | {
"resource": ""
} |
q9754 | RendererBc.getPluginController | train | public function getPluginController($pluginName)
{
/*
* Deprecated. All controllers should come from the controller manager
* now and not the service manager.
*
* @todo Remove if statement once plugins have been converted.
*/
if ($this->serviceManager->has($pluginName)) {
$serviceManager = $this->serviceManager;
} else {
$serviceManager = $this->serviceManager->get('ControllerLoader');
}
if (!$serviceManager->has($pluginName)) {
throw new InvalidPluginException(
"Plugin $pluginName is not loaded or configured. Check
config/application.config.php"
);
}
$pluginController = $serviceManager->get($pluginName);
//Plugin controllers must implement this interface
if (!$pluginController instanceof PluginInterface) {
throw new InvalidPluginException(
'Class "' . get_class($pluginController) . '" for plugin "'
. $pluginName . '" does not implement '
. '\Rcm\Plugin\PluginInterface'
);
}
return $pluginController;
} | php | {
"resource": ""
} |
q9755 | RendererBc.handleResponseFromPluginController | train | public function handleResponseFromPluginController(ResponseInterface $response, $blockInstanceName)
{
// trigger_error( //@TODO remove all this and throw exception
// 'Returning responses from plugin controllers is no longer supported.
// The following plugin attempted this: ' . $blockInstanceName .
// ' Post to your own route to avoid this problem.',
// E_USER_WARNING
// );
foreach ($response->getHeaders() as $header) {
header($header->toString());
}
// //Some plugins used to return responses like this to signal a redirect to the login page
// if ($response->getStatusCode() == 401) {
// $href = '/login?redirect=' . urlencode($request->getUri()->getPath());;
// echo "You are not authorized to view this page. Try <a href=\"{$href}\">logging in</a> first.";
// exit;
// }
echo $response->getContent();
exit;
} | php | {
"resource": ""
} |
q9756 | Container.getRevisionDbInfo | train | public function getRevisionDbInfo($siteId, $name, $revisionId)
{
/** @var \Doctrine\ORM\QueryBuilder $queryBuilder */
$queryBuilder = $this->_em->createQueryBuilder()
->select(
'container,'
. 'publishedRevision.revisionId,'
. 'revision,'
. 'pluginWrappers,'
. 'pluginInstances'
)
->from(\Rcm\Entity\Container::class, 'container')
->leftJoin('container.publishedRevision', 'publishedRevision')
->leftJoin('container.site', 'site')
->leftJoin('container.revisions', 'revision')
->leftJoin('revision.pluginWrappers', 'pluginWrappers')
->leftJoin('pluginWrappers.instance', 'pluginInstances')
->where('site.siteId = :siteId')
->andWhere('container.name = :containerName')
->andWhere('revision.revisionId = :revisionId')
->orderBy('pluginWrappers.renderOrder', 'ASC')
->setParameter('siteId', $siteId)
->setParameter('containerName', $name)
->setParameter('revisionId', $revisionId);
$getData = $queryBuilder->getQuery()->getSingleResult(
Query::HYDRATE_ARRAY
);
$result = null;
if (!empty($getData)) {
$result = $getData[0];
$result['revision'] = $result['revisions'][$revisionId];
unset($result['revisions'], $getData);
}
return $result;
} | php | {
"resource": ""
} |
q9757 | EntityManagerTrait.getFilters | train | protected function getFilters(Request $request)
{
$type = $this->getFilterType($request);
if (!$type) {
return $request->query->get('search')['value'];
}
$filter = new $type();
$param = $filter->getBlockPrefix();
return $request->query->get($param);
} | php | {
"resource": ""
} |
q9758 | EntityManagerTrait.getLimit | train | protected function getLimit(Request $request)
{
return min(
$this->getMaxLimit($request),
$request->query->get(
'length',
$this->getDefaultLimit($request)
)
);
} | php | {
"resource": ""
} |
q9759 | EntityManagerTrait.getOffset | train | protected function getOffset(Request $request)
{
return max(
$request->query->get('start', 0),
$this->getDefaultOffset($request)
);
} | php | {
"resource": ""
} |
q9760 | EntityManagerTrait.search | train | protected function search(ModelCriteria $query, Request $request)
{
$filters = $this->getFilters($request);
if (empty($filters)) {
return $query;
}
$conditions = array();
$columns = $this->getSearchColumns($request);
if (is_array($filters)) {
foreach ($columns as $name => $condition) {
$items = explode('.', $name);
$i = 0;
$values = $filters;
while (is_array($values) && array_key_exists($items[$i], $values)) {
$values = $values[$items[$i]];
$i++;
}
if (is_array($values)) {
continue;
} else {
$value = trim($values);
}
if (empty($value) && !is_numeric($value)) {
continue;
}
$query->condition(
'search_'.$name,
sprintf($condition, $value)
);
$conditions[] = 'search_'.$name;
}
if (!empty($conditions)) {
return $query->where($conditions, 'and');
}
} else {
$value = trim($filters);
foreach ($columns as $name => $condition) {
$query->condition(
'search_'.$name,
sprintf($condition, $value)
);
$conditions[] = 'search_'.$name;
}
if (!empty($conditions)) {
return $query->where($conditions, 'or');
}
}
} | php | {
"resource": ""
} |
q9761 | EntityManagerTrait.sort | train | protected function sort(ModelCriteria $query, Request $request)
{
$order = $this->getSortOrder($request);
foreach ($order as $setting) {
$column = $setting[0];
$direction = $setting[1];
$query->orderBy($column, $direction);
}
return $query;
} | php | {
"resource": ""
} |
q9762 | EntityManagerTrait.getSortOrder | train | protected function getSortOrder(Request $request)
{
$sort = array();
$order = $request->query->get('order', array());
$columns = $this->getSortColumns($request);
foreach ($order as $setting) {
$index = $setting['column'];
if (array_key_exists($index, $columns)) {
$column = $columns[$index];
if (!is_array($column)) {
$column = array($column);
}
foreach ($column as $c) {
$sort[] = array(
$c,
$setting['dir'],
);
}
}
}
// Default sort order
if (empty($sort)) {
$sort = $this->getDefaultSortOrder($request);
}
return $sort;
} | php | {
"resource": ""
} |
q9763 | HashMap.sort | train | public function sort(callable $callback, bool $keySort = false): self
{
$keys = $this->keys;
$values = $this->values;
if ($keySort) {
uasort($keys, $callback);
$values = array_replace($keys, $values);
} else {
uasort($values, $callback);
$keys = array_replace($values, $keys);
}
$this->keys = array_values($keys);
$this->values = array_values($values);
return $this;
} | php | {
"resource": ""
} |
q9764 | HashMap.stringifyArrayKey | train | private static function stringifyArrayKey(array $key): string
{
ksort($key);
foreach ($key as &$value) {
if (is_array($value)) {
$value = self::stringifyArrayKey($value);
} elseif (is_object($value)) {
$value = self::stringifyKey($value);
}
}
return json_encode($key);
} | php | {
"resource": ""
} |
q9765 | HashMap.stringifyKey | train | private static function stringifyKey($key): string
{
if ($key === null || is_scalar($key)) {
return (string) $key;
}
if (is_object($key)) {
return spl_object_hash($key);
}
return static::stringifyArrayKey($key);
} | php | {
"resource": ""
} |
q9766 | MainPageMenu.addMenuItem | train | public function addMenuItem($image, $title, $url)
{
return $this->row->addItem(
new \Ease\Html\ATag(
$url,
new \Ease\TWB\Col(2,
"$title<center><img class=\"img-responsive\" src=\"$image\" alt=\"$title\"></center>")
)
);
} | php | {
"resource": ""
} |
q9767 | ByteArkV2UrlSigner.sign | train | public function sign($url, $expires = null, $options = [])
{
if (parse_url($url, PHP_URL_QUERY)) {
throw new \InvalidArgumentException('This signer do not accept URL with query string');
}
if (!$expires) {
$expires = time() + $this->options['default_age'];
}
return $url . '?' . $this->makeQueryString($this->makeQueryParams($url, $expires, $options));
} | php | {
"resource": ""
} |
q9768 | ViewRenderer.getDispatcher | train | protected function getDispatcher(): IDispatcher
{
if ($this->dispatcher === null) {
$this->dispatcher = new Dispatcher();
}
return $this->dispatcher;
} | php | {
"resource": ""
} |
q9769 | ViewRenderer.handle | train | public function handle(string $pattern, callable $resolver, int $priority = 0): Route
{
$this->cache = [];
return $this->collection->createRoute($pattern, $resolver)->set('priority', $priority);
} | php | {
"resource": ""
} |
q9770 | ViewRenderer.resolveViewName | train | public function resolveViewName(string $name): ?string
{
if (!array_key_exists($name, $this->cache)) {
$this->collection->sort();
$view = $this->getRouter()->route(new Context($name));
if (!is_string($view)) {
$view = null;
}
$this->cache[$name] = $view;
}
return $this->cache[$name];
} | php | {
"resource": ""
} |
q9771 | PoolFilesystem.scandirTask | train | protected function scandirTask(Context $context, string $path): \Generator
{
$entries = yield $this->pool->submit($context, new MethodCall(static::class, 'scandirJob', $path));
if ($entries === null) {
throw new FilesystemException(\sprintf('Failed to scan directory: "%s"', $path));
}
return $entries;
} | php | {
"resource": ""
} |
q9772 | PoolFilesystem.scandirJob | train | protected static function scandirJob(string $path): ?array
{
if (!\is_dir($path)) {
return null;
}
$entries = @\glob($path . \DIRECTORY_SEPARATOR . '*', \GLOB_NOSORT);
return ($entries === false) ? null : $entries;
} | php | {
"resource": ""
} |
q9773 | PoolFilesystem.readStreamTask | train | protected function readStreamTask(Context $context, string $path): \Generator
{
if (!yield $this->pool->submit($context, new MethodCall(static::class, 'checkFileReadableJob', $path))) {
throw new FilesystemException(\sprintf('File is not readable: "%s"', $path));
}
if (!$this->fileTransferSupported) {
return new ReadableFileStream($this->pool, $path);
}
$file = yield $this->pool->submit($context, new MethodCall(FileDescriptor::class, 'open', $path, 'rb'));
return new ReadableDescriptorStream($this->pool, $path, $file);
} | php | {
"resource": ""
} |
q9774 | PoolFilesystem.checkFileReadableJob | train | protected static function checkFileReadableJob(string $path): bool
{
if (!\is_file($path) || !\is_readable($path)) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q9775 | PoolFilesystem.writeStreamTask | train | protected function writeStreamTask(Context $context, string $path, bool $append = false): \Generator
{
if (!yield $this->pool->submit($context, new MethodCall(static::class, 'checkFileWritableJob', $path, !$append && !$this->fileTransferSupported))) {
throw new FilesystemException(\sprintf('File is not writable: "%s"', $path));
}
if (!$this->fileTransferSupported) {
return new WritableFileStream($this->pool, $path);
}
$file = yield $this->pool->submit($context, new MethodCall(FileDescriptor::class, 'open', $path, $append ? 'ab' : 'wb'));
return new WritableDescriptorStream($this->pool, $path, $file);
} | php | {
"resource": ""
} |
q9776 | PoolFilesystem.checkFileWritableJob | train | protected static function checkFileWritableJob(string $path, bool $truncate = false): bool
{
if (\file_exists($path) && (!\is_file($path) || !\is_writable($path))) {
return false;
}
if ($truncate && \is_file($path)) {
@\ftruncate(@\fopen($path, 'wb'), 0);
}
return true;
} | php | {
"resource": ""
} |
q9777 | Thumbnail.url | train | public function url($file, array $params)
{
$cacheFileSrc = $this->make($file, $params);
return $cacheFileSrc ? $cacheFileSrc : null;
} | php | {
"resource": ""
} |
q9778 | Thumbnail.urlPlaceholder | train | private function urlPlaceholder($width, $height, $text, $backgroundColor, $textColor, $textSize, $random, array
$options)
{
if ($random) {
$backgroundColor = $this->getRandomColor();
}
$src = 'https://placeholdit.imgix.net/~text?txtsize=' . $textSize . '&bg=' . str_replace('#', '',
$backgroundColor) . '&txtclr=' . str_replace('#', '', $textColor) . '&txt=' . $text . '&w=' . $width . '&h=' . $height;
if (!$this->options['placeholder']['cache']) {
return Html::img($src, $options);
}
$cacheFileName = md5($width . $height . $text . $backgroundColor . $textColor . $textSize);
$cacheFileExt = '.jpg';
$cacheFileDir = '/' . substr($cacheFileName, 0, 2);
$cacheFilePath = Yii::getAlias($this->cachePath) . $cacheFileDir;
$cacheFile = $cacheFilePath . '/' . $cacheFileName . $cacheFileExt;
$cacheUrl = str_replace('\\', '/', preg_replace('/^@[a-z]+/', '', $this->cachePath) . $cacheFileDir . '/'
. $cacheFileName . $cacheFileExt);
if (file_exists($cacheFile)) {
if ($this->cacheExpire !== 0 && (time() - filemtime($cacheFile)) > $this->cacheExpire) {
unlink($cacheFile);
} else {
return Html::img($cacheUrl, $options);
}
}
if (!is_dir($cacheFilePath)) {
mkdir($cacheFilePath, 0755, true);
}
$image = file_get_contents($src);
file_put_contents($cacheFile, $image);
return Html::img($cacheUrl, $options);
} | php | {
"resource": ""
} |
q9779 | Thumbnail.jsPlaceholder | train | private function jsPlaceholder($width, $height, $text, $backgroundColor, $textColor, $random, array $options)
{
$src = 'holder.js/' . $width . 'x' . $height . '?bg=' . $backgroundColor . '&fg=' . $textColor . '&text=' . $text;
if ($random) {
$src .= $src . '&random=yes';
}
return Html::img('', array_merge($options, ['data-src' => $src]));
} | php | {
"resource": ""
} |
q9780 | Thumbnail.thumbnail | train | private function thumbnail(array $params)
{
$mode = isset($params['mode']) ? $params['mode'] : self::THUMBNAIL_OUTBOUND;
$width = (isset($params['width']) && is_numeric($params['width'])) ? $params['width'] : null;
$height = (isset($params['height']) && is_numeric($params['height'])) ? $params['height'] : null;
if (is_null($width) || is_null($height)) {
throw new Exception('Wrong thumbnail width or height');
}
$this->image = $this->image->thumbnail(new Box($width, $height), $mode);
} | php | {
"resource": ""
} |
q9781 | Dashlet.getDashletFields | train | public function getDashletFields()
{
/**
* if you want to use jQuery color picker instead of HTML5
* <input type='color' />, uncomment out the lined which add
* the extra class, and comment out the lines which are setting
* the attribute to type => color
*/
$extraClasses = MultiValueTextField::create('ExtraClasses');
$fields = new FieldList(new TextField('Title', _t('Dashlet.TITLE', 'Title')), $extraClasses);
$this->extend('updateDashletFields', $fields);
return $fields;
} | php | {
"resource": ""
} |
q9782 | Dashlet.canCreate | train | public function canCreate($member=null)
{
if (!$member) {
$member = singleton('SecurityContext')->getMember();
}
if ($member) {
// check dashboard controller's allowed_dashlets
$allowed = Config::inst()->get('DashboardController', 'allowed_dashlets');
if (in_array(get_class($this), $allowed)) {
return true;
}
$config = SiteConfig::current_site_config();
$required = $this->requiredPermission();
if ($config->hasMethod('checkPerm') && $config->checkPerm($required)) {
return true;
}
}
return parent::canCreate($member);
} | php | {
"resource": ""
} |
q9783 | Dashlet_Controller.save | train | public function save()
{
if ($this->widget && $this->widget->OwnerID && $this->widget->OwnerID != Member::currentUserID()) {
// check ownership, not just write access
return;
}
//Note : Gridster uses weird names... size_x? Why just not width, Argh...
// Admittedly, col and row makes sense since it's essentially
// using cells to align up objects.
$obj = self::get()->byID($this->request->param('ID'));
$obj->PosX = $this->request->postVar('col');
$obj->PosY = $this->request->postVar('row');
$obj->Width = $this->request->postVar('size_x');
$obj->Height = $this->request->postVar('size_y');
// only allow the owner access to write.
$obj->write();
} | php | {
"resource": ""
} |
q9784 | DashboardController.updateDashboard | train | public function updateDashboard()
{
$dashboardId = (int) $this->request->postVar('dashboard');
$items = (array) $this->request->postVar('order');
if ($dashboardId) {
$dashboard = $this->dataService->memberDashboardById($dashboardId);
if ($dashboard && $dashboard->exists()) {
$dashboard->Widgets()->removeAll();
if (is_array($items)) {
foreach ($items as $i => $widgetId) {
$widget = $this->dataService->dashletById($widgetId);
if ($widget) {
$widget->ParentID = $dashboard->ID;
$widget->Sort = $i+1; // need +1 here so there's no 0 sort val, otherwise onbeforewrite sets it automatically.
$widget->write();
}
}
}
}
}
} | php | {
"resource": ""
} |
q9785 | DashboardController.getRecord | train | protected function getRecord()
{
$id = (int) $this->request->param('ID');
if (!$id) {
$id = (int) $this->request->requestVar('ID');
}
if ($id) {
$type = $this->stat('model_class');
$action = $this->request->param('Action');
if ($action == 'dashlet' || $action == 'widget') {
$type = 'Dashlet';
}
$item = $this->dataService->byId($type, $id);
if ($item instanceof DashboardPage) {
$item->setController($this);
}
return $item;
}
} | php | {
"resource": ""
} |
q9786 | TableUtilitiesTrait.updateField | train | public function updateField($primaryKey, $field, $value = null): bool
{
$query = $this->query()
->update()
->set([
$field => $value,
])
->where([
$this->primaryKey() => $primaryKey,
]);
$statement = $query->execute();
$success = $statement->rowCount() > 0;
$statement->closeCursor();
return $success;
} | php | {
"resource": ""
} |
q9787 | SuperBackupService.index | train | public function index($params = [], $optParams = [])
{
if ($optParams instanceof IndexParams) {
$optParams = $optParams->toArray(true);
}
return $this->sendRequest([], [
'restAction' => 'index',
'params' => $params,
'getParams' => $optParams,
], function ($response) {
$backups = [];
if (isset($response->data['items'])) {
foreach ($response->data['items'] as $superbackup) {
$backups[] = new SuperBackup($superbackup);
}
}
return new Index([
'models' => $backups,
'nextPageToken' => $response->data['nextPageToken'],
]);
});
} | php | {
"resource": ""
} |
q9788 | SuperBackupService.create | train | public function create($params, $optParams = [])
{
if (!$params instanceof SuperBackup) {
throw new InvalidParamException(SuperBackup::class.' is required!');
}
if(!isset($optParams['cloud'])){
$optParams['cloud'] = [];
}
$optParams['cloud']['id'] = $params->cloud->id;
return $this->sendRequest([], [
'restAction' => 'create',
'uri' => '/c/<cloud.id>',
'postParams' => $params->toArray(),
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new SuperBackup($response->data) : $response;
});
} | php | {
"resource": ""
} |
q9789 | SuperBackupService.update | train | public function update($params, $optParams = [])
{
if (!$params instanceof SuperBackup) {
throw new InvalidParamException(SuperBackup::class.' is required!');
}
if(!isset($optParams['cloud'])){
$optParams['cloud'] = [];
}
if ($params->task && is_string($params->task->type)) {
$params->task = $params->task->type;
}
$optParams['cloud']['id'] = $params->cloud->id;
return $this->sendRequest([], [
'restAction' => 'update',
'uri' => '/c/<cloud.id>',
'restId' => $params->id,
'postParams' => $params->toArray(),
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new SuperBackup($response->data) : $response;
});
} | php | {
"resource": ""
} |
q9790 | SuperBackupService.delete | train | public function delete($params, $optParams = [])
{
if ($params instanceof SuperBackup) {
$params = $params->id;
}
if(!isset($optParams['cloud'])){
$optParams['cloud'] = [];
}
$optParams['cloud']['id'] = $params;
return $this->sendRequest([], [
'restAction' => 'delete',
'uri' => '/c/<cloud.id>',
'restId' => $params,
'getParams' => $optParams,
], function ($response) {
return $response->success;
});
} | php | {
"resource": ""
} |
q9791 | SuperBackupService.view | train | public function view($params, $optParams = [])
{
if ($params instanceof SuperBackup) {
$params = $params->id;
}
if(!isset($optParams['cloud'])){
$optParams['cloud'] = [];
}
$optParams['cloud']['id'] = $params;
return $this->sendRequest([], [
'restAction' => 'view',
'uri' => '/c/<cloud.id>',
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new SuperBackup($response->data) : $response;
});
} | php | {
"resource": ""
} |
q9792 | Views.render | train | public static function render($view, array $context = [], $type = null)
{
$viewBuilder = static::getViewBuilder();
$viewObject = $viewBuilder->create($view, $type);
return $viewObject->render($context);
} | php | {
"resource": ""
} |
q9793 | CssProperties.flat | train | public function flat(array $properties): string
{
Assert::isMap($properties);
return $this->arrayImploder->byGlue($properties, ';', ':');
} | php | {
"resource": ""
} |
q9794 | Client.send | train | public function send($data, array $registrationIds = [], array $options = [])
{
$this->responses = [];
$data = array_merge($options, [
'data' => $data,
]);
if (isset($options['to'])) {
$this->responses[] = $this->browser->post($this->apiUrl, $this->getHeaders(), json_encode($data));
} elseif (count($registrationIds) > 0) {
// Chunk number of registration ID's according to the maximum allowed by GCM
$chunks = array_chunk($registrationIds, $this->registrationIdMaxCount);
// Perform the calls (in parallel)
foreach ($chunks as $registrationIds) {
$data['registration_ids'] = $registrationIds;
$this->responses[] = $this->browser->post($this->apiUrl, $this->getHeaders(), json_encode($data));
}
}
$this->client->flush();
foreach ($this->responses as $response) {
$message = json_decode($response->getContent());
if ($message === null || $message->success == 0 || $message->failure > 0) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q9795 | Client.sendTo | train | public function sendTo($data, $topic = '/topics/global', array $options = [])
{
$options['to'] = $topic;
return $this->send($data, [], $options);
} | php | {
"resource": ""
} |
q9796 | AbstractField.configure | train | public function configure(array $properties)
{
foreach ($properties as $name => $value) {
$methodName = 'set' . ucfirst(strtolower($name));
if (method_exists($this, $methodName)) {
$this->$methodName($value);
}
}
} | php | {
"resource": ""
} |
q9797 | AbstractField.validate | train | public function validate($value)
{
$assert = $this->getAssert();
if ($assert !== null) {
if (is_callable($assert)) {
if (!call_user_func($assert, $value, $this)) {
throw new AssertException(
sprintf('Custom validation fail with value (%s) "%s"', gettype($value), print_r($value, true))
);
}
} else {
if ($value !== $assert) {
throw new AssertException(
sprintf(
'Failed asserting that actual value (%s) "%s" matches expected value (%s) "%s".',
gettype($value),
print_r($value, true),
gettype($assert),
print_r($assert, true)
)
);
}
}
}
return true;
} | php | {
"resource": ""
} |
q9798 | AbstractField.resolveProperty | train | protected function resolveProperty($name)
{
$value = $this->$name;
if (is_callable($value)) {
return call_user_func($value, $this);
}
return $this->resolveValue($value);
} | php | {
"resource": ""
} |
q9799 | AbstractField.resolveValue | train | private function resolveValue($value)
{
if (DataSet::isPath($value)) {
if (empty($this->dataSet)) {
throw new ConfigurationException('DataSet is required to resole value by path.');
}
$value = $this->dataSet->resolvePath($value);
}
if (is_array($value)) {
foreach ($value as $key => $subValue) {
$value[$key] = $this->resolveValue($subValue);
}
}
return $value;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.