repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._renderPragma | protected function _renderPragma($matches) {
$pragma = $matches[0];
$pragma_name = $matches['pragma_name'];
$options_string = $matches['options_string'];
if (!in_array($pragma_name, $this->_pragmasImplemented)) {
if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
} else {
return '';
}
}
$options = array();
foreach (explode(' ', trim($options_string)) as $o) {
if ($p = trim($o)) {
$p = explode('=', $p);
$options[$p[0]] = $p[1];
}
}
if (empty($options)) {
$this->_localPragmas[$pragma_name] = true;
} else {
$this->_localPragmas[$pragma_name] = $options;
}
return '';
} | php | protected function _renderPragma($matches) {
$pragma = $matches[0];
$pragma_name = $matches['pragma_name'];
$options_string = $matches['options_string'];
if (!in_array($pragma_name, $this->_pragmasImplemented)) {
if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
} else {
return '';
}
}
$options = array();
foreach (explode(' ', trim($options_string)) as $o) {
if ($p = trim($o)) {
$p = explode('=', $p);
$options[$p[0]] = $p[1];
}
}
if (empty($options)) {
$this->_localPragmas[$pragma_name] = true;
} else {
$this->_localPragmas[$pragma_name] = $options;
}
return '';
} | A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
@access protected
@param mixed $matches
@return void
@throws MustacheException unknown pragma | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L437-L465 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._hasPragma | protected function _hasPragma($pragma_name) {
if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
return true;
} else {
return false;
}
} | php | protected function _hasPragma($pragma_name) {
if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
return true;
} else {
return false;
}
} | Check whether this Mustache has a specific pragma.
@access protected
@param string $pragma_name
@return bool | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L474-L480 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._getPragmaOptions | protected function _getPragmaOptions($pragma_name) {
if (!$this->_hasPragma($pragma_name)) {
if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
}
}
return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
} | php | protected function _getPragmaOptions($pragma_name) {
if (!$this->_hasPragma($pragma_name)) {
if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
}
}
return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
} | Return pragma options, if any.
@access protected
@param string $pragma_name
@return mixed
@throws MustacheException Unknown pragma | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L490-L498 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._prepareTagRegEx | protected function _prepareTagRegEx($otag, $ctag, $first = false) {
return sprintf(
'/(?P<leading>(?:%s\\r?\\n)[ \\t]*)?%s(?P<type>[%s]?)(?P<tag_name>.+?)(?:\\2|})?%s(?P<trailing>\\s*(?:\\r?\\n|\\Z))?/s',
($first ? '\\A|' : ''),
preg_quote($otag, '/'),
self::TAG_TYPES,
preg_quote($ctag, '/')
);
} | php | protected function _prepareTagRegEx($otag, $ctag, $first = false) {
return sprintf(
'/(?P<leading>(?:%s\\r?\\n)[ \\t]*)?%s(?P<type>[%s]?)(?P<tag_name>.+?)(?:\\2|})?%s(?P<trailing>\\s*(?:\\r?\\n|\\Z))?/s',
($first ? '\\A|' : ''),
preg_quote($otag, '/'),
self::TAG_TYPES,
preg_quote($ctag, '/')
);
} | Prepare a tag RegEx for the given opening/closing tags.
@access protected
@param string $otag
@param string $ctag
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L521-L529 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._renderTags | protected function _renderTags($template) {
if (strpos($template, $this->_otag) === false) {
return $template;
}
$first = true;
$this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true);
$html = '';
$matches = array();
while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
$tag = $matches[0][0];
$offset = $matches[0][1];
$modifier = $matches['type'][0];
$tag_name = trim($matches['tag_name'][0]);
if (isset($matches['leading']) && $matches['leading'][1] > -1) {
$leading = $matches['leading'][0];
} else {
$leading = null;
}
if (isset($matches['trailing']) && $matches['trailing'][1] > -1) {
$trailing = $matches['trailing'][0];
} else {
$trailing = null;
}
$html .= substr($template, 0, $offset);
$next_offset = $offset + strlen($tag);
if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
$next_offset++;
}
$template = substr($template, $next_offset);
$html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing);
if ($first == true) {
$first = false;
$this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
}
}
return $html . $template;
} | php | protected function _renderTags($template) {
if (strpos($template, $this->_otag) === false) {
return $template;
}
$first = true;
$this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true);
$html = '';
$matches = array();
while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
$tag = $matches[0][0];
$offset = $matches[0][1];
$modifier = $matches['type'][0];
$tag_name = trim($matches['tag_name'][0]);
if (isset($matches['leading']) && $matches['leading'][1] > -1) {
$leading = $matches['leading'][0];
} else {
$leading = null;
}
if (isset($matches['trailing']) && $matches['trailing'][1] > -1) {
$trailing = $matches['trailing'][0];
} else {
$trailing = null;
}
$html .= substr($template, 0, $offset);
$next_offset = $offset + strlen($tag);
if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
$next_offset++;
}
$template = substr($template, $next_offset);
$html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing);
if ($first == true) {
$first = false;
$this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
}
}
return $html . $template;
} | Loop through and render individual Mustache tags.
@access protected
@param string $template
@return void | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L538-L583 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._renderTag | protected function _renderTag($modifier, $tag_name, $leading, $trailing) {
switch ($modifier) {
case '=':
return $this->_changeDelimiter($tag_name, $leading, $trailing);
break;
case '!':
return $this->_renderComment($tag_name, $leading, $trailing);
break;
case '>':
case '<':
return $this->_renderPartial($tag_name, $leading, $trailing);
break;
case '{':
// strip the trailing } ...
if ($tag_name[(strlen($tag_name) - 1)] == '}') {
$tag_name = substr($tag_name, 0, -1);
}
case '&':
if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
return $this->_renderEscaped($tag_name, $leading, $trailing);
} else {
return $this->_renderUnescaped($tag_name, $leading, $trailing);
}
break;
case '#':
case '^':
case "*":
return $leading . $this->server->siteUrl($tag_name) . $trailing;
break;
case '/':
// remove any leftover section tags
return $leading . $trailing;
break;
default:
if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing);
} else {
return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing);
}
break;
}
} | php | protected function _renderTag($modifier, $tag_name, $leading, $trailing) {
switch ($modifier) {
case '=':
return $this->_changeDelimiter($tag_name, $leading, $trailing);
break;
case '!':
return $this->_renderComment($tag_name, $leading, $trailing);
break;
case '>':
case '<':
return $this->_renderPartial($tag_name, $leading, $trailing);
break;
case '{':
// strip the trailing } ...
if ($tag_name[(strlen($tag_name) - 1)] == '}') {
$tag_name = substr($tag_name, 0, -1);
}
case '&':
if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
return $this->_renderEscaped($tag_name, $leading, $trailing);
} else {
return $this->_renderUnescaped($tag_name, $leading, $trailing);
}
break;
case '#':
case '^':
case "*":
return $leading . $this->server->siteUrl($tag_name) . $trailing;
break;
case '/':
// remove any leftover section tags
return $leading . $trailing;
break;
default:
if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing);
} else {
return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing);
}
break;
}
} | Render the named tag, given the specified modifier.
Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
`{` or `&` (don't escape output), or none (render escaped output).
@access protected
@param string $modifier
@param string $tag_name
@param string $leading Whitespace
@param string $trailing Whitespace
@throws MustacheException Unmatched section tag encountered.
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L599-L640 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._stringHasR | protected function _stringHasR($str) {
foreach (func_get_args() as $arg) {
if (strpos($arg, "\r") !== false) {
return true;
}
}
return false;
} | php | protected function _stringHasR($str) {
foreach (func_get_args() as $arg) {
if (strpos($arg, "\r") !== false) {
return true;
}
}
return false;
} | Returns true if any of its args contains the "\r" character.
@access protected
@param string $str
@return boolean | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L649-L656 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._renderEscaped | protected function _renderEscaped($tag_name, $leading, $trailing) {
$value = $this->_renderUnescaped($tag_name, '', '');
if (isset($this->_escape)) {
$rendered = call_user_func($this->_escape, $value);
} else {
$rendered = htmlentities($value, ENT_COMPAT, $this->_charset);
}
return $leading . $rendered . $trailing;
} | php | protected function _renderEscaped($tag_name, $leading, $trailing) {
$value = $this->_renderUnescaped($tag_name, '', '');
if (isset($this->_escape)) {
$rendered = call_user_func($this->_escape, $value);
} else {
$rendered = htmlentities($value, ENT_COMPAT, $this->_charset);
}
return $leading . $rendered . $trailing;
} | Escape and return the requested tag.
@access protected
@param string $tag_name
@param string $leading Whitespace
@param string $trailing Whitespace
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L667-L676 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._renderComment | protected function _renderComment($tag_name, $leading, $trailing) {
if ($leading !== null && $trailing !== null) {
if (strpos($leading, "\n") === false) {
return '';
}
return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
}
return $leading . $trailing;
} | php | protected function _renderComment($tag_name, $leading, $trailing) {
if ($leading !== null && $trailing !== null) {
if (strpos($leading, "\n") === false) {
return '';
}
return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
}
return $leading . $trailing;
} | Render a comment (i.e. return an empty string).
@access protected
@param string $tag_name
@param string $leading Whitespace
@param string $trailing Whitespace
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L687-L695 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._renderUnescaped | protected function _renderUnescaped($tag_name, $leading, $trailing) {
$val = $this->_getVariable($tag_name);
if ($this->_varIsCallable($val)) {
$val = $this->_renderTemplate(call_user_func($val));
}
return $leading . $val . $trailing;
} | php | protected function _renderUnescaped($tag_name, $leading, $trailing) {
$val = $this->_getVariable($tag_name);
if ($this->_varIsCallable($val)) {
$val = $this->_renderTemplate(call_user_func($val));
}
return $leading . $val . $trailing;
} | Return the requested tag unescaped.
@access protected
@param string $tag_name
@param string $leading Whitespace
@param string $trailing Whitespace
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L706-L714 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._renderPartial | protected function _renderPartial($tag_name, $leading, $trailing) {
$partial = $this->_getPartial($tag_name);
if ($leading !== null && $trailing !== null) {
$whitespace = trim($leading, "\r\n");
$partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial);
}
$view = clone($this);
if ($leading !== null && $trailing !== null) {
return $leading . $view->render($partial);
} else {
return $leading . $view->render($partial) . $trailing;
}
} | php | protected function _renderPartial($tag_name, $leading, $trailing) {
$partial = $this->_getPartial($tag_name);
if ($leading !== null && $trailing !== null) {
$whitespace = trim($leading, "\r\n");
$partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial);
}
$view = clone($this);
if ($leading !== null && $trailing !== null) {
return $leading . $view->render($partial);
} else {
return $leading . $view->render($partial) . $trailing;
}
} | Render the requested partial.
@access protected
@param string $tag_name
@param string $leading Whitespace
@param string $trailing Whitespace
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L725-L739 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._changeDelimiter | protected function _changeDelimiter($tag_name, $leading, $trailing) {
list($otag, $ctag) = explode(' ', $tag_name);
$this->_otag = $otag;
$this->_ctag = $ctag;
$this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
if ($leading !== null && $trailing !== null) {
if (strpos($leading, "\n") === false) {
return '';
}
return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
}
return $leading . $trailing;
} | php | protected function _changeDelimiter($tag_name, $leading, $trailing) {
list($otag, $ctag) = explode(' ', $tag_name);
$this->_otag = $otag;
$this->_ctag = $ctag;
$this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
if ($leading !== null && $trailing !== null) {
if (strpos($leading, "\n") === false) {
return '';
}
return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
}
return $leading . $trailing;
} | Change the Mustache tag delimiter. This method also replaces this object's current
tag RegEx with one using the new delimiters.
@access protected
@param string $tag_name
@param string $leading Whitespace
@param string $trailing Whitespace
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L751-L765 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._pushContext | protected function _pushContext(&$local_context) {
$new = array();
$new[] =& $local_context;
foreach (array_keys($this->_context) as $key) {
$new[] =& $this->_context[$key];
}
$this->_context = $new;
} | php | protected function _pushContext(&$local_context) {
$new = array();
$new[] =& $local_context;
foreach (array_keys($this->_context) as $key) {
$new[] =& $this->_context[$key];
}
$this->_context = $new;
} | Push a local context onto the stack.
@access protected
@param array &$local_context
@return void | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L774-L781 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._popContext | protected function _popContext() {
$new = array();
$keys = array_keys($this->_context);
array_shift($keys);
foreach ($keys as $key) {
$new[] =& $this->_context[$key];
}
$this->_context = $new;
} | php | protected function _popContext() {
$new = array();
$keys = array_keys($this->_context);
array_shift($keys);
foreach ($keys as $key) {
$new[] =& $this->_context[$key];
}
$this->_context = $new;
} | Remove the latest context from the stack.
@access protected
@return void | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L789-L798 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._getVariable | protected function _getVariable($tag_name) {
if ($tag_name === '.') {
return $this->_context[0];
} else if (strpos($tag_name, '.') !== false) {
$chunks = explode('.', $tag_name);
$first = array_shift($chunks);
$ret = $this->_findVariableInContext($first, $this->_context);
foreach ($chunks as $next) {
// Slice off a chunk of context for dot notation traversal.
$c = array($ret);
$ret = $this->_findVariableInContext($next, $c);
}
return $ret;
} else {
return $this->_findVariableInContext($tag_name, $this->_context);
}
} | php | protected function _getVariable($tag_name) {
if ($tag_name === '.') {
return $this->_context[0];
} else if (strpos($tag_name, '.') !== false) {
$chunks = explode('.', $tag_name);
$first = array_shift($chunks);
$ret = $this->_findVariableInContext($first, $this->_context);
foreach ($chunks as $next) {
// Slice off a chunk of context for dot notation traversal.
$c = array($ret);
$ret = $this->_findVariableInContext($next, $c);
}
return $ret;
} else {
return $this->_findVariableInContext($tag_name, $this->_context);
}
} | Get a variable from the context array.
If the view is an array, returns the value with array key $tag_name.
If the view is an object, this will check for a public member variable
named $tag_name. If none is available, this method will execute and return
any class method named $tag_name. Failing all of the above, this method will
return an empty string.
@access protected
@param string $tag_name
@throws MustacheException Unknown variable name.
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L814-L831 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._findVariableInContext | protected function _findVariableInContext($tag_name, $context) {
foreach ($context as $view) {
if (is_object($view)) {
if (method_exists($view, $tag_name)) {
return $view->$tag_name();
} else if (isset($view->$tag_name)) {
return $view->$tag_name;
}
} else if (is_array($view) && array_key_exists($tag_name, $view)) {
return $view[$tag_name];
}
}
if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
} else {
return '';
}
} | php | protected function _findVariableInContext($tag_name, $context) {
foreach ($context as $view) {
if (is_object($view)) {
if (method_exists($view, $tag_name)) {
return $view->$tag_name();
} else if (isset($view->$tag_name)) {
return $view->$tag_name;
}
} else if (is_array($view) && array_key_exists($tag_name, $view)) {
return $view[$tag_name];
}
}
if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
} else {
return '';
}
} | Get a variable from the context array. Internal helper used by getVariable() to abstract
variable traversal for dot notation.
@access protected
@param string $tag_name
@param array $context
@throws MustacheException Unknown variable name.
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L843-L861 |
Etenil/assegai | src/assegai/modules/mustache/MustacheEngine.php | MustacheEngine._getPartial | protected function _getPartial($tag_name) {
if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) {
return $this->_partials[$tag_name];
} else {
$partial_file = $this->server->getRelAppPath('views/' . $tag_name . '.tpl');
if(file_exists($partial_file)) {
return file_get_contents($partial_file);
}
}
if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
} else {
return '';
}
} | php | protected function _getPartial($tag_name) {
if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) {
return $this->_partials[$tag_name];
} else {
$partial_file = $this->server->getRelAppPath('views/' . $tag_name . '.tpl');
if(file_exists($partial_file)) {
return file_get_contents($partial_file);
}
}
if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
} else {
return '';
}
} | Retrieve the partial corresponding to the requested tag name.
Silently fails (i.e. returns '') when the requested partial is not found.
@access protected
@param string $tag_name
@throws MustacheException Unknown partial name.
@return string | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L873-L888 |
Boolive/Core | request/Request.php | Request.activate | static function activate()
{
if (get_magic_quotes_gpc()){
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)){
foreach ($val as $k => $v){
unset($process[$key][$k]);
if (is_array($v)){
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
}else{
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
// Нормализация массива $_FILES в соответствии с именованием полей формы
if (isset($_FILES)){
// Перегруппировка элементов массива $_FILES
$rec_to_array = function ($array, $name) use (&$rec_to_array){
$result = [];
foreach ($array as $key => $value){
if (is_array($value)){
$result[$key] = $rec_to_array($value, $name);
}else{
$result[$key][$name] = $value;
}
}
return $result;
};
$files = [];
foreach ($_FILES as $field => $data){
$files[$field] = [];
foreach ($data as $name => $value){
if (is_array($value)){
$files[$field] = F::arrayMergeRecursive($files[$field], $rec_to_array($value, $name));
}else{
$files[$field][$name] = $value;
}
}
}
}else{
$files = [];
}
self::$source = array(
'REQUEST' => [],
'FILES' => $files,
'COOKIE' => isset($_COOKIE)? $_COOKIE : [],
'RAW' => file_get_contents("php://input"), // Неформатированные данные
'SERVER' => $_SERVER
);
if (isset($_SERVER['REQUEST_URI'])){
$_SERVER['REQUEST_URI'] = preg_replace('#\?{1}#u', '&', $_SERVER['REQUEST_URI'], 1);
// $request_uri = preg_replace('#^'.preg_quote(DIR_WEB).'#u', '/', $_SERVER['REQUEST_URI'], 1);
parse_str('path='.$_SERVER['REQUEST_URI'], self::$source['REQUEST']);
self::$source['SERVER']['argv'] = self::$source['REQUEST'];
self::$source['SERVER']['argc'] = sizeof(self::$source['REQUEST']);
}
// Элементы пути URI
if (isset(self::$source['REQUEST']['path']) && (self::$source['REQUEST']['path'] = rtrim(self::$source['REQUEST']['path'],'/ '))){
self::$source['PATH'] = explode('/', trim(self::$source['REQUEST']['path'],' /'));
}else{
self::$source['PATH'] = [];
}
if (isset($_POST)){
self::$source['REQUEST'] = array_replace_recursive(self::$source['REQUEST'], $_POST);
}
// Аргументы из консоли (режим CLI)
if (php_sapi_name() == 'cli' && isset($_SERVER['argv'])){
self::$source['REQUEST']['method'] = 'CLI';
self::$source['SERVER']['argv'] = $_SERVER['argv'];
self::$source['SERVER']['argc'] = $_SERVER['argc'];
}
self::$source['ARG'] = self::$source['SERVER']['argv'];
// Метод запроса
if (isset(self::$source['SERVER']['REQUEST_METHOD']) && !isset(self::$source['REQUEST']['method'])){
self::$source['REQUEST']['method'] = self::$source['SERVER']['REQUEST_METHOD'];
}
} | php | static function activate()
{
if (get_magic_quotes_gpc()){
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)){
foreach ($val as $k => $v){
unset($process[$key][$k]);
if (is_array($v)){
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
}else{
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
// Нормализация массива $_FILES в соответствии с именованием полей формы
if (isset($_FILES)){
// Перегруппировка элементов массива $_FILES
$rec_to_array = function ($array, $name) use (&$rec_to_array){
$result = [];
foreach ($array as $key => $value){
if (is_array($value)){
$result[$key] = $rec_to_array($value, $name);
}else{
$result[$key][$name] = $value;
}
}
return $result;
};
$files = [];
foreach ($_FILES as $field => $data){
$files[$field] = [];
foreach ($data as $name => $value){
if (is_array($value)){
$files[$field] = F::arrayMergeRecursive($files[$field], $rec_to_array($value, $name));
}else{
$files[$field][$name] = $value;
}
}
}
}else{
$files = [];
}
self::$source = array(
'REQUEST' => [],
'FILES' => $files,
'COOKIE' => isset($_COOKIE)? $_COOKIE : [],
'RAW' => file_get_contents("php://input"), // Неформатированные данные
'SERVER' => $_SERVER
);
if (isset($_SERVER['REQUEST_URI'])){
$_SERVER['REQUEST_URI'] = preg_replace('#\?{1}#u', '&', $_SERVER['REQUEST_URI'], 1);
// $request_uri = preg_replace('#^'.preg_quote(DIR_WEB).'#u', '/', $_SERVER['REQUEST_URI'], 1);
parse_str('path='.$_SERVER['REQUEST_URI'], self::$source['REQUEST']);
self::$source['SERVER']['argv'] = self::$source['REQUEST'];
self::$source['SERVER']['argc'] = sizeof(self::$source['REQUEST']);
}
// Элементы пути URI
if (isset(self::$source['REQUEST']['path']) && (self::$source['REQUEST']['path'] = rtrim(self::$source['REQUEST']['path'],'/ '))){
self::$source['PATH'] = explode('/', trim(self::$source['REQUEST']['path'],' /'));
}else{
self::$source['PATH'] = [];
}
if (isset($_POST)){
self::$source['REQUEST'] = array_replace_recursive(self::$source['REQUEST'], $_POST);
}
// Аргументы из консоли (режим CLI)
if (php_sapi_name() == 'cli' && isset($_SERVER['argv'])){
self::$source['REQUEST']['method'] = 'CLI';
self::$source['SERVER']['argv'] = $_SERVER['argv'];
self::$source['SERVER']['argc'] = $_SERVER['argc'];
}
self::$source['ARG'] = self::$source['SERVER']['argv'];
// Метод запроса
if (isset(self::$source['SERVER']['REQUEST_METHOD']) && !isset(self::$source['REQUEST']['method'])){
self::$source['REQUEST']['method'] = self::$source['SERVER']['REQUEST_METHOD'];
}
} | Активация модуля
Создание общего контейнера входящих данных | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L59-L139 |
Boolive/Core | request/Request.php | Request.addCommand | function addCommand($name, $args = [], $prepand = false)
{
if (!isset($this->commands[$name])){
$this->commands[$name] = [];
}
if ($prepand){
array_unshift($this->commands[$name], $args);
}else{
$this->commands[$name][] = $args;
}
// Добавление команды в группы
foreach ($this->groups as $key => $g){
$this->groups[$key][] = array($name, $args, $prepand);
}
} | php | function addCommand($name, $args = [], $prepand = false)
{
if (!isset($this->commands[$name])){
$this->commands[$name] = [];
}
if ($prepand){
array_unshift($this->commands[$name], $args);
}else{
$this->commands[$name][] = $args;
}
// Добавление команды в группы
foreach ($this->groups as $key => $g){
$this->groups[$key][] = array($name, $args, $prepand);
}
} | Добавить новую команду
@param string $name
@param array $args
@param bool $prepand | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L163-L177 |
Boolive/Core | request/Request.php | Request.getCommands | function getCommands($name, $unique = false)
{
if (!isset($this->commands[$name])){
$this->commands[$name] = [];
}
if ($unique){
$keys = [];
$result = [];
foreach ($this->commands[$name] as $com){
$key = serialize($com);
if (!isset($keys[$key])){
$result[] = $com;
$keys[$key] = true;
}
}
unset($keys);
return $result;
}
return $this->commands[$name];
} | php | function getCommands($name, $unique = false)
{
if (!isset($this->commands[$name])){
$this->commands[$name] = [];
}
if ($unique){
$keys = [];
$result = [];
foreach ($this->commands[$name] as $com){
$key = serialize($com);
if (!isset($keys[$key])){
$result[] = $com;
$keys[$key] = true;
}
}
unset($keys);
return $result;
}
return $this->commands[$name];
} | Выбор команд по имени
@param string $name
@param bool $unique
@return array | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L190-L209 |
Boolive/Core | request/Request.php | Request.removeCommand | function removeCommand($name)
{
unset($this->commands[$name]);
foreach ($this->groups as $key => $commands){
foreach ($commands as $i => $c){
if ($c[0] == $name){
unset($this->groups[$key][$i]);
}
}
}
} | php | function removeCommand($name)
{
unset($this->commands[$name]);
foreach ($this->groups as $key => $commands){
foreach ($commands as $i => $c){
if ($c[0] == $name){
unset($this->groups[$key][$i]);
}
}
}
} | Удаление команд по имени
@param string $name Имя удаляемых команд | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L215-L225 |
Boolive/Core | request/Request.php | Request.getErrors | function getErrors()
{
if (!$this->errors){
$this->errors = new Error('Ошибки', 'errors', null, true);
}
return $this->errors;
} | php | function getErrors()
{
if (!$this->errors){
$this->errors = new Error('Ошибки', 'errors', null, true);
}
return $this->errors;
} | Ошибки при фильтре входящих данных
@return null|Error | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L266-L272 |
Boolive/Core | request/Request.php | Request.mix | function mix($mix)
{
if (!empty($mix) && is_array($mix)) {
$this->input = array_replace_recursive($this->input, $mix);
}
return $this;
} | php | function mix($mix)
{
if (!empty($mix) && is_array($mix)) {
$this->input = array_replace_recursive($this->input, $mix);
}
return $this;
} | Подмешать к входящим данным
@param array $mix
@return $this | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L279-L285 |
Boolive/Core | request/Request.php | Request.stash | function stash()
{
$this->stahes[] = [$this->input, $this->filtered, $this->errors];
$this->errors = null;
} | php | function stash()
{
$this->stahes[] = [$this->input, $this->filtered, $this->errors];
$this->errors = null;
} | Спрятать текщие входящие данные | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L290-L294 |
Boolive/Core | request/Request.php | Request.unstash | function unstash()
{
list($this->input, $this->filtered, $this->errors) = array_pop($this->stahes);
} | php | function unstash()
{
list($this->input, $this->filtered, $this->errors) = array_pop($this->stahes);
} | Востановить спрятанные входящие данные | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L299-L302 |
Boolive/Core | request/Request.php | Request.url | static function url($path = null, $args = [], $append = false, $host = false, $schema = 'http://')
{
// Путь. Если null, то текущий
if (!isset($path)){
$path = self::$source['REQUEST']['path'];
}
// Если начинается с /contents, то обрезать
if (mb_substr($path,0,9) == '/contents'){
$path = mb_substr($path,10);
}
$url = trim($path,'/');
// Аргументы
if (!isset($args)){
$args = self::$source['SERVER']['argv'];
}else{
if ($append){
$args = array_merge(self::$source['SERVER']['argv'], $args);
}
}
if (isset($args['path'])) unset($args['path']);
if (is_array($args)){
foreach ($args as $name => $value){
$url .= '&'.$name.($value!==''?'='.$value:'');
}
}
if ($host){
return $schema.($host===true?HTTP_HOST.'/':$host).$url;
}else{
return '/'.$url;
}
} | php | static function url($path = null, $args = [], $append = false, $host = false, $schema = 'http://')
{
// Путь. Если null, то текущий
if (!isset($path)){
$path = self::$source['REQUEST']['path'];
}
// Если начинается с /contents, то обрезать
if (mb_substr($path,0,9) == '/contents'){
$path = mb_substr($path,10);
}
$url = trim($path,'/');
// Аргументы
if (!isset($args)){
$args = self::$source['SERVER']['argv'];
}else{
if ($append){
$args = array_merge(self::$source['SERVER']['argv'], $args);
}
}
if (isset($args['path'])) unset($args['path']);
if (is_array($args)){
foreach ($args as $name => $value){
$url .= '&'.$name.($value!==''?'='.$value:'');
}
}
if ($host){
return $schema.($host===true?HTTP_HOST.'/':$host).$url;
}else{
return '/'.$url;
}
} | Создание URL на основе текущего.
Если не указан ни один параметр, то возвращается URL текущего запроса
@param null|string $path Путь uri. Если не указан, то используется текущий путь
@param array $args Массив аргументов.
@param bool $append Добавлять ли текущие аргументы к новым?
@param bool|string $host Добавлять ли адрес сайта. Если true, то добавляет адрес текущего сайта. Можно строкой указать другой сайт
@param string $schema Схема url. Указывается, если указан $host
@return string | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/request/Request.php#L314-L344 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.setName | public function setName($name)
{
$attrName = $this->isMultiple()
? "{$name}[]"
: $name;
$this->setAttribute('name', $attrName);
$this->name = $name;
if ($label = $this->getLabel()) {
$this->getLabel()->setAttribute('for', $this->generateId());
}
return $this;
} | php | public function setName($name)
{
$attrName = $this->isMultiple()
? "{$name}[]"
: $name;
$this->setAttribute('name', $attrName);
$this->name = $name;
if ($label = $this->getLabel()) {
$this->getLabel()->setAttribute('for', $this->generateId());
}
return $this;
} | Sets input name
@param string $name
@return self|$this|InputInterface|AbstractInput | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L86-L97 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.setLabel | public function setLabel($label)
{
$this->label = $this->checkLabel($label);
$class = $this->label->getAttribute('class');
$this->label->setAttribute('for', $this->generateId())
->setAttribute('class', trim("control-label {$class}"));
return $this;
} | php | public function setLabel($label)
{
$this->label = $this->checkLabel($label);
$class = $this->label->getAttribute('class');
$this->label->setAttribute('for', $this->generateId())
->setAttribute('class', trim("control-label {$class}"));
return $this;
} | Sets the input label
Label parameter can be a string or a element interface.
If a string is provided then an ElementInterface MUST be created.
This element MUST result in a <label> HTML tag when rendering and
as you may define your own implementation it is advisable that you
use the Slick\Form\Element\Label object.
@param string|ElementInterface $label
@return self|$this|InputInterface
@throws InvalidArgumentException If the provided label is not a string
or is not an object of a class implementing the ElementInterface. | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L115-L122 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.generateId | protected function generateId()
{
$inputId = static::$idPrefix . $this->getName();
if ($this->isMultiple()) {
$inputId = "{$inputId}-{$this->instances}";
}
$this->setAttribute('id', $inputId);
return $inputId;
} | php | protected function generateId()
{
$inputId = static::$idPrefix . $this->getName();
if ($this->isMultiple()) {
$inputId = "{$inputId}-{$this->instances}";
}
$this->setAttribute('id', $inputId);
return $inputId;
} | Generate input id based on provided name
@return string | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L161-L169 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.checkLabel | protected function checkLabel($label)
{
if ($label instanceof ElementInterface) {
return $label;
}
return $this->createLabel($this->translate($label));
} | php | protected function checkLabel($label)
{
if ($label instanceof ElementInterface) {
return $label;
}
return $this->createLabel($this->translate($label));
} | Check provided label
@param string|ElementInterface $label
@return ElementInterface|Label | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L178-L185 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.createLabel | protected function createLabel($label)
{
if (!is_string($label)) {
throw new InvalidArgumentException(
"Provided label is not a string or an ElementInterface ".
"interface object."
);
}
$element = class_exists($label)
? $this->createLabelFromClass($label)
: new Label('', $label);
return $element;
} | php | protected function createLabel($label)
{
if (!is_string($label)) {
throw new InvalidArgumentException(
"Provided label is not a string or an ElementInterface ".
"interface object."
);
}
$element = class_exists($label)
? $this->createLabelFromClass($label)
: new Label('', $label);
return $element;
} | Creates label from string
@param string $label
@return ElementInterface|Label | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L194-L208 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.setRequired | public function setRequired($required)
{
$this->required = (boolean) $required;
if ($this->isRequired()) {
$this->setAttribute('required');
return $this;
}
if ($this->getAttributes()->containsKey('required')) {
$this->getAttributes()->remove('required');
}
return $this;
} | php | public function setRequired($required)
{
$this->required = (boolean) $required;
if ($this->isRequired()) {
$this->setAttribute('required');
return $this;
}
if ($this->getAttributes()->containsKey('required')) {
$this->getAttributes()->remove('required');
}
return $this;
} | Sets the required flag for this input
@param boolean $required
@return $this|self|InputInterface | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L247-L259 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.getInstanceValue | public function getInstanceValue()
{
$value = $this->getValue();
if (
is_array($value) &&
array_key_exists($this->instances, $this->value)
) {
$value = $value[$this->instances];
}
return $value;
} | php | public function getInstanceValue()
{
$value = $this->getValue();
if (
is_array($value) &&
array_key_exists($this->instances, $this->value)
) {
$value = $value[$this->instances];
}
return $value;
} | If input is multiple get the instance value of it
@return mixed | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L286-L296 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.render | public function render($context = [])
{
$this->setAttribute('value', $this->getInstanceValue());
$data = parent::render($context);
if ($this->isMultiple()) {
$this->updateInstance();
}
return $data;
} | php | public function render($context = [])
{
$this->setAttribute('value', $this->getInstanceValue());
$data = parent::render($context);
if ($this->isMultiple()) {
$this->updateInstance();
}
return $data;
} | Returns the HTML string for current element
@param array $context
@return string | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L305-L313 |
slickframework/form | src/Input/AbstractInput.php | AbstractInput.updateInstance | protected function updateInstance()
{
$this->instances++;
$id = $this->generateId();
$this->setAttribute($id, $id);
if ($label = $this->getLabel()) {
$label->setAttribute('for', $id);
}
return $this;
} | php | protected function updateInstance()
{
$this->instances++;
$id = $this->generateId();
$this->setAttribute($id, $id);
if ($label = $this->getLabel()) {
$label->setAttribute('for', $id);
}
return $this;
} | Updates input id and link it to its label
@return self|AbstractInput | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L320-L330 |
romaricdrigon/OrchestraBundle | Core/Pool/RepositoryPool.php | RepositoryPool.addRepositoryDefinition | public function addRepositoryDefinition(RepositoryDefinitionInterface $repositoryDefinition)
{
$slug = $repositoryDefinition->getSlug();
if (isset($this->repositoriesBySlug[$slug])) {
throw new DomainErrorException('Two repositories has the same "'.$slug.'" slug!');
}
$this->repositoriesBySlug[$slug] = $repositoryDefinition;
} | php | public function addRepositoryDefinition(RepositoryDefinitionInterface $repositoryDefinition)
{
$slug = $repositoryDefinition->getSlug();
if (isset($this->repositoriesBySlug[$slug])) {
throw new DomainErrorException('Two repositories has the same "'.$slug.'" slug!');
}
$this->repositoriesBySlug[$slug] = $repositoryDefinition;
} | Add a repository definition to the pool
@param RepositoryDefinitionInterface $repositoryDefinition
@throws DomainErrorException | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Core/Pool/RepositoryPool.php#L34-L43 |
lrezek/Arachnid | src/LRezek/Arachnid/Proxy/Factory.php | Factory.fromRelation | function fromRelation($relationship, $repository, \Closure $loadCallback)
{
//Get the class name from the node, and the meta from that class name
$class = $relationship->getType();
//Create the proxy factory
return $this->fromEntity($relationship, $class, $repository, $loadCallback);
} | php | function fromRelation($relationship, $repository, \Closure $loadCallback)
{
//Get the class name from the node, and the meta from that class name
$class = $relationship->getType();
//Create the proxy factory
return $this->fromEntity($relationship, $class, $repository, $loadCallback);
} | Creates a proxy object for an Everyman relationship.
This creates a proxy object for a Everyman relationship, given the meta repository.
@param \Everyman\Neo4j\Relationship $relationship The node to create a proxy of.
@param \LRezek\Arachnid\Meta\Repository $repository The meta repository.
@param callable $loadCallback Callback for start/end node lazy loading.
@return mixed The proxy object. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L72-L79 |
lrezek/Arachnid | src/LRezek/Arachnid/Proxy/Factory.php | Factory.fromEntity | function fromEntity($entity, $class, $repository, $callback = null)
{
$meta = $repository->fromClass($class);
//Create the proxy object and set the meta, node, and load callback
$proxy = $this->createProxy($meta);
$proxy->__setMeta($meta);
$proxy->__setEntity($entity);
$proxy->__setLoadCallback($callback);
$proxy->__setEntity($entity);
//Set the primary key property in the object to the node id.
$pk = $meta->getPrimaryKey();
$pk->setValue($proxy, $entity->getId());
$proxy->__addHydrated($pk->getName());
//Set the properties
foreach ($meta->getProperties() as $property)
{
$name = $property->getName();
//If the value isn't null in the DB, set the property to the correct value
if($value = $entity->getProperty($name))
{
$property->setValue($proxy, $value);
$proxy->__addHydrated($name);
}
}
return $proxy;
} | php | function fromEntity($entity, $class, $repository, $callback = null)
{
$meta = $repository->fromClass($class);
//Create the proxy object and set the meta, node, and load callback
$proxy = $this->createProxy($meta);
$proxy->__setMeta($meta);
$proxy->__setEntity($entity);
$proxy->__setLoadCallback($callback);
$proxy->__setEntity($entity);
//Set the primary key property in the object to the node id.
$pk = $meta->getPrimaryKey();
$pk->setValue($proxy, $entity->getId());
$proxy->__addHydrated($pk->getName());
//Set the properties
foreach ($meta->getProperties() as $property)
{
$name = $property->getName();
//If the value isn't null in the DB, set the property to the correct value
if($value = $entity->getProperty($name))
{
$property->setValue($proxy, $value);
$proxy->__addHydrated($name);
}
}
return $proxy;
} | Creates a proxy object for a Everyman node or relationship.
This creates a proxy object for a Everyman relationship, given the meta repository and class name
@param \Everyman\Neo4j\Node|\Everyman\Neo4j\Relationship $entity The entity to create a proxy of.
@param string $class The class name.
@param \LRezek\Arachnid\Meta\Repository $repository The meta repository.
@param null $callback The load callback to use for start/end nodes.
@return mixed The proxy object. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L92-L123 |
lrezek/Arachnid | src/LRezek/Arachnid/Proxy/Factory.php | Factory.createProxy | private function createProxy(GraphElement $meta)
{
//Get the proxy class name, as well as the regular class name
$proxyClass = $meta->getProxyClass();
$className = $meta->getName();
//If the class already exists, just make an instance of it with the correct properties and return it.
if(class_exists($proxyClass, false))
{
return $this->newInstance($proxyClass);
}
//Create a target file for the class
$targetFile = "{$this->proxyDir}/$proxyClass.php";
//If the file doesn't exist
if($this->debug || !file_exists($targetFile))
{
//Initialize functions
$functions = '';
$reflectionClass = new \ReflectionClass($className);
//Loop through entities public methods
foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method)
{
//If the method isn't a constructor, destructor, or final, add it to the methods via method proxy.
if(!$method->isConstructor() && !$method->isDestructor() && !$method->isFinal())
{
$functions .= $this->methodProxy($method, $meta);
}
}
//Get the properties and primary key.
$properties = $meta->getProperties();
$properties[] = $meta->getPrimaryKey();
//Filter out private properties
$properties = array_filter($properties, function ($property) {
return !$property->isPrivate();
});
//Create an array map by property name
$properties = array_map(function ($property) {
return $property->getName();
}, $properties);
//Create php code for properties.
$properties = var_export($properties, true);
//Create the actual class.
$content = <<<CONTENT
<?php
class $proxyClass extends $className implements LRezek\\Arachnid\\Proxy\\Entity
{
private \$neo4j_hydrated = array();
private \$neo4j_meta;
private \$neo4j_entity;
private \$neo4j_loadCallback;
function getEntity()
{
\$entity = new $className;
foreach (\$this->neo4j_meta->getProperties() as \$prop)
{
\$prop->setValue(\$entity, \$prop->getValue(\$this));
}
\$prop = \$this->neo4j_meta->getPrimaryKey();
\$prop->setValue(\$entity, \$prop->getValue(\$this));
return \$entity;
}
$functions
function __addHydrated(\$name)
{
\$this->neo4j_hydrated[] = \$name;
}
function __setMeta(\$meta)
{
\$this->neo4j_meta = \$meta;
}
function __setEntity(\$entity)
{
\$this->neo4j_entity = \$entity;
}
function __getEntity()
{
return \$this->neo4j_entity;
}
function __setLoadCallback(\$loadCallback)
{
\$this->neo4j_loadCallback = \$loadCallback;
}
private function __load(\$name, \$propertyName)
{
//Already hydrated
if(in_array(\$propertyName, \$this->neo4j_hydrated))
{
return;
}
if(! \$this->neo4j_meta)
{
throw new \\LRezek\\Arachnid\\Exception('Proxy not fully initialized.');
}
\$property = \$this->neo4j_meta->findProperty(\$name);
if(strpos(\$name, 'set') === 0)
{
\$this->__addHydrated(\$propertyName);
return;
}
//Make property node
if(\$property->isStart() || \$property->isEnd())
{
\$loader = \$this->neo4j_loadCallback;
//Get the node
if(\$property->isStart())
{
\$node = \$this->neo4j_entity->getStartNode();
}
else
{
\$node = \$this->neo4j_entity->getEndNode();
}
\$node = \$loader(\$node);
//Set the property
\$property->setValue(\$this, \$node);
}
//Hydrate the property
\$this->__addHydrated(\$propertyName);
}
function __sleep()
{
return $properties;
}
}
CONTENT;
//Make sure the proxy directory is an actual directory
if(!is_dir($this->proxyDir))
{
if(false === @mkdir($this->proxyDir, 0775, true))
{
throw new Exception('Proxy Dir is not writable.');
}
}
//Make sure the directory is writable
else if(!is_writable($this->proxyDir))
{
throw new Exception('Proxy Dir is not writable.');
}
//Write the file
file_put_contents($targetFile, $content);
}
//Add file to class loader
require $targetFile;
//Return an instance of the proxy class
return $this->newInstance($proxyClass);
} | php | private function createProxy(GraphElement $meta)
{
//Get the proxy class name, as well as the regular class name
$proxyClass = $meta->getProxyClass();
$className = $meta->getName();
//If the class already exists, just make an instance of it with the correct properties and return it.
if(class_exists($proxyClass, false))
{
return $this->newInstance($proxyClass);
}
//Create a target file for the class
$targetFile = "{$this->proxyDir}/$proxyClass.php";
//If the file doesn't exist
if($this->debug || !file_exists($targetFile))
{
//Initialize functions
$functions = '';
$reflectionClass = new \ReflectionClass($className);
//Loop through entities public methods
foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method)
{
//If the method isn't a constructor, destructor, or final, add it to the methods via method proxy.
if(!$method->isConstructor() && !$method->isDestructor() && !$method->isFinal())
{
$functions .= $this->methodProxy($method, $meta);
}
}
//Get the properties and primary key.
$properties = $meta->getProperties();
$properties[] = $meta->getPrimaryKey();
//Filter out private properties
$properties = array_filter($properties, function ($property) {
return !$property->isPrivate();
});
//Create an array map by property name
$properties = array_map(function ($property) {
return $property->getName();
}, $properties);
//Create php code for properties.
$properties = var_export($properties, true);
//Create the actual class.
$content = <<<CONTENT
<?php
class $proxyClass extends $className implements LRezek\\Arachnid\\Proxy\\Entity
{
private \$neo4j_hydrated = array();
private \$neo4j_meta;
private \$neo4j_entity;
private \$neo4j_loadCallback;
function getEntity()
{
\$entity = new $className;
foreach (\$this->neo4j_meta->getProperties() as \$prop)
{
\$prop->setValue(\$entity, \$prop->getValue(\$this));
}
\$prop = \$this->neo4j_meta->getPrimaryKey();
\$prop->setValue(\$entity, \$prop->getValue(\$this));
return \$entity;
}
$functions
function __addHydrated(\$name)
{
\$this->neo4j_hydrated[] = \$name;
}
function __setMeta(\$meta)
{
\$this->neo4j_meta = \$meta;
}
function __setEntity(\$entity)
{
\$this->neo4j_entity = \$entity;
}
function __getEntity()
{
return \$this->neo4j_entity;
}
function __setLoadCallback(\$loadCallback)
{
\$this->neo4j_loadCallback = \$loadCallback;
}
private function __load(\$name, \$propertyName)
{
//Already hydrated
if(in_array(\$propertyName, \$this->neo4j_hydrated))
{
return;
}
if(! \$this->neo4j_meta)
{
throw new \\LRezek\\Arachnid\\Exception('Proxy not fully initialized.');
}
\$property = \$this->neo4j_meta->findProperty(\$name);
if(strpos(\$name, 'set') === 0)
{
\$this->__addHydrated(\$propertyName);
return;
}
//Make property node
if(\$property->isStart() || \$property->isEnd())
{
\$loader = \$this->neo4j_loadCallback;
//Get the node
if(\$property->isStart())
{
\$node = \$this->neo4j_entity->getStartNode();
}
else
{
\$node = \$this->neo4j_entity->getEndNode();
}
\$node = \$loader(\$node);
//Set the property
\$property->setValue(\$this, \$node);
}
//Hydrate the property
\$this->__addHydrated(\$propertyName);
}
function __sleep()
{
return $properties;
}
}
CONTENT;
//Make sure the proxy directory is an actual directory
if(!is_dir($this->proxyDir))
{
if(false === @mkdir($this->proxyDir, 0775, true))
{
throw new Exception('Proxy Dir is not writable.');
}
}
//Make sure the directory is writable
else if(!is_writable($this->proxyDir))
{
throw new Exception('Proxy Dir is not writable.');
}
//Write the file
file_put_contents($targetFile, $content);
}
//Add file to class loader
require $targetFile;
//Return an instance of the proxy class
return $this->newInstance($proxyClass);
} | Creates a proxy class for a graph element.
This method will create a proxy class for an entity that extends the required class and implements
LRezek\Arachnid\Proxy\Entity. This class will be generated and stored in the directory specified by the $proxyDir
property of this class. This is done so that the object returned by a query seemingly matches the object type
being queried for, while retaining its ID and other required information.
@param GraphElement $meta The meta for the entity object being proxied.
@return mixed An instance of the proxy class.
@throws \LRezek\Arachnid\Exception If something goes wrong in file writing. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L137-L320 |
lrezek/Arachnid | src/LRezek/Arachnid/Proxy/Factory.php | Factory.newInstance | private function newInstance($proxyClass)
{
static $prototypes = array();
if(!array_key_exists($proxyClass, $prototypes))
{
$prototypes[$proxyClass] = unserialize(sprintf('O:%d:"%s":0:{}', strlen($proxyClass), $proxyClass));
}
return clone $prototypes[$proxyClass];
} | php | private function newInstance($proxyClass)
{
static $prototypes = array();
if(!array_key_exists($proxyClass, $prototypes))
{
$prototypes[$proxyClass] = unserialize(sprintf('O:%d:"%s":0:{}', strlen($proxyClass), $proxyClass));
}
return clone $prototypes[$proxyClass];
} | Create a new instance of a proxy class object.
This creates an instance of a proxy class. If the class has already been created, it is retrieved from a static
prototypes array.
@param mixed $proxyClass The class to create an instance of.
@return mixed The new instance of <code>$proxyclass</code>. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L331-L341 |
lrezek/Arachnid | src/LRezek/Arachnid/Proxy/Factory.php | Factory.methodProxy | private function methodProxy($method, $meta)
{
//Find out if the method is a property getter or setter
$property = $meta->findProperty($method->getName());
//If it is not, don't need the proxy
if(!$property)
{
return;
}
//If the method is a straight up property setter/getter and not for a start/end node, you don't need a method proxy either.
if($property->isProperty() && !$property->isStart() && !$property->isEnd())
{
return;
}
$parts = array();
$arguments = array();
//Loop through the methods parameters
foreach ($method->getParameters() as $parameter)
{
//Convert to a variable name, and add it to parts array
$variable = '$' . $parameter->getName();
$parts[] = $variable;
$arg = $variable;
//If the parameter is optional, set it to its default value in the arguments list.
if($parameter->isOptional())
{
$arg .= ' = ' . var_export($parameter->getDefaultValue(), true);
}
//If the variable is passed by reference, put in an ampersand
if($parameter->isPassedByReference())
{
$arg = "& $arg";
}
//If the variable is a set class, add the class name as the type
elseif($c = $parameter->getClass())
{
$arg = $c->getName() . ' ' . $arg;
}
//If the argument is a array, add array identifier
if($parameter->isArray())
{
$arg = "array $arg";
}
//Add the argument to argument array
$arguments[] = $arg;
}
//Join the argument variable names together with commas
$parts = implode(', ', $parts);
//Join the arguments with commas
$arguments = implode(', ', $arguments);
//Get the method name as a string
$name = var_export($method->getName(), true);
//Get the property name as a string
$propertyName = var_export($property->getName(), true);
return <<<FUNC
function {$method->getName()}($arguments)
{
self::__load($name, $propertyName);
return parent::{$method->getName()}($parts);
}
FUNC;
} | php | private function methodProxy($method, $meta)
{
//Find out if the method is a property getter or setter
$property = $meta->findProperty($method->getName());
//If it is not, don't need the proxy
if(!$property)
{
return;
}
//If the method is a straight up property setter/getter and not for a start/end node, you don't need a method proxy either.
if($property->isProperty() && !$property->isStart() && !$property->isEnd())
{
return;
}
$parts = array();
$arguments = array();
//Loop through the methods parameters
foreach ($method->getParameters() as $parameter)
{
//Convert to a variable name, and add it to parts array
$variable = '$' . $parameter->getName();
$parts[] = $variable;
$arg = $variable;
//If the parameter is optional, set it to its default value in the arguments list.
if($parameter->isOptional())
{
$arg .= ' = ' . var_export($parameter->getDefaultValue(), true);
}
//If the variable is passed by reference, put in an ampersand
if($parameter->isPassedByReference())
{
$arg = "& $arg";
}
//If the variable is a set class, add the class name as the type
elseif($c = $parameter->getClass())
{
$arg = $c->getName() . ' ' . $arg;
}
//If the argument is a array, add array identifier
if($parameter->isArray())
{
$arg = "array $arg";
}
//Add the argument to argument array
$arguments[] = $arg;
}
//Join the argument variable names together with commas
$parts = implode(', ', $parts);
//Join the arguments with commas
$arguments = implode(', ', $arguments);
//Get the method name as a string
$name = var_export($method->getName(), true);
//Get the property name as a string
$propertyName = var_export($property->getName(), true);
return <<<FUNC
function {$method->getName()}($arguments)
{
self::__load($name, $propertyName);
return parent::{$method->getName()}($parts);
}
FUNC;
} | Creates proxy methods from the reflection method handle and meta information.
@param $method
@param $meta
@return string The method code. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L351-L429 |
kherge-abandoned/php-file | src/lib/KHerGe/File/Utility.php | Utility.remove | public static function remove($path)
{
if (is_dir($path)) {
if (false === ($dir = opendir($path))) {
throw FileException::removeFailed($path);
}
while (false !== ($item = readdir($dir))) {
if (('.' === $item) || ('..' === $item)) {
continue;
}
self::remove($path . DIRECTORY_SEPARATOR . $item);
}
closedir($dir);
if (!rmdir($path)) {
throw FileException::removeFailed($path);
}
} elseif (!unlink($path)) {
throw FileException::removeFailed($path);
}
} | php | public static function remove($path)
{
if (is_dir($path)) {
if (false === ($dir = opendir($path))) {
throw FileException::removeFailed($path);
}
while (false !== ($item = readdir($dir))) {
if (('.' === $item) || ('..' === $item)) {
continue;
}
self::remove($path . DIRECTORY_SEPARATOR . $item);
}
closedir($dir);
if (!rmdir($path)) {
throw FileException::removeFailed($path);
}
} elseif (!unlink($path)) {
throw FileException::removeFailed($path);
}
} | Recursively removes a path from the file system.
@param string $path The path to remove.
@throws FileException If the path could not be removed. | https://github.com/kherge-abandoned/php-file/blob/d2f0f52b2da471c36cb567840852c5041bc4c196/src/lib/KHerGe/File/Utility.php#L21-L44 |
temp/media-converter | src/Converter/ConverterResolver.php | ConverterResolver.resolve | public function resolve(Specification $spec)
{
foreach ($this->converters as $converter) {
if ($converter->accept($spec)) {
return $converter;
}
}
return null;
} | php | public function resolve(Specification $spec)
{
foreach ($this->converters as $converter) {
if ($converter->accept($spec)) {
return $converter;
}
}
return null;
} | @param Specification $spec
@return ConverterInterface | https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Converter/ConverterResolver.php#L53-L62 |
romeOz/rock-cache | src/Cache.php | Cache.serialize | protected function serialize($value)
{
if (!is_array($value)) {
return $value;
}
return Serialize::serialize($value, $this->serializer);
} | php | protected function serialize($value)
{
if (!is_array($value)) {
return $value;
}
return Serialize::serialize($value, $this->serializer);
} | Serialize value.
@param array $value
@return array|string | https://github.com/romeOz/rock-cache/blob/bbd146ee323e8cc1fb11dc1803215c3656e02c57/src/Cache.php#L239-L245 |
romeOz/rock-cache | src/Cache.php | Cache.microtime | protected function microtime($microtime = null)
{
list($usec, $sec) = explode(" ", $microtime ?: microtime());
return (float)$usec + (float)$sec;
} | php | protected function microtime($microtime = null)
{
list($usec, $sec) = explode(" ", $microtime ?: microtime());
return (float)$usec + (float)$sec;
} | Returns a microtime.
@param int|null $microtime
@return float | https://github.com/romeOz/rock-cache/blob/bbd146ee323e8cc1fb11dc1803215c3656e02c57/src/Cache.php#L273-L277 |
gluephp/glue | src/Http/Response.php | Response.binaryFile | public function binaryFile($file, $status = 200, array $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
{
return new BinaryFileResponse($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
} | php | public function binaryFile($file, $status = 200, array $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
{
return new BinaryFileResponse($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
} | Create a new BinaryFileResponse
@param \SplFileInfo|string $file The file to stream
@param int $status The response status code
@param array $headers An array of response headers
@param bool $public Files are public by default
@param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
@param bool $autoEtag Whether the ETag header should be automatically set
@param bool $autoLastModified Whether the Last-Modified header should be automatically set | https://github.com/gluephp/glue/blob/d54e0905dfe74d1c114c04f33fa89a60e2651562/src/Http/Response.php#L52-L55 |
gluephp/glue | src/Http/Response.php | Response.fileDownload | public function fileDownload($file)
{
$response = new SymfonyResponse();
$response->headers->set('Content-Disposition',
$response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$file
)
);
return $response;
} | php | public function fileDownload($file)
{
$response = new SymfonyResponse();
$response->headers->set('Content-Disposition',
$response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$file
)
);
return $response;
} | Create a new file download response
@param string $file The file | https://github.com/gluephp/glue/blob/d54e0905dfe74d1c114c04f33fa89a60e2651562/src/Http/Response.php#L63-L75 |
3ev/wordpress-core | src/Tev/Application/Bootstrap/Taxonomy.php | Taxonomy.bootstrap | public function bootstrap(Application $app)
{
// Bind a taxonomy factory instance
$app->bind('taxonomy_factory', function ($app) {
return new Factory($app->fetch('term_factory'));
});
// Bind a taxonomy repository instance
$app->bind('taxonomy_repo', function ($app) {
return new TaxonomyRepository($app->fetch('taxonomy_factory'));
});
} | php | public function bootstrap(Application $app)
{
// Bind a taxonomy factory instance
$app->bind('taxonomy_factory', function ($app) {
return new Factory($app->fetch('term_factory'));
});
// Bind a taxonomy repository instance
$app->bind('taxonomy_repo', function ($app) {
return new TaxonomyRepository($app->fetch('taxonomy_factory'));
});
} | {@inheritDoc} | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Application/Bootstrap/Taxonomy.php#L17-L30 |
schoolphp/library | MoveOrder/MoveOrder.php | MoveOrder.query | private function query($query)
{
if(!is_array($query)) {
return q($query);
} else {
foreach($query as $v) {
q($v);
}
return true;
}
} | php | private function query($query)
{
if(!is_array($query)) {
return q($query);
} else {
foreach($query as $v) {
q($v);
}
return true;
}
} | Метод query: Обработка и упрощение запросов для класса | https://github.com/schoolphp/library/blob/3470d2147c2f51226be76406baec5afddbc4efcd/MoveOrder/MoveOrder.php#L28-L38 |
schoolphp/library | MoveOrder/MoveOrder.php | MoveOrder.getGroup | private function getGroup($start = "WHERE",$table = NULL)
{
if(count($this->group))
{
$temp = [];
foreach($this->group as $k=>$v)
$temp[] = (!empty($table) ? $table."." : '')."`".$k."` = '".$v."'";
return $start." ".implode(' AND ',$temp);
}
else
return '';
} | php | private function getGroup($start = "WHERE",$table = NULL)
{
if(count($this->group))
{
$temp = [];
foreach($this->group as $k=>$v)
$temp[] = (!empty($table) ? $table."." : '')."`".$k."` = '".$v."'";
return $start." ".implode(' AND ',$temp);
}
else
return '';
} | Метод getGroup: Получение группировки | https://github.com/schoolphp/library/blob/3470d2147c2f51226be76406baec5afddbc4efcd/MoveOrder/MoveOrder.php#L45-L56 |
schoolphp/library | MoveOrder/MoveOrder.php | MoveOrder.mysqlChange | public function mysqlChange($move_do)
{
$group = $this->getGroup('AND','a');
if(!empty($group))
$group = $group.$this->getGroup(' AND','b');
if($move_do == 'up')
{
$znak = '<';
$sort = 'DESC';
}
else
{
$znak = '>';
$sort = '';
}
$res = $this->query("SELECT a.`".$this->row_id."` AS `a_id`,a.`".$this->cell."` AS `a_order`,
b.`".$this->row_id."` AS `b_id`,b.`".$this->cell."` AS `b_order`
FROM `".$this->table."` a
LEFT JOIN `".$this->table."` b ON b.`".$this->cell."` ".$znak." a.`".$this->cell."`
WHERE a.`".$this->row_id."` = ".(int)$this->id."
AND b.`".$this->cell."` is NOT NULL
".$group."
ORDER BY b.`".$this->cell."` ".$sort."
LIMIT 1
");
if($res->num_rows) {
$row = $res->fetch_assoc();
$query = [];
$query[] = "UPDATE `".$this->table."` SET
`".$this->cell."` = ".$row['b_order']."
WHERE `".$this->row_id."` = ".$row['a_id'];
$query[] = "UPDATE `".$this->table."` SET
`".$this->cell."` = ".$row['a_order']."
WHERE `".$this->row_id."` = ".$row['b_id'];
$this->query($query);
return 1;
}
else
return 2;
} | php | public function mysqlChange($move_do)
{
$group = $this->getGroup('AND','a');
if(!empty($group))
$group = $group.$this->getGroup(' AND','b');
if($move_do == 'up')
{
$znak = '<';
$sort = 'DESC';
}
else
{
$znak = '>';
$sort = '';
}
$res = $this->query("SELECT a.`".$this->row_id."` AS `a_id`,a.`".$this->cell."` AS `a_order`,
b.`".$this->row_id."` AS `b_id`,b.`".$this->cell."` AS `b_order`
FROM `".$this->table."` a
LEFT JOIN `".$this->table."` b ON b.`".$this->cell."` ".$znak." a.`".$this->cell."`
WHERE a.`".$this->row_id."` = ".(int)$this->id."
AND b.`".$this->cell."` is NOT NULL
".$group."
ORDER BY b.`".$this->cell."` ".$sort."
LIMIT 1
");
if($res->num_rows) {
$row = $res->fetch_assoc();
$query = [];
$query[] = "UPDATE `".$this->table."` SET
`".$this->cell."` = ".$row['b_order']."
WHERE `".$this->row_id."` = ".$row['a_id'];
$query[] = "UPDATE `".$this->table."` SET
`".$this->cell."` = ".$row['a_order']."
WHERE `".$this->row_id."` = ".$row['b_id'];
$this->query($query);
return 1;
}
else
return 2;
} | Метод mysqlChange: Перемещаем запись выше или ниже нынешней позиции | https://github.com/schoolphp/library/blob/3470d2147c2f51226be76406baec5afddbc4efcd/MoveOrder/MoveOrder.php#L63-L104 |
schoolphp/library | MoveOrder/MoveOrder.php | MoveOrder.mysqlReOrder | public function mysqlReOrder()
{
$group = $this->getGroup();
$res = $this->query("SELECT `".$this->row_id."`
FROM `".$this->table."`
".$group."
ORDER BY `".$this->cell."`
");
$query = [];
$i = $this->reorder;
while($row = $res->fetch_assoc())
$query[] = "UPDATE `".$this->table."` SET `".$this->cell."` = ".$i++." WHERE `".$this->row_id."`= ".$row[$this->row_id];
return ($this->query($query)) ? 9 : 10;
} | php | public function mysqlReOrder()
{
$group = $this->getGroup();
$res = $this->query("SELECT `".$this->row_id."`
FROM `".$this->table."`
".$group."
ORDER BY `".$this->cell."`
");
$query = [];
$i = $this->reorder;
while($row = $res->fetch_assoc())
$query[] = "UPDATE `".$this->table."` SET `".$this->cell."` = ".$i++." WHERE `".$this->row_id."`= ".$row[$this->row_id];
return ($this->query($query)) ? 9 : 10;
} | Метод mysqlReOrder: Востанавливает целостность группировки | https://github.com/schoolphp/library/blob/3470d2147c2f51226be76406baec5afddbc4efcd/MoveOrder/MoveOrder.php#L110-L125 |
apishka/easy-extend | source/Command/GenerateMeta.php | GenerateMeta.execute | protected function execute(InputInterface $input, OutputInterface $output): void
{
$output->writeln('Apishka Easy Extend meta generation');
$this->generateMeta();
$output->writeln('Done');
} | php | protected function execute(InputInterface $input, OutputInterface $output): void
{
$output->writeln('Apishka Easy Extend meta generation');
$this->generateMeta();
$output->writeln('Done');
} | Execute
@param InputInterface $input
@param OutputInterface $output | https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/Command/GenerateMeta.php#L32-L39 |
apishka/easy-extend | source/Command/GenerateMeta.php | GenerateMeta.generateMeta | private function generateMeta(): void
{
$generator = new Meta\Generator();
$generator->register(
$this->generateMetaDataForRouter(Broker::getInstance(), 'getRouter')
);
$generator->register(
$this->generateMetaDataForRouter(Broker::getInstance()->getRouter(Locator\ByClassName::class), 'make')
);
$generator->generate('easy-extend.meta.php');
} | php | private function generateMeta(): void
{
$generator = new Meta\Generator();
$generator->register(
$this->generateMetaDataForRouter(Broker::getInstance(), 'getRouter')
);
$generator->register(
$this->generateMetaDataForRouter(Broker::getInstance()->getRouter(Locator\ByClassName::class), 'make')
);
$generator->generate('easy-extend.meta.php');
} | Generates file with meta | https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/Command/GenerateMeta.php#L44-L57 |
apishka/easy-extend | source/Command/GenerateMeta.php | GenerateMeta.generateMetaDataForRouter | private function generateMetaDataForRouter(RouterAbstract $router, string $function): Meta\Data
{
$data = new Meta\Data(get_class($router), $function);
foreach ($router->getData() as $key => $details)
{
$data->map(
'\\' . $key,
true,
'\\' . $details['class'] . '::class',
false
);
}
return $data;
} | php | private function generateMetaDataForRouter(RouterAbstract $router, string $function): Meta\Data
{
$data = new Meta\Data(get_class($router), $function);
foreach ($router->getData() as $key => $details)
{
$data->map(
'\\' . $key,
true,
'\\' . $details['class'] . '::class',
false
);
}
return $data;
} | @param RouterAbstract $router
@param string $function
@return Meta\Data | https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/Command/GenerateMeta.php#L65-L80 |
alphacomm/alpharpc | src/AlphaRPC/Manager/ClientHandler/Client.php | Client.setRequest | public function setRequest($request, $waitForResult = true)
{
$this->previousRequest = $this->request;
$this->request = $request;
$this->waitForResult = $waitForResult;
$this->bucket->refresh($this);
return $this;
} | php | public function setRequest($request, $waitForResult = true)
{
$this->previousRequest = $this->request;
$this->request = $request;
$this->waitForResult = $waitForResult;
$this->bucket->refresh($this);
return $this;
} | Sets the request the client is interested in.
@param string $request
@param boolean $waitForResult
@return \AlphaRPC\Manager\ClientHandler\Client | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/ClientHandler/Client.php#L143-L151 |
inhere/php-library-plus | libs/Log/Handlers/StreamHandler.php | StreamHandler.write | protected function write(array $record)
{
if (!\is_resource($this->stream)) {
if (null === $this->url || '' === $this->url) {
throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
}
$this->createDir();
$this->errorMessage = null;
set_error_handler(array($this, 'customErrorHandler'));
$this->stream = fopen($this->url, 'ab');
if ($this->filePermission !== null) {
@chmod($this->url, $this->filePermission);
}
restore_error_handler();
if (!\is_resource($this->stream)) {
$this->stream = null;
throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url));
}
}
if ($this->useLocking) {
// ignoring errors here, there's not much we can do about them
flock($this->stream, LOCK_EX);
}
$this->streamWrite($this->stream, $record);
if ($this->useLocking) {
flock($this->stream, LOCK_UN);
}
} | php | protected function write(array $record)
{
if (!\is_resource($this->stream)) {
if (null === $this->url || '' === $this->url) {
throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
}
$this->createDir();
$this->errorMessage = null;
set_error_handler(array($this, 'customErrorHandler'));
$this->stream = fopen($this->url, 'ab');
if ($this->filePermission !== null) {
@chmod($this->url, $this->filePermission);
}
restore_error_handler();
if (!\is_resource($this->stream)) {
$this->stream = null;
throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url));
}
}
if ($this->useLocking) {
// ignoring errors here, there's not much we can do about them
flock($this->stream, LOCK_EX);
}
$this->streamWrite($this->stream, $record);
if ($this->useLocking) {
flock($this->stream, LOCK_UN);
}
} | {@inheritdoc} | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Log/Handlers/StreamHandler.php#L86-L116 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Session/RawSessionHandler.php | RawSessionHandler.setupNamespace | private function setupNamespace($namespace)
{
if(!is_null($namespace)) {
if(!isset($_SESSION[$namespace]) || !is_array($_SESSION[$namespace])) {
$_SESSION[$namespace] = array();
}
$this->data = &$_SESSION[$namespace];
} else {
$this->data = &$_SESSION;
}
} | php | private function setupNamespace($namespace)
{
if(!is_null($namespace)) {
if(!isset($_SESSION[$namespace]) || !is_array($_SESSION[$namespace])) {
$_SESSION[$namespace] = array();
}
$this->data = &$_SESSION[$namespace];
} else {
$this->data = &$_SESSION;
}
} | If provided, we'll use a sub-array of $_SESSION instead of the
root array. This keeps us from polluting the root $_SESSION,
which could be important if we're sharing session with other apps.
@param string $namespace
@return void | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Session/RawSessionHandler.php#L45-L55 |
vudaltsov-legacy/twig-extensions | src/Helper.php | Helper.iterableToArray | public static function iterableToArray($iterable): array
{
if (is_array($iterable)) {
return $iterable;
}
if ($iterable instanceof \Traversable) {
return iterator_to_array($iterable);
}
throw new \InvalidArgumentException('Iterable is expected.');
} | php | public static function iterableToArray($iterable): array
{
if (is_array($iterable)) {
return $iterable;
}
if ($iterable instanceof \Traversable) {
return iterator_to_array($iterable);
}
throw new \InvalidArgumentException('Iterable is expected.');
} | @param iterable $iterable
@return array
@throws \InvalidArgumentException | https://github.com/vudaltsov-legacy/twig-extensions/blob/a86574b17d7e77e8d8c79ae34702c5acfbc87861/src/Helper.php#L13-L24 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.seleccionarBd | public function seleccionarBd($basedatos)
{
if ($this->pdo->exec('USE ' . $basedatos) === false) {
if ($this->arrojarExcepciones) {
throw new \RuntimeException('No se pudo seleccionar base de datos.');
}
return false;
}
return true;
} | php | public function seleccionarBd($basedatos)
{
if ($this->pdo->exec('USE ' . $basedatos) === false) {
if ($this->arrojarExcepciones) {
throw new \RuntimeException('No se pudo seleccionar base de datos.');
}
return false;
}
return true;
} | Selecciona la base de datos interna.
@param string $basedatos
@return bool
@throws \RuntimeException | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L90-L101 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.prepararValor | public function prepararValor($valor, $tipo = 'txt', $permiteVacio = false)
{
if (is_array($valor)) {
if (empty($valor)) {
return 'NULL';
}
foreach ($valor as $llave => $v) {
$valor[$llave] = $this->prepararValor($v, $tipo);
}
return $valor;
}
// Retornamos valor boleano según el tipo
if ($tipo == 'bol' || $tipo == 'bool') {
return ($valor) ? '1' : '0';
}
// Detectamos y retornamos valor nulo
if ($valor === null || $valor === false) {
return 'NULL';
}
if (!$permiteVacio && $valor === '') {
return 'NULL';
}
// Retornamos valor numerico según el tipo
if ($tipo == 'num' || $tipo == 'int') {
if ($valor === '') return 'NULL';
return strval(floatval($valor));
}
// Retornamos valor textual como valor predeterminado
return $this->pdo->quote($valor);
} | php | public function prepararValor($valor, $tipo = 'txt', $permiteVacio = false)
{
if (is_array($valor)) {
if (empty($valor)) {
return 'NULL';
}
foreach ($valor as $llave => $v) {
$valor[$llave] = $this->prepararValor($v, $tipo);
}
return $valor;
}
// Retornamos valor boleano según el tipo
if ($tipo == 'bol' || $tipo == 'bool') {
return ($valor) ? '1' : '0';
}
// Detectamos y retornamos valor nulo
if ($valor === null || $valor === false) {
return 'NULL';
}
if (!$permiteVacio && $valor === '') {
return 'NULL';
}
// Retornamos valor numerico según el tipo
if ($tipo == 'num' || $tipo == 'int') {
if ($valor === '') return 'NULL';
return strval(floatval($valor));
}
// Retornamos valor textual como valor predeterminado
return $this->pdo->quote($valor);
} | Prepara valor segun tipo especificado.
@param mixed $valor Valor a preparar
@param string $tipo Tipo de valor pasado: bol, txt, num, def
@param bool $permiteVacio Define si permite cadena de texto vacio en vez de nulo
@return string Retorna valor escapado para MySQL | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L112-L148 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.obtener | public function obtener($indice = null, $agrupacion = null, $clase = null, array $claseArgs = [])
{
// Validamos la sentencia a ejecutar
if (empty($this->sentencia)) {
if ($this->arrojarExcepciones) {
throw new \InvalidArgumentException('La sentencia a consultar se encuentra vacia.');
}
return false;
}
// Consultamos la sentencia para obtener datos
$resultado = $this->pdo->query($this->sentencia);
if ($resultado === false) {
if ($this->arrojarExcepciones) {
$error_info = $this->pdo->errorInfo();
throw new Excepcion($error_info[2], [
'sentencia' => $this->sentencia,
'error_codigo' => $error_info[0],
], $error_info[1]);
}
return false;
}
$final = [];
$conteo = 0;
$agrupacionX = '##';
if (!empty($clase)) { // Obtenemos objetos
if ($registro = $resultado->fetchObject($clase, $claseArgs)) {
// Se valida existencia de campos requeridos según argumentos introducidos
if (!empty($agrupacion) && !property_exists($registro, $agrupacion)) {
throw new Excepcion('El campo de agrupación no está presente en los registros.', [
'campo' => $agrupacion,
]);
}
if (!empty($indice) && !property_exists($registro, $indice)) {
throw new Excepcion('El campo de indización no está presente en los registros.', [
'campo' => $agrupacion,
]);
}
// Recorremos los registros y los convertimos en objetos
while ($registro) {
if (!empty($agrupacion)) {
$agrupacionX = $registro->{$agrupacion};
}
if (empty($indice)) {
$indiceX = $conteo++;
} else {
$indiceX = $registro->{$indice};
}
$final[$agrupacionX][$indiceX] = $registro;
$registro = $resultado->fetchObject($clase, $claseArgs);
}
}
} else { // Obtenemos arreglos
if ($registro = $resultado->fetch(\PDO::FETCH_ASSOC)) {
// Se valida existencia de campos requeridos según argumentos introducidos
if (!empty($agrupacion) && !array_key_exists($agrupacion, $registro)) {
throw new Excepcion('El campo de agrupación no está presente en los registros.', [
'campo' => $agrupacion,
]);
}
if (!empty($indice) && !array_key_exists($indice, $registro)) {
throw new Excepcion('El campo de indización no está presente en los registros.', [
'campo' => $indice,
]);
}
// Recorremos los registros y los convertimos en arreglos asociativos
while ($registro) {
if (!empty($agrupacion)) {
$agrupacionX = $registro[$agrupacion];
}
if (empty($indice)) {
$indiceX = $conteo++;
} else {
$indiceX = $registro[$indice];
}
$final[$agrupacionX][$indiceX] = $registro;
$registro = $resultado->fetch(\PDO::FETCH_ASSOC);
}
}
}
// Se libera recursos consumidos
$resultado->closeCursor();
$resultado = null;
// Se quita la agrupación temporal
if (empty($agrupacion) && !empty($final)) {
$final = $final['##'];
}
return $final;
} | php | public function obtener($indice = null, $agrupacion = null, $clase = null, array $claseArgs = [])
{
// Validamos la sentencia a ejecutar
if (empty($this->sentencia)) {
if ($this->arrojarExcepciones) {
throw new \InvalidArgumentException('La sentencia a consultar se encuentra vacia.');
}
return false;
}
// Consultamos la sentencia para obtener datos
$resultado = $this->pdo->query($this->sentencia);
if ($resultado === false) {
if ($this->arrojarExcepciones) {
$error_info = $this->pdo->errorInfo();
throw new Excepcion($error_info[2], [
'sentencia' => $this->sentencia,
'error_codigo' => $error_info[0],
], $error_info[1]);
}
return false;
}
$final = [];
$conteo = 0;
$agrupacionX = '##';
if (!empty($clase)) { // Obtenemos objetos
if ($registro = $resultado->fetchObject($clase, $claseArgs)) {
// Se valida existencia de campos requeridos según argumentos introducidos
if (!empty($agrupacion) && !property_exists($registro, $agrupacion)) {
throw new Excepcion('El campo de agrupación no está presente en los registros.', [
'campo' => $agrupacion,
]);
}
if (!empty($indice) && !property_exists($registro, $indice)) {
throw new Excepcion('El campo de indización no está presente en los registros.', [
'campo' => $agrupacion,
]);
}
// Recorremos los registros y los convertimos en objetos
while ($registro) {
if (!empty($agrupacion)) {
$agrupacionX = $registro->{$agrupacion};
}
if (empty($indice)) {
$indiceX = $conteo++;
} else {
$indiceX = $registro->{$indice};
}
$final[$agrupacionX][$indiceX] = $registro;
$registro = $resultado->fetchObject($clase, $claseArgs);
}
}
} else { // Obtenemos arreglos
if ($registro = $resultado->fetch(\PDO::FETCH_ASSOC)) {
// Se valida existencia de campos requeridos según argumentos introducidos
if (!empty($agrupacion) && !array_key_exists($agrupacion, $registro)) {
throw new Excepcion('El campo de agrupación no está presente en los registros.', [
'campo' => $agrupacion,
]);
}
if (!empty($indice) && !array_key_exists($indice, $registro)) {
throw new Excepcion('El campo de indización no está presente en los registros.', [
'campo' => $indice,
]);
}
// Recorremos los registros y los convertimos en arreglos asociativos
while ($registro) {
if (!empty($agrupacion)) {
$agrupacionX = $registro[$agrupacion];
}
if (empty($indice)) {
$indiceX = $conteo++;
} else {
$indiceX = $registro[$indice];
}
$final[$agrupacionX][$indiceX] = $registro;
$registro = $resultado->fetch(\PDO::FETCH_ASSOC);
}
}
}
// Se libera recursos consumidos
$resultado->closeCursor();
$resultado = null;
// Se quita la agrupación temporal
if (empty($agrupacion) && !empty($final)) {
$final = $final['##'];
}
return $final;
} | Consulta la sentencia interna y devuelve registros encontrados en el formato solicitado.
@param string $indice Campo que desea como índice de registros
@param string $agrupacion Campo que desea como agrupación de registros
@param string $clase Nombre de clase que servirá como resultado
@param array $claseArgs Argumentos para clase a servir
@return array|bool
@throws Excepcion
@throws \InvalidArgumentException | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L173-L279 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.obtenerPrimero | public function obtenerPrimero($clase = null, array $claseArgs = [])
{
$resultado = $this->obtener(null, null, $clase, $claseArgs);
if ($resultado !== false) {
return array_shift($resultado);
}
return false;
} | php | public function obtenerPrimero($clase = null, array $claseArgs = [])
{
$resultado = $this->obtener(null, null, $clase, $claseArgs);
if ($resultado !== false) {
return array_shift($resultado);
}
return false;
} | Devuelve el primer registro generado por la consulta de la sentencia interna.
@param string $clase Nombre de clase que servirá como formato de registro
@param array $claseArgs Argumentos para instanciar clase formato
@return array|bool
@throws \RuntimeException
@throws \InvalidArgumentException | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L292-L301 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.ejecutar | public function ejecutar()
{
// Validamos la sentencia a ejecutar
if (empty($this->sentencia)) {
if ($this->arrojarExcepciones) {
throw new \InvalidArgumentException('La sentencia a ejecutar se encuentra vacia.');
}
return false;
}
// Ejecutamos la sentencia
$resultado = $this->pdo->exec($this->sentencia);
if ($resultado === false) {
if ($this->arrojarExcepciones) {
$error_info = $this->pdo->errorInfo();
throw new Excepcion($error_info[2], [
'sentencia' => $this->sentencia,
'error_codigo' => $error_info[0],
], $error_info[1]);
}
return false;
}
return $resultado;
} | php | public function ejecutar()
{
// Validamos la sentencia a ejecutar
if (empty($this->sentencia)) {
if ($this->arrojarExcepciones) {
throw new \InvalidArgumentException('La sentencia a ejecutar se encuentra vacia.');
}
return false;
}
// Ejecutamos la sentencia
$resultado = $this->pdo->exec($this->sentencia);
if ($resultado === false) {
if ($this->arrojarExcepciones) {
$error_info = $this->pdo->errorInfo();
throw new Excepcion($error_info[2], [
'sentencia' => $this->sentencia,
'error_codigo' => $error_info[0],
], $error_info[1]);
}
return false;
}
return $resultado;
} | Ejecuta la sentencia interna.
@return bool
@throws \InvalidArgumentException
@throws Excepcion | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L311-L338 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.preparar | public function preparar()
{
// Validamos la sentencia a preparar
if (empty($this->sentencia)) {
if ($this->arrojarExcepciones) {
throw new \InvalidArgumentException('La sentencia a preparar se encuentra vacia.');
}
}
return $this->pdo->prepare($this->sentencia);
} | php | public function preparar()
{
// Validamos la sentencia a preparar
if (empty($this->sentencia)) {
if ($this->arrojarExcepciones) {
throw new \InvalidArgumentException('La sentencia a preparar se encuentra vacia.');
}
}
return $this->pdo->prepare($this->sentencia);
} | Prepara la sentencia interna para su uso exterior.
@throws \Exception
@return \PDOStatement | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L359-L369 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.seleccionar | public function seleccionar($campos, $tabla)
{
if (is_array($campos)) {
$this->sentencia = 'SELECT ' . implode(', ', $campos);
} else {
$this->sentencia = 'SELECT ' . $campos;
}
$this->sentencia .= ' FROM ' . $tabla;
return $this;
} | php | public function seleccionar($campos, $tabla)
{
if (is_array($campos)) {
$this->sentencia = 'SELECT ' . implode(', ', $campos);
} else {
$this->sentencia = 'SELECT ' . $campos;
}
$this->sentencia .= ' FROM ' . $tabla;
return $this;
} | Inicia la sentencia interna con SELECT.
@param string|array $campos
@param string $tabla
@return Relacional | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L447-L457 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.donde | public function donde(array $params = null)
{
if ($params) {
$terminos_sql = [];
foreach ($params as $llave => $valor) {
// Limpiamos la llave
$llave = trim($llave);
// Extraemos operador
if (false === ($temp = strpos($llave, ' '))) {
$restante = $llave;
} else {
$restante = substr($llave, 0, $temp);
$operador = substr($llave, $temp + 1);
}
if (empty($operador)) {
if (is_array($valor)) {
$operador = 'IN';
} else {
$operador = '=';
}
}
// Extramos campo y su tipo
if (false !== ($temp = strpos($restante, '|'))) {
$tipo = substr($restante, $temp + 1);
$campo = substr($restante, 0, $temp);
} else {
$campo = $restante;
}
if (empty($tipo)) $tipo = 'txt';
// Preparamos el valor segun el tipo de campo
if (is_array($valor)) {
$valor_preparado = '(' . implode(',', $this->prepararValor($valor, $tipo)) . ')';
} else {
$valor_preparado = $this->prepararValor($valor, $tipo);
}
// Escribimos el termino dentro de los filtros
$terminos_sql[] = "{$campo} {$operador} {$valor_preparado}";
// Limpiamos las variables repetitivas
unset($restante, $campo, $operador, $tipo);
}
// Escribimos todos los terminos en formato SQL
$this->sentencia .= ' WHERE ' . implode(' AND ', $terminos_sql);
}
return $this;
} | php | public function donde(array $params = null)
{
if ($params) {
$terminos_sql = [];
foreach ($params as $llave => $valor) {
// Limpiamos la llave
$llave = trim($llave);
// Extraemos operador
if (false === ($temp = strpos($llave, ' '))) {
$restante = $llave;
} else {
$restante = substr($llave, 0, $temp);
$operador = substr($llave, $temp + 1);
}
if (empty($operador)) {
if (is_array($valor)) {
$operador = 'IN';
} else {
$operador = '=';
}
}
// Extramos campo y su tipo
if (false !== ($temp = strpos($restante, '|'))) {
$tipo = substr($restante, $temp + 1);
$campo = substr($restante, 0, $temp);
} else {
$campo = $restante;
}
if (empty($tipo)) $tipo = 'txt';
// Preparamos el valor segun el tipo de campo
if (is_array($valor)) {
$valor_preparado = '(' . implode(',', $this->prepararValor($valor, $tipo)) . ')';
} else {
$valor_preparado = $this->prepararValor($valor, $tipo);
}
// Escribimos el termino dentro de los filtros
$terminos_sql[] = "{$campo} {$operador} {$valor_preparado}";
// Limpiamos las variables repetitivas
unset($restante, $campo, $operador, $tipo);
}
// Escribimos todos los terminos en formato SQL
$this->sentencia .= ' WHERE ' . implode(' AND ', $terminos_sql);
}
return $this;
} | Prepara los campos que filtran la sentencia interna.
@param array|null $params Campos parametrizados
@return Relacional | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L484-L537 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.limitar | public function limitar($pos, $limite = null)
{
if ($limite) {
$this->sentencia .= ' LIMIT ' . $pos . ',' . $limite;
} else {
$this->sentencia .= ' LIMIT ' . $pos;
}
return $this;
} | php | public function limitar($pos, $limite = null)
{
if ($limite) {
$this->sentencia .= ' LIMIT ' . $pos . ',' . $limite;
} else {
$this->sentencia .= ' LIMIT ' . $pos;
}
return $this;
} | Implementa LIMIT a la sentencia interna.
@param int $pos
@param int $limite
@return Relacional | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L575-L584 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.actualizar | public function actualizar($tabla, array $params)
{
$terminos_sql = [];
foreach ($params as $llave => $valor) {
// Extramos campo y su tipo
$temp = explode('|', $llave);
$campo = $temp[0];
if (isset($temp[1])) {
$tipo = $temp[1];
} else {
$tipo = 'auto';
}
$terminos_sql[] = $campo . ' = ' . $this->prepararValor($valor, $tipo);
}
$this->sentencia = 'UPDATE ' . $tabla . ' SET ' . implode(', ', $terminos_sql);
return $this;
} | php | public function actualizar($tabla, array $params)
{
$terminos_sql = [];
foreach ($params as $llave => $valor) {
// Extramos campo y su tipo
$temp = explode('|', $llave);
$campo = $temp[0];
if (isset($temp[1])) {
$tipo = $temp[1];
} else {
$tipo = 'auto';
}
$terminos_sql[] = $campo . ' = ' . $this->prepararValor($valor, $tipo);
}
$this->sentencia = 'UPDATE ' . $tabla . ' SET ' . implode(', ', $terminos_sql);
return $this;
} | Inicia la sentencia interna con UPDATE.
@param string $tabla
@param array $params Campos parametrizados
@return Relacional | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L594-L613 |
armazon/armazon | src/Armazon/Bd/Relacional.php | Relacional.insertar | public function insertar($tabla, array $params)
{
$columnas = [];
$valores = [];
foreach ($params as $llave => $valor) {
// Extramos campo y su tipo
$temp = explode('|', $llave);
$campo = $temp[0];
if (isset($temp[1])) {
$tipo = $temp[1];
} else {
$tipo = 'auto';
}
$columnas[] = $campo;
$valores[] = $this->prepararValor($valor, $tipo);
}
$this->sentencia = 'INSERT INTO ' . $tabla . ' (' . implode(', ', $columnas) . ') VALUES (' . implode(', ', $valores) . ')';
return $this;
} | php | public function insertar($tabla, array $params)
{
$columnas = [];
$valores = [];
foreach ($params as $llave => $valor) {
// Extramos campo y su tipo
$temp = explode('|', $llave);
$campo = $temp[0];
if (isset($temp[1])) {
$tipo = $temp[1];
} else {
$tipo = 'auto';
}
$columnas[] = $campo;
$valores[] = $this->prepararValor($valor, $tipo);
}
$this->sentencia = 'INSERT INTO ' . $tabla . ' (' . implode(', ', $columnas) . ') VALUES (' . implode(', ', $valores) . ')';
return $this;
} | Inicia la sentencia interna con INSERT.
@param string $tabla Tabla
@param array $params Campos parametrizados
@return Relacional | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L623-L645 |
brainexe/core | src/DependencyInjection/CompilerPass/ConsoleCompilerPass.php | ConsoleCompilerPass.process | public function process(ContainerBuilder $container)
{
$console = $container->getDefinition('Console');
$console->addMethodCall('setAutoExit', [false]);
$taggedServices = $container->findTaggedServiceIds(self::TAG);
$commands = [];
foreach (array_keys($taggedServices) as $serviceId) {
/** @var Command $command */
$command = $container->get($serviceId);
$proxyService = new Definition(ProxyCommand::class, [
new Reference('service_container'),
new Reference('Console'),
$serviceId,
$command->getName(),
$command->getDescription(),
$command->getAliases(),
$this->formatDefinition($command->getDefinition())
]);
$commands[] = $proxyService;
}
$console->addMethodCall('addCommands', [$commands]);
} | php | public function process(ContainerBuilder $container)
{
$console = $container->getDefinition('Console');
$console->addMethodCall('setAutoExit', [false]);
$taggedServices = $container->findTaggedServiceIds(self::TAG);
$commands = [];
foreach (array_keys($taggedServices) as $serviceId) {
/** @var Command $command */
$command = $container->get($serviceId);
$proxyService = new Definition(ProxyCommand::class, [
new Reference('service_container'),
new Reference('Console'),
$serviceId,
$command->getName(),
$command->getDescription(),
$command->getAliases(),
$this->formatDefinition($command->getDefinition())
]);
$commands[] = $proxyService;
}
$console->addMethodCall('addCommands', [$commands]);
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/DependencyInjection/CompilerPass/ConsoleCompilerPass.php#L27-L52 |
PopSugar/php-yesmail-api | src/Yesmail/CurlClient.php | CurlClient.get | public function get($url, $data) {
curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($this->_ch, CURLOPT_URL, sprintf( "%s?%s", $url, http_build_query($data, '', '&', PHP_QUERY_RFC3986)));
curl_setopt($this->_ch, CURLOPT_HTTPHEADER, array("Accept:application/json", "Content-Type: application/json"));
return $this->_exec();
} | php | public function get($url, $data) {
curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($this->_ch, CURLOPT_URL, sprintf( "%s?%s", $url, http_build_query($data, '', '&', PHP_QUERY_RFC3986)));
curl_setopt($this->_ch, CURLOPT_HTTPHEADER, array("Accept:application/json", "Content-Type: application/json"));
return $this->_exec();
} | Perform an HTTP GET
@param string $url The URL to send the GET request to.
@param array $data An array of parameters to be added to the query string.
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/CurlClient.php#L61-L67 |
PopSugar/php-yesmail-api | src/Yesmail/CurlClient.php | CurlClient._initialize | protected function _initialize() {
$this->_ch = curl_init();
$this->_last_info = FALSE;
curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->_ch, CURLOPT_TIMEOUT, 60);
curl_setopt($this->_ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($this->_ch, CURLOPT_USERPWD, "{$this->_username}:{$this->_password}");
return;
} | php | protected function _initialize() {
$this->_ch = curl_init();
$this->_last_info = FALSE;
curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->_ch, CURLOPT_TIMEOUT, 60);
curl_setopt($this->_ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($this->_ch, CURLOPT_USERPWD, "{$this->_username}:{$this->_password}");
return;
} | Initialize the curl resource and options
@return void
@access protected | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/CurlClient.php#L136-L146 |
PopSugar/php-yesmail-api | src/Yesmail/CurlClient.php | CurlClient._exec | protected function _exec() {
$response = curl_exec($this->_ch);
$this->_last_info = curl_getinfo($this->_ch);
$error = curl_error( $this->_ch );
if ( $error ) {
throw new \Exception($error);
}
return $response;
} | php | protected function _exec() {
$response = curl_exec($this->_ch);
$this->_last_info = curl_getinfo($this->_ch);
$error = curl_error( $this->_ch );
if ( $error ) {
throw new \Exception($error);
}
return $response;
} | Execute a curl request. Maintain the info from the request in a variable
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access protected
@throws Exception | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/CurlClient.php#L155-L164 |
harp-orm/harp | src/Repo/LinkMap.php | LinkMap.get | public function get(AbstractModel $model)
{
if (! $this->repo->isModel($model)) {
throw new InvalidArgumentException(
sprintf('Model must be %s, was %s', $this->repo->getModelClass(), get_class($model))
);
}
if ($this->map->contains($model)) {
return $this->map[$model];
} else {
return $this->map[$model] = new Links($model);
}
} | php | public function get(AbstractModel $model)
{
if (! $this->repo->isModel($model)) {
throw new InvalidArgumentException(
sprintf('Model must be %s, was %s', $this->repo->getModelClass(), get_class($model))
);
}
if ($this->map->contains($model)) {
return $this->map[$model];
} else {
return $this->map[$model] = new Links($model);
}
} | Get Links object associated with this model.
If there is none, an empty Links object is created.
@param AbstractModel $model
@return Links
@throws InvalidArgumentException If model does not belong to repo | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Repo/LinkMap.php#L55-L68 |
carlosV2/DumbsmartRepositories | src/Relation/Relation.php | Relation.prepareToSave | public function prepareToSave(Transaction $transaction, $object)
{
$relation = $this;
$this->replaceField($object, function ($document) use ($transaction, $object, $relation) {
$relation->assertObjectOrNull($object, $document);
return ($document ? $transaction->save($document) : null);
});
} | php | public function prepareToSave(Transaction $transaction, $object)
{
$relation = $this;
$this->replaceField($object, function ($document) use ($transaction, $object, $relation) {
$relation->assertObjectOrNull($object, $document);
return ($document ? $transaction->save($document) : null);
});
} | {@inheritdoc} | https://github.com/carlosV2/DumbsmartRepositories/blob/4170d5e196003aa83b295c686bdce42987e22a14/src/Relation/Relation.php#L35-L44 |
carlosV2/DumbsmartRepositories | src/Relation/Relation.php | Relation.prepareToLoad | public function prepareToLoad(Transaction $transaction, $object)
{
$relation = $this;
$this->replaceField($object, function ($reference) use ($transaction, $object, $relation) {
$relation->assertReferenceOrNull($object, $reference);
return ($reference ? $transaction->findByReference($reference) : null);
});
} | php | public function prepareToLoad(Transaction $transaction, $object)
{
$relation = $this;
$this->replaceField($object, function ($reference) use ($transaction, $object, $relation) {
$relation->assertReferenceOrNull($object, $reference);
return ($reference ? $transaction->findByReference($reference) : null);
});
} | {@inheritdoc} | https://github.com/carlosV2/DumbsmartRepositories/blob/4170d5e196003aa83b295c686bdce42987e22a14/src/Relation/Relation.php#L49-L58 |
carlosV2/DumbsmartRepositories | src/Relation/Relation.php | Relation.assertObjectOrNull | public function assertObjectOrNull($object, $document)
{
if (!is_null($document) && !is_object($document)) {
throw new UnexpectedDocumentTypeException($object, $this->field, $document);
}
} | php | public function assertObjectOrNull($object, $document)
{
if (!is_null($document) && !is_object($document)) {
throw new UnexpectedDocumentTypeException($object, $this->field, $document);
}
} | @internal This method is public to make the code compliant with PHP 5.3. Do NOT rely on this method as
it can be removed at any point or have its visibility changed without previous warning.
@param object $object
@param mixed $document
@throws UnexpectedDocumentTypeException | https://github.com/carlosV2/DumbsmartRepositories/blob/4170d5e196003aa83b295c686bdce42987e22a14/src/Relation/Relation.php#L78-L83 |
carlosV2/DumbsmartRepositories | src/Relation/Relation.php | Relation.assertReferenceOrNull | public function assertReferenceOrNull($object, $document)
{
if (!is_null($document) && !$document instanceof Reference) {
throw new UnexpectedDocumentTypeException($object, $this->field, $document);
}
} | php | public function assertReferenceOrNull($object, $document)
{
if (!is_null($document) && !$document instanceof Reference) {
throw new UnexpectedDocumentTypeException($object, $this->field, $document);
}
} | @internal This method is public to make the code compliant with PHP 5.3. Do NOT rely on this method as
it can be removed at any point or have its visibility changed without previous warning.
@param object $object
@param mixed $document
@throws UnexpectedDocumentTypeException | https://github.com/carlosV2/DumbsmartRepositories/blob/4170d5e196003aa83b295c686bdce42987e22a14/src/Relation/Relation.php#L94-L99 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.start | private function start() {
if (file_exists($this->pidFile)) {
_throw('事件监听守护进程已经在运行中');
}
$queueServices = $this->extraQueueServices();
//如果没有(需要)队列化的异步事件
if (empty($queueServices)) {
_throw('没有需要队列化的异步事件');
}
//当前进程转为守护进程
$this->daemon();
//为每个事件队列分别开启一个工作进程
foreach ($queueServices as $queueServiceName) {
$this->startWorker($queueServiceName);
}
//主进程做一些管理工作
while (true) {
//如果收到SIGTERM信号要求退出,且工作进程已经全部退出,则删除PID文件,然后退出
if ($this->shouldExit && empty($this->workerMap)) {
$this->log('[master] 工作进程已经全部退出,结束运行,进程ID:' . getmypid());
unlink($this->pidFile);
exit(0);
}
pcntl_signal_dispatch();
$this->waitWorker();
sleep(3);
}
} | php | private function start() {
if (file_exists($this->pidFile)) {
_throw('事件监听守护进程已经在运行中');
}
$queueServices = $this->extraQueueServices();
//如果没有(需要)队列化的异步事件
if (empty($queueServices)) {
_throw('没有需要队列化的异步事件');
}
//当前进程转为守护进程
$this->daemon();
//为每个事件队列分别开启一个工作进程
foreach ($queueServices as $queueServiceName) {
$this->startWorker($queueServiceName);
}
//主进程做一些管理工作
while (true) {
//如果收到SIGTERM信号要求退出,且工作进程已经全部退出,则删除PID文件,然后退出
if ($this->shouldExit && empty($this->workerMap)) {
$this->log('[master] 工作进程已经全部退出,结束运行,进程ID:' . getmypid());
unlink($this->pidFile);
exit(0);
}
pcntl_signal_dispatch();
$this->waitWorker();
sleep(3);
}
} | 启动
示例:
./console event:listend
./console event:listend start | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L101-L134 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.extraQueueServices | private function extraQueueServices() {
$eventConfig = $this->appContext->getAppSetting()->getEvents();
if (empty($eventConfig)) {
return [];
}
/* @var $classMetadataLoader ClassMetadataLoader */
$classMetadataLoader = $this->appContext->getService('classMetadataLoader');
$queueServices = [];
foreach (array_keys($eventConfig) as $eventName) {
$classMetadata = $classMetadataLoader->load($eventName);
//如果不是队列化的异步事件
if (!isset($classMetadata['classMetadata']['queued'])) {
continue;
}
$queueServiceName = $classMetadata['classMetadata']['queued'];
if ($queueServiceName === true) {
$queueServiceName = 'defaultEventQueue';
}
if (!in_array($queueServiceName, $queueServices)) {
$queueServices[] = $queueServiceName;
}
}
return $queueServices;
} | php | private function extraQueueServices() {
$eventConfig = $this->appContext->getAppSetting()->getEvents();
if (empty($eventConfig)) {
return [];
}
/* @var $classMetadataLoader ClassMetadataLoader */
$classMetadataLoader = $this->appContext->getService('classMetadataLoader');
$queueServices = [];
foreach (array_keys($eventConfig) as $eventName) {
$classMetadata = $classMetadataLoader->load($eventName);
//如果不是队列化的异步事件
if (!isset($classMetadata['classMetadata']['queued'])) {
continue;
}
$queueServiceName = $classMetadata['classMetadata']['queued'];
if ($queueServiceName === true) {
$queueServiceName = 'defaultEventQueue';
}
if (!in_array($queueServiceName, $queueServices)) {
$queueServices[] = $queueServiceName;
}
}
return $queueServices;
} | 提取出所有的事件队列名称
@return array | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L141-L170 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.daemon | private function daemon() {
//先检查一下运行用户配置情况
list($userInfo, $groupInfo) = $this->checkUser();
//
umask(0);
//fuck一下
$pid = pcntl_fork();
//创建子进程出错
if ($pid < 0) {
_throw('转为守护进程失败:创建子进程出错');
}
//父进程,退出
elseif ($pid) {
exit(0);
}
//使当前进程成为会话领导进程(从控制终端脱离)
if (posix_setsid() == -1) {
_throw('转为守护进程失败:设置当前进程为会话领导进程出错');
}
//切换工作目录到根目录
chdir('/');
//关闭标准输入、输出、错误,并都重定向到/dev/null
//应用如果有输出日志消息的需求,那么最好定义自己的logger
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
fopen('/dev/null', 'r');
fopen('/dev/null', 'a');
fopen('/dev/null', 'a');
//设置信号处理器
$sigHandler = [$this, 'sigTermHandler'];
pcntl_signal(SIGTERM, $sigHandler);
pcntl_signal(SIGHUP, SIG_IGN);
//切换运行用户和用户组。switchUser方法执行之前进程所属用户是root用户,
//执行之后,就是某个低权限用户
$this->switchUser($userInfo, $groupInfo);
//把主进程ID写入pid文件中
file_put_contents($this->pidFile, getmypid());
//设置进程标题
$projectName = $this->getProjectName();
cli_set_process_title("{$projectName}.event-listend");
$this->log('[master] 启动成功,进程ID:' . getmypid());
} | php | private function daemon() {
//先检查一下运行用户配置情况
list($userInfo, $groupInfo) = $this->checkUser();
//
umask(0);
//fuck一下
$pid = pcntl_fork();
//创建子进程出错
if ($pid < 0) {
_throw('转为守护进程失败:创建子进程出错');
}
//父进程,退出
elseif ($pid) {
exit(0);
}
//使当前进程成为会话领导进程(从控制终端脱离)
if (posix_setsid() == -1) {
_throw('转为守护进程失败:设置当前进程为会话领导进程出错');
}
//切换工作目录到根目录
chdir('/');
//关闭标准输入、输出、错误,并都重定向到/dev/null
//应用如果有输出日志消息的需求,那么最好定义自己的logger
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
fopen('/dev/null', 'r');
fopen('/dev/null', 'a');
fopen('/dev/null', 'a');
//设置信号处理器
$sigHandler = [$this, 'sigTermHandler'];
pcntl_signal(SIGTERM, $sigHandler);
pcntl_signal(SIGHUP, SIG_IGN);
//切换运行用户和用户组。switchUser方法执行之前进程所属用户是root用户,
//执行之后,就是某个低权限用户
$this->switchUser($userInfo, $groupInfo);
//把主进程ID写入pid文件中
file_put_contents($this->pidFile, getmypid());
//设置进程标题
$projectName = $this->getProjectName();
cli_set_process_title("{$projectName}.event-listend");
$this->log('[master] 启动成功,进程ID:' . getmypid());
} | 转为守护进程 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L175-L228 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.checkUser | private function checkUser() {
//事件监听守护进程的配置(跟事件及其监听器的配置是两码事)
$config = $this->appContext->getConfig('eventListend') ?: [];
$username = isset($config['user']) ? $config['user'] : 'nobody';
$groupName = isset($config['group']) ? $config['group'] : 'nobody';
$userInfo = posix_getpwnam($username);
if (!$userInfo) {
_throw("用户“{$username}”不存在,启动失败");
}
$groupInfo = posix_getgrnam($groupName);
if (!$groupInfo) {
_throw("用户组“{$groupName}”不存在,启动失败");
}
return [$userInfo, $groupInfo];
} | php | private function checkUser() {
//事件监听守护进程的配置(跟事件及其监听器的配置是两码事)
$config = $this->appContext->getConfig('eventListend') ?: [];
$username = isset($config['user']) ? $config['user'] : 'nobody';
$groupName = isset($config['group']) ? $config['group'] : 'nobody';
$userInfo = posix_getpwnam($username);
if (!$userInfo) {
_throw("用户“{$username}”不存在,启动失败");
}
$groupInfo = posix_getgrnam($groupName);
if (!$groupInfo) {
_throw("用户组“{$groupName}”不存在,启动失败");
}
return [$userInfo, $groupInfo];
} | 先检查一下运行用户配置情况
@throws Exception 如果检查失败,则抛出异常
@return array 成功的情况下会返回用户及用户组信息,格式:[用户信息, 用户组信息] | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L236-L253 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.switchUser | private function switchUser($userInfo, $groupInfo) {
//准备PID文件目录,并变更其所属的用户和用户组。此时还是root用户。
$pidDir = dirname($this->pidFile);
if (!is_dir($pidDir)) {
mkdir($pidDir, 0755);
}
chown($pidDir, $userInfo['uid']);
chgrp($pidDir, $groupInfo['gid']);
//切换用户
posix_setuid($userInfo['uid']);
posix_seteuid($userInfo['uid']);
posix_setgid($groupInfo['gid']);
posix_setegid($groupInfo['gid']);
} | php | private function switchUser($userInfo, $groupInfo) {
//准备PID文件目录,并变更其所属的用户和用户组。此时还是root用户。
$pidDir = dirname($this->pidFile);
if (!is_dir($pidDir)) {
mkdir($pidDir, 0755);
}
chown($pidDir, $userInfo['uid']);
chgrp($pidDir, $groupInfo['gid']);
//切换用户
posix_setuid($userInfo['uid']);
posix_seteuid($userInfo['uid']);
posix_setgid($groupInfo['gid']);
posix_setegid($groupInfo['gid']);
} | 切换运行用户和用户组 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L258-L272 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.sigTermHandler | private function sigTermHandler($signo) {
//主进程收到SIGTERM信号,设置标志,挨个向工作进程发送SIGTERM信号
if ($this->isMaster) {
$this->log('[master] 收到SIGTERM信号,向各个工作进程发送SIGTERM信号');
$this->shouldExit = true;
foreach (array_keys($this->workerMap) as $workPid) {
posix_kill($workPid, SIGTERM);
}
}
//工作进程收到SIGTERM信号,退出运行
else {
$this->log('[worker] 收到SIGTERM信号,退出运行,进程ID:' . getmypid());
exit(0);
}
} | php | private function sigTermHandler($signo) {
//主进程收到SIGTERM信号,设置标志,挨个向工作进程发送SIGTERM信号
if ($this->isMaster) {
$this->log('[master] 收到SIGTERM信号,向各个工作进程发送SIGTERM信号');
$this->shouldExit = true;
foreach (array_keys($this->workerMap) as $workPid) {
posix_kill($workPid, SIGTERM);
}
}
//工作进程收到SIGTERM信号,退出运行
else {
$this->log('[worker] 收到SIGTERM信号,退出运行,进程ID:' . getmypid());
exit(0);
}
} | SIGTERM信号处理器
@param int $signo | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L279-L294 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.startWorker | private function startWorker($queueServiceName) {
$pid = pcntl_fork();
if ($pid == -1) {
$this->log("[master] 创建工作进程失败,队列服务名称:{$queueServiceName}", 'error');
}
//父进程
else if ($pid) {
$this->workerMap[$pid] = $queueServiceName;
}
//子进程
else {
$this->isMaster = false;
$this->log("[worker] 启动成功,进程ID:" . getmypid() . ",队列服务名称:{$queueServiceName}");
$this->listenQueue($queueServiceName);
//必须退出啊,不然就跑去执行主进程的代码了
exit(0);
}
} | php | private function startWorker($queueServiceName) {
$pid = pcntl_fork();
if ($pid == -1) {
$this->log("[master] 创建工作进程失败,队列服务名称:{$queueServiceName}", 'error');
}
//父进程
else if ($pid) {
$this->workerMap[$pid] = $queueServiceName;
}
//子进程
else {
$this->isMaster = false;
$this->log("[worker] 启动成功,进程ID:" . getmypid() . ",队列服务名称:{$queueServiceName}");
$this->listenQueue($queueServiceName);
//必须退出啊,不然就跑去执行主进程的代码了
exit(0);
}
} | 启动工作进程
@param string $queueServiceName | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L301-L321 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.listenQueue | private function listenQueue($queueServiceName) {
/* @var $queueService QueueInterface */
$queueService = $this->appContext->getService($queueServiceName);
/* @var $eventManager EventManagerInterface */
$eventManager = $this->appContext->getService('eventManager');
while (true) {
while (true) {
//出队并判断会不会是因为超时返回,如果是超时返回(返回值为null),则继续监听队列;
//如果不是超时而是异步事件到达(返回值不为null),则执行其对应的事件监听器
$event = $queueService->dequeue();
if (is_null($event)) {
break;
}
$eventManager->trigger($event, true);
pcntl_signal_dispatch();
}
pcntl_signal_dispatch();
}
} | php | private function listenQueue($queueServiceName) {
/* @var $queueService QueueInterface */
$queueService = $this->appContext->getService($queueServiceName);
/* @var $eventManager EventManagerInterface */
$eventManager = $this->appContext->getService('eventManager');
while (true) {
while (true) {
//出队并判断会不会是因为超时返回,如果是超时返回(返回值为null),则继续监听队列;
//如果不是超时而是异步事件到达(返回值不为null),则执行其对应的事件监听器
$event = $queueService->dequeue();
if (is_null($event)) {
break;
}
$eventManager->trigger($event, true);
pcntl_signal_dispatch();
}
pcntl_signal_dispatch();
}
} | 监听队列
@param string $queueServiceName 队列服务名称 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L328-L350 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.waitWorker | private function waitWorker() {
if (empty($this->workerMap)) {
return;
}
$status = 0;
if ($this->shouldExit) {
//收到SIGTERM信号要求退出,挨个等待工作进程,等到了就从workerMap里删除,
//没等到就下一次再来等
foreach (array_keys($this->workerMap) as $workerPid) {
$pid = pcntl_waitpid($workerPid, $status, WNOHANG);
if ($pid == $workerPid) {
unset($this->workerMap[$workerPid]);
$exitReason = $this->parseExitReason($status);
$this->log("[master] 工作进程“{$workerPid}”已退出运行,{$exitReason}");
}
}
} else {
$pid = pcntl_wait($status, WNOHANG);
//如果某个工作进程退出了,则启动一个新的工作进程
if ($pid > 0) {
$queueServiceName = $this->workerMap[$pid];
unset($this->workerMap[$pid]);
$exitReason = $this->parseExitReason($status);
$this->log("[master] 工作进程“{$pid}”已退出运行,{$exitReason},队列服务名称:{$queueServiceName},即将启动一个新的工作进程");
$this->startWorker($queueServiceName);
}
}
} | php | private function waitWorker() {
if (empty($this->workerMap)) {
return;
}
$status = 0;
if ($this->shouldExit) {
//收到SIGTERM信号要求退出,挨个等待工作进程,等到了就从workerMap里删除,
//没等到就下一次再来等
foreach (array_keys($this->workerMap) as $workerPid) {
$pid = pcntl_waitpid($workerPid, $status, WNOHANG);
if ($pid == $workerPid) {
unset($this->workerMap[$workerPid]);
$exitReason = $this->parseExitReason($status);
$this->log("[master] 工作进程“{$workerPid}”已退出运行,{$exitReason}");
}
}
} else {
$pid = pcntl_wait($status, WNOHANG);
//如果某个工作进程退出了,则启动一个新的工作进程
if ($pid > 0) {
$queueServiceName = $this->workerMap[$pid];
unset($this->workerMap[$pid]);
$exitReason = $this->parseExitReason($status);
$this->log("[master] 工作进程“{$pid}”已退出运行,{$exitReason},队列服务名称:{$queueServiceName},即将启动一个新的工作进程");
$this->startWorker($queueServiceName);
}
}
} | 等待工作进程 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L355-L387 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.parseExitReason | private function parseExitReason($status) {
if (pcntl_wifexited($status)) {
$exitCode = pcntl_wexitstatus($status);
return "退出原因:正常退出,退出状态码:{$exitCode}";
} elseif (pcntl_wifsignaled($status)) {
$sigNum = pcntl_wtermsig($status);
return "退出原因:被信号终止,信号代号:{$sigNum}";
}
return '退出原因:未知';
} | php | private function parseExitReason($status) {
if (pcntl_wifexited($status)) {
$exitCode = pcntl_wexitstatus($status);
return "退出原因:正常退出,退出状态码:{$exitCode}";
} elseif (pcntl_wifsignaled($status)) {
$sigNum = pcntl_wtermsig($status);
return "退出原因:被信号终止,信号代号:{$sigNum}";
}
return '退出原因:未知';
} | 解析工作进程退出原因
@param int $status
@return string | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L395-L405 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.log | private function log($msg, $level = 'info') {
static $logFile = null;
if (is_null($logFile)) {
$logDir = $this->appContext->getRuntimeDir() . '/log';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
$logFilePath = "$logDir/event-listend.log";
$logFile = fopen($logFilePath, 'a');
}
$time = date('Y-m-d H:i:s');
$logData = "[{$level}] [{$time}] {$msg}\n";
fwrite($logFile, $logData);
} | php | private function log($msg, $level = 'info') {
static $logFile = null;
if (is_null($logFile)) {
$logDir = $this->appContext->getRuntimeDir() . '/log';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
$logFilePath = "$logDir/event-listend.log";
$logFile = fopen($logFilePath, 'a');
}
$time = date('Y-m-d H:i:s');
$logData = "[{$level}] [{$time}] {$msg}\n";
fwrite($logFile, $logData);
} | 记录运行日志
@param string $msg
@param string $level 日志级别:info、error、warning | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L413-L427 |
zhengb302/LumengPHP | src/LumengPHP/Console/Commands/Job/Listend.php | Listend.stop | private function stop() {
if (!file_exists($this->pidFile)) {
_throw('事件监听守护进程尚未运行');
}
$masterPid = file_get_contents($this->pidFile);
posix_kill($masterPid, SIGTERM);
//检查是否已停止运行
while (file_exists($this->pidFile)) {
sleep(3);
}
echo "事件监听守护进程已停止运行\n";
} | php | private function stop() {
if (!file_exists($this->pidFile)) {
_throw('事件监听守护进程尚未运行');
}
$masterPid = file_get_contents($this->pidFile);
posix_kill($masterPid, SIGTERM);
//检查是否已停止运行
while (file_exists($this->pidFile)) {
sleep(3);
}
echo "事件监听守护进程已停止运行\n";
} | 停止
示例:
./console event:listend stop | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Console/Commands/Job/Listend.php#L435-L449 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.keys | public function keys(): \Traversable
{
foreach ($this->idMap->sourceIds() as $sourceId) {
if (!$this->idMap->hasTargetFor($sourceId)) {
continue;
}
foreach ($this->getKeysForSource($sourceId) as $propKey) {
yield $sourceId . '.' . $propKey;
}
}
} | php | public function keys(): \Traversable
{
foreach ($this->idMap->sourceIds() as $sourceId) {
if (!$this->idMap->hasTargetFor($sourceId)) {
continue;
}
foreach ($this->getKeysForSource($sourceId) as $propKey) {
yield $sourceId . '.' . $propKey;
}
}
} | {@inheritDoc} | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L121-L132 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.get | public function get(string $key): TranslationValueInterface
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
throw new NotSupportedException(
$this,
'Key ' . $key . ' is in bad format (need: [id].[prop-name])'
);
}
// [id].propname
if (null === ($extractor = $this->getExtractor($chunks[1]))) {
throw new NotSupportedException(
$this,
'Key "' . $key . '" is not supported (no extractor for "' . $chunks[1] . '" found)'
);
}
$sourceId = (int) $chunks[0];
$targetId = $this->idMap->getTargetIdFor($sourceId);
return $this->createValueReader($sourceId, $targetId, $extractor, implode('.', \array_slice($chunks, 2)));
} | php | public function get(string $key): TranslationValueInterface
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
throw new NotSupportedException(
$this,
'Key ' . $key . ' is in bad format (need: [id].[prop-name])'
);
}
// [id].propname
if (null === ($extractor = $this->getExtractor($chunks[1]))) {
throw new NotSupportedException(
$this,
'Key "' . $key . '" is not supported (no extractor for "' . $chunks[1] . '" found)'
);
}
$sourceId = (int) $chunks[0];
$targetId = $this->idMap->getTargetIdFor($sourceId);
return $this->createValueReader($sourceId, $targetId, $extractor, implode('.', \array_slice($chunks, 2)));
} | {@inheritDoc}
@throws NotSupportedException When the key is in bad format or the extractor can not be found. | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L139-L161 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.has | public function has(string $key): bool
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
return false;
}
// [id].propname
if (null === $this->getExtractor($chunks[1])) {
return false;
}
return $this->idMap->hasTargetFor((int) $chunks[0]);
} | php | public function has(string $key): bool
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
return false;
}
// [id].propname
if (null === $this->getExtractor($chunks[1])) {
return false;
}
return $this->idMap->hasTargetFor((int) $chunks[0]);
} | {@inheritDoc} | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L166-L179 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.getWritable | public function getWritable($key): WritableTranslationValueInterface
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
throw new NotSupportedException($this, 'Key ' . $key . ' is in bad format (need: [id].[prop-name])');
}
// [id].propname
if (null === ($extractor = $this->getExtractor($chunks[1]))) {
throw new NotSupportedException($this, 'Key ' . $key . ' is not supported (no extractor found)');
}
$sourceId = (int) $chunks[0];
$targetId = $this->idMap->getTargetIdFor($sourceId);
return $this->createValueWriter($sourceId, $targetId, $extractor, implode('.', \array_slice($chunks, 2)));
} | php | public function getWritable($key): WritableTranslationValueInterface
{
$chunks = explode('.', $key);
if (\count($chunks) < 2) {
throw new NotSupportedException($this, 'Key ' . $key . ' is in bad format (need: [id].[prop-name])');
}
// [id].propname
if (null === ($extractor = $this->getExtractor($chunks[1]))) {
throw new NotSupportedException($this, 'Key ' . $key . ' is not supported (no extractor found)');
}
$sourceId = (int) $chunks[0];
$targetId = $this->idMap->getTargetIdFor($sourceId);
return $this->createValueWriter($sourceId, $targetId, $extractor, implode('.', \array_slice($chunks, 2)));
} | {@inheritDoc}
@throws NotSupportedException When the key is in bad format or the extractor can not be found. | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L228-L244 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.getRow | public function getRow(int $idNumber): array
{
return (array) $this->getConnection()->createQueryBuilder()
->select('*')
->from($this->tableName)
->where('id=:id')
->setParameter('id', $idNumber)
->setMaxResults(1)
->execute()
->fetch(\PDO::FETCH_ASSOC);
} | php | public function getRow(int $idNumber): array
{
return (array) $this->getConnection()->createQueryBuilder()
->select('*')
->from($this->tableName)
->where('id=:id')
->setParameter('id', $idNumber)
->setMaxResults(1)
->execute()
->fetch(\PDO::FETCH_ASSOC);
} | Fetch a row.
@param int $idNumber The id to fetch.
@return array | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L263-L273 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.updateRow | public function updateRow(int $idNumber, array $values): void
{
$this->connection->update($this->tableName, $values, ['id' => $idNumber]);
} | php | public function updateRow(int $idNumber, array $values): void
{
$this->connection->update($this->tableName, $values, ['id' => $idNumber]);
} | Fetch a row.
@param int $idNumber The id to fetch.
@param array $values The row values to update.
@return void | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L283-L286 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.getKeysForSource | protected function getKeysForSource(int $sourceId): \Traversable
{
$row = $this->getRow($sourceId);
foreach ($this->extractors as $extractor) {
switch (true) {
case $extractor instanceof MultiStringExtractorInterface:
foreach ($extractor->keys($row) as $key) {
yield $extractor->name() . '.' . $key;
}
break;
case $extractor instanceof ExtractorInterface:
if ($extractor->supports($row)) {
yield $extractor->name();
}
break;
default:
throw new \InvalidArgumentException('Unknown extractor type ' . \get_class($extractor));
}
}
} | php | protected function getKeysForSource(int $sourceId): \Traversable
{
$row = $this->getRow($sourceId);
foreach ($this->extractors as $extractor) {
switch (true) {
case $extractor instanceof MultiStringExtractorInterface:
foreach ($extractor->keys($row) as $key) {
yield $extractor->name() . '.' . $key;
}
break;
case $extractor instanceof ExtractorInterface:
if ($extractor->supports($row)) {
yield $extractor->name();
}
break;
default:
throw new \InvalidArgumentException('Unknown extractor type ' . \get_class($extractor));
}
}
} | Get the keys for the source id.
@param int $sourceId The source id.
@return \Traversable|string[]
@throws \InvalidArgumentException When the extractor is unknown. | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L297-L316 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.createValueReader | protected function createValueReader(
int $sourceId,
int $targetId,
ExtractorInterface $extractor,
string $trail
): TranslationValueInterface {
return new TranslationValue($this, $sourceId, $targetId, $extractor, $trail);
} | php | protected function createValueReader(
int $sourceId,
int $targetId,
ExtractorInterface $extractor,
string $trail
): TranslationValueInterface {
return new TranslationValue($this, $sourceId, $targetId, $extractor, $trail);
} | Create a value reader instance.
@param int $sourceId The source id.
@param int $targetId The target id.
@param ExtractorInterface $extractor The extractor to use.
@param string $trail The trailing sub path.
@return TranslationValueInterface | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L340-L347 |
cyberspectrum/i18n-contao | src/ContaoTableDictionary.php | ContaoTableDictionary.createValueWriter | protected function createValueWriter(
int $sourceId,
int $targetId,
ExtractorInterface $extractor,
string $trail
): WritableTranslationValueInterface {
return new WritableTranslationValue($this, $sourceId, $targetId, $extractor, $trail);
} | php | protected function createValueWriter(
int $sourceId,
int $targetId,
ExtractorInterface $extractor,
string $trail
): WritableTranslationValueInterface {
return new WritableTranslationValue($this, $sourceId, $targetId, $extractor, $trail);
} | Create a value writer instance.
@param int $sourceId The source id.
@param int $targetId The target id.
@param ExtractorInterface $extractor The extractor to use.
@param string $trail The trailing sub path.
@return WritableTranslationValueInterface | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L359-L366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.