repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addActionTriggerFeature
public function addActionTriggerFeature($actionName, $eventLabel = ScriptLabel::MOUSECLICK) { $actionTrigger = new ActionTrigger($actionName, $this, $eventLabel); $this->addScriptFeature($actionTrigger); return $this; }
php
public function addActionTriggerFeature($actionName, $eventLabel = ScriptLabel::MOUSECLICK) { $actionTrigger = new ActionTrigger($actionName, $this, $eventLabel); $this->addScriptFeature($actionTrigger); return $this; }
[ "public", "function", "addActionTriggerFeature", "(", "$", "actionName", ",", "$", "eventLabel", "=", "ScriptLabel", "::", "MOUSECLICK", ")", "{", "$", "actionTrigger", "=", "new", "ActionTrigger", "(", "$", "actionName", ",", "$", "this", ",", "$", "eventLabel", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "actionTrigger", ")", ";", "return", "$", "this", ";", "}" ]
Add a dynamic Action Trigger @api @param string $actionName Action to trigger @param string $eventLabel (optional) Event on which the action is triggered @return static
[ "Add", "a", "dynamic", "Action", "Trigger" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L820-L825
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addMapInfoFeature
public function addMapInfoFeature($eventLabel = ScriptLabel::MOUSECLICK) { $mapInfo = new MapInfo($this, $eventLabel); $this->addScriptFeature($mapInfo); return $this; }
php
public function addMapInfoFeature($eventLabel = ScriptLabel::MOUSECLICK) { $mapInfo = new MapInfo($this, $eventLabel); $this->addScriptFeature($mapInfo); return $this; }
[ "public", "function", "addMapInfoFeature", "(", "$", "eventLabel", "=", "ScriptLabel", "::", "MOUSECLICK", ")", "{", "$", "mapInfo", "=", "new", "MapInfo", "(", "$", "this", ",", "$", "eventLabel", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "mapInfo", ")", ";", "return", "$", "this", ";", "}" ]
Add a dynamic Feature opening the current map info @api @param string $eventLabel (optional) Event on which the map info will be opened @return static
[ "Add", "a", "dynamic", "Feature", "opening", "the", "current", "map", "info" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L834-L839
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addPlayerProfileFeature
public function addPlayerProfileFeature($login, $eventLabel = ScriptLabel::MOUSECLICK) { $playerProfile = new PlayerProfile($login, $this, $eventLabel); $this->addScriptFeature($playerProfile); return $this; }
php
public function addPlayerProfileFeature($login, $eventLabel = ScriptLabel::MOUSECLICK) { $playerProfile = new PlayerProfile($login, $this, $eventLabel); $this->addScriptFeature($playerProfile); return $this; }
[ "public", "function", "addPlayerProfileFeature", "(", "$", "login", ",", "$", "eventLabel", "=", "ScriptLabel", "::", "MOUSECLICK", ")", "{", "$", "playerProfile", "=", "new", "PlayerProfile", "(", "$", "login", ",", "$", "this", ",", "$", "eventLabel", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "playerProfile", ")", ";", "return", "$", "this", ";", "}" ]
Add a dynamic Feature to open a specific player profile @api @param string $login Login of the player @param string $eventLabel (optional) Event on which the player profile will be opened @return static
[ "Add", "a", "dynamic", "Feature", "to", "open", "a", "specific", "player", "profile" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L849-L854
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addUISoundFeature
public function addUISoundFeature($soundName, $variant = 0, $eventLabel = ScriptLabel::MOUSECLICK) { $uiSound = new UISound($soundName, $this, $variant, $eventLabel); $this->addScriptFeature($uiSound); return $this; }
php
public function addUISoundFeature($soundName, $variant = 0, $eventLabel = ScriptLabel::MOUSECLICK) { $uiSound = new UISound($soundName, $this, $variant, $eventLabel); $this->addScriptFeature($uiSound); return $this; }
[ "public", "function", "addUISoundFeature", "(", "$", "soundName", ",", "$", "variant", "=", "0", ",", "$", "eventLabel", "=", "ScriptLabel", "::", "MOUSECLICK", ")", "{", "$", "uiSound", "=", "new", "UISound", "(", "$", "soundName", ",", "$", "this", ",", "$", "variant", ",", "$", "eventLabel", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "uiSound", ")", ";", "return", "$", "this", ";", "}" ]
Add a dynamic Feature playing a UISound @api @param string $soundName UISound name @param int $variant (optional) Sound variant @param string $eventLabel (optional) Event on which the sound will be played @return static
[ "Add", "a", "dynamic", "Feature", "playing", "a", "UISound" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L865-L870
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addToggleFeature
public function addToggleFeature(Control $toggledControl, $labelName = ScriptLabel::MOUSECLICK, $onlyShow = false, $onlyHide = false) { $toggle = new Toggle($this, $toggledControl, $labelName, $onlyShow, $onlyHide); $this->addScriptFeature($toggle); return $this; }
php
public function addToggleFeature(Control $toggledControl, $labelName = ScriptLabel::MOUSECLICK, $onlyShow = false, $onlyHide = false) { $toggle = new Toggle($this, $toggledControl, $labelName, $onlyShow, $onlyHide); $this->addScriptFeature($toggle); return $this; }
[ "public", "function", "addToggleFeature", "(", "Control", "$", "toggledControl", ",", "$", "labelName", "=", "ScriptLabel", "::", "MOUSECLICK", ",", "$", "onlyShow", "=", "false", ",", "$", "onlyHide", "=", "false", ")", "{", "$", "toggle", "=", "new", "Toggle", "(", "$", "this", ",", "$", "toggledControl", ",", "$", "labelName", ",", "$", "onlyShow", ",", "$", "onlyHide", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "toggle", ")", ";", "return", "$", "this", ";", "}" ]
Add a dynamic Feature toggling another Control @api @param Control $toggledControl Toggled Control @param string $labelName (optional) Script label name @param bool $onlyShow (optional) If it should only show the Control but not toggle @param bool $onlyHide (optional) If it should only hide the Control but not toggle @return static
[ "Add", "a", "dynamic", "Feature", "toggling", "another", "Control" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L882-L887
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addTooltipFeature
public function addTooltipFeature(Control $tooltipControl, $stayOnClick = false, $invert = false) { $tooltip = new Tooltip($this, $tooltipControl, $stayOnClick, $invert); $this->addScriptFeature($tooltip); return $this; }
php
public function addTooltipFeature(Control $tooltipControl, $stayOnClick = false, $invert = false) { $tooltip = new Tooltip($this, $tooltipControl, $stayOnClick, $invert); $this->addScriptFeature($tooltip); return $this; }
[ "public", "function", "addTooltipFeature", "(", "Control", "$", "tooltipControl", ",", "$", "stayOnClick", "=", "false", ",", "$", "invert", "=", "false", ")", "{", "$", "tooltip", "=", "new", "Tooltip", "(", "$", "this", ",", "$", "tooltipControl", ",", "$", "stayOnClick", ",", "$", "invert", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "tooltip", ")", ";", "return", "$", "this", ";", "}" ]
Add a dynamic Feature showing a Tooltip on hovering @api @param Control $tooltipControl Tooltip Control @param bool $stayOnClick (optional) Whether the Tooltip should stay on click @param bool $invert (optional) Whether the visibility toggling should be inverted @return static
[ "Add", "a", "dynamic", "Feature", "showing", "a", "Tooltip", "on", "hovering" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L898-L903
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addTooltipLabelFeature
public function addTooltipLabelFeature(Label $tooltipLabel, $text, $stayOnClick = false, $invert = false) { $tooltip = new Tooltip($this, $tooltipLabel, $stayOnClick, $invert, $text); $this->addScriptFeature($tooltip); return $this; }
php
public function addTooltipLabelFeature(Label $tooltipLabel, $text, $stayOnClick = false, $invert = false) { $tooltip = new Tooltip($this, $tooltipLabel, $stayOnClick, $invert, $text); $this->addScriptFeature($tooltip); return $this; }
[ "public", "function", "addTooltipLabelFeature", "(", "Label", "$", "tooltipLabel", ",", "$", "text", ",", "$", "stayOnClick", "=", "false", ",", "$", "invert", "=", "false", ")", "{", "$", "tooltip", "=", "new", "Tooltip", "(", "$", "this", ",", "$", "tooltipLabel", ",", "$", "stayOnClick", ",", "$", "invert", ",", "$", "text", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "tooltip", ")", ";", "return", "$", "this", ";", "}" ]
Add a dynamic Feature showing a Tooltip on hovering @api @param Label $tooltipLabel Tooltip Label @param string $text Text to display on the Tooltip Label @param bool $stayOnClick (optional) Whether the Tooltip should stay on click @param bool $invert (optional) Whether the visibility toggling should be inverted @return static
[ "Add", "a", "dynamic", "Feature", "showing", "a", "Tooltip", "on", "hovering" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L915-L920
steeffeen/FancyManiaLinks
FML/Controls/Control.php
Control.addScriptText
public function addScriptText($scriptText, $label = ScriptLabel::MOUSECLICK) { $customText = new ControlScript($this, $scriptText, $label); $this->addScriptFeature($customText); return $this; }
php
public function addScriptText($scriptText, $label = ScriptLabel::MOUSECLICK) { $customText = new ControlScript($this, $scriptText, $label); $this->addScriptFeature($customText); return $this; }
[ "public", "function", "addScriptText", "(", "$", "scriptText", ",", "$", "label", "=", "ScriptLabel", "::", "MOUSECLICK", ")", "{", "$", "customText", "=", "new", "ControlScript", "(", "$", "this", ",", "$", "scriptText", ",", "$", "label", ")", ";", "$", "this", "->", "addScriptFeature", "(", "$", "customText", ")", ";", "return", "$", "this", ";", "}" ]
Add a custom Control Script text part @api @param string $scriptText Script text @param string $label (optional) Script label name @return static
[ "Add", "a", "custom", "Control", "Script", "text", "part" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Controls/Control.php#L930-L935
webforge-labs/psc-cms
lib/Psc/CMS/Controller/NavigationController.php
NavigationController.saveEntity
public function saveEntity($context, FormData $requestData, $subResource = NULL) { $this->setContext($context); return $this->saveFormular((array) $requestData); }
php
public function saveEntity($context, FormData $requestData, $subResource = NULL) { $this->setContext($context); return $this->saveFormular((array) $requestData); }
[ "public", "function", "saveEntity", "(", "$", "context", ",", "FormData", "$", "requestData", ",", "$", "subResource", "=", "NULL", ")", "{", "$", "this", "->", "setContext", "(", "$", "context", ")", ";", "return", "$", "this", "->", "saveFormular", "(", "(", "array", ")", "$", "requestData", ")", ";", "}" ]
Overrides the saving of the AbstractEntityController to just save the navigation tree from UI @return array
[ "Overrides", "the", "saving", "of", "the", "AbstractEntityController", "to", "just", "save", "the", "navigation", "tree", "from", "UI" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/Controller/NavigationController.php#L40-L43
webforge-labs/psc-cms
lib/Psc/CMS/Controller/NavigationController.php
NavigationController.createNewNode
public function createNewNode(stdClass $jsonNode) { $nodeClass = $this->container->getRoleFQN('NavigationNode'); $node = new $nodeClass((array) $jsonNode->title); $node->generateSlugs(); $defaultSlug = current($node->getI18nSlug()); // not matter what current language is, this is the default language $page = $this->createNewPage($defaultSlug); $this->dc->getEntityManager()->persist($page); $node->setPage($page); return $node; }
php
public function createNewNode(stdClass $jsonNode) { $nodeClass = $this->container->getRoleFQN('NavigationNode'); $node = new $nodeClass((array) $jsonNode->title); $node->generateSlugs(); $defaultSlug = current($node->getI18nSlug()); // not matter what current language is, this is the default language $page = $this->createNewPage($defaultSlug); $this->dc->getEntityManager()->persist($page); $node->setPage($page); return $node; }
[ "public", "function", "createNewNode", "(", "stdClass", "$", "jsonNode", ")", "{", "$", "nodeClass", "=", "$", "this", "->", "container", "->", "getRoleFQN", "(", "'NavigationNode'", ")", ";", "$", "node", "=", "new", "$", "nodeClass", "(", "(", "array", ")", "$", "jsonNode", "->", "title", ")", ";", "$", "node", "->", "generateSlugs", "(", ")", ";", "$", "defaultSlug", "=", "current", "(", "$", "node", "->", "getI18nSlug", "(", ")", ")", ";", "// not matter what current language is, this is the default language", "$", "page", "=", "$", "this", "->", "createNewPage", "(", "$", "defaultSlug", ")", ";", "$", "this", "->", "dc", "->", "getEntityManager", "(", ")", "->", "persist", "(", "$", "page", ")", ";", "$", "node", "->", "setPage", "(", "$", "page", ")", ";", "return", "$", "node", ";", "}" ]
Just create one, the attributes will be set automatically @return Webforge\CMS\Navigation\Node
[ "Just", "create", "one", "the", "attributes", "will", "be", "set", "automatically" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/Controller/NavigationController.php#L306-L318
prolic/Concurrent-PHP-Utils
src/ConcurrentPhpUtils/CyclicBarrier.php
CyclicBarrier.nextGeneration
public function nextGeneration() { // signal completion of last generation Cond::broadcast($this->cond); // set up next generation $this->count = $this->parties; $this->generation = new Generation(); }
php
public function nextGeneration() { // signal completion of last generation Cond::broadcast($this->cond); // set up next generation $this->count = $this->parties; $this->generation = new Generation(); }
[ "public", "function", "nextGeneration", "(", ")", "{", "// signal completion of last generation", "Cond", "::", "broadcast", "(", "$", "this", "->", "cond", ")", ";", "// set up next generation", "$", "this", "->", "count", "=", "$", "this", "->", "parties", ";", "$", "this", "->", "generation", "=", "new", "Generation", "(", ")", ";", "}" ]
Updates state on barrier trip and wakes up everyone. Called only while holding lock. @return void @visibility private
[ "Updates", "state", "on", "barrier", "trip", "and", "wakes", "up", "everyone", ".", "Called", "only", "while", "holding", "lock", "." ]
train
https://github.com/prolic/Concurrent-PHP-Utils/blob/771b55b3ef79d9a7443c4f6d95373f41b9f34c4a/src/ConcurrentPhpUtils/CyclicBarrier.php#L77-L85
prolic/Concurrent-PHP-Utils
src/ConcurrentPhpUtils/CyclicBarrier.php
CyclicBarrier.breakBarrier
public function breakBarrier() { $this->generation->broken = true; $this->count = $this->parties; Cond::broadcast($this->cond); }
php
public function breakBarrier() { $this->generation->broken = true; $this->count = $this->parties; Cond::broadcast($this->cond); }
[ "public", "function", "breakBarrier", "(", ")", "{", "$", "this", "->", "generation", "->", "broken", "=", "true", ";", "$", "this", "->", "count", "=", "$", "this", "->", "parties", ";", "Cond", "::", "broadcast", "(", "$", "this", "->", "cond", ")", ";", "}" ]
Sets current barrier generation as broken and wakes up everyone. Called only while holding lock. @return void @visibility private
[ "Sets", "current", "barrier", "generation", "as", "broken", "and", "wakes", "up", "everyone", ".", "Called", "only", "while", "holding", "lock", "." ]
train
https://github.com/prolic/Concurrent-PHP-Utils/blob/771b55b3ef79d9a7443c4f6d95373f41b9f34c4a/src/ConcurrentPhpUtils/CyclicBarrier.php#L94-L99
phug-php/formatter
src/Phug/Formatter.php
Formatter.storeDebugNode
public function storeDebugNode(NodeInterface $node) { $nodeId = count($this->debugNodes); $this->debugNodes[] = $node; return $nodeId; }
php
public function storeDebugNode(NodeInterface $node) { $nodeId = count($this->debugNodes); $this->debugNodes[] = $node; return $nodeId; }
[ "public", "function", "storeDebugNode", "(", "NodeInterface", "$", "node", ")", "{", "$", "nodeId", "=", "count", "(", "$", "this", "->", "debugNodes", ")", ";", "$", "this", "->", "debugNodes", "[", "]", "=", "$", "node", ";", "return", "$", "nodeId", ";", "}" ]
Store a node in a debug list and return the allocated index for it. @param NodeInterface $node @return int
[ "Store", "a", "node", "in", "a", "debug", "list", "and", "return", "the", "allocated", "index", "for", "it", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L162-L168
phug-php/formatter
src/Phug/Formatter.php
Formatter.getDebugError
public function getDebugError($error, $code, $path = null) { /** @var \Throwable $error */ $line = $this->getSourceLine($error); if ($line === false) { return $error; } $source = explode("\n", $code, max(2, $line)); array_pop($source); $source = implode("\n", $source); $pos = mb_strrpos($source, 'PUG_DEBUG:'); if ($pos === false) { throw $error; } $nodeId = intval(mb_substr($source, $pos + 10, 32)); if (!$this->debugIdExists($nodeId)) { throw $error; } $node = $this->getNodeFromDebugId($nodeId); $nodeLocation = $node->getSourceLocation(); $location = new SourceLocation( ($nodeLocation ? $nodeLocation->getPath() : null) ?: $path, $nodeLocation ? $nodeLocation->getLine() : 0, $nodeLocation ? $nodeLocation->getOffset() : 0, $nodeLocation ? $nodeLocation->getOffsetLength() : 0 ); $className = $this->getOption('located_exception_class_name'); return new $className( $location, $error->getMessage(), $error->getCode(), $error ); }
php
public function getDebugError($error, $code, $path = null) { /** @var \Throwable $error */ $line = $this->getSourceLine($error); if ($line === false) { return $error; } $source = explode("\n", $code, max(2, $line)); array_pop($source); $source = implode("\n", $source); $pos = mb_strrpos($source, 'PUG_DEBUG:'); if ($pos === false) { throw $error; } $nodeId = intval(mb_substr($source, $pos + 10, 32)); if (!$this->debugIdExists($nodeId)) { throw $error; } $node = $this->getNodeFromDebugId($nodeId); $nodeLocation = $node->getSourceLocation(); $location = new SourceLocation( ($nodeLocation ? $nodeLocation->getPath() : null) ?: $path, $nodeLocation ? $nodeLocation->getLine() : 0, $nodeLocation ? $nodeLocation->getOffset() : 0, $nodeLocation ? $nodeLocation->getOffsetLength() : 0 ); $className = $this->getOption('located_exception_class_name'); return new $className( $location, $error->getMessage(), $error->getCode(), $error ); }
[ "public", "function", "getDebugError", "(", "$", "error", ",", "$", "code", ",", "$", "path", "=", "null", ")", "{", "/** @var \\Throwable $error */", "$", "line", "=", "$", "this", "->", "getSourceLine", "(", "$", "error", ")", ";", "if", "(", "$", "line", "===", "false", ")", "{", "return", "$", "error", ";", "}", "$", "source", "=", "explode", "(", "\"\\n\"", ",", "$", "code", ",", "max", "(", "2", ",", "$", "line", ")", ")", ";", "array_pop", "(", "$", "source", ")", ";", "$", "source", "=", "implode", "(", "\"\\n\"", ",", "$", "source", ")", ";", "$", "pos", "=", "mb_strrpos", "(", "$", "source", ",", "'PUG_DEBUG:'", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "{", "throw", "$", "error", ";", "}", "$", "nodeId", "=", "intval", "(", "mb_substr", "(", "$", "source", ",", "$", "pos", "+", "10", ",", "32", ")", ")", ";", "if", "(", "!", "$", "this", "->", "debugIdExists", "(", "$", "nodeId", ")", ")", "{", "throw", "$", "error", ";", "}", "$", "node", "=", "$", "this", "->", "getNodeFromDebugId", "(", "$", "nodeId", ")", ";", "$", "nodeLocation", "=", "$", "node", "->", "getSourceLocation", "(", ")", ";", "$", "location", "=", "new", "SourceLocation", "(", "(", "$", "nodeLocation", "?", "$", "nodeLocation", "->", "getPath", "(", ")", ":", "null", ")", "?", ":", "$", "path", ",", "$", "nodeLocation", "?", "$", "nodeLocation", "->", "getLine", "(", ")", ":", "0", ",", "$", "nodeLocation", "?", "$", "nodeLocation", "->", "getOffset", "(", ")", ":", "0", ",", "$", "nodeLocation", "?", "$", "nodeLocation", "->", "getOffsetLength", "(", ")", ":", "0", ")", ";", "$", "className", "=", "$", "this", "->", "getOption", "(", "'located_exception_class_name'", ")", ";", "return", "new", "$", "className", "(", "$", "location", ",", "$", "error", "->", "getMessage", "(", ")", ",", "$", "error", "->", "getCode", "(", ")", ",", "$", "error", ")", ";", "}" ]
Return a formatted error linked to pug source. @param \Throwable $error @param string $code @param string $path @throws \Throwable @return LocatedException|\Throwable
[ "Return", "a", "formatted", "error", "linked", "to", "pug", "source", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L269-L303
phug-php/formatter
src/Phug/Formatter.php
Formatter.setFormatHandler
public function setFormatHandler($doctype, $format) { if (!is_a($format, FormatInterface::class, true)) { throw new \InvalidArgumentException( "Passed format class $format must ". 'implement '.FormatInterface::class ); } $this->setOption(['formats', $doctype], $format); return $this; }
php
public function setFormatHandler($doctype, $format) { if (!is_a($format, FormatInterface::class, true)) { throw new \InvalidArgumentException( "Passed format class $format must ". 'implement '.FormatInterface::class ); } $this->setOption(['formats', $doctype], $format); return $this; }
[ "public", "function", "setFormatHandler", "(", "$", "doctype", ",", "$", "format", ")", "{", "if", "(", "!", "is_a", "(", "$", "format", ",", "FormatInterface", "::", "class", ",", "true", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Passed format class $format must \"", ".", "'implement '", ".", "FormatInterface", "::", "class", ")", ";", "}", "$", "this", "->", "setOption", "(", "[", "'formats'", ",", "$", "doctype", "]", ",", "$", "format", ")", ";", "return", "$", "this", ";", "}" ]
Set the format handler for a given doctype identifier. @param string $doctype doctype identifier @param FormatInterface|string $format format handler @return $this
[ "Set", "the", "format", "handler", "for", "a", "given", "doctype", "identifier", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L313-L324
phug-php/formatter
src/Phug/Formatter.php
Formatter.initFormats
public function initFormats() { $this->dependencies = new DependencyInjection(); $this->mixins = new DependencyInjection(); $this->destructors = new SplObjectStorage(); $this->formats = []; return $this; }
php
public function initFormats() { $this->dependencies = new DependencyInjection(); $this->mixins = new DependencyInjection(); $this->destructors = new SplObjectStorage(); $this->formats = []; return $this; }
[ "public", "function", "initFormats", "(", ")", "{", "$", "this", "->", "dependencies", "=", "new", "DependencyInjection", "(", ")", ";", "$", "this", "->", "mixins", "=", "new", "DependencyInjection", "(", ")", ";", "$", "this", "->", "destructors", "=", "new", "SplObjectStorage", "(", ")", ";", "$", "this", "->", "formats", "=", "[", "]", ";", "return", "$", "this", ";", "}" ]
Initialize the formats list and dependencies. @return $this
[ "Initialize", "the", "formats", "list", "and", "dependencies", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L341-L349
phug-php/formatter
src/Phug/Formatter.php
Formatter.getFormatInstance
public function getFormatInstance($format = null) { $format = $format ?: $this->format; if (!($format instanceof FormatInterface)) { if (!isset($this->formats[$format])) { $event = new NewFormatEvent($this, new $format($this)); $this->trigger($event); $this->formats[$format] = $event->getFormat(); } $format = $this->formats[$format]; } return $format; }
php
public function getFormatInstance($format = null) { $format = $format ?: $this->format; if (!($format instanceof FormatInterface)) { if (!isset($this->formats[$format])) { $event = new NewFormatEvent($this, new $format($this)); $this->trigger($event); $this->formats[$format] = $event->getFormat(); } $format = $this->formats[$format]; } return $format; }
[ "public", "function", "getFormatInstance", "(", "$", "format", "=", "null", ")", "{", "$", "format", "=", "$", "format", "?", ":", "$", "this", "->", "format", ";", "if", "(", "!", "(", "$", "format", "instanceof", "FormatInterface", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "formats", "[", "$", "format", "]", ")", ")", "{", "$", "event", "=", "new", "NewFormatEvent", "(", "$", "this", ",", "new", "$", "format", "(", "$", "this", ")", ")", ";", "$", "this", "->", "trigger", "(", "$", "event", ")", ";", "$", "this", "->", "formats", "[", "$", "format", "]", "=", "$", "event", "->", "getFormat", "(", ")", ";", "}", "$", "format", "=", "$", "this", "->", "formats", "[", "$", "format", "]", ";", "}", "return", "$", "format", ";", "}" ]
Return current format as instance of FormatInterface. @param FormatInterface|string optional format, if missing current format is used @return FormatInterface
[ "Return", "current", "format", "as", "instance", "of", "FormatInterface", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L358-L373
phug-php/formatter
src/Phug/Formatter.php
Formatter.formatCode
public function formatCode($code, $checked = false, $noTransformation = false) { return $this->getFormatInstance()->formatCode($code, $checked, $noTransformation); }
php
public function formatCode($code, $checked = false, $noTransformation = false) { return $this->getFormatInstance()->formatCode($code, $checked, $noTransformation); }
[ "public", "function", "formatCode", "(", "$", "code", ",", "$", "checked", "=", "false", ",", "$", "noTransformation", "=", "false", ")", "{", "return", "$", "this", "->", "getFormatInstance", "(", ")", "->", "formatCode", "(", "$", "code", ",", "$", "checked", ",", "$", "noTransformation", ")", ";", "}" ]
Format a code with transform_expression and tokens handlers. @param string $code input code @param bool $checked test variables @param bool $noTransformation disable transform_expression @return string
[ "Format", "a", "code", "with", "transform_expression", "and", "tokens", "handlers", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L396-L399
phug-php/formatter
src/Phug/Formatter.php
Formatter.setFormat
public function setFormat($doctype) { $formats = $this->getOption('formats'); $this->format = empty($formats[$doctype]) ? $this->getOption('default_format') : $formats[$doctype]; return $this; }
php
public function setFormat($doctype) { $formats = $this->getOption('formats'); $this->format = empty($formats[$doctype]) ? $this->getOption('default_format') : $formats[$doctype]; return $this; }
[ "public", "function", "setFormat", "(", "$", "doctype", ")", "{", "$", "formats", "=", "$", "this", "->", "getOption", "(", "'formats'", ")", ";", "$", "this", "->", "format", "=", "empty", "(", "$", "formats", "[", "$", "doctype", "]", ")", "?", "$", "this", "->", "getOption", "(", "'default_format'", ")", ":", "$", "formats", "[", "$", "doctype", "]", ";", "return", "$", "this", ";", "}" ]
Set a format name as the current or fallback to default if not available. @param string $doctype format identifier @return $this
[ "Set", "a", "format", "name", "as", "the", "current", "or", "fallback", "to", "default", "if", "not", "available", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L418-L426
phug-php/formatter
src/Phug/Formatter.php
Formatter.requireMixin
public function requireMixin($name) { $this->mixins->has($name) ? $this->mixins->setAsRequired($name) : array_push($this->mixinsPreCalled, $name); return $this; }
php
public function requireMixin($name) { $this->mixins->has($name) ? $this->mixins->setAsRequired($name) : array_push($this->mixinsPreCalled, $name); return $this; }
[ "public", "function", "requireMixin", "(", "$", "name", ")", "{", "$", "this", "->", "mixins", "->", "has", "(", "$", "name", ")", "?", "$", "this", "->", "mixins", "->", "setAsRequired", "(", "$", "name", ")", ":", "array_push", "(", "$", "this", "->", "mixinsPreCalled", ",", "$", "name", ")", ";", "return", "$", "this", ";", "}" ]
@param $name @return $this
[ "@param", "$name" ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L459-L466
phug-php/formatter
src/Phug/Formatter.php
Formatter.formatDependencies
public function formatDependencies() { $variablesVariable = $this->getOption('pug_variables_variable_name'); $dependencies = $variablesVariable ? implode("\n", [ '<?php', '$'.$variablesVariable.' = [];', 'foreach (array_keys(get_defined_vars()) as $__pug_key) {', ' $'.$variablesVariable.'[$__pug_key] = &$$__pug_key;', '}', '?>', ]) : ''; if ($this->dependencies->countRequiredDependencies() > 0) { $dependenciesExport = $this->dependencies->export( $this->getOption('dependencies_storage') ); $dependencies .= $this->format(new CodeElement(trim($dependenciesExport))); } foreach ($this->mixins->getRequirementsStates() as $key => $value) { if ($value || $this->mixinsAllRequired || in_array($key, $this->mixinsPreCalled)) { $dependencies .= $this->mixins->get($key); } } return $dependencies; }
php
public function formatDependencies() { $variablesVariable = $this->getOption('pug_variables_variable_name'); $dependencies = $variablesVariable ? implode("\n", [ '<?php', '$'.$variablesVariable.' = [];', 'foreach (array_keys(get_defined_vars()) as $__pug_key) {', ' $'.$variablesVariable.'[$__pug_key] = &$$__pug_key;', '}', '?>', ]) : ''; if ($this->dependencies->countRequiredDependencies() > 0) { $dependenciesExport = $this->dependencies->export( $this->getOption('dependencies_storage') ); $dependencies .= $this->format(new CodeElement(trim($dependenciesExport))); } foreach ($this->mixins->getRequirementsStates() as $key => $value) { if ($value || $this->mixinsAllRequired || in_array($key, $this->mixinsPreCalled)) { $dependencies .= $this->mixins->get($key); } } return $dependencies; }
[ "public", "function", "formatDependencies", "(", ")", "{", "$", "variablesVariable", "=", "$", "this", "->", "getOption", "(", "'pug_variables_variable_name'", ")", ";", "$", "dependencies", "=", "$", "variablesVariable", "?", "implode", "(", "\"\\n\"", ",", "[", "'<?php'", ",", "'$'", ".", "$", "variablesVariable", ".", "' = [];'", ",", "'foreach (array_keys(get_defined_vars()) as $__pug_key) {'", ",", "' $'", ".", "$", "variablesVariable", ".", "'[$__pug_key] = &$$__pug_key;'", ",", "'}'", ",", "'?>'", ",", "]", ")", ":", "''", ";", "if", "(", "$", "this", "->", "dependencies", "->", "countRequiredDependencies", "(", ")", ">", "0", ")", "{", "$", "dependenciesExport", "=", "$", "this", "->", "dependencies", "->", "export", "(", "$", "this", "->", "getOption", "(", "'dependencies_storage'", ")", ")", ";", "$", "dependencies", ".=", "$", "this", "->", "format", "(", "new", "CodeElement", "(", "trim", "(", "$", "dependenciesExport", ")", ")", ")", ";", "}", "foreach", "(", "$", "this", "->", "mixins", "->", "getRequirementsStates", "(", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "||", "$", "this", "->", "mixinsAllRequired", "||", "in_array", "(", "$", "key", ",", "$", "this", "->", "mixinsPreCalled", ")", ")", "{", "$", "dependencies", ".=", "$", "this", "->", "mixins", "->", "get", "(", "$", "key", ")", ";", "}", "}", "return", "$", "dependencies", ";", "}" ]
Create/reset the dependency injector.
[ "Create", "/", "reset", "the", "dependency", "injector", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L471-L499
phug-php/formatter
src/Phug/Formatter.php
Formatter.getDependencyStorage
public function getDependencyStorage($name) { $dependencyStorage = $this->dependencies->getStorageItem($name, $this->getOption('dependencies_storage')); $event = new DependencyStorageEvent($dependencyStorage); $this->trigger($event); return $event->getDependencyStorage(); }
php
public function getDependencyStorage($name) { $dependencyStorage = $this->dependencies->getStorageItem($name, $this->getOption('dependencies_storage')); $event = new DependencyStorageEvent($dependencyStorage); $this->trigger($event); return $event->getDependencyStorage(); }
[ "public", "function", "getDependencyStorage", "(", "$", "name", ")", "{", "$", "dependencyStorage", "=", "$", "this", "->", "dependencies", "->", "getStorageItem", "(", "$", "name", ",", "$", "this", "->", "getOption", "(", "'dependencies_storage'", ")", ")", ";", "$", "event", "=", "new", "DependencyStorageEvent", "(", "$", "dependencyStorage", ")", ";", "$", "this", "->", "trigger", "(", "$", "event", ")", ";", "return", "$", "event", "->", "getDependencyStorage", "(", ")", ";", "}" ]
@param string $name dependency name @return string
[ "@param", "string", "$name", "dependency", "name" ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L514-L522
phug-php/formatter
src/Phug/Formatter.php
Formatter.format
public function format(ElementInterface $element, $format = null) { if ($element instanceof DoctypeElement) { $formats = $this->getOption('formats'); $doctype = $element->getValue(); $this->setFormat($doctype); if (isset($formats[$doctype])) { $element->setValue(null); } } $format = $this->getFormatInstance($format); $format->setFormatter($this); $formatEvent = new FormatEvent($element, $format); $this->trigger($formatEvent); $element = $formatEvent->getElement(); $format = $formatEvent->getFormat(); $stringifyEvent = new StringifyEvent($formatEvent, $element ? $format($element) : ''); $this->trigger($stringifyEvent); return $stringifyEvent->getOutput(); }
php
public function format(ElementInterface $element, $format = null) { if ($element instanceof DoctypeElement) { $formats = $this->getOption('formats'); $doctype = $element->getValue(); $this->setFormat($doctype); if (isset($formats[$doctype])) { $element->setValue(null); } } $format = $this->getFormatInstance($format); $format->setFormatter($this); $formatEvent = new FormatEvent($element, $format); $this->trigger($formatEvent); $element = $formatEvent->getElement(); $format = $formatEvent->getFormat(); $stringifyEvent = new StringifyEvent($formatEvent, $element ? $format($element) : ''); $this->trigger($stringifyEvent); return $stringifyEvent->getOutput(); }
[ "public", "function", "format", "(", "ElementInterface", "$", "element", ",", "$", "format", "=", "null", ")", "{", "if", "(", "$", "element", "instanceof", "DoctypeElement", ")", "{", "$", "formats", "=", "$", "this", "->", "getOption", "(", "'formats'", ")", ";", "$", "doctype", "=", "$", "element", "->", "getValue", "(", ")", ";", "$", "this", "->", "setFormat", "(", "$", "doctype", ")", ";", "if", "(", "isset", "(", "$", "formats", "[", "$", "doctype", "]", ")", ")", "{", "$", "element", "->", "setValue", "(", "null", ")", ";", "}", "}", "$", "format", "=", "$", "this", "->", "getFormatInstance", "(", "$", "format", ")", ";", "$", "format", "->", "setFormatter", "(", "$", "this", ")", ";", "$", "formatEvent", "=", "new", "FormatEvent", "(", "$", "element", ",", "$", "format", ")", ";", "$", "this", "->", "trigger", "(", "$", "formatEvent", ")", ";", "$", "element", "=", "$", "formatEvent", "->", "getElement", "(", ")", ";", "$", "format", "=", "$", "formatEvent", "->", "getFormat", "(", ")", ";", "$", "stringifyEvent", "=", "new", "StringifyEvent", "(", "$", "formatEvent", ",", "$", "element", "?", "$", "format", "(", "$", "element", ")", ":", "''", ")", ";", "$", "this", "->", "trigger", "(", "$", "stringifyEvent", ")", ";", "return", "$", "stringifyEvent", "->", "getOutput", "(", ")", ";", "}" ]
Entry point of the Formatter, typically waiting for a DocumentElement and a format, to return a string with HTML and PHP nested. @param ElementInterface $element @param FormatInterface|null $format @return string
[ "Entry", "point", "of", "the", "Formatter", "typically", "waiting", "for", "a", "DocumentElement", "and", "a", "format", "to", "return", "a", "string", "with", "HTML", "and", "PHP", "nested", "." ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter.php#L533-L557
inpsyde/inpsyde-filter
src/FilterFactory.php
FilterFactory.create
public function create( $type, array $properties = [ ] ) { $type = (string) $type; if ( isset( $this->classes[ $type ] ) ) { $class = $this->classes[ $type ]; return new $class( $properties ); } else if ( class_exists( $type ) ) { $class = new $type( $properties ); if ( $class instanceof FilterInterface ) { return $class; } } throw new Exception\InvalidArgumentException( sprintf( 'The given class <code>%s</code> does not exists.', $type ) ); }
php
public function create( $type, array $properties = [ ] ) { $type = (string) $type; if ( isset( $this->classes[ $type ] ) ) { $class = $this->classes[ $type ]; return new $class( $properties ); } else if ( class_exists( $type ) ) { $class = new $type( $properties ); if ( $class instanceof FilterInterface ) { return $class; } } throw new Exception\InvalidArgumentException( sprintf( 'The given class <code>%s</code> does not exists.', $type ) ); }
[ "public", "function", "create", "(", "$", "type", ",", "array", "$", "properties", "=", "[", "]", ")", "{", "$", "type", "=", "(", "string", ")", "$", "type", ";", "if", "(", "isset", "(", "$", "this", "->", "classes", "[", "$", "type", "]", ")", ")", "{", "$", "class", "=", "$", "this", "->", "classes", "[", "$", "type", "]", ";", "return", "new", "$", "class", "(", "$", "properties", ")", ";", "}", "else", "if", "(", "class_exists", "(", "$", "type", ")", ")", "{", "$", "class", "=", "new", "$", "type", "(", "$", "properties", ")", ";", "if", "(", "$", "class", "instanceof", "FilterInterface", ")", "{", "return", "$", "class", ";", "}", "}", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The given class <code>%s</code> does not exists.'", ",", "$", "type", ")", ")", ";", "}" ]
Creates and returns a new filter instance of the given type. @param $type @param array $properties @throws Exception\InvalidArgumentException if Filter of given $type is not found. @return FilterInterface
[ "Creates", "and", "returns", "a", "new", "filter", "instance", "of", "the", "given", "type", "." ]
train
https://github.com/inpsyde/inpsyde-filter/blob/777a6208ea4dfbeed89e6d0712a35dc25eab498b/src/FilterFactory.php#L46-L69
phpmob/changmin
src/PhpMob/Sylius/Grid/FieldType/LocalizedNumberFieldType.php
LocalizedNumberFieldType.render
public function render(Field $field, $data, array $options) { if ('.' !== $field->getPath()) { $data = $this->dataExtractor->get($field, $data); } $field->setOptions($options); if ($options['divide'] && $options['multiply']) { throw new \LogicException("Can't set `divide` and `multiply` in same time."); } if (null !== $options['divide']) { $data = $data / $options['divide']; } if (null !== $options['multiply']) { $data = $data * $options['multiply']; } $formatter = twig_get_number_formatter($options['locale'], $options['style']); if ($options['precision']) { $formatter->setAttribute($formatter::FRACTION_DIGITS, $options['precision']); } if ('currency' === $options['style']) { return $formatter->formatCurrency($data, $options['currency']); } $typeValues = array( 'default' => $formatter::TYPE_DEFAULT, 'int32' => $formatter::TYPE_INT32, 'int64' => $formatter::TYPE_INT64, 'double' => $formatter::TYPE_DOUBLE, 'currency' => $formatter::TYPE_CURRENCY, ); if (!isset($typeValues[$options['type']])) { throw new Twig_Error_Syntax(sprintf('The type "%s" does not exist. Known types are: "%s"', $options['type'], implode('", "', array_keys($typeValues)))); } return $formatter->format($data, $typeValues[$options['type']]); }
php
public function render(Field $field, $data, array $options) { if ('.' !== $field->getPath()) { $data = $this->dataExtractor->get($field, $data); } $field->setOptions($options); if ($options['divide'] && $options['multiply']) { throw new \LogicException("Can't set `divide` and `multiply` in same time."); } if (null !== $options['divide']) { $data = $data / $options['divide']; } if (null !== $options['multiply']) { $data = $data * $options['multiply']; } $formatter = twig_get_number_formatter($options['locale'], $options['style']); if ($options['precision']) { $formatter->setAttribute($formatter::FRACTION_DIGITS, $options['precision']); } if ('currency' === $options['style']) { return $formatter->formatCurrency($data, $options['currency']); } $typeValues = array( 'default' => $formatter::TYPE_DEFAULT, 'int32' => $formatter::TYPE_INT32, 'int64' => $formatter::TYPE_INT64, 'double' => $formatter::TYPE_DOUBLE, 'currency' => $formatter::TYPE_CURRENCY, ); if (!isset($typeValues[$options['type']])) { throw new Twig_Error_Syntax(sprintf('The type "%s" does not exist. Known types are: "%s"', $options['type'], implode('", "', array_keys($typeValues)))); } return $formatter->format($data, $typeValues[$options['type']]); }
[ "public", "function", "render", "(", "Field", "$", "field", ",", "$", "data", ",", "array", "$", "options", ")", "{", "if", "(", "'.'", "!==", "$", "field", "->", "getPath", "(", ")", ")", "{", "$", "data", "=", "$", "this", "->", "dataExtractor", "->", "get", "(", "$", "field", ",", "$", "data", ")", ";", "}", "$", "field", "->", "setOptions", "(", "$", "options", ")", ";", "if", "(", "$", "options", "[", "'divide'", "]", "&&", "$", "options", "[", "'multiply'", "]", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"Can't set `divide` and `multiply` in same time.\"", ")", ";", "}", "if", "(", "null", "!==", "$", "options", "[", "'divide'", "]", ")", "{", "$", "data", "=", "$", "data", "/", "$", "options", "[", "'divide'", "]", ";", "}", "if", "(", "null", "!==", "$", "options", "[", "'multiply'", "]", ")", "{", "$", "data", "=", "$", "data", "*", "$", "options", "[", "'multiply'", "]", ";", "}", "$", "formatter", "=", "twig_get_number_formatter", "(", "$", "options", "[", "'locale'", "]", ",", "$", "options", "[", "'style'", "]", ")", ";", "if", "(", "$", "options", "[", "'precision'", "]", ")", "{", "$", "formatter", "->", "setAttribute", "(", "$", "formatter", "::", "FRACTION_DIGITS", ",", "$", "options", "[", "'precision'", "]", ")", ";", "}", "if", "(", "'currency'", "===", "$", "options", "[", "'style'", "]", ")", "{", "return", "$", "formatter", "->", "formatCurrency", "(", "$", "data", ",", "$", "options", "[", "'currency'", "]", ")", ";", "}", "$", "typeValues", "=", "array", "(", "'default'", "=>", "$", "formatter", "::", "TYPE_DEFAULT", ",", "'int32'", "=>", "$", "formatter", "::", "TYPE_INT32", ",", "'int64'", "=>", "$", "formatter", "::", "TYPE_INT64", ",", "'double'", "=>", "$", "formatter", "::", "TYPE_DOUBLE", ",", "'currency'", "=>", "$", "formatter", "::", "TYPE_CURRENCY", ",", ")", ";", "if", "(", "!", "isset", "(", "$", "typeValues", "[", "$", "options", "[", "'type'", "]", "]", ")", ")", "{", "throw", "new", "Twig_Error_Syntax", "(", "sprintf", "(", "'The type \"%s\" does not exist. Known types are: \"%s\"'", ",", "$", "options", "[", "'type'", "]", ",", "implode", "(", "'\", \"'", ",", "array_keys", "(", "$", "typeValues", ")", ")", ")", ")", ";", "}", "return", "$", "formatter", "->", "format", "(", "$", "data", ",", "$", "typeValues", "[", "$", "options", "[", "'type'", "]", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/Sylius/Grid/FieldType/LocalizedNumberFieldType.php#L42-L85
phpmob/changmin
src/PhpMob/Sylius/Grid/FieldType/LocalizedNumberFieldType.php
LocalizedNumberFieldType.configureOptions
public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults( [ 'width' => '150px', 'align' => 'right', 'style' => 'decimal', 'type' => 'default', 'precision' => null, 'currency' => null, 'multiply' => null, 'divide' => null, 'locale' => null, ] ); $resolver->setAllowedTypes('align', 'string'); $resolver->setAllowedTypes('width', 'string'); $resolver->setAllowedTypes('style', 'string'); $resolver->setAllowedTypes('type', 'string'); $resolver->setAllowedTypes('currency', ['null', 'string']); $resolver->setAllowedTypes('precision', ['null', 'int']); $resolver->setAllowedTypes('multiply', ['null', 'int']); $resolver->setAllowedTypes('divide', ['null', 'int']); $resolver->setAllowedTypes('locale', ['string', 'null']); }
php
public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults( [ 'width' => '150px', 'align' => 'right', 'style' => 'decimal', 'type' => 'default', 'precision' => null, 'currency' => null, 'multiply' => null, 'divide' => null, 'locale' => null, ] ); $resolver->setAllowedTypes('align', 'string'); $resolver->setAllowedTypes('width', 'string'); $resolver->setAllowedTypes('style', 'string'); $resolver->setAllowedTypes('type', 'string'); $resolver->setAllowedTypes('currency', ['null', 'string']); $resolver->setAllowedTypes('precision', ['null', 'int']); $resolver->setAllowedTypes('multiply', ['null', 'int']); $resolver->setAllowedTypes('divide', ['null', 'int']); $resolver->setAllowedTypes('locale', ['string', 'null']); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", ":", "void", "{", "$", "resolver", "->", "setDefaults", "(", "[", "'width'", "=>", "'150px'", ",", "'align'", "=>", "'right'", ",", "'style'", "=>", "'decimal'", ",", "'type'", "=>", "'default'", ",", "'precision'", "=>", "null", ",", "'currency'", "=>", "null", ",", "'multiply'", "=>", "null", ",", "'divide'", "=>", "null", ",", "'locale'", "=>", "null", ",", "]", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'align'", ",", "'string'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'width'", ",", "'string'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'style'", ",", "'string'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'type'", ",", "'string'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'currency'", ",", "[", "'null'", ",", "'string'", "]", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'precision'", ",", "[", "'null'", ",", "'int'", "]", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'multiply'", ",", "[", "'null'", ",", "'int'", "]", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'divide'", ",", "[", "'null'", ",", "'int'", "]", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'locale'", ",", "[", "'string'", ",", "'null'", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/Sylius/Grid/FieldType/LocalizedNumberFieldType.php#L90-L115
iocaste/microservice-foundation
src/Http/Middleware/TransformsRequest.php
TransformsRequest.handle
public function handle($request, Closure $next, ...$attributes) { $this->attributes = $attributes; $this->clean($request); return $next($request); }
php
public function handle($request, Closure $next, ...$attributes) { $this->attributes = $attributes; $this->clean($request); return $next($request); }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ",", "...", "$", "attributes", ")", "{", "$", "this", "->", "attributes", "=", "$", "attributes", ";", "$", "this", "->", "clean", "(", "$", "request", ")", ";", "return", "$", "next", "(", "$", "request", ")", ";", "}" ]
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @param array ...$attributes @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/iocaste/microservice-foundation/blob/274a154de4299e8a57314bab972e09f6d8cdae9e/src/Http/Middleware/TransformsRequest.php#L25-L32
yuncms/framework
src/notifications/migrations/m180410_092555_create_notification_table.php
m180410_092555_create_notification_table.safeUp
public function safeUp() { $tableOptions = null; if ($this->db->driverName === 'mysql') { // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci $tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB'; } // https://segmentfault.com/q/1010000000672529/a-1020000000679702 $this->createTable($this->tableName, [ 'id' => $this->char(24)->notNull()->comment('Id'),//通知ID 'verb' => $this->string(32),//执行了什么操作 'template' => $this->string(),//模板 'notifiable_id' => $this->unsignedInteger()->notNull()->comment('Entity'),//通知实体ID 'notifiable_class' => $this->string()->notNull()->comment('Entity'),//通知实体类名 'data' => $this->text(),//通知数据 // data_entity 触发通知的那个实体 // data_source 源实体 // data_target 目标实体 // 'read_at' => $this->unixTimestamp()->comment('Read At'),//阅读时间 'created_at' => $this->unixTimestamp()->notNull()->comment('Created At'),//创建时间 'updated_at' => $this->integer(10)->unsigned()->notNull()->comment('Updated At'),//更新时间 ], $tableOptions); $this->addPrimaryKey('{{%notification_notifiable_pk}}', $this->tableName, 'id'); $this->createIndex('notification_notifiable', $this->tableName, ['notifiable_id', 'notifiable_class']); }
php
public function safeUp() { $tableOptions = null; if ($this->db->driverName === 'mysql') { // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci $tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB'; } // https://segmentfault.com/q/1010000000672529/a-1020000000679702 $this->createTable($this->tableName, [ 'id' => $this->char(24)->notNull()->comment('Id'),//通知ID 'verb' => $this->string(32),//执行了什么操作 'template' => $this->string(),//模板 'notifiable_id' => $this->unsignedInteger()->notNull()->comment('Entity'),//通知实体ID 'notifiable_class' => $this->string()->notNull()->comment('Entity'),//通知实体类名 'data' => $this->text(),//通知数据 // data_entity 触发通知的那个实体 // data_source 源实体 // data_target 目标实体 // 'read_at' => $this->unixTimestamp()->comment('Read At'),//阅读时间 'created_at' => $this->unixTimestamp()->notNull()->comment('Created At'),//创建时间 'updated_at' => $this->integer(10)->unsigned()->notNull()->comment('Updated At'),//更新时间 ], $tableOptions); $this->addPrimaryKey('{{%notification_notifiable_pk}}', $this->tableName, 'id'); $this->createIndex('notification_notifiable', $this->tableName, ['notifiable_id', 'notifiable_class']); }
[ "public", "function", "safeUp", "(", ")", "{", "$", "tableOptions", "=", "null", ";", "if", "(", "$", "this", "->", "db", "->", "driverName", "===", "'mysql'", ")", "{", "// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci", "$", "tableOptions", "=", "'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB'", ";", "}", "// https://segmentfault.com/q/1010000000672529/a-1020000000679702", "$", "this", "->", "createTable", "(", "$", "this", "->", "tableName", ",", "[", "'id'", "=>", "$", "this", "->", "char", "(", "24", ")", "->", "notNull", "(", ")", "->", "comment", "(", "'Id'", ")", ",", "//通知ID", "'verb'", "=>", "$", "this", "->", "string", "(", "32", ")", ",", "//执行了什么操作", "'template'", "=>", "$", "this", "->", "string", "(", ")", ",", "//模板", "'notifiable_id'", "=>", "$", "this", "->", "unsignedInteger", "(", ")", "->", "notNull", "(", ")", "->", "comment", "(", "'Entity'", ")", ",", "//通知实体ID", "'notifiable_class'", "=>", "$", "this", "->", "string", "(", ")", "->", "notNull", "(", ")", "->", "comment", "(", "'Entity'", ")", ",", "//通知实体类名", "'data'", "=>", "$", "this", "->", "text", "(", ")", ",", "//通知数据", "// data_entity 触发通知的那个实体", "// data_source 源实体", "// data_target 目标实体", "//", "'read_at'", "=>", "$", "this", "->", "unixTimestamp", "(", ")", "->", "comment", "(", "'Read At'", ")", ",", "//阅读时间", "'created_at'", "=>", "$", "this", "->", "unixTimestamp", "(", ")", "->", "notNull", "(", ")", "->", "comment", "(", "'Created At'", ")", ",", "//创建时间", "'updated_at'", "=>", "$", "this", "->", "integer", "(", "10", ")", "->", "unsigned", "(", ")", "->", "notNull", "(", ")", "->", "comment", "(", "'Updated At'", ")", ",", "//更新时间", "]", ",", "$", "tableOptions", ")", ";", "$", "this", "->", "addPrimaryKey", "(", "'{{%notification_notifiable_pk}}'", ",", "$", "this", "->", "tableName", ",", "'id'", ")", ";", "$", "this", "->", "createIndex", "(", "'notification_notifiable'", ",", "$", "this", "->", "tableName", ",", "[", "'notifiable_id'", ",", "'notifiable_class'", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/notifications/migrations/m180410_092555_create_notification_table.php#L18-L45
php-rise/rise
src/Router.php
Router.match
public function match() { $result = false; $this->matchedStatus = $this->result->getStatus(); if ($this->result->hasHandler()) { $result = true; $this->matchedHandler = $this->result->getHandler(); } else { $this->matchedHandler = $this->notFoundHandler; } return $result; }
php
public function match() { $result = false; $this->matchedStatus = $this->result->getStatus(); if ($this->result->hasHandler()) { $result = true; $this->matchedHandler = $this->result->getHandler(); } else { $this->matchedHandler = $this->notFoundHandler; } return $result; }
[ "public", "function", "match", "(", ")", "{", "$", "result", "=", "false", ";", "$", "this", "->", "matchedStatus", "=", "$", "this", "->", "result", "->", "getStatus", "(", ")", ";", "if", "(", "$", "this", "->", "result", "->", "hasHandler", "(", ")", ")", "{", "$", "result", "=", "true", ";", "$", "this", "->", "matchedHandler", "=", "$", "this", "->", "result", "->", "getHandler", "(", ")", ";", "}", "else", "{", "$", "this", "->", "matchedHandler", "=", "$", "this", "->", "notFoundHandler", ";", "}", "return", "$", "result", ";", "}" ]
Match current HTTP request. @return bool
[ "Match", "current", "HTTP", "request", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Router.php#L75-L88
PortaText/php-sdk
src/PortaText/Command/Api/Simulate.php
Simulate.getEndpoint
protected function getEndpoint($method) { $endpoint = "simulate"; $queryString = array(); $text = $this->getArgument("text"); if (!is_null($text)) { $queryString['text'] = $text; $this->delArgument("text"); } $templateId = $this->getArgument("template_id"); if (!is_null($templateId)) { $queryString['template_id'] = $templateId; $this->delArgument("template_id"); } $variables = $this->getArgument("variables"); if (!is_null($variables)) { $queryString['variables'] = json_encode($variables); $this->delArgument("variables"); } $country = $this->getArgument("country"); if (is_null($country)) { throw new \InvalidArgumentException("Country cant be null"); } $queryString['country'] = $country; $this->delArgument("country"); $queryString = http_build_query($queryString); return "$endpoint?$queryString"; }
php
protected function getEndpoint($method) { $endpoint = "simulate"; $queryString = array(); $text = $this->getArgument("text"); if (!is_null($text)) { $queryString['text'] = $text; $this->delArgument("text"); } $templateId = $this->getArgument("template_id"); if (!is_null($templateId)) { $queryString['template_id'] = $templateId; $this->delArgument("template_id"); } $variables = $this->getArgument("variables"); if (!is_null($variables)) { $queryString['variables'] = json_encode($variables); $this->delArgument("variables"); } $country = $this->getArgument("country"); if (is_null($country)) { throw new \InvalidArgumentException("Country cant be null"); } $queryString['country'] = $country; $this->delArgument("country"); $queryString = http_build_query($queryString); return "$endpoint?$queryString"; }
[ "protected", "function", "getEndpoint", "(", "$", "method", ")", "{", "$", "endpoint", "=", "\"simulate\"", ";", "$", "queryString", "=", "array", "(", ")", ";", "$", "text", "=", "$", "this", "->", "getArgument", "(", "\"text\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "text", ")", ")", "{", "$", "queryString", "[", "'text'", "]", "=", "$", "text", ";", "$", "this", "->", "delArgument", "(", "\"text\"", ")", ";", "}", "$", "templateId", "=", "$", "this", "->", "getArgument", "(", "\"template_id\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "templateId", ")", ")", "{", "$", "queryString", "[", "'template_id'", "]", "=", "$", "templateId", ";", "$", "this", "->", "delArgument", "(", "\"template_id\"", ")", ";", "}", "$", "variables", "=", "$", "this", "->", "getArgument", "(", "\"variables\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "variables", ")", ")", "{", "$", "queryString", "[", "'variables'", "]", "=", "json_encode", "(", "$", "variables", ")", ";", "$", "this", "->", "delArgument", "(", "\"variables\"", ")", ";", "}", "$", "country", "=", "$", "this", "->", "getArgument", "(", "\"country\"", ")", ";", "if", "(", "is_null", "(", "$", "country", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Country cant be null\"", ")", ";", "}", "$", "queryString", "[", "'country'", "]", "=", "$", "country", ";", "$", "this", "->", "delArgument", "(", "\"country\"", ")", ";", "$", "queryString", "=", "http_build_query", "(", "$", "queryString", ")", ";", "return", "\"$endpoint?$queryString\"", ";", "}" ]
Returns a string with the endpoint for the given command. @param string $method Method for this command. @return string
[ "Returns", "a", "string", "with", "the", "endpoint", "for", "the", "given", "command", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Command/Api/Simulate.php#L64-L95
askupasoftware/amarkal
Loaders/ClassLoader.php
ClassLoader.register_namespace
public function register_namespace( $namespace, $paths ) { if ( isset( $this->namespaces[ $namespace ] ) ) { $this->namespaces[ $namespace ] = array_merge( $this->namespaces[ $namespace ], (array) $paths ); } else { $this->namespaces[ $namespace ] = (array) $paths; // Register PSR_0 as the first autoload filter for every namespace $this->register_autoload_filter( $namespace, array( $this, "PSR_0" ) ); } }
php
public function register_namespace( $namespace, $paths ) { if ( isset( $this->namespaces[ $namespace ] ) ) { $this->namespaces[ $namespace ] = array_merge( $this->namespaces[ $namespace ], (array) $paths ); } else { $this->namespaces[ $namespace ] = (array) $paths; // Register PSR_0 as the first autoload filter for every namespace $this->register_autoload_filter( $namespace, array( $this, "PSR_0" ) ); } }
[ "public", "function", "register_namespace", "(", "$", "namespace", ",", "$", "paths", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "namespaces", "[", "$", "namespace", "]", ")", ")", "{", "$", "this", "->", "namespaces", "[", "$", "namespace", "]", "=", "array_merge", "(", "$", "this", "->", "namespaces", "[", "$", "namespace", "]", ",", "(", "array", ")", "$", "paths", ")", ";", "}", "else", "{", "$", "this", "->", "namespaces", "[", "$", "namespace", "]", "=", "(", "array", ")", "$", "paths", ";", "// Register PSR_0 as the first autoload filter for every namespace", "$", "this", "->", "register_autoload_filter", "(", "$", "namespace", ",", "array", "(", "$", "this", ",", "\"PSR_0\"", ")", ")", ";", "}", "}" ]
Register a namespace @param string $namespace The namespace @param array|string $paths The path(s) to the namespace
[ "Register", "a", "namespace" ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Loaders/ClassLoader.php#L64-L80
askupasoftware/amarkal
Loaders/ClassLoader.php
ClassLoader.find_file
private function find_file( $class ) { foreach ( $this->namespaces as $namespace => $dirs ) { if ( $class === strstr( $class, $namespace ) ) { foreach ( $dirs as $dir ) { return $this->apply_namespace_filters( $namespace, $class, $dir ); } } } }
php
private function find_file( $class ) { foreach ( $this->namespaces as $namespace => $dirs ) { if ( $class === strstr( $class, $namespace ) ) { foreach ( $dirs as $dir ) { return $this->apply_namespace_filters( $namespace, $class, $dir ); } } } }
[ "private", "function", "find_file", "(", "$", "class", ")", "{", "foreach", "(", "$", "this", "->", "namespaces", "as", "$", "namespace", "=>", "$", "dirs", ")", "{", "if", "(", "$", "class", "===", "strstr", "(", "$", "class", ",", "$", "namespace", ")", ")", "{", "foreach", "(", "$", "dirs", "as", "$", "dir", ")", "{", "return", "$", "this", "->", "apply_namespace_filters", "(", "$", "namespace", ",", "$", "class", ",", "$", "dir", ")", ";", "}", "}", "}", "}" ]
Finds the path to the file where the class is defined. @param string $class The name of the class @return string The path, if found
[ "Finds", "the", "path", "to", "the", "file", "where", "the", "class", "is", "defined", "." ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Loaders/ClassLoader.php#L88-L100
askupasoftware/amarkal
Loaders/ClassLoader.php
ClassLoader.apply_namespace_filters
private function apply_namespace_filters( $namespace, $class, $dir ) { foreach( $this->filters[$namespace] as $filter ) { if( is_callable( $filter ) ) { $file = call_user_func_array( $filter, array( $class, $namespace, $dir ) ); if ( file_exists( $file ) ) { return $file; } } } }
php
private function apply_namespace_filters( $namespace, $class, $dir ) { foreach( $this->filters[$namespace] as $filter ) { if( is_callable( $filter ) ) { $file = call_user_func_array( $filter, array( $class, $namespace, $dir ) ); if ( file_exists( $file ) ) { return $file; } } } }
[ "private", "function", "apply_namespace_filters", "(", "$", "namespace", ",", "$", "class", ",", "$", "dir", ")", "{", "foreach", "(", "$", "this", "->", "filters", "[", "$", "namespace", "]", "as", "$", "filter", ")", "{", "if", "(", "is_callable", "(", "$", "filter", ")", ")", "{", "$", "file", "=", "call_user_func_array", "(", "$", "filter", ",", "array", "(", "$", "class", ",", "$", "namespace", ",", "$", "dir", ")", ")", ";", "if", "(", "file_exists", "(", "$", "file", ")", ")", "{", "return", "$", "file", ";", "}", "}", "}", "}" ]
Internally used by find_file() to apply namespace filters. @param string $namespace @param string $class @param string $dir @return string File path
[ "Internally", "used", "by", "find_file", "()", "to", "apply", "namespace", "filters", "." ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Loaders/ClassLoader.php#L110-L123
askupasoftware/amarkal
Loaders/ClassLoader.php
ClassLoader.register_autoload_filter
public function register_autoload_filter( $namespace, $filter ) { if(is_callable( $filter ) ) { if( !isset($this->filters[$namespace]) ) { $this->filters[$namespace] = array(); } $this->filters[$namespace][] = $filter; } }
php
public function register_autoload_filter( $namespace, $filter ) { if(is_callable( $filter ) ) { if( !isset($this->filters[$namespace]) ) { $this->filters[$namespace] = array(); } $this->filters[$namespace][] = $filter; } }
[ "public", "function", "register_autoload_filter", "(", "$", "namespace", ",", "$", "filter", ")", "{", "if", "(", "is_callable", "(", "$", "filter", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "filters", "[", "$", "namespace", "]", ")", ")", "{", "$", "this", "->", "filters", "[", "$", "namespace", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "filters", "[", "$", "namespace", "]", "[", "]", "=", "$", "filter", ";", "}", "}" ]
Autoload filters are functions that are used to autoload classes. These functions accept a class name as an argument and return the appropriate file path to that class. Autoload filters are applied per namespace. Each namespace can have multiple autoload filters. The class loader will loop through all the filters until a file is found. The filters are looped through in the order in which they were registered. @param type $namespace The namespace in which the filter is applied. @param type $filter A callable that returns the file path for the given class.
[ "Autoload", "filters", "are", "functions", "that", "are", "used", "to", "autoload", "classes", ".", "These", "functions", "accept", "a", "class", "name", "as", "an", "argument", "and", "return", "the", "appropriate", "file", "path", "to", "that", "class", ".", "Autoload", "filters", "are", "applied", "per", "namespace", ".", "Each", "namespace", "can", "have", "multiple", "autoload", "filters", ".", "The", "class", "loader", "will", "loop", "through", "all", "the", "filters", "until", "a", "file", "is", "found", ".", "The", "filters", "are", "looped", "through", "in", "the", "order", "in", "which", "they", "were", "registered", "." ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Loaders/ClassLoader.php#L150-L161
lmammino/e-foundation
src/Variation/Model/Variant.php
Variant.setOptionValues
public function setOptionValues(Collection $optionValues) { foreach ($optionValues as $optionValue) { $this->addOptionValue($optionValue); } return $this; }
php
public function setOptionValues(Collection $optionValues) { foreach ($optionValues as $optionValue) { $this->addOptionValue($optionValue); } return $this; }
[ "public", "function", "setOptionValues", "(", "Collection", "$", "optionValues", ")", "{", "foreach", "(", "$", "optionValues", "as", "$", "optionValue", ")", "{", "$", "this", "->", "addOptionValue", "(", "$", "optionValue", ")", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lmammino/e-foundation/blob/198b7047d93eb11c9bc0c7ddf0bfa8229d42807a/src/Variation/Model/Variant.php#L121-L128
lmammino/e-foundation
src/Variation/Model/Variant.php
Variant.addOptionValue
public function addOptionValue(OptionValueInterface $optionValue) { if (!$this->hasOptionValue($optionValue)) { $this->optionValues->add($optionValue); } return $this; }
php
public function addOptionValue(OptionValueInterface $optionValue) { if (!$this->hasOptionValue($optionValue)) { $this->optionValues->add($optionValue); } return $this; }
[ "public", "function", "addOptionValue", "(", "OptionValueInterface", "$", "optionValue", ")", "{", "if", "(", "!", "$", "this", "->", "hasOptionValue", "(", "$", "optionValue", ")", ")", "{", "$", "this", "->", "optionValues", "->", "add", "(", "$", "optionValue", ")", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lmammino/e-foundation/blob/198b7047d93eb11c9bc0c7ddf0bfa8229d42807a/src/Variation/Model/Variant.php#L133-L140
lmammino/e-foundation
src/Variation/Model/Variant.php
Variant.removeOptionValue
public function removeOptionValue(OptionValueInterface $optionValue) { if ($this->hasOptionValue($optionValue)) { $this->optionValues->removeElement($optionValue); } return $this; }
php
public function removeOptionValue(OptionValueInterface $optionValue) { if ($this->hasOptionValue($optionValue)) { $this->optionValues->removeElement($optionValue); } return $this; }
[ "public", "function", "removeOptionValue", "(", "OptionValueInterface", "$", "optionValue", ")", "{", "if", "(", "$", "this", "->", "hasOptionValue", "(", "$", "optionValue", ")", ")", "{", "$", "this", "->", "optionValues", "->", "removeElement", "(", "$", "optionValue", ")", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lmammino/e-foundation/blob/198b7047d93eb11c9bc0c7ddf0bfa8229d42807a/src/Variation/Model/Variant.php#L145-L152
lmammino/e-foundation
src/Variation/Model/Variant.php
Variant.inheritDefaults
public function inheritDefaults(VariantInterface $masterVariant) { if (!$masterVariant->isMaster()) { throw new InvalidArgumentException('Cannot inherit values from non master variant.'); } if ($this->isMaster()) { throw new LogicException('Master variant cannot inherit from another master variant.'); } return $this; }
php
public function inheritDefaults(VariantInterface $masterVariant) { if (!$masterVariant->isMaster()) { throw new InvalidArgumentException('Cannot inherit values from non master variant.'); } if ($this->isMaster()) { throw new LogicException('Master variant cannot inherit from another master variant.'); } return $this; }
[ "public", "function", "inheritDefaults", "(", "VariantInterface", "$", "masterVariant", ")", "{", "if", "(", "!", "$", "masterVariant", "->", "isMaster", "(", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot inherit values from non master variant.'", ")", ";", "}", "if", "(", "$", "this", "->", "isMaster", "(", ")", ")", "{", "throw", "new", "LogicException", "(", "'Master variant cannot inherit from another master variant.'", ")", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lmammino/e-foundation/blob/198b7047d93eb11c9bc0c7ddf0bfa8229d42807a/src/Variation/Model/Variant.php#L165-L176
webforge-labs/psc-cms
lib/Psc/CMS/EntityPropertyMeta.php
EntityPropertyMeta.getRelationEntityClass
public function getRelationEntityClass() { if ($this->type instanceof PersistentCollectionType) { return $this->type->getType()->getGClass(); } elseif ($this->type instanceof EntityType) { return $this->type->getGClass(); } }
php
public function getRelationEntityClass() { if ($this->type instanceof PersistentCollectionType) { return $this->type->getType()->getGClass(); } elseif ($this->type instanceof EntityType) { return $this->type->getGClass(); } }
[ "public", "function", "getRelationEntityClass", "(", ")", "{", "if", "(", "$", "this", "->", "type", "instanceof", "PersistentCollectionType", ")", "{", "return", "$", "this", "->", "type", "->", "getType", "(", ")", "->", "getGClass", "(", ")", ";", "}", "elseif", "(", "$", "this", "->", "type", "instanceof", "EntityType", ")", "{", "return", "$", "this", "->", "type", "->", "getGClass", "(", ")", ";", "}", "}" ]
Gibt die GClass des Entities zurück welches sich in der Relation in diesem Property befindet mach nur sinn wenn isRelation() TRUE ist @return GClass
[ "Gibt", "die", "GClass", "des", "Entities", "zurück", "welches", "sich", "in", "der", "Relation", "in", "diesem", "Property", "befindet" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/EntityPropertyMeta.php#L80-L86
webforge-labs/psc-cms
lib/Psc/CMS/EntityPropertyMeta.php
EntityPropertyMeta.getCanonicalName
public function getCanonicalName() { if (mb_strpos($this->name, 'i18n') === 0) { return mb_strtolower(mb_substr($this->name,4,1)).mb_substr($this->name, 5); } return $this->name; }
php
public function getCanonicalName() { if (mb_strpos($this->name, 'i18n') === 0) { return mb_strtolower(mb_substr($this->name,4,1)).mb_substr($this->name, 5); } return $this->name; }
[ "public", "function", "getCanonicalName", "(", ")", "{", "if", "(", "mb_strpos", "(", "$", "this", "->", "name", ",", "'i18n'", ")", "===", "0", ")", "{", "return", "mb_strtolower", "(", "mb_substr", "(", "$", "this", "->", "name", ",", "4", ",", "1", ")", ")", ".", "mb_substr", "(", "$", "this", "->", "name", ",", "5", ")", ";", "}", "return", "$", "this", "->", "name", ";", "}" ]
Returns the name of the property but cannonical cannonical means: for example without i18n in front of it
[ "Returns", "the", "name", "of", "the", "property", "but", "cannonical" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/EntityPropertyMeta.php#L125-L131
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/File/Upload.php
Zend_Validate_File_Upload.getFiles
public function getFiles($file = null) { if ($file !== null) { $return = array(); foreach ($this->_files as $name => $content) { if ($name === $file) { $return[$file] = $this->_files[$name]; } if ($content['name'] === $file) { $return[$name] = $this->_files[$name]; } } if (count($return) === 0) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("The file '$file' was not found"); } return $return; } return $this->_files; }
php
public function getFiles($file = null) { if ($file !== null) { $return = array(); foreach ($this->_files as $name => $content) { if ($name === $file) { $return[$file] = $this->_files[$name]; } if ($content['name'] === $file) { $return[$name] = $this->_files[$name]; } } if (count($return) === 0) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception("The file '$file' was not found"); } return $return; } return $this->_files; }
[ "public", "function", "getFiles", "(", "$", "file", "=", "null", ")", "{", "if", "(", "$", "file", "!==", "null", ")", "{", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "_files", "as", "$", "name", "=>", "$", "content", ")", "{", "if", "(", "$", "name", "===", "$", "file", ")", "{", "$", "return", "[", "$", "file", "]", "=", "$", "this", "->", "_files", "[", "$", "name", "]", ";", "}", "if", "(", "$", "content", "[", "'name'", "]", "===", "$", "file", ")", "{", "$", "return", "[", "$", "name", "]", "=", "$", "this", "->", "_files", "[", "$", "name", "]", ";", "}", "}", "if", "(", "count", "(", "$", "return", ")", "===", "0", ")", "{", "require_once", "'Zend/Validate/Exception.php'", ";", "throw", "new", "Zend_Validate_Exception", "(", "\"The file '$file' was not found\"", ")", ";", "}", "return", "$", "return", ";", "}", "return", "$", "this", "->", "_files", ";", "}" ]
Returns the array of set files @param string $files (Optional) The file to return in detail @return array @throws Zend_Validate_Exception If file is not found
[ "Returns", "the", "array", "of", "set", "files" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/File/Upload.php#L96-L119
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/File/Upload.php
Zend_Validate_File_Upload.setFiles
public function setFiles($files = array()) { if (count($files) === 0) { $this->_files = $_FILES; } else { $this->_files = $files; } foreach($this->_files as $file => $content) { if (!isset($content['error'])) { unset($this->_files[$file]); } } return $this; }
php
public function setFiles($files = array()) { if (count($files) === 0) { $this->_files = $_FILES; } else { $this->_files = $files; } foreach($this->_files as $file => $content) { if (!isset($content['error'])) { unset($this->_files[$file]); } } return $this; }
[ "public", "function", "setFiles", "(", "$", "files", "=", "array", "(", ")", ")", "{", "if", "(", "count", "(", "$", "files", ")", "===", "0", ")", "{", "$", "this", "->", "_files", "=", "$", "_FILES", ";", "}", "else", "{", "$", "this", "->", "_files", "=", "$", "files", ";", "}", "foreach", "(", "$", "this", "->", "_files", "as", "$", "file", "=>", "$", "content", ")", "{", "if", "(", "!", "isset", "(", "$", "content", "[", "'error'", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "_files", "[", "$", "file", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Sets the files to be checked @param array $files The files to check in syntax of Zend_File_Transfer @return Zend_Validate_File_Upload Provides a fluent interface
[ "Sets", "the", "files", "to", "be", "checked" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/File/Upload.php#L127-L142
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/File/Upload.php
Zend_Validate_File_Upload.isValid
public function isValid($value, $file = null) { if (array_key_exists($value, $this->_files)) { $files[$value] = $this->_files[$value]; } else { foreach ($this->_files as $file => $content) { if (isset($content['name']) && ($content['name'] === $value)) { $files[$file] = $this->_files[$file]; } if (isset($content['tmp_name']) && ($content['tmp_name'] === $value)) { $files[$file] = $this->_files[$file]; } } } if (empty($files)) { return $this->_throw($file, self::FILE_NOT_FOUND); } foreach ($files as $file => $content) { $this->_value = $file; switch($content['error']) { case 0: if (!is_uploaded_file($content['tmp_name'])) { $this->_throw($file, self::ATTACK); } break; case 1: $this->_throw($file, self::INI_SIZE); break; case 2: $this->_throw($file, self::FORM_SIZE); break; case 3: $this->_throw($file, self::PARTIAL); break; case 4: $this->_throw($file, self::NO_FILE); break; case 6: $this->_throw($file, self::NO_TMP_DIR); break; case 7: $this->_throw($file, self::CANT_WRITE); break; case 8: $this->_throw($file, self::EXTENSION); break; default: $this->_throw($file, self::UNKNOWN); break; } } if (count($this->_messages) > 0) { return false; } else { return true; } }
php
public function isValid($value, $file = null) { if (array_key_exists($value, $this->_files)) { $files[$value] = $this->_files[$value]; } else { foreach ($this->_files as $file => $content) { if (isset($content['name']) && ($content['name'] === $value)) { $files[$file] = $this->_files[$file]; } if (isset($content['tmp_name']) && ($content['tmp_name'] === $value)) { $files[$file] = $this->_files[$file]; } } } if (empty($files)) { return $this->_throw($file, self::FILE_NOT_FOUND); } foreach ($files as $file => $content) { $this->_value = $file; switch($content['error']) { case 0: if (!is_uploaded_file($content['tmp_name'])) { $this->_throw($file, self::ATTACK); } break; case 1: $this->_throw($file, self::INI_SIZE); break; case 2: $this->_throw($file, self::FORM_SIZE); break; case 3: $this->_throw($file, self::PARTIAL); break; case 4: $this->_throw($file, self::NO_FILE); break; case 6: $this->_throw($file, self::NO_TMP_DIR); break; case 7: $this->_throw($file, self::CANT_WRITE); break; case 8: $this->_throw($file, self::EXTENSION); break; default: $this->_throw($file, self::UNKNOWN); break; } } if (count($this->_messages) > 0) { return false; } else { return true; } }
[ "public", "function", "isValid", "(", "$", "value", ",", "$", "file", "=", "null", ")", "{", "if", "(", "array_key_exists", "(", "$", "value", ",", "$", "this", "->", "_files", ")", ")", "{", "$", "files", "[", "$", "value", "]", "=", "$", "this", "->", "_files", "[", "$", "value", "]", ";", "}", "else", "{", "foreach", "(", "$", "this", "->", "_files", "as", "$", "file", "=>", "$", "content", ")", "{", "if", "(", "isset", "(", "$", "content", "[", "'name'", "]", ")", "&&", "(", "$", "content", "[", "'name'", "]", "===", "$", "value", ")", ")", "{", "$", "files", "[", "$", "file", "]", "=", "$", "this", "->", "_files", "[", "$", "file", "]", ";", "}", "if", "(", "isset", "(", "$", "content", "[", "'tmp_name'", "]", ")", "&&", "(", "$", "content", "[", "'tmp_name'", "]", "===", "$", "value", ")", ")", "{", "$", "files", "[", "$", "file", "]", "=", "$", "this", "->", "_files", "[", "$", "file", "]", ";", "}", "}", "}", "if", "(", "empty", "(", "$", "files", ")", ")", "{", "return", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "FILE_NOT_FOUND", ")", ";", "}", "foreach", "(", "$", "files", "as", "$", "file", "=>", "$", "content", ")", "{", "$", "this", "->", "_value", "=", "$", "file", ";", "switch", "(", "$", "content", "[", "'error'", "]", ")", "{", "case", "0", ":", "if", "(", "!", "is_uploaded_file", "(", "$", "content", "[", "'tmp_name'", "]", ")", ")", "{", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "ATTACK", ")", ";", "}", "break", ";", "case", "1", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "INI_SIZE", ")", ";", "break", ";", "case", "2", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "FORM_SIZE", ")", ";", "break", ";", "case", "3", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "PARTIAL", ")", ";", "break", ";", "case", "4", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "NO_FILE", ")", ";", "break", ";", "case", "6", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "NO_TMP_DIR", ")", ";", "break", ";", "case", "7", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "CANT_WRITE", ")", ";", "break", ";", "case", "8", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "EXTENSION", ")", ";", "break", ";", "default", ":", "$", "this", "->", "_throw", "(", "$", "file", ",", "self", "::", "UNKNOWN", ")", ";", "break", ";", "}", "}", "if", "(", "count", "(", "$", "this", "->", "_messages", ")", ">", "0", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Defined by Zend_Validate_Interface Returns true if and only if the file was uploaded without errors @param string $value Single file to check for upload errors, when giving null the $_FILES array from initialization will be used @return boolean
[ "Defined", "by", "Zend_Validate_Interface" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/File/Upload.php#L153-L221
fubhy/graphql-php
src/Language/Node.php
Node.get
public function get($key, $default = NULL) { if (array_key_exists($key, $this->attributes)) { return $this->attributes[$key]; } return $default; }
php
public function get($key, $default = NULL) { if (array_key_exists($key, $this->attributes)) { return $this->attributes[$key]; } return $default; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "NULL", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "attributes", ")", ")", "{", "return", "$", "this", "->", "attributes", "[", "$", "key", "]", ";", "}", "return", "$", "default", ";", "}" ]
@param string $key @param null $default @return mixed
[ "@param", "string", "$key", "@param", "null", "$default" ]
train
https://github.com/fubhy/graphql-php/blob/c1de2233c731ca29e5c5db4c43f3b9db36478c83/src/Language/Node.php#L80-L87
haldayne/boost
src/GuardedMapAbstract.php
GuardedMapAbstract.set
public function set($key, $value) { $result = $this->allowed($value); if ($this->passes($result)) { parent::set($key, $this->normalize($value)); } else { throw new \UnexpectedValueException(sprintf( 'Value of type "%s" forbidden in this instance of %s', gettype($value), get_class($this) )); } }
php
public function set($key, $value) { $result = $this->allowed($value); if ($this->passes($result)) { parent::set($key, $this->normalize($value)); } else { throw new \UnexpectedValueException(sprintf( 'Value of type "%s" forbidden in this instance of %s', gettype($value), get_class($this) )); } }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "$", "result", "=", "$", "this", "->", "allowed", "(", "$", "value", ")", ";", "if", "(", "$", "this", "->", "passes", "(", "$", "result", ")", ")", "{", "parent", "::", "set", "(", "$", "key", ",", "$", "this", "->", "normalize", "(", "$", "value", ")", ")", ";", "}", "else", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "sprintf", "(", "'Value of type \"%s\" forbidden in this instance of %s'", ",", "gettype", "(", "$", "value", ")", ",", "get_class", "(", "$", "this", ")", ")", ")", ";", "}", "}" ]
Set the value at a given key, provided that the value passes the defined guard. Optionally, normalize the value before setting. {@inheritDoc} @throws \UnexpectedValueException
[ "Set", "the", "value", "at", "a", "given", "key", "provided", "that", "the", "value", "passes", "the", "defined", "guard", ".", "Optionally", "normalize", "the", "value", "before", "setting", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/GuardedMapAbstract.php#L25-L37
arsengoian/viper-framework
src/Viper/Core/Config.php
Config.parsePreferences
public static function parsePreferences() { foreach (new GlobIterator(root().DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'*.yaml') as $file) { $filechunks = explode(DIRECTORY_SEPARATOR,(string)$file); $chunk = array_pop($filechunks); if ($chunk == 'local.yaml' || $chunk == 'global.yaml') self::parse($file); else self::parse($file, strtoupper(explode('.', basename($file))[0])); } }
php
public static function parsePreferences() { foreach (new GlobIterator(root().DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'*.yaml') as $file) { $filechunks = explode(DIRECTORY_SEPARATOR,(string)$file); $chunk = array_pop($filechunks); if ($chunk == 'local.yaml' || $chunk == 'global.yaml') self::parse($file); else self::parse($file, strtoupper(explode('.', basename($file))[0])); } }
[ "public", "static", "function", "parsePreferences", "(", ")", "{", "foreach", "(", "new", "GlobIterator", "(", "root", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "'config'", ".", "DIRECTORY_SEPARATOR", ".", "'*.yaml'", ")", "as", "$", "file", ")", "{", "$", "filechunks", "=", "explode", "(", "DIRECTORY_SEPARATOR", ",", "(", "string", ")", "$", "file", ")", ";", "$", "chunk", "=", "array_pop", "(", "$", "filechunks", ")", ";", "if", "(", "$", "chunk", "==", "'local.yaml'", "||", "$", "chunk", "==", "'global.yaml'", ")", "self", "::", "parse", "(", "$", "file", ")", ";", "else", "self", "::", "parse", "(", "$", "file", ",", "strtoupper", "(", "explode", "(", "'.'", ",", "basename", "(", "$", "file", ")", ")", "[", "0", "]", ")", ")", ";", "}", "}" ]
TODO parse not all configs (because it's taking too much time). Find a more efficient yaml parser
[ "TODO", "parse", "not", "all", "configs", "(", "because", "it", "s", "taking", "too", "much", "time", ")", ".", "Find", "a", "more", "efficient", "yaml", "parser" ]
train
https://github.com/arsengoian/viper-framework/blob/22796c5cc219cae3ca0b4af370a347ba2acab0f2/src/Viper/Core/Config.php#L28-L36
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php
BaseRoleQuery.create
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof RoleQuery) { return $criteria; } $query = new RoleQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
php
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof RoleQuery) { return $criteria; } $query = new RoleQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
[ "public", "static", "function", "create", "(", "$", "modelAlias", "=", "null", ",", "$", "criteria", "=", "null", ")", "{", "if", "(", "$", "criteria", "instanceof", "RoleQuery", ")", "{", "return", "$", "criteria", ";", "}", "$", "query", "=", "new", "RoleQuery", "(", "null", ",", "null", ",", "$", "modelAlias", ")", ";", "if", "(", "$", "criteria", "instanceof", "Criteria", ")", "{", "$", "query", "->", "mergeWith", "(", "$", "criteria", ")", ";", "}", "return", "$", "query", ";", "}" ]
Returns a new RoleQuery object. @param string $modelAlias The alias of a model in the query @param RoleQuery|Criteria $criteria Optional Criteria to build the query from @return RoleQuery
[ "Returns", "a", "new", "RoleQuery", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php#L75-L87
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php
BaseRoleQuery.filterByRole
public function filterByRole($role = null, $comparison = null) { if (null === $comparison) { if (is_array($role)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $role)) { $role = str_replace('*', '%', $role); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(RolePeer::ROLE, $role, $comparison); }
php
public function filterByRole($role = null, $comparison = null) { if (null === $comparison) { if (is_array($role)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $role)) { $role = str_replace('*', '%', $role); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(RolePeer::ROLE, $role, $comparison); }
[ "public", "function", "filterByRole", "(", "$", "role", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "role", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "role", ")", ")", "{", "$", "role", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "role", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "RolePeer", "::", "ROLE", ",", "$", "role", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the role column Example usage: <code> $query->filterByRole('fooValue'); // WHERE role = 'fooValue' $query->filterByRole('%fooValue%'); // WHERE role LIKE '%fooValue%' </code> @param string $role The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return RoleQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "role", "column" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php#L326-L338
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php
BaseRoleQuery.filterByUserRole
public function filterByUserRole($userRole, $comparison = null) { if ($userRole instanceof UserRole) { return $this ->addUsingAlias(RolePeer::ID, $userRole->getRoleId(), $comparison); } elseif ($userRole instanceof PropelObjectCollection) { return $this ->useUserRoleQuery() ->filterByPrimaryKeys($userRole->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByUserRole() only accepts arguments of type UserRole or PropelCollection'); } }
php
public function filterByUserRole($userRole, $comparison = null) { if ($userRole instanceof UserRole) { return $this ->addUsingAlias(RolePeer::ID, $userRole->getRoleId(), $comparison); } elseif ($userRole instanceof PropelObjectCollection) { return $this ->useUserRoleQuery() ->filterByPrimaryKeys($userRole->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByUserRole() only accepts arguments of type UserRole or PropelCollection'); } }
[ "public", "function", "filterByUserRole", "(", "$", "userRole", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "userRole", "instanceof", "UserRole", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "RolePeer", "::", "ID", ",", "$", "userRole", "->", "getRoleId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "userRole", "instanceof", "PropelObjectCollection", ")", "{", "return", "$", "this", "->", "useUserRoleQuery", "(", ")", "->", "filterByPrimaryKeys", "(", "$", "userRole", "->", "getPrimaryKeys", "(", ")", ")", "->", "endUse", "(", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByUserRole() only accepts arguments of type UserRole or PropelCollection'", ")", ";", "}", "}" ]
Filter the query by a related UserRole object @param UserRole|PropelObjectCollection $userRole the related object to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return RoleQuery The current query, for fluid interface @throws PropelException - if the provided filter is invalid.
[ "Filter", "the", "query", "by", "a", "related", "UserRole", "object" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php#L349-L362
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php
BaseRoleQuery.prune
public function prune($role = null) { if ($role) { $this->addUsingAlias(RolePeer::ID, $role->getId(), Criteria::NOT_EQUAL); } return $this; }
php
public function prune($role = null) { if ($role) { $this->addUsingAlias(RolePeer::ID, $role->getId(), Criteria::NOT_EQUAL); } return $this; }
[ "public", "function", "prune", "(", "$", "role", "=", "null", ")", "{", "if", "(", "$", "role", ")", "{", "$", "this", "->", "addUsingAlias", "(", "RolePeer", "::", "ID", ",", "$", "role", "->", "getId", "(", ")", ",", "Criteria", "::", "NOT_EQUAL", ")", ";", "}", "return", "$", "this", ";", "}" ]
Exclude object from result @param Role $role Object to remove from the list of results @return RoleQuery The current query, for fluid interface
[ "Exclude", "object", "from", "result" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseRoleQuery.php#L421-L428
anime-db/app-bundle
src/Service/CommandExecutor.php
CommandExecutor.execute
public function execute($command, $timeout = 300, $callback = null) { if ($timeout > 0 || is_callable($callback)) { $this->executeCommand($command, $timeout, $callback); } else { $this->executeCommandInBackground($command); } }
php
public function execute($command, $timeout = 300, $callback = null) { if ($timeout > 0 || is_callable($callback)) { $this->executeCommand($command, $timeout, $callback); } else { $this->executeCommandInBackground($command); } }
[ "public", "function", "execute", "(", "$", "command", ",", "$", "timeout", "=", "300", ",", "$", "callback", "=", "null", ")", "{", "if", "(", "$", "timeout", ">", "0", "||", "is_callable", "(", "$", "callback", ")", ")", "{", "$", "this", "->", "executeCommand", "(", "$", "command", ",", "$", "timeout", ",", "$", "callback", ")", ";", "}", "else", "{", "$", "this", "->", "executeCommandInBackground", "(", "$", "command", ")", ";", "}", "}" ]
Execute command. If timeout <= 0 and callback is null then command will be executed in background @param string $command @param int $timeout @param callable|null $callback
[ "Execute", "command", "." ]
train
https://github.com/anime-db/app-bundle/blob/ca3b342081719d41ba018792a75970cbb1f1fe22/src/Service/CommandExecutor.php#L98-L105
anime-db/app-bundle
src/Service/CommandExecutor.php
CommandExecutor.executeCommand
protected function executeCommand($command, $timeout = 300, $callback = null) { $process = new Process($this->prepare($command), $this->cwd, null, null, $timeout); $process->run($callback); if (!$process->isSuccessful()) { throw new \RuntimeException(sprintf('An error occurred when executing the "%s" command.', $command)); } }
php
protected function executeCommand($command, $timeout = 300, $callback = null) { $process = new Process($this->prepare($command), $this->cwd, null, null, $timeout); $process->run($callback); if (!$process->isSuccessful()) { throw new \RuntimeException(sprintf('An error occurred when executing the "%s" command.', $command)); } }
[ "protected", "function", "executeCommand", "(", "$", "command", ",", "$", "timeout", "=", "300", ",", "$", "callback", "=", "null", ")", "{", "$", "process", "=", "new", "Process", "(", "$", "this", "->", "prepare", "(", "$", "command", ")", ",", "$", "this", "->", "cwd", ",", "null", ",", "null", ",", "$", "timeout", ")", ";", "$", "process", "->", "run", "(", "$", "callback", ")", ";", "if", "(", "!", "$", "process", "->", "isSuccessful", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'An error occurred when executing the \"%s\" command.'", ",", "$", "command", ")", ")", ";", "}", "}" ]
@throws \RuntimeException @param string $command @param int $timeout @param callable|null $callback
[ "@throws", "\\", "RuntimeException" ]
train
https://github.com/anime-db/app-bundle/blob/ca3b342081719d41ba018792a75970cbb1f1fe22/src/Service/CommandExecutor.php#L124-L131
anime-db/app-bundle
src/Service/CommandExecutor.php
CommandExecutor.send
public function send($command, $host = '') { $host = $host ?: $this->host; if (!$host) { throw new \InvalidArgumentException('Unknown host that will run the command'); } $content = 'command='.urlencode($command); $fp = fsockopen($this->host, 80, $errno, $errstr, self::TIMEOUT); $request = 'POST '.$this->path." HTTP/1.1\r\n"; $request .= 'Host: '.$host."\r\n"; $request .= "Content-Type: application/x-www-form-urlencoded\r\n"; $request .= 'Content-Length: '.strlen($content)."\r\n"; $request .= "Connection: Close\r\n\r\n"; $request .= $content; fwrite($fp, $request); fclose($fp); }
php
public function send($command, $host = '') { $host = $host ?: $this->host; if (!$host) { throw new \InvalidArgumentException('Unknown host that will run the command'); } $content = 'command='.urlencode($command); $fp = fsockopen($this->host, 80, $errno, $errstr, self::TIMEOUT); $request = 'POST '.$this->path." HTTP/1.1\r\n"; $request .= 'Host: '.$host."\r\n"; $request .= "Content-Type: application/x-www-form-urlencoded\r\n"; $request .= 'Content-Length: '.strlen($content)."\r\n"; $request .= "Connection: Close\r\n\r\n"; $request .= $content; fwrite($fp, $request); fclose($fp); }
[ "public", "function", "send", "(", "$", "command", ",", "$", "host", "=", "''", ")", "{", "$", "host", "=", "$", "host", "?", ":", "$", "this", "->", "host", ";", "if", "(", "!", "$", "host", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unknown host that will run the command'", ")", ";", "}", "$", "content", "=", "'command='", ".", "urlencode", "(", "$", "command", ")", ";", "$", "fp", "=", "fsockopen", "(", "$", "this", "->", "host", ",", "80", ",", "$", "errno", ",", "$", "errstr", ",", "self", "::", "TIMEOUT", ")", ";", "$", "request", "=", "'POST '", ".", "$", "this", "->", "path", ".", "\" HTTP/1.1\\r\\n\"", ";", "$", "request", ".=", "'Host: '", ".", "$", "host", ".", "\"\\r\\n\"", ";", "$", "request", ".=", "\"Content-Type: application/x-www-form-urlencoded\\r\\n\"", ";", "$", "request", ".=", "'Content-Length: '", ".", "strlen", "(", "$", "content", ")", ".", "\"\\r\\n\"", ";", "$", "request", ".=", "\"Connection: Close\\r\\n\\r\\n\"", ";", "$", "request", ".=", "$", "content", ";", "fwrite", "(", "$", "fp", ",", "$", "request", ")", ";", "fclose", "(", "$", "fp", ")", ";", "}" ]
Send the command to perform in a new thread. @param string $command @param string $host
[ "Send", "the", "command", "to", "perform", "in", "a", "new", "thread", "." ]
train
https://github.com/anime-db/app-bundle/blob/ca3b342081719d41ba018792a75970cbb1f1fe22/src/Service/CommandExecutor.php#L157-L174
anime-db/app-bundle
src/Service/CommandExecutor.php
CommandExecutor.prepare
public function prepare($command) { // change path for php if (substr($command, 0, 4) == 'php ') { $command = $this->finder->getPath().substr($command, 3); } // change path to console $command = str_replace(' app/console ', ' '.$this->console.' ', $command); // change /dev/null for Windows if (defined('PHP_WINDOWS_VERSION_BUILD')) { $command = str_replace('/dev/null', 'nul', $command); } return $command; }
php
public function prepare($command) { // change path for php if (substr($command, 0, 4) == 'php ') { $command = $this->finder->getPath().substr($command, 3); } // change path to console $command = str_replace(' app/console ', ' '.$this->console.' ', $command); // change /dev/null for Windows if (defined('PHP_WINDOWS_VERSION_BUILD')) { $command = str_replace('/dev/null', 'nul', $command); } return $command; }
[ "public", "function", "prepare", "(", "$", "command", ")", "{", "// change path for php", "if", "(", "substr", "(", "$", "command", ",", "0", ",", "4", ")", "==", "'php '", ")", "{", "$", "command", "=", "$", "this", "->", "finder", "->", "getPath", "(", ")", ".", "substr", "(", "$", "command", ",", "3", ")", ";", "}", "// change path to console", "$", "command", "=", "str_replace", "(", "' app/console '", ",", "' '", ".", "$", "this", "->", "console", ".", "' '", ",", "$", "command", ")", ";", "// change /dev/null for Windows", "if", "(", "defined", "(", "'PHP_WINDOWS_VERSION_BUILD'", ")", ")", "{", "$", "command", "=", "str_replace", "(", "'/dev/null'", ",", "'nul'", ",", "$", "command", ")", ";", "}", "return", "$", "command", ";", "}" ]
@param string $command @return string
[ "@param", "string", "$command" ]
train
https://github.com/anime-db/app-bundle/blob/ca3b342081719d41ba018792a75970cbb1f1fe22/src/Service/CommandExecutor.php#L181-L197
cviebrock/guzzle-stripbom-plugin
src/Cviebrock/Guzzle/Plugin/StripBom/StripBomPlugin.php
StripBomPlugin.onRequestComplete
public function onRequestComplete(Event $event) { if ($body = $event['response']->getBody()) { if (substr($body, 0, 3) === "\xef\xbb\xbf") { // UTF-8 $event['response']->setBody(substr($body, 3)); } else if (substr($body, 0, 4) === "\xff\xfe\x00\x00" || substr($body, 0, 4) === "\x00\x00\xfe\xff" ) { // UTF-32 $event['response']->setBody(substr($body, 4)); } else if (substr($body, 0, 2) === "\xff\xfe" || substr($body, 0, 2) === "\xfe\xff" ) { // UTF-16 $event['response']->setBody(substr($body, 2)); } } }
php
public function onRequestComplete(Event $event) { if ($body = $event['response']->getBody()) { if (substr($body, 0, 3) === "\xef\xbb\xbf") { // UTF-8 $event['response']->setBody(substr($body, 3)); } else if (substr($body, 0, 4) === "\xff\xfe\x00\x00" || substr($body, 0, 4) === "\x00\x00\xfe\xff" ) { // UTF-32 $event['response']->setBody(substr($body, 4)); } else if (substr($body, 0, 2) === "\xff\xfe" || substr($body, 0, 2) === "\xfe\xff" ) { // UTF-16 $event['response']->setBody(substr($body, 2)); } } }
[ "public", "function", "onRequestComplete", "(", "Event", "$", "event", ")", "{", "if", "(", "$", "body", "=", "$", "event", "[", "'response'", "]", "->", "getBody", "(", ")", ")", "{", "if", "(", "substr", "(", "$", "body", ",", "0", ",", "3", ")", "===", "\"\\xef\\xbb\\xbf\"", ")", "{", "// UTF-8", "$", "event", "[", "'response'", "]", "->", "setBody", "(", "substr", "(", "$", "body", ",", "3", ")", ")", ";", "}", "else", "if", "(", "substr", "(", "$", "body", ",", "0", ",", "4", ")", "===", "\"\\xff\\xfe\\x00\\x00\"", "||", "substr", "(", "$", "body", ",", "0", ",", "4", ")", "===", "\"\\x00\\x00\\xfe\\xff\"", ")", "{", "// UTF-32", "$", "event", "[", "'response'", "]", "->", "setBody", "(", "substr", "(", "$", "body", ",", "4", ")", ")", ";", "}", "else", "if", "(", "substr", "(", "$", "body", ",", "0", ",", "2", ")", "===", "\"\\xff\\xfe\"", "||", "substr", "(", "$", "body", ",", "0", ",", "2", ")", "===", "\"\\xfe\\xff\"", ")", "{", "// UTF-16", "$", "event", "[", "'response'", "]", "->", "setBody", "(", "substr", "(", "$", "body", ",", "2", ")", ")", ";", "}", "}", "}" ]
When the request is complete, check the message body and strip any BOMs, if they exist. @param Event $event
[ "When", "the", "request", "is", "complete", "check", "the", "message", "body", "and", "strip", "any", "BOMs", "if", "they", "exist", "." ]
train
https://github.com/cviebrock/guzzle-stripbom-plugin/blob/a8e7b5e166572790865d49eaf832e8e8ef8d7f21/src/Cviebrock/Guzzle/Plugin/StripBom/StripBomPlugin.php#L26-L44
phore/phore-micro-app
src/Auth/AclRule.php
AclRule.REJECT
public function REJECT(int $http_code=403, string $message="Access denied") : self { $this->rejectHttpCode = $http_code; $this->rejectMessage = $message; $this->action = self::ACTION_REJECT; return $this; }
php
public function REJECT(int $http_code=403, string $message="Access denied") : self { $this->rejectHttpCode = $http_code; $this->rejectMessage = $message; $this->action = self::ACTION_REJECT; return $this; }
[ "public", "function", "REJECT", "(", "int", "$", "http_code", "=", "403", ",", "string", "$", "message", "=", "\"Access denied\"", ")", ":", "self", "{", "$", "this", "->", "rejectHttpCode", "=", "$", "http_code", ";", "$", "this", "->", "rejectMessage", "=", "$", "message", ";", "$", "this", "->", "action", "=", "self", "::", "ACTION_REJECT", ";", "return", "$", "this", ";", "}" ]
Reject the Request @param string|null $alias @return AclRule
[ "Reject", "the", "Request" ]
train
https://github.com/phore/phore-micro-app/blob/6cf87a647b8b0be05afbfe6bd020650e98558c23/src/Auth/AclRule.php#L123-L129
trendwerk/dev-uploads
class-tp-dev-uploads.php
TP_Dev_Uploads.placehold
function placehold( $rules ) { if( 'development' == WP_ENV || 'staging' == WP_ENV ) { $dir = wp_upload_dir(); $uploads_rel_path = str_replace( trailingslashit( home_url() ), '', $dir['baseurl'] ); $tp_images_rules = array( '', '# BEGIN TP Development uploads', 'RewriteCond %{REQUEST_FILENAME} !-f', 'RewriteRule ^' . $uploads_rel_path . '/(.*)-([0-9]+)x([0-9]+).(gif|jpe?g|png|bmp)$ http://www.placehold.it/$2x$3 [NC,L]', 'RewriteCond %{REQUEST_FILENAME} !-f', 'RewriteRule ^' . $uploads_rel_path . '/(.*)(gif|jpe?g|png|bmp)$ http://www.placehold.it/600x600 [NC,L]', '# END TP Development uploads', '', ); $rules = explode( "\n", $rules ); $rules = wp_parse_args( $rules, $tp_images_rules ); $rules = implode( "\n", $rules ); } return $rules; }
php
function placehold( $rules ) { if( 'development' == WP_ENV || 'staging' == WP_ENV ) { $dir = wp_upload_dir(); $uploads_rel_path = str_replace( trailingslashit( home_url() ), '', $dir['baseurl'] ); $tp_images_rules = array( '', '# BEGIN TP Development uploads', 'RewriteCond %{REQUEST_FILENAME} !-f', 'RewriteRule ^' . $uploads_rel_path . '/(.*)-([0-9]+)x([0-9]+).(gif|jpe?g|png|bmp)$ http://www.placehold.it/$2x$3 [NC,L]', 'RewriteCond %{REQUEST_FILENAME} !-f', 'RewriteRule ^' . $uploads_rel_path . '/(.*)(gif|jpe?g|png|bmp)$ http://www.placehold.it/600x600 [NC,L]', '# END TP Development uploads', '', ); $rules = explode( "\n", $rules ); $rules = wp_parse_args( $rules, $tp_images_rules ); $rules = implode( "\n", $rules ); } return $rules; }
[ "function", "placehold", "(", "$", "rules", ")", "{", "if", "(", "'development'", "==", "WP_ENV", "||", "'staging'", "==", "WP_ENV", ")", "{", "$", "dir", "=", "wp_upload_dir", "(", ")", ";", "$", "uploads_rel_path", "=", "str_replace", "(", "trailingslashit", "(", "home_url", "(", ")", ")", ",", "''", ",", "$", "dir", "[", "'baseurl'", "]", ")", ";", "$", "tp_images_rules", "=", "array", "(", "''", ",", "'# BEGIN TP Development uploads'", ",", "'RewriteCond %{REQUEST_FILENAME} !-f'", ",", "'RewriteRule ^'", ".", "$", "uploads_rel_path", ".", "'/(.*)-([0-9]+)x([0-9]+).(gif|jpe?g|png|bmp)$ http://www.placehold.it/$2x$3 [NC,L]'", ",", "'RewriteCond %{REQUEST_FILENAME} !-f'", ",", "'RewriteRule ^'", ".", "$", "uploads_rel_path", ".", "'/(.*)(gif|jpe?g|png|bmp)$ http://www.placehold.it/600x600 [NC,L]'", ",", "'# END TP Development uploads'", ",", "''", ",", ")", ";", "$", "rules", "=", "explode", "(", "\"\\n\"", ",", "$", "rules", ")", ";", "$", "rules", "=", "wp_parse_args", "(", "$", "rules", ",", "$", "tp_images_rules", ")", ";", "$", "rules", "=", "implode", "(", "\"\\n\"", ",", "$", "rules", ")", ";", "}", "return", "$", "rules", ";", "}" ]
Redirect images from uploads to placehold.it on develop and release environments if they don't exist @param string $rules WordPress' own rules @return string New rules
[ "Redirect", "images", "from", "uploads", "to", "placehold", ".", "it", "on", "develop", "and", "release", "environments", "if", "they", "don", "t", "exist" ]
train
https://github.com/trendwerk/dev-uploads/blob/31e6efbb15e329271f2e44f9a6abfd2ac0212744/class-tp-dev-uploads.php#L27-L50
dreamfactorysoftware/df-file
src/Models/FilePublicPath.php
FilePublicPath.getConfig
public static function getConfig($id, $local_config = null, $protect = true) { if (null === $config = parent::getConfig($id, $local_config, $protect)) { $config = ['public_path' => [], 'container' => null, 'service_id' => $id]; } return $config; }
php
public static function getConfig($id, $local_config = null, $protect = true) { if (null === $config = parent::getConfig($id, $local_config, $protect)) { $config = ['public_path' => [], 'container' => null, 'service_id' => $id]; } return $config; }
[ "public", "static", "function", "getConfig", "(", "$", "id", ",", "$", "local_config", "=", "null", ",", "$", "protect", "=", "true", ")", "{", "if", "(", "null", "===", "$", "config", "=", "parent", "::", "getConfig", "(", "$", "id", ",", "$", "local_config", ",", "$", "protect", ")", ")", "{", "$", "config", "=", "[", "'public_path'", "=>", "[", "]", ",", "'container'", "=>", "null", ",", "'service_id'", "=>", "$", "id", "]", ";", "}", "return", "$", "config", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Models/FilePublicPath.php#L19-L26
zodream/thirdparty
src/ALi/Aes.php
Aes.encrypt
public function encrypt($data) { $data = trim($data); $str = $this->pkcs7Pad($data, $this->blockSize); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1); $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $str, MCRYPT_MODE_CBC); return base64_encode($encrypt_str); }
php
public function encrypt($data) { $data = trim($data); $str = $this->pkcs7Pad($data, $this->blockSize); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1); $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $str, MCRYPT_MODE_CBC); return base64_encode($encrypt_str); }
[ "public", "function", "encrypt", "(", "$", "data", ")", "{", "$", "data", "=", "trim", "(", "$", "data", ")", ";", "$", "str", "=", "$", "this", "->", "pkcs7Pad", "(", "$", "data", ",", "$", "this", "->", "blockSize", ")", ";", "$", "iv", "=", "mcrypt_create_iv", "(", "mcrypt_get_iv_size", "(", "MCRYPT_RIJNDAEL_128", ",", "MCRYPT_MODE_CBC", ")", ",", "1", ")", ";", "$", "encrypt_str", "=", "mcrypt_encrypt", "(", "MCRYPT_RIJNDAEL_128", ",", "$", "this", "->", "key", ",", "$", "str", ",", "MCRYPT_MODE_CBC", ")", ";", "return", "base64_encode", "(", "$", "encrypt_str", ")", ";", "}" ]
ENCRYPT STRING @param string $data @return string
[ "ENCRYPT", "STRING" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/Aes.php#L28-L34
zodream/thirdparty
src/ALi/Aes.php
Aes.decrypt
public function decrypt($data) { //使用BASE64对需要解密的字符串进行解码 $str = base64_decode($data); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1); $encrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $str, MCRYPT_MODE_CBC); $encrypt_str = trim($encrypt_str); $encrypt_str = $this->pkcs7UnPad($encrypt_str, $this->blockSize); return $encrypt_str; }
php
public function decrypt($data) { //使用BASE64对需要解密的字符串进行解码 $str = base64_decode($data); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1); $encrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $str, MCRYPT_MODE_CBC); $encrypt_str = trim($encrypt_str); $encrypt_str = $this->pkcs7UnPad($encrypt_str, $this->blockSize); return $encrypt_str; }
[ "public", "function", "decrypt", "(", "$", "data", ")", "{", "//使用BASE64对需要解密的字符串进行解码", "$", "str", "=", "base64_decode", "(", "$", "data", ")", ";", "$", "iv", "=", "mcrypt_create_iv", "(", "mcrypt_get_iv_size", "(", "MCRYPT_RIJNDAEL_128", ",", "MCRYPT_MODE_CBC", ")", ",", "1", ")", ";", "$", "encrypt_str", "=", "mcrypt_decrypt", "(", "MCRYPT_RIJNDAEL_128", ",", "$", "this", "->", "key", ",", "$", "str", ",", "MCRYPT_MODE_CBC", ")", ";", "$", "encrypt_str", "=", "trim", "(", "$", "encrypt_str", ")", ";", "$", "encrypt_str", "=", "$", "this", "->", "pkcs7UnPad", "(", "$", "encrypt_str", ",", "$", "this", "->", "blockSize", ")", ";", "return", "$", "encrypt_str", ";", "}" ]
DECRYPT STRING @param string $data @return string
[ "DECRYPT", "STRING" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/Aes.php#L41-L49
zephia/pilot-api-client
src/Client/PilotApiClient.php
PilotApiClient.storeLead
public function storeLead(LeadData $lead_data, $notification_email = '') { $form_params = [ 'debug' => $this->debug, 'action' => 'create', 'appkey' => $this->getAppKey(), ]; $form_params = array_merge($form_params, $lead_data->toArray()); if (!empty($notification_email)) { $form_params['notification_email'] = $notification_email; } $response = $this->guzzleClient->post(self::BASE_URI, [ 'body' => $form_params ]); if ($response->getStatusCode() === 200) { $content = json_decode($response->getBody()->getContents()); if ($content->success === false) { throw new InvalidArgumentException($content->data); } return $content; } }
php
public function storeLead(LeadData $lead_data, $notification_email = '') { $form_params = [ 'debug' => $this->debug, 'action' => 'create', 'appkey' => $this->getAppKey(), ]; $form_params = array_merge($form_params, $lead_data->toArray()); if (!empty($notification_email)) { $form_params['notification_email'] = $notification_email; } $response = $this->guzzleClient->post(self::BASE_URI, [ 'body' => $form_params ]); if ($response->getStatusCode() === 200) { $content = json_decode($response->getBody()->getContents()); if ($content->success === false) { throw new InvalidArgumentException($content->data); } return $content; } }
[ "public", "function", "storeLead", "(", "LeadData", "$", "lead_data", ",", "$", "notification_email", "=", "''", ")", "{", "$", "form_params", "=", "[", "'debug'", "=>", "$", "this", "->", "debug", ",", "'action'", "=>", "'create'", ",", "'appkey'", "=>", "$", "this", "->", "getAppKey", "(", ")", ",", "]", ";", "$", "form_params", "=", "array_merge", "(", "$", "form_params", ",", "$", "lead_data", "->", "toArray", "(", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "notification_email", ")", ")", "{", "$", "form_params", "[", "'notification_email'", "]", "=", "$", "notification_email", ";", "}", "$", "response", "=", "$", "this", "->", "guzzleClient", "->", "post", "(", "self", "::", "BASE_URI", ",", "[", "'body'", "=>", "$", "form_params", "]", ")", ";", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "===", "200", ")", "{", "$", "content", "=", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ")", ";", "if", "(", "$", "content", "->", "success", "===", "false", ")", "{", "throw", "new", "InvalidArgumentException", "(", "$", "content", "->", "data", ")", ";", "}", "return", "$", "content", ";", "}", "}" ]
Stores a lead @param LeadData $lead_data @param string $notification_email @throws InvalidArgumentException @return mixed
[ "Stores", "a", "lead" ]
train
https://github.com/zephia/pilot-api-client/blob/218fbf2fc5892e2ffc554ddd01fa95d63d6e3c0f/src/Client/PilotApiClient.php#L58-L83
jjanvier/CrowdinBundle
DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('jjanvier_crowdin'); $rootNode ->children() ->arrayNode('crowdin') ->children() ->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end() ->scalarNode('project_identifier')->isRequired()->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('archive') ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('/tmp/crowdin')->cannotBeEmpty()->end() ->booleanNode('clean')->defaultFalse()->cannotBeEmpty()->end() ->scalarNode('header')->defaultNull()->end() ->end() ->end() ->arrayNode('project') ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('/tmp/crowdin')->cannotBeEmpty()->end() ->scalarNode('default_locale')->defaultValue('en')->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('git') ->addDefaultsIfNotSet() ->children() ->scalarNode('branch_prefix')->defaultValue('crowdin')->cannotBeEmpty()->end() ->scalarNode('commit_message')->defaultValue('Updating translations from Crowdin')->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('github') ->addDefaultsIfNotSet() ->children() ->scalarNode('username')->cannotBeEmpty()->end() ->scalarNode('email')->cannotBeEmpty()->end() ->scalarNode('token')->cannotBeEmpty()->end() ->scalarNode('organization')->cannotBeEmpty()->end() ->scalarNode('project')->cannotBeEmpty()->end() ->scalarNode('origin_branch')->defaultValue('master')->cannotBeEmpty()->end() ->scalarNode('pr_title')->defaultValue('[AUTO] Updating translations from Crowdin')->cannotBeEmpty()->end() ->scalarNode('pr_message')->defaultValue('')->cannotBeEmpty()->end() ->end() ->end() ->end() ; return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('jjanvier_crowdin'); $rootNode ->children() ->arrayNode('crowdin') ->children() ->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end() ->scalarNode('project_identifier')->isRequired()->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('archive') ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('/tmp/crowdin')->cannotBeEmpty()->end() ->booleanNode('clean')->defaultFalse()->cannotBeEmpty()->end() ->scalarNode('header')->defaultNull()->end() ->end() ->end() ->arrayNode('project') ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('/tmp/crowdin')->cannotBeEmpty()->end() ->scalarNode('default_locale')->defaultValue('en')->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('git') ->addDefaultsIfNotSet() ->children() ->scalarNode('branch_prefix')->defaultValue('crowdin')->cannotBeEmpty()->end() ->scalarNode('commit_message')->defaultValue('Updating translations from Crowdin')->cannotBeEmpty()->end() ->end() ->end() ->arrayNode('github') ->addDefaultsIfNotSet() ->children() ->scalarNode('username')->cannotBeEmpty()->end() ->scalarNode('email')->cannotBeEmpty()->end() ->scalarNode('token')->cannotBeEmpty()->end() ->scalarNode('organization')->cannotBeEmpty()->end() ->scalarNode('project')->cannotBeEmpty()->end() ->scalarNode('origin_branch')->defaultValue('master')->cannotBeEmpty()->end() ->scalarNode('pr_title')->defaultValue('[AUTO] Updating translations from Crowdin')->cannotBeEmpty()->end() ->scalarNode('pr_message')->defaultValue('')->cannotBeEmpty()->end() ->end() ->end() ->end() ; return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "rootNode", "=", "$", "treeBuilder", "->", "root", "(", "'jjanvier_crowdin'", ")", ";", "$", "rootNode", "->", "children", "(", ")", "->", "arrayNode", "(", "'crowdin'", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'api_key'", ")", "->", "isRequired", "(", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'project_identifier'", ")", "->", "isRequired", "(", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'archive'", ")", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'path'", ")", "->", "defaultValue", "(", "'/tmp/crowdin'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "'clean'", ")", "->", "defaultFalse", "(", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'header'", ")", "->", "defaultNull", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'project'", ")", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'path'", ")", "->", "defaultValue", "(", "'/tmp/crowdin'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'default_locale'", ")", "->", "defaultValue", "(", "'en'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'git'", ")", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'branch_prefix'", ")", "->", "defaultValue", "(", "'crowdin'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'commit_message'", ")", "->", "defaultValue", "(", "'Updating translations from Crowdin'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'github'", ")", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'username'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'email'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'token'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'organization'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'project'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'origin_branch'", ")", "->", "defaultValue", "(", "'master'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'pr_title'", ")", "->", "defaultValue", "(", "'[AUTO] Updating translations from Crowdin'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'pr_message'", ")", "->", "defaultValue", "(", "''", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "treeBuilder", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/jjanvier/CrowdinBundle/blob/ce8fa538fde7c3b9368186bf9e58e7da1c30bc69/DependencyInjection/Configuration.php#L27-L79
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Media.php
PHPWord_Media.addSectionMediaElement
public static function addSectionMediaElement($src, $type, PHPWord_Section_MemoryImage $memoryImage = null) { $mediaId = md5($src); $key = ($type == 'image') ? 'images' : 'embeddings'; if(!array_key_exists($mediaId, self::$_sectionMedia[$key])) { $cImg = self::countSectionMediaElements('images'); $cObj = self::countSectionMediaElements('embeddings'); $rID = self::countSectionMediaElements() + 7; $media = array(); if($type == 'image') { $cImg++; $inf = pathinfo($src); $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php' && $type == 'image') ? true : false; if($isMemImage) { $ext = $memoryImage->getImageExtension(); $media['isMemImage'] = true; $media['createfunction'] = $memoryImage->getImageCreateFunction(); $media['imagefunction'] = $memoryImage->getImageFunction(); } else { $ext = $inf['extension']; if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg $ext = 'jpg'; } } $folder = 'media'; $file = $type.$cImg.'.'.strtolower($ext); } elseif($type == 'oleObject') { $cObj++; $folder = 'embedding'; $file = $type.$cObj.'.bin'; } $media['source'] = $src; $media['target'] = "$folder/section_$file"; $media['type'] = $type; $media['rID'] = $rID; self::$_sectionMedia[$key][$mediaId] = $media; if($type == 'oleObject') { return array($rID, ++self::$_objectId); } else { return $rID; } } else { if($type == 'oleObject') { $rID = self::$_sectionMedia[$key][$mediaId]['rID']; return array($rID, ++self::$_objectId); } else { return self::$_sectionMedia[$key][$mediaId]['rID']; } } }
php
public static function addSectionMediaElement($src, $type, PHPWord_Section_MemoryImage $memoryImage = null) { $mediaId = md5($src); $key = ($type == 'image') ? 'images' : 'embeddings'; if(!array_key_exists($mediaId, self::$_sectionMedia[$key])) { $cImg = self::countSectionMediaElements('images'); $cObj = self::countSectionMediaElements('embeddings'); $rID = self::countSectionMediaElements() + 7; $media = array(); if($type == 'image') { $cImg++; $inf = pathinfo($src); $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php' && $type == 'image') ? true : false; if($isMemImage) { $ext = $memoryImage->getImageExtension(); $media['isMemImage'] = true; $media['createfunction'] = $memoryImage->getImageCreateFunction(); $media['imagefunction'] = $memoryImage->getImageFunction(); } else { $ext = $inf['extension']; if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg $ext = 'jpg'; } } $folder = 'media'; $file = $type.$cImg.'.'.strtolower($ext); } elseif($type == 'oleObject') { $cObj++; $folder = 'embedding'; $file = $type.$cObj.'.bin'; } $media['source'] = $src; $media['target'] = "$folder/section_$file"; $media['type'] = $type; $media['rID'] = $rID; self::$_sectionMedia[$key][$mediaId] = $media; if($type == 'oleObject') { return array($rID, ++self::$_objectId); } else { return $rID; } } else { if($type == 'oleObject') { $rID = self::$_sectionMedia[$key][$mediaId]['rID']; return array($rID, ++self::$_objectId); } else { return self::$_sectionMedia[$key][$mediaId]['rID']; } } }
[ "public", "static", "function", "addSectionMediaElement", "(", "$", "src", ",", "$", "type", ",", "PHPWord_Section_MemoryImage", "$", "memoryImage", "=", "null", ")", "{", "$", "mediaId", "=", "md5", "(", "$", "src", ")", ";", "$", "key", "=", "(", "$", "type", "==", "'image'", ")", "?", "'images'", ":", "'embeddings'", ";", "if", "(", "!", "array_key_exists", "(", "$", "mediaId", ",", "self", "::", "$", "_sectionMedia", "[", "$", "key", "]", ")", ")", "{", "$", "cImg", "=", "self", "::", "countSectionMediaElements", "(", "'images'", ")", ";", "$", "cObj", "=", "self", "::", "countSectionMediaElements", "(", "'embeddings'", ")", ";", "$", "rID", "=", "self", "::", "countSectionMediaElements", "(", ")", "+", "7", ";", "$", "media", "=", "array", "(", ")", ";", "if", "(", "$", "type", "==", "'image'", ")", "{", "$", "cImg", "++", ";", "$", "inf", "=", "pathinfo", "(", "$", "src", ")", ";", "$", "isMemImage", "=", "(", "substr", "(", "strtolower", "(", "$", "inf", "[", "'extension'", "]", ")", ",", "0", ",", "3", ")", "==", "'php'", "&&", "$", "type", "==", "'image'", ")", "?", "true", ":", "false", ";", "if", "(", "$", "isMemImage", ")", "{", "$", "ext", "=", "$", "memoryImage", "->", "getImageExtension", "(", ")", ";", "$", "media", "[", "'isMemImage'", "]", "=", "true", ";", "$", "media", "[", "'createfunction'", "]", "=", "$", "memoryImage", "->", "getImageCreateFunction", "(", ")", ";", "$", "media", "[", "'imagefunction'", "]", "=", "$", "memoryImage", "->", "getImageFunction", "(", ")", ";", "}", "else", "{", "$", "ext", "=", "$", "inf", "[", "'extension'", "]", ";", "if", "(", "$", "ext", "==", "'jpeg'", ")", "{", "// Office crashes when adding a jpEg Image, so rename to jpg\r", "$", "ext", "=", "'jpg'", ";", "}", "}", "$", "folder", "=", "'media'", ";", "$", "file", "=", "$", "type", ".", "$", "cImg", ".", "'.'", ".", "strtolower", "(", "$", "ext", ")", ";", "}", "elseif", "(", "$", "type", "==", "'oleObject'", ")", "{", "$", "cObj", "++", ";", "$", "folder", "=", "'embedding'", ";", "$", "file", "=", "$", "type", ".", "$", "cObj", ".", "'.bin'", ";", "}", "$", "media", "[", "'source'", "]", "=", "$", "src", ";", "$", "media", "[", "'target'", "]", "=", "\"$folder/section_$file\"", ";", "$", "media", "[", "'type'", "]", "=", "$", "type", ";", "$", "media", "[", "'rID'", "]", "=", "$", "rID", ";", "self", "::", "$", "_sectionMedia", "[", "$", "key", "]", "[", "$", "mediaId", "]", "=", "$", "media", ";", "if", "(", "$", "type", "==", "'oleObject'", ")", "{", "return", "array", "(", "$", "rID", ",", "++", "self", "::", "$", "_objectId", ")", ";", "}", "else", "{", "return", "$", "rID", ";", "}", "}", "else", "{", "if", "(", "$", "type", "==", "'oleObject'", ")", "{", "$", "rID", "=", "self", "::", "$", "_sectionMedia", "[", "$", "key", "]", "[", "$", "mediaId", "]", "[", "'rID'", "]", ";", "return", "array", "(", "$", "rID", ",", "++", "self", "::", "$", "_objectId", ")", ";", "}", "else", "{", "return", "self", "::", "$", "_sectionMedia", "[", "$", "key", "]", "[", "$", "mediaId", "]", "[", "'rID'", "]", ";", "}", "}", "}" ]
Add new Section Media Element @param string $src @param string $type @return mixed
[ "Add", "new", "Section", "Media", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Media.php#L77-L133
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Media.php
PHPWord_Media.addSectionLinkElement
public static function addSectionLinkElement($linkSrc) { $rID = self::countSectionMediaElements() + 7; $link = array(); $link['target'] = $linkSrc; $link['rID'] = $rID; $link['type'] = 'hyperlink'; self::$_sectionMedia['links'][] = $link; return $rID; }
php
public static function addSectionLinkElement($linkSrc) { $rID = self::countSectionMediaElements() + 7; $link = array(); $link['target'] = $linkSrc; $link['rID'] = $rID; $link['type'] = 'hyperlink'; self::$_sectionMedia['links'][] = $link; return $rID; }
[ "public", "static", "function", "addSectionLinkElement", "(", "$", "linkSrc", ")", "{", "$", "rID", "=", "self", "::", "countSectionMediaElements", "(", ")", "+", "7", ";", "$", "link", "=", "array", "(", ")", ";", "$", "link", "[", "'target'", "]", "=", "$", "linkSrc", ";", "$", "link", "[", "'rID'", "]", "=", "$", "rID", ";", "$", "link", "[", "'type'", "]", "=", "'hyperlink'", ";", "self", "::", "$", "_sectionMedia", "[", "'links'", "]", "[", "]", "=", "$", "link", ";", "return", "$", "rID", ";", "}" ]
Add new Section Link Element @param string $linkSrc @param string $linkName @return mixed
[ "Add", "new", "Section", "Link", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Media.php#L143-L154
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Media.php
PHPWord_Media.getSectionMediaElements
public static function getSectionMediaElements($key = null) { if(!is_null($key)) { return self::$_sectionMedia[$key]; } else { $arrImages = self::$_sectionMedia['images']; $arrObjects = self::$_sectionMedia['embeddings']; $arrLinks = self::$_sectionMedia['links']; return array_merge($arrImages, $arrObjects, $arrLinks); } }
php
public static function getSectionMediaElements($key = null) { if(!is_null($key)) { return self::$_sectionMedia[$key]; } else { $arrImages = self::$_sectionMedia['images']; $arrObjects = self::$_sectionMedia['embeddings']; $arrLinks = self::$_sectionMedia['links']; return array_merge($arrImages, $arrObjects, $arrLinks); } }
[ "public", "static", "function", "getSectionMediaElements", "(", "$", "key", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "key", ")", ")", "{", "return", "self", "::", "$", "_sectionMedia", "[", "$", "key", "]", ";", "}", "else", "{", "$", "arrImages", "=", "self", "::", "$", "_sectionMedia", "[", "'images'", "]", ";", "$", "arrObjects", "=", "self", "::", "$", "_sectionMedia", "[", "'embeddings'", "]", ";", "$", "arrLinks", "=", "self", "::", "$", "_sectionMedia", "[", "'links'", "]", ";", "return", "array_merge", "(", "$", "arrImages", ",", "$", "arrObjects", ",", "$", "arrLinks", ")", ";", "}", "}" ]
Get Section Media Elements @param string $key @return array
[ "Get", "Section", "Media", "Elements" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Media.php#L162-L171
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Media.php
PHPWord_Media.countSectionMediaElements
public static function countSectionMediaElements($key = null) { if(!is_null($key)) { return count(self::$_sectionMedia[$key]); } else { $cImages = count(self::$_sectionMedia['images']); $cObjects = count(self::$_sectionMedia['embeddings']); $cLinks = count(self::$_sectionMedia['links']); return ($cImages + $cObjects + $cLinks); } }
php
public static function countSectionMediaElements($key = null) { if(!is_null($key)) { return count(self::$_sectionMedia[$key]); } else { $cImages = count(self::$_sectionMedia['images']); $cObjects = count(self::$_sectionMedia['embeddings']); $cLinks = count(self::$_sectionMedia['links']); return ($cImages + $cObjects + $cLinks); } }
[ "public", "static", "function", "countSectionMediaElements", "(", "$", "key", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "key", ")", ")", "{", "return", "count", "(", "self", "::", "$", "_sectionMedia", "[", "$", "key", "]", ")", ";", "}", "else", "{", "$", "cImages", "=", "count", "(", "self", "::", "$", "_sectionMedia", "[", "'images'", "]", ")", ";", "$", "cObjects", "=", "count", "(", "self", "::", "$", "_sectionMedia", "[", "'embeddings'", "]", ")", ";", "$", "cLinks", "=", "count", "(", "self", "::", "$", "_sectionMedia", "[", "'links'", "]", ")", ";", "return", "(", "$", "cImages", "+", "$", "cObjects", "+", "$", "cLinks", ")", ";", "}", "}" ]
Get Section Media Elements Count @param string $key @return int
[ "Get", "Section", "Media", "Elements", "Count" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Media.php#L179-L188
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Media.php
PHPWord_Media.addHeaderMediaElement
public static function addHeaderMediaElement($headerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) { $mediaId = md5($src); $key = 'header'.$headerCount; if(!array_key_exists($key, self::$_headerMedia)) { self::$_headerMedia[$key] = array(); } if(!array_key_exists($mediaId, self::$_headerMedia[$key])) { $cImg = self::countHeaderMediaElements($key); $rID = $cImg + 1; $cImg++; $inf = pathinfo($src); $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php') ? true : false; $media = array(); if($isMemImage) { $ext = $memoryImage->getImageExtension(); $media['isMemImage'] = true; $media['createfunction'] = $memoryImage->getImageCreateFunction(); $media['imagefunction'] = $memoryImage->getImageFunction(); } else { $ext = $inf['extension']; if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg $ext = 'jpg'; } } $file = 'image'.$cImg.'.'.strtolower($ext); $media['source'] = $src; $media['target'] = 'media/'.$key.'_'.$file; $media['type'] = 'image'; $media['rID'] = $rID; self::$_headerMedia[$key][$mediaId] = $media; return $rID; } else { return self::$_headerMedia[$key][$mediaId]['rID']; } }
php
public static function addHeaderMediaElement($headerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) { $mediaId = md5($src); $key = 'header'.$headerCount; if(!array_key_exists($key, self::$_headerMedia)) { self::$_headerMedia[$key] = array(); } if(!array_key_exists($mediaId, self::$_headerMedia[$key])) { $cImg = self::countHeaderMediaElements($key); $rID = $cImg + 1; $cImg++; $inf = pathinfo($src); $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php') ? true : false; $media = array(); if($isMemImage) { $ext = $memoryImage->getImageExtension(); $media['isMemImage'] = true; $media['createfunction'] = $memoryImage->getImageCreateFunction(); $media['imagefunction'] = $memoryImage->getImageFunction(); } else { $ext = $inf['extension']; if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg $ext = 'jpg'; } } $file = 'image'.$cImg.'.'.strtolower($ext); $media['source'] = $src; $media['target'] = 'media/'.$key.'_'.$file; $media['type'] = 'image'; $media['rID'] = $rID; self::$_headerMedia[$key][$mediaId] = $media; return $rID; } else { return self::$_headerMedia[$key][$mediaId]['rID']; } }
[ "public", "static", "function", "addHeaderMediaElement", "(", "$", "headerCount", ",", "$", "src", ",", "PHPWord_Section_MemoryImage", "$", "memoryImage", "=", "null", ")", "{", "$", "mediaId", "=", "md5", "(", "$", "src", ")", ";", "$", "key", "=", "'header'", ".", "$", "headerCount", ";", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "self", "::", "$", "_headerMedia", ")", ")", "{", "self", "::", "$", "_headerMedia", "[", "$", "key", "]", "=", "array", "(", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "mediaId", ",", "self", "::", "$", "_headerMedia", "[", "$", "key", "]", ")", ")", "{", "$", "cImg", "=", "self", "::", "countHeaderMediaElements", "(", "$", "key", ")", ";", "$", "rID", "=", "$", "cImg", "+", "1", ";", "$", "cImg", "++", ";", "$", "inf", "=", "pathinfo", "(", "$", "src", ")", ";", "$", "isMemImage", "=", "(", "substr", "(", "strtolower", "(", "$", "inf", "[", "'extension'", "]", ")", ",", "0", ",", "3", ")", "==", "'php'", ")", "?", "true", ":", "false", ";", "$", "media", "=", "array", "(", ")", ";", "if", "(", "$", "isMemImage", ")", "{", "$", "ext", "=", "$", "memoryImage", "->", "getImageExtension", "(", ")", ";", "$", "media", "[", "'isMemImage'", "]", "=", "true", ";", "$", "media", "[", "'createfunction'", "]", "=", "$", "memoryImage", "->", "getImageCreateFunction", "(", ")", ";", "$", "media", "[", "'imagefunction'", "]", "=", "$", "memoryImage", "->", "getImageFunction", "(", ")", ";", "}", "else", "{", "$", "ext", "=", "$", "inf", "[", "'extension'", "]", ";", "if", "(", "$", "ext", "==", "'jpeg'", ")", "{", "// Office crashes when adding a jpEg Image, so rename to jpg\r", "$", "ext", "=", "'jpg'", ";", "}", "}", "$", "file", "=", "'image'", ".", "$", "cImg", ".", "'.'", ".", "strtolower", "(", "$", "ext", ")", ";", "$", "media", "[", "'source'", "]", "=", "$", "src", ";", "$", "media", "[", "'target'", "]", "=", "'media/'", ".", "$", "key", ".", "'_'", ".", "$", "file", ";", "$", "media", "[", "'type'", "]", "=", "'image'", ";", "$", "media", "[", "'rID'", "]", "=", "$", "rID", ";", "self", "::", "$", "_headerMedia", "[", "$", "key", "]", "[", "$", "mediaId", "]", "=", "$", "media", ";", "return", "$", "rID", ";", "}", "else", "{", "return", "self", "::", "$", "_headerMedia", "[", "$", "key", "]", "[", "$", "mediaId", "]", "[", "'rID'", "]", ";", "}", "}" ]
Add new Header Media Element @param int $headerCount @param string $src @return int
[ "Add", "new", "Header", "Media", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Media.php#L197-L238
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Media.php
PHPWord_Media.addFooterMediaElement
public static function addFooterMediaElement($footerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) { $mediaId = md5($src); $key = 'footer'.$footerCount; if(!array_key_exists($key, self::$_footerMedia)) { self::$_footerMedia[$key] = array(); } if(!array_key_exists($mediaId, self::$_footerMedia[$key])) { $cImg = self::countFooterMediaElements($key); $rID = $cImg + 1; $cImg++; $inf = pathinfo($src); $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php') ? true : false; $media = array(); if($isMemImage) { $ext = $memoryImage->getImageExtension(); $media['isMemImage'] = true; $media['createfunction'] = $memoryImage->getImageCreateFunction(); $media['imagefunction'] = $memoryImage->getImageFunction(); } else { $ext = $inf['extension']; if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg $ext = 'jpg'; } } $file = 'image'.$cImg.'.'.strtolower($ext); $media['source'] = $src; $media['target'] = 'media/'.$key.'_'.$file; $media['type'] = 'image'; $media['rID'] = $rID; self::$_footerMedia[$key][$mediaId] = $media; return $rID; } else { return self::$_footerMedia[$key][$mediaId]['rID']; } }
php
public static function addFooterMediaElement($footerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) { $mediaId = md5($src); $key = 'footer'.$footerCount; if(!array_key_exists($key, self::$_footerMedia)) { self::$_footerMedia[$key] = array(); } if(!array_key_exists($mediaId, self::$_footerMedia[$key])) { $cImg = self::countFooterMediaElements($key); $rID = $cImg + 1; $cImg++; $inf = pathinfo($src); $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php') ? true : false; $media = array(); if($isMemImage) { $ext = $memoryImage->getImageExtension(); $media['isMemImage'] = true; $media['createfunction'] = $memoryImage->getImageCreateFunction(); $media['imagefunction'] = $memoryImage->getImageFunction(); } else { $ext = $inf['extension']; if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg $ext = 'jpg'; } } $file = 'image'.$cImg.'.'.strtolower($ext); $media['source'] = $src; $media['target'] = 'media/'.$key.'_'.$file; $media['type'] = 'image'; $media['rID'] = $rID; self::$_footerMedia[$key][$mediaId] = $media; return $rID; } else { return self::$_footerMedia[$key][$mediaId]['rID']; } }
[ "public", "static", "function", "addFooterMediaElement", "(", "$", "footerCount", ",", "$", "src", ",", "PHPWord_Section_MemoryImage", "$", "memoryImage", "=", "null", ")", "{", "$", "mediaId", "=", "md5", "(", "$", "src", ")", ";", "$", "key", "=", "'footer'", ".", "$", "footerCount", ";", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "self", "::", "$", "_footerMedia", ")", ")", "{", "self", "::", "$", "_footerMedia", "[", "$", "key", "]", "=", "array", "(", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "mediaId", ",", "self", "::", "$", "_footerMedia", "[", "$", "key", "]", ")", ")", "{", "$", "cImg", "=", "self", "::", "countFooterMediaElements", "(", "$", "key", ")", ";", "$", "rID", "=", "$", "cImg", "+", "1", ";", "$", "cImg", "++", ";", "$", "inf", "=", "pathinfo", "(", "$", "src", ")", ";", "$", "isMemImage", "=", "(", "substr", "(", "strtolower", "(", "$", "inf", "[", "'extension'", "]", ")", ",", "0", ",", "3", ")", "==", "'php'", ")", "?", "true", ":", "false", ";", "$", "media", "=", "array", "(", ")", ";", "if", "(", "$", "isMemImage", ")", "{", "$", "ext", "=", "$", "memoryImage", "->", "getImageExtension", "(", ")", ";", "$", "media", "[", "'isMemImage'", "]", "=", "true", ";", "$", "media", "[", "'createfunction'", "]", "=", "$", "memoryImage", "->", "getImageCreateFunction", "(", ")", ";", "$", "media", "[", "'imagefunction'", "]", "=", "$", "memoryImage", "->", "getImageFunction", "(", ")", ";", "}", "else", "{", "$", "ext", "=", "$", "inf", "[", "'extension'", "]", ";", "if", "(", "$", "ext", "==", "'jpeg'", ")", "{", "// Office crashes when adding a jpEg Image, so rename to jpg\r", "$", "ext", "=", "'jpg'", ";", "}", "}", "$", "file", "=", "'image'", ".", "$", "cImg", ".", "'.'", ".", "strtolower", "(", "$", "ext", ")", ";", "$", "media", "[", "'source'", "]", "=", "$", "src", ";", "$", "media", "[", "'target'", "]", "=", "'media/'", ".", "$", "key", ".", "'_'", ".", "$", "file", ";", "$", "media", "[", "'type'", "]", "=", "'image'", ";", "$", "media", "[", "'rID'", "]", "=", "$", "rID", ";", "self", "::", "$", "_footerMedia", "[", "$", "key", "]", "[", "$", "mediaId", "]", "=", "$", "media", ";", "return", "$", "rID", ";", "}", "else", "{", "return", "self", "::", "$", "_footerMedia", "[", "$", "key", "]", "[", "$", "mediaId", "]", "[", "'rID'", "]", ";", "}", "}" ]
Add new Footer Media Element @param int $footerCount @param string $src @return int
[ "Add", "new", "Footer", "Media", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Media.php#L266-L307
lode/fem
src/build.php
build.database_dump_structure
public static function database_dump_structure($dump_directory) { if (is_dir($dump_directory) == false) { $exception = bootstrap::get_library('exception'); throw new $exception('directory not found'); } $mysql = bootstrap::get_library('mysql'); $tables = $mysql::select($mysql::AS_ARRAY, "SHOW TABLES;"); foreach ($tables as $table) { $table_name = current($table); $drop = "DROP TABLE IF EXISTS `".$table_name."`;"; $dump = $mysql::select($mysql::AS_ROW, "SHOW CREATE TABLE `%s`;", $table_name); // structure should be w/o references to data $dump = $dump['Create Table']; $dump = preg_replace('{ AUTO_INCREMENT=[0-9]+}i', '', $dump); $full_dump = $drop."\n\n".$dump.";\n"; file_put_contents($dump_directory.'/'.$table_name.'.sql', $full_dump); } }
php
public static function database_dump_structure($dump_directory) { if (is_dir($dump_directory) == false) { $exception = bootstrap::get_library('exception'); throw new $exception('directory not found'); } $mysql = bootstrap::get_library('mysql'); $tables = $mysql::select($mysql::AS_ARRAY, "SHOW TABLES;"); foreach ($tables as $table) { $table_name = current($table); $drop = "DROP TABLE IF EXISTS `".$table_name."`;"; $dump = $mysql::select($mysql::AS_ROW, "SHOW CREATE TABLE `%s`;", $table_name); // structure should be w/o references to data $dump = $dump['Create Table']; $dump = preg_replace('{ AUTO_INCREMENT=[0-9]+}i', '', $dump); $full_dump = $drop."\n\n".$dump.";\n"; file_put_contents($dump_directory.'/'.$table_name.'.sql', $full_dump); } }
[ "public", "static", "function", "database_dump_structure", "(", "$", "dump_directory", ")", "{", "if", "(", "is_dir", "(", "$", "dump_directory", ")", "==", "false", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'directory not found'", ")", ";", "}", "$", "mysql", "=", "bootstrap", "::", "get_library", "(", "'mysql'", ")", ";", "$", "tables", "=", "$", "mysql", "::", "select", "(", "$", "mysql", "::", "AS_ARRAY", ",", "\"SHOW TABLES;\"", ")", ";", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "$", "table_name", "=", "current", "(", "$", "table", ")", ";", "$", "drop", "=", "\"DROP TABLE IF EXISTS `\"", ".", "$", "table_name", ".", "\"`;\"", ";", "$", "dump", "=", "$", "mysql", "::", "select", "(", "$", "mysql", "::", "AS_ROW", ",", "\"SHOW CREATE TABLE `%s`;\"", ",", "$", "table_name", ")", ";", "// structure should be w/o references to data", "$", "dump", "=", "$", "dump", "[", "'Create Table'", "]", ";", "$", "dump", "=", "preg_replace", "(", "'{ AUTO_INCREMENT=[0-9]+}i'", ",", "''", ",", "$", "dump", ")", ";", "$", "full_dump", "=", "$", "drop", ".", "\"\\n\\n\"", ".", "$", "dump", ".", "\";\\n\"", ";", "file_put_contents", "(", "$", "dump_directory", ".", "'/'", ".", "$", "table_name", ".", "'.sql'", ",", "$", "full_dump", ")", ";", "}", "}" ]
dumps create table statements per table in the specified path @param string $dump_directory directory to be filled with tablename.sql files @return void
[ "dumps", "create", "table", "statements", "per", "table", "in", "the", "specified", "path" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/build.php#L13-L35
lode/fem
src/build.php
build.check_composer_updates
public static function check_composer_updates() { $composer_json = file_get_contents(ROOT_DIR.'/composer.json'); $composer_json = json_decode($composer_json, true); if (empty($composer_json['require'])) { $exception = bootstrap::get_library('exception'); throw new $exception('there are no required packages to check'); } $composer_lock = file_get_contents(ROOT_DIR.'/composer.lock'); $composer_lock = json_decode($composer_lock, true); if (empty($composer_lock['packages'])) { $exception = bootstrap::get_library('exception'); throw new $exception('lock file is missing its packages'); } $composer_executable = 'composer'; if (file_exists(ROOT_DIR.'composer.phar')) { $composer_executable = 'php composer.phar'; } $required_packages = $composer_json['require']; $installed_packages = $composer_lock['packages']; $update_packages = []; foreach ($installed_packages as $installed_package) { $package_name = $installed_package['name']; $installed_version = preg_replace('/v([0-9].*)/', '$1', $installed_package['version']); $version_regex = '/versions\s*:.+v?([0-9]+\.[0-9]+(\.[0-9]+)?)(,|$)/U'; // skip dependencies of dependencies if (empty($required_packages[$package_name])) { continue; } // check commit hash for dev-* versions if (strpos($installed_version, 'dev-') === 0) { $installed_version = $installed_package['source']['reference']; $version_regex = '/source\s*:.+ ([a-f0-9]{40})$/m'; } // find out the newest release $package_info = shell_exec($composer_executable.' show -a '.escapeshellarg($package_name)); preg_match($version_regex, $package_info, $possible_version); if (empty($possible_version)) { $exception = bootstrap::get_library('exception'); throw new $exception('can not find out newest release for '.$package_name); } if (ENVIRONMENT == 'development') { echo 'installed '.$package_name.' at '.$installed_version.', possible version is '.$possible_version[1].PHP_EOL; } if ($possible_version[1] == $installed_version) { continue; } $update_packages[$package_name] = [ 'required' => $required_packages[$package_name], 'installed' => $installed_version, 'possible' => $possible_version[1], ]; } return $update_packages; }
php
public static function check_composer_updates() { $composer_json = file_get_contents(ROOT_DIR.'/composer.json'); $composer_json = json_decode($composer_json, true); if (empty($composer_json['require'])) { $exception = bootstrap::get_library('exception'); throw new $exception('there are no required packages to check'); } $composer_lock = file_get_contents(ROOT_DIR.'/composer.lock'); $composer_lock = json_decode($composer_lock, true); if (empty($composer_lock['packages'])) { $exception = bootstrap::get_library('exception'); throw new $exception('lock file is missing its packages'); } $composer_executable = 'composer'; if (file_exists(ROOT_DIR.'composer.phar')) { $composer_executable = 'php composer.phar'; } $required_packages = $composer_json['require']; $installed_packages = $composer_lock['packages']; $update_packages = []; foreach ($installed_packages as $installed_package) { $package_name = $installed_package['name']; $installed_version = preg_replace('/v([0-9].*)/', '$1', $installed_package['version']); $version_regex = '/versions\s*:.+v?([0-9]+\.[0-9]+(\.[0-9]+)?)(,|$)/U'; // skip dependencies of dependencies if (empty($required_packages[$package_name])) { continue; } // check commit hash for dev-* versions if (strpos($installed_version, 'dev-') === 0) { $installed_version = $installed_package['source']['reference']; $version_regex = '/source\s*:.+ ([a-f0-9]{40})$/m'; } // find out the newest release $package_info = shell_exec($composer_executable.' show -a '.escapeshellarg($package_name)); preg_match($version_regex, $package_info, $possible_version); if (empty($possible_version)) { $exception = bootstrap::get_library('exception'); throw new $exception('can not find out newest release for '.$package_name); } if (ENVIRONMENT == 'development') { echo 'installed '.$package_name.' at '.$installed_version.', possible version is '.$possible_version[1].PHP_EOL; } if ($possible_version[1] == $installed_version) { continue; } $update_packages[$package_name] = [ 'required' => $required_packages[$package_name], 'installed' => $installed_version, 'possible' => $possible_version[1], ]; } return $update_packages; }
[ "public", "static", "function", "check_composer_updates", "(", ")", "{", "$", "composer_json", "=", "file_get_contents", "(", "ROOT_DIR", ".", "'/composer.json'", ")", ";", "$", "composer_json", "=", "json_decode", "(", "$", "composer_json", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "composer_json", "[", "'require'", "]", ")", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'there are no required packages to check'", ")", ";", "}", "$", "composer_lock", "=", "file_get_contents", "(", "ROOT_DIR", ".", "'/composer.lock'", ")", ";", "$", "composer_lock", "=", "json_decode", "(", "$", "composer_lock", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "composer_lock", "[", "'packages'", "]", ")", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'lock file is missing its packages'", ")", ";", "}", "$", "composer_executable", "=", "'composer'", ";", "if", "(", "file_exists", "(", "ROOT_DIR", ".", "'composer.phar'", ")", ")", "{", "$", "composer_executable", "=", "'php composer.phar'", ";", "}", "$", "required_packages", "=", "$", "composer_json", "[", "'require'", "]", ";", "$", "installed_packages", "=", "$", "composer_lock", "[", "'packages'", "]", ";", "$", "update_packages", "=", "[", "]", ";", "foreach", "(", "$", "installed_packages", "as", "$", "installed_package", ")", "{", "$", "package_name", "=", "$", "installed_package", "[", "'name'", "]", ";", "$", "installed_version", "=", "preg_replace", "(", "'/v([0-9].*)/'", ",", "'$1'", ",", "$", "installed_package", "[", "'version'", "]", ")", ";", "$", "version_regex", "=", "'/versions\\s*:.+v?([0-9]+\\.[0-9]+(\\.[0-9]+)?)(,|$)/U'", ";", "// skip dependencies of dependencies", "if", "(", "empty", "(", "$", "required_packages", "[", "$", "package_name", "]", ")", ")", "{", "continue", ";", "}", "// check commit hash for dev-* versions", "if", "(", "strpos", "(", "$", "installed_version", ",", "'dev-'", ")", "===", "0", ")", "{", "$", "installed_version", "=", "$", "installed_package", "[", "'source'", "]", "[", "'reference'", "]", ";", "$", "version_regex", "=", "'/source\\s*:.+ ([a-f0-9]{40})$/m'", ";", "}", "// find out the newest release", "$", "package_info", "=", "shell_exec", "(", "$", "composer_executable", ".", "' show -a '", ".", "escapeshellarg", "(", "$", "package_name", ")", ")", ";", "preg_match", "(", "$", "version_regex", ",", "$", "package_info", ",", "$", "possible_version", ")", ";", "if", "(", "empty", "(", "$", "possible_version", ")", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'can not find out newest release for '", ".", "$", "package_name", ")", ";", "}", "if", "(", "ENVIRONMENT", "==", "'development'", ")", "{", "echo", "'installed '", ".", "$", "package_name", ".", "' at '", ".", "$", "installed_version", ".", "', possible version is '", ".", "$", "possible_version", "[", "1", "]", ".", "PHP_EOL", ";", "}", "if", "(", "$", "possible_version", "[", "1", "]", "==", "$", "installed_version", ")", "{", "continue", ";", "}", "$", "update_packages", "[", "$", "package_name", "]", "=", "[", "'required'", "=>", "$", "required_packages", "[", "$", "package_name", "]", ",", "'installed'", "=>", "$", "installed_version", ",", "'possible'", "=>", "$", "possible_version", "[", "1", "]", ",", "]", ";", "}", "return", "$", "update_packages", ";", "}" ]
checks composer packages for new releases since the installed version @todo check if the required version is significantly off which would mean the json needs to change to be able to update @return array { @var $required @var $installed @var $possible }
[ "checks", "composer", "packages", "for", "new", "releases", "since", "the", "installed", "version" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/build.php#L49-L113
alanpich/slender
src/Core/ModuleResolver/ResolverStack.php
ResolverStack.getPath
public function getPath($module) { foreach ($this->resolvers as $resolver) { $path = $resolver->getPath($module); if ($path !==false) { return $path; } } return false; }
php
public function getPath($module) { foreach ($this->resolvers as $resolver) { $path = $resolver->getPath($module); if ($path !==false) { return $path; } } return false; }
[ "public", "function", "getPath", "(", "$", "module", ")", "{", "foreach", "(", "$", "this", "->", "resolvers", "as", "$", "resolver", ")", "{", "$", "path", "=", "$", "resolver", "->", "getPath", "(", "$", "module", ")", ";", "if", "(", "$", "path", "!==", "false", ")", "{", "return", "$", "path", ";", "}", "}", "return", "false", ";", "}" ]
Return the path to Module $module, or false if not found @param string $module Module name or Namespace @return string|false
[ "Return", "the", "path", "to", "Module", "$module", "or", "false", "if", "not", "found" ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/ModuleResolver/ResolverStack.php#L100-L110
alanpich/slender
src/Core/ModuleResolver/ResolverStack.php
ResolverStack.getConfig
public function getConfig($module) { if (!isset($this->cache['paths'][$module])) { $path = $this->getPath($module); $file = $path.DIRECTORY_SEPARATOR.'slender.yml'; $parsed = $this->parser->parseFile($file); $parsed['path'] = $path; $this->cache['paths'][$module] = $parsed; } return $this->cache['paths'][$module]; }
php
public function getConfig($module) { if (!isset($this->cache['paths'][$module])) { $path = $this->getPath($module); $file = $path.DIRECTORY_SEPARATOR.'slender.yml'; $parsed = $this->parser->parseFile($file); $parsed['path'] = $path; $this->cache['paths'][$module] = $parsed; } return $this->cache['paths'][$module]; }
[ "public", "function", "getConfig", "(", "$", "module", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "cache", "[", "'paths'", "]", "[", "$", "module", "]", ")", ")", "{", "$", "path", "=", "$", "this", "->", "getPath", "(", "$", "module", ")", ";", "$", "file", "=", "$", "path", ".", "DIRECTORY_SEPARATOR", ".", "'slender.yml'", ";", "$", "parsed", "=", "$", "this", "->", "parser", "->", "parseFile", "(", "$", "file", ")", ";", "$", "parsed", "[", "'path'", "]", "=", "$", "path", ";", "$", "this", "->", "cache", "[", "'paths'", "]", "[", "$", "module", "]", "=", "$", "parsed", ";", "}", "return", "$", "this", "->", "cache", "[", "'paths'", "]", "[", "$", "module", "]", ";", "}" ]
Return parsed config file for module @param $module @return mixed
[ "Return", "parsed", "config", "file", "for", "module" ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/ModuleResolver/ResolverStack.php#L118-L129
php-rise/rise
src/Request.php
Request.getHttpVersion
public function getHttpVersion() { if (!isset($this->httpVersion)) { $serverProtocol = $_SERVER['SERVER_PROTOCOL']; $this->httpVersion = substr($serverProtocol, strpos($serverProtocol, '/') + 1); } return $this->httpVersion; }
php
public function getHttpVersion() { if (!isset($this->httpVersion)) { $serverProtocol = $_SERVER['SERVER_PROTOCOL']; $this->httpVersion = substr($serverProtocol, strpos($serverProtocol, '/') + 1); } return $this->httpVersion; }
[ "public", "function", "getHttpVersion", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "httpVersion", ")", ")", "{", "$", "serverProtocol", "=", "$", "_SERVER", "[", "'SERVER_PROTOCOL'", "]", ";", "$", "this", "->", "httpVersion", "=", "substr", "(", "$", "serverProtocol", ",", "strpos", "(", "$", "serverProtocol", ",", "'/'", ")", "+", "1", ")", ";", "}", "return", "$", "this", "->", "httpVersion", ";", "}" ]
Get request HTTP version. @return string
[ "Get", "request", "HTTP", "version", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Request.php#L80-L86
php-rise/rise
src/Request.php
Request.getHost
public function getHost() { if (!is_null($this->host)) { return $this->host; } if ($_SERVER['HTTP_X_FORWARDED_HOST']) { $elements = explode(',', $value); $host = trim(end($elements)); } else if ($_SERVER['HTTP_HOST']) { $host = $_SERVER['HTTP_HOST']; } else if ($_SERVER['SERVER_NAME']) { $host = $_SERVER['SERVER_NAME']; } if (isset($host)) { $host = preg_replace('/:\d+$/', '', $host); $this->host = $host; } return $this->host; }
php
public function getHost() { if (!is_null($this->host)) { return $this->host; } if ($_SERVER['HTTP_X_FORWARDED_HOST']) { $elements = explode(',', $value); $host = trim(end($elements)); } else if ($_SERVER['HTTP_HOST']) { $host = $_SERVER['HTTP_HOST']; } else if ($_SERVER['SERVER_NAME']) { $host = $_SERVER['SERVER_NAME']; } if (isset($host)) { $host = preg_replace('/:\d+$/', '', $host); $this->host = $host; } return $this->host; }
[ "public", "function", "getHost", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "host", ")", ")", "{", "return", "$", "this", "->", "host", ";", "}", "if", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_HOST'", "]", ")", "{", "$", "elements", "=", "explode", "(", "','", ",", "$", "value", ")", ";", "$", "host", "=", "trim", "(", "end", "(", "$", "elements", ")", ")", ";", "}", "else", "if", "(", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", "{", "$", "host", "=", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ";", "}", "else", "if", "(", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ")", "{", "$", "host", "=", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ";", "}", "if", "(", "isset", "(", "$", "host", ")", ")", "{", "$", "host", "=", "preg_replace", "(", "'/:\\d+$/'", ",", "''", ",", "$", "host", ")", ";", "$", "this", "->", "host", "=", "$", "host", ";", "}", "return", "$", "this", "->", "host", ";", "}" ]
Get HTTP host. @return string
[ "Get", "HTTP", "host", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Request.php#L130-L150
php-rise/rise
src/Request.php
Request.getHeader
public function getHeader($key, $defaultValue = null) { if (!is_string($key) || $key === '') { return $defaultValue; } $key = strtoupper(str_replace('-', '_', $key)); return $_SERVER['HTTP_' . $key] ?? $_SERVER[$key] ?? $defaultValue; }
php
public function getHeader($key, $defaultValue = null) { if (!is_string($key) || $key === '') { return $defaultValue; } $key = strtoupper(str_replace('-', '_', $key)); return $_SERVER['HTTP_' . $key] ?? $_SERVER[$key] ?? $defaultValue; }
[ "public", "function", "getHeader", "(", "$", "key", ",", "$", "defaultValue", "=", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "key", ")", "||", "$", "key", "===", "''", ")", "{", "return", "$", "defaultValue", ";", "}", "$", "key", "=", "strtoupper", "(", "str_replace", "(", "'-'", ",", "'_'", ",", "$", "key", ")", ")", ";", "return", "$", "_SERVER", "[", "'HTTP_'", ".", "$", "key", "]", "??", "$", "_SERVER", "[", "$", "key", "]", "??", "$", "defaultValue", ";", "}" ]
Get header value. @param string $key @param mixed $defaultValue @return mixed
[ "Get", "header", "value", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Request.php#L159-L167
php-rise/rise
src/Request.php
Request.getContentType
public function getContentType() { if (!isset($this->contentType)) { $numOfMatches = preg_match('/^([^;]*)/', $this->getHeader('Content-Type'), $matches); if ($numOfMatches) { $this->contentType = trim($matches[1]); } else { $this->contentType = ''; } } return $this->contentType; }
php
public function getContentType() { if (!isset($this->contentType)) { $numOfMatches = preg_match('/^([^;]*)/', $this->getHeader('Content-Type'), $matches); if ($numOfMatches) { $this->contentType = trim($matches[1]); } else { $this->contentType = ''; } } return $this->contentType; }
[ "public", "function", "getContentType", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "contentType", ")", ")", "{", "$", "numOfMatches", "=", "preg_match", "(", "'/^([^;]*)/'", ",", "$", "this", "->", "getHeader", "(", "'Content-Type'", ")", ",", "$", "matches", ")", ";", "if", "(", "$", "numOfMatches", ")", "{", "$", "this", "->", "contentType", "=", "trim", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "else", "{", "$", "this", "->", "contentType", "=", "''", ";", "}", "}", "return", "$", "this", "->", "contentType", ";", "}" ]
Get content type. @return string
[ "Get", "content", "type", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Request.php#L174-L184
php-rise/rise
src/Request.php
Request.getCharset
public function getCharset() { if (!isset($this->charset)) { $numOfMatches = preg_match('/charset\s*=([^;]*)/', $this->getHeader('Content-Type'), $matches); if ($numOfMatches) { $this->charset = trim($matches[1]); } else { $this->charset = ''; } } return $this->charset; }
php
public function getCharset() { if (!isset($this->charset)) { $numOfMatches = preg_match('/charset\s*=([^;]*)/', $this->getHeader('Content-Type'), $matches); if ($numOfMatches) { $this->charset = trim($matches[1]); } else { $this->charset = ''; } } return $this->charset; }
[ "public", "function", "getCharset", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "charset", ")", ")", "{", "$", "numOfMatches", "=", "preg_match", "(", "'/charset\\s*=([^;]*)/'", ",", "$", "this", "->", "getHeader", "(", "'Content-Type'", ")", ",", "$", "matches", ")", ";", "if", "(", "$", "numOfMatches", ")", "{", "$", "this", "->", "charset", "=", "trim", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "else", "{", "$", "this", "->", "charset", "=", "''", ";", "}", "}", "return", "$", "this", "->", "charset", ";", "}" ]
Get charset. @return string
[ "Get", "charset", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Request.php#L191-L201
php-rise/rise
src/Request.php
Request.getInput
public function getInput() { if (!isset($this->input)) { switch ($this->method) { case 'POST': switch ($this->getContentType()) { case 'application/x-www-form-urlencoded': case 'multipart/form-data': $this->input = $_POST; break; default: $this->input = $this->getParamsFromInput(); break; } break; case 'PUT': case 'DELETE': $this->input = $this->getParamsFromInput(); break; default: $this->input = []; break; } } return $this->input; }
php
public function getInput() { if (!isset($this->input)) { switch ($this->method) { case 'POST': switch ($this->getContentType()) { case 'application/x-www-form-urlencoded': case 'multipart/form-data': $this->input = $_POST; break; default: $this->input = $this->getParamsFromInput(); break; } break; case 'PUT': case 'DELETE': $this->input = $this->getParamsFromInput(); break; default: $this->input = []; break; } } return $this->input; }
[ "public", "function", "getInput", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "input", ")", ")", "{", "switch", "(", "$", "this", "->", "method", ")", "{", "case", "'POST'", ":", "switch", "(", "$", "this", "->", "getContentType", "(", ")", ")", "{", "case", "'application/x-www-form-urlencoded'", ":", "case", "'multipart/form-data'", ":", "$", "this", "->", "input", "=", "$", "_POST", ";", "break", ";", "default", ":", "$", "this", "->", "input", "=", "$", "this", "->", "getParamsFromInput", "(", ")", ";", "break", ";", "}", "break", ";", "case", "'PUT'", ":", "case", "'DELETE'", ":", "$", "this", "->", "input", "=", "$", "this", "->", "getParamsFromInput", "(", ")", ";", "break", ";", "default", ":", "$", "this", "->", "input", "=", "[", "]", ";", "break", ";", "}", "}", "return", "$", "this", "->", "input", ";", "}" ]
Return HTTP POST, PUT or DELETE variables. @return array
[ "Return", "HTTP", "POST", "PUT", "or", "DELETE", "variables", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Request.php#L217-L245
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.isProductInBasket
public function isProductInBasket($hash) { foreach($this->owner->cache as $item) { if ($item['hash_product'] == $hash) return true; } return false; // return (bool)$this->find() // ->where([ // 'id_user' => $this->idUser, // 'hash_product' => $hash // ]) // ->count(); }
php
public function isProductInBasket($hash) { foreach($this->owner->cache as $item) { if ($item['hash_product'] == $hash) return true; } return false; // return (bool)$this->find() // ->where([ // 'id_user' => $this->idUser, // 'hash_product' => $hash // ]) // ->count(); }
[ "public", "function", "isProductInBasket", "(", "$", "hash", ")", "{", "foreach", "(", "$", "this", "->", "owner", "->", "cache", "as", "$", "item", ")", "{", "if", "(", "$", "item", "[", "'hash_product'", "]", "==", "$", "hash", ")", "return", "true", ";", "}", "return", "false", ";", "// return (bool)$this->find()", "// ->where([", "// 'id_user' => $this->idUser,", "// 'hash_product' => $hash", "// ])", "// ->count();", "}" ]
Проверяет, присутствует ли товар в корзине пользователя @param $hash - уникальный Хэш товара @return boolean
[ "Проверяет", "присутствует", "ли", "товар", "в", "корзине", "пользователя" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L56-L70
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.insertProduct
public function insertProduct($hash, $pid, $price, $params=[], $count=1) { // Если этот товар еще не в корзине if(!$this->isProductInBasket($hash)) { $basketProduct = new static; $basketProduct->id_user = $this->idUser; $basketProduct->storage = $this->owner->storageName; $basketProduct->id_product = $pid; $basketProduct->hash_product = $hash; $basketProduct->count = $count; $basketProduct->price = $price; $basketProduct->params = Json::encode($params); $basketProduct->created_at = time(); $basketProduct->updated_at = time(); $basketProduct->save(); } else { $basketProduct = $this->findOne([ 'id_user' => $this->idUser, 'hash_product' => $hash, 'storage' => $this->owner->storageName ]); // Если модель не найдена, генерим Exception if(is_null($basketProduct)) { throw new HttpException(404, 'Model not found'); } // Если кол-во == 0, то удаляем из корзины if(0<$count) { $basketProduct->count = $count; $basketProduct->price = $price; $basketProduct->save(); } else { $basketProduct->delete(); } } // После изменения товара в корзине, нужно обновить наш кеш $this->owner->cache = $this->getBasketProducts(); return [ 'global' => [ 'count' => Yii::$app->formatter->asInteger($this->getBasketCount()), 'total' => Yii::$app->formatter->asInteger($this->getBasketTotal()), 'cost' => Yii::$app->formatter->asCurrency($this->getBasketCost()), ], 'current' => [ 'price' => Yii::$app->formatter->asCurrency($price), 'count' => $count, 'cost' => Yii::$app->formatter->asCurrency($price*$count), ], 'result' => $this->isProductInBasket($hash) ]; }
php
public function insertProduct($hash, $pid, $price, $params=[], $count=1) { // Если этот товар еще не в корзине if(!$this->isProductInBasket($hash)) { $basketProduct = new static; $basketProduct->id_user = $this->idUser; $basketProduct->storage = $this->owner->storageName; $basketProduct->id_product = $pid; $basketProduct->hash_product = $hash; $basketProduct->count = $count; $basketProduct->price = $price; $basketProduct->params = Json::encode($params); $basketProduct->created_at = time(); $basketProduct->updated_at = time(); $basketProduct->save(); } else { $basketProduct = $this->findOne([ 'id_user' => $this->idUser, 'hash_product' => $hash, 'storage' => $this->owner->storageName ]); // Если модель не найдена, генерим Exception if(is_null($basketProduct)) { throw new HttpException(404, 'Model not found'); } // Если кол-во == 0, то удаляем из корзины if(0<$count) { $basketProduct->count = $count; $basketProduct->price = $price; $basketProduct->save(); } else { $basketProduct->delete(); } } // После изменения товара в корзине, нужно обновить наш кеш $this->owner->cache = $this->getBasketProducts(); return [ 'global' => [ 'count' => Yii::$app->formatter->asInteger($this->getBasketCount()), 'total' => Yii::$app->formatter->asInteger($this->getBasketTotal()), 'cost' => Yii::$app->formatter->asCurrency($this->getBasketCost()), ], 'current' => [ 'price' => Yii::$app->formatter->asCurrency($price), 'count' => $count, 'cost' => Yii::$app->formatter->asCurrency($price*$count), ], 'result' => $this->isProductInBasket($hash) ]; }
[ "public", "function", "insertProduct", "(", "$", "hash", ",", "$", "pid", ",", "$", "price", ",", "$", "params", "=", "[", "]", ",", "$", "count", "=", "1", ")", "{", "// Если этот товар еще не в корзине", "if", "(", "!", "$", "this", "->", "isProductInBasket", "(", "$", "hash", ")", ")", "{", "$", "basketProduct", "=", "new", "static", ";", "$", "basketProduct", "->", "id_user", "=", "$", "this", "->", "idUser", ";", "$", "basketProduct", "->", "storage", "=", "$", "this", "->", "owner", "->", "storageName", ";", "$", "basketProduct", "->", "id_product", "=", "$", "pid", ";", "$", "basketProduct", "->", "hash_product", "=", "$", "hash", ";", "$", "basketProduct", "->", "count", "=", "$", "count", ";", "$", "basketProduct", "->", "price", "=", "$", "price", ";", "$", "basketProduct", "->", "params", "=", "Json", "::", "encode", "(", "$", "params", ")", ";", "$", "basketProduct", "->", "created_at", "=", "time", "(", ")", ";", "$", "basketProduct", "->", "updated_at", "=", "time", "(", ")", ";", "$", "basketProduct", "->", "save", "(", ")", ";", "}", "else", "{", "$", "basketProduct", "=", "$", "this", "->", "findOne", "(", "[", "'id_user'", "=>", "$", "this", "->", "idUser", ",", "'hash_product'", "=>", "$", "hash", ",", "'storage'", "=>", "$", "this", "->", "owner", "->", "storageName", "]", ")", ";", "// Если модель не найдена, генерим Exception", "if", "(", "is_null", "(", "$", "basketProduct", ")", ")", "{", "throw", "new", "HttpException", "(", "404", ",", "'Model not found'", ")", ";", "}", "// Если кол-во == 0, то удаляем из корзины", "if", "(", "0", "<", "$", "count", ")", "{", "$", "basketProduct", "->", "count", "=", "$", "count", ";", "$", "basketProduct", "->", "price", "=", "$", "price", ";", "$", "basketProduct", "->", "save", "(", ")", ";", "}", "else", "{", "$", "basketProduct", "->", "delete", "(", ")", ";", "}", "}", "// После изменения товара в корзине, нужно обновить наш кеш", "$", "this", "->", "owner", "->", "cache", "=", "$", "this", "->", "getBasketProducts", "(", ")", ";", "return", "[", "'global'", "=>", "[", "'count'", "=>", "Yii", "::", "$", "app", "->", "formatter", "->", "asInteger", "(", "$", "this", "->", "getBasketCount", "(", ")", ")", ",", "'total'", "=>", "Yii", "::", "$", "app", "->", "formatter", "->", "asInteger", "(", "$", "this", "->", "getBasketTotal", "(", ")", ")", ",", "'cost'", "=>", "Yii", "::", "$", "app", "->", "formatter", "->", "asCurrency", "(", "$", "this", "->", "getBasketCost", "(", ")", ")", ",", "]", ",", "'current'", "=>", "[", "'price'", "=>", "Yii", "::", "$", "app", "->", "formatter", "->", "asCurrency", "(", "$", "price", ")", ",", "'count'", "=>", "$", "count", ",", "'cost'", "=>", "Yii", "::", "$", "app", "->", "formatter", "->", "asCurrency", "(", "$", "price", "*", "$", "count", ")", ",", "]", ",", "'result'", "=>", "$", "this", "->", "isProductInBasket", "(", "$", "hash", ")", "]", ";", "}" ]
Добавляет товар в корзину @param $hash - уникальный Хэш товара @param $pid - id товара @param $price - цена товара @param $params - дополнительные параметры товара @param $count - количество @return array @throws HttpException
[ "Добавляет", "товар", "в", "корзину" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L82-L136
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.getBasketProducts
public function getBasketProducts() { return array_map( function($item) { $item['params'] = Json::decode($item['params']); return $item; }, $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->asArray() ->all() ); }
php
public function getBasketProducts() { return array_map( function($item) { $item['params'] = Json::decode($item['params']); return $item; }, $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->asArray() ->all() ); }
[ "public", "function", "getBasketProducts", "(", ")", "{", "return", "array_map", "(", "function", "(", "$", "item", ")", "{", "$", "item", "[", "'params'", "]", "=", "Json", "::", "decode", "(", "$", "item", "[", "'params'", "]", ")", ";", "return", "$", "item", ";", "}", ",", "$", "this", "->", "find", "(", ")", "->", "where", "(", "[", "'id_user'", "=>", "$", "this", "->", "idUser", ",", "'storage'", "=>", "$", "this", "->", "owner", "->", "storageName", "]", ")", "->", "asArray", "(", ")", "->", "all", "(", ")", ")", ";", "}" ]
Возвращает список товаров в корзине @return array
[ "Возвращает", "список", "товаров", "в", "корзине" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L142-L157
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.getBasketCount
public function getBasketCount() { return $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->count(); }
php
public function getBasketCount() { return $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->count(); }
[ "public", "function", "getBasketCount", "(", ")", "{", "return", "$", "this", "->", "find", "(", ")", "->", "where", "(", "[", "'id_user'", "=>", "$", "this", "->", "idUser", ",", "'storage'", "=>", "$", "this", "->", "owner", "->", "storageName", "]", ")", "->", "count", "(", ")", ";", "}" ]
Возвращает количество наименований товара в корзине @return int
[ "Возвращает", "количество", "наименований", "товара", "в", "корзине" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L189-L197
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.getBasketTotal
public function getBasketTotal() { $total = $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->sum('count'); return ($total) ? $total : 0; }
php
public function getBasketTotal() { $total = $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->sum('count'); return ($total) ? $total : 0; }
[ "public", "function", "getBasketTotal", "(", ")", "{", "$", "total", "=", "$", "this", "->", "find", "(", ")", "->", "where", "(", "[", "'id_user'", "=>", "$", "this", "->", "idUser", ",", "'storage'", "=>", "$", "this", "->", "owner", "->", "storageName", "]", ")", "->", "sum", "(", "'count'", ")", ";", "return", "(", "$", "total", ")", "?", "$", "total", ":", "0", ";", "}" ]
Возвращает количество единиц товаров в корзине @return int
[ "Возвращает", "количество", "единиц", "товаров", "в", "корзине" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L203-L213
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.getBasketCost
public function getBasketCost() { $cost = $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->sum('price*count'); return ($cost) ? $cost : 0; }
php
public function getBasketCost() { $cost = $this->find() ->where([ 'id_user' => $this->idUser, 'storage' => $this->owner->storageName ]) ->sum('price*count'); return ($cost) ? $cost : 0; }
[ "public", "function", "getBasketCost", "(", ")", "{", "$", "cost", "=", "$", "this", "->", "find", "(", ")", "->", "where", "(", "[", "'id_user'", "=>", "$", "this", "->", "idUser", ",", "'storage'", "=>", "$", "this", "->", "owner", "->", "storageName", "]", ")", "->", "sum", "(", "'price*count'", ")", ";", "return", "(", "$", "cost", ")", "?", "$", "cost", ":", "0", ";", "}" ]
Возвращает сумму товаров в корзине @return float
[ "Возвращает", "сумму", "товаров", "в", "корзине" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L219-L229
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.merge
public function merge() { $sessionProducts = Yii::$app->session->get($this->owner->storageName, []); // Сливаем корзины из сессии и из БД в соответствии с выбранным методом switch($this->owner->mergeMethod) { // корзина в сессии и корзина в БД (если такая была) будут объеденины, а кол-во одинаковых товаров просуммируются case 'sum': $this->mergeBasket_sum( $sessionProducts ); break; // корзина в БД будет полностью заменена новой case 'new': $this->mergeBasket_new( $sessionProducts ); break; // в БД будут добавлены новые товары, а у совпадающих сохраниться наибольшее кол-во case 'max': $this->mergeBasket_max( $sessionProducts ); break; // в БД будут добавлены только новые товары default: $this->mergeBasket_merge( $sessionProducts ); } // Очищаем корзину в сессии Yii::$app->session->set($this->owner->storageName, null); }
php
public function merge() { $sessionProducts = Yii::$app->session->get($this->owner->storageName, []); // Сливаем корзины из сессии и из БД в соответствии с выбранным методом switch($this->owner->mergeMethod) { // корзина в сессии и корзина в БД (если такая была) будут объеденины, а кол-во одинаковых товаров просуммируются case 'sum': $this->mergeBasket_sum( $sessionProducts ); break; // корзина в БД будет полностью заменена новой case 'new': $this->mergeBasket_new( $sessionProducts ); break; // в БД будут добавлены новые товары, а у совпадающих сохраниться наибольшее кол-во case 'max': $this->mergeBasket_max( $sessionProducts ); break; // в БД будут добавлены только новые товары default: $this->mergeBasket_merge( $sessionProducts ); } // Очищаем корзину в сессии Yii::$app->session->set($this->owner->storageName, null); }
[ "public", "function", "merge", "(", ")", "{", "$", "sessionProducts", "=", "Yii", "::", "$", "app", "->", "session", "->", "get", "(", "$", "this", "->", "owner", "->", "storageName", ",", "[", "]", ")", ";", "// Сливаем корзины из сессии и из БД в соответствии с выбранным методом", "switch", "(", "$", "this", "->", "owner", "->", "mergeMethod", ")", "{", "// корзина в сессии и корзина в БД (если такая была) будут объеденины, а кол-во одинаковых товаров просуммируются", "case", "'sum'", ":", "$", "this", "->", "mergeBasket_sum", "(", "$", "sessionProducts", ")", ";", "break", ";", "// корзина в БД будет полностью заменена новой", "case", "'new'", ":", "$", "this", "->", "mergeBasket_new", "(", "$", "sessionProducts", ")", ";", "break", ";", "// в БД будут добавлены новые товары, а у совпадающих сохраниться наибольшее кол-во", "case", "'max'", ":", "$", "this", "->", "mergeBasket_max", "(", "$", "sessionProducts", ")", ";", "break", ";", "// в БД будут добавлены только новые товары", "default", ":", "$", "this", "->", "mergeBasket_merge", "(", "$", "sessionProducts", ")", ";", "}", "// Очищаем корзину в сессии", "Yii", "::", "$", "app", "->", "session", "->", "set", "(", "$", "this", "->", "owner", "->", "storageName", ",", "null", ")", ";", "}" ]
Сливает корзины из сессии и из БД
[ "Сливает", "корзины", "из", "сессии", "и", "из", "БД" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L234-L262
AndreyKluev/yii2-shop-basket
models/DbBasket.php
DbBasket.mergeBasket_max
public function mergeBasket_max($sessionProducts) { $dbProducts = $this->getBasketProducts(); // Пробегаем все товары из БД и сравниваем кол-во // Обработанные товары удаляем из сессии foreach($dbProducts as $bItem) { if( isset($sessionProducts[ $bItem['hash_product'] ])) { if($bItem['count']<$sessionProducts[ $bItem['hash_product'] ]['count']) { /** * @todo Нужно обновить кол-во в БД */ } // Удаляем из сессионной корзины unset( $sessionProducts[ $bItem['hash_product'] ] ); } } // Пробегаем оставшиеся в сессии товары и добавляем их в БД foreach($sessionProducts as $hash => $bItem) { $this->insertProduct($hash, $bItem['id_product'], $bItem['price'], Json::decode($bItem['params']), $bItem['count']); } }
php
public function mergeBasket_max($sessionProducts) { $dbProducts = $this->getBasketProducts(); // Пробегаем все товары из БД и сравниваем кол-во // Обработанные товары удаляем из сессии foreach($dbProducts as $bItem) { if( isset($sessionProducts[ $bItem['hash_product'] ])) { if($bItem['count']<$sessionProducts[ $bItem['hash_product'] ]['count']) { /** * @todo Нужно обновить кол-во в БД */ } // Удаляем из сессионной корзины unset( $sessionProducts[ $bItem['hash_product'] ] ); } } // Пробегаем оставшиеся в сессии товары и добавляем их в БД foreach($sessionProducts as $hash => $bItem) { $this->insertProduct($hash, $bItem['id_product'], $bItem['price'], Json::decode($bItem['params']), $bItem['count']); } }
[ "public", "function", "mergeBasket_max", "(", "$", "sessionProducts", ")", "{", "$", "dbProducts", "=", "$", "this", "->", "getBasketProducts", "(", ")", ";", "// Пробегаем все товары из БД и сравниваем кол-во", "// Обработанные товары удаляем из сессии", "foreach", "(", "$", "dbProducts", "as", "$", "bItem", ")", "{", "if", "(", "isset", "(", "$", "sessionProducts", "[", "$", "bItem", "[", "'hash_product'", "]", "]", ")", ")", "{", "if", "(", "$", "bItem", "[", "'count'", "]", "<", "$", "sessionProducts", "[", "$", "bItem", "[", "'hash_product'", "]", "]", "[", "'count'", "]", ")", "{", "/**\n * @todo Нужно обновить кол-во в БД\n */", "}", "// Удаляем из сессионной корзины", "unset", "(", "$", "sessionProducts", "[", "$", "bItem", "[", "'hash_product'", "]", "]", ")", ";", "}", "}", "// Пробегаем оставшиеся в сессии товары и добавляем их в БД", "foreach", "(", "$", "sessionProducts", "as", "$", "hash", "=>", "$", "bItem", ")", "{", "$", "this", "->", "insertProduct", "(", "$", "hash", ",", "$", "bItem", "[", "'id_product'", "]", ",", "$", "bItem", "[", "'price'", "]", ",", "Json", "::", "decode", "(", "$", "bItem", "[", "'params'", "]", ")", ",", "$", "bItem", "[", "'count'", "]", ")", ";", "}", "}" ]
Сливает корзины из сессии и из БД `max` - в БД будут добавлены новые товары, а у совпадающих сохраниться наибольшее кол-во @param $sessionProducts
[ "Сливает", "корзины", "из", "сессии", "и", "из", "БД", "max", "-", "в", "БД", "будут", "добавлены", "новые", "товары", "а", "у", "совпадающих", "сохраниться", "наибольшее", "кол", "-", "во" ]
train
https://github.com/AndreyKluev/yii2-shop-basket/blob/3bc529fd576a18403096f911112d5337cb5b1069/models/DbBasket.php#L296-L319
webforge-labs/psc-cms
lib/Psc/PHPExcel/Importer.php
Importer.process
public function process() { foreach ($this->sheet->getRowIterator() as $row) { if ($row->getRowIndex() < $this->getOption('minRow')) { $this->log .= 'Skip.minRow: '.$row->getRowIndex()."\n"; continue; } if ($row->getRowIndex() > $this->getOption('maxRow')) { $this->log .= 'Break.maxRow: '.$row->getRowIndex()."\n"; break; } $this->log .= 'processRow('.$row->getRowIndex().")\n"; $this->currentRow = $row; $this->processRow($row); } }
php
public function process() { foreach ($this->sheet->getRowIterator() as $row) { if ($row->getRowIndex() < $this->getOption('minRow')) { $this->log .= 'Skip.minRow: '.$row->getRowIndex()."\n"; continue; } if ($row->getRowIndex() > $this->getOption('maxRow')) { $this->log .= 'Break.maxRow: '.$row->getRowIndex()."\n"; break; } $this->log .= 'processRow('.$row->getRowIndex().")\n"; $this->currentRow = $row; $this->processRow($row); } }
[ "public", "function", "process", "(", ")", "{", "foreach", "(", "$", "this", "->", "sheet", "->", "getRowIterator", "(", ")", "as", "$", "row", ")", "{", "if", "(", "$", "row", "->", "getRowIndex", "(", ")", "<", "$", "this", "->", "getOption", "(", "'minRow'", ")", ")", "{", "$", "this", "->", "log", ".=", "'Skip.minRow: '", ".", "$", "row", "->", "getRowIndex", "(", ")", ".", "\"\\n\"", ";", "continue", ";", "}", "if", "(", "$", "row", "->", "getRowIndex", "(", ")", ">", "$", "this", "->", "getOption", "(", "'maxRow'", ")", ")", "{", "$", "this", "->", "log", ".=", "'Break.maxRow: '", ".", "$", "row", "->", "getRowIndex", "(", ")", ".", "\"\\n\"", ";", "break", ";", "}", "$", "this", "->", "log", ".=", "'processRow('", ".", "$", "row", "->", "getRowIndex", "(", ")", ".", "\")\\n\"", ";", "$", "this", "->", "currentRow", "=", "$", "row", ";", "$", "this", "->", "processRow", "(", "$", "row", ")", ";", "}", "}" ]
Führt für alle Zeilen des Dokumentes processRow() aus
[ "Führt", "für", "alle", "Zeilen", "des", "Dokumentes", "processRow", "()", "aus" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/PHPExcel/Importer.php#L83-L99
digitalkaoz/versioneye-php
src/Authentication/RubyConfigFileToken.php
RubyConfigFileToken.read
public function read() { if (!is_readable($this->file)) { return; } $data = file_get_contents($this->file); $data = parse_ini_string(str_replace([': ', ':'], ['= ', ''], $data)); //stupid convert from .rc to .ini if (isset($data['api_key']) && $data['api_key']) { return trim($data['api_key']); } }
php
public function read() { if (!is_readable($this->file)) { return; } $data = file_get_contents($this->file); $data = parse_ini_string(str_replace([': ', ':'], ['= ', ''], $data)); //stupid convert from .rc to .ini if (isset($data['api_key']) && $data['api_key']) { return trim($data['api_key']); } }
[ "public", "function", "read", "(", ")", "{", "if", "(", "!", "is_readable", "(", "$", "this", "->", "file", ")", ")", "{", "return", ";", "}", "$", "data", "=", "file_get_contents", "(", "$", "this", "->", "file", ")", ";", "$", "data", "=", "parse_ini_string", "(", "str_replace", "(", "[", "': '", ",", "':'", "]", ",", "[", "'= '", ",", "''", "]", ",", "$", "data", ")", ")", ";", "//stupid convert from .rc to .ini", "if", "(", "isset", "(", "$", "data", "[", "'api_key'", "]", ")", "&&", "$", "data", "[", "'api_key'", "]", ")", "{", "return", "trim", "(", "$", "data", "[", "'api_key'", "]", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/digitalkaoz/versioneye-php/blob/7b8eb9cdc83e01138dda0e709c07e3beb6aad136/src/Authentication/RubyConfigFileToken.php#L29-L41
alanpich/slender
src/Core/DependencyInjector/DependencyInjector.php
DependencyInjector.getDiRequirements
public function getDiRequirements($className) { if (!isset($this->classCache[$className])) { $reflectionClass = new \ReflectionClass($className); $injects = []; // get all defined properties $props = $reflectionClass->getProperties(); foreach ($props as $prop) { $inject = $this->annotationReader->getPropertyAnnotation( $prop, 'Slender\Core\DependencyInjector\Annotation\Inject' ); if ($inject) { // Get the DI identifier $identifier = $inject->getIdentifier(); if (!$identifier) { $identifier = Util::hyphenCase($prop->getName()); } $data = array( 'identifier' => $identifier, 'isPublic' => $prop->isPublic(), 'setter' => false ); // Is there a setter method (cos its still faster andrew...) if (!$prop->isPublic()) { $setter = Util::setterMethodName($prop->getName()); if (method_exists($className, $setter)) { $data['hasSetter'] = $setter; }; }; $injects[$prop->getName()] = $data; } } $this->classCache[$className] = $injects; } return $this->classCache[$className]; }
php
public function getDiRequirements($className) { if (!isset($this->classCache[$className])) { $reflectionClass = new \ReflectionClass($className); $injects = []; // get all defined properties $props = $reflectionClass->getProperties(); foreach ($props as $prop) { $inject = $this->annotationReader->getPropertyAnnotation( $prop, 'Slender\Core\DependencyInjector\Annotation\Inject' ); if ($inject) { // Get the DI identifier $identifier = $inject->getIdentifier(); if (!$identifier) { $identifier = Util::hyphenCase($prop->getName()); } $data = array( 'identifier' => $identifier, 'isPublic' => $prop->isPublic(), 'setter' => false ); // Is there a setter method (cos its still faster andrew...) if (!$prop->isPublic()) { $setter = Util::setterMethodName($prop->getName()); if (method_exists($className, $setter)) { $data['hasSetter'] = $setter; }; }; $injects[$prop->getName()] = $data; } } $this->classCache[$className] = $injects; } return $this->classCache[$className]; }
[ "public", "function", "getDiRequirements", "(", "$", "className", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "classCache", "[", "$", "className", "]", ")", ")", "{", "$", "reflectionClass", "=", "new", "\\", "ReflectionClass", "(", "$", "className", ")", ";", "$", "injects", "=", "[", "]", ";", "// get all defined properties", "$", "props", "=", "$", "reflectionClass", "->", "getProperties", "(", ")", ";", "foreach", "(", "$", "props", "as", "$", "prop", ")", "{", "$", "inject", "=", "$", "this", "->", "annotationReader", "->", "getPropertyAnnotation", "(", "$", "prop", ",", "'Slender\\Core\\DependencyInjector\\Annotation\\Inject'", ")", ";", "if", "(", "$", "inject", ")", "{", "// Get the DI identifier", "$", "identifier", "=", "$", "inject", "->", "getIdentifier", "(", ")", ";", "if", "(", "!", "$", "identifier", ")", "{", "$", "identifier", "=", "Util", "::", "hyphenCase", "(", "$", "prop", "->", "getName", "(", ")", ")", ";", "}", "$", "data", "=", "array", "(", "'identifier'", "=>", "$", "identifier", ",", "'isPublic'", "=>", "$", "prop", "->", "isPublic", "(", ")", ",", "'setter'", "=>", "false", ")", ";", "// Is there a setter method (cos its still faster andrew...)", "if", "(", "!", "$", "prop", "->", "isPublic", "(", ")", ")", "{", "$", "setter", "=", "Util", "::", "setterMethodName", "(", "$", "prop", "->", "getName", "(", ")", ")", ";", "if", "(", "method_exists", "(", "$", "className", ",", "$", "setter", ")", ")", "{", "$", "data", "[", "'hasSetter'", "]", "=", "$", "setter", ";", "}", ";", "}", ";", "$", "injects", "[", "$", "prop", "->", "getName", "(", ")", "]", "=", "$", "data", ";", "}", "}", "$", "this", "->", "classCache", "[", "$", "className", "]", "=", "$", "injects", ";", "}", "return", "$", "this", "->", "classCache", "[", "$", "className", "]", ";", "}" ]
Interrogate a class and see what dependencies it wants to be passed into its constructor @param string $className Name of class to inspece @return array of DI container identifiers
[ "Interrogate", "a", "class", "and", "see", "what", "dependencies", "it", "wants", "to", "be", "passed", "into", "its", "constructor" ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/DependencyInjector/DependencyInjector.php#L84-L124
alanpich/slender
src/Core/DependencyInjector/DependencyInjector.php
DependencyInjector.prepare
public function prepare(&$instance) { $requirements = $this->getDiRequirements(get_class($instance)); foreach ($requirements as $propertyName => $property) { $dependencyIdentifier = $property['identifier']; $dependency = $this->container[$dependencyIdentifier]; if (!isset($this->container[$dependencyIdentifier])) { throw new \InvalidArgumentException("Unable to resolve dependency $dependencyIdentifier for injection"); } if ($property['isPublic']) { // If its public, just set it! $instance->$propertyName = $dependency; } else { if ($property['setter']) { // If there is a setter method, use that call_user_func($instance, $property['setter'], $dependency); } else { // Otherwise set by brute force $refl = new \ReflectionClass($instance); $prop = $refl->getProperty($propertyName); $prop->setAccessible(true); $prop->setValue($instance, $this->container[$dependencyIdentifier]); $prop->setAccessible(false); } } } }
php
public function prepare(&$instance) { $requirements = $this->getDiRequirements(get_class($instance)); foreach ($requirements as $propertyName => $property) { $dependencyIdentifier = $property['identifier']; $dependency = $this->container[$dependencyIdentifier]; if (!isset($this->container[$dependencyIdentifier])) { throw new \InvalidArgumentException("Unable to resolve dependency $dependencyIdentifier for injection"); } if ($property['isPublic']) { // If its public, just set it! $instance->$propertyName = $dependency; } else { if ($property['setter']) { // If there is a setter method, use that call_user_func($instance, $property['setter'], $dependency); } else { // Otherwise set by brute force $refl = new \ReflectionClass($instance); $prop = $refl->getProperty($propertyName); $prop->setAccessible(true); $prop->setValue($instance, $this->container[$dependencyIdentifier]); $prop->setAccessible(false); } } } }
[ "public", "function", "prepare", "(", "&", "$", "instance", ")", "{", "$", "requirements", "=", "$", "this", "->", "getDiRequirements", "(", "get_class", "(", "$", "instance", ")", ")", ";", "foreach", "(", "$", "requirements", "as", "$", "propertyName", "=>", "$", "property", ")", "{", "$", "dependencyIdentifier", "=", "$", "property", "[", "'identifier'", "]", ";", "$", "dependency", "=", "$", "this", "->", "container", "[", "$", "dependencyIdentifier", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "container", "[", "$", "dependencyIdentifier", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Unable to resolve dependency $dependencyIdentifier for injection\"", ")", ";", "}", "if", "(", "$", "property", "[", "'isPublic'", "]", ")", "{", "// If its public, just set it!", "$", "instance", "->", "$", "propertyName", "=", "$", "dependency", ";", "}", "else", "{", "if", "(", "$", "property", "[", "'setter'", "]", ")", "{", "// If there is a setter method, use that", "call_user_func", "(", "$", "instance", ",", "$", "property", "[", "'setter'", "]", ",", "$", "dependency", ")", ";", "}", "else", "{", "// Otherwise set by brute force", "$", "refl", "=", "new", "\\", "ReflectionClass", "(", "$", "instance", ")", ";", "$", "prop", "=", "$", "refl", "->", "getProperty", "(", "$", "propertyName", ")", ";", "$", "prop", "->", "setAccessible", "(", "true", ")", ";", "$", "prop", "->", "setValue", "(", "$", "instance", ",", "$", "this", "->", "container", "[", "$", "dependencyIdentifier", "]", ")", ";", "$", "prop", "->", "setAccessible", "(", "false", ")", ";", "}", "}", "}", "}" ]
Scan a class instance for injectable dependencies, and inject them if found, then return prepared instance. @param object $instance Class instance to prepare @throws \RuntimeException @throws \InvalidArgumentException
[ "Scan", "a", "class", "instance", "for", "injectable", "dependencies", "and", "inject", "them", "if", "found", "then", "return", "prepared", "instance", "." ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/DependencyInjector/DependencyInjector.php#L135-L167
aedart/laravel-helpers
src/Traits/Auth/AuthFactoryTrait.php
AuthFactoryTrait.getAuthFactory
public function getAuthFactory(): ?Factory { if (!$this->hasAuthFactory()) { $this->setAuthFactory($this->getDefaultAuthFactory()); } return $this->authFactory; }
php
public function getAuthFactory(): ?Factory { if (!$this->hasAuthFactory()) { $this->setAuthFactory($this->getDefaultAuthFactory()); } return $this->authFactory; }
[ "public", "function", "getAuthFactory", "(", ")", ":", "?", "Factory", "{", "if", "(", "!", "$", "this", "->", "hasAuthFactory", "(", ")", ")", "{", "$", "this", "->", "setAuthFactory", "(", "$", "this", "->", "getDefaultAuthFactory", "(", ")", ")", ";", "}", "return", "$", "this", "->", "authFactory", ";", "}" ]
Get auth factory If no auth factory has been set, this method will set and return a default auth factory, if any such value is available @see getDefaultAuthFactory() @return Factory|null auth factory or null if none auth factory has been set
[ "Get", "auth", "factory" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Auth/AuthFactoryTrait.php#L53-L59
tigris-php/telegram-bot-api
src/Types/Base/BaseObject.php
BaseObject.build
public static function build(array $values) { $result = new static; foreach ($values as $field => $value) { /** @var $className TypeInterface */ $result->$field = $value; } return $result; }
php
public static function build(array $values) { $result = new static; foreach ($values as $field => $value) { /** @var $className TypeInterface */ $result->$field = $value; } return $result; }
[ "public", "static", "function", "build", "(", "array", "$", "values", ")", "{", "$", "result", "=", "new", "static", ";", "foreach", "(", "$", "values", "as", "$", "field", "=>", "$", "value", ")", "{", "/** @var $className TypeInterface */", "$", "result", "->", "$", "field", "=", "$", "value", ";", "}", "return", "$", "result", ";", "}" ]
Builds object from array of field values indexed by field name. @param array $values @return static
[ "Builds", "object", "from", "array", "of", "field", "values", "indexed", "by", "field", "name", "." ]
train
https://github.com/tigris-php/telegram-bot-api/blob/7350c81d571387005d58079d8c654ee44504cdcf/src/Types/Base/BaseObject.php#L40-L50
steeffeen/FancyManiaLinks
FML/Script/Features/GraphSettings.php
GraphSettings.getOnInitScriptText
protected function getOnInitScriptText() { $scriptText = ""; if ($this->minimumCoordinates) { $minimumCoordinatesValue = Builder::getVec2($this->minimumCoordinates); $scriptText .= " Graph.CoordsMin = {$minimumCoordinatesValue};"; } if ($this->maximumCoordinates) { $maximumCoordinatesValue = Builder::getVec2($this->maximumCoordinates); $scriptText .= " Graph.CoordsMax = {$maximumCoordinatesValue};"; } return $scriptText; }
php
protected function getOnInitScriptText() { $scriptText = ""; if ($this->minimumCoordinates) { $minimumCoordinatesValue = Builder::getVec2($this->minimumCoordinates); $scriptText .= " Graph.CoordsMin = {$minimumCoordinatesValue};"; } if ($this->maximumCoordinates) { $maximumCoordinatesValue = Builder::getVec2($this->maximumCoordinates); $scriptText .= " Graph.CoordsMax = {$maximumCoordinatesValue};"; } return $scriptText; }
[ "protected", "function", "getOnInitScriptText", "(", ")", "{", "$", "scriptText", "=", "\"\"", ";", "if", "(", "$", "this", "->", "minimumCoordinates", ")", "{", "$", "minimumCoordinatesValue", "=", "Builder", "::", "getVec2", "(", "$", "this", "->", "minimumCoordinates", ")", ";", "$", "scriptText", ".=", "\"\nGraph.CoordsMin = {$minimumCoordinatesValue};\"", ";", "}", "if", "(", "$", "this", "->", "maximumCoordinates", ")", "{", "$", "maximumCoordinatesValue", "=", "Builder", "::", "getVec2", "(", "$", "this", "->", "maximumCoordinates", ")", ";", "$", "scriptText", ".=", "\"\nGraph.CoordsMax = {$maximumCoordinatesValue};\"", ";", "}", "return", "$", "scriptText", ";", "}" ]
Get the on init event script text @return string
[ "Get", "the", "on", "init", "event", "script", "text" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Script/Features/GraphSettings.php#L136-L150
steeffeen/FancyManiaLinks
FML/ManiaLinks.php
ManiaLinks.addChild
public function addChild(ManiaLink $child) { if (!in_array($child, $this->children, true)) { array_push($this->children, $child); } return $this; }
php
public function addChild(ManiaLink $child) { if (!in_array($child, $this->children, true)) { array_push($this->children, $child); } return $this; }
[ "public", "function", "addChild", "(", "ManiaLink", "$", "child", ")", "{", "if", "(", "!", "in_array", "(", "$", "child", ",", "$", "this", "->", "children", ",", "true", ")", ")", "{", "array_push", "(", "$", "this", "->", "children", ",", "$", "child", ")", ";", "}", "return", "$", "this", ";", "}" ]
Add a child ManiaLink @api @param ManiaLink $child Child ManiaLink @return static
[ "Add", "a", "child", "ManiaLink" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/ManiaLinks.php#L82-L88
steeffeen/FancyManiaLinks
FML/ManiaLinks.php
ManiaLinks.getCustomUI
public function getCustomUI($createIfEmpty = true) { if (!$this->customUI && $createIfEmpty) { $this->setCustomUI(new CustomUI()); } return $this->customUI; }
php
public function getCustomUI($createIfEmpty = true) { if (!$this->customUI && $createIfEmpty) { $this->setCustomUI(new CustomUI()); } return $this->customUI; }
[ "public", "function", "getCustomUI", "(", "$", "createIfEmpty", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "customUI", "&&", "$", "createIfEmpty", ")", "{", "$", "this", "->", "setCustomUI", "(", "new", "CustomUI", "(", ")", ")", ";", "}", "return", "$", "this", "->", "customUI", ";", "}" ]
Get the CustomUI @api @param bool $createIfEmpty (optional) If the Custom UI should be created if it doesn't exist yet @return CustomUI
[ "Get", "the", "CustomUI" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/ManiaLinks.php#L150-L156
steeffeen/FancyManiaLinks
FML/ManiaLinks.php
ManiaLinks.render
public function render($echo = false) { $domDocument = new \DOMDocument("1.0", "utf-8"); $domDocument->xmlStandalone = true; $maniaLinks = $domDocument->createElement("manialinks"); $domDocument->appendChild($maniaLinks); foreach ($this->children as $child) { $childXml = $child->render(false, $domDocument); $maniaLinks->appendChild($childXml); } if ($this->customUI) { $customUIElement = $this->customUI->render($domDocument); $maniaLinks->appendChild($customUIElement); } if ($echo) { header("Content-Type: application/xml; charset=utf-8;"); echo $domDocument->saveXML(); } return $domDocument; }
php
public function render($echo = false) { $domDocument = new \DOMDocument("1.0", "utf-8"); $domDocument->xmlStandalone = true; $maniaLinks = $domDocument->createElement("manialinks"); $domDocument->appendChild($maniaLinks); foreach ($this->children as $child) { $childXml = $child->render(false, $domDocument); $maniaLinks->appendChild($childXml); } if ($this->customUI) { $customUIElement = $this->customUI->render($domDocument); $maniaLinks->appendChild($customUIElement); } if ($echo) { header("Content-Type: application/xml; charset=utf-8;"); echo $domDocument->saveXML(); } return $domDocument; }
[ "public", "function", "render", "(", "$", "echo", "=", "false", ")", "{", "$", "domDocument", "=", "new", "\\", "DOMDocument", "(", "\"1.0\"", ",", "\"utf-8\"", ")", ";", "$", "domDocument", "->", "xmlStandalone", "=", "true", ";", "$", "maniaLinks", "=", "$", "domDocument", "->", "createElement", "(", "\"manialinks\"", ")", ";", "$", "domDocument", "->", "appendChild", "(", "$", "maniaLinks", ")", ";", "foreach", "(", "$", "this", "->", "children", "as", "$", "child", ")", "{", "$", "childXml", "=", "$", "child", "->", "render", "(", "false", ",", "$", "domDocument", ")", ";", "$", "maniaLinks", "->", "appendChild", "(", "$", "childXml", ")", ";", "}", "if", "(", "$", "this", "->", "customUI", ")", "{", "$", "customUIElement", "=", "$", "this", "->", "customUI", "->", "render", "(", "$", "domDocument", ")", ";", "$", "maniaLinks", "->", "appendChild", "(", "$", "customUIElement", ")", ";", "}", "if", "(", "$", "echo", ")", "{", "header", "(", "\"Content-Type: application/xml; charset=utf-8;\"", ")", ";", "echo", "$", "domDocument", "->", "saveXML", "(", ")", ";", "}", "return", "$", "domDocument", ";", "}" ]
Render the ManiaLinks object @param bool (optional) $echo If the XML text should be echoed and the Content-Type header should be set @return \DOMDocument
[ "Render", "the", "ManiaLinks", "object" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/ManiaLinks.php#L177-L200
Double-Opt-in/php-client-api
src/Client/Commands/Responses/Response.php
Response.decoded
protected function decoded() { if ($this->json === null) { /** @var \Guzzle\Http\Message\Header $contentType */ $contentType = (string)$this->response->getHeader('content-type'); if ($contentType === 'application/json') $this->json = json_decode($this->response->getBody(true)); } return $this->json; }
php
protected function decoded() { if ($this->json === null) { /** @var \Guzzle\Http\Message\Header $contentType */ $contentType = (string)$this->response->getHeader('content-type'); if ($contentType === 'application/json') $this->json = json_decode($this->response->getBody(true)); } return $this->json; }
[ "protected", "function", "decoded", "(", ")", "{", "if", "(", "$", "this", "->", "json", "===", "null", ")", "{", "/** @var \\Guzzle\\Http\\Message\\Header $contentType */", "$", "contentType", "=", "(", "string", ")", "$", "this", "->", "response", "->", "getHeader", "(", "'content-type'", ")", ";", "if", "(", "$", "contentType", "===", "'application/json'", ")", "$", "this", "->", "json", "=", "json_decode", "(", "$", "this", "->", "response", "->", "getBody", "(", "true", ")", ")", ";", "}", "return", "$", "this", "->", "json", ";", "}" ]
returns decoded object @return null|stdClass
[ "returns", "decoded", "object" ]
train
https://github.com/Double-Opt-in/php-client-api/blob/2f17da58ec20a408bbd55b2cdd053bc689f995f4/src/Client/Commands/Responses/Response.php#L82-L92
Double-Opt-in/php-client-api
src/Client/Commands/Responses/Response.php
Response.errorMessage
public function errorMessage() { if ($this->decoded() === null) { throw new \RuntimeException('No result from server.'); } $decoded = $this->decoded(); if (isset($decoded->error)) return sprintf('%s (%s)', $decoded->error->message, $decoded->error->code); $message = sprintf('%s (%s)', $decoded->message, $this->statusCode()); if (isset($this->decoded()->errors)) { $errors = $this->decoded()->errors; $message .= $this->resolveAttributes($errors); } return $message; }
php
public function errorMessage() { if ($this->decoded() === null) { throw new \RuntimeException('No result from server.'); } $decoded = $this->decoded(); if (isset($decoded->error)) return sprintf('%s (%s)', $decoded->error->message, $decoded->error->code); $message = sprintf('%s (%s)', $decoded->message, $this->statusCode()); if (isset($this->decoded()->errors)) { $errors = $this->decoded()->errors; $message .= $this->resolveAttributes($errors); } return $message; }
[ "public", "function", "errorMessage", "(", ")", "{", "if", "(", "$", "this", "->", "decoded", "(", ")", "===", "null", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'No result from server.'", ")", ";", "}", "$", "decoded", "=", "$", "this", "->", "decoded", "(", ")", ";", "if", "(", "isset", "(", "$", "decoded", "->", "error", ")", ")", "return", "sprintf", "(", "'%s (%s)'", ",", "$", "decoded", "->", "error", "->", "message", ",", "$", "decoded", "->", "error", "->", "code", ")", ";", "$", "message", "=", "sprintf", "(", "'%s (%s)'", ",", "$", "decoded", "->", "message", ",", "$", "this", "->", "statusCode", "(", ")", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "decoded", "(", ")", "->", "errors", ")", ")", "{", "$", "errors", "=", "$", "this", "->", "decoded", "(", ")", "->", "errors", ";", "$", "message", ".=", "$", "this", "->", "resolveAttributes", "(", "$", "errors", ")", ";", "}", "return", "$", "message", ";", "}" ]
returns the error message @return string
[ "returns", "the", "error", "message" ]
train
https://github.com/Double-Opt-in/php-client-api/blob/2f17da58ec20a408bbd55b2cdd053bc689f995f4/src/Client/Commands/Responses/Response.php#L99-L118
Double-Opt-in/php-client-api
src/Client/Commands/Responses/Response.php
Response.resolveAttributes
private function resolveAttributes(stdClass $stdClass) { $attributes = array('action', 'hash', 'scope', 'data'); $message = ''; foreach ($attributes as $attribute) { $message .= $this->resolveAttribute($stdClass, $attribute); } return $message; }
php
private function resolveAttributes(stdClass $stdClass) { $attributes = array('action', 'hash', 'scope', 'data'); $message = ''; foreach ($attributes as $attribute) { $message .= $this->resolveAttribute($stdClass, $attribute); } return $message; }
[ "private", "function", "resolveAttributes", "(", "stdClass", "$", "stdClass", ")", "{", "$", "attributes", "=", "array", "(", "'action'", ",", "'hash'", ",", "'scope'", ",", "'data'", ")", ";", "$", "message", "=", "''", ";", "foreach", "(", "$", "attributes", "as", "$", "attribute", ")", "{", "$", "message", ".=", "$", "this", "->", "resolveAttribute", "(", "$", "stdClass", ",", "$", "attribute", ")", ";", "}", "return", "$", "message", ";", "}" ]
resolves all known attributes @param stdClass $stdClass @return string
[ "resolves", "all", "known", "attributes" ]
train
https://github.com/Double-Opt-in/php-client-api/blob/2f17da58ec20a408bbd55b2cdd053bc689f995f4/src/Client/Commands/Responses/Response.php#L127-L137
Double-Opt-in/php-client-api
src/Client/Commands/Responses/Response.php
Response.resolveAttribute
private function resolveAttribute(stdClass $stdClass, $attribute) { if (isset($stdClass->$attribute)) return PHP_EOL . sprintf(' %s: %s', $attribute, implode(', ', $stdClass->$attribute)); return ''; }
php
private function resolveAttribute(stdClass $stdClass, $attribute) { if (isset($stdClass->$attribute)) return PHP_EOL . sprintf(' %s: %s', $attribute, implode(', ', $stdClass->$attribute)); return ''; }
[ "private", "function", "resolveAttribute", "(", "stdClass", "$", "stdClass", ",", "$", "attribute", ")", "{", "if", "(", "isset", "(", "$", "stdClass", "->", "$", "attribute", ")", ")", "return", "PHP_EOL", ".", "sprintf", "(", "' %s: %s'", ",", "$", "attribute", ",", "implode", "(", "', '", ",", "$", "stdClass", "->", "$", "attribute", ")", ")", ";", "return", "''", ";", "}" ]
resolves an attribute @param stdClass $stdClass @param string $attribute @return string
[ "resolves", "an", "attribute" ]
train
https://github.com/Double-Opt-in/php-client-api/blob/2f17da58ec20a408bbd55b2cdd053bc689f995f4/src/Client/Commands/Responses/Response.php#L147-L153