_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9600 | RouteServiceProvider.adminController | train | protected function adminController($route = null)
{
if ($route) {
return $this->namespace.'\\'.$this->compatibilityVersion.'\AdminController@'.$route;
}
return $this->namespace.'\\'.$this->compatibilityVersion.'\AdminController';
} | php | {
"resource": ""
} |
q9601 | CsvAction.run | train | public function run()
{
$this->controller->getSearchCriteria();
$this->controller->dataProvider->pagination = false;
$query = $this->controller->dataProvider->query;
$config = new ExporterConfig();
$exporter = new Exporter($config);
$result = $query->asArray()->all();
$fields = $this->fields;
$values = array_map(function ($ar) use ($fields) {
//$values = array_map(function () use ($fields) {
$return = [];
foreach($fields as $field) {
$keyString = "['" . str_replace('.', "']['", $field) . "']";
eval("\$return[] = \$ar".$keyString.";");
}
return $return;
}, $result);
if(isset($_GET['test'])) {
return json_encode(array_merge([$this->fields], $values));
} else {
$this->setHttpHeaders('csv', $this->controller->getCompatibilityId(), 'text/plain');
$exporter->export('php://output', array_merge([$this->fields], $values));
}
} | php | {
"resource": ""
} |
q9602 | CsvAction.setHttpHeaders | train | protected function setHttpHeaders($type, $name, $mime, $encoding = 'utf-8')
{
Yii::$app->response->format = Response::FORMAT_RAW;
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE") == false) {
header("Cache-Control: no-cache");
header("Pragma: no-cache");
} else {
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
}
header("Expires: Sat, 26 Jul 1979 05:00:00 GMT");
header("Content-Encoding: {$encoding}");
header("Content-Type: {$mime}; charset={$encoding}");
header("Content-Disposition: attachment; filename={$name}.{$type}");
header("Cache-Control: max-age=0");
} | php | {
"resource": ""
} |
q9603 | ResourceProvider.getResource | train | public function getResource($resourceId)
{
if (isset($this->resources[$resourceId])) {
return $this->resources[$resourceId];
}
$dynamicResource = $this->dynamicResourceMapper($resourceId);
if (!empty($dynamicResource)) {
return $dynamicResource;
}
return null;
} | php | {
"resource": ""
} |
q9604 | ResourceProvider.dynamicResourceMapper | train | protected function dynamicResourceMapper($resourceId)
{
// Page Resource Mapper
$resource = $this->pageResourceMapper($resourceId);
if (!empty($resource)) {
return $resource;
}
$resource = $this->siteResourceMapper($resourceId);
if (!empty($resource)) {
return $resource;
}
return null;
} | php | {
"resource": ""
} |
q9605 | ResourceProvider.pageResourceMapper | train | protected function pageResourceMapper($resourceId)
{
if (!$this->resourceName->isPagesResourceId($resourceId)) {
return null;
}
$resources = explode('.', $resourceId);
if (empty($resources[1])) {
return null;
}
$siteResourceId = $this->resourceName->get(self::RESOURCE_SITES, $resources[1]);
$return = [
'resourceId' => $resourceId,
'parentResourceId' => $siteResourceId,
];
if ($this->resourceName->isPageResourceId($resourceId)) {
$pagesResourceId = $this->resourceName->get(self::RESOURCE_SITES, $resources[1], self::RESOURCE_PAGES);
$return['parentResourceId'] = $pagesResourceId;
}
return array_merge(
$this->resources[self::RESOURCE_PAGES],
$return
);
} | php | {
"resource": ""
} |
q9606 | ResourceProvider.siteResourceMapper | train | protected function siteResourceMapper($resourceId)
{
if (!$this->resourceName->isSitesResourceId($resourceId)) {
return null;
}
$sitesResourceId = $this->resourceName->get(self::RESOURCE_SITES);
$return = [
'resourceId' => $resourceId,
'parentResourceId' => $sitesResourceId,
];
return array_merge(
$this->resources[self::RESOURCE_SITES],
$return
);
} | php | {
"resource": ""
} |
q9607 | ResourceProvider.getSiteResources | train | protected function getSiteResources(Site $site)
{
$primaryDomain = $site->getDomain();
if (empty($primaryDomain)) {
// no resources if domain missing
return array();
}
$primaryDomainName = $primaryDomain->getDomainName();
$siteId = $site->getSiteId();
$sitesResourceId = $this->resourceName->get(self::RESOURCE_SITES);
$siteResourceId = $this->resourceName->get(self::RESOURCE_SITES, $siteId);
$return[$siteResourceId] = [
'resourceId' => $siteResourceId,
'parentResourceId' => $sitesResourceId,
'name' => $primaryDomainName,
'description' => "Resource for site '{$primaryDomainName}'"
];
$return[$siteResourceId] = array_merge(
$this->resources[$sitesResourceId],
$return[$siteResourceId]
);
$pagesResourceId = $this->resourceName->get(self::RESOURCE_SITES, $siteId, self::RESOURCE_PAGES);
$return[$pagesResourceId] = [
'resourceId' => $pagesResourceId,
'parentResourceId' => $siteResourceId,
'name' => $primaryDomainName . ' - pages',
'description' => "Resource for pages on site '{$primaryDomainName}'"
];
$return[$pagesResourceId] = array_merge(
$this->resources[self::RESOURCE_PAGES],
$return[$pagesResourceId]
);
$pages = $site->getPages();
/** @var \Rcm\Entity\Page $page */
foreach ($pages as &$page) {
$pageResources = $this->getPageResources($page, $site);
$return = array_merge($pageResources, $return);
}
return $return;
} | php | {
"resource": ""
} |
q9608 | ResourceProvider.getPageResources | train | protected function getPageResources(Page $page, Site $site)
{
$primaryDomainName = $site->getDomain()->getDomainName();
$siteId = $site->getSiteId();
$pageName = $page->getName();
$pageType = $page->getPageType();
$pagesResourceId = $this->resourceName->get(self::RESOURCE_SITES, $siteId, self::RESOURCE_PAGES);
$pageResourceId = $this->resourceName->get(
self::RESOURCE_SITES,
$siteId,
self::RESOURCE_PAGES,
$pageType,
$pageName
);
$return[$pageResourceId] = [
'resourceId' => $pageResourceId,
'parentResourceId' => $pagesResourceId,
'name' => $primaryDomainName . ' - pages - ' . $pageName,
'description' => "Resource for page '{$pageName}'" . " of type '{$pageType}' on site '{$primaryDomainName}'"
];
$return[$pageResourceId] = array_merge(
$this->resources[self::RESOURCE_PAGES],
$return[$pageResourceId]
);
return $return;
} | php | {
"resource": ""
} |
q9609 | ForkableLibEventLoop.subscribeStreamEvent | train | private function subscribeStreamEvent($stream, $flag)
{
$key = (int) $stream;
if (isset($this->streamEvents[$key])) {
$event = $this->streamEvents[$key];
$flags = $this->streamFlags[$key] |= $flag;
event_del($event);
event_set($event, $stream, EV_PERSIST | $flags, $this->streamCallback);
} else {
$event = event_new();
event_set($event, $stream, EV_PERSIST | $flag, $this->streamCallback);
event_base_set($event, $this->eventBase);
$this->streamEvents[$key] = $event;
$this->streamFlags[$key] = $flag;
}
event_add($event);
} | php | {
"resource": ""
} |
q9610 | ForkableLibEventLoop.unsubscribeStreamEvent | train | private function unsubscribeStreamEvent($stream, $flag)
{
$key = (int) $stream;
$flags = $this->streamFlags[$key] &= ~$flag;
if (0 === $flags) {
$this->removeStream($stream);
return;
}
$event = $this->streamEvents[$key];
event_del($event);
event_set($event, $stream, EV_PERSIST | $flags, $this->streamCallback);
event_add($event);
} | php | {
"resource": ""
} |
q9611 | ForkableLibEventLoop.afterForkChild | train | public function afterForkChild()
{
//possible event base free?
unset($this->eventBase);
unset($this->nextTickQueue);
unset($this->futureTickQueue);
//bugfix lambda function destructed while executing -.-
//unset($this->timerCallback);
//unset($this->streamCallback);
unset($this->timerEvents);
unset($this->running);
$this->streamEvents = array();
$this->streamFlags = array();
$this->readListeners = array();
$this->writeListeners = array();
//call constructor
$this->__construct();
return $this;
} | php | {
"resource": ""
} |
q9612 | Categoryable.getCategoryAttribute | train | public function getCategoryAttribute()
{
if(is_null($category = $this->categories->last())) {
$category = new \stdClass();
$category->title = 'No name';
$category->slug = 'none';
$category->alt_url = null;
$category->template = null;
}
return $category;
} | php | {
"resource": ""
} |
q9613 | DisplayErrors.renderErrors | train | public function renderErrors($errors)
{
if (empty($errors)) {
return null;
}
$message = '';
foreach ($errors as &$error) {
foreach ($error as $errorCode => &$errorMsg) {
$message .= $this->errorMapper($errorCode, $errorMsg);
}
}
return $message;
} | php | {
"resource": ""
} |
q9614 | HomeController.index | train | public function index()
{
pageinfo([
'title' => setting('system.meta_title', 'BixBite'),
'description' => setting('system.meta_description', 'BixBite - Content Management System'),
'keywords' => setting('system.meta_keywords', 'BixBite CMS, BBCMS, CMS'),
'onHomePage' => true,
]);
if (! setting('themes.home_page_personalized', false)) {
return app('\BBCMS\Http\Controllers\ArticlesController')->index();
}
return $this->makeResponse('index');
} | php | {
"resource": ""
} |
q9615 | Database.buildFromConfiguration | train | public static function buildFromConfiguration(): Database
{
if (!is_null(self::$sharedInstance)) {
return self::$sharedInstance;
}
$config = Configuration::getDatabaseConfiguration();
$instance = self::initializeFromConfiguration($config);
if ($config['shared'] ?? false) {
self::$sharedInstance = $instance;
}
return $instance;
} | php | {
"resource": ""
} |
q9616 | NavigationTreeHelper.activeNodes | train | protected static function activeNodes(Request $request, array $nodes = [], $level = 0) {
$result = false;
foreach ($nodes as $n) {
if (false === ($n instanceof AbstractNavigationNode)) {
continue;
}
if (true === self::nodeMatch($n, $request)) {
$current = true;
} else {
$current = self::activeNodes($request, $n->getNodes(), $level + 1);
}
if (false === $current) {
continue;
}
$n->setActive(true);
$result = true;
}
return $result;
} | php | {
"resource": ""
} |
q9617 | NavigationTreeHelper.activeTree | train | public static function activeTree(NavigationTree $tree, Request $request) {
self::activeNodes($request, $tree->getNodes());
} | php | {
"resource": ""
} |
q9618 | NavigationTreeHelper.getBreadcrumbs | train | public static function getBreadcrumbs(AbstractNavigationNode $node) {
$breadcrumbs = [];
if (true === ($node instanceof NavigationNode || $node instanceof BreadcrumbNode) && true === $node->getActive()) {
$breadcrumbs[] = $node;
}
foreach ($node->getNodes() as $current) {
if (false === ($current instanceof AbstractNavigationNode)) {
continue;
}
$breadcrumbs = array_merge($breadcrumbs, self::getBreadcrumbs($current));
}
return $breadcrumbs;
} | php | {
"resource": ""
} |
q9619 | NavigationTreeHelper.nodeMatch | train | protected static function nodeMatch(AbstractNavigationNode $node, Request $request) {
$result = false;
switch ($node->getMatcher()) {
case NavigationInterface::NAVIGATION_MATCHER_REGEXP:
$result = preg_match("/" . $node->getUri() . "/", $request->getUri());
break;
case NavigationInterface::NAVIGATION_MATCHER_ROUTER:
$result = $request->get("_route") === $node->getUri();
break;
case NavigationInterface::NAVIGATION_MATCHER_URL:
$result = $request->getUri() === $node->getUri() || $request->getRequestUri() === $node->getUri();
break;
}
return boolval($result);
} | php | {
"resource": ""
} |
q9620 | CronType.buildForm | train | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('expression', TextType::class, [
'required' => true,
'constraints' => [new ExpressionConstraint()],
])
->add('arguments', TextType::class, [
'required' => false,
'constraints' => [new ArgumentsConstraint()],
])
->add('priority', IntegerType::class, [
'required' => true,
])
->add('enabled', CheckboxType::class, [
'required' => false,
])
->add('update', SubmitType::class, [
'label' => /** @Desc("Update") */
'cron_update_form.update',
]);
} | php | {
"resource": ""
} |
q9621 | UrlHelper.protocolHostPort | train | public static function protocolHostPort()
{
if (RequestHelper::isCli()) {
return null;
}
$isHttps = RequestHelper::isHttps();
$protocol = 'http' . ($isHttps ? 's' : '');
$serverName = $_SERVER['SERVER_NAME'];
$serverPort = (int)$_SERVER['SERVER_PORT'];
$protocolHostPort = $protocol . '://';
if ((!$isHttps && $serverPort !== 80) || ($isHttps && $serverPort !== 443)) {
$protocolHostPort .= $serverName . ':' . $serverPort;
} else {
$protocolHostPort .= $serverName;
}
return $protocolHostPort;
} | php | {
"resource": ""
} |
q9622 | UrlHelper.query | train | public static function query(array $parameters = null, bool $mergeGetVariables = true)
{
if ($mergeGetVariables) {
if ($parameters === null) {
$parameters = $_GET;
} else {
$parameters = array_replace_recursive($_GET, $parameters);
}
}
if (empty($parameters)) {
return null;
}
$query = http_build_query($parameters, '', '&');
return ($query === '') ? '' : ('?' . $query);
} | php | {
"resource": ""
} |
q9623 | BaseController.makeResponse | train | protected function makeResponse(string $template, array $vars = [])
{
if (request()->ajax()) {
return $this->jsonOutput($vars);
}
return $this->renderOutput($template, $vars);
} | php | {
"resource": ""
} |
q9624 | JQueryInputMaskTwigExtension.jQueryInputMaskPhoneNumberFunction | train | public function jQueryInputMaskPhoneNumberFunction(array $args = []) {
$defaultMask = "99 99 99 99 99";
return $this->jQueryInputMask(ArrayHelper::get($args, "selector"), $defaultMask, $this->prepareOptions($args, $defaultMask), ArrayHelper::get($args, "scriptTag", false));
} | php | {
"resource": ""
} |
q9625 | JQueryInputMaskTwigExtension.jQueryInputMaskTime12Function | train | public function jQueryInputMaskTime12Function(array $args = []) {
$defaultMask = "hh:mm t";
return $this->jQueryInputMask(ArrayHelper::get($args, "selector"), $defaultMask, array_merge($this->prepareOptions($args, null), ["hourFormat" => "12", "placeholder" => "__:__ _m"]), ArrayHelper::get($args, "scriptTag", false));
} | php | {
"resource": ""
} |
q9626 | EventWrapper.viewResponseEvent | train | public function viewResponseEvent(ViewEvent $event)
{
/** @var \Rcm\EventListener\ViewEventListener $viewEventListener */
$viewEventListener
= $this->serviceLocator->get(\Rcm\EventListener\ViewEventListener::class);
$return = $viewEventListener->processRcmResponses($event);
if (!empty($return)) {
return $return;
}
return null;
} | php | {
"resource": ""
} |
q9627 | NoteController.actionSave | train | public function actionSave()
{
$post = Yii::$app->request->post();
$id = $post['Note']['id'];
if($id) {
$model = Note::findOne($id);
} else {
$model = new Note;
}
Yii::$app->response->format = 'json';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return ['success' => true];
} else {
return ['success' => false, 'errors' => $model->getErrors()];
}
} | php | {
"resource": ""
} |
q9628 | DependencyManager.init_handlers | train | protected function init_handlers() {
$keys = [ self::KEY_SCRIPTS, self::KEY_STYLES ];
foreach ( $keys as $key ) {
if ( $this->hasConfigKey( $key ) ) {
$this->add_handler( $key );
}
}
} | php | {
"resource": ""
} |
q9629 | DependencyManager.add_handler | train | protected function add_handler( $dependency ) {
if ( $this->hasConfigKey( $dependency ) ) {
$handler = $this->hasConfigKey( self::KEY_HANDLERS, $dependency )
? $this->getConfigKey( self::KEY_HANDLERS, $dependency )
: $this->get_default_handler( $dependency );
if ( $handler ) {
$this->handlers[ $dependency ] = new $handler;
}
}
} | php | {
"resource": ""
} |
q9630 | DependencyManager.get_default_handler | train | protected function get_default_handler( $dependency ) {
switch ( $dependency ) {
case self::KEY_STYLES:
return self::DEFAULT_STYLE_HANDLER;
case self::KEY_SCRIPTS:
return self::DEFAULT_SCRIPT_HANDLER;
default:
return null;
}
} | php | {
"resource": ""
} |
q9631 | DependencyManager.init_dependencies | train | protected function init_dependencies() {
array_walk( $this->handlers,
function ( $handler, $dependency_type ) {
if ( $this->hasConfigKey( $dependency_type ) ) {
$this->dependencies[ $dependency_type ] = $this->init_dependency_type( $dependency_type );
}
} );
} | php | {
"resource": ""
} |
q9632 | DependencyManager.init_dependency_type | train | protected function init_dependency_type( $type ) {
$array = [ ];
$data = $this->getConfigKey( $type );
foreach ( $data as $dependency ) {
$handle = array_key_exists( 'handle',
$dependency ) ? $dependency['handle'] : '';
$array[ $handle ] = $dependency;
}
return $array;
} | php | {
"resource": ""
} |
q9633 | DependencyManager.register | train | public function register( $context = null ) {
$context = $this->validate_context( $context );
array_walk( $this->dependencies,
[ $this, 'register_dependency_type' ], $context );
} | php | {
"resource": ""
} |
q9634 | DependencyManager.enqueue | train | public function enqueue( $context = null ) {
$context = $this->validate_context( $context );
array_walk( $this->dependencies,
[ $this, 'enqueue_dependency_type' ], $context );
} | php | {
"resource": ""
} |
q9635 | DependencyManager.enqueue_handle | train | public function enqueue_handle( $handle, $context = null, $fallback = false ) {
if ( ! $this->enqueue_internal_handle( $handle, $context ) ) {
return $this->enqueue_fallback_handle( $handle );
}
return true;
} | php | {
"resource": ""
} |
q9636 | DependencyManager.enqueue_internal_handle | train | protected function enqueue_internal_handle( $handle, $context = null ) {
list( $dependency_type, $dependency ) = $this->get_dependency_array( $handle );
$context['dependency_type'] = $dependency_type;
if ( ! $dependency ) {
return false;
}
$this->enqueue_dependency(
$dependency,
$handle,
$context
);
$this->maybe_localize( $dependency, $context );
$this->maybe_add_inline_script( $dependency, $context );
return true;
} | php | {
"resource": ""
} |
q9637 | DependencyManager.get_dependency_array | train | protected function get_dependency_array( $handle ) {
foreach ( $this->dependencies as $type => $dependencies ) {
if ( array_key_exists( $handle, $dependencies ) ) {
return [ $type, $dependencies[ $handle ] ];
}
}
// Handle not found, return an empty array.
return [ '', null ];
} | php | {
"resource": ""
} |
q9638 | DependencyManager.enqueue_dependency | train | protected function enqueue_dependency( $dependency, $dependency_key, $context = null ) {
if ( ! $this->is_needed( $dependency, $context ) ) {
return;
}
$handler = $this->handlers[ $context['dependency_type'] ];
$handler->enqueue( $dependency );
} | php | {
"resource": ""
} |
q9639 | DependencyManager.is_needed | train | protected function is_needed( $dependency, $context ) {
$is_needed = array_key_exists( 'is_needed', $dependency )
? $dependency['is_needed']
: null;
if ( null === $is_needed ) {
return true;
}
return is_callable( $is_needed ) && $is_needed( $context );
} | php | {
"resource": ""
} |
q9640 | DependencyManager.maybe_localize | train | protected function maybe_localize( $dependency, $context ) {
if ( ! array_key_exists( 'localize', $dependency ) ) {
return;
}
$localize = $dependency['localize'];
$data = $localize['data'];
if ( is_callable( $data ) ) {
$data = $data( $context );
}
wp_localize_script( $dependency['handle'], $localize['name'], $data );
} | php | {
"resource": ""
} |
q9641 | DependencyManager.maybe_add_inline_script | train | protected function maybe_add_inline_script( $dependency, $context ) {
if ( ! array_key_exists( 'add_inline', $dependency ) ) {
return;
}
$inline_script = $dependency['add_inline'];
if ( is_callable( $inline_script ) ) {
$inline_script = $inline_script( $context );
}
wp_add_inline_script( $dependency['handle'], $inline_script );
} | php | {
"resource": ""
} |
q9642 | DependencyManager.enqueue_fallback_handle | train | protected function enqueue_fallback_handle( $handle ) {
$result = false;
foreach ( $this->handlers as $handler ) {
$result = $result || $handler->maybe_enqueue( $handle );
}
return $result;
} | php | {
"resource": ""
} |
q9643 | DependencyManager.enqueue_dependency_type | train | protected function enqueue_dependency_type( $dependencies, $dependency_type, $context = null ) {
$context['dependency_type'] = $dependency_type;
array_walk( $dependencies, [ $this, 'enqueue_dependency' ], $context );
} | php | {
"resource": ""
} |
q9644 | DependencyManager.register_dependency_type | train | protected function register_dependency_type( $dependencies, $dependency_type, $context = null ) {
$context['dependency_type'] = $dependency_type;
array_walk( $dependencies, [ $this, 'register_dependency' ], $context );
} | php | {
"resource": ""
} |
q9645 | DependencyManager.register_dependency | train | protected function register_dependency( $dependency, $dependency_key, $context = null ) {
$handler = $this->handlers[ $context['dependency_type'] ];
$handler->register( $dependency );
if ( $this->enqueue_immediately ) {
$this->register_enqueue_hooks( $dependency, $context );
}
} | php | {
"resource": ""
} |
q9646 | DependencyManager.register_enqueue_hooks | train | protected function register_enqueue_hooks( $dependency, $context = null ) {
$priority = $this->get_priority( $dependency );
foreach ( [ 'wp_enqueue_scripts', 'admin_enqueue_scripts' ] as $hook ) {
add_action( $hook, [ $this, 'enqueue' ], $priority, 1 );
}
$this->maybe_localize( $dependency, $context );
$this->maybe_add_inline_script( $dependency, $context );
} | php | {
"resource": ""
} |
q9647 | DataDiscovery.updateElasticMappings | train | public function updateElasticMappings($mappings)
{
$mappings['BoostTerms'] = ['type' => 'keyword'];
$mappings['Categories'] = ['type' => 'keyword'];
$mappings['Keywords'] = ['type' => 'text'];
$mappings['Tags'] = ['type' => 'keyword'];
if ($this->owner instanceof \SiteTree) {
// store the SS_URL for consistency
$mappings['SS_URL'] = ['type' => 'text'];
}
} | php | {
"resource": ""
} |
q9648 | FormSerializer.createFormErrorArray | train | public function createFormErrorArray(Form $data)
{
$form = [];
$errors = [];
foreach ($data->getErrors() as $error) {
$errors[] = $this->getErrorMessage($error);
}
if ($errors) {
$form['errors'] = $errors;
}
$children = [];
foreach ($data->all() as $child) {
if ($child instanceof Form) {
$children[$child->getName()] = $this->createFormErrorArray($child);
}
}
if ($children) {
$form['children'] = $children;
}
return $form;
} | php | {
"resource": ""
} |
q9649 | Controller.ssePolling | train | protected function ssePolling($data, $eventId = 'stream', $retry = 1000): Response
{
return ResponseFactory::getInstance()->buildPollingSse($data, $eventId, $retry);
} | php | {
"resource": ""
} |
q9650 | Controller.sseStreaming | train | protected function sseStreaming($callback, $eventId = 'stream', $sleep = 1): Response
{
return ResponseFactory::getInstance()->buildStreamingSse($callback, $eventId, $sleep);
} | php | {
"resource": ""
} |
q9651 | AbstractMaterialDesignColorPaletteTwigExtension.materialDesignColorPalette | train | protected function materialDesignColorPalette($type, $name, $value) {
$color = $this->getColors()[0];
foreach ($this->getColors() as $current) {
if ($name !== $current->getName()) {
continue;
}
$color = $current;
}
$html = [];
$html[] = "mdc";
$html[] = $type;
$html[] = $color->getName();
if (null !== $value && true === array_key_exists($value, $color->getColors())) {
$html[] = $value;
}
return implode("-", $html);
} | php | {
"resource": ""
} |
q9652 | TagsBehavior.getTags | train | public function getTags() {
return implode(",", array_keys(ArrayHelper::map($this->owner->getModelTags()->asArray()->all(), 'name', 'name')));
} | php | {
"resource": ""
} |
q9653 | TagsBehavior.tagsRelationTable | train | public function tagsRelationTable() {
$model_name = $this->owner->formName();
if($model_name > 'Tag') {
$relationship_table = 'Tag_' . $model_name;
} else {
$relationship_table = $model_name . '_Tag';
}
return $relationship_table;
} | php | {
"resource": ""
} |
q9654 | TransactionPDO.beginTransaction | train | public function beginTransaction()
{
if ($this->currentTransactionLevel == 0 || !$this->nestable()) {
parent::beginTransaction();
} else {
$this->exec("SAVEPOINT LEVEL{$this->currentTransactionLevel}");
}
++$this->currentTransactionLevel;
return true;
} | php | {
"resource": ""
} |
q9655 | TransactionPDO.commit | train | public function commit()
{
--$this->currentTransactionLevel;
if ($this->currentTransactionLevel == 0 || !$this->nestable()) {
parent::commit();
} else {
$this->exec("RELEASE SAVEPOINT LEVEL{$this->currentTransactionLevel}");
}
} | php | {
"resource": ""
} |
q9656 | TransactionPDO.rollBack | train | public function rollBack()
{
--$this->currentTransactionLevel;
if ($this->currentTransactionLevel == 0 || !$this->nestable()) {
parent::rollBack();
} else {
$this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->currentTransactionLevel}");
}
} | php | {
"resource": ""
} |
q9657 | Site.getSiteInfo | train | public function getSiteInfo($siteId)
{
/** @var \Doctrine\ORM\QueryBuilder $queryBuilder */
$queryBuilder = $this->_em->createQueryBuilder();
$queryBuilder->select(
'partial site.{
owner,
theme,
status,
favIcon,
loginPage,
notAuthorizedPage,
siteLayout,
siteTitle,
siteId
},
language,
country'
)->from(\Rcm\Entity\Site::class, 'site')
->join('site.country', 'country')
->join('site.language', 'language')
->where('site.siteId = :siteId')
->setParameter('siteId', $siteId);
try {
return $queryBuilder->getQuery()->getSingleResult(
Query::HYDRATE_ARRAY
);
} catch (NoResultException $e) {
return null;
}
} | php | {
"resource": ""
} |
q9658 | Site.getSites | train | public function getSites($mustBeActive = false)
{
$repo = $this->_em
->getRepository(\Rcm\Entity\Site::class);
if ($mustBeActive) {
return $repo->findBy(['status' => \Rcm\Entity\Site::STATUS_ACTIVE]);
} else {
return $repo->findAll();
}
} | php | {
"resource": ""
} |
q9659 | Site.isValidSiteId | train | public function isValidSiteId($siteId, $checkActive = false)
{
if (empty($siteId) || !is_numeric($siteId)) {
return false;
}
if ($checkActive && in_array($siteId, $this->activeSiteIdCache)) {
return true;
}
$queryBuilder = $this->_em->createQueryBuilder();
$queryBuilder->select('site.siteId')
->from(\Rcm\Entity\Site::class, 'site')
->where('site.siteId = :siteId')
->setParameter('siteId', $siteId);
if ($checkActive) {
$queryBuilder->andWhere('site.status = :status');
$queryBuilder->setParameter('status', \Rcm\Entity\Site::STATUS_ACTIVE);
}
$result = $queryBuilder->getQuery()->getScalarResult();
if (!empty($result)) {
if ($checkActive) {
$this->activeSiteIdCache[] = $siteId;
}
return true;
}
return false;
} | php | {
"resource": ""
} |
q9660 | Site.getSiteByDomain | train | public function getSiteByDomain($domain)
{
$queryBuilder = $this->_em->createQueryBuilder();
$queryBuilder->select('domain, site, primaryDomain')
->from(\Rcm\Entity\Domain::class, 'domain')
->leftJoin('domain.site', 'site')
->leftJoin('domain.primaryDomain', 'primaryDomain')
->where('domain.domain = :domainName')
->setParameter('domainName', $domain);
try {
/** @var \Rcm\Entity\Domain $domain */
$domain = $queryBuilder->getQuery()->getSingleResult();
} catch (NoResultException $e) {
return null;
}
if ($domain->getPrimary()) {
$site = $domain->getPrimary()->getSite();
$this->_em->detach($site);
$this->_em->detach($domain);
$site->setDomain($domain);
} else {
$site = $domain->getSite();
}
return $site;
} | php | {
"resource": ""
} |
q9661 | Site.getPrimaryDomain | train | protected function getPrimaryDomain($domain)
{
/** @var \Rcm\Entity\Domain $domain */
$domain = $this->_em->getRepository(\Rcm\Entity\Domain::class)
->findOneBy(['domain' => $domain]);
if (empty($domain)) {
return null;
}
$primary = $domain->getPrimary();
if (!$primary->getPrimary()) {
return $primary;
}
return $this->getPrimaryDomain($primary->getDomainName());
} | php | {
"resource": ""
} |
q9662 | AdminController.getDashboard | train | public function getDashboard()
{
$view = 'admin.dashboard';
if (!view()->exists($view)) {
$view = 'flare::'.$view;
}
return view($view, ['widgets' => (new WidgetAdminManager())]);
} | php | {
"resource": ""
} |
q9663 | FullTextSearch.fullTextWildcards | train | protected function fullTextWildcards($term)
{
// removing symbols used by MySQL
$reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~'];
$term = str_replace($reservedSymbols, '', $term);
$words = explode(' ', $term);
foreach ($words as $key => $word) {
/*
* applying + operator (required word) only big words
* because smaller ones are not indexed by mysql
*/
if (strlen($word) >= 3) {
// $words[$key] = '+' . $word . '*';
$words[$key] = $word.'*';
}
}
$searchTerm = implode(' ', $words);
return $searchTerm;
} | php | {
"resource": ""
} |
q9664 | FullTextSearch.scopeSearch | train | public function scopeSearch($query, $term)
{
$columns = implode(',', $this->searchable);
$query->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)", $this->fullTextWildcards($term));
// $term = $this->fullTextWildcards($term);
//
// $query
// ->selectRaw('MATCH (title, content) AGAINST (? in boolean mode) as REL', [$term])
// ->whereRaw('MATCH (title, content) AGAINST (? in boolean mode)' , $term)
// ->orderBy('REL', 'desc')
// ;
return $query;
} | php | {
"resource": ""
} |
q9665 | RegisterHandlers.process | train | public function process(ContainerBuilder $container)
{
if (!$container->has($this->serviceId)) {
return;
}
$definition = $container->findDefinition($this->serviceId);
$handlers = array();
$this->collectServiceIds(
$container,
$this->tag,
$this->keyAttribute,
function ($key, $serviceId, array $tagAttributes) use (&$handlers) {
if (isset($tagAttributes['method'])) {
$callable = [$serviceId, $tagAttributes['method']];
} else {
$callable = $serviceId;
}
$handlers[ltrim($key, '\\')] = $callable;
}
);
$definition->replaceArgument(0, $handlers);
} | php | {
"resource": ""
} |
q9666 | ThreadConnection.writeAsync | train | public function writeAsync($data)
{
$this->dataBuffer .= $this->buffer->encodeMessage(serialize($data));
if ($this->writeEvent === false)
{
$this->loop->addWriteStream($this->connection, function ($stream, LoopInterface $loop)
{
if (strlen($this->dataBuffer) > 0)
{
$dataWritten = fwrite($stream,$this->dataBuffer);
$this->dataBuffer = substr($this->dataBuffer,$dataWritten);
if(strlen($this->dataBuffer) <= 0)
{
$loop->removeWriteStream($stream);
$this->writeEvent = false;
}
}
});
$this->writeEvent = true;
}
} | php | {
"resource": ""
} |
q9667 | ThreadConnection.readSync | train | public function readSync()
{
$this->ThrowOnConnectionInvalid();
$this->loop->removeReadStream($this->connection);
$this->readToBuffer();
$this->attachReadStream();
} | php | {
"resource": ""
} |
q9668 | ThreadConnection.close | train | public function close()
{
if($this->connection !== null)
{
if ($this->writeEvent) {
$this->loop->removeWriteStream($this->connection);
}
$this->loop->removeReadStream($this->connection);
fclose($this->connection);
$this->emit('close', array($this));
}
$this->connection = null;
} | php | {
"resource": ""
} |
q9669 | ThreadConnection.attachReadStream | train | protected function attachReadStream()
{
$this->ThrowOnConnectionInvalid();
$this->loop->addReadStream($this->connection, function () {
$this->readToBuffer();
});
} | php | {
"resource": ""
} |
q9670 | ThreadConnection.readToBuffer | train | protected function readToBuffer()
{
$this->ThrowOnConnectionInvalid();
$message = stream_socket_recvfrom($this->connection, 1024, 0, $peer);
//$message = fread($conn,1024);
if ($message !== '' && $message !== false) {
$this->buffer->pushData($message);
foreach ($this->buffer->getMessages() as $messageData) {
$messageData = unserialize($messageData);
$this->emit('message', array($this, $messageData));
}
} else {
$this->close();
}
} | php | {
"resource": ""
} |
q9671 | DoctrineMiddleware.setup | train | public function setup()
{
$app = $this->getApplication();
$options = $app->config('doctrine');
if (is_array($options)) {
$this->setOptions($this->options, $options);
}
$proxyDir = $this->getOption('proxy_path');
$cache = DoctrineCacheFactory::configureCache($this->getOption('cache_driver'));
$config = Setup::createConfiguration(!!$app->config('debug'), $proxyDir, $cache);
$config->setNamingStrategy(new UnderscoreNamingStrategy());
$this->setupAnnotationMetadata();
if (!$this->setupMetadataDriver($config)) {
throw new \RuntimeException('No Metadata Driver defined');
}
$config->setAutoGenerateProxyClasses($this->getOption('auto_generate_proxies', true) == true);
$connection = $this->getOption('connection');
$app->container->singleton(
'entityManager',
function () use ($connection, $config) {
return EntityManager::create($connection, $config);
}
);
} | php | {
"resource": ""
} |
q9672 | TokenProvider.loadUserByUsername | train | public function loadUserByUsername($username)
{
if (!$this->authTokenService->isValid($username)) {
throw new UsernameNotFoundException("Invalid Token.");
}
try {
return $this->authTokenService->getUser($username);
} catch (ProgrammerException $ex) {
throw new UsernameNotFoundException($ex->getMessage(), $ex->getCode());
}
} | php | {
"resource": ""
} |
q9673 | AssetsHelper.listAssets | train | protected static function listAssets($directory) {
if (false === is_dir($directory)) {
throw new InvalidArgumentException(sprintf("\"%s\" is not a directory", $directory));
}
$assets = [];
foreach (new DirectoryIterator(realpath($directory)) as $current) {
// Check the filename and his extension.
if (true === in_array($current->getFilename(), [".", ".."]) || 0 === preg_match("/\.zip$/", $current->getFilename())) {
continue;
}
$assets[] = $current->getPathname();
}
sort($assets);
return $assets;
} | php | {
"resource": ""
} |
q9674 | AssetsHelper.unzipAssets | train | public static function unzipAssets($src, $dst) {
if (false === is_dir($dst)) {
throw new InvalidArgumentException(sprintf("\"%s\" is not a directory", $dst));
}
$result = [];
foreach (static::listAssets($src) as $current) {
$zip = new ZipArchive();
if (true === $zip->open($current)) {
$result[$current] = $zip->extractTo(realpath($dst));
$zip->close();
}
}
return $result;
} | php | {
"resource": ""
} |
q9675 | AbstractPluginRestfulController.getInstanceConfig | train | protected function getInstanceConfig($instanceId = 0)
{
/** @var \Rcm\Service\PluginManager $pluginManager */
$pluginManager = $this->getServiceLocator()->get(
'Rcm\Service\PluginManager'
);
$instanceConfig = [];
$pluginName = $this->getRcmPluginName();
if ($instanceId > 0) {
try {
$instanceConfig = $pluginManager->getInstanceConfig($instanceId);
} catch (PluginInstanceNotFoundException $e) {
// ignore error
}
}
if (empty($instanceConfig)) {
$instanceConfig = $pluginManager->getDefaultInstanceConfig(
$pluginName
);
}
return $instanceConfig;
} | php | {
"resource": ""
} |
q9676 | ColorHelper.getMaterialDesignColorPalette | train | public static function getMaterialDesignColorPalette() {
return [
new RedColorProvider(),
new PinkColorProvider(),
new PurpleColorProvider(),
new DeepPurpleColorProvider(),
new IndigoColorProvider(),
new BlueColorProvider(),
new LightBlueColorProvider(),
new CyanColorProvider(),
new TealColorProvider(),
new GreenColorProvider(),
new LightGreenColorProvider(),
new LimeColorProvider(),
new YellowColorProvider(),
new AmberColorProvider(),
new OrangeColorProvider(),
new DeepOrangeColorProvider(),
new BrownColorProvider(),
new GreyColorProvider(),
new BlueGreyColorProvider(),
new BlackColorProvider(),
new WhiteColorProvider(),
];
} | php | {
"resource": ""
} |
q9677 | BaseRestController.serializeFormError | train | public function serializeFormError(FormInterface $form)
{
$errors = $this->formSerializer->createFormErrorArray($form);
$responseModel = new ResponseFormErrorModel($errors);
return new JsonResponse($responseModel->getBody(), Response::HTTP_BAD_REQUEST);
} | php | {
"resource": ""
} |
q9678 | SessionExpiration.isObsolete | train | public function isObsolete()
{
if ($this->refreshNthRequests == 1 || $this->isRefreshNeededByProbability()) {
return true;
}
if (isset($_SESSION['__HANDLER_REQUESTS_BEFORE_REFRESH'])) {
if ($_SESSION['__HANDLER_REQUESTS_BEFORE_REFRESH'] <= 1) {
return true; // @codeCoverageIgnore
}
$_SESSION['__HANDLER_REQUESTS_BEFORE_REFRESH']--;
}
if (isset($_SESSION['__HANDLER_SECONDS_BEFORE_REFRESH'])) {
$timeDifference = time() - $_SESSION['__HANDLER_LAST_ACTIVITY_TIMESTAMP'];
if ($timeDifference >= $_SESSION['__HANDLER_SECONDS_BEFORE_REFRESH']) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q9679 | SessionExpiration.isRefreshNeededByProbability | train | private function isRefreshNeededByProbability()
{
if (is_null($this->refreshProbability)) {
return false;
}
$rand = (float) mt_rand() / (float) mt_getrandmax();
if ($this->refreshProbability == 1.0 || $rand <= $this->refreshProbability) {
return true;
}
return false; // @codeCoverageIgnore
} | php | {
"resource": ""
} |
q9680 | WidgetFactory.make | train | public function make()
{
try {
$args = func_get_args();
$active = $args[1]['active'] ?? true;
// If widget has non active status.
if (! $active) {
return false;
}
$this->widgetName = trim((string) array_shift($args));
$this->widgetParams = (array) array_shift($args);
$this->widget = $this->getWidget();
return $this->getContentFromCache();
} catch (\Exception $e) {
return sprintf(
trans('common.msg.error'), $e->getMessage()
);
}
} | php | {
"resource": ""
} |
q9681 | WidgetFactory.getWidgetPath | train | protected function getWidgetPath()
{
$name = html_clean($this->widgetName);
$name = str_replace(['.', '_'], ' ', $name);
$name = str_replace(' ', '', ucwords($name));
$name = $this->namespace . '\\' . $name . 'Widget';
if (! is_subclass_of($name, WidgetAbstract::class)) {
throw new \Exception(sprintf(
'Widget class `%s` not available!', $name
));
}
return $name;
} | php | {
"resource": ""
} |
q9682 | WidgetFactory.getContent | train | protected function getContent()
{
$widget = (object) $this->widget->execute();
$widget->cache_key = $this->widget->cacheKeys();
return trim(preg_replace('/(\s|\r|\n)+</', '<',
view($this->widget->template(), compact('widget'))->render()
));
// Debug function if App has error:
// `Cannot end a section without first starting one.`
return view($this->widget->template(), compact('widget'));
} | php | {
"resource": ""
} |
q9683 | WidgetFactory.getContentFromCache | train | protected function getContentFromCache()
{
$cache_key = $this->widget->cacheKey();
$cache_time = $this->widget->cacheTime();
// Check the existence of the cache.
if (! cache()->has($cache_key)) {
// If cache is empty and validation is fails.
$this->checkWidgetParams();
// If cache is empty and template file does not exists.
$this->checkWidgetTemplate();
}
return cache()->remember($cache_key, $cache_time, function () {
return $this->getContent();
});
} | php | {
"resource": ""
} |
q9684 | AbstractApi.url | train | protected function url(string $endpoint, ...$replacements): string
{
return $this->client->baseUrl.vsprintf($endpoint, $replacements);
} | php | {
"resource": ""
} |
q9685 | AbstractApi.createOptionsResolver | train | protected function createOptionsResolver(): OptionsResolver
{
$resolver = new OptionsResolver();
$resolver->setDefined('limit')
->setAllowedTypes('limit', 'int')
->setAllowedValues('limit', function ($value) {
return $value > 0;
});
$resolver->setDefined('offset')
->setAllowedTypes('offset', 'string');
return $resolver;
} | php | {
"resource": ""
} |
q9686 | HtmlDomNode.hasClass | train | public static function hasClass($domElement, $className) {
$classAttr = $domElement->class;
$classNames = explode(" ", $classAttr);
return in_array($className, $classNames);
} | php | {
"resource": ""
} |
q9687 | ControllerTrait.serializeSingleObject | train | public function serializeSingleObject(array $data, $type, $statusCode = Response::HTTP_OK)
{
$model = new ResponseModel($data, $type);
return new JsonResponse($model->getBody(), $statusCode);
} | php | {
"resource": ""
} |
q9688 | ControllerTrait.serializeList | train | public function serializeList(PageModel $pageModel, $type, $page, $statusCode = Response::HTTP_OK)
{
$page = new ResponsePageModel($pageModel, $type, $page);
return new JsonResponse($page->getBody(), $statusCode);
} | php | {
"resource": ""
} |
q9689 | TemplatesController.edit | train | public function edit(TemplateRequest $request, $template)
{
try {
$template = $request->template;
$path = theme_path('views').$template;
return response()->json([
'status' => true, 'message' => null,
'file' => [
'content' => \File::get($path),
'size' => formatBytes(\File::size($path)),
'modified' => strftime('%Y-%m-%d %H:%M', \File::lastModified($path))
]
], 200);
} catch (ValidationException $e) {
$message = $e->validator->errors()->first();
return response()->json(['status' => false, 'message' => $message], 200);
} catch (\Exception $e) {
$message = $e->getMessage();
return response()->json(['status' => false, 'message' => $message], 404 );
}
} | php | {
"resource": ""
} |
q9690 | TemplatesController.update | train | public function update(TemplateRequest $request, $template)
{
try {
$template = $request->template;
$path = theme_path('views').$template;
$content = $request->content;
// Notify if file was not changed.
if (\File::exists($path) and \File::get($path) == $content) {
return response()->json([
'status' => false,
'message' => sprintf(__('msg.not_updated'), $template),
], 200);
}
\File::put($path, $content, true);
return response()->json([
'status' => true,
'message' => sprintf(__('msg.updated'), $template),
'file' => [
'size' => formatBytes(\File::size($path)),
'modified' => strftime('%Y-%m-%d %H:%M', \File::lastModified($path))
]
], 200);
} catch (ValidationException $e) {
$message = $e->validator->errors()->first();
return response()->json(['status' => false, 'message' => $message], 200);
} catch (\Exception $e) {
$message = $e->getMessage();
return response()->json(['status' => false, 'message' => $message], 404 );
}
} | php | {
"resource": ""
} |
q9691 | TemplatesController.destroy | train | public function destroy(TemplateRequest $request, $template)
{
$template = $request->template;
$path = theme_path('views').$template;
// Block and notify if file does not exist.
if (! \File::exists($path)) {
return $this->makeRedirect(false, 'admin.templates.index', sprintf(
__('msg.not_exists'), $template
));
}
// Block if file not delete.
if (! \File::delete($path)) {
return $this->makeRedirect(false, 'admin.templates.index', sprintf(
__('msg.not_deleted'), $template
));
}
return $this->makeRedirect(true, 'admin.templates.index', sprintf(
__('msg.deleted'), $template
));
} | php | {
"resource": ""
} |
q9692 | SitePageCreateInputFilter.build | train | protected function build()
{
$factory = $this->getFactory();
foreach ($this->filterConfig as $field => $config) {
$this->add(
$factory->createInput(
$config
)
);
}
} | php | {
"resource": ""
} |
q9693 | FormHelper.checkCollection | train | public function checkCollection($collection, $notification, $redirectURL, $expected = 1) {
if (null === $collection || (false === is_array($collection) && false === ($collection instanceof Countable))) {
throw new InvalidArgumentException("The collection must be a countable");
}
if ($expected <= count($collection)) {
return;
}
$eventName = NotificationEvents::NOTIFICATION_WARNING;
if (null !== $this->getEventDispatcher() && true === $this->getEventDispatcher()->hasListeners($eventName)) {
$notification = NotificationFactory::newWarningNotification($notification);
$event = new NotificationEvent($eventName, $notification);
$this->getEventDispatcher()->dispatch($eventName, $event);
}
throw new RedirectResponseException($redirectURL, null);
} | php | {
"resource": ""
} |
q9694 | FormHelper.onPostHandleRequestWithCollection | train | public function onPostHandleRequestWithCollection(Collection $oldCollection, Collection $newCollection) {
$deleted = 0;
foreach ($oldCollection as $current) {
if (true === $newCollection->contains($current)) {
continue;
}
$this->getObjectManager()->remove($current);
++$deleted;
}
return $deleted;
} | php | {
"resource": ""
} |
q9695 | FormHelper.onPreHandleRequestWithCollection | train | public function onPreHandleRequestWithCollection(Collection $collection) {
$output = new ArrayCollection();
foreach ($collection as $current) {
$output->add($current);
}
return $output;
} | php | {
"resource": ""
} |
q9696 | ValueHelper.isInteger | train | public static function isInteger($value)
{
if (is_int($value)) {
return true;
} elseif (!is_string($value)) {
return false;
}
return preg_match('/^\d+$/', $value) > 0;
} | php | {
"resource": ""
} |
q9697 | ValueHelper.isFloat | train | public static function isFloat($value)
{
if (is_float($value)) {
return true;
} elseif (!is_string($value)) {
return false;
}
return preg_match('/^[0-9]+\.[0-9]+$/', $value) > 0;
} | php | {
"resource": ""
} |
q9698 | ValueHelper.isDateTime | train | public static function isDateTime($date, string $format = null): bool
{
if ($date instanceof \DateTime) {
return true;
}
if (false === is_string($date)) {
return false;
}
if ($format) {
return \DateTime::createFromFormat($format, $date) instanceof \DateTime;
}
return (bool)strtotime($date);
} | php | {
"resource": ""
} |
q9699 | EdgarEzCronRepository.updateCron | train | public function updateCron(EdgarEzCron $cron): bool
{
try {
$this->getEntityManager()->persist($cron);
$this->getEntityManager()->flush();
} catch (ORMException $e) {
return false;
}
return true;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.