repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
gplcart/cli
controllers/commands/Language.php
Language.cmdGetLanguage
public function cmdGetLanguage() { $list = $this->getListLanguage(); $this->outputFormat($list); $this->outputFormatTableLanguage($list); $this->output(); }
php
public function cmdGetLanguage() { $list = $this->getListLanguage(); $this->outputFormat($list); $this->outputFormatTableLanguage($list); $this->output(); }
[ "public", "function", "cmdGetLanguage", "(", ")", "{", "$", "list", "=", "$", "this", "->", "getListLanguage", "(", ")", ";", "$", "this", "->", "outputFormat", "(", "$", "list", ")", ";", "$", "this", "->", "outputFormatTableLanguage", "(", "$", "list", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "language-get" command
[ "Callback", "for", "language", "-", "get", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Language.php#L64-L70
train
gplcart/cli
controllers/commands/Language.php
Language.cmdDeleteLanguage
public function cmdDeleteLanguage() { $id = $this->getParam(0); $all = $this->getParam('all'); if (!isset($id) && empty($all)) { $this->errorAndExit($this->text('Invalid command')); } $result = false; if (isset($id)) { $result = $this->language->delete($id); } else if (!empty($all)) { $deleted = $count = 0; foreach ($this->language->getList(array('in_database' => true)) as $language) { $count++; $deleted += (int) $this->language->delete($language['code']); } $result = $count && $count == $deleted; } if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } $this->output(); }
php
public function cmdDeleteLanguage() { $id = $this->getParam(0); $all = $this->getParam('all'); if (!isset($id) && empty($all)) { $this->errorAndExit($this->text('Invalid command')); } $result = false; if (isset($id)) { $result = $this->language->delete($id); } else if (!empty($all)) { $deleted = $count = 0; foreach ($this->language->getList(array('in_database' => true)) as $language) { $count++; $deleted += (int) $this->language->delete($language['code']); } $result = $count && $count == $deleted; } if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } $this->output(); }
[ "public", "function", "cmdDeleteLanguage", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getParam", "(", "0", ")", ";", "$", "all", "=", "$", "this", "->", "getParam", "(", "'all'", ")", ";", "if", "(", "!", "isset", "(", "$", "id", ")", "&&", "empty", "(", "$", "all", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid command'", ")", ")", ";", "}", "$", "result", "=", "false", ";", "if", "(", "isset", "(", "$", "id", ")", ")", "{", "$", "result", "=", "$", "this", "->", "language", "->", "delete", "(", "$", "id", ")", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "all", ")", ")", "{", "$", "deleted", "=", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "language", "->", "getList", "(", "array", "(", "'in_database'", "=>", "true", ")", ")", "as", "$", "language", ")", "{", "$", "count", "++", ";", "$", "deleted", "+=", "(", "int", ")", "$", "this", "->", "language", "->", "delete", "(", "$", "language", "[", "'code'", "]", ")", ";", "}", "$", "result", "=", "$", "count", "&&", "$", "count", "==", "$", "deleted", ";", "}", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "language-delete" command
[ "Callback", "for", "language", "-", "delete", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Language.php#L75-L105
train
gplcart/cli
controllers/commands/Language.php
Language.submitAddLanguage
protected function submitAddLanguage() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('language'); $this->addLanguage(); }
php
protected function submitAddLanguage() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('language'); $this->addLanguage(); }
[ "protected", "function", "submitAddLanguage", "(", ")", "{", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "this", "->", "getParam", "(", ")", ")", ";", "$", "this", "->", "validateComponent", "(", "'language'", ")", ";", "$", "this", "->", "addLanguage", "(", ")", ";", "}" ]
Add a language at once
[ "Add", "a", "language", "at", "once" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Language.php#L187-L192
train
gplcart/cli
controllers/commands/Language.php
Language.wizardAddLanguage
protected function wizardAddLanguage() { $this->validatePrompt('code', $this->text('Code'), 'language'); $this->validatePrompt('name', $this->text('Name'), 'language', ''); $this->validatePrompt('native_name', $this->text('Native name'), 'language', ''); $this->validatePrompt('status', $this->text('Status'), 'language', 0); $this->validatePrompt('default', $this->text('Default') . '?', 'language', 0); $this->validatePrompt('weight', $this->text('Weight'), 'language', 0); $this->validatePrompt('rtl', $this->text('Right-to-left') . '?', 'language', 0); $this->validateComponent('language'); $this->addLanguage(); }
php
protected function wizardAddLanguage() { $this->validatePrompt('code', $this->text('Code'), 'language'); $this->validatePrompt('name', $this->text('Name'), 'language', ''); $this->validatePrompt('native_name', $this->text('Native name'), 'language', ''); $this->validatePrompt('status', $this->text('Status'), 'language', 0); $this->validatePrompt('default', $this->text('Default') . '?', 'language', 0); $this->validatePrompt('weight', $this->text('Weight'), 'language', 0); $this->validatePrompt('rtl', $this->text('Right-to-left') . '?', 'language', 0); $this->validateComponent('language'); $this->addLanguage(); }
[ "protected", "function", "wizardAddLanguage", "(", ")", "{", "$", "this", "->", "validatePrompt", "(", "'code'", ",", "$", "this", "->", "text", "(", "'Code'", ")", ",", "'language'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'name'", ",", "$", "this", "->", "text", "(", "'Name'", ")", ",", "'language'", ",", "''", ")", ";", "$", "this", "->", "validatePrompt", "(", "'native_name'", ",", "$", "this", "->", "text", "(", "'Native name'", ")", ",", "'language'", ",", "''", ")", ";", "$", "this", "->", "validatePrompt", "(", "'status'", ",", "$", "this", "->", "text", "(", "'Status'", ")", ",", "'language'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'default'", ",", "$", "this", "->", "text", "(", "'Default'", ")", ".", "'?'", ",", "'language'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'weight'", ",", "$", "this", "->", "text", "(", "'Weight'", ")", ",", "'language'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'rtl'", ",", "$", "this", "->", "text", "(", "'Right-to-left'", ")", ".", "'?'", ",", "'language'", ",", "0", ")", ";", "$", "this", "->", "validateComponent", "(", "'language'", ")", ";", "$", "this", "->", "addLanguage", "(", ")", ";", "}" ]
Adds a language step by step
[ "Adds", "a", "language", "step", "by", "step" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Language.php#L197-L209
train
pvsaintpe/yii2-boost
db/ActiveRecord.php
ActiveRecord.oneOf
protected function oneOf($name, $conditions) { $method = 'get' . ucfirst($name); if (method_exists($this, $method)) { /** @var \yii\db\ActiveQuery $q */ $q = call_user_func([$this, $method]); $q->andOnCondition($conditions); return $q->one(); } throw new InvalidArgumentException(Yii::t('error', 'Method {method} not found.', compact('method'))); }
php
protected function oneOf($name, $conditions) { $method = 'get' . ucfirst($name); if (method_exists($this, $method)) { /** @var \yii\db\ActiveQuery $q */ $q = call_user_func([$this, $method]); $q->andOnCondition($conditions); return $q->one(); } throw new InvalidArgumentException(Yii::t('error', 'Method {method} not found.', compact('method'))); }
[ "protected", "function", "oneOf", "(", "$", "name", ",", "$", "conditions", ")", "{", "$", "method", "=", "'get'", ".", "ucfirst", "(", "$", "name", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "/** @var \\yii\\db\\ActiveQuery $q */", "$", "q", "=", "call_user_func", "(", "[", "$", "this", ",", "$", "method", "]", ")", ";", "$", "q", "->", "andOnCondition", "(", "$", "conditions", ")", ";", "return", "$", "q", "->", "one", "(", ")", ";", "}", "throw", "new", "InvalidArgumentException", "(", "Yii", "::", "t", "(", "'error'", ",", "'Method {method} not found.'", ",", "compact", "(", "'method'", ")", ")", ")", ";", "}" ]
"One of" functionality @param string $name @param array $conditions @return array|null|ActiveRecord @throws InvalidArgumentException
[ "One", "of", "functionality" ]
68765919b61d0294a80f33cf4399e5ad7510ce0d
https://github.com/pvsaintpe/yii2-boost/blob/68765919b61d0294a80f33cf4399e5ad7510ce0d/db/ActiveRecord.php#L295-L305
train
Hnto/nuki
src/Handlers/Http/Headers.php
Headers.set
public function set($key, $value) { header('' . $key . ': ' . $value . '', true); $this->vars[$key] = $value; }
php
public function set($key, $value) { header('' . $key . ': ' . $value . '', true); $this->vars[$key] = $value; }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "header", "(", "''", ".", "$", "key", ".", "': '", ".", "$", "value", ".", "''", ",", "true", ")", ";", "$", "this", "->", "vars", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Alias of add But if key exists, it will be replaced @param mixed $key @param mixed $value
[ "Alias", "of", "add", "But", "if", "key", "exists", "it", "will", "be", "replaced" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Http/Headers.php#L71-L74
train
eureka-framework/component-http
src/Http/Bag/Session.php
Session.getEphemeral
public function getEphemeral($name) { $ephemeral = $this->get(self::EPHEMERAL); if (isset($ephemeral[$name][self::VARIABLE])) { return $ephemeral[$name][self::VARIABLE]; } else { return null; } }
php
public function getEphemeral($name) { $ephemeral = $this->get(self::EPHEMERAL); if (isset($ephemeral[$name][self::VARIABLE])) { return $ephemeral[$name][self::VARIABLE]; } else { return null; } }
[ "public", "function", "getEphemeral", "(", "$", "name", ")", "{", "$", "ephemeral", "=", "$", "this", "->", "get", "(", "self", "::", "EPHEMERAL", ")", ";", "if", "(", "isset", "(", "$", "ephemeral", "[", "$", "name", "]", "[", "self", "::", "VARIABLE", "]", ")", ")", "{", "return", "$", "ephemeral", "[", "$", "name", "]", "[", "self", "::", "VARIABLE", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get Session ephemeral variable specified. @param string $name @return mixed Variable value.
[ "Get", "Session", "ephemeral", "variable", "specified", "." ]
698c3b73581a9703a9c932890c57e50f8774607a
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Bag/Session.php#L76-L84
train
eureka-framework/component-http
src/Http/Bag/Session.php
Session.hasEphemeral
public function hasEphemeral($name) { $ephemeral = $this->get(self::EPHEMERAL); return isset($ephemeral[$name]); }
php
public function hasEphemeral($name) { $ephemeral = $this->get(self::EPHEMERAL); return isset($ephemeral[$name]); }
[ "public", "function", "hasEphemeral", "(", "$", "name", ")", "{", "$", "ephemeral", "=", "$", "this", "->", "get", "(", "self", "::", "EPHEMERAL", ")", ";", "return", "isset", "(", "$", "ephemeral", "[", "$", "name", "]", ")", ";", "}" ]
Check if have specified ephemeral var in Session. @param string $name Index Session name. @return bool
[ "Check", "if", "have", "specified", "ephemeral", "var", "in", "Session", "." ]
698c3b73581a9703a9c932890c57e50f8774607a
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Bag/Session.php#L92-L97
train
eureka-framework/component-http
src/Http/Bag/Session.php
Session.clearEphemeral
public function clearEphemeral() { //~ Check ephemeral vars if ($this->has(self::EPHEMERAL)) { $ephemeral = $this->get(self::EPHEMERAL); foreach ($ephemeral as $name => &$var) { if (true === $var[self::ACTIVE]) { $var[self::ACTIVE] = false; } else { unset($ephemeral[$name]); } } } else { $ephemeral = array(); } //~ Save in Session. $this->set(self::EPHEMERAL, $ephemeral); return $this; }
php
public function clearEphemeral() { //~ Check ephemeral vars if ($this->has(self::EPHEMERAL)) { $ephemeral = $this->get(self::EPHEMERAL); foreach ($ephemeral as $name => &$var) { if (true === $var[self::ACTIVE]) { $var[self::ACTIVE] = false; } else { unset($ephemeral[$name]); } } } else { $ephemeral = array(); } //~ Save in Session. $this->set(self::EPHEMERAL, $ephemeral); return $this; }
[ "public", "function", "clearEphemeral", "(", ")", "{", "//~ Check ephemeral vars", "if", "(", "$", "this", "->", "has", "(", "self", "::", "EPHEMERAL", ")", ")", "{", "$", "ephemeral", "=", "$", "this", "->", "get", "(", "self", "::", "EPHEMERAL", ")", ";", "foreach", "(", "$", "ephemeral", "as", "$", "name", "=>", "&", "$", "var", ")", "{", "if", "(", "true", "===", "$", "var", "[", "self", "::", "ACTIVE", "]", ")", "{", "$", "var", "[", "self", "::", "ACTIVE", "]", "=", "false", ";", "}", "else", "{", "unset", "(", "$", "ephemeral", "[", "$", "name", "]", ")", ";", "}", "}", "}", "else", "{", "$", "ephemeral", "=", "array", "(", ")", ";", "}", "//~ Save in Session.", "$", "this", "->", "set", "(", "self", "::", "EPHEMERAL", ",", "$", "ephemeral", ")", ";", "return", "$", "this", ";", "}" ]
Initialize Session. Remove old ephemeral var in Session. @return self
[ "Initialize", "Session", ".", "Remove", "old", "ephemeral", "var", "in", "Session", "." ]
698c3b73581a9703a9c932890c57e50f8774607a
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Bag/Session.php#L104-L124
train
eureka-framework/component-http
src/Http/Bag/Session.php
Session.setEphemeral
public function setEphemeral($name, $value) { $ephemeral = $this->get(self::EPHEMERAL); $ephemeral[$name][self::ACTIVE] = true; $ephemeral[$name][self::VARIABLE] = $value; $this->set(self::EPHEMERAL, $ephemeral); return $this; }
php
public function setEphemeral($name, $value) { $ephemeral = $this->get(self::EPHEMERAL); $ephemeral[$name][self::ACTIVE] = true; $ephemeral[$name][self::VARIABLE] = $value; $this->set(self::EPHEMERAL, $ephemeral); return $this; }
[ "public", "function", "setEphemeral", "(", "$", "name", ",", "$", "value", ")", "{", "$", "ephemeral", "=", "$", "this", "->", "get", "(", "self", "::", "EPHEMERAL", ")", ";", "$", "ephemeral", "[", "$", "name", "]", "[", "self", "::", "ACTIVE", "]", "=", "true", ";", "$", "ephemeral", "[", "$", "name", "]", "[", "self", "::", "VARIABLE", "]", "=", "$", "value", ";", "$", "this", "->", "set", "(", "self", "::", "EPHEMERAL", ",", "$", "ephemeral", ")", ";", "return", "$", "this", ";", "}" ]
Set ephemeral variable in Session. @param string $name @param mixed $value @return self
[ "Set", "ephemeral", "variable", "in", "Session", "." ]
698c3b73581a9703a9c932890c57e50f8774607a
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Bag/Session.php#L133-L141
train
agentmedia/phine-core
src/Core/Snippets/TreeBranches/PageBranch.php
PageBranch.CanCreateAfter
protected function CanCreateAfter() { $parent = $this->tree->ParentOf($this->page); if ($parent) { return BackendModule::Guard()->Allow(BackendAction::Create(), $parent); } return BackendModule::Guard()->GrantAddPageToSite($this->page->GetSite()) ->ToBool(); }
php
protected function CanCreateAfter() { $parent = $this->tree->ParentOf($this->page); if ($parent) { return BackendModule::Guard()->Allow(BackendAction::Create(), $parent); } return BackendModule::Guard()->GrantAddPageToSite($this->page->GetSite()) ->ToBool(); }
[ "protected", "function", "CanCreateAfter", "(", ")", "{", "$", "parent", "=", "$", "this", "->", "tree", "->", "ParentOf", "(", "$", "this", "->", "page", ")", ";", "if", "(", "$", "parent", ")", "{", "return", "BackendModule", "::", "Guard", "(", ")", "->", "Allow", "(", "BackendAction", "::", "Create", "(", ")", ",", "$", "parent", ")", ";", "}", "return", "BackendModule", "::", "Guard", "(", ")", "->", "GrantAddPageToSite", "(", "$", "this", "->", "page", "->", "GetSite", "(", ")", ")", "->", "ToBool", "(", ")", ";", "}" ]
True if page can be appended @param Page $page The page before @return bool
[ "True", "if", "page", "can", "be", "appended" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/TreeBranches/PageBranch.php#L114-L123
train
agentmedia/phine-core
src/Core/Snippets/TreeBranches/PageBranch.php
PageBranch.AreaUrl
protected function AreaUrl(Area $area) { $params = array(); $params['page'] = $this->page->GetID(); $params['area'] = $area->GetID(); return BackendRouter::ModuleUrl(new PageContentTree(), $params); }
php
protected function AreaUrl(Area $area) { $params = array(); $params['page'] = $this->page->GetID(); $params['area'] = $area->GetID(); return BackendRouter::ModuleUrl(new PageContentTree(), $params); }
[ "protected", "function", "AreaUrl", "(", "Area", "$", "area", ")", "{", "$", "params", "=", "array", "(", ")", ";", "$", "params", "[", "'page'", "]", "=", "$", "this", "->", "page", "->", "GetID", "(", ")", ";", "$", "params", "[", "'area'", "]", "=", "$", "area", "->", "GetID", "(", ")", ";", "return", "BackendRouter", "::", "ModuleUrl", "(", "new", "PageContentTree", "(", ")", ",", "$", "params", ")", ";", "}" ]
Gets the content tree url @param Area $area @return string Returns the page content tree url
[ "Gets", "the", "content", "tree", "url" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/TreeBranches/PageBranch.php#L160-L166
train
ezra-obiwale/dSCore
src/Stdlib/TwBootstrap.php
TwBootstrap.parseAttributes
final public static function parseAttributes($attributes, $ignore = array()) { if (!is_array($attributes)) { return $attributes; } $return = ""; foreach ($attributes as $attr => $value) { if (in_array($attr, $ignore)) continue; $return .= $attr . '="' . $value . '" '; } return $return; }
php
final public static function parseAttributes($attributes, $ignore = array()) { if (!is_array($attributes)) { return $attributes; } $return = ""; foreach ($attributes as $attr => $value) { if (in_array($attr, $ignore)) continue; $return .= $attr . '="' . $value . '" '; } return $return; }
[ "final", "public", "static", "function", "parseAttributes", "(", "$", "attributes", ",", "$", "ignore", "=", "array", "(", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "attributes", ")", ")", "{", "return", "$", "attributes", ";", "}", "$", "return", "=", "\"\"", ";", "foreach", "(", "$", "attributes", "as", "$", "attr", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "attr", ",", "$", "ignore", ")", ")", "continue", ";", "$", "return", ".=", "$", "attr", ".", "'=\"'", ".", "$", "value", ".", "'\" '", ";", "}", "return", "$", "return", ";", "}" ]
Parses the attributes for use @param array $attributes @param array $ignore Array of attributes to ignore @return string
[ "Parses", "the", "attributes", "for", "use" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/TwBootstrap.php#L421-L433
train
ezra-obiwale/dSCore
src/Stdlib/TwBootstrap.php
TwBootstrap.carousel
public static function carousel(array $items, array $attributes = array()) { self::$carousels++; $id = (isset($attributes['id'])) ? $attributes['id'] : 'myCarousel' . self::$carousels; $class = (isset($attributes['class'])) ? $attributes['class'] . ' carousel slide' : 'carousel slide'; $attributes['id'] = $id; $attributes['class'] = $class; $controls = (isset($attributes['controls']) && !$attributes['controls']) ? false : true; unset($attributes['controls']); ob_start(); ?> <div <?= self::parseAttributes($attributes) ?> > <!-- Carousel items --> <div class="carousel-inner"> <?php foreach ($items as $t_id => $item): ?> <?php if (isset($item['img'])): ?> <div id="<?= $t_id ?>" class="item <?= (isset($item['active']) && $item['active']) ? 'active' : '' ?>"> <?= $item['img'] ?> <?php if (isset($item['caption'])): ?> <div class="carousel-caption"> <?= $item['caption'] ?> </div> <?php endif; ?> </div> <?php endif; ?> <?php endforeach; ?> </div> <?php if ($controls): ?> <!-- Carousel nav --> <a class="carousel-control left" href="#<?= $id ?>" data-slide="prev">&lsaquo;</a> <a class="carousel-control right" href="#<?= $id ?>" data-slide="next">&rsaquo;</a> <?php endif; ?> </div> <?php if (self::$addCarouselJs): self::$addCarouselJs = false; ?> <script> function positionActiveImg(container) { if (!container) container = '.carousel'; $.each($(container).children('.carousel-inner'), function (i, inner) { var img = $(inner).children('.item.active').children('img'); $(img).on('complete', function () { $(img).css({'margin-left': (($(inner).width() - $(img).width()) / 2)}); $(inner).css({'margin-top': (($(inner).parent().height() - $(inner).height()) / 2)}); }); }); } function resizeImgs(container) { if (!container) container = '.carousel'; $.each($(container), function (i, v) { if ($(v).height()) var h = ($(v).height() > $(v).width()) ? $(v).width() : $(v).height(); else var h = $(v).width(); h = (!h) ? 'auto' : h; $.each($(this).children('.carousel-inner').children().children('img'), function (i, value) { $(value).css({height: h, width: 'auto'}); }); }); setTimeout(positionActiveImg, 1000, container); } </script> <?php endif; ?> <script> $(document).ready(function () { $('#<?= $id ?>').carousel(); resizeImgs('#<?= $id ?>'); }); </script> <?php return ob_get_clean(); }
php
public static function carousel(array $items, array $attributes = array()) { self::$carousels++; $id = (isset($attributes['id'])) ? $attributes['id'] : 'myCarousel' . self::$carousels; $class = (isset($attributes['class'])) ? $attributes['class'] . ' carousel slide' : 'carousel slide'; $attributes['id'] = $id; $attributes['class'] = $class; $controls = (isset($attributes['controls']) && !$attributes['controls']) ? false : true; unset($attributes['controls']); ob_start(); ?> <div <?= self::parseAttributes($attributes) ?> > <!-- Carousel items --> <div class="carousel-inner"> <?php foreach ($items as $t_id => $item): ?> <?php if (isset($item['img'])): ?> <div id="<?= $t_id ?>" class="item <?= (isset($item['active']) && $item['active']) ? 'active' : '' ?>"> <?= $item['img'] ?> <?php if (isset($item['caption'])): ?> <div class="carousel-caption"> <?= $item['caption'] ?> </div> <?php endif; ?> </div> <?php endif; ?> <?php endforeach; ?> </div> <?php if ($controls): ?> <!-- Carousel nav --> <a class="carousel-control left" href="#<?= $id ?>" data-slide="prev">&lsaquo;</a> <a class="carousel-control right" href="#<?= $id ?>" data-slide="next">&rsaquo;</a> <?php endif; ?> </div> <?php if (self::$addCarouselJs): self::$addCarouselJs = false; ?> <script> function positionActiveImg(container) { if (!container) container = '.carousel'; $.each($(container).children('.carousel-inner'), function (i, inner) { var img = $(inner).children('.item.active').children('img'); $(img).on('complete', function () { $(img).css({'margin-left': (($(inner).width() - $(img).width()) / 2)}); $(inner).css({'margin-top': (($(inner).parent().height() - $(inner).height()) / 2)}); }); }); } function resizeImgs(container) { if (!container) container = '.carousel'; $.each($(container), function (i, v) { if ($(v).height()) var h = ($(v).height() > $(v).width()) ? $(v).width() : $(v).height(); else var h = $(v).width(); h = (!h) ? 'auto' : h; $.each($(this).children('.carousel-inner').children().children('img'), function (i, value) { $(value).css({height: h, width: 'auto'}); }); }); setTimeout(positionActiveImg, 1000, container); } </script> <?php endif; ?> <script> $(document).ready(function () { $('#<?= $id ?>').carousel(); resizeImgs('#<?= $id ?>'); }); </script> <?php return ob_get_clean(); }
[ "public", "static", "function", "carousel", "(", "array", "$", "items", ",", "array", "$", "attributes", "=", "array", "(", ")", ")", "{", "self", "::", "$", "carousels", "++", ";", "$", "id", "=", "(", "isset", "(", "$", "attributes", "[", "'id'", "]", ")", ")", "?", "$", "attributes", "[", "'id'", "]", ":", "'myCarousel'", ".", "self", "::", "$", "carousels", ";", "$", "class", "=", "(", "isset", "(", "$", "attributes", "[", "'class'", "]", ")", ")", "?", "$", "attributes", "[", "'class'", "]", ".", "' carousel slide'", ":", "'carousel slide'", ";", "$", "attributes", "[", "'id'", "]", "=", "$", "id", ";", "$", "attributes", "[", "'class'", "]", "=", "$", "class", ";", "$", "controls", "=", "(", "isset", "(", "$", "attributes", "[", "'controls'", "]", ")", "&&", "!", "$", "attributes", "[", "'controls'", "]", ")", "?", "false", ":", "true", ";", "unset", "(", "$", "attributes", "[", "'controls'", "]", ")", ";", "ob_start", "(", ")", ";", "?>\n <div <?=", "self", "::", "parseAttributes", "(", "$", "attributes", ")", "?> >\n <!-- Carousel items -->\n <div class=\"carousel-inner\">\n <?php", "foreach", "(", "$", "items", "as", "$", "t_id", "=>", "$", "item", ")", ":", "?>\n <?php", "if", "(", "isset", "(", "$", "item", "[", "'img'", "]", ")", ")", ":", "?>\n <div id=\"<?=", "$", "t_id", "?>\" class=\"item <?=", "(", "isset", "(", "$", "item", "[", "'active'", "]", ")", "&&", "$", "item", "[", "'active'", "]", ")", "?", "'active'", ":", "''", "?>\">\n <?=", "$", "item", "[", "'img'", "]", "?>\n <?php", "if", "(", "isset", "(", "$", "item", "[", "'caption'", "]", ")", ")", ":", "?>\n <div class=\"carousel-caption\">\n <?=", "$", "item", "[", "'caption'", "]", "?>\n </div>\n <?php", "endif", ";", "?>\n </div>\n <?php", "endif", ";", "?>\n <?php", "endforeach", ";", "?>\n </div>\n <?php", "if", "(", "$", "controls", ")", ":", "?>\n <!-- Carousel nav -->\n <a class=\"carousel-control left\" href=\"#<?=", "$", "id", "?>\" data-slide=\"prev\">&lsaquo;</a>\n <a class=\"carousel-control right\" href=\"#<?=", "$", "id", "?>\" data-slide=\"next\">&rsaquo;</a>\n <?php", "endif", ";", "?>\n </div>\n <?php", "if", "(", "self", "::", "$", "addCarouselJs", ")", ":", "self", "::", "$", "addCarouselJs", "=", "false", ";", "?>\n <script>\n function positionActiveImg(container) {\n if (!container)\n container = '.carousel';\n $.each($(container).children('.carousel-inner'), function (i, inner) {\n var img = $(inner).children('.item.active').children('img');\n $(img).on('complete', function () {\n $(img).css({'margin-left': (($(inner).width() - $(img).width()) / 2)});\n $(inner).css({'margin-top': (($(inner).parent().height() - $(inner).height()) / 2)});\n });\n });\n }\n\n function resizeImgs(container) {\n if (!container)\n container = '.carousel';\n $.each($(container), function (i, v) {\n if ($(v).height())\n var h = ($(v).height() > $(v).width()) ? $(v).width() : $(v).height();\n else\n var h = $(v).width();\n\n h = (!h) ? 'auto' : h;\n $.each($(this).children('.carousel-inner').children().children('img'), function (i, value) {\n $(value).css({height: h, width: 'auto'});\n });\n });\n\n setTimeout(positionActiveImg, 1000, container);\n }\n </script>\n <?php", "endif", ";", "?>\n <script>\n $(document).ready(function () {\n $('#<?=", "$", "id", "?>').carousel();\n resizeImgs('#<?=", "$", "id", "?>');\n });\n </script>\n <?php", "return", "ob_get_clean", "(", ")", ";", "}" ]
Creates a carousel @param array $items Array of items to add to the carousel<br /><br /> Example:<br /> Array (<br /> array(<br /> 'img' => '<img src="path/to/src" />',<br /> 'caption' => '',<br /> 'active' => true|false,<br /> )<br /> )<br /> @param array $attributes Array of attributes for the carousel<br /><br /> Example:<br /> Array (<br /> array(<br /> 'controls' => true|false,<br /> 'class' => '',<br /> )<br /> )<br /> @return string
[ "Creates", "a", "carousel" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/TwBootstrap.php#L458-L534
train
ezra-obiwale/dSCore
src/Stdlib/TwBootstrap.php
TwBootstrap.accordion
public static function accordion(array $groups, array $attributes = array()) { self::$accordions++; $collapse = 1; ob_start(); ?> <div data-close="<?= @$attributes['close'] ?>" class="accordion <?= @$attributes['class'] ?>" id="accordion<?= self::$accordions ?>" <?= self::parseAttributes($attributes, array('class', 'id', 'close')) ?>> <?php foreach ($groups as $key => $group) { if (empty($group['heading']) || empty($group['body'])) { throw new Exception('Each accordion group must have a heading and a body'); } ?> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion<?= self::$accordions ?>" href="#group-<?= self::$accordions . $key ?>"> <?= $group['heading'] ?> </a> </div> <div class="accordion-body collapse in" id="group-<?= self::$accordions . $key ?>"> <div class="accordion-inner"> <?= $group['body'] ?> </div> </div> </div> <?php $collapse++; } ?> </div> <script> $(document).ready(function () { $('#accordion<?= self::$accordions ?>').collapse(); }) </script> <?php return ob_get_clean(); }
php
public static function accordion(array $groups, array $attributes = array()) { self::$accordions++; $collapse = 1; ob_start(); ?> <div data-close="<?= @$attributes['close'] ?>" class="accordion <?= @$attributes['class'] ?>" id="accordion<?= self::$accordions ?>" <?= self::parseAttributes($attributes, array('class', 'id', 'close')) ?>> <?php foreach ($groups as $key => $group) { if (empty($group['heading']) || empty($group['body'])) { throw new Exception('Each accordion group must have a heading and a body'); } ?> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion<?= self::$accordions ?>" href="#group-<?= self::$accordions . $key ?>"> <?= $group['heading'] ?> </a> </div> <div class="accordion-body collapse in" id="group-<?= self::$accordions . $key ?>"> <div class="accordion-inner"> <?= $group['body'] ?> </div> </div> </div> <?php $collapse++; } ?> </div> <script> $(document).ready(function () { $('#accordion<?= self::$accordions ?>').collapse(); }) </script> <?php return ob_get_clean(); }
[ "public", "static", "function", "accordion", "(", "array", "$", "groups", ",", "array", "$", "attributes", "=", "array", "(", ")", ")", "{", "self", "::", "$", "accordions", "++", ";", "$", "collapse", "=", "1", ";", "ob_start", "(", ")", ";", "?>\n <div data-close=\"<?=", "@", "$", "attributes", "[", "'close'", "]", "?>\" class=\"accordion <?=", "@", "$", "attributes", "[", "'class'", "]", "?>\" id=\"accordion<?=", "self", "::", "$", "accordions", "?>\" <?=", "self", "::", "parseAttributes", "(", "$", "attributes", ",", "array", "(", "'class'", ",", "'id'", ",", "'close'", ")", ")", "?>>\n <?php", "foreach", "(", "$", "groups", "as", "$", "key", "=>", "$", "group", ")", "{", "if", "(", "empty", "(", "$", "group", "[", "'heading'", "]", ")", "||", "empty", "(", "$", "group", "[", "'body'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'Each accordion group must have a heading and a body'", ")", ";", "}", "?>\n <div class=\"accordion-group\">\n <div class=\"accordion-heading\">\n <a class=\"accordion-toggle\" data-toggle=\"collapse\"\n data-parent=\"#accordion<?=", "self", "::", "$", "accordions", "?>\"\n href=\"#group-<?=", "self", "::", "$", "accordions", ".", "$", "key", "?>\">\n <?=", "$", "group", "[", "'heading'", "]", "?>\n </a>\n </div>\n <div class=\"accordion-body collapse in\" id=\"group-<?=", "self", "::", "$", "accordions", ".", "$", "key", "?>\">\n <div class=\"accordion-inner\">\n <?=", "$", "group", "[", "'body'", "]", "?>\n </div>\n </div>\n </div>\n <?php", "$", "collapse", "++", ";", "}", "?>\n </div>\n <script>\n $(document).ready(function () {\n $('#accordion<?=", "self", "::", "$", "accordions", "?>').collapse();\n })\n </script>\n <?php", "return", "ob_get_clean", "(", ")", ";", "}" ]
Creates an accordion @todo Allow closing on attribute close. Currently, TWB closes it but no longer allows opening. So, this is to be implemented in the future @param array $groups Array of groups to add to the carousel Example: Array ( array( 'heading' => 'Group Heading', 'body' => 'Group content to be shown|hidden', ) ) @param array $attributes Array of attributes for the accordion. An optional attribute is 'close' which takes a boolean indicating whether the accordion should be collapsed(true) or not (false) @return string
[ "Creates", "an", "accordion" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/TwBootstrap.php#L553-L591
train
ezra-obiwale/dSCore
src/Stdlib/TwBootstrap.php
TwBootstrap.groupIntoRows
public static function groupIntoRows(array $items, $itemsPerRow, array $options = array()) { ob_start(); ?> <div class="row-fluid <?= @$options['rows']['class'] ?>" <?= self::parseAttributes(@$options['rows'], array('class')) ?>> <?php foreach ($items as $key => $item) { if ($key && $key % $itemsPerRow === 0) { ?> </div> <div class="row-fluid <?= @$options['rows']['class'] ?>"> <?php } if (@$options['wrap'] !== false): ?> <div class="span<?= round(12 / $itemsPerRow) ?> <?= @$options['spans']['class'] ?>" <?= self::parseAttributes(@$options['spans'], array('class')) ?>> <?php endif; echo $item; if (@$options['wrap'] !== false): ?> </div> <?php endif; } ?> </div> <?php return ob_get_clean(); }
php
public static function groupIntoRows(array $items, $itemsPerRow, array $options = array()) { ob_start(); ?> <div class="row-fluid <?= @$options['rows']['class'] ?>" <?= self::parseAttributes(@$options['rows'], array('class')) ?>> <?php foreach ($items as $key => $item) { if ($key && $key % $itemsPerRow === 0) { ?> </div> <div class="row-fluid <?= @$options['rows']['class'] ?>"> <?php } if (@$options['wrap'] !== false): ?> <div class="span<?= round(12 / $itemsPerRow) ?> <?= @$options['spans']['class'] ?>" <?= self::parseAttributes(@$options['spans'], array('class')) ?>> <?php endif; echo $item; if (@$options['wrap'] !== false): ?> </div> <?php endif; } ?> </div> <?php return ob_get_clean(); }
[ "public", "static", "function", "groupIntoRows", "(", "array", "$", "items", ",", "$", "itemsPerRow", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "ob_start", "(", ")", ";", "?>\n <div class=\"row-fluid <?=", "@", "$", "options", "[", "'rows'", "]", "[", "'class'", "]", "?>\"\n <?=", "self", "::", "parseAttributes", "(", "@", "$", "options", "[", "'rows'", "]", ",", "array", "(", "'class'", ")", ")", "?>>\n <?php", "foreach", "(", "$", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "if", "(", "$", "key", "&&", "$", "key", "%", "$", "itemsPerRow", "===", "0", ")", "{", "?>\n </div>\n <div class=\"row-fluid <?=", "@", "$", "options", "[", "'rows'", "]", "[", "'class'", "]", "?>\">\n <?php", "}", "if", "(", "@", "$", "options", "[", "'wrap'", "]", "!==", "false", ")", ":", "?>\n <div class=\"span<?=", "round", "(", "12", "/", "$", "itemsPerRow", ")", "?> <?=", "@", "$", "options", "[", "'spans'", "]", "[", "'class'", "]", "?>\"\n <?=", "self", "::", "parseAttributes", "(", "@", "$", "options", "[", "'spans'", "]", ",", "array", "(", "'class'", ")", ")", "?>>\n <?php", "endif", ";", "echo", "$", "item", ";", "if", "(", "@", "$", "options", "[", "'wrap'", "]", "!==", "false", ")", ":", "?>\n </div>\n <?php", "endif", ";", "}", "?>\n </div>\n <?php", "return", "ob_get_clean", "(", ")", ";", "}" ]
Groups given items into rows with class "row-fluid" @param array $items Array of items to group @param integer $itemsPerRow Number of items per row. This should be any of 1,2,3,4,6,12 @param array $options Array of additional options with the following possible keys:<br /> <b>wrap (boolean)</b>: True to wrap each item with div containers having class depicting the right span size<br /> <b>rows (array)</b>: Array of attributes for each row<br /> <b>spans (array)</b>: Array of attributes for each span. This is only only applicable if option wrap is True. @return string
[ "Groups", "given", "items", "into", "rows", "with", "class", "row", "-", "fluid" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/TwBootstrap.php#L605-L636
train
ezra-obiwale/dSCore
src/Stdlib/TwBootstrap.php
TwBootstrap.progress
public static function progress($message = 'Loading. Please wait ...', $percentage = 100, $style = 'info', $striped = true, $active = true) { ob_start(); ?> <div class="progress <?= ($striped) ? 'progress-striped' : '' ?> progress-<?= $style ?> <?= ($striped) ? 'active' : '' ?>"> <div class="bar" style="width:<?= $percentage ?>%"><?= $message ?></div> </div> <?php return ob_get_clean(); }
php
public static function progress($message = 'Loading. Please wait ...', $percentage = 100, $style = 'info', $striped = true, $active = true) { ob_start(); ?> <div class="progress <?= ($striped) ? 'progress-striped' : '' ?> progress-<?= $style ?> <?= ($striped) ? 'active' : '' ?>"> <div class="bar" style="width:<?= $percentage ?>%"><?= $message ?></div> </div> <?php return ob_get_clean(); }
[ "public", "static", "function", "progress", "(", "$", "message", "=", "'Loading. Please wait ...'", ",", "$", "percentage", "=", "100", ",", "$", "style", "=", "'info'", ",", "$", "striped", "=", "true", ",", "$", "active", "=", "true", ")", "{", "ob_start", "(", ")", ";", "?>\n <div class=\"progress <?=", "(", "$", "striped", ")", "?", "'progress-striped'", ":", "''", "?> progress-<?=", "$", "style", "?> <?=", "(", "$", "striped", ")", "?", "'active'", ":", "''", "?>\">\n <div class=\"bar\" style=\"width:<?=", "$", "percentage", "?>%\"><?=", "$", "message", "?></div>\n </div>\n <?php", "return", "ob_get_clean", "(", ")", ";", "}" ]
Creates a progress bar @param string $message Message to show in the bar @param int $percentage Percentage of the progress @param string $style Style of the progress (danger|info|success|warning|) @param boolean $striped Indicates whether bar should be striped @param boolean $active Indicates whether bar should be active @return string
[ "Creates", "a", "progress", "bar" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/TwBootstrap.php#L647-L655
train
ezra-obiwale/dSCore
src/Stdlib/TwBootstrap.php
TwBootstrap.popover
public static function popover($content, $label, $placement = 'top', $title = null, $class = null) { ob_start(); ?> <a href="#" class="<?= $class ?>" rel="popover" data-placement="<?= $placement ?>" data-content='<?= $content ?>' <?= $title ? ' data-original-title="' . $title . '"' : '' ?>><?= $label ?></a> <?php if (self::$addPopoverJs): ?> <script> $(document).ready(function () { $('a[rel="popover"]').popover({ html: true }); }); </script> <?php endif; return ob_get_clean(); }
php
public static function popover($content, $label, $placement = 'top', $title = null, $class = null) { ob_start(); ?> <a href="#" class="<?= $class ?>" rel="popover" data-placement="<?= $placement ?>" data-content='<?= $content ?>' <?= $title ? ' data-original-title="' . $title . '"' : '' ?>><?= $label ?></a> <?php if (self::$addPopoverJs): ?> <script> $(document).ready(function () { $('a[rel="popover"]').popover({ html: true }); }); </script> <?php endif; return ob_get_clean(); }
[ "public", "static", "function", "popover", "(", "$", "content", ",", "$", "label", ",", "$", "placement", "=", "'top'", ",", "$", "title", "=", "null", ",", "$", "class", "=", "null", ")", "{", "ob_start", "(", ")", ";", "?>\n <a href=\"#\" class=\"<?=", "$", "class", "?>\" rel=\"popover\" data-placement=\"<?=", "$", "placement", "?>\"\n data-content='<?=", "$", "content", "?>' <?=", "$", "title", "?", "' data-original-title=\"'", ".", "$", "title", ".", "'\"'", ":", "''", "?>><?=", "$", "label", "?></a>\n <?php", "if", "(", "self", "::", "$", "addPopoverJs", ")", ":", "?>\n <script>\n $(document).ready(function () {\n $('a[rel=\"popover\"]').popover({\n html: true\n });\n });\n </script>\n <?php", "endif", ";", "return", "ob_get_clean", "(", ")", ";", "}" ]
Create a popover and it's link @param string $content Content of the popover @param string $label The label for the link that'll call the popover @param string $placement top|bottom|left|right @param string $title @param string $class @return string
[ "Create", "a", "popover", "and", "it", "s", "link" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/TwBootstrap.php#L669-L688
train
PenoaksDev/Milky-Framework
src/Milky/Http/Routing/Route.php
Route.controllerMiddleware
protected function controllerMiddleware() { list( $class, $method ) = explode( '@', $this->action['uses'] ); $controller = UniversalBuilder::resolve( $class ); return ( new ControllerDispatcher( $this->router ) )->getMiddleware( $controller, $method ); }
php
protected function controllerMiddleware() { list( $class, $method ) = explode( '@', $this->action['uses'] ); $controller = UniversalBuilder::resolve( $class ); return ( new ControllerDispatcher( $this->router ) )->getMiddleware( $controller, $method ); }
[ "protected", "function", "controllerMiddleware", "(", ")", "{", "list", "(", "$", "class", ",", "$", "method", ")", "=", "explode", "(", "'@'", ",", "$", "this", "->", "action", "[", "'uses'", "]", ")", ";", "$", "controller", "=", "UniversalBuilder", "::", "resolve", "(", "$", "class", ")", ";", "return", "(", "new", "ControllerDispatcher", "(", "$", "this", "->", "router", ")", ")", "->", "getMiddleware", "(", "$", "controller", ",", "$", "method", ")", ";", "}" ]
Get the controller middleware for the route. @return array
[ "Get", "the", "controller", "middleware", "for", "the", "route", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Http/Routing/Route.php#L248-L255
train
jabernardo/lollipop-php
Library/Text.php
Text.lock
static function lock($string, $key = null) { return openssl_encrypt($string, self::_getSecMethod(), Utils::spare($key, self::_geteSecKey()), false, self::_getSecIv()); }
php
static function lock($string, $key = null) { return openssl_encrypt($string, self::_getSecMethod(), Utils::spare($key, self::_geteSecKey()), false, self::_getSecIv()); }
[ "static", "function", "lock", "(", "$", "string", ",", "$", "key", "=", "null", ")", "{", "return", "openssl_encrypt", "(", "$", "string", ",", "self", "::", "_getSecMethod", "(", ")", ",", "Utils", "::", "spare", "(", "$", "key", ",", "self", "::", "_geteSecKey", "(", ")", ")", ",", "false", ",", "self", "::", "_getSecIv", "(", ")", ")", ";", "}" ]
Encrypts values passed @param string $string String to be encoded. @param string $key Passphrase @return string
[ "Encrypts", "values", "passed" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/Text.php#L74-L76
train
jabernardo/lollipop-php
Library/Text.php
Text.unlock
static function unlock($cipher, $key = null) { return openssl_decrypt($cipher, self::_getSecMethod(), Utils::spare($key, self::_geteSecKey()), false, self::_getSecIv()); }
php
static function unlock($cipher, $key = null) { return openssl_decrypt($cipher, self::_getSecMethod(), Utils::spare($key, self::_geteSecKey()), false, self::_getSecIv()); }
[ "static", "function", "unlock", "(", "$", "cipher", ",", "$", "key", "=", "null", ")", "{", "return", "openssl_decrypt", "(", "$", "cipher", ",", "self", "::", "_getSecMethod", "(", ")", ",", "Utils", "::", "spare", "(", "$", "key", ",", "self", "::", "_geteSecKey", "(", ")", ")", ",", "false", ",", "self", "::", "_getSecIv", "(", ")", ")", ";", "}" ]
Decrypts values passed @param string $cipher Code to be decrypt. @param string $key Passphrase @return string
[ "Decrypts", "values", "passed" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/Text.php#L86-L88
train
jenskooij/cloudcontrol
src/cc/application/ApplicationRunner.php
ApplicationRunner.runApplicationComponents
public function runApplicationComponents($applicationComponents) { foreach ($applicationComponents as $key => $applicationComponent) { $class = $applicationComponent->component; $parameters = $applicationComponent->parameters; $applicationComponents[$key]->{'object'} = $this->getComponentObject($class, null, $parameters, null); $applicationComponents[$key]->{'object'}->run($this->storage); } }
php
public function runApplicationComponents($applicationComponents) { foreach ($applicationComponents as $key => $applicationComponent) { $class = $applicationComponent->component; $parameters = $applicationComponent->parameters; $applicationComponents[$key]->{'object'} = $this->getComponentObject($class, null, $parameters, null); $applicationComponents[$key]->{'object'}->run($this->storage); } }
[ "public", "function", "runApplicationComponents", "(", "$", "applicationComponents", ")", "{", "foreach", "(", "$", "applicationComponents", "as", "$", "key", "=>", "$", "applicationComponent", ")", "{", "$", "class", "=", "$", "applicationComponent", "->", "component", ";", "$", "parameters", "=", "$", "applicationComponent", "->", "parameters", ";", "$", "applicationComponents", "[", "$", "key", "]", "->", "{", "'object'", "}", "=", "$", "this", "->", "getComponentObject", "(", "$", "class", ",", "null", ",", "$", "parameters", ",", "null", ")", ";", "$", "applicationComponents", "[", "$", "key", "]", "->", "{", "'object'", "}", "->", "run", "(", "$", "this", "->", "storage", ")", ";", "}", "}" ]
Loop through all application components and run them @param $applicationComponents
[ "Loop", "through", "all", "application", "components", "and", "run", "them" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/cc/application/ApplicationRunner.php#L31-L39
train
rollerworks/search-core
Field/GenericResolvedFieldType.php
GenericResolvedFieldType.newField
protected function newField($name, array $options): FieldConfig { if (OrderField::isOrder($name)) { return new OrderField($name, $this, $options); } return new SearchField($name, $this, $options); }
php
protected function newField($name, array $options): FieldConfig { if (OrderField::isOrder($name)) { return new OrderField($name, $this, $options); } return new SearchField($name, $this, $options); }
[ "protected", "function", "newField", "(", "$", "name", ",", "array", "$", "options", ")", ":", "FieldConfig", "{", "if", "(", "OrderField", "::", "isOrder", "(", "$", "name", ")", ")", "{", "return", "new", "OrderField", "(", "$", "name", ",", "$", "this", ",", "$", "options", ")", ";", "}", "return", "new", "SearchField", "(", "$", "name", ",", "$", "this", ",", "$", "options", ")", ";", "}" ]
Creates a new SearchField instance. Override this method if you want to customize the field class.
[ "Creates", "a", "new", "SearchField", "instance", "." ]
6b5671b8c4d6298906ded768261b0a59845140fb
https://github.com/rollerworks/search-core/blob/6b5671b8c4d6298906ded768261b0a59845140fb/Field/GenericResolvedFieldType.php#L146-L153
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileSelectPart
protected function compileSelectPart(Query $query, array &$bindings): string { $columns = []; foreach (($query->select ?: ['*']) as $alias => $column) { if ($column instanceof Aggregate) { $column = $this->compileAggregate($column, $bindings); } else { $column = $this->compileIdentifier($column, $bindings); } $columns[] = $column.(is_string($alias) ? $this->compileAlias($alias) : ''); } return 'SELECT '.implode(', ', $columns); }
php
protected function compileSelectPart(Query $query, array &$bindings): string { $columns = []; foreach (($query->select ?: ['*']) as $alias => $column) { if ($column instanceof Aggregate) { $column = $this->compileAggregate($column, $bindings); } else { $column = $this->compileIdentifier($column, $bindings); } $columns[] = $column.(is_string($alias) ? $this->compileAlias($alias) : ''); } return 'SELECT '.implode(', ', $columns); }
[ "protected", "function", "compileSelectPart", "(", "Query", "$", "query", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "$", "columns", "=", "[", "]", ";", "foreach", "(", "(", "$", "query", "->", "select", "?", ":", "[", "'*'", "]", ")", "as", "$", "alias", "=>", "$", "column", ")", "{", "if", "(", "$", "column", "instanceof", "Aggregate", ")", "{", "$", "column", "=", "$", "this", "->", "compileAggregate", "(", "$", "column", ",", "$", "bindings", ")", ";", "}", "else", "{", "$", "column", "=", "$", "this", "->", "compileIdentifier", "(", "$", "column", ",", "$", "bindings", ")", ";", "}", "$", "columns", "[", "]", "=", "$", "column", ".", "(", "is_string", "(", "$", "alias", ")", "?", "$", "this", "->", "compileAlias", "(", "$", "alias", ")", ":", "''", ")", ";", "}", "return", "'SELECT '", ".", "implode", "(", "', '", ",", "$", "columns", ")", ";", "}" ]
Compiles a SELECT part of an SQL query. @param Query $query Query data @param array $bindings Bound values (array is filled by link) @return string SQL text
[ "Compiles", "a", "SELECT", "part", "of", "an", "SQL", "query", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L201-L216
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileFromPart
protected function compileFromPart(Query $query, array &$bindings): string { if ($query->table === null) { throw new InvalidQueryException('The FROM table is not set'); } return 'FROM '.$this->compileIdentifierWithAlias($query->table, $query->tableAlias, $bindings); }
php
protected function compileFromPart(Query $query, array &$bindings): string { if ($query->table === null) { throw new InvalidQueryException('The FROM table is not set'); } return 'FROM '.$this->compileIdentifierWithAlias($query->table, $query->tableAlias, $bindings); }
[ "protected", "function", "compileFromPart", "(", "Query", "$", "query", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "if", "(", "$", "query", "->", "table", "===", "null", ")", "{", "throw", "new", "InvalidQueryException", "(", "'The FROM table is not set'", ")", ";", "}", "return", "'FROM '", ".", "$", "this", "->", "compileIdentifierWithAlias", "(", "$", "query", "->", "table", ",", "$", "query", "->", "tableAlias", ",", "$", "bindings", ")", ";", "}" ]
Compiles a FROM part of an SQL query. @param Query $query Query data @param array $bindings Bound values (array is filled by link) @return string SQL text @throws InvalidQueryException
[ "Compiles", "a", "FROM", "part", "of", "an", "SQL", "query", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L226-L233
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileJoinPart
protected function compileJoinPart(Query $query, array &$bindings): string { $joinsSQL = []; foreach ($query->join as $join) { $joinsSQL[] = $this->compileOneJoin($join, $bindings); } return $this->implodeSQL($joinsSQL); }
php
protected function compileJoinPart(Query $query, array &$bindings): string { $joinsSQL = []; foreach ($query->join as $join) { $joinsSQL[] = $this->compileOneJoin($join, $bindings); } return $this->implodeSQL($joinsSQL); }
[ "protected", "function", "compileJoinPart", "(", "Query", "$", "query", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "$", "joinsSQL", "=", "[", "]", ";", "foreach", "(", "$", "query", "->", "join", "as", "$", "join", ")", "{", "$", "joinsSQL", "[", "]", "=", "$", "this", "->", "compileOneJoin", "(", "$", "join", ",", "$", "bindings", ")", ";", "}", "return", "$", "this", "->", "implodeSQL", "(", "$", "joinsSQL", ")", ";", "}" ]
Compiles a JOIN parts of an SQL query. @param Query $query Query data @param array $bindings Bound values (array is filled by link) @return string SQL text @throws InvalidQueryException
[ "Compiles", "a", "JOIN", "parts", "of", "an", "SQL", "query", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L243-L252
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileWherePart
protected function compileWherePart(Query $query, array &$bindings): string { $sql = $this->compileCriteria($query->where, $bindings); if ($sql !== '') { $sql = 'WHERE '.$sql; } return $sql; }
php
protected function compileWherePart(Query $query, array &$bindings): string { $sql = $this->compileCriteria($query->where, $bindings); if ($sql !== '') { $sql = 'WHERE '.$sql; } return $sql; }
[ "protected", "function", "compileWherePart", "(", "Query", "$", "query", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "$", "sql", "=", "$", "this", "->", "compileCriteria", "(", "$", "query", "->", "where", ",", "$", "bindings", ")", ";", "if", "(", "$", "sql", "!==", "''", ")", "{", "$", "sql", "=", "'WHERE '", ".", "$", "sql", ";", "}", "return", "$", "sql", ";", "}" ]
Compiles a WHERE part of an SQL query. @param Query $query Query data @param array $bindings Bound values (array is filled by link) @return string SQL text @throws InvalidQueryException
[ "Compiles", "a", "WHERE", "part", "of", "an", "SQL", "query", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L289-L297
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileOrderPart
protected function compileOrderPart(Query $query, array &$bindings): string { $ordersSQL = []; foreach ($query->order as $order) { $orderSQL = $this->compileOneOrder($order, $bindings); if ($orderSQL !== '') { $ordersSQL[] = $orderSQL; } } return $ordersSQL ? 'ORDER BY '.implode(', ', $ordersSQL) : ''; }
php
protected function compileOrderPart(Query $query, array &$bindings): string { $ordersSQL = []; foreach ($query->order as $order) { $orderSQL = $this->compileOneOrder($order, $bindings); if ($orderSQL !== '') { $ordersSQL[] = $orderSQL; } } return $ordersSQL ? 'ORDER BY '.implode(', ', $ordersSQL) : ''; }
[ "protected", "function", "compileOrderPart", "(", "Query", "$", "query", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "$", "ordersSQL", "=", "[", "]", ";", "foreach", "(", "$", "query", "->", "order", "as", "$", "order", ")", "{", "$", "orderSQL", "=", "$", "this", "->", "compileOneOrder", "(", "$", "order", ",", "$", "bindings", ")", ";", "if", "(", "$", "orderSQL", "!==", "''", ")", "{", "$", "ordersSQL", "[", "]", "=", "$", "orderSQL", ";", "}", "}", "return", "$", "ordersSQL", "?", "'ORDER BY '", ".", "implode", "(", "', '", ",", "$", "ordersSQL", ")", ":", "''", ";", "}" ]
Compiles a ORDER part of an SQL query. @param Query $query Query data @param array $bindings Bound values (array is filled by link) @return string SQL text @throws InvalidQueryException
[ "Compiles", "a", "ORDER", "part", "of", "an", "SQL", "query", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L307-L320
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileUpdateValues
protected function compileUpdateValues(array $values, array &$bindings): string { $parts = []; foreach ($values as $column => $value) { $parts[] = $this->quoteCompositeIdentifier($column).' = '.$this->compileValue($value, $bindings); } return implode(', ', $parts); }
php
protected function compileUpdateValues(array $values, array &$bindings): string { $parts = []; foreach ($values as $column => $value) { $parts[] = $this->quoteCompositeIdentifier($column).' = '.$this->compileValue($value, $bindings); } return implode(', ', $parts); }
[ "protected", "function", "compileUpdateValues", "(", "array", "$", "values", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "$", "parts", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "column", "=>", "$", "value", ")", "{", "$", "parts", "[", "]", "=", "$", "this", "->", "quoteCompositeIdentifier", "(", "$", "column", ")", ".", "' = '", ".", "$", "this", "->", "compileValue", "(", "$", "value", ",", "$", "bindings", ")", ";", "}", "return", "implode", "(", "', '", ",", "$", "parts", ")", ";", "}" ]
Compiles a values list for the SET part of a update SQL query. @param Query mixed[]|Query[]|StatementInterface[] Values. The indexes are the columns names, the values are the values. @param array $bindings Bound values (array is filled by link) @return string SQL text @throws InvalidQueryException
[ "Compiles", "a", "values", "list", "for", "the", "SET", "part", "of", "a", "update", "SQL", "query", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L331-L340
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileValue
protected function compileValue($value, array &$bindings): string { if ($value instanceof Query || $value instanceof StatementInterface) { return $this->compileSubQuery($value, $bindings); } $this->mergeBindings($bindings, [$value]); return '?'; }
php
protected function compileValue($value, array &$bindings): string { if ($value instanceof Query || $value instanceof StatementInterface) { return $this->compileSubQuery($value, $bindings); } $this->mergeBindings($bindings, [$value]); return '?'; }
[ "protected", "function", "compileValue", "(", "$", "value", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "if", "(", "$", "value", "instanceof", "Query", "||", "$", "value", "instanceof", "StatementInterface", ")", "{", "return", "$", "this", "->", "compileSubQuery", "(", "$", "value", ",", "$", "bindings", ")", ";", "}", "$", "this", "->", "mergeBindings", "(", "$", "bindings", ",", "[", "$", "value", "]", ")", ";", "return", "'?'", ";", "}" ]
Converts a value to a part of an SQL query text. Actually it sends all the values to the bindings. @param mixed|Query|StatementInterface $value Value (a scalar value or a subquery) @param array $bindings Bound values (array is filled by link) @return string SQL text
[ "Converts", "a", "value", "to", "a", "part", "of", "an", "SQL", "query", "text", ".", "Actually", "it", "sends", "all", "the", "values", "to", "the", "bindings", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L365-L373
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileSubQuery
protected function compileSubQuery($subQuery, array &$bindings, bool $parenthesise = true): string { if ($subQuery instanceof Query) { try { $subQuery = $this->compile($subQuery); } catch (InvalidQueryException $exception) { throw new InvalidQueryException( 'Error in subquery: '.$exception->getMessage(), $exception->getCode(), $exception ); } } $this->mergeBindings($bindings, $subQuery->getBindings()); $sql = $subQuery->getSQL(); return $parenthesise ? '('.$sql.')' : $sql; }
php
protected function compileSubQuery($subQuery, array &$bindings, bool $parenthesise = true): string { if ($subQuery instanceof Query) { try { $subQuery = $this->compile($subQuery); } catch (InvalidQueryException $exception) { throw new InvalidQueryException( 'Error in subquery: '.$exception->getMessage(), $exception->getCode(), $exception ); } } $this->mergeBindings($bindings, $subQuery->getBindings()); $sql = $subQuery->getSQL(); return $parenthesise ? '('.$sql.')' : $sql; }
[ "protected", "function", "compileSubQuery", "(", "$", "subQuery", ",", "array", "&", "$", "bindings", ",", "bool", "$", "parenthesise", "=", "true", ")", ":", "string", "{", "if", "(", "$", "subQuery", "instanceof", "Query", ")", "{", "try", "{", "$", "subQuery", "=", "$", "this", "->", "compile", "(", "$", "subQuery", ")", ";", "}", "catch", "(", "InvalidQueryException", "$", "exception", ")", "{", "throw", "new", "InvalidQueryException", "(", "'Error in subquery: '", ".", "$", "exception", "->", "getMessage", "(", ")", ",", "$", "exception", "->", "getCode", "(", ")", ",", "$", "exception", ")", ";", "}", "}", "$", "this", "->", "mergeBindings", "(", "$", "bindings", ",", "$", "subQuery", "->", "getBindings", "(", ")", ")", ";", "$", "sql", "=", "$", "subQuery", "->", "getSQL", "(", ")", ";", "return", "$", "parenthesise", "?", "'('", ".", "$", "sql", ".", "')'", ":", "$", "sql", ";", "}" ]
Converts a subquery to an SQL query text. @param Query|StatementInterface $subQuery Subquery @param array $bindings Bound values (array is filled by link) @param bool $parenthesise Wrap the subquery in parentheses? @return string SQL text wrapped in parentheses
[ "Converts", "a", "subquery", "to", "an", "SQL", "query", "text", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L383-L401
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileAggregate
protected function compileAggregate(Aggregate $aggregate, array &$bindings): string { return $aggregate->function.'('.$this->compileIdentifier($aggregate->column, $bindings).')'; }
php
protected function compileAggregate(Aggregate $aggregate, array &$bindings): string { return $aggregate->function.'('.$this->compileIdentifier($aggregate->column, $bindings).')'; }
[ "protected", "function", "compileAggregate", "(", "Aggregate", "$", "aggregate", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "return", "$", "aggregate", "->", "function", ".", "'('", ".", "$", "this", "->", "compileIdentifier", "(", "$", "aggregate", "->", "column", ",", "$", "bindings", ")", ".", "')'", ";", "}" ]
Converts an Aggregate object to an SQL query text. @param Aggregate $aggregate Aggregate @param array $bindings Bound values (array is filled by link) @return string SQL text
[ "Converts", "an", "Aggregate", "object", "to", "an", "SQL", "query", "text", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L410-L413
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileOneJoin
protected function compileOneJoin(Join $join, array &$bindings): string { $sql = $join->type.' JOIN '.$this->compileIdentifierWithAlias($join->table, $join->tableAlias, $bindings); if ($join->criteria) { $sql .= ' ON '.$this->compileCriteria($join->criteria, $bindings); } return $sql; }
php
protected function compileOneJoin(Join $join, array &$bindings): string { $sql = $join->type.' JOIN '.$this->compileIdentifierWithAlias($join->table, $join->tableAlias, $bindings); if ($join->criteria) { $sql .= ' ON '.$this->compileCriteria($join->criteria, $bindings); } return $sql; }
[ "protected", "function", "compileOneJoin", "(", "Join", "$", "join", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "$", "sql", "=", "$", "join", "->", "type", ".", "' JOIN '", ".", "$", "this", "->", "compileIdentifierWithAlias", "(", "$", "join", "->", "table", ",", "$", "join", "->", "tableAlias", ",", "$", "bindings", ")", ";", "if", "(", "$", "join", "->", "criteria", ")", "{", "$", "sql", ".=", "' ON '", ".", "$", "this", "->", "compileCriteria", "(", "$", "join", "->", "criteria", ",", "$", "bindings", ")", ";", "}", "return", "$", "sql", ";", "}" ]
Converts a Join object ot an SQL query text. @param Join $join Join @param array $bindings Bound values (array is filled by link) @return string SQL text
[ "Converts", "a", "Join", "object", "ot", "an", "SQL", "query", "text", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L422-L431
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileOneOrder
protected function compileOneOrder($order, array &$bindings): string { if ($order instanceof Order) { return $this->compileIdentifier($order->column, $bindings).' '.($order->isDescending ? 'DESC' : 'ASC'); } if ($order instanceof OrderByIsNull) { return $this->compileIdentifier($order->column, $bindings).' IS'.($order->areNullFirst ? ' NOT' : '').' NULL'; } if ($order instanceof ExplicitOrder) { if (!$order->order) { return ''; } $sql = 'CASE '.$this->compileIdentifier($order->column, $bindings); foreach (array_values($order->order) as $index => $value) { $sql .= ' WHEN '.$this->compileValue($value, $bindings).' THEN ?'; $this->mergeBindings($bindings, [$index]); } $sql .= ' ELSE ?'; $this->mergeBindings($bindings, [$order->areOtherFirst ? -1 : count($order->order)]); return $sql; } if ($order === 'random') { return 'RANDOM()'; } throw new InvalidQueryException(sprintf( 'The given order `%s` is unknown', is_string($order) ? $order : gettype($order) )); }
php
protected function compileOneOrder($order, array &$bindings): string { if ($order instanceof Order) { return $this->compileIdentifier($order->column, $bindings).' '.($order->isDescending ? 'DESC' : 'ASC'); } if ($order instanceof OrderByIsNull) { return $this->compileIdentifier($order->column, $bindings).' IS'.($order->areNullFirst ? ' NOT' : '').' NULL'; } if ($order instanceof ExplicitOrder) { if (!$order->order) { return ''; } $sql = 'CASE '.$this->compileIdentifier($order->column, $bindings); foreach (array_values($order->order) as $index => $value) { $sql .= ' WHEN '.$this->compileValue($value, $bindings).' THEN ?'; $this->mergeBindings($bindings, [$index]); } $sql .= ' ELSE ?'; $this->mergeBindings($bindings, [$order->areOtherFirst ? -1 : count($order->order)]); return $sql; } if ($order === 'random') { return 'RANDOM()'; } throw new InvalidQueryException(sprintf( 'The given order `%s` is unknown', is_string($order) ? $order : gettype($order) )); }
[ "protected", "function", "compileOneOrder", "(", "$", "order", ",", "array", "&", "$", "bindings", ")", ":", "string", "{", "if", "(", "$", "order", "instanceof", "Order", ")", "{", "return", "$", "this", "->", "compileIdentifier", "(", "$", "order", "->", "column", ",", "$", "bindings", ")", ".", "' '", ".", "(", "$", "order", "->", "isDescending", "?", "'DESC'", ":", "'ASC'", ")", ";", "}", "if", "(", "$", "order", "instanceof", "OrderByIsNull", ")", "{", "return", "$", "this", "->", "compileIdentifier", "(", "$", "order", "->", "column", ",", "$", "bindings", ")", ".", "' IS'", ".", "(", "$", "order", "->", "areNullFirst", "?", "' NOT'", ":", "''", ")", ".", "' NULL'", ";", "}", "if", "(", "$", "order", "instanceof", "ExplicitOrder", ")", "{", "if", "(", "!", "$", "order", "->", "order", ")", "{", "return", "''", ";", "}", "$", "sql", "=", "'CASE '", ".", "$", "this", "->", "compileIdentifier", "(", "$", "order", "->", "column", ",", "$", "bindings", ")", ";", "foreach", "(", "array_values", "(", "$", "order", "->", "order", ")", "as", "$", "index", "=>", "$", "value", ")", "{", "$", "sql", ".=", "' WHEN '", ".", "$", "this", "->", "compileValue", "(", "$", "value", ",", "$", "bindings", ")", ".", "' THEN ?'", ";", "$", "this", "->", "mergeBindings", "(", "$", "bindings", ",", "[", "$", "index", "]", ")", ";", "}", "$", "sql", ".=", "' ELSE ?'", ";", "$", "this", "->", "mergeBindings", "(", "$", "bindings", ",", "[", "$", "order", "->", "areOtherFirst", "?", "-", "1", ":", "count", "(", "$", "order", "->", "order", ")", "]", ")", ";", "return", "$", "sql", ";", "}", "if", "(", "$", "order", "===", "'random'", ")", "{", "return", "'RANDOM()'", ";", "}", "throw", "new", "InvalidQueryException", "(", "sprintf", "(", "'The given order `%s` is unknown'", ",", "is_string", "(", "$", "order", ")", "?", "$", "order", ":", "gettype", "(", "$", "order", ")", ")", ")", ";", "}" ]
Converts a single order to an SQL query text. @param Order|OrderByIsNull|ExplicitOrder|string $order Order. String `random` means that the order should be random. @param array $bindings Bound values (array is filled by link) @return string SQL text or an empty string @throws InvalidQueryException
[ "Converts", "a", "single", "order", "to", "an", "SQL", "query", "text", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L600-L633
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileInsertFromValues
protected function compileInsertFromValues($table, string $tableAlias = null, array $values): array { if (empty($values)) { return []; } $bindings = []; // Step 1. Fetch unique columns list. $columns = []; foreach ($values as $row) { foreach ($row as $column => $value) { if (!isset($columns[$column])) { $columns[$column] = count($columns); } } } // Step 2. Build the values matrix. $compiledRows = []; foreach ($values as $row) { $compiledRow = []; foreach ($columns as $column => $columnIndex) { if (array_key_exists($column, $row)) { $compiledRow[$columnIndex] = $this->compileValue($row[$column], $bindings); } else { $compiledRow[$columnIndex] = 'DEFAULT'; } } $compiledRows[] = '('.implode(', ', $compiledRow).')'; } // Step 3. Build the SQL $sqlLine1 = 'INSERT INTO '.$this->compileIdentifierWithAlias($table, $tableAlias, $bindings) . ' ('.implode(', ', array_map([$this, 'quoteCompositeIdentifier'], array_keys($columns))).')'; $sqlLine2 = 'VALUES '.implode(', ', $compiledRows); return [new Raw($this->implodeSQL([$sqlLine1, $sqlLine2]), $bindings)]; }
php
protected function compileInsertFromValues($table, string $tableAlias = null, array $values): array { if (empty($values)) { return []; } $bindings = []; // Step 1. Fetch unique columns list. $columns = []; foreach ($values as $row) { foreach ($row as $column => $value) { if (!isset($columns[$column])) { $columns[$column] = count($columns); } } } // Step 2. Build the values matrix. $compiledRows = []; foreach ($values as $row) { $compiledRow = []; foreach ($columns as $column => $columnIndex) { if (array_key_exists($column, $row)) { $compiledRow[$columnIndex] = $this->compileValue($row[$column], $bindings); } else { $compiledRow[$columnIndex] = 'DEFAULT'; } } $compiledRows[] = '('.implode(', ', $compiledRow).')'; } // Step 3. Build the SQL $sqlLine1 = 'INSERT INTO '.$this->compileIdentifierWithAlias($table, $tableAlias, $bindings) . ' ('.implode(', ', array_map([$this, 'quoteCompositeIdentifier'], array_keys($columns))).')'; $sqlLine2 = 'VALUES '.implode(', ', $compiledRows); return [new Raw($this->implodeSQL([$sqlLine1, $sqlLine2]), $bindings)]; }
[ "protected", "function", "compileInsertFromValues", "(", "$", "table", ",", "string", "$", "tableAlias", "=", "null", ",", "array", "$", "values", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "values", ")", ")", "{", "return", "[", "]", ";", "}", "$", "bindings", "=", "[", "]", ";", "// Step 1. Fetch unique columns list.", "$", "columns", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "row", ")", "{", "foreach", "(", "$", "row", "as", "$", "column", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "columns", "[", "$", "column", "]", ")", ")", "{", "$", "columns", "[", "$", "column", "]", "=", "count", "(", "$", "columns", ")", ";", "}", "}", "}", "// Step 2. Build the values matrix.", "$", "compiledRows", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "row", ")", "{", "$", "compiledRow", "=", "[", "]", ";", "foreach", "(", "$", "columns", "as", "$", "column", "=>", "$", "columnIndex", ")", "{", "if", "(", "array_key_exists", "(", "$", "column", ",", "$", "row", ")", ")", "{", "$", "compiledRow", "[", "$", "columnIndex", "]", "=", "$", "this", "->", "compileValue", "(", "$", "row", "[", "$", "column", "]", ",", "$", "bindings", ")", ";", "}", "else", "{", "$", "compiledRow", "[", "$", "columnIndex", "]", "=", "'DEFAULT'", ";", "}", "}", "$", "compiledRows", "[", "]", "=", "'('", ".", "implode", "(", "', '", ",", "$", "compiledRow", ")", ".", "')'", ";", "}", "// Step 3. Build the SQL", "$", "sqlLine1", "=", "'INSERT INTO '", ".", "$", "this", "->", "compileIdentifierWithAlias", "(", "$", "table", ",", "$", "tableAlias", ",", "$", "bindings", ")", ".", "' ('", ".", "implode", "(", "', '", ",", "array_map", "(", "[", "$", "this", ",", "'quoteCompositeIdentifier'", "]", ",", "array_keys", "(", "$", "columns", ")", ")", ")", ".", "')'", ";", "$", "sqlLine2", "=", "'VALUES '", ".", "implode", "(", "', '", ",", "$", "compiledRows", ")", ";", "return", "[", "new", "Raw", "(", "$", "this", "->", "implodeSQL", "(", "[", "$", "sqlLine1", ",", "$", "sqlLine2", "]", ")", ",", "$", "bindings", ")", "]", ";", "}" ]
Compiles set of full INSERT queries from an array of values. @param string|Query|StatementInterface $table Target table name @param string|null $tableAlias Table alias @param mixed[][]|Query[][]|StatementInterface[][] $values Array of rows of values @return StatementInterface[] @throws InvalidQueryException
[ "Compiles", "set", "of", "full", "INSERT", "queries", "from", "an", "array", "of", "values", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L670-L708
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.compileInsertFromSelect
protected function compileInsertFromSelect( $table, string $tableAlias = null, array $columns = null, $selectQuery ): StatementInterface { $bindings = []; $sqlLine1 = 'INSERT INTO '.$this->compileIdentifierWithAlias($table, $tableAlias, $bindings); if ($columns !== null) { $sqlLine1 .= ' ('.implode(', ', array_map([$this, 'quoteCompositeIdentifier'], $columns)).')'; } $sqlLine2 = $this->compileSubQuery($selectQuery, $bindings, false); return new Raw($this->implodeSQL([$sqlLine1, $sqlLine2]), $bindings); }
php
protected function compileInsertFromSelect( $table, string $tableAlias = null, array $columns = null, $selectQuery ): StatementInterface { $bindings = []; $sqlLine1 = 'INSERT INTO '.$this->compileIdentifierWithAlias($table, $tableAlias, $bindings); if ($columns !== null) { $sqlLine1 .= ' ('.implode(', ', array_map([$this, 'quoteCompositeIdentifier'], $columns)).')'; } $sqlLine2 = $this->compileSubQuery($selectQuery, $bindings, false); return new Raw($this->implodeSQL([$sqlLine1, $sqlLine2]), $bindings); }
[ "protected", "function", "compileInsertFromSelect", "(", "$", "table", ",", "string", "$", "tableAlias", "=", "null", ",", "array", "$", "columns", "=", "null", ",", "$", "selectQuery", ")", ":", "StatementInterface", "{", "$", "bindings", "=", "[", "]", ";", "$", "sqlLine1", "=", "'INSERT INTO '", ".", "$", "this", "->", "compileIdentifierWithAlias", "(", "$", "table", ",", "$", "tableAlias", ",", "$", "bindings", ")", ";", "if", "(", "$", "columns", "!==", "null", ")", "{", "$", "sqlLine1", ".=", "' ('", ".", "implode", "(", "', '", ",", "array_map", "(", "[", "$", "this", ",", "'quoteCompositeIdentifier'", "]", ",", "$", "columns", ")", ")", ".", "')'", ";", "}", "$", "sqlLine2", "=", "$", "this", "->", "compileSubQuery", "(", "$", "selectQuery", ",", "$", "bindings", ",", "false", ")", ";", "return", "new", "Raw", "(", "$", "this", "->", "implodeSQL", "(", "[", "$", "sqlLine1", ",", "$", "sqlLine2", "]", ")", ",", "$", "bindings", ")", ";", "}" ]
Compiles a full INSERT query from a select query. @param string|Query|StatementInterface $table Target table name @param string|null $tableAlias Table alias @param string[]|null $columns Columns of a target table. If null, the list of columns is omitted. @param Query|StatementInterface $selectQuery The select query @return StatementInterface @throws InvalidQueryException
[ "Compiles", "a", "full", "INSERT", "query", "from", "a", "select", "query", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L720-L736
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.mergeBindings
protected function mergeBindings(array &$target, array $source) { $targetBindingsAmount = count($target); $sourceBindingsIndex = 0; foreach ($source as $name => $value) { $key = is_int($name) ? $targetBindingsAmount + $sourceBindingsIndex : $name; $target[$key] = $value; $sourceBindingsIndex += 1; } }
php
protected function mergeBindings(array &$target, array $source) { $targetBindingsAmount = count($target); $sourceBindingsIndex = 0; foreach ($source as $name => $value) { $key = is_int($name) ? $targetBindingsAmount + $sourceBindingsIndex : $name; $target[$key] = $value; $sourceBindingsIndex += 1; } }
[ "protected", "function", "mergeBindings", "(", "array", "&", "$", "target", ",", "array", "$", "source", ")", "{", "$", "targetBindingsAmount", "=", "count", "(", "$", "target", ")", ";", "$", "sourceBindingsIndex", "=", "0", ";", "foreach", "(", "$", "source", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "key", "=", "is_int", "(", "$", "name", ")", "?", "$", "targetBindingsAmount", "+", "$", "sourceBindingsIndex", ":", "$", "name", ";", "$", "target", "[", "$", "key", "]", "=", "$", "value", ";", "$", "sourceBindingsIndex", "+=", "1", ";", "}", "}" ]
Merges two arrays of bound values. @param array $target Where to add values. The values are added by link. @param array $source Values to add
[ "Merges", "two", "arrays", "of", "bound", "values", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L744-L754
train
Finesse/QueryScribe
src/Grammars/CommonGrammar.php
CommonGrammar.implodeSQL
protected function implodeSQL(array $parts): string { $result = ''; foreach ($parts as $part) { if ($part === '') { continue; } $result .= ($result === '' ? '' : "\n").$part; } return $result; }
php
protected function implodeSQL(array $parts): string { $result = ''; foreach ($parts as $part) { if ($part === '') { continue; } $result .= ($result === '' ? '' : "\n").$part; } return $result; }
[ "protected", "function", "implodeSQL", "(", "array", "$", "parts", ")", ":", "string", "{", "$", "result", "=", "''", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "if", "(", "$", "part", "===", "''", ")", "{", "continue", ";", "}", "$", "result", ".=", "(", "$", "result", "===", "''", "?", "''", ":", "\"\\n\"", ")", ".", "$", "part", ";", "}", "return", "$", "result", ";", "}" ]
Implodes parts of SQL query to a single string. @param string[] $parts @return string
[ "Implodes", "parts", "of", "SQL", "query", "to", "a", "single", "string", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/Grammars/CommonGrammar.php#L762-L774
train
ScaraMVC/Framework
src/Scara/Routing/Router.php
Router.registerRoutes
public function registerRoutes() { $this->_route = new Route(); $this->_config = Config::from('app'); $router = $this; // MUST KEEP!!!!!!!!! require_once $this->_config->from('app')->get('routes'); }
php
public function registerRoutes() { $this->_route = new Route(); $this->_config = Config::from('app'); $router = $this; // MUST KEEP!!!!!!!!! require_once $this->_config->from('app')->get('routes'); }
[ "public", "function", "registerRoutes", "(", ")", "{", "$", "this", "->", "_route", "=", "new", "Route", "(", ")", ";", "$", "this", "->", "_config", "=", "Config", "::", "from", "(", "'app'", ")", ";", "$", "router", "=", "$", "this", ";", "// MUST KEEP!!!!!!!!!", "require_once", "$", "this", "->", "_config", "->", "from", "(", "'app'", ")", "->", "get", "(", "'routes'", ")", ";", "}" ]
Handles registering defined routes. @return void
[ "Handles", "registering", "defined", "routes", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Routing/Router.php#L33-L41
train
ScaraMVC/Framework
src/Scara/Routing/Router.php
Router.getRoute
public function getRoute($url) { $routes = $this->_route->getRoutes(); $return = ''; foreach ($routes as $route) { $routeURI = $this->_config->from('app')->get('basepath').$route['uri']; // POST requests if (isset($_POST)) { foreach ($_POST as $key => $value) { $route['query'][] = [$key => $value]; } } // GET requests $getexp = explode('?', $_SERVER['REQUEST_URI']); if (isset($getexp[1])) { if (implode('?', $getexp) == $routeURI.'?'.$getexp[1]) { $route['querystring'] = $getexp[1]; $qexp = explode('&', $route['querystring']); foreach ($qexp as $q) { $i = explode('=', $q); $route['query'][] = [$i[0] => $i[1]]; } } } // For handling routes with variables $expressionExp = explode('/', $route['uri']); $serveruri = '/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], $expressionExp[1])); $serveruriexp = explode('/', $serveruri); for ($i = 0; $i < count($expressionExp); $i++) { $expressionExp[$i] = preg_replace_callback('/\{(.+)\}/', function ($m) use ($serveruriexp, $i, &$route) { $route['query'][] = [$m[1] => $serveruriexp[$i]]; return strtolower($serveruriexp[$i]); // url hack to accept upper cases too }, $expressionExp[$i]); } $expression = implode('/', $expressionExp); $route['uri'] = $expression; if (isset($route['querystring'])) { $checkurl = $route['uri'].'?'.$route['querystring']; } else { $checkurl = $route['uri']; } if ((strtolower($checkurl) == $url) && ($_SERVER['REQUEST_METHOD'] == $route['method'])) { return $route; } } }
php
public function getRoute($url) { $routes = $this->_route->getRoutes(); $return = ''; foreach ($routes as $route) { $routeURI = $this->_config->from('app')->get('basepath').$route['uri']; // POST requests if (isset($_POST)) { foreach ($_POST as $key => $value) { $route['query'][] = [$key => $value]; } } // GET requests $getexp = explode('?', $_SERVER['REQUEST_URI']); if (isset($getexp[1])) { if (implode('?', $getexp) == $routeURI.'?'.$getexp[1]) { $route['querystring'] = $getexp[1]; $qexp = explode('&', $route['querystring']); foreach ($qexp as $q) { $i = explode('=', $q); $route['query'][] = [$i[0] => $i[1]]; } } } // For handling routes with variables $expressionExp = explode('/', $route['uri']); $serveruri = '/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], $expressionExp[1])); $serveruriexp = explode('/', $serveruri); for ($i = 0; $i < count($expressionExp); $i++) { $expressionExp[$i] = preg_replace_callback('/\{(.+)\}/', function ($m) use ($serveruriexp, $i, &$route) { $route['query'][] = [$m[1] => $serveruriexp[$i]]; return strtolower($serveruriexp[$i]); // url hack to accept upper cases too }, $expressionExp[$i]); } $expression = implode('/', $expressionExp); $route['uri'] = $expression; if (isset($route['querystring'])) { $checkurl = $route['uri'].'?'.$route['querystring']; } else { $checkurl = $route['uri']; } if ((strtolower($checkurl) == $url) && ($_SERVER['REQUEST_METHOD'] == $route['method'])) { return $route; } } }
[ "public", "function", "getRoute", "(", "$", "url", ")", "{", "$", "routes", "=", "$", "this", "->", "_route", "->", "getRoutes", "(", ")", ";", "$", "return", "=", "''", ";", "foreach", "(", "$", "routes", "as", "$", "route", ")", "{", "$", "routeURI", "=", "$", "this", "->", "_config", "->", "from", "(", "'app'", ")", "->", "get", "(", "'basepath'", ")", ".", "$", "route", "[", "'uri'", "]", ";", "// POST requests", "if", "(", "isset", "(", "$", "_POST", ")", ")", "{", "foreach", "(", "$", "_POST", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "route", "[", "'query'", "]", "[", "]", "=", "[", "$", "key", "=>", "$", "value", "]", ";", "}", "}", "// GET requests", "$", "getexp", "=", "explode", "(", "'?'", ",", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ";", "if", "(", "isset", "(", "$", "getexp", "[", "1", "]", ")", ")", "{", "if", "(", "implode", "(", "'?'", ",", "$", "getexp", ")", "==", "$", "routeURI", ".", "'?'", ".", "$", "getexp", "[", "1", "]", ")", "{", "$", "route", "[", "'querystring'", "]", "=", "$", "getexp", "[", "1", "]", ";", "$", "qexp", "=", "explode", "(", "'&'", ",", "$", "route", "[", "'querystring'", "]", ")", ";", "foreach", "(", "$", "qexp", "as", "$", "q", ")", "{", "$", "i", "=", "explode", "(", "'='", ",", "$", "q", ")", ";", "$", "route", "[", "'query'", "]", "[", "]", "=", "[", "$", "i", "[", "0", "]", "=>", "$", "i", "[", "1", "]", "]", ";", "}", "}", "}", "// For handling routes with variables", "$", "expressionExp", "=", "explode", "(", "'/'", ",", "$", "route", "[", "'uri'", "]", ")", ";", "$", "serveruri", "=", "'/'", ".", "substr", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ",", "strrpos", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ",", "$", "expressionExp", "[", "1", "]", ")", ")", ";", "$", "serveruriexp", "=", "explode", "(", "'/'", ",", "$", "serveruri", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "expressionExp", ")", ";", "$", "i", "++", ")", "{", "$", "expressionExp", "[", "$", "i", "]", "=", "preg_replace_callback", "(", "'/\\{(.+)\\}/'", ",", "function", "(", "$", "m", ")", "use", "(", "$", "serveruriexp", ",", "$", "i", ",", "&", "$", "route", ")", "{", "$", "route", "[", "'query'", "]", "[", "]", "=", "[", "$", "m", "[", "1", "]", "=>", "$", "serveruriexp", "[", "$", "i", "]", "]", ";", "return", "strtolower", "(", "$", "serveruriexp", "[", "$", "i", "]", ")", ";", "// url hack to accept upper cases too", "}", ",", "$", "expressionExp", "[", "$", "i", "]", ")", ";", "}", "$", "expression", "=", "implode", "(", "'/'", ",", "$", "expressionExp", ")", ";", "$", "route", "[", "'uri'", "]", "=", "$", "expression", ";", "if", "(", "isset", "(", "$", "route", "[", "'querystring'", "]", ")", ")", "{", "$", "checkurl", "=", "$", "route", "[", "'uri'", "]", ".", "'?'", ".", "$", "route", "[", "'querystring'", "]", ";", "}", "else", "{", "$", "checkurl", "=", "$", "route", "[", "'uri'", "]", ";", "}", "if", "(", "(", "strtolower", "(", "$", "checkurl", ")", "==", "$", "url", ")", "&&", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", "==", "$", "route", "[", "'method'", "]", ")", ")", "{", "return", "$", "route", ";", "}", "}", "}" ]
Gets the route from supplied URL. @param string $url - The route's URL @return array
[ "Gets", "the", "route", "from", "supplied", "URL", "." ]
199b08b45fadf5dae14ac4732af03b36e15bbef2
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Routing/Router.php#L76-L129
train
Kris-Kuiper/sFire-Framework
src/Utils/Number.php
Number.round
public function round($decimals = 2) { if(false === ('-' . intval($decimals) == '-' . $decimals)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($decimals)), E_USER_ERROR); } return $this -> convert(function($number, $decimals) { return round($number, $decimals); }, [$decimals]); }
php
public function round($decimals = 2) { if(false === ('-' . intval($decimals) == '-' . $decimals)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($decimals)), E_USER_ERROR); } return $this -> convert(function($number, $decimals) { return round($number, $decimals); }, [$decimals]); }
[ "public", "function", "round", "(", "$", "decimals", "=", "2", ")", "{", "if", "(", "false", "===", "(", "'-'", ".", "intval", "(", "$", "decimals", ")", "==", "'-'", ".", "$", "decimals", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "decimals", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "return", "$", "this", "->", "convert", "(", "function", "(", "$", "number", ",", "$", "decimals", ")", "{", "return", "round", "(", "$", "number", ",", "$", "decimals", ")", ";", "}", ",", "[", "$", "decimals", "]", ")", ";", "}" ]
Round all the numbers with a precision @param int $decimals @return sFire\Number\Number
[ "Round", "all", "the", "numbers", "with", "a", "precision" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Utils/Number.php#L94-L103
train
Kris-Kuiper/sFire-Framework
src/Utils/Number.php
Number.toFixed
public function toFixed($decimals = 2) { if(false === ('-' . intval($decimals) == '-' . $decimals)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($decimals)), E_USER_ERROR); } return $this -> convert(function($number, $decimals) { $split = explode('.', (string) $number); if(count($split) < 2) { $split[1] = str_repeat('0', $decimals); } if(strlen($split[1]) < $decimals) { $split[1] .= str_repeat('0', $decimals - strlen($split[1])); } return rtrim(rtrim($split[0] . '.' . substr($split[1], 0, $decimals), ','), '.'); }, [$decimals]); }
php
public function toFixed($decimals = 2) { if(false === ('-' . intval($decimals) == '-' . $decimals)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($decimals)), E_USER_ERROR); } return $this -> convert(function($number, $decimals) { $split = explode('.', (string) $number); if(count($split) < 2) { $split[1] = str_repeat('0', $decimals); } if(strlen($split[1]) < $decimals) { $split[1] .= str_repeat('0', $decimals - strlen($split[1])); } return rtrim(rtrim($split[0] . '.' . substr($split[1], 0, $decimals), ','), '.'); }, [$decimals]); }
[ "public", "function", "toFixed", "(", "$", "decimals", "=", "2", ")", "{", "if", "(", "false", "===", "(", "'-'", ".", "intval", "(", "$", "decimals", ")", "==", "'-'", ".", "$", "decimals", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "decimals", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "return", "$", "this", "->", "convert", "(", "function", "(", "$", "number", ",", "$", "decimals", ")", "{", "$", "split", "=", "explode", "(", "'.'", ",", "(", "string", ")", "$", "number", ")", ";", "if", "(", "count", "(", "$", "split", ")", "<", "2", ")", "{", "$", "split", "[", "1", "]", "=", "str_repeat", "(", "'0'", ",", "$", "decimals", ")", ";", "}", "if", "(", "strlen", "(", "$", "split", "[", "1", "]", ")", "<", "$", "decimals", ")", "{", "$", "split", "[", "1", "]", ".=", "str_repeat", "(", "'0'", ",", "$", "decimals", "-", "strlen", "(", "$", "split", "[", "1", "]", ")", ")", ";", "}", "return", "rtrim", "(", "rtrim", "(", "$", "split", "[", "0", "]", ".", "'.'", ".", "substr", "(", "$", "split", "[", "1", "]", ",", "0", ",", "$", "decimals", ")", ",", "','", ")", ",", "'.'", ")", ";", "}", ",", "[", "$", "decimals", "]", ")", ";", "}" ]
Converts number into a string, keeping a specified number of decimal @param int $decimals @return sFire\Number\Number
[ "Converts", "number", "into", "a", "string", "keeping", "a", "specified", "number", "of", "decimal" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Utils/Number.php#L111-L132
train
Kris-Kuiper/sFire-Framework
src/Utils/Number.php
Number.val
public function val($index = 0) { if(false === ('-' . intval($index) == '-' . $index)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($index)), E_USER_ERROR); } $val = $this -> strip(); if(true === isset($val[$index])) { return $val[$index]; } return null; }
php
public function val($index = 0) { if(false === ('-' . intval($index) == '-' . $index)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($index)), E_USER_ERROR); } $val = $this -> strip(); if(true === isset($val[$index])) { return $val[$index]; } return null; }
[ "public", "function", "val", "(", "$", "index", "=", "0", ")", "{", "if", "(", "false", "===", "(", "'-'", ".", "intval", "(", "$", "index", ")", "==", "'-'", ".", "$", "index", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "index", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "val", "=", "$", "this", "->", "strip", "(", ")", ";", "if", "(", "true", "===", "isset", "(", "$", "val", "[", "$", "index", "]", ")", ")", "{", "return", "$", "val", "[", "$", "index", "]", ";", "}", "return", "null", ";", "}" ]
Strips all the numbers from a string and returns the value with an optional index to retrieve @return mixed
[ "Strips", "all", "the", "numbers", "from", "a", "string", "and", "returns", "the", "value", "with", "an", "optional", "index", "to", "retrieve" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Utils/Number.php#L153-L166
train
Kris-Kuiper/sFire-Framework
src/Utils/Number.php
Number.format
public function format($decimals = 2, $point = '.', $thousands_sep = ',', $currency = null) { if(false === ('-' . intval($decimals) == '-' . $decimals)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($decimals)), E_USER_ERROR); } if(false === is_string($point)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($point)), E_USER_ERROR); } if(false === is_string($thousands_sep)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($thousands_sep)), E_USER_ERROR); } if(null !== $currency && false === is_string($currency)) { return trigger_error(sprintf('Argument 4 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($currency)), E_USER_ERROR); } return $this -> convert(function($number, $decimals, $point, $thousands_sep, $currency) { return ($currency ?: $currency) . number_format($number, $decimals, $point, $thousands_sep); }, [$decimals, $point, $thousands_sep, $currency]); }
php
public function format($decimals = 2, $point = '.', $thousands_sep = ',', $currency = null) { if(false === ('-' . intval($decimals) == '-' . $decimals)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($decimals)), E_USER_ERROR); } if(false === is_string($point)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($point)), E_USER_ERROR); } if(false === is_string($thousands_sep)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($thousands_sep)), E_USER_ERROR); } if(null !== $currency && false === is_string($currency)) { return trigger_error(sprintf('Argument 4 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($currency)), E_USER_ERROR); } return $this -> convert(function($number, $decimals, $point, $thousands_sep, $currency) { return ($currency ?: $currency) . number_format($number, $decimals, $point, $thousands_sep); }, [$decimals, $point, $thousands_sep, $currency]); }
[ "public", "function", "format", "(", "$", "decimals", "=", "2", ",", "$", "point", "=", "'.'", ",", "$", "thousands_sep", "=", "','", ",", "$", "currency", "=", "null", ")", "{", "if", "(", "false", "===", "(", "'-'", ".", "intval", "(", "$", "decimals", ")", "==", "'-'", ".", "$", "decimals", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "decimals", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "point", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "point", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "thousands_sep", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 3 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "thousands_sep", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "null", "!==", "$", "currency", "&&", "false", "===", "is_string", "(", "$", "currency", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 4 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "currency", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "return", "$", "this", "->", "convert", "(", "function", "(", "$", "number", ",", "$", "decimals", ",", "$", "point", ",", "$", "thousands_sep", ",", "$", "currency", ")", "{", "return", "(", "$", "currency", "?", ":", "$", "currency", ")", ".", "number_format", "(", "$", "number", ",", "$", "decimals", ",", "$", "point", ",", "$", "thousands_sep", ")", ";", "}", ",", "[", "$", "decimals", ",", "$", "point", ",", "$", "thousands_sep", ",", "$", "currency", "]", ")", ";", "}" ]
Converts all the numbers in a string to a specific format @param int $decimals @param string $point @param string $thousands_sep @param string $currency @return sFire\Number\Number
[ "Converts", "all", "the", "numbers", "in", "a", "string", "to", "a", "specific", "format" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Utils/Number.php#L177-L198
train
Kris-Kuiper/sFire-Framework
src/Utils/Number.php
Number.convert
private function convert($callback, $variables = []) { $this -> number = preg_replace_callback('~[0-9\.,]+~', function($number) use ($callback, $variables) { return call_user_func_array($callback, array_merge([(float) str_replace(',', '', $number[0])], $variables)); }, $this -> number); return $this; }
php
private function convert($callback, $variables = []) { $this -> number = preg_replace_callback('~[0-9\.,]+~', function($number) use ($callback, $variables) { return call_user_func_array($callback, array_merge([(float) str_replace(',', '', $number[0])], $variables)); }, $this -> number); return $this; }
[ "private", "function", "convert", "(", "$", "callback", ",", "$", "variables", "=", "[", "]", ")", "{", "$", "this", "->", "number", "=", "preg_replace_callback", "(", "'~[0-9\\.,]+~'", ",", "function", "(", "$", "number", ")", "use", "(", "$", "callback", ",", "$", "variables", ")", "{", "return", "call_user_func_array", "(", "$", "callback", ",", "array_merge", "(", "[", "(", "float", ")", "str_replace", "(", "','", ",", "''", ",", "$", "number", "[", "0", "]", ")", "]", ",", "$", "variables", ")", ")", ";", "}", ",", "$", "this", "->", "number", ")", ";", "return", "$", "this", ";", "}" ]
Executes a callable function and returns this instance @param object $callback @param array $variables @return sFire\Number\Number
[ "Executes", "a", "callable", "function", "and", "returns", "this", "instance" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Utils/Number.php#L207-L214
train
SlaxWeb/Output
src/Handler/View.php
View.addData
public function addData(array $data, string $type = "all"): self { $this->viewData[$type] = array_merge($this->viewData[$type] ?? [], $data); return $this; }
php
public function addData(array $data, string $type = "all"): self { $this->viewData[$type] = array_merge($this->viewData[$type] ?? [], $data); return $this; }
[ "public", "function", "addData", "(", "array", "$", "data", ",", "string", "$", "type", "=", "\"all\"", ")", ":", "self", "{", "$", "this", "->", "viewData", "[", "$", "type", "]", "=", "array_merge", "(", "$", "this", "->", "viewData", "[", "$", "type", "]", "??", "[", "]", ",", "$", "data", ")", ";", "return", "$", "this", ";", "}" ]
Add view data Adds an array of data to the internal view data container. The second parameter, $type, defines if the data received will be used for a specific View, or all views. The $type needs to be set to the full class name of a view in order to be recognized as view data for that specific view. If the second parameters is omitted or value "all" is used, then data will be used for all views. @param array $data View data @param string $type View data type @return self
[ "Add", "view", "data" ]
5bee3258f2fe63e161d3e8abe85118bfbf02ab48
https://github.com/SlaxWeb/Output/blob/5bee3258f2fe63e161d3e8abe85118bfbf02ab48/src/Handler/View.php#L75-L79
train
Kris-Kuiper/sFire-Framework
src/MVC/MVC.php
MVC.loadController
public function loadController($module, $controller) { if(false === is_string($module)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($module)), E_USER_ERROR); } if(false === is_string($controller)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($controller)), E_USER_ERROR); } $folders = explode('.', $controller); //Convert dots to directory separators $amount = count($folders) - 1; $namespace = ''; foreach($folders as $index => $folder) { if($amount === $index) { $controller = Application :: get(['prefix', 'controller']) . $folder; $namespace .= $controller; break; } $namespace .= $folder . DIRECTORY_SEPARATOR; } $controller = str_replace(DIRECTORY_SEPARATOR, '\\', $module . DIRECTORY_SEPARATOR . Application :: get(['directory', 'controller']) . $namespace); return $controller; }
php
public function loadController($module, $controller) { if(false === is_string($module)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($module)), E_USER_ERROR); } if(false === is_string($controller)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($controller)), E_USER_ERROR); } $folders = explode('.', $controller); //Convert dots to directory separators $amount = count($folders) - 1; $namespace = ''; foreach($folders as $index => $folder) { if($amount === $index) { $controller = Application :: get(['prefix', 'controller']) . $folder; $namespace .= $controller; break; } $namespace .= $folder . DIRECTORY_SEPARATOR; } $controller = str_replace(DIRECTORY_SEPARATOR, '\\', $module . DIRECTORY_SEPARATOR . Application :: get(['directory', 'controller']) . $namespace); return $controller; }
[ "public", "function", "loadController", "(", "$", "module", ",", "$", "controller", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "module", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "module", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "controller", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "controller", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "folders", "=", "explode", "(", "'.'", ",", "$", "controller", ")", ";", "//Convert dots to directory separators\r", "$", "amount", "=", "count", "(", "$", "folders", ")", "-", "1", ";", "$", "namespace", "=", "''", ";", "foreach", "(", "$", "folders", "as", "$", "index", "=>", "$", "folder", ")", "{", "if", "(", "$", "amount", "===", "$", "index", ")", "{", "$", "controller", "=", "Application", "::", "get", "(", "[", "'prefix'", ",", "'controller'", "]", ")", ".", "$", "folder", ";", "$", "namespace", ".=", "$", "controller", ";", "break", ";", "}", "$", "namespace", ".=", "$", "folder", ".", "DIRECTORY_SEPARATOR", ";", "}", "$", "controller", "=", "str_replace", "(", "DIRECTORY_SEPARATOR", ",", "'\\\\'", ",", "$", "module", ".", "DIRECTORY_SEPARATOR", ".", "Application", "::", "get", "(", "[", "'directory'", ",", "'controller'", "]", ")", ".", "$", "namespace", ")", ";", "return", "$", "controller", ";", "}" ]
Loads controller by module name and controller name @param string $module @param string $controller @return string
[ "Loads", "controller", "by", "module", "name", "and", "controller", "name" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/MVC.php#L72-L102
train
Kris-Kuiper/sFire-Framework
src/MVC/MVC.php
MVC.executeController
private function executeController($controller, Route $method, $matches) { if(false === is_object($controller)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type object, "%s" given', __METHOD__, gettype($controller)), E_USER_ERROR); } if(false === is_array($matches)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($matches)), E_USER_ERROR); } //Load the module dispatch file if exists and readable $this -> loadBoot($method -> getModule()); //Execute start method if controller supports it if(true === is_callable([$controller, '__start'])) { call_user_func_array([$controller, '__start'], []); } //Execute main function $action = Application :: get(['prefix', 'action']) . $method -> getAction(); //Trigger error if main function does not exists if(false === is_callable([$controller, $action])) { return trigger_error(sprintf('Method "%s" does not exists in "%s" controller', Application :: get(['prefix', 'action']) . ucfirst($method -> getAction()), $method -> getController()), E_USER_ERROR); } call_user_func_array([$controller, $action], $matches); //Execute end method if controller supports it if(true === is_callable([$controller, '__end'])) { call_user_func_array([$controller, '__end'], []); } }
php
private function executeController($controller, Route $method, $matches) { if(false === is_object($controller)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type object, "%s" given', __METHOD__, gettype($controller)), E_USER_ERROR); } if(false === is_array($matches)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array, "%s" given', __METHOD__, gettype($matches)), E_USER_ERROR); } //Load the module dispatch file if exists and readable $this -> loadBoot($method -> getModule()); //Execute start method if controller supports it if(true === is_callable([$controller, '__start'])) { call_user_func_array([$controller, '__start'], []); } //Execute main function $action = Application :: get(['prefix', 'action']) . $method -> getAction(); //Trigger error if main function does not exists if(false === is_callable([$controller, $action])) { return trigger_error(sprintf('Method "%s" does not exists in "%s" controller', Application :: get(['prefix', 'action']) . ucfirst($method -> getAction()), $method -> getController()), E_USER_ERROR); } call_user_func_array([$controller, $action], $matches); //Execute end method if controller supports it if(true === is_callable([$controller, '__end'])) { call_user_func_array([$controller, '__end'], []); } }
[ "private", "function", "executeController", "(", "$", "controller", ",", "Route", "$", "method", ",", "$", "matches", ")", "{", "if", "(", "false", "===", "is_object", "(", "$", "controller", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type object, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "controller", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_array", "(", "$", "matches", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type array, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "matches", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "//Load the module dispatch file if exists and readable\r", "$", "this", "->", "loadBoot", "(", "$", "method", "->", "getModule", "(", ")", ")", ";", "//Execute start method if controller supports it\r", "if", "(", "true", "===", "is_callable", "(", "[", "$", "controller", ",", "'__start'", "]", ")", ")", "{", "call_user_func_array", "(", "[", "$", "controller", ",", "'__start'", "]", ",", "[", "]", ")", ";", "}", "//Execute main function\r", "$", "action", "=", "Application", "::", "get", "(", "[", "'prefix'", ",", "'action'", "]", ")", ".", "$", "method", "->", "getAction", "(", ")", ";", "//Trigger error if main function does not exists\r", "if", "(", "false", "===", "is_callable", "(", "[", "$", "controller", ",", "$", "action", "]", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Method \"%s\" does not exists in \"%s\" controller'", ",", "Application", "::", "get", "(", "[", "'prefix'", ",", "'action'", "]", ")", ".", "ucfirst", "(", "$", "method", "->", "getAction", "(", ")", ")", ",", "$", "method", "->", "getController", "(", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "call_user_func_array", "(", "[", "$", "controller", ",", "$", "action", "]", ",", "$", "matches", ")", ";", "//Execute end method if controller supports it\r", "if", "(", "true", "===", "is_callable", "(", "[", "$", "controller", ",", "'__end'", "]", ")", ")", "{", "call_user_func_array", "(", "[", "$", "controller", ",", "'__end'", "]", ",", "[", "]", ")", ";", "}", "}" ]
Executes default controller functions @param object $controller @param sFire\Routing\Extend\Route $method @param array $matches
[ "Executes", "default", "controller", "functions" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/MVC.php#L111-L143
train
Kris-Kuiper/sFire-Framework
src/MVC/MVC.php
MVC.loadBoot
private function loadBoot($module) { if(false === is_string($module)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($module)), E_USER_ERROR); } $boot = Path :: get('modules') . $module . DIRECTORY_SEPARATOR . Files :: get('boot'); if(true === is_readable($boot)) { require_once($boot); } }
php
private function loadBoot($module) { if(false === is_string($module)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($module)), E_USER_ERROR); } $boot = Path :: get('modules') . $module . DIRECTORY_SEPARATOR . Files :: get('boot'); if(true === is_readable($boot)) { require_once($boot); } }
[ "private", "function", "loadBoot", "(", "$", "module", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "module", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "module", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "boot", "=", "Path", "::", "get", "(", "'modules'", ")", ".", "$", "module", ".", "DIRECTORY_SEPARATOR", ".", "Files", "::", "get", "(", "'boot'", ")", ";", "if", "(", "true", "===", "is_readable", "(", "$", "boot", ")", ")", "{", "require_once", "(", "$", "boot", ")", ";", "}", "}" ]
Load the module boot file if exists and readable @param string $module
[ "Load", "the", "module", "boot", "file", "if", "exists", "and", "readable" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/MVC/MVC.php#L151-L162
train
cubicmushroom/valueobjects
src/Web/Domain.php
Domain.specifyType
public static function specifyType($domain) { if (false !== filter_var($domain, FILTER_VALIDATE_IP)) { return new IPAddress($domain); } return new Hostname($domain); }
php
public static function specifyType($domain) { if (false !== filter_var($domain, FILTER_VALIDATE_IP)) { return new IPAddress($domain); } return new Hostname($domain); }
[ "public", "static", "function", "specifyType", "(", "$", "domain", ")", "{", "if", "(", "false", "!==", "filter_var", "(", "$", "domain", ",", "FILTER_VALIDATE_IP", ")", ")", "{", "return", "new", "IPAddress", "(", "$", "domain", ")", ";", "}", "return", "new", "Hostname", "(", "$", "domain", ")", ";", "}" ]
Returns a Hostname or a IPAddress object depending on passed value @param $domain @return Hostname|IPAddress
[ "Returns", "a", "Hostname", "or", "a", "IPAddress", "object", "depending", "on", "passed", "value" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/Web/Domain.php#L15-L22
train
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php
SmartTemplate.result
function result ( $_top = '' ) { ob_start(); $this->output( $_top ); $result = ob_get_contents(); ob_end_clean(); return $result; }
php
function result ( $_top = '' ) { ob_start(); $this->output( $_top ); $result = ob_get_contents(); ob_end_clean(); return $result; }
[ "function", "result", "(", "$", "_top", "=", "''", ")", "{", "ob_start", "(", ")", ";", "$", "this", "->", "output", "(", "$", "_top", ")", ";", "$", "result", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "return", "$", "result", ";", "}" ]
Parser Wrapper Returns Template Output as a String @access public @param array $_top Content Array @return string Parsed Template @desc Output Buffer Parser Wrapper
[ "Parser", "Wrapper", "Returns", "Template", "Output", "as", "a", "String" ]
86efc9c8a0d504e01e2fea55868227fdc8928841
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php#L215-L222
train
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php
SmartTemplate.output
function output ( $_top = '' ) { global $_top; // Make sure that folder names have a trailing '/' if (strlen($this->template_dir) && substr($this->template_dir, -1) != '/') { $this->template_dir .= '/'; } if (strlen($this->temp_dir) && substr($this->temp_dir, -1) != '/') { $this->temp_dir .= '/'; } // Prepare Template Content if (!is_array($_top)) { if (strlen($_top)) { $this->tpl_file = $_top; } $_top = $this->data; } $_obj = &$_top; $_stack_cnt = 0; $_stack[$_stack_cnt++] = $_obj; // Check if template is already compiled $cpl_file_name = preg_replace('/[:\/.\\\\]/', '_', $this->tpl_file); if (strlen($cpl_file_name) > 0) { $this->cpl_file = $this->temp_dir . $cpl_file_name . '.php'; $compile_template = true; if ($this->reuse_code) { if (is_file($this->cpl_file)) { if ($this->mtime($this->cpl_file) > $this->mtime($this->template_dir . $this->tpl_file)) { $compile_template = false; } } } if ($compile_template) { if (@include_once("class.smarttemplateparser.php")) { $this->parser = new SmartTemplateParser($this->template_dir . $this->tpl_file); if (!$this->parser->compile($this->cpl_file)) { exit( "SmartTemplate Parser Error: " . $this->parser->error ); } } else { exit( "SmartTemplate Error: Cannot find class.smarttemplateparser.php; check SmartTemplate installation"); } } // Execute Compiled Template include($this->cpl_file); } else { exit( "SmartTemplate Error: You must set a template file name"); } // Delete Global Content Array in order to allow multiple use of SmartTemplate class in one script unset ($_top); }
php
function output ( $_top = '' ) { global $_top; // Make sure that folder names have a trailing '/' if (strlen($this->template_dir) && substr($this->template_dir, -1) != '/') { $this->template_dir .= '/'; } if (strlen($this->temp_dir) && substr($this->temp_dir, -1) != '/') { $this->temp_dir .= '/'; } // Prepare Template Content if (!is_array($_top)) { if (strlen($_top)) { $this->tpl_file = $_top; } $_top = $this->data; } $_obj = &$_top; $_stack_cnt = 0; $_stack[$_stack_cnt++] = $_obj; // Check if template is already compiled $cpl_file_name = preg_replace('/[:\/.\\\\]/', '_', $this->tpl_file); if (strlen($cpl_file_name) > 0) { $this->cpl_file = $this->temp_dir . $cpl_file_name . '.php'; $compile_template = true; if ($this->reuse_code) { if (is_file($this->cpl_file)) { if ($this->mtime($this->cpl_file) > $this->mtime($this->template_dir . $this->tpl_file)) { $compile_template = false; } } } if ($compile_template) { if (@include_once("class.smarttemplateparser.php")) { $this->parser = new SmartTemplateParser($this->template_dir . $this->tpl_file); if (!$this->parser->compile($this->cpl_file)) { exit( "SmartTemplate Parser Error: " . $this->parser->error ); } } else { exit( "SmartTemplate Error: Cannot find class.smarttemplateparser.php; check SmartTemplate installation"); } } // Execute Compiled Template include($this->cpl_file); } else { exit( "SmartTemplate Error: You must set a template file name"); } // Delete Global Content Array in order to allow multiple use of SmartTemplate class in one script unset ($_top); }
[ "function", "output", "(", "$", "_top", "=", "''", ")", "{", "global", "$", "_top", ";", "//\tMake sure that folder names have a trailing '/'", "if", "(", "strlen", "(", "$", "this", "->", "template_dir", ")", "&&", "substr", "(", "$", "this", "->", "template_dir", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "this", "->", "template_dir", ".=", "'/'", ";", "}", "if", "(", "strlen", "(", "$", "this", "->", "temp_dir", ")", "&&", "substr", "(", "$", "this", "->", "temp_dir", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "this", "->", "temp_dir", ".=", "'/'", ";", "}", "//\tPrepare Template Content", "if", "(", "!", "is_array", "(", "$", "_top", ")", ")", "{", "if", "(", "strlen", "(", "$", "_top", ")", ")", "{", "$", "this", "->", "tpl_file", "=", "$", "_top", ";", "}", "$", "_top", "=", "$", "this", "->", "data", ";", "}", "$", "_obj", "=", "&", "$", "_top", ";", "$", "_stack_cnt", "=", "0", ";", "$", "_stack", "[", "$", "_stack_cnt", "++", "]", "=", "$", "_obj", ";", "//\tCheck if template is already compiled", "$", "cpl_file_name", "=", "preg_replace", "(", "'/[:\\/.\\\\\\\\]/'", ",", "'_'", ",", "$", "this", "->", "tpl_file", ")", ";", "if", "(", "strlen", "(", "$", "cpl_file_name", ")", ">", "0", ")", "{", "$", "this", "->", "cpl_file", "=", "$", "this", "->", "temp_dir", ".", "$", "cpl_file_name", ".", "'.php'", ";", "$", "compile_template", "=", "true", ";", "if", "(", "$", "this", "->", "reuse_code", ")", "{", "if", "(", "is_file", "(", "$", "this", "->", "cpl_file", ")", ")", "{", "if", "(", "$", "this", "->", "mtime", "(", "$", "this", "->", "cpl_file", ")", ">", "$", "this", "->", "mtime", "(", "$", "this", "->", "template_dir", ".", "$", "this", "->", "tpl_file", ")", ")", "{", "$", "compile_template", "=", "false", ";", "}", "}", "}", "if", "(", "$", "compile_template", ")", "{", "if", "(", "@", "include_once", "(", "\"class.smarttemplateparser.php\"", ")", ")", "{", "$", "this", "->", "parser", "=", "new", "SmartTemplateParser", "(", "$", "this", "->", "template_dir", ".", "$", "this", "->", "tpl_file", ")", ";", "if", "(", "!", "$", "this", "->", "parser", "->", "compile", "(", "$", "this", "->", "cpl_file", ")", ")", "{", "exit", "(", "\"SmartTemplate Parser Error: \"", ".", "$", "this", "->", "parser", "->", "error", ")", ";", "}", "}", "else", "{", "exit", "(", "\"SmartTemplate Error: Cannot find class.smarttemplateparser.php; check SmartTemplate installation\"", ")", ";", "}", "}", "//\tExecute Compiled Template", "include", "(", "$", "this", "->", "cpl_file", ")", ";", "}", "else", "{", "exit", "(", "\"SmartTemplate Error: You must set a template file name\"", ")", ";", "}", "//\tDelete Global Content Array in order to allow multiple use of SmartTemplate class in one script", "unset", "(", "$", "_top", ")", ";", "}" ]
Execute parsed Template Prints Parsing Results to Standard Output @access public @param array $_top Content Array @desc Execute parsed Template
[ "Execute", "parsed", "Template", "Prints", "Parsing", "Results", "to", "Standard", "Output" ]
86efc9c8a0d504e01e2fea55868227fdc8928841
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php#L233-L299
train
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php
SmartTemplate.use_cache
function use_cache ( $key = '' ) { if (empty($_POST)) { $this->cache_filename = $this->cache_dir . 'cache_' . md5($_SERVER['REQUEST_URI'] . serialize($key)) . '.ser'; if (($_SERVER['HTTP_CACHE_CONTROL'] != 'no-cache') && ($_SERVER['HTTP_PRAGMA'] != 'no-cache') && @is_file($this->cache_filename)) { if ((time() - filemtime($this->cache_filename)) < $this->cache_lifetime) { readfile($this->cache_filename); exit; } } ob_start( array( &$this, 'cache_callback' ) ); } }
php
function use_cache ( $key = '' ) { if (empty($_POST)) { $this->cache_filename = $this->cache_dir . 'cache_' . md5($_SERVER['REQUEST_URI'] . serialize($key)) . '.ser'; if (($_SERVER['HTTP_CACHE_CONTROL'] != 'no-cache') && ($_SERVER['HTTP_PRAGMA'] != 'no-cache') && @is_file($this->cache_filename)) { if ((time() - filemtime($this->cache_filename)) < $this->cache_lifetime) { readfile($this->cache_filename); exit; } } ob_start( array( &$this, 'cache_callback' ) ); } }
[ "function", "use_cache", "(", "$", "key", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "_POST", ")", ")", "{", "$", "this", "->", "cache_filename", "=", "$", "this", "->", "cache_dir", ".", "'cache_'", ".", "md5", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ".", "serialize", "(", "$", "key", ")", ")", ".", "'.ser'", ";", "if", "(", "(", "$", "_SERVER", "[", "'HTTP_CACHE_CONTROL'", "]", "!=", "'no-cache'", ")", "&&", "(", "$", "_SERVER", "[", "'HTTP_PRAGMA'", "]", "!=", "'no-cache'", ")", "&&", "@", "is_file", "(", "$", "this", "->", "cache_filename", ")", ")", "{", "if", "(", "(", "time", "(", ")", "-", "filemtime", "(", "$", "this", "->", "cache_filename", ")", ")", "<", "$", "this", "->", "cache_lifetime", ")", "{", "readfile", "(", "$", "this", "->", "cache_filename", ")", ";", "exit", ";", "}", "}", "ob_start", "(", "array", "(", "&", "$", "this", ",", "'cache_callback'", ")", ")", ";", "}", "}" ]
Start Ouput Content Buffering Usage Example: $page = new SmartTemplate('template.html'); $page->use_cache(); ... @access public @desc Output Cache
[ "Start", "Ouput", "Content", "Buffering" ]
86efc9c8a0d504e01e2fea55868227fdc8928841
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php#L339-L354
train
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php
SmartTemplate.cache_callback
function cache_callback ( $output ) { if ($hd = @fopen($this->cache_filename, 'w')) { fputs($hd, $output); fclose($hd); } return $output; }
php
function cache_callback ( $output ) { if ($hd = @fopen($this->cache_filename, 'w')) { fputs($hd, $output); fclose($hd); } return $output; }
[ "function", "cache_callback", "(", "$", "output", ")", "{", "if", "(", "$", "hd", "=", "@", "fopen", "(", "$", "this", "->", "cache_filename", ",", "'w'", ")", ")", "{", "fputs", "(", "$", "hd", ",", "$", "output", ")", ";", "fclose", "(", "$", "hd", ")", ";", "}", "return", "$", "output", ";", "}" ]
Output Buffer Callback Function @access private @param string $output @return string $output
[ "Output", "Buffer", "Callback", "Function" ]
86efc9c8a0d504e01e2fea55868227fdc8928841
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplate.php#L364-L372
train
phospr/DoubleEntryBundle
Model/Posting.php
Posting.getOffsetPosting
public function getOffsetPosting() { $this->getJournal()->assertIsSimpleJournal(); foreach ($this->getJournal()->getPostings() as $posting) { if ($posting != $this) { return $posting; } } }
php
public function getOffsetPosting() { $this->getJournal()->assertIsSimpleJournal(); foreach ($this->getJournal()->getPostings() as $posting) { if ($posting != $this) { return $posting; } } }
[ "public", "function", "getOffsetPosting", "(", ")", "{", "$", "this", "->", "getJournal", "(", ")", "->", "assertIsSimpleJournal", "(", ")", ";", "foreach", "(", "$", "this", "->", "getJournal", "(", ")", "->", "getPostings", "(", ")", "as", "$", "posting", ")", "{", "if", "(", "$", "posting", "!=", "$", "this", ")", "{", "return", "$", "posting", ";", "}", "}", "}" ]
Get offset posting If this Posting's Journal has only two Postings, then return the offset Posting @author Tom Haskins-Vaughan <[email protected]> @since 0.8.0 @todo Use better Exception class @return Posting
[ "Get", "offset", "posting" ]
d9c421f30922b461483731983c59beb26047fb7f
https://github.com/phospr/DoubleEntryBundle/blob/d9c421f30922b461483731983c59beb26047fb7f/Model/Posting.php#L365-L374
train
netbull/CoreBundle
Form/DataTransformer/PointToStringTransformer.php
PointToStringTransformer.reverseTransform
public function reverseTransform($stringPoint) { if (!$stringPoint) { return null; } if (null === $stringPoint) { throw new TransformationFailedException(sprintf( 'An area with number "%s" does not exist!', $stringPoint )); } if (is_array($stringPoint)) { $stringPoint = $stringPoint['gpsCoordinate']; } $coordinates = explode(', ', $stringPoint); if (count($coordinates) !== 2) { throw new TransformationFailedException(sprintf( 'The Coordinates should contain latitude and longitude!', $stringPoint )); } return new Point($coordinates[0], $coordinates[1]); }
php
public function reverseTransform($stringPoint) { if (!$stringPoint) { return null; } if (null === $stringPoint) { throw new TransformationFailedException(sprintf( 'An area with number "%s" does not exist!', $stringPoint )); } if (is_array($stringPoint)) { $stringPoint = $stringPoint['gpsCoordinate']; } $coordinates = explode(', ', $stringPoint); if (count($coordinates) !== 2) { throw new TransformationFailedException(sprintf( 'The Coordinates should contain latitude and longitude!', $stringPoint )); } return new Point($coordinates[0], $coordinates[1]); }
[ "public", "function", "reverseTransform", "(", "$", "stringPoint", ")", "{", "if", "(", "!", "$", "stringPoint", ")", "{", "return", "null", ";", "}", "if", "(", "null", "===", "$", "stringPoint", ")", "{", "throw", "new", "TransformationFailedException", "(", "sprintf", "(", "'An area with number \"%s\" does not exist!'", ",", "$", "stringPoint", ")", ")", ";", "}", "if", "(", "is_array", "(", "$", "stringPoint", ")", ")", "{", "$", "stringPoint", "=", "$", "stringPoint", "[", "'gpsCoordinate'", "]", ";", "}", "$", "coordinates", "=", "explode", "(", "', '", ",", "$", "stringPoint", ")", ";", "if", "(", "count", "(", "$", "coordinates", ")", "!==", "2", ")", "{", "throw", "new", "TransformationFailedException", "(", "sprintf", "(", "'The Coordinates should contain latitude and longitude!'", ",", "$", "stringPoint", ")", ")", ";", "}", "return", "new", "Point", "(", "$", "coordinates", "[", "0", "]", ",", "$", "coordinates", "[", "1", "]", ")", ";", "}" ]
Transforms a string to an object. @param mixed $stringPoint @return null|string
[ "Transforms", "a", "string", "to", "an", "object", "." ]
0bacc1d9e4733b6da613027400c48421e5a14645
https://github.com/netbull/CoreBundle/blob/0bacc1d9e4733b6da613027400c48421e5a14645/Form/DataTransformer/PointToStringTransformer.php#L34-L61
train
phospr/DoubleEntryBundle
Model/Organization.php
Organization.findVendorForSlug
public function findVendorForSlug($slug) { $criteria = Criteria::create() ->where(Criteria::expr()->eq('slug', $slug)) ; return $this->getVendors()->matching($criteria)->first(); }
php
public function findVendorForSlug($slug) { $criteria = Criteria::create() ->where(Criteria::expr()->eq('slug', $slug)) ; return $this->getVendors()->matching($criteria)->first(); }
[ "public", "function", "findVendorForSlug", "(", "$", "slug", ")", "{", "$", "criteria", "=", "Criteria", "::", "create", "(", ")", "->", "where", "(", "Criteria", "::", "expr", "(", ")", "->", "eq", "(", "'slug'", ",", "$", "slug", ")", ")", ";", "return", "$", "this", "->", "getVendors", "(", ")", "->", "matching", "(", "$", "criteria", ")", "->", "first", "(", ")", ";", "}" ]
Find Vendor given slug @author Tom Haskins-Vaughan <[email protected]> @since 0.8.0 @return Vendor
[ "Find", "Vendor", "given", "slug" ]
d9c421f30922b461483731983c59beb26047fb7f
https://github.com/phospr/DoubleEntryBundle/blob/d9c421f30922b461483731983c59beb26047fb7f/Model/Organization.php#L411-L418
train
aegis-security/JSON
src/Decoder.php
Decoder.decodeUnicodeString
public static function decodeUnicodeString($chrs) { $chrs = (string) $chrs; $utf8 = ''; $strlenChrs = strlen($chrs); for ($i = 0; $i < $strlenChrs; $i++) { $ordChrsC = ord($chrs[$i]); switch (true) { case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $i, 6)): // single, escaped unicode character $utf16 = chr(hexdec(substr($chrs, ($i + 2), 2))) . chr(hexdec(substr($chrs, ($i + 4), 2))); $utf8char = self::_utf162utf8($utf16); $search = array('\\', "\n", "\t", "\r", chr(0x08), chr(0x0C), '"', '\'', '/'); if (in_array($utf8char, $search)) { $replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\\"', '\\\'', '\\/'); $utf8char = str_replace($search, $replace, $utf8char); } $utf8 .= $utf8char; $i += 5; break; case ($ordChrsC >= 0x20) && ($ordChrsC <= 0x7F): $utf8 .= $chrs{$i}; break; case ($ordChrsC & 0xE0) == 0xC0: // characters U-00000080 - U-000007FF, mask 110XXXXX //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 2); ++$i; break; case ($ordChrsC & 0xF0) == 0xE0: // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 3); $i += 2; break; case ($ordChrsC & 0xF8) == 0xF0: // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 4); $i += 3; break; case ($ordChrsC & 0xFC) == 0xF8: // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 5); $i += 4; break; case ($ordChrsC & 0xFE) == 0xFC: // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 6); $i += 5; break; } } return $utf8; }
php
public static function decodeUnicodeString($chrs) { $chrs = (string) $chrs; $utf8 = ''; $strlenChrs = strlen($chrs); for ($i = 0; $i < $strlenChrs; $i++) { $ordChrsC = ord($chrs[$i]); switch (true) { case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $i, 6)): // single, escaped unicode character $utf16 = chr(hexdec(substr($chrs, ($i + 2), 2))) . chr(hexdec(substr($chrs, ($i + 4), 2))); $utf8char = self::_utf162utf8($utf16); $search = array('\\', "\n", "\t", "\r", chr(0x08), chr(0x0C), '"', '\'', '/'); if (in_array($utf8char, $search)) { $replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\\"', '\\\'', '\\/'); $utf8char = str_replace($search, $replace, $utf8char); } $utf8 .= $utf8char; $i += 5; break; case ($ordChrsC >= 0x20) && ($ordChrsC <= 0x7F): $utf8 .= $chrs{$i}; break; case ($ordChrsC & 0xE0) == 0xC0: // characters U-00000080 - U-000007FF, mask 110XXXXX //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 2); ++$i; break; case ($ordChrsC & 0xF0) == 0xE0: // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 3); $i += 2; break; case ($ordChrsC & 0xF8) == 0xF0: // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 4); $i += 3; break; case ($ordChrsC & 0xFC) == 0xF8: // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 5); $i += 4; break; case ($ordChrsC & 0xFE) == 0xFC: // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $i, 6); $i += 5; break; } } return $utf8; }
[ "public", "static", "function", "decodeUnicodeString", "(", "$", "chrs", ")", "{", "$", "chrs", "=", "(", "string", ")", "$", "chrs", ";", "$", "utf8", "=", "''", ";", "$", "strlenChrs", "=", "strlen", "(", "$", "chrs", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "strlenChrs", ";", "$", "i", "++", ")", "{", "$", "ordChrsC", "=", "ord", "(", "$", "chrs", "[", "$", "i", "]", ")", ";", "switch", "(", "true", ")", "{", "case", "preg_match", "(", "'/\\\\\\u[0-9A-F]{4}/i'", ",", "substr", "(", "$", "chrs", ",", "$", "i", ",", "6", ")", ")", ":", "// single, escaped unicode character", "$", "utf16", "=", "chr", "(", "hexdec", "(", "substr", "(", "$", "chrs", ",", "(", "$", "i", "+", "2", ")", ",", "2", ")", ")", ")", ".", "chr", "(", "hexdec", "(", "substr", "(", "$", "chrs", ",", "(", "$", "i", "+", "4", ")", ",", "2", ")", ")", ")", ";", "$", "utf8char", "=", "self", "::", "_utf162utf8", "(", "$", "utf16", ")", ";", "$", "search", "=", "array", "(", "'\\\\'", ",", "\"\\n\"", ",", "\"\\t\"", ",", "\"\\r\"", ",", "chr", "(", "0x08", ")", ",", "chr", "(", "0x0C", ")", ",", "'\"'", ",", "'\\''", ",", "'/'", ")", ";", "if", "(", "in_array", "(", "$", "utf8char", ",", "$", "search", ")", ")", "{", "$", "replace", "=", "array", "(", "'\\\\\\\\'", ",", "'\\\\n'", ",", "'\\\\t'", ",", "'\\\\r'", ",", "'\\\\b'", ",", "'\\\\f'", ",", "'\\\\\"'", ",", "'\\\\\\''", ",", "'\\\\/'", ")", ";", "$", "utf8char", "=", "str_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "utf8char", ")", ";", "}", "$", "utf8", ".=", "$", "utf8char", ";", "$", "i", "+=", "5", ";", "break", ";", "case", "(", "$", "ordChrsC", ">=", "0x20", ")", "&&", "(", "$", "ordChrsC", "<=", "0x7F", ")", ":", "$", "utf8", ".=", "$", "chrs", "{", "$", "i", "}", ";", "break", ";", "case", "(", "$", "ordChrsC", "&", "0xE0", ")", "==", "0xC0", ":", "// characters U-00000080 - U-000007FF, mask 110XXXXX", "//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "$", "utf8", ".=", "substr", "(", "$", "chrs", ",", "$", "i", ",", "2", ")", ";", "++", "$", "i", ";", "break", ";", "case", "(", "$", "ordChrsC", "&", "0xF0", ")", "==", "0xE0", ":", "// characters U-00000800 - U-0000FFFF, mask 1110XXXX", "// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "$", "utf8", ".=", "substr", "(", "$", "chrs", ",", "$", "i", ",", "3", ")", ";", "$", "i", "+=", "2", ";", "break", ";", "case", "(", "$", "ordChrsC", "&", "0xF8", ")", "==", "0xF0", ":", "// characters U-00010000 - U-001FFFFF, mask 11110XXX", "// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "$", "utf8", ".=", "substr", "(", "$", "chrs", ",", "$", "i", ",", "4", ")", ";", "$", "i", "+=", "3", ";", "break", ";", "case", "(", "$", "ordChrsC", "&", "0xFC", ")", "==", "0xF8", ":", "// characters U-00200000 - U-03FFFFFF, mask 111110XX", "// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "$", "utf8", ".=", "substr", "(", "$", "chrs", ",", "$", "i", ",", "5", ")", ";", "$", "i", "+=", "4", ";", "break", ";", "case", "(", "$", "ordChrsC", "&", "0xFE", ")", "==", "0xFC", ":", "// characters U-04000000 - U-7FFFFFFF, mask 1111110X", "// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "$", "utf8", ".=", "substr", "(", "$", "chrs", ",", "$", "i", ",", "6", ")", ";", "$", "i", "+=", "5", ";", "break", ";", "}", "}", "return", "$", "utf8", ";", "}" ]
Decode Unicode Characters from \u0000 ASCII syntax. This algorithm was originally developed for the Solar Framework by Paul M. Jones @link http://solarphp.com/ @link https://github.com/solarphp/core/blob/master/Solar/Json.php @param string $chrs @return string
[ "Decode", "Unicode", "Characters", "from", "\\", "u0000", "ASCII", "syntax", "." ]
7bc8e442e9e570ecbc480053d9aaa42a52910fbc
https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Decoder.php#L83-L143
train
aegis-security/JSON
src/Decoder.php
Decoder._decodeValue
protected function _decodeValue() { switch ($this->token) { case self::DATUM: $result = $this->tokenValue; $this->_getNextToken(); return($result); case self::LBRACE: return($this->_decodeObject()); case self::LBRACKET: return($this->_decodeArray()); } }
php
protected function _decodeValue() { switch ($this->token) { case self::DATUM: $result = $this->tokenValue; $this->_getNextToken(); return($result); case self::LBRACE: return($this->_decodeObject()); case self::LBRACKET: return($this->_decodeArray()); } }
[ "protected", "function", "_decodeValue", "(", ")", "{", "switch", "(", "$", "this", "->", "token", ")", "{", "case", "self", "::", "DATUM", ":", "$", "result", "=", "$", "this", "->", "tokenValue", ";", "$", "this", "->", "_getNextToken", "(", ")", ";", "return", "(", "$", "result", ")", ";", "case", "self", "::", "LBRACE", ":", "return", "(", "$", "this", "->", "_decodeObject", "(", ")", ")", ";", "case", "self", "::", "LBRACKET", ":", "return", "(", "$", "this", "->", "_decodeArray", "(", ")", ")", ";", "}", "}" ]
Recursive driving routine for supported toplevel tops @return mixed
[ "Recursive", "driving", "routine", "for", "supported", "toplevel", "tops" ]
7bc8e442e9e570ecbc480053d9aaa42a52910fbc
https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Decoder.php#L211-L228
train
aegis-security/JSON
src/Decoder.php
Decoder._eatWhitespace
protected function _eatWhitespace() { if (preg_match('/([\t\b\f\n\r ])*/s', $this->source, $matches, PREG_OFFSET_CAPTURE, $this->offset) && $matches[0][1] == $this->offset) { $this->offset += strlen($matches[0][0]); } }
php
protected function _eatWhitespace() { if (preg_match('/([\t\b\f\n\r ])*/s', $this->source, $matches, PREG_OFFSET_CAPTURE, $this->offset) && $matches[0][1] == $this->offset) { $this->offset += strlen($matches[0][0]); } }
[ "protected", "function", "_eatWhitespace", "(", ")", "{", "if", "(", "preg_match", "(", "'/([\\t\\b\\f\\n\\r ])*/s'", ",", "$", "this", "->", "source", ",", "$", "matches", ",", "PREG_OFFSET_CAPTURE", ",", "$", "this", "->", "offset", ")", "&&", "$", "matches", "[", "0", "]", "[", "1", "]", "==", "$", "this", "->", "offset", ")", "{", "$", "this", "->", "offset", "+=", "strlen", "(", "$", "matches", "[", "0", "]", "[", "0", "]", ")", ";", "}", "}" ]
Removes whitespace characters from the source input
[ "Removes", "whitespace", "characters", "from", "the", "source", "input" ]
7bc8e442e9e570ecbc480053d9aaa42a52910fbc
https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Decoder.php#L334-L340
train
aegis-security/JSON
src/Decoder.php
Decoder._utf162utf8
protected static function _utf162utf8($utf16) { // Check for mb extension otherwise do by hand. if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); } $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); switch (true) { case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x7F & $bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } // ignoring UTF-32 for now, sorry return ''; }
php
protected static function _utf162utf8($utf16) { // Check for mb extension otherwise do by hand. if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); } $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); switch (true) { case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x7F & $bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } // ignoring UTF-32 for now, sorry return ''; }
[ "protected", "static", "function", "_utf162utf8", "(", "$", "utf16", ")", "{", "// Check for mb extension otherwise do by hand.", "if", "(", "function_exists", "(", "'mb_convert_encoding'", ")", ")", "{", "return", "mb_convert_encoding", "(", "$", "utf16", ",", "'UTF-8'", ",", "'UTF-16'", ")", ";", "}", "$", "bytes", "=", "(", "ord", "(", "$", "utf16", "{", "0", "}", ")", "<<", "8", ")", "|", "ord", "(", "$", "utf16", "{", "1", "}", ")", ";", "switch", "(", "true", ")", "{", "case", "(", "(", "0x7F", "&", "$", "bytes", ")", "==", "$", "bytes", ")", ":", "// this case should never be reached, because we are in ASCII range", "// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "return", "chr", "(", "0x7F", "&", "$", "bytes", ")", ";", "case", "(", "0x07FF", "&", "$", "bytes", ")", "==", "$", "bytes", ":", "// return a 2-byte UTF-8 character", "// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "return", "chr", "(", "0xC0", "|", "(", "(", "$", "bytes", ">>", "6", ")", "&", "0x1F", ")", ")", ".", "chr", "(", "0x80", "|", "(", "$", "bytes", "&", "0x3F", ")", ")", ";", "case", "(", "0xFFFF", "&", "$", "bytes", ")", "==", "$", "bytes", ":", "// return a 3-byte UTF-8 character", "// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8", "return", "chr", "(", "0xE0", "|", "(", "(", "$", "bytes", ">>", "12", ")", "&", "0x0F", ")", ")", ".", "chr", "(", "0x80", "|", "(", "(", "$", "bytes", ">>", "6", ")", "&", "0x3F", ")", ")", ".", "chr", "(", "0x80", "|", "(", "$", "bytes", "&", "0x3F", ")", ")", ";", "}", "// ignoring UTF-32 for now, sorry", "return", "''", ";", "}" ]
Convert a string from one UTF-16 char to one UTF-8 char. Normally should be handled by mb_convert_encoding, but provides a slower PHP-only method for installations that lack the multibyte string extension. This method is from the Solar Framework by Paul M. Jones @link http://solarphp.com @param string $utf16 UTF-16 character @return string UTF-8 character
[ "Convert", "a", "string", "from", "one", "UTF", "-", "16", "char", "to", "one", "UTF", "-", "8", "char", "." ]
7bc8e442e9e570ecbc480053d9aaa42a52910fbc
https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Decoder.php#L508-L539
train
shgysk8zer0/core_api
traits/consolehandlers.php
ConsoleHandlers.reportError
final public function reportError( $errno, $errstr, $errfile, $errline, array $errcontext = array() ) { $this->_addRow( array($errstr), $this->_formatLocation($errfile, $errline), self::ERROR ); }
php
final public function reportError( $errno, $errstr, $errfile, $errline, array $errcontext = array() ) { $this->_addRow( array($errstr), $this->_formatLocation($errfile, $errline), self::ERROR ); }
[ "final", "public", "function", "reportError", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ",", "array", "$", "errcontext", "=", "array", "(", ")", ")", "{", "$", "this", "->", "_addRow", "(", "array", "(", "$", "errstr", ")", ",", "$", "this", "->", "_formatLocation", "(", "$", "errfile", ",", "$", "errline", ")", ",", "self", "::", "ERROR", ")", ";", "}" ]
logs a PHP error to the console as an error @param int $errno the level of the error raised @param string $errstr the error message @param string $errfile the filename that the error was raised in @param int $errline the line number the error was raised at @param array $errcontext an array that points to the active symbol table at the point the error occurred @return void
[ "logs", "a", "PHP", "error", "to", "the", "console", "as", "an", "error" ]
9e9b8baf761af874b95256ad2462e55fbb2b2e58
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/consolehandlers.php#L42-L55
train
shgysk8zer0/core_api
traits/consolehandlers.php
ConsoleHandlers.reportException
final public function reportException(\Exception $e) { $this->_addRow( array($e->getMessage()), $this->_formatLocation($e->getFile(), $e->getLine()), self::WARN ); }
php
final public function reportException(\Exception $e) { $this->_addRow( array($e->getMessage()), $this->_formatLocation($e->getFile(), $e->getLine()), self::WARN ); }
[ "final", "public", "function", "reportException", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "_addRow", "(", "array", "(", "$", "e", "->", "getMessage", "(", ")", ")", ",", "$", "this", "->", "_formatLocation", "(", "$", "e", "->", "getFile", "(", ")", ",", "$", "e", "->", "getLine", "(", ")", ")", ",", "self", "::", "WARN", ")", ";", "}" ]
logs a PHP exception to the console as a warn @param Exception $e the exception @return void
[ "logs", "a", "PHP", "exception", "to", "the", "console", "as", "a", "warn" ]
9e9b8baf761af874b95256ad2462e55fbb2b2e58
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/consolehandlers.php#L64-L71
train
vpg/titon.utility
src/Titon/Utility/Format.php
Format.phone
public static function phone($value, $format) { $value = preg_replace('/[^0-9]+/', '', $value); if (is_array($format)) { $length = mb_strlen($value); if ($length >= 11) { $format = $format[11]; } else if ($length >= 10) { $format = $format[10]; } else { $format = $format[7]; } } return static::format($value, $format); }
php
public static function phone($value, $format) { $value = preg_replace('/[^0-9]+/', '', $value); if (is_array($format)) { $length = mb_strlen($value); if ($length >= 11) { $format = $format[11]; } else if ($length >= 10) { $format = $format[10]; } else { $format = $format[7]; } } return static::format($value, $format); }
[ "public", "static", "function", "phone", "(", "$", "value", ",", "$", "format", ")", "{", "$", "value", "=", "preg_replace", "(", "'/[^0-9]+/'", ",", "''", ",", "$", "value", ")", ";", "if", "(", "is_array", "(", "$", "format", ")", ")", "{", "$", "length", "=", "mb_strlen", "(", "$", "value", ")", ";", "if", "(", "$", "length", ">=", "11", ")", "{", "$", "format", "=", "$", "format", "[", "11", "]", ";", "}", "else", "if", "(", "$", "length", ">=", "10", ")", "{", "$", "format", "=", "$", "format", "[", "10", "]", ";", "}", "else", "{", "$", "format", "=", "$", "format", "[", "7", "]", ";", "}", "}", "return", "static", "::", "format", "(", "$", "value", ",", "$", "format", ")", ";", "}" ]
Format a phone number. A phone number can support multiple variations, depending on how many numbers are present. @param int $value @param string $format @return string
[ "Format", "a", "phone", "number", ".", "A", "phone", "number", "can", "support", "multiple", "variations", "depending", "on", "how", "many", "numbers", "are", "present", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Format.php#L109-L125
train
mpf-soft/admin-widgets
form/fields/ForumTextarea.php
ForumTextarea._replaceRuleText
protected static function _replaceRuleText($text, $rule){ for ($parts = 1; $parts < 20; $parts++){ if (false === strpos($rule, "{T$parts}")) break; } if (1=== $parts){ return str_replace(["T", "T1"], $text, $rule); } $text = str_replace("\\|", "<<__E\$C@P#D__>>", $text); $pieces = explode("|", $text, $parts); $text = str_replace("{T}", $text, $rule); for ($i = 0; $i < $parts; $i++){ $text = str_replace("{T".($i+1)."}", $pieces[$i], $text); } return str_replace("<<__E\$C@P#D__>>", "\\|", $text); }
php
protected static function _replaceRuleText($text, $rule){ for ($parts = 1; $parts < 20; $parts++){ if (false === strpos($rule, "{T$parts}")) break; } if (1=== $parts){ return str_replace(["T", "T1"], $text, $rule); } $text = str_replace("\\|", "<<__E\$C@P#D__>>", $text); $pieces = explode("|", $text, $parts); $text = str_replace("{T}", $text, $rule); for ($i = 0; $i < $parts; $i++){ $text = str_replace("{T".($i+1)."}", $pieces[$i], $text); } return str_replace("<<__E\$C@P#D__>>", "\\|", $text); }
[ "protected", "static", "function", "_replaceRuleText", "(", "$", "text", ",", "$", "rule", ")", "{", "for", "(", "$", "parts", "=", "1", ";", "$", "parts", "<", "20", ";", "$", "parts", "++", ")", "{", "if", "(", "false", "===", "strpos", "(", "$", "rule", ",", "\"{T$parts}\"", ")", ")", "break", ";", "}", "if", "(", "1", "===", "$", "parts", ")", "{", "return", "str_replace", "(", "[", "\"T\"", ",", "\"T1\"", "]", ",", "$", "text", ",", "$", "rule", ")", ";", "}", "$", "text", "=", "str_replace", "(", "\"\\\\|\"", ",", "\"<<__E\\$C@P#D__>>\"", ",", "$", "text", ")", ";", "$", "pieces", "=", "explode", "(", "\"|\"", ",", "$", "text", ",", "$", "parts", ")", ";", "$", "text", "=", "str_replace", "(", "\"{T}\"", ",", "$", "text", ",", "$", "rule", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "parts", ";", "$", "i", "++", ")", "{", "$", "text", "=", "str_replace", "(", "\"{T\"", ".", "(", "$", "i", "+", "1", ")", ".", "\"}\"", ",", "$", "pieces", "[", "$", "i", "]", ",", "$", "text", ")", ";", "}", "return", "str_replace", "(", "\"<<__E\\$C@P#D__>>\"", ",", "\"\\\\|\"", ",", "$", "text", ")", ";", "}" ]
Replaced found text for a rule. @param string $text @param string $rule @return string
[ "Replaced", "found", "text", "for", "a", "rule", "." ]
92597f9a09d086664268d6b7e0111d5a5586d8c7
https://github.com/mpf-soft/admin-widgets/blob/92597f9a09d086664268d6b7e0111d5a5586d8c7/form/fields/ForumTextarea.php#L153-L168
train
zarathustra323/modlr-data
src/Zarathustra/ModlrData/Resource/Entity.php
Entity.getRelationship
public function getRelationship($key) { if (isset($this->relationships[$key])) { return $this->relationships[$key]; } return null; }
php
public function getRelationship($key) { if (isset($this->relationships[$key])) { return $this->relationships[$key]; } return null; }
[ "public", "function", "getRelationship", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "relationships", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "relationships", "[", "$", "key", "]", ";", "}", "return", "null", ";", "}" ]
Gets a relationship from this entity. Returns null if the relationship doesn't exist. @param string $key @return Relationship|null
[ "Gets", "a", "relationship", "from", "this", "entity", ".", "Returns", "null", "if", "the", "relationship", "doesn", "t", "exist", "." ]
7c2c767216055f75abf8cf22e2200f11998ed24e
https://github.com/zarathustra323/modlr-data/blob/7c2c767216055f75abf8cf22e2200f11998ed24e/src/Zarathustra/ModlrData/Resource/Entity.php#L100-L106
train
zarathustra323/modlr-data
src/Zarathustra/ModlrData/Resource/Resource.php
Resource.pushData
public function pushData(Entity $entity) { if ($this->isMany()) { $this->primaryData[] = $entity; return $this; } $this->primaryData = $entity; return $this; }
php
public function pushData(Entity $entity) { if ($this->isMany()) { $this->primaryData[] = $entity; return $this; } $this->primaryData = $entity; return $this; }
[ "public", "function", "pushData", "(", "Entity", "$", "entity", ")", "{", "if", "(", "$", "this", "->", "isMany", "(", ")", ")", "{", "$", "this", "->", "primaryData", "[", "]", "=", "$", "entity", ";", "return", "$", "this", ";", "}", "$", "this", "->", "primaryData", "=", "$", "entity", ";", "return", "$", "this", ";", "}" ]
Pushes entities to this resource. @param Entity $entity @return self
[ "Pushes", "entities", "to", "this", "resource", "." ]
7c2c767216055f75abf8cf22e2200f11998ed24e
https://github.com/zarathustra323/modlr-data/blob/7c2c767216055f75abf8cf22e2200f11998ed24e/src/Zarathustra/ModlrData/Resource/Resource.php#L81-L89
train
GetOlympus/olympus-social-field
src/Social/Social.php
Social.hex2rgb
protected function hex2rgb($hexcolor) { preg_match("/^#{0,1}([0-9a-f]{1,6})$/i", $hexcolor, $match); if (!isset($match[1])) { return []; } $color = $match[1]; #91d04d if (6 == strlen($color)) { list($r, $g, $b) = [ $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] ]; } else if (3 == strlen($color)) { #aaa list($r, $g, $b) = [ $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] ]; } else if (2 == strlen($color)) { #bb list($r, $g, $b) = [ $color[0] . $color[1], $color[0] . $color[1], $color[0] . $color[1] ]; } else if (1 == strlen($color)) { #c list($r, $g, $b) = [ $color . $color, $color . $color, $color . $color ]; } else { return []; } return [ 'r' => hexdec($r), 'g' => hexdec($g), 'b' => hexdec($b), ]; }
php
protected function hex2rgb($hexcolor) { preg_match("/^#{0,1}([0-9a-f]{1,6})$/i", $hexcolor, $match); if (!isset($match[1])) { return []; } $color = $match[1]; #91d04d if (6 == strlen($color)) { list($r, $g, $b) = [ $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] ]; } else if (3 == strlen($color)) { #aaa list($r, $g, $b) = [ $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] ]; } else if (2 == strlen($color)) { #bb list($r, $g, $b) = [ $color[0] . $color[1], $color[0] . $color[1], $color[0] . $color[1] ]; } else if (1 == strlen($color)) { #c list($r, $g, $b) = [ $color . $color, $color . $color, $color . $color ]; } else { return []; } return [ 'r' => hexdec($r), 'g' => hexdec($g), 'b' => hexdec($b), ]; }
[ "protected", "function", "hex2rgb", "(", "$", "hexcolor", ")", "{", "preg_match", "(", "\"/^#{0,1}([0-9a-f]{1,6})$/i\"", ",", "$", "hexcolor", ",", "$", "match", ")", ";", "if", "(", "!", "isset", "(", "$", "match", "[", "1", "]", ")", ")", "{", "return", "[", "]", ";", "}", "$", "color", "=", "$", "match", "[", "1", "]", ";", "#91d04d", "if", "(", "6", "==", "strlen", "(", "$", "color", ")", ")", "{", "list", "(", "$", "r", ",", "$", "g", ",", "$", "b", ")", "=", "[", "$", "color", "[", "0", "]", ".", "$", "color", "[", "1", "]", ",", "$", "color", "[", "2", "]", ".", "$", "color", "[", "3", "]", ",", "$", "color", "[", "4", "]", ".", "$", "color", "[", "5", "]", "]", ";", "}", "else", "if", "(", "3", "==", "strlen", "(", "$", "color", ")", ")", "{", "#aaa", "list", "(", "$", "r", ",", "$", "g", ",", "$", "b", ")", "=", "[", "$", "color", "[", "0", "]", ".", "$", "color", "[", "0", "]", ",", "$", "color", "[", "1", "]", ".", "$", "color", "[", "1", "]", ",", "$", "color", "[", "2", "]", ".", "$", "color", "[", "2", "]", "]", ";", "}", "else", "if", "(", "2", "==", "strlen", "(", "$", "color", ")", ")", "{", "#bb", "list", "(", "$", "r", ",", "$", "g", ",", "$", "b", ")", "=", "[", "$", "color", "[", "0", "]", ".", "$", "color", "[", "1", "]", ",", "$", "color", "[", "0", "]", ".", "$", "color", "[", "1", "]", ",", "$", "color", "[", "0", "]", ".", "$", "color", "[", "1", "]", "]", ";", "}", "else", "if", "(", "1", "==", "strlen", "(", "$", "color", ")", ")", "{", "#c", "list", "(", "$", "r", ",", "$", "g", ",", "$", "b", ")", "=", "[", "$", "color", ".", "$", "color", ",", "$", "color", ".", "$", "color", ",", "$", "color", ".", "$", "color", "]", ";", "}", "else", "{", "return", "[", "]", ";", "}", "return", "[", "'r'", "=>", "hexdec", "(", "$", "r", ")", ",", "'g'", "=>", "hexdec", "(", "$", "g", ")", ",", "'b'", "=>", "hexdec", "(", "$", "b", ")", ",", "]", ";", "}" ]
Return RGB array from hex color. @param string $hexcolor @return array $rgb
[ "Return", "RGB", "array", "from", "hex", "color", "." ]
aaa38a7e796c79386a3261c599de02082029c280
https://github.com/GetOlympus/olympus-social-field/blob/aaa38a7e796c79386a3261c599de02082029c280/src/Social/Social.php#L348-L395
train
nativgames-old/pegase
src/Pegase/Core/Path/Service/Path.php
Path.get_html_path
public function get_html_path($resource_path) { //pointe vers /web/$path // étape 1: mettre un chemin relatif, donc rajouter tous les "../" nécessaires $uri = $this->sm->get('pegase.core.request')->get_uri(); $uri = explode('?', $uri); $uri = $uri[0]; $nb = substr_count($uri, '/') - 1; $path = ""; for($i = 0; $i < $nb; $i++) { $path .= "../"; } $pos = strpos($resource_path, '/'); if($pos === 0) { $resource_path = substr($resource_path, 1); } $path .= $resource_path; // si c'est le dossier principal, et qu'on est dans le dossier principal // on doit corriger le chemin if($path == '') $path = './'; return $path; }
php
public function get_html_path($resource_path) { //pointe vers /web/$path // étape 1: mettre un chemin relatif, donc rajouter tous les "../" nécessaires $uri = $this->sm->get('pegase.core.request')->get_uri(); $uri = explode('?', $uri); $uri = $uri[0]; $nb = substr_count($uri, '/') - 1; $path = ""; for($i = 0; $i < $nb; $i++) { $path .= "../"; } $pos = strpos($resource_path, '/'); if($pos === 0) { $resource_path = substr($resource_path, 1); } $path .= $resource_path; // si c'est le dossier principal, et qu'on est dans le dossier principal // on doit corriger le chemin if($path == '') $path = './'; return $path; }
[ "public", "function", "get_html_path", "(", "$", "resource_path", ")", "{", "//pointe vers /web/$path", "// étape 1: mettre un chemin relatif, donc rajouter tous les \"../\" nécessaires ", "$", "uri", "=", "$", "this", "->", "sm", "->", "get", "(", "'pegase.core.request'", ")", "->", "get_uri", "(", ")", ";", "$", "uri", "=", "explode", "(", "'?'", ",", "$", "uri", ")", ";", "$", "uri", "=", "$", "uri", "[", "0", "]", ";", "$", "nb", "=", "substr_count", "(", "$", "uri", ",", "'/'", ")", "-", "1", ";", "$", "path", "=", "\"\"", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "nb", ";", "$", "i", "++", ")", "{", "$", "path", ".=", "\"../\"", ";", "}", "$", "pos", "=", "strpos", "(", "$", "resource_path", ",", "'/'", ")", ";", "if", "(", "$", "pos", "===", "0", ")", "{", "$", "resource_path", "=", "substr", "(", "$", "resource_path", ",", "1", ")", ";", "}", "$", "path", ".=", "$", "resource_path", ";", "// si c'est le dossier principal, et qu'on est dans le dossier principal", "// on doit corriger le chemin", "if", "(", "$", "path", "==", "''", ")", "$", "path", "=", "'./'", ";", "return", "$", "path", ";", "}" ]
relatif, pour les liens dans le html
[ "relatif", "pour", "les", "liens", "dans", "le", "html" ]
9a00e09a26f391c988aadecd7640c72316eaa521
https://github.com/nativgames-old/pegase/blob/9a00e09a26f391c988aadecd7640c72316eaa521/src/Pegase/Core/Path/Service/Path.php#L28-L58
train
Dhii/stringable-helper-base
src/StringableSplitCapableTrait.php
StringableSplitCapableTrait._stringableSplit
protected function _stringableSplit($subject, $separator) { $subject = $this->_normalizeString($subject); $separator = $this->_normalizeString($separator); return explode($separator, $subject); }
php
protected function _stringableSplit($subject, $separator) { $subject = $this->_normalizeString($subject); $separator = $this->_normalizeString($separator); return explode($separator, $subject); }
[ "protected", "function", "_stringableSplit", "(", "$", "subject", ",", "$", "separator", ")", "{", "$", "subject", "=", "$", "this", "->", "_normalizeString", "(", "$", "subject", ")", ";", "$", "separator", "=", "$", "this", "->", "_normalizeString", "(", "$", "separator", ")", ";", "return", "explode", "(", "$", "separator", ",", "$", "subject", ")", ";", "}" ]
Splits a stringable into pieces using a separator. @since [*next-version*] @param string|Stringable $subject The string to split. @param string|Stringable $separator The separator to split by. @throws InvalidArgumentException If the subject or the separator are invalid. @return array|stdClass|Traversable The list of pieces.
[ "Splits", "a", "stringable", "into", "pieces", "using", "a", "separator", "." ]
904254409800710665135a751659b59d140a2b40
https://github.com/Dhii/stringable-helper-base/blob/904254409800710665135a751659b59d140a2b40/src/StringableSplitCapableTrait.php#L29-L35
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.get_mime_type
public static function get_mime_type($filename) { if (extension_loaded('fileinfo')) { try { $finfo = new \finfo(FILEINFO_MIME_TYPE); return $finfo->file($filename); } catch (\Exception $e) { // Try next option... } } if (function_exists('mime_content_type')) { try { return mime_content_type($filename); } catch (\Exception $e) { // Try next option... } } $mime = \pdyn\filesystem\Mimetype::ext2mime(static::get_ext($filename)); // Strip out encoding, if present. if (mb_strpos($mime, ';') !== false) { $mime = explode(';', $mime); $mime = $mime[0]; } return $mime; }
php
public static function get_mime_type($filename) { if (extension_loaded('fileinfo')) { try { $finfo = new \finfo(FILEINFO_MIME_TYPE); return $finfo->file($filename); } catch (\Exception $e) { // Try next option... } } if (function_exists('mime_content_type')) { try { return mime_content_type($filename); } catch (\Exception $e) { // Try next option... } } $mime = \pdyn\filesystem\Mimetype::ext2mime(static::get_ext($filename)); // Strip out encoding, if present. if (mb_strpos($mime, ';') !== false) { $mime = explode(';', $mime); $mime = $mime[0]; } return $mime; }
[ "public", "static", "function", "get_mime_type", "(", "$", "filename", ")", "{", "if", "(", "extension_loaded", "(", "'fileinfo'", ")", ")", "{", "try", "{", "$", "finfo", "=", "new", "\\", "finfo", "(", "FILEINFO_MIME_TYPE", ")", ";", "return", "$", "finfo", "->", "file", "(", "$", "filename", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Try next option...", "}", "}", "if", "(", "function_exists", "(", "'mime_content_type'", ")", ")", "{", "try", "{", "return", "mime_content_type", "(", "$", "filename", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Try next option...", "}", "}", "$", "mime", "=", "\\", "pdyn", "\\", "filesystem", "\\", "Mimetype", "::", "ext2mime", "(", "static", "::", "get_ext", "(", "$", "filename", ")", ")", ";", "// Strip out encoding, if present.", "if", "(", "mb_strpos", "(", "$", "mime", ",", "';'", ")", "!==", "false", ")", "{", "$", "mime", "=", "explode", "(", "';'", ",", "$", "mime", ")", ";", "$", "mime", "=", "$", "mime", "[", "0", "]", ";", "}", "return", "$", "mime", ";", "}" ]
Determine the mime-type of a file. @param string $filename The full, absolute path to a file. @return string The mime type.
[ "Determine", "the", "mime", "-", "type", "of", "a", "file", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L35-L61
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.normalize_filename
public static function normalize_filename($input) { if (empty($input)) { return false; } $pathinfo = pathinfo($input); // Normalize extension. $ext = mb_strtolower($pathinfo['extension']); if ($ext === 'jpeg') { $ext = 'jpg'; } // Rebuild filename. $filename = $pathinfo['filename'].'.'.$ext; // Sanitize. $filename = static::sanitize_filename($filename); return $filename; }
php
public static function normalize_filename($input) { if (empty($input)) { return false; } $pathinfo = pathinfo($input); // Normalize extension. $ext = mb_strtolower($pathinfo['extension']); if ($ext === 'jpeg') { $ext = 'jpg'; } // Rebuild filename. $filename = $pathinfo['filename'].'.'.$ext; // Sanitize. $filename = static::sanitize_filename($filename); return $filename; }
[ "public", "static", "function", "normalize_filename", "(", "$", "input", ")", "{", "if", "(", "empty", "(", "$", "input", ")", ")", "{", "return", "false", ";", "}", "$", "pathinfo", "=", "pathinfo", "(", "$", "input", ")", ";", "// Normalize extension.", "$", "ext", "=", "mb_strtolower", "(", "$", "pathinfo", "[", "'extension'", "]", ")", ";", "if", "(", "$", "ext", "===", "'jpeg'", ")", "{", "$", "ext", "=", "'jpg'", ";", "}", "// Rebuild filename.", "$", "filename", "=", "$", "pathinfo", "[", "'filename'", "]", ".", "'.'", ".", "$", "ext", ";", "// Sanitize.", "$", "filename", "=", "static", "::", "sanitize_filename", "(", "$", "filename", ")", ";", "return", "$", "filename", ";", "}" ]
This helps us create normalized filenames. As the point of this function is to alter the input, the result should not be used to refer to the original, but instead used as a normalized name for storing new files. @param string $input The input filename. @return string Normalized filename.
[ "This", "helps", "us", "create", "normalized", "filenames", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L72-L92
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.sanitize_filename
public static function sanitize_filename($i, $allow_subdirs = false, $allowabsolute = false) { $i = trim($i); $replacements = ['../', './']; if ($allow_subdirs === false) { $replacements[] = '/'; } if ($allowabsolute !== true && $i{0} === '/') { $i = substr($i, 1); } return str_replace($replacements, '', $i); }
php
public static function sanitize_filename($i, $allow_subdirs = false, $allowabsolute = false) { $i = trim($i); $replacements = ['../', './']; if ($allow_subdirs === false) { $replacements[] = '/'; } if ($allowabsolute !== true && $i{0} === '/') { $i = substr($i, 1); } return str_replace($replacements, '', $i); }
[ "public", "static", "function", "sanitize_filename", "(", "$", "i", ",", "$", "allow_subdirs", "=", "false", ",", "$", "allowabsolute", "=", "false", ")", "{", "$", "i", "=", "trim", "(", "$", "i", ")", ";", "$", "replacements", "=", "[", "'../'", ",", "'./'", "]", ";", "if", "(", "$", "allow_subdirs", "===", "false", ")", "{", "$", "replacements", "[", "]", "=", "'/'", ";", "}", "if", "(", "$", "allowabsolute", "!==", "true", "&&", "$", "i", "{", "0", "}", "===", "'/'", ")", "{", "$", "i", "=", "substr", "(", "$", "i", ",", "1", ")", ";", "}", "return", "str_replace", "(", "$", "replacements", ",", "''", ",", "$", "i", ")", ";", "}" ]
Sanitize a filename. Specifically, this removes directory traversal via ./ and ../ @param string $i The input value. @param boolean $allow_subdirs Whether to allow forward directory traversal (i.e. subdirectories). @return string The sanitized string.
[ "Sanitize", "a", "filename", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L103-L113
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.create_directory_structure
public static function create_directory_structure($folders, $base_dir) { if (!empty($folders) && is_array($folders)) { foreach ($folders as $name => $subfolders) { if (!file_exists($base_dir.$name.'/')) { mkdir($base_dir.$name.'/'); } touch($base_dir.$name.'/index.html'); if (!empty($subfolders) && is_array($subfolders)) { static::create_directory_structure($subfolders, $base_dir.$name.'/'); } } } }
php
public static function create_directory_structure($folders, $base_dir) { if (!empty($folders) && is_array($folders)) { foreach ($folders as $name => $subfolders) { if (!file_exists($base_dir.$name.'/')) { mkdir($base_dir.$name.'/'); } touch($base_dir.$name.'/index.html'); if (!empty($subfolders) && is_array($subfolders)) { static::create_directory_structure($subfolders, $base_dir.$name.'/'); } } } }
[ "public", "static", "function", "create_directory_structure", "(", "$", "folders", ",", "$", "base_dir", ")", "{", "if", "(", "!", "empty", "(", "$", "folders", ")", "&&", "is_array", "(", "$", "folders", ")", ")", "{", "foreach", "(", "$", "folders", "as", "$", "name", "=>", "$", "subfolders", ")", "{", "if", "(", "!", "file_exists", "(", "$", "base_dir", ".", "$", "name", ".", "'/'", ")", ")", "{", "mkdir", "(", "$", "base_dir", ".", "$", "name", ".", "'/'", ")", ";", "}", "touch", "(", "$", "base_dir", ".", "$", "name", ".", "'/index.html'", ")", ";", "if", "(", "!", "empty", "(", "$", "subfolders", ")", "&&", "is_array", "(", "$", "subfolders", ")", ")", "{", "static", "::", "create_directory_structure", "(", "$", "subfolders", ",", "$", "base_dir", ".", "$", "name", ".", "'/'", ")", ";", "}", "}", "}", "}" ]
Create a complete directory structure in a given path. @param array $folders An array representing the structure to be created. Keys are folder names, values are arrays of subfolders (with keys being names and values being subfolders, etc) @param string $base_dir The directory to create the structure in. Must include trailing slash.
[ "Create", "a", "complete", "directory", "structure", "in", "a", "given", "path", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L122-L134
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.rrmdir
public static function rrmdir($path) { if (is_file($path)) { return unlink($path); } elseif (is_dir($path)) { $dir_members = scandir($path); foreach ($dir_members as $member) { if ($member !== '.' && $member !== '..') { static::rrmdir($path.'/'.$member); } } return @rmdir($path); } }
php
public static function rrmdir($path) { if (is_file($path)) { return unlink($path); } elseif (is_dir($path)) { $dir_members = scandir($path); foreach ($dir_members as $member) { if ($member !== '.' && $member !== '..') { static::rrmdir($path.'/'.$member); } } return @rmdir($path); } }
[ "public", "static", "function", "rrmdir", "(", "$", "path", ")", "{", "if", "(", "is_file", "(", "$", "path", ")", ")", "{", "return", "unlink", "(", "$", "path", ")", ";", "}", "elseif", "(", "is_dir", "(", "$", "path", ")", ")", "{", "$", "dir_members", "=", "scandir", "(", "$", "path", ")", ";", "foreach", "(", "$", "dir_members", "as", "$", "member", ")", "{", "if", "(", "$", "member", "!==", "'.'", "&&", "$", "member", "!==", "'..'", ")", "{", "static", "::", "rrmdir", "(", "$", "path", ".", "'/'", ".", "$", "member", ")", ";", "}", "}", "return", "@", "rmdir", "(", "$", "path", ")", ";", "}", "}" ]
Delete a folder and all subfolders. @param string $path The absolute path to the folder to delete. @return bool Success/Failure.
[ "Delete", "a", "folder", "and", "all", "subfolders", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L142-L154
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.unzip
public static function unzip($file, $destination) { if (!file_exists($file)) { return false; } if (!file_exists($destination)) { mkdir($destination); } if (class_exists('ZipArchive')) { $result = static::unzip_using_ziparchive($file, $destination); if ($result === true) { return true; } } else { throw new \Exception('No zip support available', 500); } }
php
public static function unzip($file, $destination) { if (!file_exists($file)) { return false; } if (!file_exists($destination)) { mkdir($destination); } if (class_exists('ZipArchive')) { $result = static::unzip_using_ziparchive($file, $destination); if ($result === true) { return true; } } else { throw new \Exception('No zip support available', 500); } }
[ "public", "static", "function", "unzip", "(", "$", "file", ",", "$", "destination", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "file_exists", "(", "$", "destination", ")", ")", "{", "mkdir", "(", "$", "destination", ")", ";", "}", "if", "(", "class_exists", "(", "'ZipArchive'", ")", ")", "{", "$", "result", "=", "static", "::", "unzip_using_ziparchive", "(", "$", "file", ",", "$", "destination", ")", ";", "if", "(", "$", "result", "===", "true", ")", "{", "return", "true", ";", "}", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "'No zip support available'", ",", "500", ")", ";", "}", "}" ]
Unzip a zip file into a directory. @param string $file The absolute path to a zip file. @param string $destination The absolute path to the directory to unzip to file into. @return bool Success/Failure.
[ "Unzip", "a", "zip", "file", "into", "a", "directory", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L163-L180
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.unzip_using_ziparchive
public static function unzip_using_ziparchive($file, $destination) { $za = new \ZipArchive; $zares = $za->open($file); if ($zares === true) { $za->extractTo($destination); $za->close(); return true; } else { return false; } }
php
public static function unzip_using_ziparchive($file, $destination) { $za = new \ZipArchive; $zares = $za->open($file); if ($zares === true) { $za->extractTo($destination); $za->close(); return true; } else { return false; } }
[ "public", "static", "function", "unzip_using_ziparchive", "(", "$", "file", ",", "$", "destination", ")", "{", "$", "za", "=", "new", "\\", "ZipArchive", ";", "$", "zares", "=", "$", "za", "->", "open", "(", "$", "file", ")", ";", "if", "(", "$", "zares", "===", "true", ")", "{", "$", "za", "->", "extractTo", "(", "$", "destination", ")", ";", "$", "za", "->", "close", "(", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Unzip a file into a directory using the ZipArchive class. @param string $file The absolute path to a zip file. @param string $destination The absolute path to the directory to unzip to file into. @return bool Success/Failure.
[ "Unzip", "a", "file", "into", "a", "directory", "using", "the", "ZipArchive", "class", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L189-L199
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.get_file_type_from_mime
public static function get_file_type_from_mime($mime) { $validtypes = ['application', 'audio', 'image', 'message', 'multipart', 'text', 'video']; if (mb_stripos($mime, '/') === false) { // Malformed mime type. return false; } $iparts = explode('/', $mime); if (count($iparts) !== 2) { // Malformed mime type. return false; } return (in_array($iparts[0], $validtypes, true)) ? $iparts[0] : false; }
php
public static function get_file_type_from_mime($mime) { $validtypes = ['application', 'audio', 'image', 'message', 'multipart', 'text', 'video']; if (mb_stripos($mime, '/') === false) { // Malformed mime type. return false; } $iparts = explode('/', $mime); if (count($iparts) !== 2) { // Malformed mime type. return false; } return (in_array($iparts[0], $validtypes, true)) ? $iparts[0] : false; }
[ "public", "static", "function", "get_file_type_from_mime", "(", "$", "mime", ")", "{", "$", "validtypes", "=", "[", "'application'", ",", "'audio'", ",", "'image'", ",", "'message'", ",", "'multipart'", ",", "'text'", ",", "'video'", "]", ";", "if", "(", "mb_stripos", "(", "$", "mime", ",", "'/'", ")", "===", "false", ")", "{", "// Malformed mime type.", "return", "false", ";", "}", "$", "iparts", "=", "explode", "(", "'/'", ",", "$", "mime", ")", ";", "if", "(", "count", "(", "$", "iparts", ")", "!==", "2", ")", "{", "// Malformed mime type.", "return", "false", ";", "}", "return", "(", "in_array", "(", "$", "iparts", "[", "0", "]", ",", "$", "validtypes", ",", "true", ")", ")", "?", "$", "iparts", "[", "0", "]", ":", "false", ";", "}" ]
Get the general file type from a mime type. This returns the beginning part (before the slash) of a mime type, giving a more general category of the file. @param string $mime The mime type. @return string The general file type.
[ "Get", "the", "general", "file", "type", "from", "a", "mime", "type", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L209-L224
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.make_human_readable_filesize
public static function make_human_readable_filesize($bytes) { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); $num_units = count($units); $size = $bytes; foreach ($units as $i => $unit) { if ($size < 1024 || (($i + 1) === $num_units)) { return round($size, 2).$unit; } $size = $size / 1024; } return $size; }
php
public static function make_human_readable_filesize($bytes) { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); $num_units = count($units); $size = $bytes; foreach ($units as $i => $unit) { if ($size < 1024 || (($i + 1) === $num_units)) { return round($size, 2).$unit; } $size = $size / 1024; } return $size; }
[ "public", "static", "function", "make_human_readable_filesize", "(", "$", "bytes", ")", "{", "$", "units", "=", "array", "(", "'B'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", ")", ";", "$", "num_units", "=", "count", "(", "$", "units", ")", ";", "$", "size", "=", "$", "bytes", ";", "foreach", "(", "$", "units", "as", "$", "i", "=>", "$", "unit", ")", "{", "if", "(", "$", "size", "<", "1024", "||", "(", "(", "$", "i", "+", "1", ")", "===", "$", "num_units", ")", ")", "{", "return", "round", "(", "$", "size", ",", "2", ")", ".", "$", "unit", ";", "}", "$", "size", "=", "$", "size", "/", "1024", ";", "}", "return", "$", "size", ";", "}" ]
Convert bytes into a human-readable format. For example: $bytes = 1024 would return 1KB, $bytes = 1048576 would return 1MB, etc. @param int $bytes The number of bytes to convert. @return string The human readable representation of the bytes.
[ "Convert", "bytes", "into", "a", "human", "-", "readable", "format", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L257-L268
train
pdyn/filesystem
FilesystemUtils.php
FilesystemUtils.dirsize
public static function dirsize($dir, $createifmissing = false) { $dirsize = 0; if (!file_exists($dir)) { if ($createifmissing === true) { mkdir($dir); return 0; } throw new \Exception('Directory does not exist!', 400); } $dir_info = scandir($dir); if ($dir{(mb_strlen($dir) - 1)} !== '/') { $dir .= '/'; } clearstatcache(); foreach ($dir_info as $i => $member) { if ($member === '.' || $member === '..') { continue; } $abs_member = $dir.$member; if (is_file($abs_member)) { $dirsize += filesize($abs_member); } elseif (is_dir($abs_member)) { $dirsize += static::dirsize($abs_member.'/'); } } return $dirsize; }
php
public static function dirsize($dir, $createifmissing = false) { $dirsize = 0; if (!file_exists($dir)) { if ($createifmissing === true) { mkdir($dir); return 0; } throw new \Exception('Directory does not exist!', 400); } $dir_info = scandir($dir); if ($dir{(mb_strlen($dir) - 1)} !== '/') { $dir .= '/'; } clearstatcache(); foreach ($dir_info as $i => $member) { if ($member === '.' || $member === '..') { continue; } $abs_member = $dir.$member; if (is_file($abs_member)) { $dirsize += filesize($abs_member); } elseif (is_dir($abs_member)) { $dirsize += static::dirsize($abs_member.'/'); } } return $dirsize; }
[ "public", "static", "function", "dirsize", "(", "$", "dir", ",", "$", "createifmissing", "=", "false", ")", "{", "$", "dirsize", "=", "0", ";", "if", "(", "!", "file_exists", "(", "$", "dir", ")", ")", "{", "if", "(", "$", "createifmissing", "===", "true", ")", "{", "mkdir", "(", "$", "dir", ")", ";", "return", "0", ";", "}", "throw", "new", "\\", "Exception", "(", "'Directory does not exist!'", ",", "400", ")", ";", "}", "$", "dir_info", "=", "scandir", "(", "$", "dir", ")", ";", "if", "(", "$", "dir", "{", "(", "mb_strlen", "(", "$", "dir", ")", "-", "1", ")", "}", "!==", "'/'", ")", "{", "$", "dir", ".=", "'/'", ";", "}", "clearstatcache", "(", ")", ";", "foreach", "(", "$", "dir_info", "as", "$", "i", "=>", "$", "member", ")", "{", "if", "(", "$", "member", "===", "'.'", "||", "$", "member", "===", "'..'", ")", "{", "continue", ";", "}", "$", "abs_member", "=", "$", "dir", ".", "$", "member", ";", "if", "(", "is_file", "(", "$", "abs_member", ")", ")", "{", "$", "dirsize", "+=", "filesize", "(", "$", "abs_member", ")", ";", "}", "elseif", "(", "is_dir", "(", "$", "abs_member", ")", ")", "{", "$", "dirsize", "+=", "static", "::", "dirsize", "(", "$", "abs_member", ".", "'/'", ")", ";", "}", "}", "return", "$", "dirsize", ";", "}" ]
Get the disk usage of a given directory. @param string $dir The absolute path to the directory to get the disk usage of. @return int The disk usage of the directory in bytes.
[ "Get", "the", "disk", "usage", "of", "a", "given", "directory", "." ]
e2f780eac166aa60071e601d600133b860ace594
https://github.com/pdyn/filesystem/blob/e2f780eac166aa60071e601d600133b860ace594/FilesystemUtils.php#L276-L305
train
net-tools/core
src/Helpers/FileHelper.php
FileHelper.guessMimeType
static function guessMimeType($file, $def = 'application/octet-stream') { // extract file extension (after . symbol) $ext = substr(strrchr(strtolower($file), '.'), 1); switch ( $ext ) { case 'gif': case 'jpeg': case 'png': return "image/$ext"; case 'jpg': return 'image/jpeg'; case 'mp4': case 'mpeg': case 'avi': return "video/$ext"; case 'mp3': return 'audio/mpeg3'; case 'wav': return 'audio/wav'; case 'pdf': return 'application/pdf'; case 'htm': case 'html': return 'text/html'; case 'txt': return 'text/plain'; case 'eml': return 'message/rfc822'; case 'doc': return 'application/msword'; case 'docx': return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; case 'xls': return 'application/vnd.ms-excel'; case 'xlsx': return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; case 'ppt': case 'pps': return 'application/vnd.ms-powerpoint'; case 'pptx': case 'ppsx': return 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; case 'odt': return 'application/vnd.oasis.opendocument.text'; case 'ods': return 'application/vnd.oasis.opendocument.spreadsheet'; case 'odp': return 'application/vnd.oasis.opendocument.presentation'; case 'zip': return 'application/zip'; default : return $def; } }
php
static function guessMimeType($file, $def = 'application/octet-stream') { // extract file extension (after . symbol) $ext = substr(strrchr(strtolower($file), '.'), 1); switch ( $ext ) { case 'gif': case 'jpeg': case 'png': return "image/$ext"; case 'jpg': return 'image/jpeg'; case 'mp4': case 'mpeg': case 'avi': return "video/$ext"; case 'mp3': return 'audio/mpeg3'; case 'wav': return 'audio/wav'; case 'pdf': return 'application/pdf'; case 'htm': case 'html': return 'text/html'; case 'txt': return 'text/plain'; case 'eml': return 'message/rfc822'; case 'doc': return 'application/msword'; case 'docx': return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; case 'xls': return 'application/vnd.ms-excel'; case 'xlsx': return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; case 'ppt': case 'pps': return 'application/vnd.ms-powerpoint'; case 'pptx': case 'ppsx': return 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; case 'odt': return 'application/vnd.oasis.opendocument.text'; case 'ods': return 'application/vnd.oasis.opendocument.spreadsheet'; case 'odp': return 'application/vnd.oasis.opendocument.presentation'; case 'zip': return 'application/zip'; default : return $def; } }
[ "static", "function", "guessMimeType", "(", "$", "file", ",", "$", "def", "=", "'application/octet-stream'", ")", "{", "// extract file extension (after . symbol)", "$", "ext", "=", "substr", "(", "strrchr", "(", "strtolower", "(", "$", "file", ")", ",", "'.'", ")", ",", "1", ")", ";", "switch", "(", "$", "ext", ")", "{", "case", "'gif'", ":", "case", "'jpeg'", ":", "case", "'png'", ":", "return", "\"image/$ext\"", ";", "case", "'jpg'", ":", "return", "'image/jpeg'", ";", "case", "'mp4'", ":", "case", "'mpeg'", ":", "case", "'avi'", ":", "return", "\"video/$ext\"", ";", "case", "'mp3'", ":", "return", "'audio/mpeg3'", ";", "case", "'wav'", ":", "return", "'audio/wav'", ";", "case", "'pdf'", ":", "return", "'application/pdf'", ";", "case", "'htm'", ":", "case", "'html'", ":", "return", "'text/html'", ";", "case", "'txt'", ":", "return", "'text/plain'", ";", "case", "'eml'", ":", "return", "'message/rfc822'", ";", "case", "'doc'", ":", "return", "'application/msword'", ";", "case", "'docx'", ":", "return", "'application/vnd.openxmlformats-officedocument.wordprocessingml.document'", ";", "case", "'xls'", ":", "return", "'application/vnd.ms-excel'", ";", "case", "'xlsx'", ":", "return", "'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'", ";", "case", "'ppt'", ":", "case", "'pps'", ":", "return", "'application/vnd.ms-powerpoint'", ";", "case", "'pptx'", ":", "case", "'ppsx'", ":", "return", "'application/vnd.openxmlformats-officedocument.presentationml.presentation'", ";", "case", "'odt'", ":", "return", "'application/vnd.oasis.opendocument.text'", ";", "case", "'ods'", ":", "return", "'application/vnd.oasis.opendocument.spreadsheet'", ";", "case", "'odp'", ":", "return", "'application/vnd.oasis.opendocument.presentation'", ";", "case", "'zip'", ":", "return", "'application/zip'", ";", "default", ":", "return", "$", "def", ";", "}", "}" ]
Guess Mime type from file name @param string $file Filename to process @param string $def Default value for Mime type @return string The Mime type guessed from the filename
[ "Guess", "Mime", "type", "from", "file", "name" ]
51446641cee22c0cf53d2b409c76cc8bd1a187e7
https://github.com/net-tools/core/blob/51446641cee22c0cf53d2b409c76cc8bd1a187e7/src/Helpers/FileHelper.php#L89-L144
train
Rockbeat-Sky/yii
src/db/ActiveRecord.php
ActiveRecord.getConstants
public static function getConstants($name) { if (isset(self::$_const[$name])) { return self::$_const[$name]; } $self = new \ReflectionClass(new static()); $contants = $self->getConstants(); $prefix = strtoupper($name) . '_'; $prefixLength = strlen($prefix); $prefixOffset = $prefixLength - 1; self::$_const[$name] = []; foreach ($contants as $key => $value) { if (substr($key, 0, $prefixLength) === $prefix) { self::$_const[$name][$value] = ucwords(strtolower(Inflector::humanize(substr($key, $prefixLength)))); } } return self::$_const[$name]; }
php
public static function getConstants($name) { if (isset(self::$_const[$name])) { return self::$_const[$name]; } $self = new \ReflectionClass(new static()); $contants = $self->getConstants(); $prefix = strtoupper($name) . '_'; $prefixLength = strlen($prefix); $prefixOffset = $prefixLength - 1; self::$_const[$name] = []; foreach ($contants as $key => $value) { if (substr($key, 0, $prefixLength) === $prefix) { self::$_const[$name][$value] = ucwords(strtolower(Inflector::humanize(substr($key, $prefixLength)))); } } return self::$_const[$name]; }
[ "public", "static", "function", "getConstants", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "_const", "[", "$", "name", "]", ")", ")", "{", "return", "self", "::", "$", "_const", "[", "$", "name", "]", ";", "}", "$", "self", "=", "new", "\\", "ReflectionClass", "(", "new", "static", "(", ")", ")", ";", "$", "contants", "=", "$", "self", "->", "getConstants", "(", ")", ";", "$", "prefix", "=", "strtoupper", "(", "$", "name", ")", ".", "'_'", ";", "$", "prefixLength", "=", "strlen", "(", "$", "prefix", ")", ";", "$", "prefixOffset", "=", "$", "prefixLength", "-", "1", ";", "self", "::", "$", "_const", "[", "$", "name", "]", "=", "[", "]", ";", "foreach", "(", "$", "contants", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "substr", "(", "$", "key", ",", "0", ",", "$", "prefixLength", ")", "===", "$", "prefix", ")", "{", "self", "::", "$", "_const", "[", "$", "name", "]", "[", "$", "value", "]", "=", "ucwords", "(", "strtolower", "(", "Inflector", "::", "humanize", "(", "substr", "(", "$", "key", ",", "$", "prefixLength", ")", ")", ")", ")", ";", "}", "}", "return", "self", "::", "$", "_const", "[", "$", "name", "]", ";", "}" ]
get constants by name @param string $name @return array
[ "get", "constants", "by", "name" ]
80758d1519162d650ca2d41e00f46e760ee35b92
https://github.com/Rockbeat-Sky/yii/blob/80758d1519162d650ca2d41e00f46e760ee35b92/src/db/ActiveRecord.php#L72-L89
train
anime-db/catalog-bundle
src/Controller/FillController.php
FillController.fillerAction
public function fillerAction($plugin, Request $request) { /* @var $response Response */ $response = $this->getCacheTimeKeeper()->getResponse(); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } /* @var $chain ChainFiller */ $chain = $this->get('anime_db.plugin.filler'); /* @var $filler FillerInterface */ if (!($filler = $chain->getPlugin($plugin))) { throw $this->createNotFoundException('Plugin \''.$plugin.'\' is not found'); } /* @var $form Form */ $form = $this->createForm($filler->getForm()); $fill_form = null; $form->handleRequest($request); if ($form->isValid()) { $item = $filler->fill($form->getData()); if (!($item instanceof Item)) { $form->addError(new FormError('Can`t get content from the specified source')); } else { $fill_form = $this->createForm('entity_item', $item)->createView(); } } return $this->render('AnimeDbCatalogBundle:Fill:filler.html.twig', [ 'plugin' => $plugin, 'plugin_name' => $filler->getTitle(), 'form' => $form->createView(), 'fill_form' => $fill_form, ], $response); }
php
public function fillerAction($plugin, Request $request) { /* @var $response Response */ $response = $this->getCacheTimeKeeper()->getResponse(); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } /* @var $chain ChainFiller */ $chain = $this->get('anime_db.plugin.filler'); /* @var $filler FillerInterface */ if (!($filler = $chain->getPlugin($plugin))) { throw $this->createNotFoundException('Plugin \''.$plugin.'\' is not found'); } /* @var $form Form */ $form = $this->createForm($filler->getForm()); $fill_form = null; $form->handleRequest($request); if ($form->isValid()) { $item = $filler->fill($form->getData()); if (!($item instanceof Item)) { $form->addError(new FormError('Can`t get content from the specified source')); } else { $fill_form = $this->createForm('entity_item', $item)->createView(); } } return $this->render('AnimeDbCatalogBundle:Fill:filler.html.twig', [ 'plugin' => $plugin, 'plugin_name' => $filler->getTitle(), 'form' => $form->createView(), 'fill_form' => $fill_form, ], $response); }
[ "public", "function", "fillerAction", "(", "$", "plugin", ",", "Request", "$", "request", ")", "{", "/* @var $response Response */", "$", "response", "=", "$", "this", "->", "getCacheTimeKeeper", "(", ")", "->", "getResponse", "(", ")", ";", "// response was not modified for this request", "if", "(", "$", "response", "->", "isNotModified", "(", "$", "request", ")", ")", "{", "return", "$", "response", ";", "}", "/* @var $chain ChainFiller */", "$", "chain", "=", "$", "this", "->", "get", "(", "'anime_db.plugin.filler'", ")", ";", "/* @var $filler FillerInterface */", "if", "(", "!", "(", "$", "filler", "=", "$", "chain", "->", "getPlugin", "(", "$", "plugin", ")", ")", ")", "{", "throw", "$", "this", "->", "createNotFoundException", "(", "'Plugin \\''", ".", "$", "plugin", ".", "'\\' is not found'", ")", ";", "}", "/* @var $form Form */", "$", "form", "=", "$", "this", "->", "createForm", "(", "$", "filler", "->", "getForm", "(", ")", ")", ";", "$", "fill_form", "=", "null", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "$", "item", "=", "$", "filler", "->", "fill", "(", "$", "form", "->", "getData", "(", ")", ")", ";", "if", "(", "!", "(", "$", "item", "instanceof", "Item", ")", ")", "{", "$", "form", "->", "addError", "(", "new", "FormError", "(", "'Can`t get content from the specified source'", ")", ")", ";", "}", "else", "{", "$", "fill_form", "=", "$", "this", "->", "createForm", "(", "'entity_item'", ",", "$", "item", ")", "->", "createView", "(", ")", ";", "}", "}", "return", "$", "this", "->", "render", "(", "'AnimeDbCatalogBundle:Fill:filler.html.twig'", ",", "[", "'plugin'", "=>", "$", "plugin", ",", "'plugin_name'", "=>", "$", "filler", "->", "getTitle", "(", ")", ",", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "'fill_form'", "=>", "$", "fill_form", ",", "]", ",", "$", "response", ")", ";", "}" ]
Create new item from source fill. @param string $plugin @param Request $request @return Response
[ "Create", "new", "item", "from", "source", "fill", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/FillController.php#L42-L78
train
anime-db/catalog-bundle
src/Controller/FillController.php
FillController.searchFillerAction
public function searchFillerAction(Request $request) { /* @var $chain ChainFiller */ $chain = $this->get('anime_db.plugin.filler'); $response = $this->getResponseFromChain($chain); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } $entity = new SearchFiller($chain); /* @var $form Form */ $form = $this->createForm(new SearchFillerForm(), $entity)->handleRequest($request); if ($form->isValid()) { return $this->redirect($entity->getFiller()->getLinkForFill($entity->getUrl())); } return $this->render('AnimeDbCatalogBundle:Fill:search_filler.html.twig', [ 'form' => $form->createView(), ], $response); }
php
public function searchFillerAction(Request $request) { /* @var $chain ChainFiller */ $chain = $this->get('anime_db.plugin.filler'); $response = $this->getResponseFromChain($chain); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } $entity = new SearchFiller($chain); /* @var $form Form */ $form = $this->createForm(new SearchFillerForm(), $entity)->handleRequest($request); if ($form->isValid()) { return $this->redirect($entity->getFiller()->getLinkForFill($entity->getUrl())); } return $this->render('AnimeDbCatalogBundle:Fill:search_filler.html.twig', [ 'form' => $form->createView(), ], $response); }
[ "public", "function", "searchFillerAction", "(", "Request", "$", "request", ")", "{", "/* @var $chain ChainFiller */", "$", "chain", "=", "$", "this", "->", "get", "(", "'anime_db.plugin.filler'", ")", ";", "$", "response", "=", "$", "this", "->", "getResponseFromChain", "(", "$", "chain", ")", ";", "// response was not modified for this request", "if", "(", "$", "response", "->", "isNotModified", "(", "$", "request", ")", ")", "{", "return", "$", "response", ";", "}", "$", "entity", "=", "new", "SearchFiller", "(", "$", "chain", ")", ";", "/* @var $form Form */", "$", "form", "=", "$", "this", "->", "createForm", "(", "new", "SearchFillerForm", "(", ")", ",", "$", "entity", ")", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "return", "$", "this", "->", "redirect", "(", "$", "entity", "->", "getFiller", "(", ")", "->", "getLinkForFill", "(", "$", "entity", "->", "getUrl", "(", ")", ")", ")", ";", "}", "return", "$", "this", "->", "render", "(", "'AnimeDbCatalogBundle:Fill:search_filler.html.twig'", ",", "[", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "]", ",", "$", "response", ")", ";", "}" ]
Search filler by URL for fill item. @param Request $request @return Response
[ "Search", "filler", "by", "URL", "for", "fill", "item", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/FillController.php#L160-L181
train
anime-db/catalog-bundle
src/Controller/FillController.php
FillController.getResponseFromChain
protected function getResponseFromChain(Chain $chain) { if (!$chain->getPlugins()) { throw $this->createNotFoundException('No any plugins'); } $names = ''; /* @var $plugin PluginInterface */ foreach ($chain->getPlugins() as $plugin) { $names .= '|'.$plugin->getName(); } return $this ->getCacheTimeKeeper() ->getResponse() ->setEtag(md5($names)); }
php
protected function getResponseFromChain(Chain $chain) { if (!$chain->getPlugins()) { throw $this->createNotFoundException('No any plugins'); } $names = ''; /* @var $plugin PluginInterface */ foreach ($chain->getPlugins() as $plugin) { $names .= '|'.$plugin->getName(); } return $this ->getCacheTimeKeeper() ->getResponse() ->setEtag(md5($names)); }
[ "protected", "function", "getResponseFromChain", "(", "Chain", "$", "chain", ")", "{", "if", "(", "!", "$", "chain", "->", "getPlugins", "(", ")", ")", "{", "throw", "$", "this", "->", "createNotFoundException", "(", "'No any plugins'", ")", ";", "}", "$", "names", "=", "''", ";", "/* @var $plugin PluginInterface */", "foreach", "(", "$", "chain", "->", "getPlugins", "(", ")", "as", "$", "plugin", ")", "{", "$", "names", ".=", "'|'", ".", "$", "plugin", "->", "getName", "(", ")", ";", "}", "return", "$", "this", "->", "getCacheTimeKeeper", "(", ")", "->", "getResponse", "(", ")", "->", "setEtag", "(", "md5", "(", "$", "names", ")", ")", ";", "}" ]
Get response from plugins chain. @param Chain $chain @return Response
[ "Get", "response", "from", "plugins", "chain", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/FillController.php#L190-L206
train
zarathustra323/modlr-data
src/Zarathustra/ModlrData/Metadata/Cache/RedisCache.php
RedisCache.serialize
private function serialize(EntityMetadata $metadata) { switch ($this->serializer) { case self::SERIALIZER_PHP: return serialize($metadata); case self::SERIALIZER_IGBINARY: return igbinary_serialize($metadata); default: throw new RuntimeException('Unable to handle serialization of the metadata object'); } }
php
private function serialize(EntityMetadata $metadata) { switch ($this->serializer) { case self::SERIALIZER_PHP: return serialize($metadata); case self::SERIALIZER_IGBINARY: return igbinary_serialize($metadata); default: throw new RuntimeException('Unable to handle serialization of the metadata object'); } }
[ "private", "function", "serialize", "(", "EntityMetadata", "$", "metadata", ")", "{", "switch", "(", "$", "this", "->", "serializer", ")", "{", "case", "self", "::", "SERIALIZER_PHP", ":", "return", "serialize", "(", "$", "metadata", ")", ";", "case", "self", "::", "SERIALIZER_IGBINARY", ":", "return", "igbinary_serialize", "(", "$", "metadata", ")", ";", "default", ":", "throw", "new", "RuntimeException", "(", "'Unable to handle serialization of the metadata object'", ")", ";", "}", "}" ]
Serializes the metadata object based on the selected serializer. @param EntityMetadata $metadata @return string @throws RuntimeException
[ "Serializes", "the", "metadata", "object", "based", "on", "the", "selected", "serializer", "." ]
7c2c767216055f75abf8cf22e2200f11998ed24e
https://github.com/zarathustra323/modlr-data/blob/7c2c767216055f75abf8cf22e2200f11998ed24e/src/Zarathustra/ModlrData/Metadata/Cache/RedisCache.php#L115-L125
train
zarathustra323/modlr-data
src/Zarathustra/ModlrData/Metadata/Cache/RedisCache.php
RedisCache.unserialize
private function unserialize($value) { switch ($this->serializer) { case self::SERIALIZER_PHP: return unserialize($value); case self::SERIALIZER_IGBINARY: return igbinary_unserialize($value); default: throw new RuntimeException('Unable to handle unserialization of the metadata object'); } }
php
private function unserialize($value) { switch ($this->serializer) { case self::SERIALIZER_PHP: return unserialize($value); case self::SERIALIZER_IGBINARY: return igbinary_unserialize($value); default: throw new RuntimeException('Unable to handle unserialization of the metadata object'); } }
[ "private", "function", "unserialize", "(", "$", "value", ")", "{", "switch", "(", "$", "this", "->", "serializer", ")", "{", "case", "self", "::", "SERIALIZER_PHP", ":", "return", "unserialize", "(", "$", "value", ")", ";", "case", "self", "::", "SERIALIZER_IGBINARY", ":", "return", "igbinary_unserialize", "(", "$", "value", ")", ";", "default", ":", "throw", "new", "RuntimeException", "(", "'Unable to handle unserialization of the metadata object'", ")", ";", "}", "}" ]
Unserializes the metadata object based on the selected serializer. @param string $value @return string @throws RuntimeException
[ "Unserializes", "the", "metadata", "object", "based", "on", "the", "selected", "serializer", "." ]
7c2c767216055f75abf8cf22e2200f11998ed24e
https://github.com/zarathustra323/modlr-data/blob/7c2c767216055f75abf8cf22e2200f11998ed24e/src/Zarathustra/ModlrData/Metadata/Cache/RedisCache.php#L134-L144
train
jbouzekri/SculpinTagCloudBundle
Component/Strategy/PercentSizeStrategy.php
PercentSizeStrategy.setPercentSize
private function setPercentSize(\Jb\Bundle\TagCloudBundle\Model\Tag $tag, $max) { $percent = ($tag->getCounter() / $max) * 100; $weight = floor($percent / 10); if ($percent >= 5) { $weight++; } if ($percent >= 80 && $percent < 100) { $weight = 8; } elseif ($percent == 100) { $weight = 9; } $tag->setWeight($weight); }
php
private function setPercentSize(\Jb\Bundle\TagCloudBundle\Model\Tag $tag, $max) { $percent = ($tag->getCounter() / $max) * 100; $weight = floor($percent / 10); if ($percent >= 5) { $weight++; } if ($percent >= 80 && $percent < 100) { $weight = 8; } elseif ($percent == 100) { $weight = 9; } $tag->setWeight($weight); }
[ "private", "function", "setPercentSize", "(", "\\", "Jb", "\\", "Bundle", "\\", "TagCloudBundle", "\\", "Model", "\\", "Tag", "$", "tag", ",", "$", "max", ")", "{", "$", "percent", "=", "(", "$", "tag", "->", "getCounter", "(", ")", "/", "$", "max", ")", "*", "100", ";", "$", "weight", "=", "floor", "(", "$", "percent", "/", "10", ")", ";", "if", "(", "$", "percent", ">=", "5", ")", "{", "$", "weight", "++", ";", "}", "if", "(", "$", "percent", ">=", "80", "&&", "$", "percent", "<", "100", ")", "{", "$", "weight", "=", "8", ";", "}", "elseif", "(", "$", "percent", "==", "100", ")", "{", "$", "weight", "=", "9", ";", "}", "$", "tag", "->", "setWeight", "(", "$", "weight", ")", ";", "}" ]
Set a size @param \Jb\Bundle\TagCloudBundle\Model\Tag $tag @param type $max
[ "Set", "a", "size" ]
936cf34ce60cb8fb4774931b1841fc775a3e9208
https://github.com/jbouzekri/SculpinTagCloudBundle/blob/936cf34ce60cb8fb4774931b1841fc775a3e9208/Component/Strategy/PercentSizeStrategy.php#L29-L46
train
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/Utility/LifecycleEventManager.php
LifecycleEventManager.documentNotFound
public function documentNotFound($proxy, Identifier $identifier) { $eventArgs = new DocumentNotFoundEventArgs($proxy, $this->dm, $identifier); $this->evm->dispatchEvent(Event::documentNotFound, $eventArgs); return $eventArgs->isExceptionDisabled(); }
php
public function documentNotFound($proxy, Identifier $identifier) { $eventArgs = new DocumentNotFoundEventArgs($proxy, $this->dm, $identifier); $this->evm->dispatchEvent(Event::documentNotFound, $eventArgs); return $eventArgs->isExceptionDisabled(); }
[ "public", "function", "documentNotFound", "(", "$", "proxy", ",", "Identifier", "$", "identifier", ")", "{", "$", "eventArgs", "=", "new", "DocumentNotFoundEventArgs", "(", "$", "proxy", ",", "$", "this", "->", "dm", ",", "$", "identifier", ")", ";", "$", "this", "->", "evm", "->", "dispatchEvent", "(", "Event", "::", "documentNotFound", ",", "$", "eventArgs", ")", ";", "return", "$", "eventArgs", "->", "isExceptionDisabled", "(", ")", ";", "}" ]
Return whether the exceptionDisabled flag was set. @param object $proxy @param Identifier $identifier @return bool
[ "Return", "whether", "the", "exceptionDisabled", "flag", "was", "set", "." ]
119d355e2c5cbaef1f867970349b4432f5704fcd
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Utility/LifecycleEventManager.php#L130-L136
train
LPLabs/wordpress-muplugin-installer
src/Installer/WordPressMustUsePluginInstaller.php
WordPressMustUsePluginInstaller.installEntryFiles
protected function installEntryFiles(PackageInterface $package) { foreach ($this->getEntryFileLocations($package) as $src => $dest) { $copied = $this->filesystem->copyFile($src, $dest); $this->io->notice( sprintf( ' <fg=default>Copying <fg=magenta>%1$s</> to <fg=magenta>%2$s</> -</> %3$s', $src, $dest, $copied ? '<fg=green>OK</>' : '<fg=red>FAILED</>' ) ); if (! $copied) { throw new RuntimeException(sprintf('Cannot copy %s to %s', $src, $dest)); } } }
php
protected function installEntryFiles(PackageInterface $package) { foreach ($this->getEntryFileLocations($package) as $src => $dest) { $copied = $this->filesystem->copyFile($src, $dest); $this->io->notice( sprintf( ' <fg=default>Copying <fg=magenta>%1$s</> to <fg=magenta>%2$s</> -</> %3$s', $src, $dest, $copied ? '<fg=green>OK</>' : '<fg=red>FAILED</>' ) ); if (! $copied) { throw new RuntimeException(sprintf('Cannot copy %s to %s', $src, $dest)); } } }
[ "protected", "function", "installEntryFiles", "(", "PackageInterface", "$", "package", ")", "{", "foreach", "(", "$", "this", "->", "getEntryFileLocations", "(", "$", "package", ")", "as", "$", "src", "=>", "$", "dest", ")", "{", "$", "copied", "=", "$", "this", "->", "filesystem", "->", "copyFile", "(", "$", "src", ",", "$", "dest", ")", ";", "$", "this", "->", "io", "->", "notice", "(", "sprintf", "(", "' <fg=default>Copying <fg=magenta>%1$s</> to <fg=magenta>%2$s</> -</> %3$s'", ",", "$", "src", ",", "$", "dest", ",", "$", "copied", "?", "'<fg=green>OK</>'", ":", "'<fg=red>FAILED</>'", ")", ")", ";", "if", "(", "!", "$", "copied", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'Cannot copy %s to %s'", ",", "$", "src", ",", "$", "dest", ")", ")", ";", "}", "}", "}" ]
Install each must-use plugin entry file @param PackageInterface $package @return void
[ "Install", "each", "must", "-", "use", "plugin", "entry", "file" ]
c216c1ecd60a2cf47839f804d7591b7db2fd0db1
https://github.com/LPLabs/wordpress-muplugin-installer/blob/c216c1ecd60a2cf47839f804d7591b7db2fd0db1/src/Installer/WordPressMustUsePluginInstaller.php#L85-L103
train
LPLabs/wordpress-muplugin-installer
src/Installer/WordPressMustUsePluginInstaller.php
WordPressMustUsePluginInstaller.uninstallEntryFiles
protected function uninstallEntryFiles(PackageInterface $package) { foreach ($this->getEntryFileLocations($package) as $dest) { $unlinked = $this->filesystem->unlinkFile($dest); $this->io->notice( sprintf( ' <fg=default>Removing <fg=magenta>%1$s</> -</> %2$s', $dest, $unlinked ? '<fg=green>OK</>' : '<fg=red>FAILED</>' ) ); if (! $unlinked) { throw new RuntimeException('Cannot unlink ' . $dest); } } }
php
protected function uninstallEntryFiles(PackageInterface $package) { foreach ($this->getEntryFileLocations($package) as $dest) { $unlinked = $this->filesystem->unlinkFile($dest); $this->io->notice( sprintf( ' <fg=default>Removing <fg=magenta>%1$s</> -</> %2$s', $dest, $unlinked ? '<fg=green>OK</>' : '<fg=red>FAILED</>' ) ); if (! $unlinked) { throw new RuntimeException('Cannot unlink ' . $dest); } } }
[ "protected", "function", "uninstallEntryFiles", "(", "PackageInterface", "$", "package", ")", "{", "foreach", "(", "$", "this", "->", "getEntryFileLocations", "(", "$", "package", ")", "as", "$", "dest", ")", "{", "$", "unlinked", "=", "$", "this", "->", "filesystem", "->", "unlinkFile", "(", "$", "dest", ")", ";", "$", "this", "->", "io", "->", "notice", "(", "sprintf", "(", "' <fg=default>Removing <fg=magenta>%1$s</> -</> %2$s'", ",", "$", "dest", ",", "$", "unlinked", "?", "'<fg=green>OK</>'", ":", "'<fg=red>FAILED</>'", ")", ")", ";", "if", "(", "!", "$", "unlinked", ")", "{", "throw", "new", "RuntimeException", "(", "'Cannot unlink '", ".", "$", "dest", ")", ";", "}", "}", "}" ]
Uninstall each must-use plugin entry file @param PackageInterface $package @return void
[ "Uninstall", "each", "must", "-", "use", "plugin", "entry", "file" ]
c216c1ecd60a2cf47839f804d7591b7db2fd0db1
https://github.com/LPLabs/wordpress-muplugin-installer/blob/c216c1ecd60a2cf47839f804d7591b7db2fd0db1/src/Installer/WordPressMustUsePluginInstaller.php#L111-L128
train
LPLabs/wordpress-muplugin-installer
src/Installer/WordPressMustUsePluginInstaller.php
WordPressMustUsePluginInstaller.getPackageExtra
protected function getPackageExtra(PackageInterface $package, $key, $default = null) { $extra = $package->getExtra(); return array_key_exists($key, $extra) ? $extra[ $key ] : $default; }
php
protected function getPackageExtra(PackageInterface $package, $key, $default = null) { $extra = $package->getExtra(); return array_key_exists($key, $extra) ? $extra[ $key ] : $default; }
[ "protected", "function", "getPackageExtra", "(", "PackageInterface", "$", "package", ",", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "extra", "=", "$", "package", "->", "getExtra", "(", ")", ";", "return", "array_key_exists", "(", "$", "key", ",", "$", "extra", ")", "?", "$", "extra", "[", "$", "key", "]", ":", "$", "default", ";", "}" ]
Get an item from the package extra array @param PackageInterface $package @param string $key @param mixed $default @return mixed
[ "Get", "an", "item", "from", "the", "package", "extra", "array" ]
c216c1ecd60a2cf47839f804d7591b7db2fd0db1
https://github.com/LPLabs/wordpress-muplugin-installer/blob/c216c1ecd60a2cf47839f804d7591b7db2fd0db1/src/Installer/WordPressMustUsePluginInstaller.php#L138-L143
train
LPLabs/wordpress-muplugin-installer
src/Installer/WordPressMustUsePluginInstaller.php
WordPressMustUsePluginInstaller.getPackageEntryPoints
protected function getPackageEntryPoints(PackageInterface $package) { $dir = $this->composer->getInstallationManager()->getInstallPath($package); $entry = $this->getPackageExtra($package, 'wordpress-muplugin-entry'); $entryPoints = $entry ? (is_array($entry) ? $entry : [ $entry ]) : []; if (empty($entryPoints)) { $phpFiles = glob(rtrim($dir, '/') . '/*.php', GLOB_NOSORT); foreach ($phpFiles as $file) { $entryPoints[] = basename($file); } } foreach ($entryPoints as $index => $file) { $entryPoints[ $index ] = $dir . $file; } return array_filter($entryPoints, [ $this, 'looksLikePlugin' ]); }
php
protected function getPackageEntryPoints(PackageInterface $package) { $dir = $this->composer->getInstallationManager()->getInstallPath($package); $entry = $this->getPackageExtra($package, 'wordpress-muplugin-entry'); $entryPoints = $entry ? (is_array($entry) ? $entry : [ $entry ]) : []; if (empty($entryPoints)) { $phpFiles = glob(rtrim($dir, '/') . '/*.php', GLOB_NOSORT); foreach ($phpFiles as $file) { $entryPoints[] = basename($file); } } foreach ($entryPoints as $index => $file) { $entryPoints[ $index ] = $dir . $file; } return array_filter($entryPoints, [ $this, 'looksLikePlugin' ]); }
[ "protected", "function", "getPackageEntryPoints", "(", "PackageInterface", "$", "package", ")", "{", "$", "dir", "=", "$", "this", "->", "composer", "->", "getInstallationManager", "(", ")", "->", "getInstallPath", "(", "$", "package", ")", ";", "$", "entry", "=", "$", "this", "->", "getPackageExtra", "(", "$", "package", ",", "'wordpress-muplugin-entry'", ")", ";", "$", "entryPoints", "=", "$", "entry", "?", "(", "is_array", "(", "$", "entry", ")", "?", "$", "entry", ":", "[", "$", "entry", "]", ")", ":", "[", "]", ";", "if", "(", "empty", "(", "$", "entryPoints", ")", ")", "{", "$", "phpFiles", "=", "glob", "(", "rtrim", "(", "$", "dir", ",", "'/'", ")", ".", "'/*.php'", ",", "GLOB_NOSORT", ")", ";", "foreach", "(", "$", "phpFiles", "as", "$", "file", ")", "{", "$", "entryPoints", "[", "]", "=", "basename", "(", "$", "file", ")", ";", "}", "}", "foreach", "(", "$", "entryPoints", "as", "$", "index", "=>", "$", "file", ")", "{", "$", "entryPoints", "[", "$", "index", "]", "=", "$", "dir", ".", "$", "file", ";", "}", "return", "array_filter", "(", "$", "entryPoints", ",", "[", "$", "this", ",", "'looksLikePlugin'", "]", ")", ";", "}" ]
Get the package entry points @param PackageInterface $package @return array
[ "Get", "the", "package", "entry", "points" ]
c216c1ecd60a2cf47839f804d7591b7db2fd0db1
https://github.com/LPLabs/wordpress-muplugin-installer/blob/c216c1ecd60a2cf47839f804d7591b7db2fd0db1/src/Installer/WordPressMustUsePluginInstaller.php#L172-L191
train
LPLabs/wordpress-muplugin-installer
src/Installer/WordPressMustUsePluginInstaller.php
WordPressMustUsePluginInstaller.looksLikePlugin
protected function looksLikePlugin($file) { if (! $file || ! $this->filesystem->isFile($file) || ! $this->filesystem->isReadable($file)) { return false; } $chunk = str_replace("\r", "\n", file_get_contents($file, false, null, 0, 8192)); return preg_match('/^[ \t\/*#@]*Plugin Name:(.*)$/mi', $chunk, $match) && $match[1]; }
php
protected function looksLikePlugin($file) { if (! $file || ! $this->filesystem->isFile($file) || ! $this->filesystem->isReadable($file)) { return false; } $chunk = str_replace("\r", "\n", file_get_contents($file, false, null, 0, 8192)); return preg_match('/^[ \t\/*#@]*Plugin Name:(.*)$/mi', $chunk, $match) && $match[1]; }
[ "protected", "function", "looksLikePlugin", "(", "$", "file", ")", "{", "if", "(", "!", "$", "file", "||", "!", "$", "this", "->", "filesystem", "->", "isFile", "(", "$", "file", ")", "||", "!", "$", "this", "->", "filesystem", "->", "isReadable", "(", "$", "file", ")", ")", "{", "return", "false", ";", "}", "$", "chunk", "=", "str_replace", "(", "\"\\r\"", ",", "\"\\n\"", ",", "file_get_contents", "(", "$", "file", ",", "false", ",", "null", ",", "0", ",", "8192", ")", ")", ";", "return", "preg_match", "(", "'/^[ \\t\\/*#@]*Plugin Name:(.*)$/mi'", ",", "$", "chunk", ",", "$", "match", ")", "&&", "$", "match", "[", "1", "]", ";", "}" ]
Does the file look like a WordPress plugin? @param string $file @return bool
[ "Does", "the", "file", "look", "like", "a", "WordPress", "plugin?" ]
c216c1ecd60a2cf47839f804d7591b7db2fd0db1
https://github.com/LPLabs/wordpress-muplugin-installer/blob/c216c1ecd60a2cf47839f804d7591b7db2fd0db1/src/Installer/WordPressMustUsePluginInstaller.php#L199-L208
train
agentmedia/phine-core
src/Core/Logic/Module/BackendModule.php
BackendModule.RenderBlock
public function RenderBlock($block) { $templateFile = $this->BuiltInTemplateFile(); $blockFile = Path::AddExtension($templateFile, $block, true); $blockFileExt = Path::AddExtension($blockFile, 'phtml'); if (!File::Exists($blockFileExt)) { return ''; } ob_start(); require $blockFileExt; return ob_get_clean(); }
php
public function RenderBlock($block) { $templateFile = $this->BuiltInTemplateFile(); $blockFile = Path::AddExtension($templateFile, $block, true); $blockFileExt = Path::AddExtension($blockFile, 'phtml'); if (!File::Exists($blockFileExt)) { return ''; } ob_start(); require $blockFileExt; return ob_get_clean(); }
[ "public", "function", "RenderBlock", "(", "$", "block", ")", "{", "$", "templateFile", "=", "$", "this", "->", "BuiltInTemplateFile", "(", ")", ";", "$", "blockFile", "=", "Path", "::", "AddExtension", "(", "$", "templateFile", ",", "$", "block", ",", "true", ")", ";", "$", "blockFileExt", "=", "Path", "::", "AddExtension", "(", "$", "blockFile", ",", "'phtml'", ")", ";", "if", "(", "!", "File", "::", "Exists", "(", "$", "blockFileExt", ")", ")", "{", "return", "''", ";", "}", "ob_start", "(", ")", ";", "require", "$", "blockFileExt", ";", "return", "ob_get_clean", "(", ")", ";", "}" ]
Renders a block by name @param string $block @return string
[ "Renders", "a", "block", "by", "name" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Module/BackendModule.php#L39-L51
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/model/Object.php
Object.setFromArray
public function setFromArray(array $fields) { foreach($fields as $key => $value) { $this->fields[$key] = $value; unset($key); unset($value); } }
php
public function setFromArray(array $fields) { foreach($fields as $key => $value) { $this->fields[$key] = $value; unset($key); unset($value); } }
[ "public", "function", "setFromArray", "(", "array", "$", "fields", ")", "{", "foreach", "(", "$", "fields", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "fields", "[", "$", "key", "]", "=", "$", "value", ";", "unset", "(", "$", "key", ")", ";", "unset", "(", "$", "value", ")", ";", "}", "}" ]
Sets the fields on the object. @param array $fields array of fields returned from SQL select result set @return void
[ "Sets", "the", "fields", "on", "the", "object", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/model/Object.php#L57-L65
train
devlabmtl/haven-cms
Lib/Handler/CommentFormHandler.php
CommentFormHandler.createAddCommentForm
public function createAddCommentForm(Content $content, $user = null) { $comment = new Comment(); $comment->setContent($content); if ($user !== 'anon.') { $comment->setEmail($user->getEmail()); } $form = $this->form_factory->create(new CommentType(), $comment); return $form; }
php
public function createAddCommentForm(Content $content, $user = null) { $comment = new Comment(); $comment->setContent($content); if ($user !== 'anon.') { $comment->setEmail($user->getEmail()); } $form = $this->form_factory->create(new CommentType(), $comment); return $form; }
[ "public", "function", "createAddCommentForm", "(", "Content", "$", "content", ",", "$", "user", "=", "null", ")", "{", "$", "comment", "=", "new", "Comment", "(", ")", ";", "$", "comment", "->", "setContent", "(", "$", "content", ")", ";", "if", "(", "$", "user", "!==", "'anon.'", ")", "{", "$", "comment", "->", "setEmail", "(", "$", "user", "->", "getEmail", "(", ")", ")", ";", "}", "$", "form", "=", "$", "this", "->", "form_factory", "->", "create", "(", "new", "CommentType", "(", ")", ",", "$", "comment", ")", ";", "return", "$", "form", ";", "}" ]
Creates a form to comment on a content. @param Haven\CmsBundle\Entity\Content $content @return Haven\CmsBundle\Form\CommentType $form
[ "Creates", "a", "form", "to", "comment", "on", "a", "content", "." ]
c20761a07c201a966dbda1f3eae33617f80e1ece
https://github.com/devlabmtl/haven-cms/blob/c20761a07c201a966dbda1f3eae33617f80e1ece/Lib/Handler/CommentFormHandler.php#L63-L72
train
romm/configuration_object
Classes/Service/Items/Parents/ParentsTrait.php
ParentsTrait.attachParents
public function attachParents(array $parents) { $this->_parents = []; foreach ($parents as $parent) { $this->attachParent($parent, false); } }
php
public function attachParents(array $parents) { $this->_parents = []; foreach ($parents as $parent) { $this->attachParent($parent, false); } }
[ "public", "function", "attachParents", "(", "array", "$", "parents", ")", "{", "$", "this", "->", "_parents", "=", "[", "]", ";", "foreach", "(", "$", "parents", "as", "$", "parent", ")", "{", "$", "this", "->", "attachParent", "(", "$", "parent", ",", "false", ")", ";", "}", "}" ]
Loops on each given parent and attach it to this object. The order matters: the first item will be added as a direct parent whereas the last one will be the remote parent. Note that this function will also reset @param object[] $parents
[ "Loops", "on", "each", "given", "parent", "and", "attach", "it", "to", "this", "object", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Service/Items/Parents/ParentsTrait.php#L94-L101
train
romm/configuration_object
Classes/Service/Items/Parents/ParentsTrait.php
ParentsTrait.hasParent
public function hasParent($parentClassName) { $found = false; $this->alongParents(function ($parent) use ($parentClassName, &$found) { if ($parent instanceof $parentClassName) { $found = true; return false; } return true; }); return $found; }
php
public function hasParent($parentClassName) { $found = false; $this->alongParents(function ($parent) use ($parentClassName, &$found) { if ($parent instanceof $parentClassName) { $found = true; return false; } return true; }); return $found; }
[ "public", "function", "hasParent", "(", "$", "parentClassName", ")", "{", "$", "found", "=", "false", ";", "$", "this", "->", "alongParents", "(", "function", "(", "$", "parent", ")", "use", "(", "$", "parentClassName", ",", "&", "$", "found", ")", "{", "if", "(", "$", "parent", "instanceof", "$", "parentClassName", ")", "{", "$", "found", "=", "true", ";", "return", "false", ";", "}", "return", "true", ";", "}", ")", ";", "return", "$", "found", ";", "}" ]
Returns true if the class has a given parent. @param string $parentClassName Name of the parent class. @return bool
[ "Returns", "true", "if", "the", "class", "has", "a", "given", "parent", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Service/Items/Parents/ParentsTrait.php#L123-L138
train
romm/configuration_object
Classes/Service/Items/Parents/ParentsTrait.php
ParentsTrait.withFirstParent
public function withFirstParent($parentClassName, callable $callback, callable $notFoundCallback = null) { $result = null; if ($this->hasParent($parentClassName)) { $parent = $this->getFirstParent($parentClassName); $result = call_user_func($callback, $parent); } elseif (null !== $notFoundCallback) { $result = call_user_func($notFoundCallback); } return $result; }
php
public function withFirstParent($parentClassName, callable $callback, callable $notFoundCallback = null) { $result = null; if ($this->hasParent($parentClassName)) { $parent = $this->getFirstParent($parentClassName); $result = call_user_func($callback, $parent); } elseif (null !== $notFoundCallback) { $result = call_user_func($notFoundCallback); } return $result; }
[ "public", "function", "withFirstParent", "(", "$", "parentClassName", ",", "callable", "$", "callback", ",", "callable", "$", "notFoundCallback", "=", "null", ")", "{", "$", "result", "=", "null", ";", "if", "(", "$", "this", "->", "hasParent", "(", "$", "parentClassName", ")", ")", "{", "$", "parent", "=", "$", "this", "->", "getFirstParent", "(", "$", "parentClassName", ")", ";", "$", "result", "=", "call_user_func", "(", "$", "callback", ",", "$", "parent", ")", ";", "}", "elseif", "(", "null", "!==", "$", "notFoundCallback", ")", "{", "$", "result", "=", "call_user_func", "(", "$", "notFoundCallback", ")", ";", "}", "return", "$", "result", ";", "}" ]
Will fetch the first parent which matches the given class name. If a parent is found, then `$callback` is called, and its returned value is returned by this function. If no parent is found, then `$notFoundCallBack` is called if it was defined. @param string $parentClassName Name of the class name of the wanted parent. @param callable $callback A closure which will be called if the parent is found. @param callable $notFoundCallback A closure which is called if the parent is not found. @return mixed|null
[ "Will", "fetch", "the", "first", "parent", "which", "matches", "the", "given", "class", "name", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Service/Items/Parents/ParentsTrait.php#L154-L166
train