id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
45,500
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scss_parser.selector
protected function selector(&$out) { $selector = array(); while (true) { if ($this->match('[>+~]+', $m)) { $selector[] = array($m[0]); } elseif ($this->selectorSingle($part)) { $selector[] = $part; $this->whitespace(); } else { break; } } if (count($selector) == 0) { return false; } $out = $selector; return true; }
php
protected function selector(&$out) { $selector = array(); while (true) { if ($this->match('[>+~]+', $m)) { $selector[] = array($m[0]); } elseif ($this->selectorSingle($part)) { $selector[] = $part; $this->whitespace(); } else { break; } } if (count($selector) == 0) { return false; } $out = $selector; return true; }
[ "protected", "function", "selector", "(", "&", "$", "out", ")", "{", "$", "selector", "=", "array", "(", ")", ";", "while", "(", "true", ")", "{", "if", "(", "$", "this", "->", "match", "(", "'[>+~]+'", ",", "$", "m", ")", ")", "{", "$", "selec...
whitespace separated list of selectorSingle
[ "whitespace", "separated", "list", "of", "selectorSingle" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L3365-L3386
45,501
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scss_parser.whitespace
protected function whitespace() { $gotWhite = false; while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) { if ($this->insertComments) { if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { $this->append(array("comment", $m[1])); $this->commentsSeen[$this->count] = true; } } $this->count += strlen($m[0]); $gotWhite = true; } return $gotWhite; }
php
protected function whitespace() { $gotWhite = false; while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) { if ($this->insertComments) { if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { $this->append(array("comment", $m[1])); $this->commentsSeen[$this->count] = true; } } $this->count += strlen($m[0]); $gotWhite = true; } return $gotWhite; }
[ "protected", "function", "whitespace", "(", ")", "{", "$", "gotWhite", "=", "false", ";", "while", "(", "preg_match", "(", "self", "::", "$", "whitePattern", ",", "$", "this", "->", "buffer", ",", "$", "m", ",", "null", ",", "$", "this", "->", "count...
match some whitespace
[ "match", "some", "whitespace" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L3626-L3639
45,502
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scss_formatter_nested.adjustAllChildren
public function adjustAllChildren($block) { // flatten empty nested blocks $children = array(); foreach ($block->children as $i => $child) { if (empty($child->lines) && empty($child->children)) { if (isset($block->children[$i + 1])) { $block->children[$i + 1]->depth = $child->depth; } continue; } $children[] = $child; } $count = count($children); for ($i = 0; $i < $count; $i++) { $depth = $children[$i]->depth; $j = $i + 1; if (isset($children[$j]) && $depth < $children[$j]->depth) { $childDepth = $children[$j]->depth; for (; $j < $count; $j++) { if ($depth < $children[$j]->depth && $childDepth >= $children[$j]->depth) { $children[$j]->depth = $depth + 1; } } } } $block->children = $children; // make relative to parent foreach ($block->children as $child) { $this->adjustAllChildren($child); $child->depth = $child->depth - $block->depth; } }
php
public function adjustAllChildren($block) { // flatten empty nested blocks $children = array(); foreach ($block->children as $i => $child) { if (empty($child->lines) && empty($child->children)) { if (isset($block->children[$i + 1])) { $block->children[$i + 1]->depth = $child->depth; } continue; } $children[] = $child; } $count = count($children); for ($i = 0; $i < $count; $i++) { $depth = $children[$i]->depth; $j = $i + 1; if (isset($children[$j]) && $depth < $children[$j]->depth) { $childDepth = $children[$j]->depth; for (; $j < $count; $j++) { if ($depth < $children[$j]->depth && $childDepth >= $children[$j]->depth) { $children[$j]->depth = $depth + 1; } } } } $block->children = $children; // make relative to parent foreach ($block->children as $child) { $this->adjustAllChildren($child); $child->depth = $child->depth - $block->depth; } }
[ "public", "function", "adjustAllChildren", "(", "$", "block", ")", "{", "// flatten empty nested blocks", "$", "children", "=", "array", "(", ")", ";", "foreach", "(", "$", "block", "->", "children", "as", "$", "i", "=>", "$", "child", ")", "{", "if", "(...
adjust the depths of all children, depth first
[ "adjust", "the", "depths", "of", "all", "children", "depth", "first" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L3735-L3769
45,503
Pawka/phrozn
Phrozn/Registry/Dao/Serialized.php
Serialized.save
public function save() { if ($path = $this->getProjectPath()) { $path .= '/' . $this->getOutputFile(); file_put_contents($path, serialize($this->getContainer())); } else { throw new \RuntimeException('No project path provided.'); } return $this; }
php
public function save() { if ($path = $this->getProjectPath()) { $path .= '/' . $this->getOutputFile(); file_put_contents($path, serialize($this->getContainer())); } else { throw new \RuntimeException('No project path provided.'); } return $this; }
[ "public", "function", "save", "(", ")", "{", "if", "(", "$", "path", "=", "$", "this", "->", "getProjectPath", "(", ")", ")", "{", "$", "path", ".=", "'/'", ".", "$", "this", "->", "getOutputFile", "(", ")", ";", "file_put_contents", "(", "$", "pat...
Save current registry container @return \Phorzn\Registry\Dao
[ "Save", "current", "registry", "container" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Dao/Serialized.php#L42-L51
45,504
Pawka/phrozn
Phrozn/Registry/Dao/Serialized.php
Serialized.read
public function read() { $path = $this->getProjectPath() . '/' . $this->getOutputFile(); if (!is_readable($path)) { $this->getContainer()->setValues(null); return $this->getContainer(); } $newContainer = unserialize(file_get_contents($path)); return $newContainer; }
php
public function read() { $path = $this->getProjectPath() . '/' . $this->getOutputFile(); if (!is_readable($path)) { $this->getContainer()->setValues(null); return $this->getContainer(); } $newContainer = unserialize(file_get_contents($path)); return $newContainer; }
[ "public", "function", "read", "(", ")", "{", "$", "path", "=", "$", "this", "->", "getProjectPath", "(", ")", ".", "'/'", ".", "$", "this", "->", "getOutputFile", "(", ")", ";", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "$",...
Read registry data into container. @return \Phrozn\Registry\Container
[ "Read", "registry", "data", "into", "container", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Dao/Serialized.php#L58-L67
45,505
Pawka/phrozn
Phrozn/Processor/Twig.php
Twig.getLoader
protected function getLoader() { $config = $this->getConfig(); $chain = new \Twig_Loader_Chain(); // use template's own directory to search for templates $paths = array($config['phr_template_dir']); // inject common paths $projectPath = new ProjectPath($config['phr_template_dir']); if ($projectPath = $projectPath->get()) { $paths[] = $projectPath . DIRECTORY_SEPARATOR . 'layouts'; $paths[] = $projectPath; } $chain->addLoader(new \Twig_Loader_Filesystem($paths)); // add string template loader, which is responsible for loading templates // and removing front-matter $chain->addLoader(new \Phrozn\Twig\Loader\String); return $chain; }
php
protected function getLoader() { $config = $this->getConfig(); $chain = new \Twig_Loader_Chain(); // use template's own directory to search for templates $paths = array($config['phr_template_dir']); // inject common paths $projectPath = new ProjectPath($config['phr_template_dir']); if ($projectPath = $projectPath->get()) { $paths[] = $projectPath . DIRECTORY_SEPARATOR . 'layouts'; $paths[] = $projectPath; } $chain->addLoader(new \Twig_Loader_Filesystem($paths)); // add string template loader, which is responsible for loading templates // and removing front-matter $chain->addLoader(new \Phrozn\Twig\Loader\String); return $chain; }
[ "protected", "function", "getLoader", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "$", "chain", "=", "new", "\\", "Twig_Loader_Chain", "(", ")", ";", "// use template's own directory to search for templates", "$", "paths", ...
Get template loader chain @return \Twig_LoaderInterface
[ "Get", "template", "loader", "chain" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Processor/Twig.php#L105-L126
45,506
joomla-framework/session
Session.php
Session.set
public function set($name, $value = null, $namespace = 'default') { // Add prefix to namespace to avoid collisions $namespace = '__' . $namespace; if ($this->getState() !== 'active') { return; } $old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null; if ($value === null) { unset($_SESSION[$namespace][$name]); } else { $_SESSION[$namespace][$name] = $value; } return $old; }
php
public function set($name, $value = null, $namespace = 'default') { // Add prefix to namespace to avoid collisions $namespace = '__' . $namespace; if ($this->getState() !== 'active') { return; } $old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null; if ($value === null) { unset($_SESSION[$namespace][$name]); } else { $_SESSION[$namespace][$name] = $value; } return $old; }
[ "public", "function", "set", "(", "$", "name", ",", "$", "value", "=", "null", ",", "$", "namespace", "=", "'default'", ")", "{", "// Add prefix to namespace to avoid collisions", "$", "namespace", "=", "'__'", ".", "$", "namespace", ";", "if", "(", "$", "...
Set data into the session store. @param string $name Name of a variable. @param mixed $value Value of a variable. @param string $namespace Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.} @return mixed Old value of a variable. @since 1.0
[ "Set", "data", "into", "the", "session", "store", "." ]
d721b3e59388432091bfd17f828e278d6641a77e
https://github.com/joomla-framework/session/blob/d721b3e59388432091bfd17f828e278d6641a77e/Session.php#L459-L481
45,507
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.handle
public function handle() { Deprecation::notice('5.0', 'handle() will be removed. Use addToCampaign or Form directly'); $object = $this->getObject($this->data['ID'], $this->data['ClassName']); if (empty($this->data['Campaign'])) { return $this->Form($object)->forTemplate(); } else { return $this->addToCampaign($object, $this->data['Campaign']); } }
php
public function handle() { Deprecation::notice('5.0', 'handle() will be removed. Use addToCampaign or Form directly'); $object = $this->getObject($this->data['ID'], $this->data['ClassName']); if (empty($this->data['Campaign'])) { return $this->Form($object)->forTemplate(); } else { return $this->addToCampaign($object, $this->data['Campaign']); } }
[ "public", "function", "handle", "(", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'handle() will be removed. Use addToCampaign or Form directly'", ")", ";", "$", "object", "=", "$", "this", "->", "getObject", "(", "$", "this", "->", "data", "[", ...
Perform the action. Either returns a Form or performs the action, as per the class doc @return DBHTMLText|HTTPResponse
[ "Perform", "the", "action", ".", "Either", "returns", "a", "Form", "or", "performs", "the", "action", "as", "per", "the", "class", "doc" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L99-L109
45,508
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getAvailableChangeSets
protected function getAvailableChangeSets() { return ChangeSet::get() ->filter('State', ChangeSet::STATE_OPEN) ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return $item->canView(); }); }
php
protected function getAvailableChangeSets() { return ChangeSet::get() ->filter('State', ChangeSet::STATE_OPEN) ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return $item->canView(); }); }
[ "protected", "function", "getAvailableChangeSets", "(", ")", "{", "return", "ChangeSet", "::", "get", "(", ")", "->", "filter", "(", "'State'", ",", "ChangeSet", "::", "STATE_OPEN", ")", "->", "filterByCallback", "(", "function", "(", "$", "item", ")", "{", ...
Get what ChangeSets are available for an item to be added to by this user @return ArrayList|ChangeSet[]
[ "Get", "what", "ChangeSets", "are", "available", "for", "an", "item", "to", "be", "added", "to", "by", "this", "user" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L116-L124
45,509
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getInChangeSets
protected function getInChangeSets($object) { $inChangeSetIDs = array_unique(ChangeSetItem::get_for_object($object)->column('ChangeSetID')); if ($inChangeSetIDs > 0) { $changeSets = $this->getAvailableChangeSets()->filter([ 'ID' => $inChangeSetIDs, 'State' => ChangeSet::STATE_OPEN ]); } else { $changeSets = new ArrayList(); } return $changeSets; }
php
protected function getInChangeSets($object) { $inChangeSetIDs = array_unique(ChangeSetItem::get_for_object($object)->column('ChangeSetID')); if ($inChangeSetIDs > 0) { $changeSets = $this->getAvailableChangeSets()->filter([ 'ID' => $inChangeSetIDs, 'State' => ChangeSet::STATE_OPEN ]); } else { $changeSets = new ArrayList(); } return $changeSets; }
[ "protected", "function", "getInChangeSets", "(", "$", "object", ")", "{", "$", "inChangeSetIDs", "=", "array_unique", "(", "ChangeSetItem", "::", "get_for_object", "(", "$", "object", ")", "->", "column", "(", "'ChangeSetID'", ")", ")", ";", "if", "(", "$", ...
Get changesets that a given object is already in @param DataObject @return ArrayList[ChangeSet]
[ "Get", "changesets", "that", "a", "given", "object", "is", "already", "in" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L132-L145
45,510
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.Form
public function Form($object) { $inChangeSets = $this->getInChangeSets($object); $inChangeSetIDs = $inChangeSets->column('ID'); // Get changesets that can be added to $candidateChangeSets = $this->getAvailableChangeSets(); if ($inChangeSetIDs) { $candidateChangeSets = $candidateChangeSets->exclude('ID', $inChangeSetIDs); } $canCreate = ChangeSet::singleton()->canCreate(); $message = $this->getFormAlert($inChangeSets, $candidateChangeSets, $canCreate); $fields = new FieldList(array_filter([ $message ? LiteralField::create("AlertMessages", $message) : null, HiddenField::create('ID', null, $object->ID), HiddenField::create('ClassName', null, $object->baseClass()) ])); // Add fields based on available options $showSelect = $candidateChangeSets->count() > 0; if ($showSelect) { $campaignDropdown = DropdownField::create( 'Campaign', _t(__CLASS__ . '.AddToCampaignAvailableLabel', 'Available campaigns'), $candidateChangeSets ) ->setEmptyString(_t(__CLASS__ . '.AddToCampaignFormFieldLabel', 'Select a Campaign')) ->addExtraClass('noborder') ->addExtraClass('no-chosen'); $fields->push($campaignDropdown); // Show visibilty toggle of other create field if ($canCreate) { $addCampaignSelect = CheckboxField::create('AddNewSelect', _t( __CLASS__ . '.ADD_TO_A_NEW_CAMPAIGN', 'Add to a new campaign' )) ->setAttribute('data-shows', 'NewTitle') ->setSchemaData(['data' => ['shows' => 'NewTitle']]); $fields->push($addCampaignSelect); } } if ($canCreate) { $placeholder = _t(__CLASS__ . '.CREATE_NEW_PLACEHOLDER', 'Enter campaign name'); $createBox = TextField::create( 'NewTitle', _t(__CLASS__ . '.CREATE_NEW', 'Create a new campaign') ) ->setAttribute('placeholder', $placeholder) ->setSchemaData(['attributes' => ['placeholder' => $placeholder]]); $fields->push($createBox); } $actions = FieldList::create(); if ($canCreate || $showSelect) { $actions->push( AddToCampaignHandler_FormAction::create() ->setTitle(_t(__CLASS__ . '.AddToCampaignAddAction', 'Add')) ->addExtraClass('add-to-campaign__action') ); } $form = Form::create( $this->controller, $this->name, $fields, $actions, AddToCampaignValidator::create() ); $form->setHTMLID('Form_EditForm_AddToCampaign'); $form->addExtraClass('form--no-dividers add-to-campaign__form'); return $form; }
php
public function Form($object) { $inChangeSets = $this->getInChangeSets($object); $inChangeSetIDs = $inChangeSets->column('ID'); // Get changesets that can be added to $candidateChangeSets = $this->getAvailableChangeSets(); if ($inChangeSetIDs) { $candidateChangeSets = $candidateChangeSets->exclude('ID', $inChangeSetIDs); } $canCreate = ChangeSet::singleton()->canCreate(); $message = $this->getFormAlert($inChangeSets, $candidateChangeSets, $canCreate); $fields = new FieldList(array_filter([ $message ? LiteralField::create("AlertMessages", $message) : null, HiddenField::create('ID', null, $object->ID), HiddenField::create('ClassName', null, $object->baseClass()) ])); // Add fields based on available options $showSelect = $candidateChangeSets->count() > 0; if ($showSelect) { $campaignDropdown = DropdownField::create( 'Campaign', _t(__CLASS__ . '.AddToCampaignAvailableLabel', 'Available campaigns'), $candidateChangeSets ) ->setEmptyString(_t(__CLASS__ . '.AddToCampaignFormFieldLabel', 'Select a Campaign')) ->addExtraClass('noborder') ->addExtraClass('no-chosen'); $fields->push($campaignDropdown); // Show visibilty toggle of other create field if ($canCreate) { $addCampaignSelect = CheckboxField::create('AddNewSelect', _t( __CLASS__ . '.ADD_TO_A_NEW_CAMPAIGN', 'Add to a new campaign' )) ->setAttribute('data-shows', 'NewTitle') ->setSchemaData(['data' => ['shows' => 'NewTitle']]); $fields->push($addCampaignSelect); } } if ($canCreate) { $placeholder = _t(__CLASS__ . '.CREATE_NEW_PLACEHOLDER', 'Enter campaign name'); $createBox = TextField::create( 'NewTitle', _t(__CLASS__ . '.CREATE_NEW', 'Create a new campaign') ) ->setAttribute('placeholder', $placeholder) ->setSchemaData(['attributes' => ['placeholder' => $placeholder]]); $fields->push($createBox); } $actions = FieldList::create(); if ($canCreate || $showSelect) { $actions->push( AddToCampaignHandler_FormAction::create() ->setTitle(_t(__CLASS__ . '.AddToCampaignAddAction', 'Add')) ->addExtraClass('add-to-campaign__action') ); } $form = Form::create( $this->controller, $this->name, $fields, $actions, AddToCampaignValidator::create() ); $form->setHTMLID('Form_EditForm_AddToCampaign'); $form->addExtraClass('form--no-dividers add-to-campaign__form'); return $form; }
[ "public", "function", "Form", "(", "$", "object", ")", "{", "$", "inChangeSets", "=", "$", "this", "->", "getInChangeSets", "(", "$", "object", ")", ";", "$", "inChangeSetIDs", "=", "$", "inChangeSets", "->", "column", "(", "'ID'", ")", ";", "// Get chan...
Builds a Form that mirrors the parent editForm, but with an extra field to collect the ChangeSet ID @param DataObject $object The object we're going to be adding to whichever ChangeSet is chosen @return Form
[ "Builds", "a", "Form", "that", "mirrors", "the", "parent", "editForm", "but", "with", "an", "extra", "field", "to", "collect", "the", "ChangeSet", "ID" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L203-L278
45,511
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.addToCampaign
public function addToCampaign($object, $data) { // Extract $campaignID from $data $campaignID = $this->getOrCreateCampaign($data); /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($campaignID); if (!$changeSet) { throw new ValidationException(_t( __CLASS__ . '.ErrorNotFound', 'That {Type} couldn\'t be found', ['Type' => 'Campaign'] )); } if (!$changeSet->canEdit()) { throw new ValidationException(_t( __CLASS__ . '.ErrorCampaignPermissionDenied', 'It seems you don\'t have the necessary permissions to add {ObjectTitle} to {CampaignTitle}', [ 'ObjectTitle' => $object->Title, 'CampaignTitle' => $changeSet->Title ] )); } $changeSet->addObject($object); $request = $this->controller->getRequest(); $message = _t( __CLASS__ . '.Success', 'Successfully added <strong>{ObjectTitle}</strong> to <strong>{CampaignTitle}</strong>', [ 'ObjectTitle' => Convert::raw2xml($object->Title), 'CampaignTitle' => Convert::raw2xml($changeSet->Title) ] ); if ($request->getHeader('X-Formschema-Request')) { return $message; } elseif (Director::is_ajax()) { $response = new HTTPResponse($message, 200); $response->addHeader('Content-Type', 'text/html; charset=utf-8'); return $response; } else { return $this->controller->redirectBack(); } }
php
public function addToCampaign($object, $data) { // Extract $campaignID from $data $campaignID = $this->getOrCreateCampaign($data); /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($campaignID); if (!$changeSet) { throw new ValidationException(_t( __CLASS__ . '.ErrorNotFound', 'That {Type} couldn\'t be found', ['Type' => 'Campaign'] )); } if (!$changeSet->canEdit()) { throw new ValidationException(_t( __CLASS__ . '.ErrorCampaignPermissionDenied', 'It seems you don\'t have the necessary permissions to add {ObjectTitle} to {CampaignTitle}', [ 'ObjectTitle' => $object->Title, 'CampaignTitle' => $changeSet->Title ] )); } $changeSet->addObject($object); $request = $this->controller->getRequest(); $message = _t( __CLASS__ . '.Success', 'Successfully added <strong>{ObjectTitle}</strong> to <strong>{CampaignTitle}</strong>', [ 'ObjectTitle' => Convert::raw2xml($object->Title), 'CampaignTitle' => Convert::raw2xml($changeSet->Title) ] ); if ($request->getHeader('X-Formschema-Request')) { return $message; } elseif (Director::is_ajax()) { $response = new HTTPResponse($message, 200); $response->addHeader('Content-Type', 'text/html; charset=utf-8'); return $response; } else { return $this->controller->redirectBack(); } }
[ "public", "function", "addToCampaign", "(", "$", "object", ",", "$", "data", ")", "{", "// Extract $campaignID from $data", "$", "campaignID", "=", "$", "this", "->", "getOrCreateCampaign", "(", "$", "data", ")", ";", "/** @var ChangeSet $changeSet */", "$", "chan...
Performs the actual action of adding the object to the ChangeSet, once the ChangeSet ID is known @param DataObject $object The object to add to the ChangeSet @param array|int $data Post data for this campaign form, or the ID of the campaign to add to @return HTTPResponse @throws ValidationException
[ "Performs", "the", "actual", "action", "of", "adding", "the", "object", "to", "the", "ChangeSet", "once", "the", "ChangeSet", "ID", "is", "known" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L288-L336
45,512
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getFormAlert
protected function getFormAlert($inChangeSets, $candidateChangeSets, $canCreate) { // In a subset of changesets if ($inChangeSets->count() > 0 && $candidateChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabel', 'Heads up, this item is already in campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // In all changesets if ($inChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabelAll', 'Heads up, this item is already in ALL campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // Create only if ($candidateChangeSets->count() === 0 && $canCreate) { return sprintf( '<div class="alert alert-info">%s</div>', _t( __CLASS__ . '.NO_CAMPAIGNS', "You currently don't have any campaigns. " . "You can edit campaign details later in the Campaigns section." ) ); } // Can't select or create if ($candidateChangeSets->count() === 0 && !$canCreate) { return sprintf( '<div class="alert alert-warning">%s</div>', _t( __CLASS__ . '.NO_CREATE', "Oh no! You currently don't have any campaigns created. " . "Your current login does not have privileges to create campaigns. " . "Campaigns can only be created by users with Campaigns section rights." ) ); } return null; }
php
protected function getFormAlert($inChangeSets, $candidateChangeSets, $canCreate) { // In a subset of changesets if ($inChangeSets->count() > 0 && $candidateChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabel', 'Heads up, this item is already in campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // In all changesets if ($inChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabelAll', 'Heads up, this item is already in ALL campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // Create only if ($candidateChangeSets->count() === 0 && $canCreate) { return sprintf( '<div class="alert alert-info">%s</div>', _t( __CLASS__ . '.NO_CAMPAIGNS', "You currently don't have any campaigns. " . "You can edit campaign details later in the Campaigns section." ) ); } // Can't select or create if ($candidateChangeSets->count() === 0 && !$canCreate) { return sprintf( '<div class="alert alert-warning">%s</div>', _t( __CLASS__ . '.NO_CREATE', "Oh no! You currently don't have any campaigns created. " . "Your current login does not have privileges to create campaigns. " . "Campaigns can only be created by users with Campaigns section rights." ) ); } return null; }
[ "protected", "function", "getFormAlert", "(", "$", "inChangeSets", ",", "$", "candidateChangeSets", ",", "$", "canCreate", ")", "{", "// In a subset of changesets", "if", "(", "$", "inChangeSets", "->", "count", "(", ")", ">", "0", "&&", "$", "candidateChangeSet...
Get descriptive alert to display at the top of the form @param ArrayList $inChangeSets List of changesets this item exists in @param ArrayList $candidateChangeSets List of changesets this item could be added to @param bool $canCreate @return string
[ "Get", "descriptive", "alert", "to", "display", "at", "the", "top", "of", "the", "form" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L346-L397
45,513
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getOrCreateCampaign
protected function getOrCreateCampaign($data) { // Create new campaign if selected if (is_array($data) && !empty($data['AddNewSelect']) // Explicitly click "Add to a new campaign" || (is_array($data) && !isset($data['Campaign']) && isset($data['NewTitle'])) // This is the only option ) { // Permission if (!ChangeSet::singleton()->canCreate()) { throw $this->validationResult( _t(__CLASS__ . '.CREATE_DENIED', 'You do not have permission to create campaigns') ); } // Check title is valid $title = $data['NewTitle']; if (empty($title)) { throw $this->validationResult( _t(__CLASS__ . '.MISSING_TITLE', 'Campaign name is required'), 'NewTitle' ); } // Prevent duplicates $hasExistingName = Changeset::get() ->filter('Name:nocase', $title) ->count() > 0; if ($hasExistingName) { throw $this->validationResult( _t( 'SilverStripe\\CampaignAdmin\\CampaignAdmin.ERROR_DUPLICATE_NAME', 'Name "{Name}" already exists', ['Name' => $title] ), 'NewTitle' ); } // Create and return $campaign = ChangeSet::create(); $campaign->Name = $title; $campaign->write(); return $campaign->ID; } // Get selected campaign ID $campaignID = null; if (is_array($data) && !empty($data['Campaign'])) { $campaignID = $data['Campaign']; } elseif (is_numeric($data)) { $campaignID = (int)$data; } if (empty($campaignID)) { throw $this->validationResult(_t(__CLASS__ . '.NONE_SELECTED', 'No campaign selected')); } return $campaignID; }
php
protected function getOrCreateCampaign($data) { // Create new campaign if selected if (is_array($data) && !empty($data['AddNewSelect']) // Explicitly click "Add to a new campaign" || (is_array($data) && !isset($data['Campaign']) && isset($data['NewTitle'])) // This is the only option ) { // Permission if (!ChangeSet::singleton()->canCreate()) { throw $this->validationResult( _t(__CLASS__ . '.CREATE_DENIED', 'You do not have permission to create campaigns') ); } // Check title is valid $title = $data['NewTitle']; if (empty($title)) { throw $this->validationResult( _t(__CLASS__ . '.MISSING_TITLE', 'Campaign name is required'), 'NewTitle' ); } // Prevent duplicates $hasExistingName = Changeset::get() ->filter('Name:nocase', $title) ->count() > 0; if ($hasExistingName) { throw $this->validationResult( _t( 'SilverStripe\\CampaignAdmin\\CampaignAdmin.ERROR_DUPLICATE_NAME', 'Name "{Name}" already exists', ['Name' => $title] ), 'NewTitle' ); } // Create and return $campaign = ChangeSet::create(); $campaign->Name = $title; $campaign->write(); return $campaign->ID; } // Get selected campaign ID $campaignID = null; if (is_array($data) && !empty($data['Campaign'])) { $campaignID = $data['Campaign']; } elseif (is_numeric($data)) { $campaignID = (int)$data; } if (empty($campaignID)) { throw $this->validationResult(_t(__CLASS__ . '.NONE_SELECTED', 'No campaign selected')); } return $campaignID; }
[ "protected", "function", "getOrCreateCampaign", "(", "$", "data", ")", "{", "// Create new campaign if selected", "if", "(", "is_array", "(", "$", "data", ")", "&&", "!", "empty", "(", "$", "data", "[", "'AddNewSelect'", "]", ")", "// Explicitly click \"Add to a n...
Find or build campaign from posted data @param array|int $data @return int @throws ValidationException
[ "Find", "or", "build", "campaign", "from", "posted", "data" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L406-L462
45,514
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.validationResult
protected function validationResult($message, $field = null) { $error = ValidationResult::create() ->addFieldError($field, $message); return new ValidationException($error); }
php
protected function validationResult($message, $field = null) { $error = ValidationResult::create() ->addFieldError($field, $message); return new ValidationException($error); }
[ "protected", "function", "validationResult", "(", "$", "message", ",", "$", "field", "=", "null", ")", "{", "$", "error", "=", "ValidationResult", "::", "create", "(", ")", "->", "addFieldError", "(", "$", "field", ",", "$", "message", ")", ";", "return"...
Raise validation error @param string $message @param string $field @return ValidationException
[ "Raise", "validation", "error" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L471-L476
45,515
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.readCampaigns
public function readCampaigns() { $response = new HTTPResponse(); $response->addHeader('Content-Type', 'application/json'); $hal = $this->getListResource(); $response->setBody(json_encode($hal)); return $response; }
php
public function readCampaigns() { $response = new HTTPResponse(); $response->addHeader('Content-Type', 'application/json'); $hal = $this->getListResource(); $response->setBody(json_encode($hal)); return $response; }
[ "public", "function", "readCampaigns", "(", ")", "{", "$", "response", "=", "new", "HTTPResponse", "(", ")", ";", "$", "response", "->", "addHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "$", "hal", "=", "$", "this", "->", "getListRe...
REST endpoint to get a list of campaigns. @return HTTPResponse
[ "REST", "endpoint", "to", "get", "a", "list", "of", "campaigns", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L190-L197
45,516
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getListResource
protected function getListResource() { $items = $this->getListItems(); $count = $items->count(); /** @var string $treeClass */ $treeClass = $this->config()->get('tree_class'); $hal = [ 'count' => $count, 'total' => $count, '_links' => [ 'self' => [ 'href' => $this->Link('items') ] ], '_embedded' => [$treeClass => []] ]; /** @var ChangeSet $item */ foreach ($items as $item) { $sync = $this->shouldCampaignSync($item); $resource = $this->getChangeSetResource($item, $sync); $hal['_embedded'][$treeClass][] = $resource; } return $hal; }
php
protected function getListResource() { $items = $this->getListItems(); $count = $items->count(); /** @var string $treeClass */ $treeClass = $this->config()->get('tree_class'); $hal = [ 'count' => $count, 'total' => $count, '_links' => [ 'self' => [ 'href' => $this->Link('items') ] ], '_embedded' => [$treeClass => []] ]; /** @var ChangeSet $item */ foreach ($items as $item) { $sync = $this->shouldCampaignSync($item); $resource = $this->getChangeSetResource($item, $sync); $hal['_embedded'][$treeClass][] = $resource; } return $hal; }
[ "protected", "function", "getListResource", "(", ")", "{", "$", "items", "=", "$", "this", "->", "getListItems", "(", ")", ";", "$", "count", "=", "$", "items", "->", "count", "(", ")", ";", "/** @var string $treeClass */", "$", "treeClass", "=", "$", "t...
Get list contained as a hal wrapper @return array
[ "Get", "list", "contained", "as", "a", "hal", "wrapper" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L235-L258
45,517
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getChangeSetResource
protected function getChangeSetResource(ChangeSet $changeSet, $sync = false) { $stateLabel = sprintf( '<span class="campaign-status campaign-status--%s"></span>%s', $changeSet->State, $changeSet->getStateLabel() ); $hal = [ '_links' => [ 'self' => [ 'href' => $this->SetLink($changeSet->ID) ] ], 'ID' => $changeSet->ID, 'Name' => $changeSet->Name, 'Created' => $changeSet->Created, 'LastEdited' => $changeSet->LastEdited, 'State' => $changeSet->State, 'StateLabel' => [ 'html' => $stateLabel ], 'IsInferred' => $changeSet->IsInferred, 'canEdit' => $changeSet->canEdit(), 'canPublish' => false, '_embedded' => ['items' => []], 'placeholderGroups' => $this->getPlaceholderGroups(), ]; // Before presenting the changeset to the client, // synchronise it with new changes. try { if ($sync) { $changeSet->sync(); } $hal['PublishedLabel'] = $changeSet->getPublishedLabel() ?: '-'; $hal['Details'] = $changeSet->getDetails(); $hal['canPublish'] = $changeSet->canPublish() && $changeSet->hasChanges(); foreach ($changeSet->Changes() as $changeSetItem) { if (!$changeSetItem) { continue; } /** @var ChangesetItem $changeSetItem */ $resource = $this->getChangeSetItemResource($changeSetItem); if (!empty($resource)) { $hal['_embedded']['items'][] = $resource; } } // An unexpected data exception means that the database is corrupt } catch (UnexpectedDataException $e) { $hal['PublishedLabel'] = '-'; $hal['Details'] = 'Corrupt database! ' . $e->getMessage(); $hal['canPublish'] = false; } return $hal; }
php
protected function getChangeSetResource(ChangeSet $changeSet, $sync = false) { $stateLabel = sprintf( '<span class="campaign-status campaign-status--%s"></span>%s', $changeSet->State, $changeSet->getStateLabel() ); $hal = [ '_links' => [ 'self' => [ 'href' => $this->SetLink($changeSet->ID) ] ], 'ID' => $changeSet->ID, 'Name' => $changeSet->Name, 'Created' => $changeSet->Created, 'LastEdited' => $changeSet->LastEdited, 'State' => $changeSet->State, 'StateLabel' => [ 'html' => $stateLabel ], 'IsInferred' => $changeSet->IsInferred, 'canEdit' => $changeSet->canEdit(), 'canPublish' => false, '_embedded' => ['items' => []], 'placeholderGroups' => $this->getPlaceholderGroups(), ]; // Before presenting the changeset to the client, // synchronise it with new changes. try { if ($sync) { $changeSet->sync(); } $hal['PublishedLabel'] = $changeSet->getPublishedLabel() ?: '-'; $hal['Details'] = $changeSet->getDetails(); $hal['canPublish'] = $changeSet->canPublish() && $changeSet->hasChanges(); foreach ($changeSet->Changes() as $changeSetItem) { if (!$changeSetItem) { continue; } /** @var ChangesetItem $changeSetItem */ $resource = $this->getChangeSetItemResource($changeSetItem); if (!empty($resource)) { $hal['_embedded']['items'][] = $resource; } } // An unexpected data exception means that the database is corrupt } catch (UnexpectedDataException $e) { $hal['PublishedLabel'] = '-'; $hal['Details'] = 'Corrupt database! ' . $e->getMessage(); $hal['canPublish'] = false; } return $hal; }
[ "protected", "function", "getChangeSetResource", "(", "ChangeSet", "$", "changeSet", ",", "$", "sync", "=", "false", ")", "{", "$", "stateLabel", "=", "sprintf", "(", "'<span class=\"campaign-status campaign-status--%s\"></span>%s'", ",", "$", "changeSet", "->", "Stat...
Build item resource from a changeset @param ChangeSet $changeSet @param bool $sync Set to true to force async of this changeset @return array
[ "Build", "item", "resource", "from", "a", "changeset" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L267-L323
45,518
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getChangeSetItemResource
protected function getChangeSetItemResource(ChangeSetItem $changeSetItem) { $baseClass = DataObject::getSchema()->baseDataClass($changeSetItem->ObjectClass); $baseSingleton = DataObject::singleton($baseClass); // Allow items to opt out of being displayed in changesets if ($baseSingleton->config()->get('hide_in_campaigns')) { return []; } $thumbnailWidth = (int)$this->config()->get('thumbnail_width'); $thumbnailHeight = (int)$this->config()->get('thumbnail_height'); $hal = [ '_links' => [ 'self' => [ 'id' => $changeSetItem->ID, 'href' => $this->ItemLink($changeSetItem->ID) ] ], 'ID' => $changeSetItem->ID, 'Created' => $changeSetItem->Created, 'LastEdited' => $changeSetItem->LastEdited, 'Title' => $changeSetItem->getTitle(), 'ChangeType' => $changeSetItem->getChangeType(), 'Added' => $changeSetItem->Added, 'ObjectClass' => $changeSetItem->ObjectClass, 'ObjectID' => $changeSetItem->ObjectID, 'BaseClass' => $baseClass, 'Singular' => $baseSingleton->i18n_singular_name(), 'Plural' => $baseSingleton->i18n_plural_name(), 'Thumbnail' => $changeSetItem->ThumbnailURL($thumbnailWidth, $thumbnailHeight), ]; // Get preview urls $previews = $changeSetItem->getPreviewLinks(); if ($previews) { $hal['_links']['preview'] = $previews; } // Get edit link $editLink = $changeSetItem->CMSEditLink(); if ($editLink) { $hal['_links']['edit'] = [ 'href' => $editLink, ]; } // Depending on whether the object was added implicitly or explicitly, set // other related objects. if ($changeSetItem->Added === ChangeSetItem::IMPLICITLY) { $referencedItems = $changeSetItem->ReferencedBy(); $referencedBy = []; foreach ($referencedItems as $referencedItem) { $referencedBy[] = [ 'href' => $this->SetLink($referencedItem->ID), 'ChangeSetItemID' => $referencedItem->ID ]; } if ($referencedBy) { $hal['_links']['referenced_by'] = $referencedBy; } } $referToItems = $changeSetItem->References(); $referTo = []; foreach ($referToItems as $referToItem) { $referTo[] = [ 'ChangeSetItemID' => $referToItem->ID, ]; } $hal['_links']['references'] = $referTo; return $hal; }
php
protected function getChangeSetItemResource(ChangeSetItem $changeSetItem) { $baseClass = DataObject::getSchema()->baseDataClass($changeSetItem->ObjectClass); $baseSingleton = DataObject::singleton($baseClass); // Allow items to opt out of being displayed in changesets if ($baseSingleton->config()->get('hide_in_campaigns')) { return []; } $thumbnailWidth = (int)$this->config()->get('thumbnail_width'); $thumbnailHeight = (int)$this->config()->get('thumbnail_height'); $hal = [ '_links' => [ 'self' => [ 'id' => $changeSetItem->ID, 'href' => $this->ItemLink($changeSetItem->ID) ] ], 'ID' => $changeSetItem->ID, 'Created' => $changeSetItem->Created, 'LastEdited' => $changeSetItem->LastEdited, 'Title' => $changeSetItem->getTitle(), 'ChangeType' => $changeSetItem->getChangeType(), 'Added' => $changeSetItem->Added, 'ObjectClass' => $changeSetItem->ObjectClass, 'ObjectID' => $changeSetItem->ObjectID, 'BaseClass' => $baseClass, 'Singular' => $baseSingleton->i18n_singular_name(), 'Plural' => $baseSingleton->i18n_plural_name(), 'Thumbnail' => $changeSetItem->ThumbnailURL($thumbnailWidth, $thumbnailHeight), ]; // Get preview urls $previews = $changeSetItem->getPreviewLinks(); if ($previews) { $hal['_links']['preview'] = $previews; } // Get edit link $editLink = $changeSetItem->CMSEditLink(); if ($editLink) { $hal['_links']['edit'] = [ 'href' => $editLink, ]; } // Depending on whether the object was added implicitly or explicitly, set // other related objects. if ($changeSetItem->Added === ChangeSetItem::IMPLICITLY) { $referencedItems = $changeSetItem->ReferencedBy(); $referencedBy = []; foreach ($referencedItems as $referencedItem) { $referencedBy[] = [ 'href' => $this->SetLink($referencedItem->ID), 'ChangeSetItemID' => $referencedItem->ID ]; } if ($referencedBy) { $hal['_links']['referenced_by'] = $referencedBy; } } $referToItems = $changeSetItem->References(); $referTo = []; foreach ($referToItems as $referToItem) { $referTo[] = [ 'ChangeSetItemID' => $referToItem->ID, ]; } $hal['_links']['references'] = $referTo; return $hal; }
[ "protected", "function", "getChangeSetItemResource", "(", "ChangeSetItem", "$", "changeSetItem", ")", "{", "$", "baseClass", "=", "DataObject", "::", "getSchema", "(", ")", "->", "baseDataClass", "(", "$", "changeSetItem", "->", "ObjectClass", ")", ";", "$", "ba...
Build item resource from a changesetitem @param ChangeSetItem $changeSetItem @return array
[ "Build", "item", "resource", "from", "a", "changesetitem" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L331-L403
45,519
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getListItems
protected function getListItems() { $changesets = ChangeSet::get(); // Filter out published items if disabled if (!$this->config()->get('show_published')) { $changesets = $changesets->filter('State', ChangeSet::STATE_OPEN); } // Filter out automatically created changesets if (!$this->config()->get('show_inferred')) { $changesets = $changesets->filter('IsInferred', 0); } return $changesets ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return ($item->canView()); }); }
php
protected function getListItems() { $changesets = ChangeSet::get(); // Filter out published items if disabled if (!$this->config()->get('show_published')) { $changesets = $changesets->filter('State', ChangeSet::STATE_OPEN); } // Filter out automatically created changesets if (!$this->config()->get('show_inferred')) { $changesets = $changesets->filter('IsInferred', 0); } return $changesets ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return ($item->canView()); }); }
[ "protected", "function", "getListItems", "(", ")", "{", "$", "changesets", "=", "ChangeSet", "::", "get", "(", ")", ";", "// Filter out published items if disabled", "if", "(", "!", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'show_published'", ...
Gets viewable list of campaigns @return SS_List
[ "Gets", "viewable", "list", "of", "campaigns" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L410-L426
45,520
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.readCampaign
public function readCampaign(HTTPRequest $request) { $response = new HTTPResponse(); $accepts = $request->getAcceptMimetypes(); //accept 'text/json' for legacy reasons if (in_array('application/json', $accepts) || in_array('text/json', $accepts)) { $response->addHeader('Content-Type', 'application/json'); if (!$request->param('Name')) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($request->param('ID')); if (!$changeSet) { return (new HTTPResponse(null, 404)); } if (!$changeSet->canView()) { return (new HTTPResponse(null, 403)); } $body = json_encode($this->getChangeSetResource($changeSet, true)); return (new HTTPResponse($body, 200)) ->addHeader('Content-Type', 'application/json'); } else { return $this->index($request); } }
php
public function readCampaign(HTTPRequest $request) { $response = new HTTPResponse(); $accepts = $request->getAcceptMimetypes(); //accept 'text/json' for legacy reasons if (in_array('application/json', $accepts) || in_array('text/json', $accepts)) { $response->addHeader('Content-Type', 'application/json'); if (!$request->param('Name')) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($request->param('ID')); if (!$changeSet) { return (new HTTPResponse(null, 404)); } if (!$changeSet->canView()) { return (new HTTPResponse(null, 403)); } $body = json_encode($this->getChangeSetResource($changeSet, true)); return (new HTTPResponse($body, 200)) ->addHeader('Content-Type', 'application/json'); } else { return $this->index($request); } }
[ "public", "function", "readCampaign", "(", "HTTPRequest", "$", "request", ")", "{", "$", "response", "=", "new", "HTTPResponse", "(", ")", ";", "$", "accepts", "=", "$", "request", "->", "getAcceptMimetypes", "(", ")", ";", "//accept 'text/json' for legacy reaso...
REST endpoint to get a campaign. @param HTTPRequest $request @return HTTPResponse
[ "REST", "endpoint", "to", "get", "a", "campaign", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L436-L464
45,521
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.removeCampaignItem
public function removeCampaignItem(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $campaignID = $request->param('CampaignID'); $itemID = $request->param('ItemID'); if (!$campaignID || !is_numeric($campaignID) || !$itemID || !is_numeric($itemID)) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $campaign */ $campaign = ChangeSet::get()->byID($campaignID); /** @var ChangeSetItem $item */ $item = ChangeSetItem::get()->byID($itemID); if (!$campaign || !$item) { return (new HTTPResponse(null, 404)); } $campaign->removeObject($item->Object()); return (new HTTPResponse(null, 204)); }
php
public function removeCampaignItem(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $campaignID = $request->param('CampaignID'); $itemID = $request->param('ItemID'); if (!$campaignID || !is_numeric($campaignID) || !$itemID || !is_numeric($itemID)) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $campaign */ $campaign = ChangeSet::get()->byID($campaignID); /** @var ChangeSetItem $item */ $item = ChangeSetItem::get()->byID($itemID); if (!$campaign || !$item) { return (new HTTPResponse(null, 404)); } $campaign->removeObject($item->Object()); return (new HTTPResponse(null, 204)); }
[ "public", "function", "removeCampaignItem", "(", "HTTPRequest", "$", "request", ")", "{", "// Check security ID", "if", "(", "!", "SecurityToken", "::", "inst", "(", ")", "->", "checkRequest", "(", "$", "request", ")", ")", "{", "return", "new", "HTTPResponse"...
REST endpoint to delete a campaign item. @param HTTPRequest $request @return HTTPResponse
[ "REST", "endpoint", "to", "delete", "a", "campaign", "item", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L473-L502
45,522
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.deleteCampaign
public function deleteCampaign(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $id = $request->param('ID'); if (!$id || !is_numeric($id)) { return (new HTTPResponse(null, 400)); } $record = ChangeSet::get()->byID($id); if (!$record) { return (new HTTPResponse(null, 404)); } if (!$record->canDelete()) { return (new HTTPResponse(null, 403)); } $record->delete(); return (new HTTPResponse(null, 204)); }
php
public function deleteCampaign(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $id = $request->param('ID'); if (!$id || !is_numeric($id)) { return (new HTTPResponse(null, 400)); } $record = ChangeSet::get()->byID($id); if (!$record) { return (new HTTPResponse(null, 404)); } if (!$record->canDelete()) { return (new HTTPResponse(null, 403)); } $record->delete(); return (new HTTPResponse(null, 204)); }
[ "public", "function", "deleteCampaign", "(", "HTTPRequest", "$", "request", ")", "{", "// Check security ID", "if", "(", "!", "SecurityToken", "::", "inst", "(", ")", "->", "checkRequest", "(", "$", "request", ")", ")", "{", "return", "new", "HTTPResponse", ...
REST endpoint to delete a campaign. @param HTTPRequest $request @return HTTPResponse
[ "REST", "endpoint", "to", "delete", "a", "campaign", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L511-L535
45,523
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.campaignEditForm
public function campaignEditForm($request) { // Get ID either from posted back value, or url parameter if (!$request) { $this->httpError(400); return null; } $id = $request->param('ID'); if (!$id) { $this->httpError(400); return null; } return $this->getCampaignEditForm($id); }
php
public function campaignEditForm($request) { // Get ID either from posted back value, or url parameter if (!$request) { $this->httpError(400); return null; } $id = $request->param('ID'); if (!$id) { $this->httpError(400); return null; } return $this->getCampaignEditForm($id); }
[ "public", "function", "campaignEditForm", "(", "$", "request", ")", "{", "// Get ID either from posted back value, or url parameter", "if", "(", "!", "$", "request", ")", "{", "$", "this", "->", "httpError", "(", "400", ")", ";", "return", "null", ";", "}", "$...
Url handler for edit form @param HTTPRequest $request @return Form
[ "Url", "handler", "for", "edit", "form" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L585-L598
45,524
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.shouldCampaignSync
protected function shouldCampaignSync(ChangeSet $item) { // Don't sync published changesets if ($item->State !== ChangeSet::STATE_OPEN) { return false; } // Get sync threshold $syncOlderThan = DBDatetime::now()->getTimestamp() - $this->config()->get('sync_expires'); /** @var DBDatetime $lastSynced */ $lastSynced = $item->dbObject('LastSynced'); return !$lastSynced || $lastSynced->getTimestamp() < $syncOlderThan; }
php
protected function shouldCampaignSync(ChangeSet $item) { // Don't sync published changesets if ($item->State !== ChangeSet::STATE_OPEN) { return false; } // Get sync threshold $syncOlderThan = DBDatetime::now()->getTimestamp() - $this->config()->get('sync_expires'); /** @var DBDatetime $lastSynced */ $lastSynced = $item->dbObject('LastSynced'); return !$lastSynced || $lastSynced->getTimestamp() < $syncOlderThan; }
[ "protected", "function", "shouldCampaignSync", "(", "ChangeSet", "$", "item", ")", "{", "// Don't sync published changesets", "if", "(", "$", "item", "->", "State", "!==", "ChangeSet", "::", "STATE_OPEN", ")", "{", "return", "false", ";", "}", "// Get sync thresho...
Check if the given campaign should be synced before view @param ChangeSet $item @return bool
[ "Check", "if", "the", "given", "campaign", "should", "be", "synced", "before", "view" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L844-L856
45,525
spiral/database
src/Query/SelectQuery.php
SelectQuery.runChunks
public function runChunks(int $limit, callable $callback) { $count = $this->count(); //To keep original query untouched $select = clone $this; $select->limit($limit); $offset = 0; while ($offset + $limit <= $count) { $result = call_user_func_array( $callback, [$select->offset($offset)->getIterator(), $offset, $count] ); if ($result === false) { //Stop iteration return; } $offset += $limit; } }
php
public function runChunks(int $limit, callable $callback) { $count = $this->count(); //To keep original query untouched $select = clone $this; $select->limit($limit); $offset = 0; while ($offset + $limit <= $count) { $result = call_user_func_array( $callback, [$select->offset($offset)->getIterator(), $offset, $count] ); if ($result === false) { //Stop iteration return; } $offset += $limit; } }
[ "public", "function", "runChunks", "(", "int", "$", "limit", ",", "callable", "$", "callback", ")", "{", "$", "count", "=", "$", "this", "->", "count", "(", ")", ";", "//To keep original query untouched", "$", "select", "=", "clone", "$", "this", ";", "$...
Iterate thought result using smaller data chinks with defined size and walk function. Example: $select->chunked(100, function(PDOResult $result, $offset, $count) { dump($result); }); You must return FALSE from walk function to stop chunking. @param int $limit @param callable $callback
[ "Iterate", "thought", "result", "using", "smaller", "data", "chinks", "with", "defined", "size", "and", "walk", "function", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/SelectQuery.php#L290-L312
45,526
spiral/database
src/Query/SelectQuery.php
SelectQuery.fetchAll
public function fetchAll(): array { $st = $this->run(); try { return $st->fetchAll(\PDO::FETCH_ASSOC); } finally { $st->close(); } }
php
public function fetchAll(): array { $st = $this->run(); try { return $st->fetchAll(\PDO::FETCH_ASSOC); } finally { $st->close(); } }
[ "public", "function", "fetchAll", "(", ")", ":", "array", "{", "$", "st", "=", "$", "this", "->", "run", "(", ")", ";", "try", "{", "return", "$", "st", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "}", "finally", "{", "$", ...
Request all results as array. @return array
[ "Request", "all", "results", "as", "array", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/SelectQuery.php#L428-L436
45,527
spiral/database
src/Statement.php
Statement.bind
public function bind($columnID, &$variable): Statement { if (is_numeric($columnID)) { //PDO columns are 1-indexed $columnID = $columnID + 1; } $this->bindColumn($columnID, $variable); return $this; }
php
public function bind($columnID, &$variable): Statement { if (is_numeric($columnID)) { //PDO columns are 1-indexed $columnID = $columnID + 1; } $this->bindColumn($columnID, $variable); return $this; }
[ "public", "function", "bind", "(", "$", "columnID", ",", "&", "$", "variable", ")", ":", "Statement", "{", "if", "(", "is_numeric", "(", "$", "columnID", ")", ")", "{", "//PDO columns are 1-indexed", "$", "columnID", "=", "$", "columnID", "+", "1", ";", ...
Bind a column value to a PHP variable. Aliased to bindParam. @param int|string $columnID Column number (0 - first column) @param mixed $variable @return self|$this
[ "Bind", "a", "column", "value", "to", "a", "PHP", "variable", ".", "Aliased", "to", "bindParam", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Statement.php#L38-L48
45,528
spiral/database
src/Query/AbstractQuery.php
AbstractQuery.flattenParameters
protected function flattenParameters(array $parameters): array { $result = []; foreach ($parameters as $parameter) { if ($parameter instanceof BuilderInterface) { $result = array_merge($result, $parameter->getParameters()); continue; } $result[] = $parameter; } return $result; }
php
protected function flattenParameters(array $parameters): array { $result = []; foreach ($parameters as $parameter) { if ($parameter instanceof BuilderInterface) { $result = array_merge($result, $parameter->getParameters()); continue; } $result[] = $parameter; } return $result; }
[ "protected", "function", "flattenParameters", "(", "array", "$", "parameters", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "parameters", "as", "$", "parameter", ")", "{", "if", "(", "$", "parameter", "instanceof", "Bui...
Expand all QueryBuilder parameters to create flatten list. @param array $parameters @return array
[ "Expand", "all", "QueryBuilder", "parameters", "to", "create", "flatten", "list", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/AbstractQuery.php#L112-L125
45,529
spiral/database
src/Query/Interpolator.php
Interpolator.interpolate
public static function interpolate(string $query, array $parameters = []): string { if (empty($parameters)) { return $query; } //Flattening $parameters = self::flattenParameters($parameters); //Let's prepare values so they looks better foreach ($parameters as $index => $parameter) { $value = self::resolveValue($parameter); if (is_numeric($index)) { $query = self::replaceOnce('?', $value, $query); } else { $query = str_replace($index, $value, $query); } } return $query; }
php
public static function interpolate(string $query, array $parameters = []): string { if (empty($parameters)) { return $query; } //Flattening $parameters = self::flattenParameters($parameters); //Let's prepare values so they looks better foreach ($parameters as $index => $parameter) { $value = self::resolveValue($parameter); if (is_numeric($index)) { $query = self::replaceOnce('?', $value, $query); } else { $query = str_replace($index, $value, $query); } } return $query; }
[ "public", "static", "function", "interpolate", "(", "string", "$", "query", ",", "array", "$", "parameters", "=", "[", "]", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "parameters", ")", ")", "{", "return", "$", "query", ";", "}", "//Flatt...
Helper method used to interpolate SQL query with set of parameters, must be used only for development purposes and never for real query! @param string $query @param ParameterInterface[] $parameters Parameters to be binded into query. Named list are supported. @return string
[ "Helper", "method", "used", "to", "interpolate", "SQL", "query", "with", "set", "of", "parameters", "must", "be", "used", "only", "for", "development", "purposes", "and", "never", "for", "real", "query!" ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Interpolator.php#L30-L52
45,530
spiral/database
src/Query/Interpolator.php
Interpolator.resolveValue
protected static function resolveValue($parameter): string { if ($parameter instanceof ParameterInterface) { return self::resolveValue($parameter->getValue()); } switch (gettype($parameter)) { case 'boolean': return $parameter ? 'true' : 'false'; case 'integer': return strval($parameter + 0); case 'NULL': return 'NULL'; case 'double': return sprintf('%F', $parameter); case 'string': return "'" . addcslashes($parameter, "'") . "'"; case 'object': if (method_exists($parameter, '__toString')) { return "'" . addcslashes((string)$parameter, "'") . "'"; } if ($parameter instanceof \DateTime) { //Let's process dates different way return "'" . $parameter->format(\DateTime::ISO8601) . "'"; } } return '[UNRESOLVED]'; }
php
protected static function resolveValue($parameter): string { if ($parameter instanceof ParameterInterface) { return self::resolveValue($parameter->getValue()); } switch (gettype($parameter)) { case 'boolean': return $parameter ? 'true' : 'false'; case 'integer': return strval($parameter + 0); case 'NULL': return 'NULL'; case 'double': return sprintf('%F', $parameter); case 'string': return "'" . addcslashes($parameter, "'") . "'"; case 'object': if (method_exists($parameter, '__toString')) { return "'" . addcslashes((string)$parameter, "'") . "'"; } if ($parameter instanceof \DateTime) { //Let's process dates different way return "'" . $parameter->format(\DateTime::ISO8601) . "'"; } } return '[UNRESOLVED]'; }
[ "protected", "static", "function", "resolveValue", "(", "$", "parameter", ")", ":", "string", "{", "if", "(", "$", "parameter", "instanceof", "ParameterInterface", ")", "{", "return", "self", "::", "resolveValue", "(", "$", "parameter", "->", "getValue", "(", ...
Get parameter value. @param mixed $parameter @return string
[ "Get", "parameter", "value", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Interpolator.php#L100-L134
45,531
spiral/database
src/Driver/Driver.php
Driver.connect
public function connect() { if (!$this->isConnected()) { $this->pdo = $this->createPDO(); $this->pdo->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [Statement::class]); } }
php
public function connect() { if (!$this->isConnected()) { $this->pdo = $this->createPDO(); $this->pdo->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [Statement::class]); } }
[ "public", "function", "connect", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isConnected", "(", ")", ")", "{", "$", "this", "->", "pdo", "=", "$", "this", "->", "createPDO", "(", ")", ";", "$", "this", "->", "pdo", "->", "setAttribute", "(...
Force driver connection. @throws DriverException
[ "Force", "driver", "connection", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L160-L166
45,532
spiral/database
src/Driver/Driver.php
Driver.execute
public function execute(string $query, array $parameters = []): int { return $this->statement($query, $parameters)->rowCount(); }
php
public function execute(string $query, array $parameters = []): int { return $this->statement($query, $parameters)->rowCount(); }
[ "public", "function", "execute", "(", "string", "$", "query", ",", "array", "$", "parameters", "=", "[", "]", ")", ":", "int", "{", "return", "$", "this", "->", "statement", "(", "$", "query", ",", "$", "parameters", ")", "->", "rowCount", "(", ")", ...
Execute query and return number of affected rows. @param string $query @param array $parameters @return int @throws StatementException
[ "Execute", "query", "and", "return", "number", "of", "affected", "rows", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L231-L234
45,533
spiral/database
src/Driver/Driver.php
Driver.statement
protected function statement(string $query, array $parameters = [], bool $retry = null): Statement { if (is_null($retry)) { $retry = $this->options['reconnect']; } try { $flatten = $this->flattenParameters($parameters); //Mounting all input parameters $statement = $this->bindParameters($this->prepare($query), $flatten); $statement->execute(); if ($this->isProfiling()) { $this->getLogger()->info( Interpolator::interpolate($query, $parameters), compact('query', 'parameters') ); } } catch (\PDOException $e) { $queryString = Interpolator::interpolate($query, $parameters); $this->getLogger()->error($queryString, compact('query', 'parameters')); $this->getLogger()->alert($e->getMessage()); //Converting exception into query or integrity exception $e = $this->mapException($e, $queryString); if ( $e instanceof StatementException\ConnectionException && $this->transactionLevel === 0 && $retry ) { // retrying return $this->statement($query, $parameters, false); } throw $e; } return $statement; }
php
protected function statement(string $query, array $parameters = [], bool $retry = null): Statement { if (is_null($retry)) { $retry = $this->options['reconnect']; } try { $flatten = $this->flattenParameters($parameters); //Mounting all input parameters $statement = $this->bindParameters($this->prepare($query), $flatten); $statement->execute(); if ($this->isProfiling()) { $this->getLogger()->info( Interpolator::interpolate($query, $parameters), compact('query', 'parameters') ); } } catch (\PDOException $e) { $queryString = Interpolator::interpolate($query, $parameters); $this->getLogger()->error($queryString, compact('query', 'parameters')); $this->getLogger()->alert($e->getMessage()); //Converting exception into query or integrity exception $e = $this->mapException($e, $queryString); if ( $e instanceof StatementException\ConnectionException && $this->transactionLevel === 0 && $retry ) { // retrying return $this->statement($query, $parameters, false); } throw $e; } return $statement; }
[ "protected", "function", "statement", "(", "string", "$", "query", ",", "array", "$", "parameters", "=", "[", "]", ",", "bool", "$", "retry", "=", "null", ")", ":", "Statement", "{", "if", "(", "is_null", "(", "$", "retry", ")", ")", "{", "$", "ret...
Create instance of PDOStatement using provided SQL query and set of parameters and execute it. Will attempt singular reconnect. @param string $query @param array $parameters Parameters to be binded into query. @param bool|null $retry @return Statement @throws StatementException
[ "Create", "instance", "of", "PDOStatement", "using", "provided", "SQL", "query", "and", "set", "of", "parameters", "and", "execute", "it", ".", "Will", "attempt", "singular", "reconnect", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L266-L306
45,534
spiral/database
src/Driver/Driver.php
Driver.bindParameters
protected function bindParameters(Statement $statement, array $parameters): Statement { foreach ($parameters as $index => $parameter) { if (is_numeric($index)) { //Numeric, @see http://php.net/manual/en/pdostatement.bindparam.php $statement->bindValue($index + 1, $parameter->getValue(), $parameter->getType()); } else { //Named $statement->bindValue($index, $parameter->getValue(), $parameter->getType()); } } return $statement; }
php
protected function bindParameters(Statement $statement, array $parameters): Statement { foreach ($parameters as $index => $parameter) { if (is_numeric($index)) { //Numeric, @see http://php.net/manual/en/pdostatement.bindparam.php $statement->bindValue($index + 1, $parameter->getValue(), $parameter->getType()); } else { //Named $statement->bindValue($index, $parameter->getValue(), $parameter->getType()); } } return $statement; }
[ "protected", "function", "bindParameters", "(", "Statement", "$", "statement", ",", "array", "$", "parameters", ")", ":", "Statement", "{", "foreach", "(", "$", "parameters", "as", "$", "index", "=>", "$", "parameter", ")", "{", "if", "(", "is_numeric", "(...
Bind parameters into statement. @param Statement $statement @param ParameterInterface[] $parameters Named hash of ParameterInterface. @return Statement
[ "Bind", "parameters", "into", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L389-L402
45,535
spiral/database
src/Driver/Driver.php
Driver.isolationLevel
protected function isolationLevel(string $level) { if (!empty($level)) { $this->isProfiling() && $this->getLogger()->info("Set transaction isolation level to '{$level}'"); $this->execute("SET TRANSACTION ISOLATION LEVEL {$level}"); } }
php
protected function isolationLevel(string $level) { if (!empty($level)) { $this->isProfiling() && $this->getLogger()->info("Set transaction isolation level to '{$level}'"); $this->execute("SET TRANSACTION ISOLATION LEVEL {$level}"); } }
[ "protected", "function", "isolationLevel", "(", "string", "$", "level", ")", "{", "if", "(", "!", "empty", "(", "$", "level", ")", ")", "{", "$", "this", "->", "isProfiling", "(", ")", "&&", "$", "this", "->", "getLogger", "(", ")", "->", "info", "...
Set transaction isolation level, this feature may not be supported by specific database driver. @param string $level
[ "Set", "transaction", "isolation", "level", "this", "feature", "may", "not", "be", "supported", "by", "specific", "database", "driver", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L514-L520
45,536
spiral/database
src/Driver/Driver.php
Driver.createPDO
protected function createPDO(): PDO { return new PDO( $this->options['connection'] ?? $this->options['dsn'], $this->options['username'], $this->options['password'], $this->options['options'] ); }
php
protected function createPDO(): PDO { return new PDO( $this->options['connection'] ?? $this->options['dsn'], $this->options['username'], $this->options['password'], $this->options['options'] ); }
[ "protected", "function", "createPDO", "(", ")", ":", "PDO", "{", "return", "new", "PDO", "(", "$", "this", "->", "options", "[", "'connection'", "]", "??", "$", "this", "->", "options", "[", "'dsn'", "]", ",", "$", "this", "->", "options", "[", "'use...
Create instance of configured PDO class. @return PDO
[ "Create", "instance", "of", "configured", "PDO", "class", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L588-L596
45,537
spiral/database
src/Driver/Driver.php
Driver.formatDatetime
protected function formatDatetime(\DateTimeInterface $value): string { try { $datetime = new \DateTimeImmutable('now', $this->getTimezone()); } catch (\Exception $e) { throw new DriverException($e->getMessage(), $e->getCode(), $e); } return $datetime->setTimestamp($value->getTimestamp())->format(static::DATETIME); }
php
protected function formatDatetime(\DateTimeInterface $value): string { try { $datetime = new \DateTimeImmutable('now', $this->getTimezone()); } catch (\Exception $e) { throw new DriverException($e->getMessage(), $e->getCode(), $e); } return $datetime->setTimestamp($value->getTimestamp())->format(static::DATETIME); }
[ "protected", "function", "formatDatetime", "(", "\\", "DateTimeInterface", "$", "value", ")", ":", "string", "{", "try", "{", "$", "datetime", "=", "new", "\\", "DateTimeImmutable", "(", "'now'", ",", "$", "this", "->", "getTimezone", "(", ")", ")", ";", ...
Convert DateTime object into local database representation. Driver will automatically force needed timezone. @param \DateTimeInterface $value @return string @throws DriverException
[ "Convert", "DateTime", "object", "into", "local", "database", "representation", ".", "Driver", "will", "automatically", "force", "needed", "timezone", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L623-L632
45,538
spiral/database
src/DatabaseManager.php
DatabaseManager.getDatabases
public function getDatabases(): array { $names = array_unique(array_merge(array_keys($this->databases), array_keys($this->config->getDatabases()))); $result = []; foreach ($names as $name) { $result[] = $this->database($name); } return $result; }
php
public function getDatabases(): array { $names = array_unique(array_merge(array_keys($this->databases), array_keys($this->config->getDatabases()))); $result = []; foreach ($names as $name) { $result[] = $this->database($name); } return $result; }
[ "public", "function", "getDatabases", "(", ")", ":", "array", "{", "$", "names", "=", "array_unique", "(", "array_merge", "(", "array_keys", "(", "$", "this", "->", "databases", ")", ",", "array_keys", "(", "$", "this", "->", "config", "->", "getDatabases"...
Get all databases. @return Database[] @throws DatabaseException
[ "Get", "all", "databases", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/DatabaseManager.php#L124-L134
45,539
spiral/database
src/DatabaseManager.php
DatabaseManager.database
public function database(string $database = null): DatabaseInterface { if (empty($database)) { $database = $this->config->getDefaultDatabase(); } //Spiral support ability to link multiple virtual databases together using aliases $database = $this->config->resolveAlias($database); if (isset($this->databases[$database])) { return $this->databases[$database]; } if (!$this->config->hasDatabase($database)) { throw new DBALException( "Unable to create Database, no presets for '{$database}' found" ); } return $this->databases[$database] = $this->makeDatabase( $this->config->getDatabase($database) ); }
php
public function database(string $database = null): DatabaseInterface { if (empty($database)) { $database = $this->config->getDefaultDatabase(); } //Spiral support ability to link multiple virtual databases together using aliases $database = $this->config->resolveAlias($database); if (isset($this->databases[$database])) { return $this->databases[$database]; } if (!$this->config->hasDatabase($database)) { throw new DBALException( "Unable to create Database, no presets for '{$database}' found" ); } return $this->databases[$database] = $this->makeDatabase( $this->config->getDatabase($database) ); }
[ "public", "function", "database", "(", "string", "$", "database", "=", "null", ")", ":", "DatabaseInterface", "{", "if", "(", "empty", "(", "$", "database", ")", ")", "{", "$", "database", "=", "$", "this", "->", "config", "->", "getDefaultDatabase", "("...
Get Database associated with a given database alias or automatically created one. @param string|null $database @return Database|DatabaseInterface @throws DBALException
[ "Get", "Database", "associated", "with", "a", "given", "database", "alias", "or", "automatically", "created", "one", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/DatabaseManager.php#L144-L166
45,540
spiral/database
src/DatabaseManager.php
DatabaseManager.addDatabase
public function addDatabase(Database $database) { if (isset($this->databases[$database->getName()])) { throw new DBALException("Database '{$database->getName()}' already exists"); } $this->databases[$database->getName()] = $database; }
php
public function addDatabase(Database $database) { if (isset($this->databases[$database->getName()])) { throw new DBALException("Database '{$database->getName()}' already exists"); } $this->databases[$database->getName()] = $database; }
[ "public", "function", "addDatabase", "(", "Database", "$", "database", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "databases", "[", "$", "database", "->", "getName", "(", ")", "]", ")", ")", "{", "throw", "new", "DBALException", "(", "\"Data...
Add new database. @param Database $database @throws DBALException
[ "Add", "new", "database", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/DatabaseManager.php#L175-L182
45,541
spiral/database
src/DatabaseManager.php
DatabaseManager.driver
public function driver(string $driver): DriverInterface { if (isset($this->drivers[$driver])) { return $this->drivers[$driver]; } try { return $this->drivers[$driver] = $this->config->getDriver($driver)->resolve($this->factory); } catch (ContainerExceptionInterface $e) { throw new DBALException($e->getMessage(), $e->getCode(), $e); } }
php
public function driver(string $driver): DriverInterface { if (isset($this->drivers[$driver])) { return $this->drivers[$driver]; } try { return $this->drivers[$driver] = $this->config->getDriver($driver)->resolve($this->factory); } catch (ContainerExceptionInterface $e) { throw new DBALException($e->getMessage(), $e->getCode(), $e); } }
[ "public", "function", "driver", "(", "string", "$", "driver", ")", ":", "DriverInterface", "{", "if", "(", "isset", "(", "$", "this", "->", "drivers", "[", "$", "driver", "]", ")", ")", "{", "return", "$", "this", "->", "drivers", "[", "$", "driver",...
Get driver instance by it's name or automatically create one. @param string $driver @return DriverInterface @throws DBALException
[ "Get", "driver", "instance", "by", "it", "s", "name", "or", "automatically", "create", "one", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/DatabaseManager.php#L211-L221
45,542
spiral/database
src/DatabaseManager.php
DatabaseManager.addDriver
public function addDriver(string $name, DriverInterface $driver): DatabaseManager { if (isset($this->drivers[$name])) { throw new DBALException("Connection '{$name}' already exists"); } $this->drivers[$name] = $driver; return $this; }
php
public function addDriver(string $name, DriverInterface $driver): DatabaseManager { if (isset($this->drivers[$name])) { throw new DBALException("Connection '{$name}' already exists"); } $this->drivers[$name] = $driver; return $this; }
[ "public", "function", "addDriver", "(", "string", "$", "name", ",", "DriverInterface", "$", "driver", ")", ":", "DatabaseManager", "{", "if", "(", "isset", "(", "$", "this", "->", "drivers", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "DBALEx...
Manually set connection instance. @param string $name @param DriverInterface $driver @return self @throws DBALException
[ "Manually", "set", "connection", "instance", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/DatabaseManager.php#L232-L241
45,543
spiral/database
src/Driver/Traits/BuilderTrait.php
BuilderTrait.insertQuery
public function insertQuery(string $prefix, string $table = null): InsertQuery { return new InsertQuery($this, $this->getCompiler($prefix), $table); }
php
public function insertQuery(string $prefix, string $table = null): InsertQuery { return new InsertQuery($this, $this->getCompiler($prefix), $table); }
[ "public", "function", "insertQuery", "(", "string", "$", "prefix", ",", "string", "$", "table", "=", "null", ")", ":", "InsertQuery", "{", "return", "new", "InsertQuery", "(", "$", "this", ",", "$", "this", "->", "getCompiler", "(", "$", "prefix", ")", ...
Get InsertQuery builder with driver specific query compiler. @param string $prefix Database specific table prefix, used to quote table names and build aliases. @param string|null $table @return InsertQuery
[ "Get", "InsertQuery", "builder", "with", "driver", "specific", "query", "compiler", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Traits/BuilderTrait.php#L32-L35
45,544
spiral/database
src/Driver/Traits/BuilderTrait.php
BuilderTrait.selectQuery
public function selectQuery(string $prefix, array $from = [], array $columns = []): SelectQuery { return new SelectQuery($this, $this->getCompiler($prefix), $from, $columns); }
php
public function selectQuery(string $prefix, array $from = [], array $columns = []): SelectQuery { return new SelectQuery($this, $this->getCompiler($prefix), $from, $columns); }
[ "public", "function", "selectQuery", "(", "string", "$", "prefix", ",", "array", "$", "from", "=", "[", "]", ",", "array", "$", "columns", "=", "[", "]", ")", ":", "SelectQuery", "{", "return", "new", "SelectQuery", "(", "$", "this", ",", "$", "this"...
Get SelectQuery builder with driver specific query compiler. @param string $prefix Database specific table prefix, used to quote table names and build aliases. @param array $from @param array $columns @return SelectQuery
[ "Get", "SelectQuery", "builder", "with", "driver", "specific", "query", "compiler", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Traits/BuilderTrait.php#L46-L49
45,545
spiral/database
src/Driver/Traits/BuilderTrait.php
BuilderTrait.updateQuery
public function updateQuery( string $prefix, string $table = null, array $where = [], array $values = [] ): UpdateQuery { return new UpdateQuery($this, $this->getCompiler($prefix), $table, $where, $values); }
php
public function updateQuery( string $prefix, string $table = null, array $where = [], array $values = [] ): UpdateQuery { return new UpdateQuery($this, $this->getCompiler($prefix), $table, $where, $values); }
[ "public", "function", "updateQuery", "(", "string", "$", "prefix", ",", "string", "$", "table", "=", "null", ",", "array", "$", "where", "=", "[", "]", ",", "array", "$", "values", "=", "[", "]", ")", ":", "UpdateQuery", "{", "return", "new", "Update...
Get UpdateQuery builder with driver specific query compiler. @param string $prefix Database specific table prefix, used to quote table names and build aliases. @param string|null $table @param array $where @param array $values @return UpdateQuery
[ "Get", "UpdateQuery", "builder", "with", "driver", "specific", "query", "compiler", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Traits/BuilderTrait.php#L73-L80
45,546
spiral/database
src/Query/Traits/TokenTrait.php
TokenTrait.createToken
protected function createToken($joiner, array $parameters, &$tokens, callable $wrapper) { list($identifier, $valueA, $valueB, $valueC) = $parameters + array_fill(0, 5, null); if (empty($identifier)) { //Nothing to do return; } //Where conditions specified in array form if (is_array($identifier)) { if (count($identifier) == 1) { $this->arrayWhere( $joiner == 'AND' ? Compiler::TOKEN_AND : Compiler::TOKEN_OR, $identifier, $tokens, $wrapper ); return; } $tokens[] = [$joiner, '(']; $this->arrayWhere(Compiler::TOKEN_AND, $identifier, $tokens, $wrapper); $tokens[] = ['', ')']; return; } if ($identifier instanceof \Closure) { $tokens[] = [$joiner, '(']; call_user_func($identifier, $this, $joiner, $wrapper); $tokens[] = ['', ')']; return; } if ($identifier instanceof BuilderInterface) { //Will copy every parameter from QueryBuilder $wrapper($identifier); } switch (count($parameters)) { case 1: //AND|OR [identifier: sub-query] $tokens[] = [$joiner, $identifier]; break; case 2: //AND|OR [identifier] = [valueA] $tokens[] = [$joiner, [$identifier, '=', $wrapper($valueA)]]; break; case 3: if (is_string($valueA)) { $valueA = strtoupper($valueA); if (in_array($valueA, ['BETWEEN', 'NOT BETWEEN'])) { throw new BuilderException('Between statements expects exactly 2 values'); } } //AND|OR [identifier] [valueA: OPERATION] [valueA] $tokens[] = [$joiner, [$identifier, strval($valueA), $wrapper($valueB)]]; break; case 4: //BETWEEN or NOT BETWEEN if (!is_string($valueA) || !in_array(strtoupper($valueA), ['BETWEEN', 'NOT BETWEEN'])) { throw new BuilderException( 'Only "BETWEEN" or "NOT BETWEEN" can define second comparision value' ); } //AND|OR [identifier] [valueA: BETWEEN|NOT BETWEEN] [valueB] [valueC] $tokens[] = [$joiner, [$identifier, strtoupper($valueA), $wrapper($valueB), $wrapper($valueC)]]; } }
php
protected function createToken($joiner, array $parameters, &$tokens, callable $wrapper) { list($identifier, $valueA, $valueB, $valueC) = $parameters + array_fill(0, 5, null); if (empty($identifier)) { //Nothing to do return; } //Where conditions specified in array form if (is_array($identifier)) { if (count($identifier) == 1) { $this->arrayWhere( $joiner == 'AND' ? Compiler::TOKEN_AND : Compiler::TOKEN_OR, $identifier, $tokens, $wrapper ); return; } $tokens[] = [$joiner, '(']; $this->arrayWhere(Compiler::TOKEN_AND, $identifier, $tokens, $wrapper); $tokens[] = ['', ')']; return; } if ($identifier instanceof \Closure) { $tokens[] = [$joiner, '(']; call_user_func($identifier, $this, $joiner, $wrapper); $tokens[] = ['', ')']; return; } if ($identifier instanceof BuilderInterface) { //Will copy every parameter from QueryBuilder $wrapper($identifier); } switch (count($parameters)) { case 1: //AND|OR [identifier: sub-query] $tokens[] = [$joiner, $identifier]; break; case 2: //AND|OR [identifier] = [valueA] $tokens[] = [$joiner, [$identifier, '=', $wrapper($valueA)]]; break; case 3: if (is_string($valueA)) { $valueA = strtoupper($valueA); if (in_array($valueA, ['BETWEEN', 'NOT BETWEEN'])) { throw new BuilderException('Between statements expects exactly 2 values'); } } //AND|OR [identifier] [valueA: OPERATION] [valueA] $tokens[] = [$joiner, [$identifier, strval($valueA), $wrapper($valueB)]]; break; case 4: //BETWEEN or NOT BETWEEN if (!is_string($valueA) || !in_array(strtoupper($valueA), ['BETWEEN', 'NOT BETWEEN'])) { throw new BuilderException( 'Only "BETWEEN" or "NOT BETWEEN" can define second comparision value' ); } //AND|OR [identifier] [valueA: BETWEEN|NOT BETWEEN] [valueB] [valueC] $tokens[] = [$joiner, [$identifier, strtoupper($valueA), $wrapper($valueB), $wrapper($valueC)]]; } }
[ "protected", "function", "createToken", "(", "$", "joiner", ",", "array", "$", "parameters", ",", "&", "$", "tokens", ",", "callable", "$", "wrapper", ")", "{", "list", "(", "$", "identifier", ",", "$", "valueA", ",", "$", "valueB", ",", "$", "valueC",...
Convert various amount of where function arguments into valid where token. @param string $joiner Boolean joiner (AND | OR). @param array $parameters Set of parameters collected from where functions. @param array $tokens Array to aggregate compiled tokens. Reference. @param callable $wrapper Callback or closure used to wrap/collect every potential parameter. @throws BuilderException @see AbstractWhere
[ "Convert", "various", "amount", "of", "where", "function", "arguments", "into", "valid", "where", "token", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/TokenTrait.php#L31-L104
45,547
spiral/database
src/Query/Traits/TokenTrait.php
TokenTrait.arrayWhere
private function arrayWhere(string $grouper, array $where, &$tokens, callable $wrapper) { $joiner = ($grouper == Compiler::TOKEN_AND ? 'AND' : 'OR'); foreach ($where as $key => $value) { $token = strtoupper($key); //Grouping identifier (@OR, @AND), MongoDB like style if ($token == Compiler::TOKEN_AND || $token == Compiler::TOKEN_OR) { $tokens[] = [$joiner, '(']; foreach ($value as $nested) { if (count($nested) == 1) { $this->arrayWhere($token, $nested, $tokens, $wrapper); continue; } $tokens[] = [$token == Compiler::TOKEN_AND ? 'AND' : 'OR', '(']; $this->arrayWhere(Compiler::TOKEN_AND, $nested, $tokens, $wrapper); $tokens[] = ['', ')']; } $tokens[] = ['', ')']; continue; } //AND|OR [name] = [value] if (!is_array($value)) { $tokens[] = [$joiner, [$key, '=', $wrapper($value)]]; continue; } if (count($value) > 1) { //Multiple values to be joined by AND condition (x = 1, x != 5) $tokens[] = [$joiner, '(']; $this->builtConditions('AND', $key, $value, $tokens, $wrapper); $tokens[] = ['', ')']; } else { $this->builtConditions($joiner, $key, $value, $tokens, $wrapper); } } return; }
php
private function arrayWhere(string $grouper, array $where, &$tokens, callable $wrapper) { $joiner = ($grouper == Compiler::TOKEN_AND ? 'AND' : 'OR'); foreach ($where as $key => $value) { $token = strtoupper($key); //Grouping identifier (@OR, @AND), MongoDB like style if ($token == Compiler::TOKEN_AND || $token == Compiler::TOKEN_OR) { $tokens[] = [$joiner, '(']; foreach ($value as $nested) { if (count($nested) == 1) { $this->arrayWhere($token, $nested, $tokens, $wrapper); continue; } $tokens[] = [$token == Compiler::TOKEN_AND ? 'AND' : 'OR', '(']; $this->arrayWhere(Compiler::TOKEN_AND, $nested, $tokens, $wrapper); $tokens[] = ['', ')']; } $tokens[] = ['', ')']; continue; } //AND|OR [name] = [value] if (!is_array($value)) { $tokens[] = [$joiner, [$key, '=', $wrapper($value)]]; continue; } if (count($value) > 1) { //Multiple values to be joined by AND condition (x = 1, x != 5) $tokens[] = [$joiner, '(']; $this->builtConditions('AND', $key, $value, $tokens, $wrapper); $tokens[] = ['', ')']; } else { $this->builtConditions($joiner, $key, $value, $tokens, $wrapper); } } return; }
[ "private", "function", "arrayWhere", "(", "string", "$", "grouper", ",", "array", "$", "where", ",", "&", "$", "tokens", ",", "callable", "$", "wrapper", ")", "{", "$", "joiner", "=", "(", "$", "grouper", "==", "Compiler", "::", "TOKEN_AND", "?", "'AND...
Convert simplified where definition into valid set of where tokens. @param string $grouper Grouper type (see self::TOKEN_AND, self::TOKEN_OR). @param array $where Simplified where definition. @param array $tokens Array to aggregate compiled tokens. Reference. @param callable $wrapper Callback or closure used to wrap/collect every potential parameter. @throws BuilderException @see AbstractWhere
[ "Convert", "simplified", "where", "definition", "into", "valid", "set", "of", "where", "tokens", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/TokenTrait.php#L119-L163
45,548
spiral/database
src/Query/Traits/TokenTrait.php
TokenTrait.builtConditions
private function builtConditions( string $innerJoiner, string $key, $where, &$tokens, callable $wrapper ) { foreach ($where as $operation => $value) { if (is_numeric($operation)) { throw new BuilderException('Nested conditions should have defined operator'); } $operation = strtoupper($operation); if (!in_array($operation, ['BETWEEN', 'NOT BETWEEN'])) { //AND|OR [name] [OPERATION] [nestedValue] $tokens[] = [$innerJoiner, [$key, $operation, $wrapper($value)]]; continue; } /* * Between and not between condition described using array of [left, right] syntax. */ if (!is_array($value) || count($value) != 2) { throw new BuilderException( 'Exactly 2 array values are required for between statement' ); } $tokens[] = [ //AND|OR [name] [BETWEEN|NOT BETWEEN] [value 1] [value 2] $innerJoiner, [$key, $operation, $wrapper($value[0]), $wrapper($value[1])], ]; } return $tokens; }
php
private function builtConditions( string $innerJoiner, string $key, $where, &$tokens, callable $wrapper ) { foreach ($where as $operation => $value) { if (is_numeric($operation)) { throw new BuilderException('Nested conditions should have defined operator'); } $operation = strtoupper($operation); if (!in_array($operation, ['BETWEEN', 'NOT BETWEEN'])) { //AND|OR [name] [OPERATION] [nestedValue] $tokens[] = [$innerJoiner, [$key, $operation, $wrapper($value)]]; continue; } /* * Between and not between condition described using array of [left, right] syntax. */ if (!is_array($value) || count($value) != 2) { throw new BuilderException( 'Exactly 2 array values are required for between statement' ); } $tokens[] = [ //AND|OR [name] [BETWEEN|NOT BETWEEN] [value 1] [value 2] $innerJoiner, [$key, $operation, $wrapper($value[0]), $wrapper($value[1])], ]; } return $tokens; }
[ "private", "function", "builtConditions", "(", "string", "$", "innerJoiner", ",", "string", "$", "key", ",", "$", "where", ",", "&", "$", "tokens", ",", "callable", "$", "wrapper", ")", "{", "foreach", "(", "$", "where", "as", "$", "operation", "=>", "...
Build set of conditions for specified identifier. @param string $innerJoiner Inner boolean joiner. @param string $key Column identifier. @param array $where Operations associated with identifier. @param array $tokens Array to aggregate compiled tokens. Reference. @param callable $wrapper Callback or closure used to wrap/collect every potential parameter. @return array @throws BuilderException
[ "Build", "set", "of", "conditions", "for", "specified", "identifier", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/TokenTrait.php#L179-L216
45,549
spiral/database
src/Driver/Compiler.php
Compiler.compileInsert
public function compileInsert(string $table, array $columns, array $rowsets): string { if (empty($columns)) { throw new CompilerException( 'Unable to build insert statement, columns must be set' ); } if (empty($rowsets)) { throw new CompilerException( 'Unable to build insert statement, at least one value set must be provided' ); } //To add needed prefixes (if any) $table = $this->quote($table, true); //Compiling list of columns $columns = $this->prepareColumns($columns); //Simply joining every rowset $rowsets = implode(",\n", $rowsets); return "INSERT INTO {$table} ({$columns})\nVALUES {$rowsets}"; }
php
public function compileInsert(string $table, array $columns, array $rowsets): string { if (empty($columns)) { throw new CompilerException( 'Unable to build insert statement, columns must be set' ); } if (empty($rowsets)) { throw new CompilerException( 'Unable to build insert statement, at least one value set must be provided' ); } //To add needed prefixes (if any) $table = $this->quote($table, true); //Compiling list of columns $columns = $this->prepareColumns($columns); //Simply joining every rowset $rowsets = implode(",\n", $rowsets); return "INSERT INTO {$table} ({$columns})\nVALUES {$rowsets}"; }
[ "public", "function", "compileInsert", "(", "string", "$", "table", ",", "array", "$", "columns", ",", "array", "$", "rowsets", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "columns", ")", ")", "{", "throw", "new", "CompilerException", "(", "...
Create insert query using table names, columns and rowsets. Must support both - single and batch inserts. @param string $table @param array $columns @param FragmentInterface[] $rowsets Every rowset has to be convertable into string. Raw data not allowed! @return string @throws CompilerException
[ "Create", "insert", "query", "using", "table", "names", "columns", "and", "rowsets", ".", "Must", "support", "both", "-", "single", "and", "batch", "inserts", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L102-L126
45,550
spiral/database
src/Driver/Compiler.php
Compiler.compileUpdate
public function compileUpdate(string $table, array $updates, array $whereTokens = []): string { $table = $this->quote($table, true); //Preparing update column statement $updates = $this->prepareUpdates($updates); //Where statement is optional for update queries $whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens)); return rtrim("UPDATE {$table}\nSET {$updates} {$whereStatement}"); }
php
public function compileUpdate(string $table, array $updates, array $whereTokens = []): string { $table = $this->quote($table, true); //Preparing update column statement $updates = $this->prepareUpdates($updates); //Where statement is optional for update queries $whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens)); return rtrim("UPDATE {$table}\nSET {$updates} {$whereStatement}"); }
[ "public", "function", "compileUpdate", "(", "string", "$", "table", ",", "array", "$", "updates", ",", "array", "$", "whereTokens", "=", "[", "]", ")", ":", "string", "{", "$", "table", "=", "$", "this", "->", "quote", "(", "$", "table", ",", "true",...
Create update statement. @param string $table @param array $updates @param array $whereTokens @return string @throws CompilerException
[ "Create", "update", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L139-L150
45,551
spiral/database
src/Driver/Compiler.php
Compiler.compileDelete
public function compileDelete(string $table, array $whereTokens = []): string { $table = $this->quote($table, true); //Where statement is optional for delete query (which is weird) $whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens)); return rtrim("DELETE FROM {$table} {$whereStatement}"); }
php
public function compileDelete(string $table, array $whereTokens = []): string { $table = $this->quote($table, true); //Where statement is optional for delete query (which is weird) $whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens)); return rtrim("DELETE FROM {$table} {$whereStatement}"); }
[ "public", "function", "compileDelete", "(", "string", "$", "table", ",", "array", "$", "whereTokens", "=", "[", "]", ")", ":", "string", "{", "$", "table", "=", "$", "this", "->", "quote", "(", "$", "table", ",", "true", ")", ";", "//Where statement is...
Create delete statement. @param string $table @param array $whereTokens @return string @throws CompilerException
[ "Create", "delete", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L162-L170
45,552
spiral/database
src/Driver/Compiler.php
Compiler.compileSelect
public function compileSelect( array $fromTables, $distinct, array $columns, array $joinTokens = [], array $whereTokens = [], array $havingTokens = [], array $grouping = [], array $ordering = [], int $limit = 0, int $offset = 0, array $unionTokens = [] ): string { //This statement parts should be processed first to define set of table and column aliases $fromTables = $this->compileTables($fromTables); $joinsStatement = $this->optional(' ', $this->compileJoins($joinTokens), ' '); //Distinct flag (if any) $distinct = $this->optional(' ', $this->compileDistinct($distinct)); //Columns are compiled after table names and joins to ensure aliases and prefixes $columns = $this->prepareColumns($columns); //A lot of constrain and other statements $whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens)); $havingStatement = $this->optional("\nHAVING", $this->compileWhere($havingTokens)); $groupingStatement = $this->optional("\nGROUP BY", $this->compileGrouping($grouping), ' '); //Union statement has new line at beginning of every union $unionsStatement = $this->optional("\n", $this->compileUnions($unionTokens)); $orderingStatement = $this->optional("\nORDER BY", $this->compileOrdering($ordering)); $limingStatement = $this->optional("\n", $this->compileLimit($limit, $offset)); //Initial statement have predictable order $statement = "SELECT{$distinct}\n{$columns}\nFROM {$fromTables}"; $statement .= "{$joinsStatement}{$whereStatement}{$groupingStatement}{$havingStatement}"; $statement .= "{$unionsStatement}{$orderingStatement}{$limingStatement}"; return rtrim($statement); }
php
public function compileSelect( array $fromTables, $distinct, array $columns, array $joinTokens = [], array $whereTokens = [], array $havingTokens = [], array $grouping = [], array $ordering = [], int $limit = 0, int $offset = 0, array $unionTokens = [] ): string { //This statement parts should be processed first to define set of table and column aliases $fromTables = $this->compileTables($fromTables); $joinsStatement = $this->optional(' ', $this->compileJoins($joinTokens), ' '); //Distinct flag (if any) $distinct = $this->optional(' ', $this->compileDistinct($distinct)); //Columns are compiled after table names and joins to ensure aliases and prefixes $columns = $this->prepareColumns($columns); //A lot of constrain and other statements $whereStatement = $this->optional("\nWHERE", $this->compileWhere($whereTokens)); $havingStatement = $this->optional("\nHAVING", $this->compileWhere($havingTokens)); $groupingStatement = $this->optional("\nGROUP BY", $this->compileGrouping($grouping), ' '); //Union statement has new line at beginning of every union $unionsStatement = $this->optional("\n", $this->compileUnions($unionTokens)); $orderingStatement = $this->optional("\nORDER BY", $this->compileOrdering($ordering)); $limingStatement = $this->optional("\n", $this->compileLimit($limit, $offset)); //Initial statement have predictable order $statement = "SELECT{$distinct}\n{$columns}\nFROM {$fromTables}"; $statement .= "{$joinsStatement}{$whereStatement}{$groupingStatement}{$havingStatement}"; $statement .= "{$unionsStatement}{$orderingStatement}{$limingStatement}"; return rtrim($statement); }
[ "public", "function", "compileSelect", "(", "array", "$", "fromTables", ",", "$", "distinct", ",", "array", "$", "columns", ",", "array", "$", "joinTokens", "=", "[", "]", ",", "array", "$", "whereTokens", "=", "[", "]", ",", "array", "$", "havingTokens"...
Create select statement. Compiler must validly resolve table and column aliases used in conditions and joins. @param array $fromTables @param bool|string $distinct String only for PostgresSQL. @param array $columns @param array $joinTokens @param array $whereTokens @param array $havingTokens @param array $grouping @param array $ordering @param int $limit @param int $offset @param array $unionTokens @return string @throws CompilerException
[ "Create", "select", "statement", ".", "Compiler", "must", "validly", "resolve", "table", "and", "column", "aliases", "used", "in", "conditions", "and", "joins", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L192-L233
45,553
spiral/database
src/Driver/Compiler.php
Compiler.prepareUpdates
protected function prepareUpdates(array $updates): string { foreach ($updates as $column => &$value) { if ($value instanceof FragmentInterface) { $value = $this->prepareFragment($value); } else { //Simple value (such condition should never be met since every value has to be //wrapped using parameter interface) $value = '?'; } $value = "{$this->quote($column)} = {$value}"; unset($value); } return trim(implode(', ', $updates)); }
php
protected function prepareUpdates(array $updates): string { foreach ($updates as $column => &$value) { if ($value instanceof FragmentInterface) { $value = $this->prepareFragment($value); } else { //Simple value (such condition should never be met since every value has to be //wrapped using parameter interface) $value = '?'; } $value = "{$this->quote($column)} = {$value}"; unset($value); } return trim(implode(', ', $updates)); }
[ "protected", "function", "prepareUpdates", "(", "array", "$", "updates", ")", ":", "string", "{", "foreach", "(", "$", "updates", "as", "$", "column", "=>", "&", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "FragmentInterface", ")", "{"...
Prepare column values to be used in UPDATE statement. @param array $updates @return string
[ "Prepare", "column", "values", "to", "be", "used", "in", "UPDATE", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L258-L274
45,554
spiral/database
src/Driver/Compiler.php
Compiler.compileTables
protected function compileTables(array $tables): string { foreach ($tables as &$table) { $table = $this->quote($table, true); unset($table); } return implode(', ', $tables); }
php
protected function compileTables(array $tables): string { foreach ($tables as &$table) { $table = $this->quote($table, true); unset($table); } return implode(', ', $tables); }
[ "protected", "function", "compileTables", "(", "array", "$", "tables", ")", ":", "string", "{", "foreach", "(", "$", "tables", "as", "&", "$", "table", ")", "{", "$", "table", "=", "$", "this", "->", "quote", "(", "$", "table", ",", "true", ")", ";...
Compile table names statement. @param array $tables @return string
[ "Compile", "table", "names", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L299-L307
45,555
spiral/database
src/Driver/Compiler.php
Compiler.compileJoins
protected function compileJoins(array $joinTokens): string { $statement = ''; foreach ($joinTokens as $join) { $statement .= "\n{$join['type']} JOIN {$this->quote($join['outer'], true)}"; if (!empty($join['alias'])) { $this->quoter->registerAlias($join['alias'], (string)$join['outer']); $statement .= " AS " . $this->quote($join['alias']); } $statement .= $this->optional("\n ON", $this->compileWhere($join['on'])); } return $statement; }
php
protected function compileJoins(array $joinTokens): string { $statement = ''; foreach ($joinTokens as $join) { $statement .= "\n{$join['type']} JOIN {$this->quote($join['outer'], true)}"; if (!empty($join['alias'])) { $this->quoter->registerAlias($join['alias'], (string)$join['outer']); $statement .= " AS " . $this->quote($join['alias']); } $statement .= $this->optional("\n ON", $this->compileWhere($join['on'])); } return $statement; }
[ "protected", "function", "compileJoins", "(", "array", "$", "joinTokens", ")", ":", "string", "{", "$", "statement", "=", "''", ";", "foreach", "(", "$", "joinTokens", "as", "$", "join", ")", "{", "$", "statement", ".=", "\"\\n{$join['type']} JOIN {$this->quot...
Compiler joins statement. @param array $joinTokens @return string
[ "Compiler", "joins", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L316-L331
45,556
spiral/database
src/Driver/Compiler.php
Compiler.compileUnions
protected function compileUnions(array $unionTokens): string { if (empty($unionTokens)) { return ''; } $statement = ''; foreach ($unionTokens as $union) { if (!empty($union[0])) { //First key is union type, second united query (no need to share compiler) $statement .= "\nUNION {$union[0]}\n({$union[1]})"; } else { //No extra space $statement .= "\nUNION \n({$union[1]})"; } } return ltrim($statement, "\n"); }
php
protected function compileUnions(array $unionTokens): string { if (empty($unionTokens)) { return ''; } $statement = ''; foreach ($unionTokens as $union) { if (!empty($union[0])) { //First key is union type, second united query (no need to share compiler) $statement .= "\nUNION {$union[0]}\n({$union[1]})"; } else { //No extra space $statement .= "\nUNION \n({$union[1]})"; } } return ltrim($statement, "\n"); }
[ "protected", "function", "compileUnions", "(", "array", "$", "unionTokens", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "unionTokens", ")", ")", "{", "return", "''", ";", "}", "$", "statement", "=", "''", ";", "foreach", "(", "$", "unionToke...
Compile union statement chunk. Keywords UNION and ALL will be included, this methods will automatically move every union on new line. @param array $unionTokens @return string
[ "Compile", "union", "statement", "chunk", ".", "Keywords", "UNION", "and", "ALL", "will", "be", "included", "this", "methods", "will", "automatically", "move", "every", "union", "on", "new", "line", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L341-L359
45,557
spiral/database
src/Driver/Compiler.php
Compiler.compileOrdering
protected function compileOrdering(array $ordering): string { $result = []; foreach ($ordering as $order) { $direction = strtoupper($order[1]); if (!in_array($direction, ['ASC', 'DESC'])) { throw new CompilerException("Invalid sorting direction, only ASC and DESC are allowed"); } $result[] = $this->quote($order[0]) . ' ' . $direction; } return implode(', ', $result); }
php
protected function compileOrdering(array $ordering): string { $result = []; foreach ($ordering as $order) { $direction = strtoupper($order[1]); if (!in_array($direction, ['ASC', 'DESC'])) { throw new CompilerException("Invalid sorting direction, only ASC and DESC are allowed"); } $result[] = $this->quote($order[0]) . ' ' . $direction; } return implode(', ', $result); }
[ "protected", "function", "compileOrdering", "(", "array", "$", "ordering", ")", ":", "string", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "ordering", "as", "$", "order", ")", "{", "$", "direction", "=", "strtoupper", "(", "$", "order"...
Compile ORDER BY statement. @param array $ordering @return string
[ "Compile", "ORDER", "BY", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L368-L382
45,558
spiral/database
src/Driver/Compiler.php
Compiler.compileGrouping
protected function compileGrouping(array $grouping): string { $statement = ''; foreach ($grouping as $identifier) { $statement .= $this->quote($identifier); } return $statement; }
php
protected function compileGrouping(array $grouping): string { $statement = ''; foreach ($grouping as $identifier) { $statement .= $this->quote($identifier); } return $statement; }
[ "protected", "function", "compileGrouping", "(", "array", "$", "grouping", ")", ":", "string", "{", "$", "statement", "=", "''", ";", "foreach", "(", "$", "grouping", "as", "$", "identifier", ")", "{", "$", "statement", ".=", "$", "this", "->", "quote", ...
Compiler GROUP BY statement. @param array $grouping @return string
[ "Compiler", "GROUP", "BY", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L391-L399
45,559
spiral/database
src/Driver/Compiler.php
Compiler.compileLimit
protected function compileLimit(int $limit, int $offset): string { if (empty($limit) && empty($offset)) { return ''; } $statement = ''; if (!empty($limit)) { $statement = "LIMIT {$limit} "; } if (!empty($offset)) { $statement .= "OFFSET {$offset}"; } return trim($statement); }
php
protected function compileLimit(int $limit, int $offset): string { if (empty($limit) && empty($offset)) { return ''; } $statement = ''; if (!empty($limit)) { $statement = "LIMIT {$limit} "; } if (!empty($offset)) { $statement .= "OFFSET {$offset}"; } return trim($statement); }
[ "protected", "function", "compileLimit", "(", "int", "$", "limit", ",", "int", "$", "offset", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "limit", ")", "&&", "empty", "(", "$", "offset", ")", ")", "{", "return", "''", ";", "}", "$", "s...
Compile limit statement. @param int $limit @param int $offset @return string
[ "Compile", "limit", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L409-L425
45,560
spiral/database
src/Driver/Compiler.php
Compiler.compileWhere
protected function compileWhere(array $tokens): string { if (empty($tokens)) { return ''; } $statement = ''; $activeGroup = true; foreach ($tokens as $condition) { //OR/AND keyword $boolean = $condition[0]; //See AbstractWhere $context = $condition[1]; //First condition in group/query, no any AND, OR required if ($activeGroup) { //Kill AND, OR and etc. $boolean = ''; //Next conditions require AND or OR $activeGroup = false; } /* * When context is string it usually represent control keyword/syntax such as opening * or closing braces. */ if (is_string($context)) { if ($context == '(') { //New where group. $activeGroup = true; } $statement .= ltrim("{$boolean} {$context} "); if ($context == ')') { //We don't need trailing space $statement = rtrim($statement); } continue; } if ($context instanceof FragmentInterface) { //Fragments has to be compiled separately $statement .= "{$boolean} {$this->prepareFragment($context)} "; continue; } //Now we are operating with "class" where function, where we need 3 variables where(id, =, 1) if (!is_array($context)) { throw new CompilerException('Invalid where token, context expected to be an array'); } /* * This is "normal" where token which includes identifier, operator and value. */ list($identifier, $operator, $value) = $context; //Identifier can be column name, expression or even query builder $identifier = $this->quote($identifier); //Value has to be prepared as well $placeholder = $this->prepareValue($value); if ($operator == 'BETWEEN' || $operator == 'NOT BETWEEN') { //Between statement has additional parameter $right = $this->prepareValue($context[3]); $statement .= "{$boolean} {$identifier} {$operator} {$placeholder} AND {$right} "; continue; } //Compiler can switch equal to IN if value points to array (do we need it?) $operator = $this->prepareOperator($value, $operator); $statement .= "{$boolean} {$identifier} {$operator} {$placeholder} "; } if ($activeGroup) { throw new CompilerException('Unable to build where statement, unclosed where group'); } return trim($statement); }
php
protected function compileWhere(array $tokens): string { if (empty($tokens)) { return ''; } $statement = ''; $activeGroup = true; foreach ($tokens as $condition) { //OR/AND keyword $boolean = $condition[0]; //See AbstractWhere $context = $condition[1]; //First condition in group/query, no any AND, OR required if ($activeGroup) { //Kill AND, OR and etc. $boolean = ''; //Next conditions require AND or OR $activeGroup = false; } /* * When context is string it usually represent control keyword/syntax such as opening * or closing braces. */ if (is_string($context)) { if ($context == '(') { //New where group. $activeGroup = true; } $statement .= ltrim("{$boolean} {$context} "); if ($context == ')') { //We don't need trailing space $statement = rtrim($statement); } continue; } if ($context instanceof FragmentInterface) { //Fragments has to be compiled separately $statement .= "{$boolean} {$this->prepareFragment($context)} "; continue; } //Now we are operating with "class" where function, where we need 3 variables where(id, =, 1) if (!is_array($context)) { throw new CompilerException('Invalid where token, context expected to be an array'); } /* * This is "normal" where token which includes identifier, operator and value. */ list($identifier, $operator, $value) = $context; //Identifier can be column name, expression or even query builder $identifier = $this->quote($identifier); //Value has to be prepared as well $placeholder = $this->prepareValue($value); if ($operator == 'BETWEEN' || $operator == 'NOT BETWEEN') { //Between statement has additional parameter $right = $this->prepareValue($context[3]); $statement .= "{$boolean} {$identifier} {$operator} {$placeholder} AND {$right} "; continue; } //Compiler can switch equal to IN if value points to array (do we need it?) $operator = $this->prepareOperator($value, $operator); $statement .= "{$boolean} {$identifier} {$operator} {$placeholder} "; } if ($activeGroup) { throw new CompilerException('Unable to build where statement, unclosed where group'); } return trim($statement); }
[ "protected", "function", "compileWhere", "(", "array", "$", "tokens", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "tokens", ")", ")", "{", "return", "''", ";", "}", "$", "statement", "=", "''", ";", "$", "activeGroup", "=", "true", ";", ...
Compile where statement. @param array $tokens @return string @throws CompilerException
[ "Compile", "where", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L436-L522
45,561
spiral/database
src/Driver/Compiler.php
Compiler.prepareFragment
protected function prepareFragment(FragmentInterface $context): string { if ($context instanceof BuilderInterface) { //Nested queries has to be wrapped with braces return '(' . $context->sqlStatement($this) . ')'; } if ($context instanceof ExpressionInterface) { //Fragments does not need braces around them return $context->sqlStatement($this); } return $context->sqlStatement(); }
php
protected function prepareFragment(FragmentInterface $context): string { if ($context instanceof BuilderInterface) { //Nested queries has to be wrapped with braces return '(' . $context->sqlStatement($this) . ')'; } if ($context instanceof ExpressionInterface) { //Fragments does not need braces around them return $context->sqlStatement($this); } return $context->sqlStatement(); }
[ "protected", "function", "prepareFragment", "(", "FragmentInterface", "$", "context", ")", ":", "string", "{", "if", "(", "$", "context", "instanceof", "BuilderInterface", ")", "{", "//Nested queries has to be wrapped with braces", "return", "'('", ".", "$", "context"...
Prepare where fragment to be injected into statement. @param FragmentInterface $context @return string
[ "Prepare", "where", "fragment", "to", "be", "injected", "into", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Compiler.php#L599-L612
45,562
spiral/database
src/Schema/State.php
State.getPrimaryKeys
public function getPrimaryKeys(): array { $primaryColumns = []; foreach ($this->getColumns() as $column) { if ($column->getAbstractType() == 'primary' || $column->getAbstractType() == 'bigPrimary') { if (!in_array($column->getName(), $this->primaryKeys)) { //Only columns not listed as primary keys already $primaryColumns[] = $column->getName(); } } } return array_unique(array_merge($this->primaryKeys, $primaryColumns)); }
php
public function getPrimaryKeys(): array { $primaryColumns = []; foreach ($this->getColumns() as $column) { if ($column->getAbstractType() == 'primary' || $column->getAbstractType() == 'bigPrimary') { if (!in_array($column->getName(), $this->primaryKeys)) { //Only columns not listed as primary keys already $primaryColumns[] = $column->getName(); } } } return array_unique(array_merge($this->primaryKeys, $primaryColumns)); }
[ "public", "function", "getPrimaryKeys", "(", ")", ":", "array", "{", "$", "primaryColumns", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getColumns", "(", ")", "as", "$", "column", ")", "{", "if", "(", "$", "column", "->", "getAbstractType",...
Method combines primary keys with primary keys automatically calculated based on registered columns. @return array
[ "Method", "combines", "primary", "keys", "with", "primary", "keys", "automatically", "calculated", "based", "on", "registered", "columns", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L101-L114
45,563
spiral/database
src/Schema/State.php
State.forgetColumn
public function forgetColumn(AbstractColumn $column): State { foreach ($this->columns as $name => $columnSchema) { if ($columnSchema == $column) { unset($this->columns[$name]); break; } } return $this; }
php
public function forgetColumn(AbstractColumn $column): State { foreach ($this->columns as $name => $columnSchema) { if ($columnSchema == $column) { unset($this->columns[$name]); break; } } return $this; }
[ "public", "function", "forgetColumn", "(", "AbstractColumn", "$", "column", ")", ":", "State", "{", "foreach", "(", "$", "this", "->", "columns", "as", "$", "name", "=>", "$", "columnSchema", ")", "{", "if", "(", "$", "columnSchema", "==", "$", "column",...
Drop column from table schema. @param AbstractColumn $column @return self
[ "Drop", "column", "from", "table", "schema", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L173-L183
45,564
spiral/database
src/Schema/State.php
State.forgetIndex
public function forgetIndex(AbstractIndex $index) { foreach ($this->indexes as $name => $indexSchema) { if ($indexSchema == $index) { unset($this->indexes[$name]); break; } } }
php
public function forgetIndex(AbstractIndex $index) { foreach ($this->indexes as $name => $indexSchema) { if ($indexSchema == $index) { unset($this->indexes[$name]); break; } } }
[ "public", "function", "forgetIndex", "(", "AbstractIndex", "$", "index", ")", "{", "foreach", "(", "$", "this", "->", "indexes", "as", "$", "name", "=>", "$", "indexSchema", ")", "{", "if", "(", "$", "indexSchema", "==", "$", "index", ")", "{", "unset"...
Drop index from table schema using it's name or forming columns. @param AbstractIndex $index
[ "Drop", "index", "from", "table", "schema", "using", "it", "s", "name", "or", "forming", "columns", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L190-L198
45,565
spiral/database
src/Schema/State.php
State.forgerForeignKey
public function forgerForeignKey(AbstractForeignKey $foreignKey) { foreach ($this->foreignKeys as $name => $foreignSchema) { if ($foreignSchema == $foreignKey) { unset($this->foreignKeys[$name]); break; } } }
php
public function forgerForeignKey(AbstractForeignKey $foreignKey) { foreach ($this->foreignKeys as $name => $foreignSchema) { if ($foreignSchema == $foreignKey) { unset($this->foreignKeys[$name]); break; } } }
[ "public", "function", "forgerForeignKey", "(", "AbstractForeignKey", "$", "foreignKey", ")", "{", "foreach", "(", "$", "this", "->", "foreignKeys", "as", "$", "name", "=>", "$", "foreignSchema", ")", "{", "if", "(", "$", "foreignSchema", "==", "$", "foreignK...
Drop foreign key from table schema using it's forming column. @param AbstractForeignKey $foreignKey
[ "Drop", "foreign", "key", "from", "table", "schema", "using", "it", "s", "forming", "column", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L205-L213
45,566
spiral/database
src/Schema/State.php
State.findIndex
public function findIndex(array $columns): ?AbstractIndex { foreach ($this->indexes as $index) { if ($index->getColumns() == $columns) { return $index; } } return null; }
php
public function findIndex(array $columns): ?AbstractIndex { foreach ($this->indexes as $index) { if ($index->getColumns() == $columns) { return $index; } } return null; }
[ "public", "function", "findIndex", "(", "array", "$", "columns", ")", ":", "?", "AbstractIndex", "{", "foreach", "(", "$", "this", "->", "indexes", "as", "$", "index", ")", "{", "if", "(", "$", "index", "->", "getColumns", "(", ")", "==", "$", "colum...
Find index by it's columns or return null. @param array $columns @return null|AbstractIndex
[ "Find", "index", "by", "it", "s", "columns", "or", "return", "null", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L236-L245
45,567
spiral/database
src/Schema/State.php
State.findForeignKey
public function findForeignKey(string $column): ?AbstractForeignKey { foreach ($this->foreignKeys as $reference) { if ($reference->getColumn() == $column) { return $reference; } } return null; }
php
public function findForeignKey(string $column): ?AbstractForeignKey { foreach ($this->foreignKeys as $reference) { if ($reference->getColumn() == $column) { return $reference; } } return null; }
[ "public", "function", "findForeignKey", "(", "string", "$", "column", ")", ":", "?", "AbstractForeignKey", "{", "foreach", "(", "$", "this", "->", "foreignKeys", "as", "$", "reference", ")", "{", "if", "(", "$", "reference", "->", "getColumn", "(", ")", ...
Find foreign key by it's column or return null. @param string $column @return null|AbstractForeignKey
[ "Find", "foreign", "key", "by", "it", "s", "column", "or", "return", "null", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L253-L262
45,568
spiral/database
src/Schema/State.php
State.remountElements
public function remountElements() { $columns = []; foreach ($this->columns as $column) { $columns[$column->getName()] = $column; } $indexes = []; foreach ($this->indexes as $index) { $indexes[$index->getName()] = $index; } $foreignKeys = []; foreach ($this->foreignKeys as $foreignKey) { $foreignKeys[$foreignKey->getName()] = $foreignKey; } $this->columns = $columns; $this->indexes = $indexes; $this->foreignKeys = $foreignKeys; }
php
public function remountElements() { $columns = []; foreach ($this->columns as $column) { $columns[$column->getName()] = $column; } $indexes = []; foreach ($this->indexes as $index) { $indexes[$index->getName()] = $index; } $foreignKeys = []; foreach ($this->foreignKeys as $foreignKey) { $foreignKeys[$foreignKey->getName()] = $foreignKey; } $this->columns = $columns; $this->indexes = $indexes; $this->foreignKeys = $foreignKeys; }
[ "public", "function", "remountElements", "(", ")", "{", "$", "columns", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "columns", "as", "$", "column", ")", "{", "$", "columns", "[", "$", "column", "->", "getName", "(", ")", "]", "=", "$", ...
Remount elements under their current name.
[ "Remount", "elements", "under", "their", "current", "name", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L267-L287
45,569
spiral/database
src/Schema/State.php
State.syncState
public function syncState(State $source): self { $this->name = $source->name; $this->primaryKeys = $source->primaryKeys; $this->columns = []; foreach ($source->columns as $name => $column) { $this->columns[$name] = clone $column; } $this->indexes = []; foreach ($source->indexes as $name => $index) { $this->indexes[$name] = clone $index; } $this->foreignKeys = []; foreach ($source->foreignKeys as $name => $foreignKey) { $this->foreignKeys[$name] = clone $foreignKey; } $this->remountElements(); return $this; }
php
public function syncState(State $source): self { $this->name = $source->name; $this->primaryKeys = $source->primaryKeys; $this->columns = []; foreach ($source->columns as $name => $column) { $this->columns[$name] = clone $column; } $this->indexes = []; foreach ($source->indexes as $name => $index) { $this->indexes[$name] = clone $index; } $this->foreignKeys = []; foreach ($source->foreignKeys as $name => $foreignKey) { $this->foreignKeys[$name] = clone $foreignKey; } $this->remountElements(); return $this; }
[ "public", "function", "syncState", "(", "State", "$", "source", ")", ":", "self", "{", "$", "this", "->", "name", "=", "$", "source", "->", "name", ";", "$", "this", "->", "primaryKeys", "=", "$", "source", "->", "primaryKeys", ";", "$", "this", "->"...
Re-populate schema elements using other state as source. Elements will be cloned under their schema name. @param State $source @return self
[ "Re", "-", "populate", "schema", "elements", "using", "other", "state", "as", "source", ".", "Elements", "will", "be", "cloned", "under", "their", "schema", "name", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/State.php#L297-L320
45,570
spiral/database
src/Schema/AbstractColumn.php
AbstractColumn.getAbstractType
public function getAbstractType(): string { foreach ($this->reverseMapping as $type => $candidates) { foreach ($candidates as $candidate) { if (is_string($candidate)) { if (strtolower($candidate) == strtolower($this->type)) { return $type; } continue; } if (strtolower($candidate['type']) != strtolower($this->type)) { continue; } foreach ($candidate as $option => $required) { if ($option == 'type') { continue; } if ($this->{$option} != $required) { continue 2; } } return $type; } } return 'unknown'; }
php
public function getAbstractType(): string { foreach ($this->reverseMapping as $type => $candidates) { foreach ($candidates as $candidate) { if (is_string($candidate)) { if (strtolower($candidate) == strtolower($this->type)) { return $type; } continue; } if (strtolower($candidate['type']) != strtolower($this->type)) { continue; } foreach ($candidate as $option => $required) { if ($option == 'type') { continue; } if ($this->{$option} != $required) { continue 2; } } return $type; } } return 'unknown'; }
[ "public", "function", "getAbstractType", "(", ")", ":", "string", "{", "foreach", "(", "$", "this", "->", "reverseMapping", "as", "$", "type", "=>", "$", "candidates", ")", "{", "foreach", "(", "$", "candidates", "as", "$", "candidate", ")", "{", "if", ...
DBMS specific reverse mapping must map database specific type into limited set of abstract types. @return string
[ "DBMS", "specific", "reverse", "mapping", "must", "map", "database", "specific", "type", "into", "limited", "set", "of", "abstract", "types", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractColumn.php#L380-L411
45,571
spiral/database
src/Schema/AbstractColumn.php
AbstractColumn.type
public function type(string $abstract): AbstractColumn { if (isset($this->aliases[$abstract])) { //Make recursive $abstract = $this->aliases[$abstract]; } if (!isset($this->mapping[$abstract])) { throw new SchemaException("Undefined abstract/virtual type '{$abstract}'"); } //Resetting all values to default state. $this->size = $this->precision = $this->scale = 0; $this->enumValues = []; //Abstract type points to DBMS specific type if (is_string($this->mapping[$abstract])) { $this->type = $this->mapping[$abstract]; return $this; } //Configuring column properties based on abstractType preferences foreach ($this->mapping[$abstract] as $property => $value) { $this->{$property} = $value; } return $this; }
php
public function type(string $abstract): AbstractColumn { if (isset($this->aliases[$abstract])) { //Make recursive $abstract = $this->aliases[$abstract]; } if (!isset($this->mapping[$abstract])) { throw new SchemaException("Undefined abstract/virtual type '{$abstract}'"); } //Resetting all values to default state. $this->size = $this->precision = $this->scale = 0; $this->enumValues = []; //Abstract type points to DBMS specific type if (is_string($this->mapping[$abstract])) { $this->type = $this->mapping[$abstract]; return $this; } //Configuring column properties based on abstractType preferences foreach ($this->mapping[$abstract] as $property => $value) { $this->{$property} = $value; } return $this; }
[ "public", "function", "type", "(", "string", "$", "abstract", ")", ":", "AbstractColumn", "{", "if", "(", "isset", "(", "$", "this", "->", "aliases", "[", "$", "abstract", "]", ")", ")", "{", "//Make recursive", "$", "abstract", "=", "$", "this", "->",...
Give column new abstract type. DBMS specific implementation must map provided type into one of internal database values. Attention, changing type of existed columns in some databases has a lot of restrictions like cross type conversions and etc. Try do not change column type without a reason. @param string $abstract Abstract or virtual type declared in mapping. @return self|$this @throws SchemaException @todo Support native database types (simply bypass abstractType)!
[ "Give", "column", "new", "abstract", "type", ".", "DBMS", "specific", "implementation", "must", "map", "provided", "type", "into", "one", "of", "internal", "database", "values", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractColumn.php#L427-L455
45,572
spiral/database
src/Schema/AbstractColumn.php
AbstractColumn.enum
public function enum($values): AbstractColumn { $this->type('enum'); $this->enumValues = array_map('strval', is_array($values) ? $values : func_get_args()); return $this; }
php
public function enum($values): AbstractColumn { $this->type('enum'); $this->enumValues = array_map('strval', is_array($values) ? $values : func_get_args()); return $this; }
[ "public", "function", "enum", "(", "$", "values", ")", ":", "AbstractColumn", "{", "$", "this", "->", "type", "(", "'enum'", ")", ";", "$", "this", "->", "enumValues", "=", "array_map", "(", "'strval'", ",", "is_array", "(", "$", "values", ")", "?", ...
Set column as enum type and specify set of allowed values. Most of drivers will emulate enums using column constraints. Examples: $table->status->enum(['active', 'disabled']); $table->status->enum('active', 'disabled'); @param string|array $values Enum values (array or comma separated). String values only. @return self
[ "Set", "column", "as", "enum", "type", "and", "specify", "set", "of", "allowed", "values", ".", "Most", "of", "drivers", "will", "emulate", "enums", "using", "column", "constraints", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractColumn.php#L500-L506
45,573
spiral/database
src/Schema/AbstractColumn.php
AbstractColumn.string
public function string(int $size = 255): AbstractColumn { $this->type('string'); if ($size > 255) { throw new SchemaException("String size can't exceed 255 characters. Use text instead"); } if ($size < 0) { throw new SchemaException('Invalid string length value'); } $this->size = (int)$size; return $this; }
php
public function string(int $size = 255): AbstractColumn { $this->type('string'); if ($size > 255) { throw new SchemaException("String size can't exceed 255 characters. Use text instead"); } if ($size < 0) { throw new SchemaException('Invalid string length value'); } $this->size = (int)$size; return $this; }
[ "public", "function", "string", "(", "int", "$", "size", "=", "255", ")", ":", "AbstractColumn", "{", "$", "this", "->", "type", "(", "'string'", ")", ";", "if", "(", "$", "size", ">", "255", ")", "{", "throw", "new", "SchemaException", "(", "\"Strin...
Set column type as string with limited size. Maximum allowed size is 255 bytes, use "text" abstract types for longer strings. Strings are perfect type to store email addresses as it big enough to store valid address and can be covered with unique index. @link http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address @param int $size Max string length. @return self|$this @throws SchemaException
[ "Set", "column", "type", "as", "string", "with", "limited", "size", ".", "Maximum", "allowed", "size", "is", "255", "bytes", "use", "text", "abstract", "types", "for", "longer", "strings", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractColumn.php#L523-L538
45,574
spiral/database
src/Schema/AbstractColumn.php
AbstractColumn.decimal
public function decimal(int $precision, int $scale = 0): AbstractColumn { $this->type('decimal'); if (empty($precision)) { throw new SchemaException('Invalid precision value'); } $this->precision = (int)$precision; $this->scale = (int)$scale; return $this; }
php
public function decimal(int $precision, int $scale = 0): AbstractColumn { $this->type('decimal'); if (empty($precision)) { throw new SchemaException('Invalid precision value'); } $this->precision = (int)$precision; $this->scale = (int)$scale; return $this; }
[ "public", "function", "decimal", "(", "int", "$", "precision", ",", "int", "$", "scale", "=", "0", ")", ":", "AbstractColumn", "{", "$", "this", "->", "type", "(", "'decimal'", ")", ";", "if", "(", "empty", "(", "$", "precision", ")", ")", "{", "th...
Set column type as decimal with specific precision and scale. @param int $precision @param int $scale @return self|$this @throws SchemaException
[ "Set", "column", "type", "as", "decimal", "with", "specific", "precision", "and", "scale", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractColumn.php#L549-L561
45,575
spiral/database
src/Schema/AbstractColumn.php
AbstractColumn.quoteEnum
protected function quoteEnum(DriverInterface $driver): string { $enumValues = []; foreach ($this->enumValues as $value) { $enumValues[] = $driver->quote($value); } if (!empty($enumValues)) { return '(' . implode(', ', $enumValues) . ')'; } return ''; }
php
protected function quoteEnum(DriverInterface $driver): string { $enumValues = []; foreach ($this->enumValues as $value) { $enumValues[] = $driver->quote($value); } if (!empty($enumValues)) { return '(' . implode(', ', $enumValues) . ')'; } return ''; }
[ "protected", "function", "quoteEnum", "(", "DriverInterface", "$", "driver", ")", ":", "string", "{", "$", "enumValues", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "enumValues", "as", "$", "value", ")", "{", "$", "enumValues", "[", "]", "="...
Get database specific enum type definition options. @param DriverInterface $driver @return string
[ "Get", "database", "specific", "enum", "type", "definition", "options", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractColumn.php#L694-L706
45,576
spiral/database
src/Schema/AbstractColumn.php
AbstractColumn.quoteDefault
protected function quoteDefault(DriverInterface $driver): string { $defaultValue = $this->getDefaultValue(); if ($defaultValue === null) { return 'NULL'; } if ($defaultValue instanceof FragmentInterface) { return $defaultValue->sqlStatement(); } if ($this->getType() == 'bool') { return $defaultValue ? 'TRUE' : 'FALSE'; } if ($this->getType() == 'float') { return sprintf('%F', $defaultValue); } if ($this->getType() == 'int') { return strval($defaultValue); } return strval($driver->quote($defaultValue)); }
php
protected function quoteDefault(DriverInterface $driver): string { $defaultValue = $this->getDefaultValue(); if ($defaultValue === null) { return 'NULL'; } if ($defaultValue instanceof FragmentInterface) { return $defaultValue->sqlStatement(); } if ($this->getType() == 'bool') { return $defaultValue ? 'TRUE' : 'FALSE'; } if ($this->getType() == 'float') { return sprintf('%F', $defaultValue); } if ($this->getType() == 'int') { return strval($defaultValue); } return strval($driver->quote($defaultValue)); }
[ "protected", "function", "quoteDefault", "(", "DriverInterface", "$", "driver", ")", ":", "string", "{", "$", "defaultValue", "=", "$", "this", "->", "getDefaultValue", "(", ")", ";", "if", "(", "$", "defaultValue", "===", "null", ")", "{", "return", "'NUL...
Must return driver specific default value. @param DriverInterface $driver @return string
[ "Must", "return", "driver", "specific", "default", "value", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractColumn.php#L714-L738
45,577
spiral/database
src/Query/Traits/WhereTrait.php
WhereTrait.where
public function where(...$args): self { $this->createToken('AND', $args, $this->whereTokens, $this->whereWrapper()); return $this; }
php
public function where(...$args): self { $this->createToken('AND', $args, $this->whereTokens, $this->whereWrapper()); return $this; }
[ "public", "function", "where", "(", "...", "$", "args", ")", ":", "self", "{", "$", "this", "->", "createToken", "(", "'AND'", ",", "$", "args", ",", "$", "this", "->", "whereTokens", ",", "$", "this", "->", "whereWrapper", "(", ")", ")", ";", "ret...
Simple WHERE condition with various set of arguments. @param mixed ...$args [(column, value), (column, operator, value)] @return self|$this @throws BuilderException @see AbstractWhere
[ "Simple", "WHERE", "condition", "with", "various", "set", "of", "arguments", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/WhereTrait.php#L47-L52
45,578
spiral/database
src/Query/Traits/WhereTrait.php
WhereTrait.andWhere
public function andWhere(...$args): self { $this->createToken('AND', $args, $this->whereTokens, $this->whereWrapper()); return $this; }
php
public function andWhere(...$args): self { $this->createToken('AND', $args, $this->whereTokens, $this->whereWrapper()); return $this; }
[ "public", "function", "andWhere", "(", "...", "$", "args", ")", ":", "self", "{", "$", "this", "->", "createToken", "(", "'AND'", ",", "$", "args", ",", "$", "this", "->", "whereTokens", ",", "$", "this", "->", "whereWrapper", "(", ")", ")", ";", "...
Simple AND WHERE condition with various set of arguments. @param mixed ...$args [(column, value), (column, operator, value)] @return self|$this @throws BuilderException @see AbstractWhere
[ "Simple", "AND", "WHERE", "condition", "with", "various", "set", "of", "arguments", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/WhereTrait.php#L65-L70
45,579
spiral/database
src/Query/Traits/WhereTrait.php
WhereTrait.orWhere
public function orWhere(...$args): self { $this->createToken('OR', $args, $this->whereTokens, $this->whereWrapper()); return $this; }
php
public function orWhere(...$args): self { $this->createToken('OR', $args, $this->whereTokens, $this->whereWrapper()); return $this; }
[ "public", "function", "orWhere", "(", "...", "$", "args", ")", ":", "self", "{", "$", "this", "->", "createToken", "(", "'OR'", ",", "$", "args", ",", "$", "this", "->", "whereTokens", ",", "$", "this", "->", "whereWrapper", "(", ")", ")", ";", "re...
Simple OR WHERE condition with various set of arguments. @param mixed ...$args [(column, value), (column, operator, value)] @return self|$this @throws BuilderException @see AbstractWhere
[ "Simple", "OR", "WHERE", "condition", "with", "various", "set", "of", "arguments", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/WhereTrait.php#L83-L88
45,580
spiral/database
src/Query/Traits/WhereTrait.php
WhereTrait.whereWrapper
private function whereWrapper() { return function ($parameter) { if ($parameter instanceof FragmentInterface) { //We are only not creating bindings for plan fragments if (!$parameter instanceof ParameterInterface && !$parameter instanceof BuilderInterface) { return $parameter; } } if (is_array($parameter)) { throw new BuilderException('Arrays must be wrapped with Parameter instance'); } //Wrapping all values with ParameterInterface if (!$parameter instanceof ParameterInterface && !$parameter instanceof ExpressionInterface) { $parameter = new Parameter($parameter, Parameter::DETECT_TYPE); }; //Let's store to sent to driver when needed $this->whereParameters[] = $parameter; return $parameter; }; }
php
private function whereWrapper() { return function ($parameter) { if ($parameter instanceof FragmentInterface) { //We are only not creating bindings for plan fragments if (!$parameter instanceof ParameterInterface && !$parameter instanceof BuilderInterface) { return $parameter; } } if (is_array($parameter)) { throw new BuilderException('Arrays must be wrapped with Parameter instance'); } //Wrapping all values with ParameterInterface if (!$parameter instanceof ParameterInterface && !$parameter instanceof ExpressionInterface) { $parameter = new Parameter($parameter, Parameter::DETECT_TYPE); }; //Let's store to sent to driver when needed $this->whereParameters[] = $parameter; return $parameter; }; }
[ "private", "function", "whereWrapper", "(", ")", "{", "return", "function", "(", "$", "parameter", ")", "{", "if", "(", "$", "parameter", "instanceof", "FragmentInterface", ")", "{", "//We are only not creating bindings for plan fragments", "if", "(", "!", "$", "p...
Applied to every potential parameter while where tokens generation. Used to prepare and collect where parameters. @return \Closure
[ "Applied", "to", "every", "potential", "parameter", "while", "where", "tokens", "generation", ".", "Used", "to", "prepare", "and", "collect", "where", "parameters", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/WhereTrait.php#L116-L140
45,581
spiral/database
src/Driver/SQLServer/SQLServerDriver.php
SQLServerDriver.bindParameters
protected function bindParameters(Statement $statement, array $parameters): Statement { foreach ($parameters as $index => $parameter) { if (is_numeric($index)) { if ($parameter->getType() == PDO::PARAM_LOB) { $value = $parameter->getValue(); $statement->bindParam( $index + 1, $value, $parameter->getType(), 0, PDO::SQLSRV_ENCODING_BINARY ); continue; } //Numeric, @see http://php.net/manual/en/pdostatement.bindparam.php $statement->bindValue($index + 1, $parameter->getValue(), $parameter->getType()); } else { //Named $statement->bindValue($index, $parameter->getValue(), $parameter->getType()); } } return $statement; }
php
protected function bindParameters(Statement $statement, array $parameters): Statement { foreach ($parameters as $index => $parameter) { if (is_numeric($index)) { if ($parameter->getType() == PDO::PARAM_LOB) { $value = $parameter->getValue(); $statement->bindParam( $index + 1, $value, $parameter->getType(), 0, PDO::SQLSRV_ENCODING_BINARY ); continue; } //Numeric, @see http://php.net/manual/en/pdostatement.bindparam.php $statement->bindValue($index + 1, $parameter->getValue(), $parameter->getType()); } else { //Named $statement->bindValue($index, $parameter->getValue(), $parameter->getType()); } } return $statement; }
[ "protected", "function", "bindParameters", "(", "Statement", "$", "statement", ",", "array", "$", "parameters", ")", ":", "Statement", "{", "foreach", "(", "$", "parameters", "as", "$", "index", "=>", "$", "parameter", ")", "{", "if", "(", "is_numeric", "(...
Bind parameters into statement. SQLServer need encoding to be specified for binary parameters. @param Statement $statement @param ParameterInterface[] $parameters Named hash of ParameterInterface. @return Statement
[ "Bind", "parameters", "into", "statement", ".", "SQLServer", "need", "encoding", "to", "be", "specified", "for", "binary", "parameters", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/SQLServer/SQLServerDriver.php#L104-L129
45,582
spiral/database
src/Driver/SQLServer/SQLServerDriver.php
SQLServerDriver.savepointCreate
protected function savepointCreate(int $level) { $this->isProfiling() && $this->getLogger()->info("Transaction: new savepoint 'SVP{$level}'"); $this->execute('SAVE TRANSACTION ' . $this->identifier("SVP{$level}")); }
php
protected function savepointCreate(int $level) { $this->isProfiling() && $this->getLogger()->info("Transaction: new savepoint 'SVP{$level}'"); $this->execute('SAVE TRANSACTION ' . $this->identifier("SVP{$level}")); }
[ "protected", "function", "savepointCreate", "(", "int", "$", "level", ")", "{", "$", "this", "->", "isProfiling", "(", ")", "&&", "$", "this", "->", "getLogger", "(", ")", "->", "info", "(", "\"Transaction: new savepoint 'SVP{$level}'\"", ")", ";", "$", "thi...
Create nested transaction save point. @link http://en.wikipedia.org/wiki/Savepoint @param int $level Savepoint name/id, must not contain spaces and be valid database identifier.
[ "Create", "nested", "transaction", "save", "point", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/SQLServer/SQLServerDriver.php#L139-L143
45,583
spiral/database
src/Table.php
Table.getSchema
public function getSchema(): AbstractTable { return $this->database->getDriver(DatabaseInterface::WRITE)->getSchema($this->name, $this->database->getPrefix()); }
php
public function getSchema(): AbstractTable { return $this->database->getDriver(DatabaseInterface::WRITE)->getSchema($this->name, $this->database->getPrefix()); }
[ "public", "function", "getSchema", "(", ")", ":", "AbstractTable", "{", "return", "$", "this", "->", "database", "->", "getDriver", "(", "DatabaseInterface", "::", "WRITE", ")", "->", "getSchema", "(", "$", "this", "->", "name", ",", "$", "this", "->", "...
Get modifiable table schema. @return AbstractTable
[ "Get", "modifiable", "table", "schema", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Table.php#L82-L86
45,584
spiral/database
src/Table.php
Table.insertOne
public function insertOne(array $rowset = []): int { return $this->database->insert($this->name)->values($rowset)->run(); }
php
public function insertOne(array $rowset = []): int { return $this->database->insert($this->name)->values($rowset)->run(); }
[ "public", "function", "insertOne", "(", "array", "$", "rowset", "=", "[", "]", ")", ":", "int", "{", "return", "$", "this", "->", "database", "->", "insert", "(", "$", "this", "->", "name", ")", "->", "values", "(", "$", "rowset", ")", "->", "run",...
Insert one fieldset into table and return last inserted id. Example: $table->insertOne(["name" => "Wolfy-J", "balance" => 10]); @param array $rowset @return int @throws BuilderException
[ "Insert", "one", "fieldset", "into", "table", "and", "return", "last", "inserted", "id", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Table.php#L107-L110
45,585
spiral/database
src/Table.php
Table.insertMultiple
public function insertMultiple(array $columns = [], array $rowsets = []) { //No return value $this->database->insert($this->name)->columns($columns)->values($rowsets)->run(); }
php
public function insertMultiple(array $columns = [], array $rowsets = []) { //No return value $this->database->insert($this->name)->columns($columns)->values($rowsets)->run(); }
[ "public", "function", "insertMultiple", "(", "array", "$", "columns", "=", "[", "]", ",", "array", "$", "rowsets", "=", "[", "]", ")", "{", "//No return value", "$", "this", "->", "database", "->", "insert", "(", "$", "this", "->", "name", ")", "->", ...
Perform batch insert into table, every rowset should have identical amount of values matched with column names provided in first argument. Method will return lastInsertID on success. Example: $table->insertMultiple(["name", "balance"], array(["Bob", 10], ["Jack", 20])) @param array $columns Array of columns. @param array $rowsets Array of rowsets.
[ "Perform", "batch", "insert", "into", "table", "every", "rowset", "should", "have", "identical", "amount", "of", "values", "matched", "with", "column", "names", "provided", "in", "first", "argument", ".", "Method", "will", "return", "lastInsertID", "on", "succes...
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Table.php#L122-L126
45,586
spiral/database
src/Table.php
Table.select
public function select($columns = '*'): SelectQuery { return $this->database->select(func_num_args() ? func_get_args() : '*')->from($this->name); }
php
public function select($columns = '*'): SelectQuery { return $this->database->select(func_num_args() ? func_get_args() : '*')->from($this->name); }
[ "public", "function", "select", "(", "$", "columns", "=", "'*'", ")", ":", "SelectQuery", "{", "return", "$", "this", "->", "database", "->", "select", "(", "func_num_args", "(", ")", "?", "func_get_args", "(", ")", ":", "'*'", ")", "->", "from", "(", ...
Get SelectQuery builder with pre-populated from tables. @param string $columns @return SelectQuery
[ "Get", "SelectQuery", "builder", "with", "pre", "-", "populated", "from", "tables", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Table.php#L145-L148
45,587
spiral/database
src/Schema/AbstractTable.php
AbstractTable.setName
public function setName(string $name): string { $this->current->setName($this->prefix . $name); return $this->getName(); }
php
public function setName(string $name): string { $this->current->setName($this->prefix . $name); return $this->getName(); }
[ "public", "function", "setName", "(", "string", "$", "name", ")", ":", "string", "{", "$", "this", "->", "current", "->", "setName", "(", "$", "this", "->", "prefix", ".", "$", "name", ")", ";", "return", "$", "this", "->", "getName", "(", ")", ";"...
Sets table name. Use this function in combination with save to rename table. @param string $name @return string Prefixed table name.
[ "Sets", "table", "name", ".", "Use", "this", "function", "in", "combination", "with", "save", "to", "rename", "table", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L185-L190
45,588
spiral/database
src/Schema/AbstractTable.php
AbstractTable.declareDropped
public function declareDropped() { if ($this->status == self::STATUS_NEW) { throw new SchemaException("Unable to drop non existed table"); } //Declaring as dropped $this->status = self::STATUS_DECLARED_DROPPED; }
php
public function declareDropped() { if ($this->status == self::STATUS_NEW) { throw new SchemaException("Unable to drop non existed table"); } //Declaring as dropped $this->status = self::STATUS_DECLARED_DROPPED; }
[ "public", "function", "declareDropped", "(", ")", "{", "if", "(", "$", "this", "->", "status", "==", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "SchemaException", "(", "\"Unable to drop non existed table\"", ")", ";", "}", "//Declaring as dropped", "$...
Declare table as dropped, you have to sync table using "save" method in order to apply this change. Attention, method will flush declared FKs to ensure that table express no dependecies.
[ "Declare", "table", "as", "dropped", "you", "have", "to", "sync", "table", "using", "save", "method", "in", "order", "to", "apply", "this", "change", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L216-L224
45,589
spiral/database
src/Schema/AbstractTable.php
AbstractTable.dropColumn
public function dropColumn(string $column): AbstractTable { if (empty($schema = $this->current->findColumn($column))) { throw new SchemaException("Undefined column '{$column}' in '{$this->getName()}'"); } //Dropping column from current schema $this->current->forgetColumn($schema); return $this; }
php
public function dropColumn(string $column): AbstractTable { if (empty($schema = $this->current->findColumn($column))) { throw new SchemaException("Undefined column '{$column}' in '{$this->getName()}'"); } //Dropping column from current schema $this->current->forgetColumn($schema); return $this; }
[ "public", "function", "dropColumn", "(", "string", "$", "column", ")", ":", "AbstractTable", "{", "if", "(", "empty", "(", "$", "schema", "=", "$", "this", "->", "current", "->", "findColumn", "(", "$", "column", ")", ")", ")", "{", "throw", "new", "...
Drop column by it's name. @param string $column @return self @throws SchemaException
[ "Drop", "column", "by", "it", "s", "name", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L510-L520
45,590
spiral/database
src/Schema/AbstractTable.php
AbstractTable.dropIndex
public function dropIndex(array $columns): AbstractTable { if (empty($schema = $this->current->findIndex($columns))) { throw new SchemaException( "Undefined index ['" . join("', '", $columns) . "'] in '{$this->getName()}'" ); } //Dropping index from current schema $this->current->forgetIndex($schema); return $this; }
php
public function dropIndex(array $columns): AbstractTable { if (empty($schema = $this->current->findIndex($columns))) { throw new SchemaException( "Undefined index ['" . join("', '", $columns) . "'] in '{$this->getName()}'" ); } //Dropping index from current schema $this->current->forgetIndex($schema); return $this; }
[ "public", "function", "dropIndex", "(", "array", "$", "columns", ")", ":", "AbstractTable", "{", "if", "(", "empty", "(", "$", "schema", "=", "$", "this", "->", "current", "->", "findIndex", "(", "$", "columns", ")", ")", ")", "{", "throw", "new", "S...
Drop index by it's forming columns. @param array $columns @return self @throws SchemaException
[ "Drop", "index", "by", "it", "s", "forming", "columns", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L530-L542
45,591
spiral/database
src/Schema/AbstractTable.php
AbstractTable.dropForeignKey
public function dropForeignKey(string $column): AbstractTable { if (empty($schema = $this->current->findForeignKey($column))) { throw new SchemaException("Undefined FK on '{$column}' in '{$this->getName()}'"); } //Dropping foreign from current schema $this->current->forgerForeignKey($schema); return $this; }
php
public function dropForeignKey(string $column): AbstractTable { if (empty($schema = $this->current->findForeignKey($column))) { throw new SchemaException("Undefined FK on '{$column}' in '{$this->getName()}'"); } //Dropping foreign from current schema $this->current->forgerForeignKey($schema); return $this; }
[ "public", "function", "dropForeignKey", "(", "string", "$", "column", ")", ":", "AbstractTable", "{", "if", "(", "empty", "(", "$", "schema", "=", "$", "this", "->", "current", "->", "findForeignKey", "(", "$", "column", ")", ")", ")", "{", "throw", "n...
Drop foreign key by it's name. @param string $column @return self @throws SchemaException
[ "Drop", "foreign", "key", "by", "it", "s", "name", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L552-L562
45,592
spiral/database
src/Schema/AbstractTable.php
AbstractTable.setState
public function setState(State $state = null): AbstractTable { $this->current = new State($this->initial->getName()); if (!empty($state)) { $this->current->setName($state->getName()); $this->current->syncState($state); } return $this; }
php
public function setState(State $state = null): AbstractTable { $this->current = new State($this->initial->getName()); if (!empty($state)) { $this->current->setName($state->getName()); $this->current->syncState($state); } return $this; }
[ "public", "function", "setState", "(", "State", "$", "state", "=", "null", ")", ":", "AbstractTable", "{", "$", "this", "->", "current", "=", "new", "State", "(", "$", "this", "->", "initial", "->", "getName", "(", ")", ")", ";", "if", "(", "!", "e...
Reset table state to new form. @param State $state Use null to flush table schema. @return self|$this
[ "Reset", "table", "state", "to", "new", "form", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L584-L594
45,593
spiral/database
src/Schema/AbstractTable.php
AbstractTable.normalizeSchema
protected function normalizeSchema(bool $withForeignKeys = true) { // To make sure that no pre-sync modifications will be reflected on current table $target = clone $this; // declare all FKs dropped on tables scheduled for removal if ($this->status === self::STATUS_DECLARED_DROPPED) { foreach ($target->getForeignKeys() as $fk) { $target->current->forgerForeignKey($fk); } } /* * In cases where columns are removed we have to automatically remove related indexes and * foreign keys. */ foreach ($this->getComparator()->droppedColumns() as $column) { foreach ($target->getIndexes() as $index) { if (in_array($column->getName(), $index->getColumns())) { $target->current->forgetIndex($index); } } foreach ($target->getForeignKeys() as $foreign) { if ($column->getName() == $foreign->getColumn()) { $target->current->forgerForeignKey($foreign); } } } //We also have to adjusts indexes and foreign keys foreach ($this->getComparator()->alteredColumns() as $pair) { /** * @var AbstractColumn $initial * @var AbstractColumn $name */ list($name, $initial) = $pair; foreach ($target->getIndexes() as $index) { if (in_array($initial->getName(), $index->getColumns())) { $columns = $index->getColumns(); //Replacing column name foreach ($columns as &$column) { if ($column == $initial->getName()) { $column = $name->getName(); } unset($column); } $targetIndex = $target->initial->findIndex($index->getColumns()); if (!empty($targetIndex)) { //Target index got renamed or removed. $targetIndex->columns($columns); } $index->columns($columns); } } foreach ($target->getForeignKeys() as $foreign) { if ($initial->getName() == $foreign->getColumn()) { $foreign->column($name->getName()); } } } if (!$withForeignKeys) { foreach ($this->getComparator()->addedForeignKeys() as $foreign) { //Excluding from creation $target->current->forgerForeignKey($foreign); } } return $target; }
php
protected function normalizeSchema(bool $withForeignKeys = true) { // To make sure that no pre-sync modifications will be reflected on current table $target = clone $this; // declare all FKs dropped on tables scheduled for removal if ($this->status === self::STATUS_DECLARED_DROPPED) { foreach ($target->getForeignKeys() as $fk) { $target->current->forgerForeignKey($fk); } } /* * In cases where columns are removed we have to automatically remove related indexes and * foreign keys. */ foreach ($this->getComparator()->droppedColumns() as $column) { foreach ($target->getIndexes() as $index) { if (in_array($column->getName(), $index->getColumns())) { $target->current->forgetIndex($index); } } foreach ($target->getForeignKeys() as $foreign) { if ($column->getName() == $foreign->getColumn()) { $target->current->forgerForeignKey($foreign); } } } //We also have to adjusts indexes and foreign keys foreach ($this->getComparator()->alteredColumns() as $pair) { /** * @var AbstractColumn $initial * @var AbstractColumn $name */ list($name, $initial) = $pair; foreach ($target->getIndexes() as $index) { if (in_array($initial->getName(), $index->getColumns())) { $columns = $index->getColumns(); //Replacing column name foreach ($columns as &$column) { if ($column == $initial->getName()) { $column = $name->getName(); } unset($column); } $targetIndex = $target->initial->findIndex($index->getColumns()); if (!empty($targetIndex)) { //Target index got renamed or removed. $targetIndex->columns($columns); } $index->columns($columns); } } foreach ($target->getForeignKeys() as $foreign) { if ($initial->getName() == $foreign->getColumn()) { $foreign->column($name->getName()); } } } if (!$withForeignKeys) { foreach ($this->getComparator()->addedForeignKeys() as $foreign) { //Excluding from creation $target->current->forgerForeignKey($foreign); } } return $target; }
[ "protected", "function", "normalizeSchema", "(", "bool", "$", "withForeignKeys", "=", "true", ")", "{", "// To make sure that no pre-sync modifications will be reflected on current table", "$", "target", "=", "clone", "$", "this", ";", "// declare all FKs dropped on tables sche...
Ensure that no wrong indexes left in table. This method will create AbstracTable copy in order to prevent cross modifications. @param bool $withForeignKeys @return AbstractTable
[ "Ensure", "that", "no", "wrong", "indexes", "left", "in", "table", ".", "This", "method", "will", "create", "AbstracTable", "copy", "in", "order", "to", "prevent", "cross", "modifications", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L664-L740
45,594
spiral/database
src/Schema/AbstractTable.php
AbstractTable.createIdentifier
protected function createIdentifier(string $type, array $columns): string { $name = $this->getName() . '_' . $type . '_' . join('_', $columns) . '_' . uniqid(); if (strlen($name) > 64) { //Many DBMS has limitations on identifier length $name = md5($name); } return $name; }
php
protected function createIdentifier(string $type, array $columns): string { $name = $this->getName() . '_' . $type . '_' . join('_', $columns) . '_' . uniqid(); if (strlen($name) > 64) { //Many DBMS has limitations on identifier length $name = md5($name); } return $name; }
[ "protected", "function", "createIdentifier", "(", "string", "$", "type", ",", "array", "$", "columns", ")", ":", "string", "{", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ".", "'_'", ".", "$", "type", ".", "'_'", ".", "join", "(", "'...
Generate unique name for indexes and foreign keys. @param string $type @param array $columns @return string
[ "Generate", "unique", "name", "for", "indexes", "and", "foreign", "keys", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/AbstractTable.php#L861-L871
45,595
spiral/database
src/Query/Traits/HavingTrait.php
HavingTrait.having
public function having(...$args): self { $this->createToken('AND', $args, $this->havingTokens, $this->havingWrapper()); return $this; }
php
public function having(...$args): self { $this->createToken('AND', $args, $this->havingTokens, $this->havingWrapper()); return $this; }
[ "public", "function", "having", "(", "...", "$", "args", ")", ":", "self", "{", "$", "this", "->", "createToken", "(", "'AND'", ",", "$", "args", ",", "$", "this", "->", "havingTokens", ",", "$", "this", "->", "havingWrapper", "(", ")", ")", ";", "...
Simple HAVING condition with various set of arguments. @param mixed ...$args [(column, value), (column, operator, value)] @return self|$this @throws BuilderException @see AbstractWhere
[ "Simple", "HAVING", "condition", "with", "various", "set", "of", "arguments", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/HavingTrait.php#L50-L55
45,596
spiral/database
src/Query/Traits/HavingTrait.php
HavingTrait.andHaving
public function andHaving(...$args): self { $this->createToken('AND', $args, $this->havingTokens, $this->havingWrapper()); return $this; }
php
public function andHaving(...$args): self { $this->createToken('AND', $args, $this->havingTokens, $this->havingWrapper()); return $this; }
[ "public", "function", "andHaving", "(", "...", "$", "args", ")", ":", "self", "{", "$", "this", "->", "createToken", "(", "'AND'", ",", "$", "args", ",", "$", "this", "->", "havingTokens", ",", "$", "this", "->", "havingWrapper", "(", ")", ")", ";", ...
Simple AND HAVING condition with various set of arguments. @param mixed ...$args [(column, value), (column, operator, value)] @return self|$this @throws BuilderException @see AbstractWhere
[ "Simple", "AND", "HAVING", "condition", "with", "various", "set", "of", "arguments", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/HavingTrait.php#L67-L72
45,597
spiral/database
src/Query/Traits/HavingTrait.php
HavingTrait.orHaving
public function orHaving(...$args): self { $this->createToken('OR', $args, $this->havingTokens, $this->havingWrapper()); return $this; }
php
public function orHaving(...$args): self { $this->createToken('OR', $args, $this->havingTokens, $this->havingWrapper()); return $this; }
[ "public", "function", "orHaving", "(", "...", "$", "args", ")", ":", "self", "{", "$", "this", "->", "createToken", "(", "'OR'", ",", "$", "args", ",", "$", "this", "->", "havingTokens", ",", "$", "this", "->", "havingWrapper", "(", ")", ")", ";", ...
Simple OR HAVING condition with various set of arguments. @param mixed ...$args [(column, value), (column, operator, value)] @return self|$this @throws BuilderException @see AbstractWhere
[ "Simple", "OR", "HAVING", "condition", "with", "various", "set", "of", "arguments", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/HavingTrait.php#L85-L90
45,598
spiral/database
src/Query/Traits/HavingTrait.php
HavingTrait.havingWrapper
private function havingWrapper() { return function ($parameter) { if ($parameter instanceof FragmentInterface) { //We are only not creating bindings for plan fragments if (!$parameter instanceof ParameterInterface && !$parameter instanceof BuilderInterface) { return $parameter; } } if (is_array($parameter)) { throw new BuilderException('Arrays must be wrapped with Parameter instance'); } //Wrapping all values with ParameterInterface if (!$parameter instanceof ParameterInterface && !$parameter instanceof ExpressionInterface) { $parameter = new Parameter($parameter, Parameter::DETECT_TYPE); }; //Let's store to sent to driver when needed $this->havingParameters[] = $parameter; return $parameter; }; }
php
private function havingWrapper() { return function ($parameter) { if ($parameter instanceof FragmentInterface) { //We are only not creating bindings for plan fragments if (!$parameter instanceof ParameterInterface && !$parameter instanceof BuilderInterface) { return $parameter; } } if (is_array($parameter)) { throw new BuilderException('Arrays must be wrapped with Parameter instance'); } //Wrapping all values with ParameterInterface if (!$parameter instanceof ParameterInterface && !$parameter instanceof ExpressionInterface) { $parameter = new Parameter($parameter, Parameter::DETECT_TYPE); }; //Let's store to sent to driver when needed $this->havingParameters[] = $parameter; return $parameter; }; }
[ "private", "function", "havingWrapper", "(", ")", "{", "return", "function", "(", "$", "parameter", ")", "{", "if", "(", "$", "parameter", "instanceof", "FragmentInterface", ")", "{", "//We are only not creating bindings for plan fragments", "if", "(", "!", "$", "...
Applied to every potential parameter while having tokens generation. @return \Closure
[ "Applied", "to", "every", "potential", "parameter", "while", "having", "tokens", "generation", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Traits/HavingTrait.php#L117-L142
45,599
spiral/database
src/Schema/Reflector.php
Reflector.addTable
public function addTable(AbstractTable $table) { $this->tables[$table->getName()] = $table; $this->dependencies[$table->getName()] = $table->getDependencies(); $this->collectDrivers(); }
php
public function addTable(AbstractTable $table) { $this->tables[$table->getName()] = $table; $this->dependencies[$table->getName()] = $table->getDependencies(); $this->collectDrivers(); }
[ "public", "function", "addTable", "(", "AbstractTable", "$", "table", ")", "{", "$", "this", "->", "tables", "[", "$", "table", "->", "getName", "(", ")", "]", "=", "$", "table", ";", "$", "this", "->", "dependencies", "[", "$", "table", "->", "getNa...
Add table to the collection. @param AbstractTable $table
[ "Add", "table", "to", "the", "collection", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Schema/Reflector.php#L44-L50