id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
30,900
dshanske/parse-this
includes/Parser.php
Parser.isElementParsed
private function isElementParsed(\DOMElement $e, $prefix) { if (!$this->parsed->contains($e)) { return false; } $prefixes = $this->parsed[$e]; if (!in_array($prefix, $prefixes)) { return false; } return true; }
php
private function isElementParsed(\DOMElement $e, $prefix) { if (!$this->parsed->contains($e)) { return false; } $prefixes = $this->parsed[$e]; if (!in_array($prefix, $prefixes)) { return false; } return true; }
[ "private", "function", "isElementParsed", "(", "\\", "DOMElement", "$", "e", ",", "$", "prefix", ")", "{", "if", "(", "!", "$", "this", "->", "parsed", "->", "contains", "(", "$", "e", ")", ")", "{", "return", "false", ";", "}", "$", "prefixes", "=", "$", "this", "->", "parsed", "[", "$", "e", "]", ";", "if", "(", "!", "in_array", "(", "$", "prefix", ",", "$", "prefixes", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determine if the element has already been parsed @param DOMElement $e @param string $prefix @return bool
[ "Determine", "if", "the", "element", "has", "already", "been", "parsed" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L421-L433
30,901
dshanske/parse-this
includes/Parser.php
Parser.isElementUpgraded
private function isElementUpgraded(\DOMElement $el, $property) { if ( $this->upgraded->contains($el) ) { if ( in_array($property, $this->upgraded[$el]) ) { return true; } } return false; }
php
private function isElementUpgraded(\DOMElement $el, $property) { if ( $this->upgraded->contains($el) ) { if ( in_array($property, $this->upgraded[$el]) ) { return true; } } return false; }
[ "private", "function", "isElementUpgraded", "(", "\\", "DOMElement", "$", "el", ",", "$", "property", ")", "{", "if", "(", "$", "this", "->", "upgraded", "->", "contains", "(", "$", "el", ")", ")", "{", "if", "(", "in_array", "(", "$", "property", ",", "$", "this", "->", "upgraded", "[", "$", "el", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine if the element's specified property has already been upgraded during backcompat @param DOMElement $el @param string $property @return bool
[ "Determine", "if", "the", "element", "s", "specified", "property", "has", "already", "been", "upgraded", "during", "backcompat" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L441-L449
30,902
dshanske/parse-this
includes/Parser.php
Parser.textContent
public function textContent(DOMElement $element, $implied=false) { return preg_replace( '/(^[\t\n\f\r ]+| +(?=\n)|(?<=\n) +| +(?= )|[\t\n\f\r ]+$)/', '', $this->elementToString($element, $implied) ); }
php
public function textContent(DOMElement $element, $implied=false) { return preg_replace( '/(^[\t\n\f\r ]+| +(?=\n)|(?<=\n) +| +(?= )|[\t\n\f\r ]+$)/', '', $this->elementToString($element, $implied) ); }
[ "public", "function", "textContent", "(", "DOMElement", "$", "element", ",", "$", "implied", "=", "false", ")", "{", "return", "preg_replace", "(", "'/(^[\\t\\n\\f\\r ]+| +(?=\\n)|(?<=\\n) +| +(?= )|[\\t\\n\\f\\r ]+$)/'", ",", "''", ",", "$", "this", "->", "elementToString", "(", "$", "element", ",", "$", "implied", ")", ")", ";", "}" ]
The following two methods implements plain text parsing. @param DOMElement $element @param bool $implied @see https://wiki.zegnat.net/media/textparsing.html
[ "The", "following", "two", "methods", "implements", "plain", "text", "parsing", "." ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L472-L479
30,903
dshanske/parse-this
includes/Parser.php
Parser.language
public function language(DOMElement $el) { // element has a lang attribute; use it if ($el->hasAttribute('lang')) { return unicodeTrim($el->getAttribute('lang')); } if ($el->tagName == 'html') { // we're at the <html> element and no lang; check <meta> http-equiv Content-Language foreach ( $this->xpath->query('.//meta[@http-equiv]') as $node ) { if ($node->hasAttribute('http-equiv') && $node->hasAttribute('content') && strtolower($node->getAttribute('http-equiv')) == 'content-language') { return unicodeTrim($node->getAttribute('content')); } } } elseif ($el->parentNode instanceof DOMElement) { // check the parent node return $this->language($el->parentNode); } return ''; }
php
public function language(DOMElement $el) { // element has a lang attribute; use it if ($el->hasAttribute('lang')) { return unicodeTrim($el->getAttribute('lang')); } if ($el->tagName == 'html') { // we're at the <html> element and no lang; check <meta> http-equiv Content-Language foreach ( $this->xpath->query('.//meta[@http-equiv]') as $node ) { if ($node->hasAttribute('http-equiv') && $node->hasAttribute('content') && strtolower($node->getAttribute('http-equiv')) == 'content-language') { return unicodeTrim($node->getAttribute('content')); } } } elseif ($el->parentNode instanceof DOMElement) { // check the parent node return $this->language($el->parentNode); } return ''; }
[ "public", "function", "language", "(", "DOMElement", "$", "el", ")", "{", "// element has a lang attribute; use it", "if", "(", "$", "el", "->", "hasAttribute", "(", "'lang'", ")", ")", "{", "return", "unicodeTrim", "(", "$", "el", "->", "getAttribute", "(", "'lang'", ")", ")", ";", "}", "if", "(", "$", "el", "->", "tagName", "==", "'html'", ")", "{", "// we're at the <html> element and no lang; check <meta> http-equiv Content-Language", "foreach", "(", "$", "this", "->", "xpath", "->", "query", "(", "'.//meta[@http-equiv]'", ")", "as", "$", "node", ")", "{", "if", "(", "$", "node", "->", "hasAttribute", "(", "'http-equiv'", ")", "&&", "$", "node", "->", "hasAttribute", "(", "'content'", ")", "&&", "strtolower", "(", "$", "node", "->", "getAttribute", "(", "'http-equiv'", ")", ")", "==", "'content-language'", ")", "{", "return", "unicodeTrim", "(", "$", "node", "->", "getAttribute", "(", "'content'", ")", ")", ";", "}", "}", "}", "elseif", "(", "$", "el", "->", "parentNode", "instanceof", "DOMElement", ")", "{", "// check the parent node", "return", "$", "this", "->", "language", "(", "$", "el", "->", "parentNode", ")", ";", "}", "return", "''", ";", "}" ]
This method parses the language of an element @param DOMElement $el @access public @return string
[ "This", "method", "parses", "the", "language", "of", "an", "element" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L514-L535
30,904
dshanske/parse-this
includes/Parser.php
Parser.parseE
public function parseE(\DOMElement $e) { $classTitle = $this->parseValueClassTitle($e); if ($classTitle !== null) return $classTitle; // Expand relative URLs within children of this element // TODO: as it is this is not relative to only children, make this .// and rerun tests $this->resolveChildUrls($e); // Temporarily move all descendants into a separate DocumentFragment. // This way we can DOMDocument::saveHTML on the entire collection at once. // Running DOMDocument::saveHTML per node may add whitespace that isn't in source. // See https://stackoverflow.com/q/38317903 $innerNodes = $e->ownerDocument->createDocumentFragment(); while ($e->hasChildNodes()) { $innerNodes->appendChild($e->firstChild); } $html = $e->ownerDocument->saveHtml($innerNodes); // Put the nodes back in place. if($innerNodes->hasChildNodes()) { $e->appendChild($innerNodes); } $return = array( 'html' => unicodeTrim($html), 'value' => $this->textContent($e), ); if($this->lang) { // Language if ( $html_lang = $this->language($e) ) { $return['lang'] = $html_lang; } } return $return; }
php
public function parseE(\DOMElement $e) { $classTitle = $this->parseValueClassTitle($e); if ($classTitle !== null) return $classTitle; // Expand relative URLs within children of this element // TODO: as it is this is not relative to only children, make this .// and rerun tests $this->resolveChildUrls($e); // Temporarily move all descendants into a separate DocumentFragment. // This way we can DOMDocument::saveHTML on the entire collection at once. // Running DOMDocument::saveHTML per node may add whitespace that isn't in source. // See https://stackoverflow.com/q/38317903 $innerNodes = $e->ownerDocument->createDocumentFragment(); while ($e->hasChildNodes()) { $innerNodes->appendChild($e->firstChild); } $html = $e->ownerDocument->saveHtml($innerNodes); // Put the nodes back in place. if($innerNodes->hasChildNodes()) { $e->appendChild($innerNodes); } $return = array( 'html' => unicodeTrim($html), 'value' => $this->textContent($e), ); if($this->lang) { // Language if ( $html_lang = $this->language($e) ) { $return['lang'] = $html_lang; } } return $return; }
[ "public", "function", "parseE", "(", "\\", "DOMElement", "$", "e", ")", "{", "$", "classTitle", "=", "$", "this", "->", "parseValueClassTitle", "(", "$", "e", ")", ";", "if", "(", "$", "classTitle", "!==", "null", ")", "return", "$", "classTitle", ";", "// Expand relative URLs within children of this element", "// TODO: as it is this is not relative to only children, make this .// and rerun tests", "$", "this", "->", "resolveChildUrls", "(", "$", "e", ")", ";", "// Temporarily move all descendants into a separate DocumentFragment.", "// This way we can DOMDocument::saveHTML on the entire collection at once.", "// Running DOMDocument::saveHTML per node may add whitespace that isn't in source.", "// See https://stackoverflow.com/q/38317903", "$", "innerNodes", "=", "$", "e", "->", "ownerDocument", "->", "createDocumentFragment", "(", ")", ";", "while", "(", "$", "e", "->", "hasChildNodes", "(", ")", ")", "{", "$", "innerNodes", "->", "appendChild", "(", "$", "e", "->", "firstChild", ")", ";", "}", "$", "html", "=", "$", "e", "->", "ownerDocument", "->", "saveHtml", "(", "$", "innerNodes", ")", ";", "// Put the nodes back in place.", "if", "(", "$", "innerNodes", "->", "hasChildNodes", "(", ")", ")", "{", "$", "e", "->", "appendChild", "(", "$", "innerNodes", ")", ";", "}", "$", "return", "=", "array", "(", "'html'", "=>", "unicodeTrim", "(", "$", "html", ")", ",", "'value'", "=>", "$", "this", "->", "textContent", "(", "$", "e", ")", ",", ")", ";", "if", "(", "$", "this", "->", "lang", ")", "{", "// Language", "if", "(", "$", "html_lang", "=", "$", "this", "->", "language", "(", "$", "e", ")", ")", "{", "$", "return", "[", "'lang'", "]", "=", "$", "html_lang", ";", "}", "}", "return", "$", "return", ";", "}" ]
Given the root element of some embedded markup, return a string representing that markup @param DOMElement $e The element to parse @return string $e’s innerHTML @todo need to mark this element as e- parsed so it doesn’t get parsed as it’s parent’s e-* too
[ "Given", "the", "root", "element", "of", "some", "embedded", "markup", "return", "a", "string", "representing", "that", "markup" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L861-L898
30,905
dshanske/parse-this
includes/Parser.php
Parser.parse
public function parse($convertClassic = true, DOMElement $context = null) { $this->convertClassic = $convertClassic; $mfs = $this->parse_recursive($context); // Parse rels list($rels, $rel_urls, $alternates) = $this->parseRelsAndAlternates(); $top = array( 'items' => array_values(array_filter($mfs)), 'rels' => $rels, 'rel-urls' => $rel_urls, ); if ($this->enableAlternates && count($alternates)) { $top['alternates'] = $alternates; } return $top; }
php
public function parse($convertClassic = true, DOMElement $context = null) { $this->convertClassic = $convertClassic; $mfs = $this->parse_recursive($context); // Parse rels list($rels, $rel_urls, $alternates) = $this->parseRelsAndAlternates(); $top = array( 'items' => array_values(array_filter($mfs)), 'rels' => $rels, 'rel-urls' => $rel_urls, ); if ($this->enableAlternates && count($alternates)) { $top['alternates'] = $alternates; } return $top; }
[ "public", "function", "parse", "(", "$", "convertClassic", "=", "true", ",", "DOMElement", "$", "context", "=", "null", ")", "{", "$", "this", "->", "convertClassic", "=", "$", "convertClassic", ";", "$", "mfs", "=", "$", "this", "->", "parse_recursive", "(", "$", "context", ")", ";", "// Parse rels", "list", "(", "$", "rels", ",", "$", "rel_urls", ",", "$", "alternates", ")", "=", "$", "this", "->", "parseRelsAndAlternates", "(", ")", ";", "$", "top", "=", "array", "(", "'items'", "=>", "array_values", "(", "array_filter", "(", "$", "mfs", ")", ")", ",", "'rels'", "=>", "$", "rels", ",", "'rel-urls'", "=>", "$", "rel_urls", ",", ")", ";", "if", "(", "$", "this", "->", "enableAlternates", "&&", "count", "(", "$", "alternates", ")", ")", "{", "$", "top", "[", "'alternates'", "]", "=", "$", "alternates", ";", "}", "return", "$", "top", ";", "}" ]
Kicks off the parsing routine @param bool $convertClassic whether to do backcompat parsing on microformats1. Defaults to true. @param DOMElement $context optionally specify an element from which to parse microformats @return array An array containing all the microformats found in the current document
[ "Kicks", "off", "the", "parsing", "routine" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L1349-L1367
30,906
dshanske/parse-this
includes/Parser.php
Parser.parseFromId
public function parseFromId($id, $convertClassic=true) { $matches = $this->xpath->query("//*[@id='{$id}']"); if (empty($matches)) return array('items' => array(), 'rels' => array(), 'alternates' => array()); return $this->parse($convertClassic, $matches->item(0)); }
php
public function parseFromId($id, $convertClassic=true) { $matches = $this->xpath->query("//*[@id='{$id}']"); if (empty($matches)) return array('items' => array(), 'rels' => array(), 'alternates' => array()); return $this->parse($convertClassic, $matches->item(0)); }
[ "public", "function", "parseFromId", "(", "$", "id", ",", "$", "convertClassic", "=", "true", ")", "{", "$", "matches", "=", "$", "this", "->", "xpath", "->", "query", "(", "\"//*[@id='{$id}']\"", ")", ";", "if", "(", "empty", "(", "$", "matches", ")", ")", "return", "array", "(", "'items'", "=>", "array", "(", ")", ",", "'rels'", "=>", "array", "(", ")", ",", "'alternates'", "=>", "array", "(", ")", ")", ";", "return", "$", "this", "->", "parse", "(", "$", "convertClassic", ",", "$", "matches", "->", "item", "(", "0", ")", ")", ";", "}" ]
Parse From ID Given an ID, parse all microformats which are children of the element with that ID. Note that rel values are still document-wide. If an element with the ID is not found, an empty skeleton mf2 array structure will be returned. @param string $id @param bool $htmlSafe = false whether or not to HTML-encode angle brackets in non e-* properties @return array
[ "Parse", "From", "ID" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L1467-L1474
30,907
dshanske/parse-this
includes/Parser.php
Parser.getRootMF
public function getRootMF(DOMElement $context = null) { // start with mf2 root class name xpath $xpaths = array( 'contains(concat(" ",normalize-space(@class)), " h-")' ); // add mf1 root class names foreach ( $this->classicRootMap as $old => $new ) { $xpaths[] = '( contains(concat(" ",normalize-space(@class), " "), " ' . $old . ' ") )'; } // final xpath with OR $xpath = '//*[' . implode(' or ', $xpaths) . ']'; $mfElements = (null === $context) ? $this->xpath->query($xpath) : $this->xpath->query('.' . $xpath, $context); return $mfElements; }
php
public function getRootMF(DOMElement $context = null) { // start with mf2 root class name xpath $xpaths = array( 'contains(concat(" ",normalize-space(@class)), " h-")' ); // add mf1 root class names foreach ( $this->classicRootMap as $old => $new ) { $xpaths[] = '( contains(concat(" ",normalize-space(@class), " "), " ' . $old . ' ") )'; } // final xpath with OR $xpath = '//*[' . implode(' or ', $xpaths) . ']'; $mfElements = (null === $context) ? $this->xpath->query($xpath) : $this->xpath->query('.' . $xpath, $context); return $mfElements; }
[ "public", "function", "getRootMF", "(", "DOMElement", "$", "context", "=", "null", ")", "{", "// start with mf2 root class name xpath", "$", "xpaths", "=", "array", "(", "'contains(concat(\" \",normalize-space(@class)), \" h-\")'", ")", ";", "// add mf1 root class names", "foreach", "(", "$", "this", "->", "classicRootMap", "as", "$", "old", "=>", "$", "new", ")", "{", "$", "xpaths", "[", "]", "=", "'( contains(concat(\" \",normalize-space(@class), \" \"), \" '", ".", "$", "old", ".", "' \") )'", ";", "}", "// final xpath with OR", "$", "xpath", "=", "'//*['", ".", "implode", "(", "' or '", ",", "$", "xpaths", ")", ".", "']'", ";", "$", "mfElements", "=", "(", "null", "===", "$", "context", ")", "?", "$", "this", "->", "xpath", "->", "query", "(", "$", "xpath", ")", ":", "$", "this", "->", "xpath", "->", "query", "(", "'.'", ".", "$", "xpath", ",", "$", "context", ")", ";", "return", "$", "mfElements", ";", "}" ]
Get the root microformat elements @param DOMElement $context @return DOMNodeList
[ "Get", "the", "root", "microformat", "elements" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L1481-L1500
30,908
dshanske/parse-this
includes/Parser.php
Parser.addUpgraded
public function addUpgraded(DOMElement $el, $property) { if ( !is_array($property) ) { $property = array($property); } // add element to list of upgraded elements if ( !$this->upgraded->contains($el) ) { $this->upgraded->attach($el, $property); } else { $this->upgraded[$el] = array_merge($this->upgraded[$el], $property); } }
php
public function addUpgraded(DOMElement $el, $property) { if ( !is_array($property) ) { $property = array($property); } // add element to list of upgraded elements if ( !$this->upgraded->contains($el) ) { $this->upgraded->attach($el, $property); } else { $this->upgraded[$el] = array_merge($this->upgraded[$el], $property); } }
[ "public", "function", "addUpgraded", "(", "DOMElement", "$", "el", ",", "$", "property", ")", "{", "if", "(", "!", "is_array", "(", "$", "property", ")", ")", "{", "$", "property", "=", "array", "(", "$", "property", ")", ";", "}", "// add element to list of upgraded elements", "if", "(", "!", "$", "this", "->", "upgraded", "->", "contains", "(", "$", "el", ")", ")", "{", "$", "this", "->", "upgraded", "->", "attach", "(", "$", "el", ",", "$", "property", ")", ";", "}", "else", "{", "$", "this", "->", "upgraded", "[", "$", "el", "]", "=", "array_merge", "(", "$", "this", "->", "upgraded", "[", "$", "el", "]", ",", "$", "property", ")", ";", "}", "}" ]
Add element + property as upgraded during backcompat @param DOMElement $el @param string|array $property
[ "Add", "element", "+", "property", "as", "upgraded", "during", "backcompat" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L1629-L1640
30,909
dshanske/parse-this
includes/Parser.php
Parser.addMfClasses
public function addMfClasses(DOMElement $el, $classes) { $existingClasses = str_replace(array("\t", "\n"), ' ', $el->getAttribute('class')); $existingClasses = array_filter(explode(' ', $existingClasses)); $addClasses = array_diff(explode(' ', $classes), $existingClasses); if ( $addClasses ) { $el->setAttribute('class', $el->getAttribute('class') . ' ' . implode(' ', $addClasses)); } }
php
public function addMfClasses(DOMElement $el, $classes) { $existingClasses = str_replace(array("\t", "\n"), ' ', $el->getAttribute('class')); $existingClasses = array_filter(explode(' ', $existingClasses)); $addClasses = array_diff(explode(' ', $classes), $existingClasses); if ( $addClasses ) { $el->setAttribute('class', $el->getAttribute('class') . ' ' . implode(' ', $addClasses)); } }
[ "public", "function", "addMfClasses", "(", "DOMElement", "$", "el", ",", "$", "classes", ")", "{", "$", "existingClasses", "=", "str_replace", "(", "array", "(", "\"\\t\"", ",", "\"\\n\"", ")", ",", "' '", ",", "$", "el", "->", "getAttribute", "(", "'class'", ")", ")", ";", "$", "existingClasses", "=", "array_filter", "(", "explode", "(", "' '", ",", "$", "existingClasses", ")", ")", ";", "$", "addClasses", "=", "array_diff", "(", "explode", "(", "' '", ",", "$", "classes", ")", ",", "$", "existingClasses", ")", ";", "if", "(", "$", "addClasses", ")", "{", "$", "el", "->", "setAttribute", "(", "'class'", ",", "$", "el", "->", "getAttribute", "(", "'class'", ")", ".", "' '", ".", "implode", "(", "' '", ",", "$", "addClasses", ")", ")", ";", "}", "}" ]
Add the provided classes to an element. Does not add duplicate if class name already exists. @param DOMElement $el @param string $classes
[ "Add", "the", "provided", "classes", "to", "an", "element", ".", "Does", "not", "add", "duplicate", "if", "class", "name", "already", "exists", "." ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L1648-L1657
30,910
dshanske/parse-this
includes/Parser.php
Parser.convertLegacy
public function convertLegacy() { $doc = $this->doc; $xp = new DOMXPath($doc); // replace all roots foreach ($this->classicRootMap as $old => $new) { foreach ($xp->query('//*[contains(concat(" ", @class, " "), " ' . $old . ' ") and not(contains(concat(" ", @class, " "), " ' . $new . ' "))]') as $el) { $el->setAttribute('class', $el->getAttribute('class') . ' ' . $new); } } foreach ($this->classicPropertyMap as $oldRoot => $properties) { $newRoot = $this->classicRootMap[$oldRoot]; foreach ($properties as $old => $data) { foreach ($xp->query('//*[contains(concat(" ", @class, " "), " ' . $oldRoot . ' ")]//*[contains(concat(" ", @class, " "), " ' . $old . ' ") and not(contains(concat(" ", @class, " "), " ' . $data['replace'] . ' "))]') as $el) { $el->setAttribute('class', $el->getAttribute('class') . ' ' . $data['replace']); } } } return $this; }
php
public function convertLegacy() { $doc = $this->doc; $xp = new DOMXPath($doc); // replace all roots foreach ($this->classicRootMap as $old => $new) { foreach ($xp->query('//*[contains(concat(" ", @class, " "), " ' . $old . ' ") and not(contains(concat(" ", @class, " "), " ' . $new . ' "))]') as $el) { $el->setAttribute('class', $el->getAttribute('class') . ' ' . $new); } } foreach ($this->classicPropertyMap as $oldRoot => $properties) { $newRoot = $this->classicRootMap[$oldRoot]; foreach ($properties as $old => $data) { foreach ($xp->query('//*[contains(concat(" ", @class, " "), " ' . $oldRoot . ' ")]//*[contains(concat(" ", @class, " "), " ' . $old . ' ") and not(contains(concat(" ", @class, " "), " ' . $data['replace'] . ' "))]') as $el) { $el->setAttribute('class', $el->getAttribute('class') . ' ' . $data['replace']); } } } return $this; }
[ "public", "function", "convertLegacy", "(", ")", "{", "$", "doc", "=", "$", "this", "->", "doc", ";", "$", "xp", "=", "new", "DOMXPath", "(", "$", "doc", ")", ";", "// replace all roots", "foreach", "(", "$", "this", "->", "classicRootMap", "as", "$", "old", "=>", "$", "new", ")", "{", "foreach", "(", "$", "xp", "->", "query", "(", "'//*[contains(concat(\" \", @class, \" \"), \" '", ".", "$", "old", ".", "' \") and not(contains(concat(\" \", @class, \" \"), \" '", ".", "$", "new", ".", "' \"))]'", ")", "as", "$", "el", ")", "{", "$", "el", "->", "setAttribute", "(", "'class'", ",", "$", "el", "->", "getAttribute", "(", "'class'", ")", ".", "' '", ".", "$", "new", ")", ";", "}", "}", "foreach", "(", "$", "this", "->", "classicPropertyMap", "as", "$", "oldRoot", "=>", "$", "properties", ")", "{", "$", "newRoot", "=", "$", "this", "->", "classicRootMap", "[", "$", "oldRoot", "]", ";", "foreach", "(", "$", "properties", "as", "$", "old", "=>", "$", "data", ")", "{", "foreach", "(", "$", "xp", "->", "query", "(", "'//*[contains(concat(\" \", @class, \" \"), \" '", ".", "$", "oldRoot", ".", "' \")]//*[contains(concat(\" \", @class, \" \"), \" '", ".", "$", "old", ".", "' \") and not(contains(concat(\" \", @class, \" \"), \" '", ".", "$", "data", "[", "'replace'", "]", ".", "' \"))]'", ")", "as", "$", "el", ")", "{", "$", "el", "->", "setAttribute", "(", "'class'", ",", "$", "el", "->", "getAttribute", "(", "'class'", ")", ".", "' '", ".", "$", "data", "[", "'replace'", "]", ")", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Convert Legacy Classnames Adds microformats2 classnames into a document containing only legacy semantic classnames. @return Parser $this
[ "Convert", "Legacy", "Classnames" ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/Parser.php#L1684-L1705
30,911
QuickenLoans/mcp-logger
src/FilterLogger.php
FilterLogger.setLevel
public function setLevel($level) { if (!array_key_exists($level, self::LEVEL_PRIORITIES)) { throw new Exception(self::ERR_INVALID_LEVEL); } $lowestPriority = self::LEVEL_PRIORITIES[$level]; $accepted = []; foreach (self::LEVEL_PRIORITIES as $level => $priority) { if ($priority > $lowestPriority) { continue; } $accepted[] = $level; } $this->acceptedLevels = $accepted; }
php
public function setLevel($level) { if (!array_key_exists($level, self::LEVEL_PRIORITIES)) { throw new Exception(self::ERR_INVALID_LEVEL); } $lowestPriority = self::LEVEL_PRIORITIES[$level]; $accepted = []; foreach (self::LEVEL_PRIORITIES as $level => $priority) { if ($priority > $lowestPriority) { continue; } $accepted[] = $level; } $this->acceptedLevels = $accepted; }
[ "public", "function", "setLevel", "(", "$", "level", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "level", ",", "self", "::", "LEVEL_PRIORITIES", ")", ")", "{", "throw", "new", "Exception", "(", "self", "::", "ERR_INVALID_LEVEL", ")", ";", "}", "$", "lowestPriority", "=", "self", "::", "LEVEL_PRIORITIES", "[", "$", "level", "]", ";", "$", "accepted", "=", "[", "]", ";", "foreach", "(", "self", "::", "LEVEL_PRIORITIES", "as", "$", "level", "=>", "$", "priority", ")", "{", "if", "(", "$", "priority", ">", "$", "lowestPriority", ")", "{", "continue", ";", "}", "$", "accepted", "[", "]", "=", "$", "level", ";", "}", "$", "this", "->", "acceptedLevels", "=", "$", "accepted", ";", "}" ]
Set the lowest priority log level. When setting this value, ensure it is a valid level as defined in `Psr\Log\LogLevel`. @param string $level @throws Exception @return void
[ "Set", "the", "lowest", "priority", "log", "level", "." ]
ec0960fc32de1a4c583b2447b99d0ef8c801f1ae
https://github.com/QuickenLoans/mcp-logger/blob/ec0960fc32de1a4c583b2447b99d0ef8c801f1ae/src/FilterLogger.php#L92-L110
30,912
dshanske/parse-this
includes/class-parse-this-html.php
Parse_This_HTML.limit_string
private static function limit_string( $value ) { $return = ''; if ( is_numeric( $value ) || is_bool( $value ) ) { $return = $value; } elseif ( is_string( $value ) ) { if ( mb_strlen( $value ) > 5000 ) { $return = mb_substr( $value, 0, 5000 ); } else { $return = $value; } // $return = html_entity_decode( $return, ENT_QUOTES, 'UTF-8' ); $return = sanitize_text_field( trim( $return ) ); } return $return; }
php
private static function limit_string( $value ) { $return = ''; if ( is_numeric( $value ) || is_bool( $value ) ) { $return = $value; } elseif ( is_string( $value ) ) { if ( mb_strlen( $value ) > 5000 ) { $return = mb_substr( $value, 0, 5000 ); } else { $return = $value; } // $return = html_entity_decode( $return, ENT_QUOTES, 'UTF-8' ); $return = sanitize_text_field( trim( $return ) ); } return $return; }
[ "private", "static", "function", "limit_string", "(", "$", "value", ")", "{", "$", "return", "=", "''", ";", "if", "(", "is_numeric", "(", "$", "value", ")", "||", "is_bool", "(", "$", "value", ")", ")", "{", "$", "return", "=", "$", "value", ";", "}", "elseif", "(", "is_string", "(", "$", "value", ")", ")", "{", "if", "(", "mb_strlen", "(", "$", "value", ")", ">", "5000", ")", "{", "$", "return", "=", "mb_substr", "(", "$", "value", ",", "0", ",", "5000", ")", ";", "}", "else", "{", "$", "return", "=", "$", "value", ";", "}", "// $return = html_entity_decode( $return, ENT_QUOTES, 'UTF-8' );", "$", "return", "=", "sanitize_text_field", "(", "trim", "(", "$", "return", ")", ")", ";", "}", "return", "$", "return", ";", "}" ]
Utility method to limit the length of a given string to 5,000 characters. @ignore @since 4.2.0 @param string $value String to limit. @return bool|int|string If boolean or integer, that value. If a string, the original value if fewer than 5,000 characters, a truncated version, otherwise an empty string.
[ "Utility", "method", "to", "limit", "the", "length", "of", "a", "given", "string", "to", "5", "000", "characters", "." ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/class-parse-this-html.php#L41-L58
30,913
dshanske/parse-this
includes/class-parse-this-html.php
Parse_This_HTML.limit_url
private static function limit_url( $url, $source_url ) { if ( ! is_string( $url ) ) { return ''; } // HTTP 1.1 allows 8000 chars but the "de-facto" standard supported in all current browsers is 2048. if ( strlen( $url ) > 2048 ) { return ''; // Return empty rather than a truncated/invalid URL } // Does not look like a URL. if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return ''; } $url = WP_Http::make_absolute_url( $url, $source_url ); return esc_url_raw( $url, array( 'http', 'https' ) ); }
php
private static function limit_url( $url, $source_url ) { if ( ! is_string( $url ) ) { return ''; } // HTTP 1.1 allows 8000 chars but the "de-facto" standard supported in all current browsers is 2048. if ( strlen( $url ) > 2048 ) { return ''; // Return empty rather than a truncated/invalid URL } // Does not look like a URL. if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return ''; } $url = WP_Http::make_absolute_url( $url, $source_url ); return esc_url_raw( $url, array( 'http', 'https' ) ); }
[ "private", "static", "function", "limit_url", "(", "$", "url", ",", "$", "source_url", ")", "{", "if", "(", "!", "is_string", "(", "$", "url", ")", ")", "{", "return", "''", ";", "}", "// HTTP 1.1 allows 8000 chars but the \"de-facto\" standard supported in all current browsers is 2048.", "if", "(", "strlen", "(", "$", "url", ")", ">", "2048", ")", "{", "return", "''", ";", "// Return empty rather than a truncated/invalid URL", "}", "// Does not look like a URL.", "if", "(", "!", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "''", ";", "}", "$", "url", "=", "WP_Http", "::", "make_absolute_url", "(", "$", "url", ",", "$", "source_url", ")", ";", "return", "esc_url_raw", "(", "$", "url", ",", "array", "(", "'http'", ",", "'https'", ")", ")", ";", "}" ]
Utility method to limit a given URL to 2,048 characters. @ignore @since 4.2.0 @param string $url URL to check for length and validity. @param string $source_url URL URL to use to resolve relative URLs @return string Escaped URL if of valid length (< 2048) and makeup. Empty string otherwise.
[ "Utility", "method", "to", "limit", "a", "given", "URL", "to", "2", "048", "characters", "." ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/class-parse-this-html.php#L70-L88
30,914
dshanske/parse-this
includes/class-parse-this-html.php
Parse_This_HTML.limit_img
private static function limit_img( $src, $source_url ) { $src = self::limit_url( $src, $source_url ); if ( preg_match( '!/ad[sx]?/!i', $src ) ) { // Ads return ''; } elseif ( preg_match( '!(/share-?this[^.]+?\.[a-z0-9]{3,4})(\?.*)?$!i', $src ) ) { // Share-this type button return ''; } elseif ( preg_match( '!/(spinner|loading|spacer|blank|rss)\.(gif|jpg|png)!i', $src ) ) { // Loaders, spinners, spacers return ''; } elseif ( preg_match( '!/([^./]+[-_])?(spinner|loading|spacer|blank)s?([-_][^./]+)?\.[a-z0-9]{3,4}!i', $src ) ) { // Fancy loaders, spinners, spacers return ''; } elseif ( preg_match( '!([^./]+[-_])?thumb[^.]*\.(gif|jpg|png)$!i', $src ) ) { // Thumbnails, too small, usually irrelevant to context return ''; } elseif ( false !== stripos( $src, '/wp-includes/' ) ) { // Classic WordPress interface images return ''; } elseif ( false !== stripos( $src, '/wp-content/themes' ) ) { // Anything within a WordPress theme directory return ''; } elseif ( false !== stripos( $src, '/wp-content/plugins' ) ) { // Anything within a WordPress plugin directory return ''; } elseif ( preg_match( '![^\d]\d{1,2}x\d+\.(gif|jpg|png)$!i', $src ) ) { // Most often tiny buttons/thumbs (< 100px wide) return ''; } elseif ( preg_match( '!/pixel\.(mathtag|quantserve)\.com!i', $src ) ) { // See mathtag.com and https://www.quantcast.com/how-we-do-it/iab-standard-measurement/how-we-collect-data/ return ''; } elseif ( preg_match( '!/[gb]\.gif(\?.+)?$!i', $src ) ) { // WordPress.com stats gif return ''; } // Optionally add additional limits return apply_filters( 'parse_this_img_filters', $src ); }
php
private static function limit_img( $src, $source_url ) { $src = self::limit_url( $src, $source_url ); if ( preg_match( '!/ad[sx]?/!i', $src ) ) { // Ads return ''; } elseif ( preg_match( '!(/share-?this[^.]+?\.[a-z0-9]{3,4})(\?.*)?$!i', $src ) ) { // Share-this type button return ''; } elseif ( preg_match( '!/(spinner|loading|spacer|blank|rss)\.(gif|jpg|png)!i', $src ) ) { // Loaders, spinners, spacers return ''; } elseif ( preg_match( '!/([^./]+[-_])?(spinner|loading|spacer|blank)s?([-_][^./]+)?\.[a-z0-9]{3,4}!i', $src ) ) { // Fancy loaders, spinners, spacers return ''; } elseif ( preg_match( '!([^./]+[-_])?thumb[^.]*\.(gif|jpg|png)$!i', $src ) ) { // Thumbnails, too small, usually irrelevant to context return ''; } elseif ( false !== stripos( $src, '/wp-includes/' ) ) { // Classic WordPress interface images return ''; } elseif ( false !== stripos( $src, '/wp-content/themes' ) ) { // Anything within a WordPress theme directory return ''; } elseif ( false !== stripos( $src, '/wp-content/plugins' ) ) { // Anything within a WordPress plugin directory return ''; } elseif ( preg_match( '![^\d]\d{1,2}x\d+\.(gif|jpg|png)$!i', $src ) ) { // Most often tiny buttons/thumbs (< 100px wide) return ''; } elseif ( preg_match( '!/pixel\.(mathtag|quantserve)\.com!i', $src ) ) { // See mathtag.com and https://www.quantcast.com/how-we-do-it/iab-standard-measurement/how-we-collect-data/ return ''; } elseif ( preg_match( '!/[gb]\.gif(\?.+)?$!i', $src ) ) { // WordPress.com stats gif return ''; } // Optionally add additional limits return apply_filters( 'parse_this_img_filters', $src ); }
[ "private", "static", "function", "limit_img", "(", "$", "src", ",", "$", "source_url", ")", "{", "$", "src", "=", "self", "::", "limit_url", "(", "$", "src", ",", "$", "source_url", ")", ";", "if", "(", "preg_match", "(", "'!/ad[sx]?/!i'", ",", "$", "src", ")", ")", "{", "// Ads", "return", "''", ";", "}", "elseif", "(", "preg_match", "(", "'!(/share-?this[^.]+?\\.[a-z0-9]{3,4})(\\?.*)?$!i'", ",", "$", "src", ")", ")", "{", "// Share-this type button", "return", "''", ";", "}", "elseif", "(", "preg_match", "(", "'!/(spinner|loading|spacer|blank|rss)\\.(gif|jpg|png)!i'", ",", "$", "src", ")", ")", "{", "// Loaders, spinners, spacers", "return", "''", ";", "}", "elseif", "(", "preg_match", "(", "'!/([^./]+[-_])?(spinner|loading|spacer|blank)s?([-_][^./]+)?\\.[a-z0-9]{3,4}!i'", ",", "$", "src", ")", ")", "{", "// Fancy loaders, spinners, spacers", "return", "''", ";", "}", "elseif", "(", "preg_match", "(", "'!([^./]+[-_])?thumb[^.]*\\.(gif|jpg|png)$!i'", ",", "$", "src", ")", ")", "{", "// Thumbnails, too small, usually irrelevant to context", "return", "''", ";", "}", "elseif", "(", "false", "!==", "stripos", "(", "$", "src", ",", "'/wp-includes/'", ")", ")", "{", "// Classic WordPress interface images", "return", "''", ";", "}", "elseif", "(", "false", "!==", "stripos", "(", "$", "src", ",", "'/wp-content/themes'", ")", ")", "{", "// Anything within a WordPress theme directory", "return", "''", ";", "}", "elseif", "(", "false", "!==", "stripos", "(", "$", "src", ",", "'/wp-content/plugins'", ")", ")", "{", "// Anything within a WordPress plugin directory", "return", "''", ";", "}", "elseif", "(", "preg_match", "(", "'![^\\d]\\d{1,2}x\\d+\\.(gif|jpg|png)$!i'", ",", "$", "src", ")", ")", "{", "// Most often tiny buttons/thumbs (< 100px wide)", "return", "''", ";", "}", "elseif", "(", "preg_match", "(", "'!/pixel\\.(mathtag|quantserve)\\.com!i'", ",", "$", "src", ")", ")", "{", "// See mathtag.com and https://www.quantcast.com/how-we-do-it/iab-standard-measurement/how-we-collect-data/", "return", "''", ";", "}", "elseif", "(", "preg_match", "(", "'!/[gb]\\.gif(\\?.+)?$!i'", ",", "$", "src", ")", ")", "{", "// WordPress.com stats gif", "return", "''", ";", "}", "// Optionally add additional limits", "return", "apply_filters", "(", "'parse_this_img_filters'", ",", "$", "src", ")", ";", "}" ]
Utility method to limit image source URLs. Excluded URLs include share-this type buttons, loaders, spinners, spacers, WordPress interface images, tiny buttons or thumbs, mathtag.com or quantserve.com images, or the WordPress.com stats gif. @param string $src Image source URL. @return string If not matched an excluded URL type, the original URL, empty string otherwise.
[ "Utility", "method", "to", "limit", "image", "source", "URLs", "." ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/class-parse-this-html.php#L100-L139
30,915
dshanske/parse-this
includes/class-parse-this-html.php
Parse_This_HTML.limit_embed
private static function limit_embed( $src, $source_url ) { $src = self::limit_url( $src, $source_url ); if ( empty( $src ) ) { return ''; } if ( preg_match( '!//(m|www)\.youtube\.com/(embed|v)/([^?]+)\?.+$!i', $src, $src_matches ) ) { // Embedded Youtube videos (www or mobile) $src = 'https://www.youtube.com/watch?v=' . $src_matches[3]; } elseif ( preg_match( '!//player\.vimeo\.com/video/([\d]+)([?/].*)?$!i', $src, $src_matches ) ) { // Embedded Vimeo iframe videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } elseif ( preg_match( '!//vimeo\.com/moogaloop\.swf\?clip_id=([\d]+)$!i', $src, $src_matches ) ) { // Embedded Vimeo Flash videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } elseif ( preg_match( '!//vine\.co/v/([^/]+)/embed!i', $src, $src_matches ) ) { // Embedded Vine videos $src = 'https://vine.co/v/' . $src_matches[1]; } elseif ( preg_match( '!//(www\.)?dailymotion\.com/embed/video/([^/?]+)([/?].+)?!i', $src, $src_matches ) ) { // Embedded Daily Motion videos $src = 'https://www.dailymotion.com/video/' . $src_matches[2]; } else { $oembed = _wp_oembed_get_object(); if ( ! $oembed->get_provider( $src, array( 'discover' => false, ) ) ) { $src = ''; } } return $src; }
php
private static function limit_embed( $src, $source_url ) { $src = self::limit_url( $src, $source_url ); if ( empty( $src ) ) { return ''; } if ( preg_match( '!//(m|www)\.youtube\.com/(embed|v)/([^?]+)\?.+$!i', $src, $src_matches ) ) { // Embedded Youtube videos (www or mobile) $src = 'https://www.youtube.com/watch?v=' . $src_matches[3]; } elseif ( preg_match( '!//player\.vimeo\.com/video/([\d]+)([?/].*)?$!i', $src, $src_matches ) ) { // Embedded Vimeo iframe videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } elseif ( preg_match( '!//vimeo\.com/moogaloop\.swf\?clip_id=([\d]+)$!i', $src, $src_matches ) ) { // Embedded Vimeo Flash videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } elseif ( preg_match( '!//vine\.co/v/([^/]+)/embed!i', $src, $src_matches ) ) { // Embedded Vine videos $src = 'https://vine.co/v/' . $src_matches[1]; } elseif ( preg_match( '!//(www\.)?dailymotion\.com/embed/video/([^/?]+)([/?].+)?!i', $src, $src_matches ) ) { // Embedded Daily Motion videos $src = 'https://www.dailymotion.com/video/' . $src_matches[2]; } else { $oembed = _wp_oembed_get_object(); if ( ! $oembed->get_provider( $src, array( 'discover' => false, ) ) ) { $src = ''; } } return $src; }
[ "private", "static", "function", "limit_embed", "(", "$", "src", ",", "$", "source_url", ")", "{", "$", "src", "=", "self", "::", "limit_url", "(", "$", "src", ",", "$", "source_url", ")", ";", "if", "(", "empty", "(", "$", "src", ")", ")", "{", "return", "''", ";", "}", "if", "(", "preg_match", "(", "'!//(m|www)\\.youtube\\.com/(embed|v)/([^?]+)\\?.+$!i'", ",", "$", "src", ",", "$", "src_matches", ")", ")", "{", "// Embedded Youtube videos (www or mobile)", "$", "src", "=", "'https://www.youtube.com/watch?v='", ".", "$", "src_matches", "[", "3", "]", ";", "}", "elseif", "(", "preg_match", "(", "'!//player\\.vimeo\\.com/video/([\\d]+)([?/].*)?$!i'", ",", "$", "src", ",", "$", "src_matches", ")", ")", "{", "// Embedded Vimeo iframe videos", "$", "src", "=", "'https://vimeo.com/'", ".", "(", "int", ")", "$", "src_matches", "[", "1", "]", ";", "}", "elseif", "(", "preg_match", "(", "'!//vimeo\\.com/moogaloop\\.swf\\?clip_id=([\\d]+)$!i'", ",", "$", "src", ",", "$", "src_matches", ")", ")", "{", "// Embedded Vimeo Flash videos", "$", "src", "=", "'https://vimeo.com/'", ".", "(", "int", ")", "$", "src_matches", "[", "1", "]", ";", "}", "elseif", "(", "preg_match", "(", "'!//vine\\.co/v/([^/]+)/embed!i'", ",", "$", "src", ",", "$", "src_matches", ")", ")", "{", "// Embedded Vine videos", "$", "src", "=", "'https://vine.co/v/'", ".", "$", "src_matches", "[", "1", "]", ";", "}", "elseif", "(", "preg_match", "(", "'!//(www\\.)?dailymotion\\.com/embed/video/([^/?]+)([/?].+)?!i'", ",", "$", "src", ",", "$", "src_matches", ")", ")", "{", "// Embedded Daily Motion videos", "$", "src", "=", "'https://www.dailymotion.com/video/'", ".", "$", "src_matches", "[", "2", "]", ";", "}", "else", "{", "$", "oembed", "=", "_wp_oembed_get_object", "(", ")", ";", "if", "(", "!", "$", "oembed", "->", "get_provider", "(", "$", "src", ",", "array", "(", "'discover'", "=>", "false", ",", ")", ")", ")", "{", "$", "src", "=", "''", ";", "}", "}", "return", "$", "src", ";", "}" ]
Limit embed source URLs to specific providers. Not all core oEmbed providers are supported. Supported providers include YouTube, Vimeo, Vine, Daily Motion, SoundCloud, and Twitter. @param string $src Embed source URL. @param string $source_url Source URL @return string If not from a supported provider, an empty string. Otherwise, a reformatted embed URL.
[ "Limit", "embed", "source", "URLs", "to", "specific", "providers", "." ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/class-parse-this-html.php#L152-L188
30,916
QuickenLoans/mcp-cache
src/Utility/StampedeProtectionTrait.php
StampedeProtectionTrait.setPrecomputeBeta
public function setPrecomputeBeta($beta) { if (!is_int($beta) || $beta < 1 || $beta > 10) { throw new Exception('Invalid beta specified. An integer between 1 and 10 is required.'); } $this->precomputeBeta = $beta; }
php
public function setPrecomputeBeta($beta) { if (!is_int($beta) || $beta < 1 || $beta > 10) { throw new Exception('Invalid beta specified. An integer between 1 and 10 is required.'); } $this->precomputeBeta = $beta; }
[ "public", "function", "setPrecomputeBeta", "(", "$", "beta", ")", "{", "if", "(", "!", "is_int", "(", "$", "beta", ")", "||", "$", "beta", "<", "1", "||", "$", "beta", ">", "10", ")", "{", "throw", "new", "Exception", "(", "'Invalid beta specified. An integer between 1 and 10 is required.'", ")", ";", "}", "$", "this", "->", "precomputeBeta", "=", "$", "beta", ";", "}" ]
Set the beta - early expiration scale. This affects the probability of early expiration. Default is 4, Set to any value from 1 to 10 to increase the chance of early expiration. @return void
[ "Set", "the", "beta", "-", "early", "expiration", "scale", "." ]
2dba32705f85452cb9099e35e0241a6c7a98b717
https://github.com/QuickenLoans/mcp-cache/blob/2dba32705f85452cb9099e35e0241a6c7a98b717/src/Utility/StampedeProtectionTrait.php#L70-L77
30,917
QuickenLoans/mcp-cache
src/Utility/StampedeProtectionTrait.php
StampedeProtectionTrait.setPrecomputeDelta
public function setPrecomputeDelta($delta) { if (!is_int($delta) || $delta < 1 || $delta > 100) { throw new Exception('Invalid delta specified. An integer between 1 and 100 is required.'); } $this->precomputeDelta = $delta; }
php
public function setPrecomputeDelta($delta) { if (!is_int($delta) || $delta < 1 || $delta > 100) { throw new Exception('Invalid delta specified. An integer between 1 and 100 is required.'); } $this->precomputeDelta = $delta; }
[ "public", "function", "setPrecomputeDelta", "(", "$", "delta", ")", "{", "if", "(", "!", "is_int", "(", "$", "delta", ")", "||", "$", "delta", "<", "1", "||", "$", "delta", ">", "100", ")", "{", "throw", "new", "Exception", "(", "'Invalid delta specified. An integer between 1 and 100 is required.'", ")", ";", "}", "$", "this", "->", "precomputeDelta", "=", "$", "delta", ";", "}" ]
Set the delta - percentage of TTL at which data should have a change to expire. Default is 10%, set to higher to increase the time of early expiration. @return void
[ "Set", "the", "delta", "-", "percentage", "of", "TTL", "at", "which", "data", "should", "have", "a", "change", "to", "expire", "." ]
2dba32705f85452cb9099e35e0241a6c7a98b717
https://github.com/QuickenLoans/mcp-cache/blob/2dba32705f85452cb9099e35e0241a6c7a98b717/src/Utility/StampedeProtectionTrait.php#L86-L93
30,918
QuickenLoans/mcp-cache
src/PredisCache.php
PredisCache.get
public function get($key) { $key = $this->salted($key, $this->suffix); $raw = $this->predis->get($key); // every response should be a php serialized string. // values not matching this pattern will explode. // missing data should return null, which is not unserialized. if (is_string($raw)) { return unserialize($raw); } return $raw; }
php
public function get($key) { $key = $this->salted($key, $this->suffix); $raw = $this->predis->get($key); // every response should be a php serialized string. // values not matching this pattern will explode. // missing data should return null, which is not unserialized. if (is_string($raw)) { return unserialize($raw); } return $raw; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "$", "key", "=", "$", "this", "->", "salted", "(", "$", "key", ",", "$", "this", "->", "suffix", ")", ";", "$", "raw", "=", "$", "this", "->", "predis", "->", "get", "(", "$", "key", ")", ";", "// every response should be a php serialized string.", "// values not matching this pattern will explode.", "// missing data should return null, which is not unserialized.", "if", "(", "is_string", "(", "$", "raw", ")", ")", "{", "return", "unserialize", "(", "$", "raw", ")", ";", "}", "return", "$", "raw", ";", "}" ]
This cacher performs serialization and unserialization. All string responses from redis will be unserialized. For this reason, only mcp cachers should attempt to retrieve data cached by mcp cachers. {@inheritdoc}
[ "This", "cacher", "performs", "serialization", "and", "unserialization", ".", "All", "string", "responses", "from", "redis", "will", "be", "unserialized", "." ]
2dba32705f85452cb9099e35e0241a6c7a98b717
https://github.com/QuickenLoans/mcp-cache/blob/2dba32705f85452cb9099e35e0241a6c7a98b717/src/PredisCache.php#L58-L73
30,919
bovigo/callmap
src/main/php/FunctionProxy.php
FunctionProxy.returns
public function returns($returnValue): self { if ($this->returnVoid) { throw new \LogicException( 'Trying to map function ' . $this->name . '(), but it is declared as returning void.' ); } $this->callMap = new CallMap(['function' => $returnValue]); return $this; }
php
public function returns($returnValue): self { if ($this->returnVoid) { throw new \LogicException( 'Trying to map function ' . $this->name . '(), but it is declared as returning void.' ); } $this->callMap = new CallMap(['function' => $returnValue]); return $this; }
[ "public", "function", "returns", "(", "$", "returnValue", ")", ":", "self", "{", "if", "(", "$", "this", "->", "returnVoid", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Trying to map function '", ".", "$", "this", "->", "name", ".", "'(), but it is declared as returning void.'", ")", ";", "}", "$", "this", "->", "callMap", "=", "new", "CallMap", "(", "[", "'function'", "=>", "$", "returnValue", "]", ")", ";", "return", "$", "this", ";", "}" ]
sets the call map to use @api @param mixed $returnValue @return $this @throws \LogicException when mapped function is declared as returning void @since 3.2.0
[ "sets", "the", "call", "map", "to", "use" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/FunctionProxy.php#L70-L81
30,920
bovigo/callmap
src/main/php/FunctionProxy.php
FunctionProxy.handleFunctionCall
protected function handleFunctionCall(array $arguments) { $invocation = $this->invocations->recordCall($arguments); if (null !== $this->callMap && $this->callMap->hasResultFor('function', $invocation)) { return $this->callMap->resultFor('function', $arguments, $invocation); } if ($this->parentCallsAllowed) { $originalFunction = $this->invocations->name(); return $originalFunction(...$arguments); } return null; }
php
protected function handleFunctionCall(array $arguments) { $invocation = $this->invocations->recordCall($arguments); if (null !== $this->callMap && $this->callMap->hasResultFor('function', $invocation)) { return $this->callMap->resultFor('function', $arguments, $invocation); } if ($this->parentCallsAllowed) { $originalFunction = $this->invocations->name(); return $originalFunction(...$arguments); } return null; }
[ "protected", "function", "handleFunctionCall", "(", "array", "$", "arguments", ")", "{", "$", "invocation", "=", "$", "this", "->", "invocations", "->", "recordCall", "(", "$", "arguments", ")", ";", "if", "(", "null", "!==", "$", "this", "->", "callMap", "&&", "$", "this", "->", "callMap", "->", "hasResultFor", "(", "'function'", ",", "$", "invocation", ")", ")", "{", "return", "$", "this", "->", "callMap", "->", "resultFor", "(", "'function'", ",", "$", "arguments", ",", "$", "invocation", ")", ";", "}", "if", "(", "$", "this", "->", "parentCallsAllowed", ")", "{", "$", "originalFunction", "=", "$", "this", "->", "invocations", "->", "name", "(", ")", ";", "return", "$", "originalFunction", "(", "...", "$", "arguments", ")", ";", "}", "return", "null", ";", "}" ]
handles actual function calls @param mixed[] $arguments list of given arguments for function @return mixed
[ "handles", "actual", "function", "calls" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/FunctionProxy.php#L103-L116
30,921
QuickenLoans/mcp-cache
src/Utility/KeySaltingTrait.php
KeySaltingTrait.salted
private function salted($key, $suffix = null) { $delimiter = ':'; if (defined('static::DELIMITER')) { $delimiter = static::DELIMITER; } if (defined('static::PREFIX')) { $key = sprintf('%s%s%s', static::PREFIX, $delimiter, $key); } if ($suffix) { return sprintf('%s%s%s', $key, $delimiter, $suffix); } return $key; }
php
private function salted($key, $suffix = null) { $delimiter = ':'; if (defined('static::DELIMITER')) { $delimiter = static::DELIMITER; } if (defined('static::PREFIX')) { $key = sprintf('%s%s%s', static::PREFIX, $delimiter, $key); } if ($suffix) { return sprintf('%s%s%s', $key, $delimiter, $suffix); } return $key; }
[ "private", "function", "salted", "(", "$", "key", ",", "$", "suffix", "=", "null", ")", "{", "$", "delimiter", "=", "':'", ";", "if", "(", "defined", "(", "'static::DELIMITER'", ")", ")", "{", "$", "delimiter", "=", "static", "::", "DELIMITER", ";", "}", "if", "(", "defined", "(", "'static::PREFIX'", ")", ")", "{", "$", "key", "=", "sprintf", "(", "'%s%s%s'", ",", "static", "::", "PREFIX", ",", "$", "delimiter", ",", "$", "key", ")", ";", "}", "if", "(", "$", "suffix", ")", "{", "return", "sprintf", "(", "'%s%s%s'", ",", "$", "key", ",", "$", "delimiter", ",", "$", "suffix", ")", ";", "}", "return", "$", "key", ";", "}" ]
Salt the cache key if a salt is provided. @param string $key @param string|null $suffix @return string
[ "Salt", "the", "cache", "key", "if", "a", "salt", "is", "provided", "." ]
2dba32705f85452cb9099e35e0241a6c7a98b717
https://github.com/QuickenLoans/mcp-cache/blob/2dba32705f85452cb9099e35e0241a6c7a98b717/src/Utility/KeySaltingTrait.php#L26-L42
30,922
Werkspot/message-bus
src/Bus/DeliveryChain/Middleware/LockingMiddleware.php
LockingMiddleware.enqueue
private function enqueue(MessageInterface $message, callable $next): void { $this->queue[] = function () use ($message, $next): void { $next($message); }; }
php
private function enqueue(MessageInterface $message, callable $next): void { $this->queue[] = function () use ($message, $next): void { $next($message); }; }
[ "private", "function", "enqueue", "(", "MessageInterface", "$", "message", ",", "callable", "$", "next", ")", ":", "void", "{", "$", "this", "->", "queue", "[", "]", "=", "function", "(", ")", "use", "(", "$", "message", ",", "$", "next", ")", ":", "void", "{", "$", "next", "(", "$", "message", ")", ";", "}", ";", "}" ]
Queues the execution of the next message instead of executing it when it's added to the message bus
[ "Queues", "the", "execution", "of", "the", "next", "message", "instead", "of", "executing", "it", "when", "it", "s", "added", "to", "the", "message", "bus" ]
4dbc553c7fa7932c5413776dcf470ca8950ac2bd
https://github.com/Werkspot/message-bus/blob/4dbc553c7fa7932c5413776dcf470ca8950ac2bd/src/Bus/DeliveryChain/Middleware/LockingMiddleware.php#L51-L56
30,923
symbiote/silverstripe-datachange-tracker
src/Extension/ChangeRecordable.php
ChangeRecordable.getDataChangesList
public function getDataChangesList() { return DataChangeRecord::get()->filter([ 'ChangeRecordID' => $this->owner->ID, 'ChangeRecordClass' => $this->owner->ClassName ]); }
php
public function getDataChangesList() { return DataChangeRecord::get()->filter([ 'ChangeRecordID' => $this->owner->ID, 'ChangeRecordClass' => $this->owner->ClassName ]); }
[ "public", "function", "getDataChangesList", "(", ")", "{", "return", "DataChangeRecord", "::", "get", "(", ")", "->", "filter", "(", "[", "'ChangeRecordID'", "=>", "$", "this", "->", "owner", "->", "ID", ",", "'ChangeRecordClass'", "=>", "$", "this", "->", "owner", "->", "ClassName", "]", ")", ";", "}" ]
Get the list of data changes for this item @return \SilverStripe\ORM\DataList
[ "Get", "the", "list", "of", "data", "changes", "for", "this", "item" ]
4895935726ecb3209a502cfd63a4b2ccef7a9bf1
https://github.com/symbiote/silverstripe-datachange-tracker/blob/4895935726ecb3209a502cfd63a4b2ccef7a9bf1/src/Extension/ChangeRecordable.php#L83-L88
30,924
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.callMapClass
private static function callMapClass($target): \ReflectionClass { $class = self::reflect($target); if (!isset(self::$classes[$class->getName()])) { self::$classes[$class->getName()] = self::forkCallMapClass($class); } return self::$classes[$class->getName()]; }
php
private static function callMapClass($target): \ReflectionClass { $class = self::reflect($target); if (!isset(self::$classes[$class->getName()])) { self::$classes[$class->getName()] = self::forkCallMapClass($class); } return self::$classes[$class->getName()]; }
[ "private", "static", "function", "callMapClass", "(", "$", "target", ")", ":", "\\", "ReflectionClass", "{", "$", "class", "=", "self", "::", "reflect", "(", "$", "target", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "classes", "[", "$", "class", "->", "getName", "(", ")", "]", ")", ")", "{", "self", "::", "$", "classes", "[", "$", "class", "->", "getName", "(", ")", "]", "=", "self", "::", "forkCallMapClass", "(", "$", "class", ")", ";", "}", "return", "self", "::", "$", "classes", "[", "$", "class", "->", "getName", "(", ")", "]", ";", "}" ]
returns the proxy class for given target class or interface @param string|object $target @return \ReflectionClass
[ "returns", "the", "proxy", "class", "for", "given", "target", "class", "or", "interface" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L77-L85
30,925
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.reflect
private static function reflect($class): \ReflectionClass { if (is_string($class) && (class_exists($class) || interface_exists($class) || trait_exists($class))) { return new \ReflectionClass($class); } elseif (is_object($class)) { return new \ReflectionObject($class); } throw new \InvalidArgumentException( 'Given class must either be an existing class, interface or' . ' trait name or class instance, ' . \gettype($class) . ' with value "' . $class . '" given' ); }
php
private static function reflect($class): \ReflectionClass { if (is_string($class) && (class_exists($class) || interface_exists($class) || trait_exists($class))) { return new \ReflectionClass($class); } elseif (is_object($class)) { return new \ReflectionObject($class); } throw new \InvalidArgumentException( 'Given class must either be an existing class, interface or' . ' trait name or class instance, ' . \gettype($class) . ' with value "' . $class . '" given' ); }
[ "private", "static", "function", "reflect", "(", "$", "class", ")", ":", "\\", "ReflectionClass", "{", "if", "(", "is_string", "(", "$", "class", ")", "&&", "(", "class_exists", "(", "$", "class", ")", "||", "interface_exists", "(", "$", "class", ")", "||", "trait_exists", "(", "$", "class", ")", ")", ")", "{", "return", "new", "\\", "ReflectionClass", "(", "$", "class", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "class", ")", ")", "{", "return", "new", "\\", "ReflectionObject", "(", "$", "class", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given class must either be an existing class, interface or'", ".", "' trait name or class instance, '", ".", "\\", "gettype", "(", "$", "class", ")", ".", "' with value \"'", ".", "$", "class", ".", "'\" given'", ")", ";", "}" ]
reflects given class value @param string|object $class @return \ReflectionClass @throws \InvalidArgumentException
[ "reflects", "given", "class", "value" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L94-L107
30,926
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.forkCallMapClass
private static function forkCallMapClass(\ReflectionClass $class): \ReflectionClass { if ($class->isTrait()) { $class = self::forkTrait($class); } try { $compile = self::$compile; $compile(self::createCallmapProxyCode($class)); } catch (\ParseError $pe) { throw new ProxyCreationFailure( 'Failure while creating CallMap instance of ' . $class->getName() . ': ' . $pe->getMessage(), $pe ); } return new \ReflectionClass($class->getName() . 'CallMapProxy'); }
php
private static function forkCallMapClass(\ReflectionClass $class): \ReflectionClass { if ($class->isTrait()) { $class = self::forkTrait($class); } try { $compile = self::$compile; $compile(self::createCallmapProxyCode($class)); } catch (\ParseError $pe) { throw new ProxyCreationFailure( 'Failure while creating CallMap instance of ' . $class->getName() . ': ' . $pe->getMessage(), $pe ); } return new \ReflectionClass($class->getName() . 'CallMapProxy'); }
[ "private", "static", "function", "forkCallMapClass", "(", "\\", "ReflectionClass", "$", "class", ")", ":", "\\", "ReflectionClass", "{", "if", "(", "$", "class", "->", "isTrait", "(", ")", ")", "{", "$", "class", "=", "self", "::", "forkTrait", "(", "$", "class", ")", ";", "}", "try", "{", "$", "compile", "=", "self", "::", "$", "compile", ";", "$", "compile", "(", "self", "::", "createCallmapProxyCode", "(", "$", "class", ")", ")", ";", "}", "catch", "(", "\\", "ParseError", "$", "pe", ")", "{", "throw", "new", "ProxyCreationFailure", "(", "'Failure while creating CallMap instance of '", ".", "$", "class", "->", "getName", "(", ")", ".", "': '", ".", "$", "pe", "->", "getMessage", "(", ")", ",", "$", "pe", ")", ";", "}", "return", "new", "\\", "ReflectionClass", "(", "$", "class", "->", "getName", "(", ")", ".", "'CallMapProxy'", ")", ";", "}" ]
creates a new class from the given class which uses the CallMap trait @param \ReflectionClass $class @return \ReflectionClass @throws ProxyCreationFailure
[ "creates", "a", "new", "class", "from", "the", "given", "class", "which", "uses", "the", "CallMap", "trait" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L124-L142
30,927
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.forkTrait
private static function forkTrait(\ReflectionClass $class): \ReflectionClass { $code = sprintf( "abstract class %sCallMapFork {\n" . " use \%s;\n}", $class->getShortName(), $class->getName() ); if ($class->inNamespace()) { $code = sprintf( "namespace %s {\n%s}\n", $class->getNamespaceName(), $code ); } try { $compile = self::$compile; $compile($code); } catch (\ParseError $pe) { throw new ProxyCreationFailure( 'Failure while creating forked trait instance of ' . $class->getName() . ': ' . $pe->getMessage(), $pe ); } return new \ReflectionClass($class->getName() . 'CallMapFork'); }
php
private static function forkTrait(\ReflectionClass $class): \ReflectionClass { $code = sprintf( "abstract class %sCallMapFork {\n" . " use \%s;\n}", $class->getShortName(), $class->getName() ); if ($class->inNamespace()) { $code = sprintf( "namespace %s {\n%s}\n", $class->getNamespaceName(), $code ); } try { $compile = self::$compile; $compile($code); } catch (\ParseError $pe) { throw new ProxyCreationFailure( 'Failure while creating forked trait instance of ' . $class->getName() . ': ' . $pe->getMessage(), $pe ); } return new \ReflectionClass($class->getName() . 'CallMapFork'); }
[ "private", "static", "function", "forkTrait", "(", "\\", "ReflectionClass", "$", "class", ")", ":", "\\", "ReflectionClass", "{", "$", "code", "=", "sprintf", "(", "\"abstract class %sCallMapFork {\\n\"", ".", "\" use \\%s;\\n}\"", ",", "$", "class", "->", "getShortName", "(", ")", ",", "$", "class", "->", "getName", "(", ")", ")", ";", "if", "(", "$", "class", "->", "inNamespace", "(", ")", ")", "{", "$", "code", "=", "sprintf", "(", "\"namespace %s {\\n%s}\\n\"", ",", "$", "class", "->", "getNamespaceName", "(", ")", ",", "$", "code", ")", ";", "}", "try", "{", "$", "compile", "=", "self", "::", "$", "compile", ";", "$", "compile", "(", "$", "code", ")", ";", "}", "catch", "(", "\\", "ParseError", "$", "pe", ")", "{", "throw", "new", "ProxyCreationFailure", "(", "'Failure while creating forked trait instance of '", ".", "$", "class", "->", "getName", "(", ")", ".", "': '", ".", "$", "pe", "->", "getMessage", "(", ")", ",", "$", "pe", ")", ";", "}", "return", "new", "\\", "ReflectionClass", "(", "$", "class", "->", "getName", "(", ")", ".", "'CallMapFork'", ")", ";", "}" ]
create an intermediate class for the trait so that any methods of the trait become callable as parent @param \ReflectionClass $class @return \ReflectionClass @throws ProxyCreationFailure
[ "create", "an", "intermediate", "class", "for", "the", "trait", "so", "that", "any", "methods", "of", "the", "trait", "become", "callable", "as", "parent" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L152-L180
30,928
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.createMethods
private static function createMethods(\ReflectionClass $class): string { $code = ''; $methods = []; $params = []; $voidMethods = []; foreach (self::methodsOf($class) as $method) { $return = true; $returnType = determineReturnTypeOf($method); if ($returnType === ': void') { $voidMethods[$method->getName()] = $method->getName(); $return = false; } $param = paramsOf($method); /* @var $method \ReflectionMethod */ $code .= sprintf( " %s function %s(%s)%s {\n" . " %s\$this->handleMethodCall('%s', func_get_args(), %s);\n" . " }\n", ($method->isPublic() ? 'public' : 'protected'), $method->getName(), $param['string'], $returnType, $return ? 'return ' : '', $method->getName(), self::shouldReturnSelf($class, $method) ? 'true' : 'false' ); $methods[] = "'" . $method->getName() . "' => '" . $method->getName() . "'"; $params[$method->getName()] = $param['names']; } return $code . sprintf( "\n private \$_allowedMethods = [%s];\n", join(', ', $methods) ) . sprintf( "\n private \$_methodParams = %s;\n", var_export($params, true) ) . sprintf( "\n private \$_voidMethods = %s;\n", var_export($voidMethods, true) ); }
php
private static function createMethods(\ReflectionClass $class): string { $code = ''; $methods = []; $params = []; $voidMethods = []; foreach (self::methodsOf($class) as $method) { $return = true; $returnType = determineReturnTypeOf($method); if ($returnType === ': void') { $voidMethods[$method->getName()] = $method->getName(); $return = false; } $param = paramsOf($method); /* @var $method \ReflectionMethod */ $code .= sprintf( " %s function %s(%s)%s {\n" . " %s\$this->handleMethodCall('%s', func_get_args(), %s);\n" . " }\n", ($method->isPublic() ? 'public' : 'protected'), $method->getName(), $param['string'], $returnType, $return ? 'return ' : '', $method->getName(), self::shouldReturnSelf($class, $method) ? 'true' : 'false' ); $methods[] = "'" . $method->getName() . "' => '" . $method->getName() . "'"; $params[$method->getName()] = $param['names']; } return $code . sprintf( "\n private \$_allowedMethods = [%s];\n", join(', ', $methods) ) . sprintf( "\n private \$_methodParams = %s;\n", var_export($params, true) ) . sprintf( "\n private \$_voidMethods = %s;\n", var_export($voidMethods, true) ); }
[ "private", "static", "function", "createMethods", "(", "\\", "ReflectionClass", "$", "class", ")", ":", "string", "{", "$", "code", "=", "''", ";", "$", "methods", "=", "[", "]", ";", "$", "params", "=", "[", "]", ";", "$", "voidMethods", "=", "[", "]", ";", "foreach", "(", "self", "::", "methodsOf", "(", "$", "class", ")", "as", "$", "method", ")", "{", "$", "return", "=", "true", ";", "$", "returnType", "=", "determineReturnTypeOf", "(", "$", "method", ")", ";", "if", "(", "$", "returnType", "===", "': void'", ")", "{", "$", "voidMethods", "[", "$", "method", "->", "getName", "(", ")", "]", "=", "$", "method", "->", "getName", "(", ")", ";", "$", "return", "=", "false", ";", "}", "$", "param", "=", "paramsOf", "(", "$", "method", ")", ";", "/* @var $method \\ReflectionMethod */", "$", "code", ".=", "sprintf", "(", "\" %s function %s(%s)%s {\\n\"", ".", "\" %s\\$this->handleMethodCall('%s', func_get_args(), %s);\\n\"", ".", "\" }\\n\"", ",", "(", "$", "method", "->", "isPublic", "(", ")", "?", "'public'", ":", "'protected'", ")", ",", "$", "method", "->", "getName", "(", ")", ",", "$", "param", "[", "'string'", "]", ",", "$", "returnType", ",", "$", "return", "?", "'return '", ":", "''", ",", "$", "method", "->", "getName", "(", ")", ",", "self", "::", "shouldReturnSelf", "(", "$", "class", ",", "$", "method", ")", "?", "'true'", ":", "'false'", ")", ";", "$", "methods", "[", "]", "=", "\"'\"", ".", "$", "method", "->", "getName", "(", ")", ".", "\"' => '\"", ".", "$", "method", "->", "getName", "(", ")", ".", "\"'\"", ";", "$", "params", "[", "$", "method", "->", "getName", "(", ")", "]", "=", "$", "param", "[", "'names'", "]", ";", "}", "return", "$", "code", ".", "sprintf", "(", "\"\\n private \\$_allowedMethods = [%s];\\n\"", ",", "join", "(", "', '", ",", "$", "methods", ")", ")", ".", "sprintf", "(", "\"\\n private \\$_methodParams = %s;\\n\"", ",", "var_export", "(", "$", "params", ",", "true", ")", ")", ".", "sprintf", "(", "\"\\n private \\$_voidMethods = %s;\\n\"", ",", "var_export", "(", "$", "voidMethods", ",", "true", ")", ")", ";", "}" ]
creates methods for the proxy @param \ReflectionClass $class @return string
[ "creates", "methods", "for", "the", "proxy" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L235-L277
30,929
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.methodsOf
private static function methodsOf(\ReflectionClass $class): \Iterator { return new \CallbackFilterIterator( new \ArrayIterator($class->getMethods()), function(\ReflectionMethod $method) { return !$method->isPrivate() && !$method->isFinal() && !$method->isStatic() && !$method->isConstructor() && !$method->isDestructor(); } ); }
php
private static function methodsOf(\ReflectionClass $class): \Iterator { return new \CallbackFilterIterator( new \ArrayIterator($class->getMethods()), function(\ReflectionMethod $method) { return !$method->isPrivate() && !$method->isFinal() && !$method->isStatic() && !$method->isConstructor() && !$method->isDestructor(); } ); }
[ "private", "static", "function", "methodsOf", "(", "\\", "ReflectionClass", "$", "class", ")", ":", "\\", "Iterator", "{", "return", "new", "\\", "CallbackFilterIterator", "(", "new", "\\", "ArrayIterator", "(", "$", "class", "->", "getMethods", "(", ")", ")", ",", "function", "(", "\\", "ReflectionMethod", "$", "method", ")", "{", "return", "!", "$", "method", "->", "isPrivate", "(", ")", "&&", "!", "$", "method", "->", "isFinal", "(", ")", "&&", "!", "$", "method", "->", "isStatic", "(", ")", "&&", "!", "$", "method", "->", "isConstructor", "(", ")", "&&", "!", "$", "method", "->", "isDestructor", "(", ")", ";", "}", ")", ";", "}" ]
returns applicable methods for given class @param \ReflectionClass $class @return \Iterator
[ "returns", "applicable", "methods", "for", "given", "class" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L285-L298
30,930
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.shouldReturnSelf
private static function shouldReturnSelf(\ReflectionClass $class, \ReflectionMethod $method): bool { $returnType = self::detectReturnType($method); if (null === $returnType) { return false; } if (in_array($returnType, ['$this', 'self', $class->getName(), $class->getShortName()])) { return true; } foreach ($class->getInterfaces() as $interface) { if ($interface->getName() !== 'Traversable' && ($interface->getName() === $returnType || $interface->getShortName() === $returnType)) { return true; } } while ($parent = $class->getParentClass()) { if ($parent->getName() === $returnType || $parent->getShortName() === $returnType) { return true; } $class = $parent; } return false; }
php
private static function shouldReturnSelf(\ReflectionClass $class, \ReflectionMethod $method): bool { $returnType = self::detectReturnType($method); if (null === $returnType) { return false; } if (in_array($returnType, ['$this', 'self', $class->getName(), $class->getShortName()])) { return true; } foreach ($class->getInterfaces() as $interface) { if ($interface->getName() !== 'Traversable' && ($interface->getName() === $returnType || $interface->getShortName() === $returnType)) { return true; } } while ($parent = $class->getParentClass()) { if ($parent->getName() === $returnType || $parent->getShortName() === $returnType) { return true; } $class = $parent; } return false; }
[ "private", "static", "function", "shouldReturnSelf", "(", "\\", "ReflectionClass", "$", "class", ",", "\\", "ReflectionMethod", "$", "method", ")", ":", "bool", "{", "$", "returnType", "=", "self", "::", "detectReturnType", "(", "$", "method", ")", ";", "if", "(", "null", "===", "$", "returnType", ")", "{", "return", "false", ";", "}", "if", "(", "in_array", "(", "$", "returnType", ",", "[", "'$this'", ",", "'self'", ",", "$", "class", "->", "getName", "(", ")", ",", "$", "class", "->", "getShortName", "(", ")", "]", ")", ")", "{", "return", "true", ";", "}", "foreach", "(", "$", "class", "->", "getInterfaces", "(", ")", "as", "$", "interface", ")", "{", "if", "(", "$", "interface", "->", "getName", "(", ")", "!==", "'Traversable'", "&&", "(", "$", "interface", "->", "getName", "(", ")", "===", "$", "returnType", "||", "$", "interface", "->", "getShortName", "(", ")", "===", "$", "returnType", ")", ")", "{", "return", "true", ";", "}", "}", "while", "(", "$", "parent", "=", "$", "class", "->", "getParentClass", "(", ")", ")", "{", "if", "(", "$", "parent", "->", "getName", "(", ")", "===", "$", "returnType", "||", "$", "parent", "->", "getShortName", "(", ")", "===", "$", "returnType", ")", "{", "return", "true", ";", "}", "$", "class", "=", "$", "parent", ";", "}", "return", "false", ";", "}" ]
detects whether a method should return the instance or null @param \ReflectionClass $class @param \ReflectionMethod $method @return bool
[ "detects", "whether", "a", "method", "should", "return", "the", "instance", "or", "null" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L307-L333
30,931
bovigo/callmap
src/main/php/NewInstance.php
NewInstance.detectReturnType
private static function detectReturnType(\ReflectionMethod $method): ?string { if ($method->hasReturnType()) { return (string) $method->getReturnType(); } $docComment = $method->getDocComment(); if (false === $docComment) { return null; } $returnPart = strstr($docComment, '@return'); if (false === $returnPart) { return null; } $returnParts = explode(' ', trim(str_replace('@return', '', $returnPart))); $returnType = ltrim(trim($returnParts[0]), '\\'); if (empty($returnType) || strpos($returnType, '*') !== false) { return null; } return $returnType; }
php
private static function detectReturnType(\ReflectionMethod $method): ?string { if ($method->hasReturnType()) { return (string) $method->getReturnType(); } $docComment = $method->getDocComment(); if (false === $docComment) { return null; } $returnPart = strstr($docComment, '@return'); if (false === $returnPart) { return null; } $returnParts = explode(' ', trim(str_replace('@return', '', $returnPart))); $returnType = ltrim(trim($returnParts[0]), '\\'); if (empty($returnType) || strpos($returnType, '*') !== false) { return null; } return $returnType; }
[ "private", "static", "function", "detectReturnType", "(", "\\", "ReflectionMethod", "$", "method", ")", ":", "?", "string", "{", "if", "(", "$", "method", "->", "hasReturnType", "(", ")", ")", "{", "return", "(", "string", ")", "$", "method", "->", "getReturnType", "(", ")", ";", "}", "$", "docComment", "=", "$", "method", "->", "getDocComment", "(", ")", ";", "if", "(", "false", "===", "$", "docComment", ")", "{", "return", "null", ";", "}", "$", "returnPart", "=", "strstr", "(", "$", "docComment", ",", "'@return'", ")", ";", "if", "(", "false", "===", "$", "returnPart", ")", "{", "return", "null", ";", "}", "$", "returnParts", "=", "explode", "(", "' '", ",", "trim", "(", "str_replace", "(", "'@return'", ",", "''", ",", "$", "returnPart", ")", ")", ")", ";", "$", "returnType", "=", "ltrim", "(", "trim", "(", "$", "returnParts", "[", "0", "]", ")", ",", "'\\\\'", ")", ";", "if", "(", "empty", "(", "$", "returnType", ")", "||", "strpos", "(", "$", "returnType", ",", "'*'", ")", "!==", "false", ")", "{", "return", "null", ";", "}", "return", "$", "returnType", ";", "}" ]
detects return type of method It will make use of reflection to detect the return type. In case this does not yield a result the doc comment will be parsed for the return annotation. @param \ReflectionMethod $method @return string|null
[ "detects", "return", "type", "of", "method" ]
0dbf2c234469bf18f4cc06d31962b6141923754b
https://github.com/bovigo/callmap/blob/0dbf2c234469bf18f4cc06d31962b6141923754b/src/main/php/NewInstance.php#L345-L368
30,932
aplazame/php-sdk
src/Api/Client.php
Client.get
public function get($path, array $query = array()) { if (!empty($query)) { $query = http_build_query($query); $path .= '?' . $query; } return $this->request('GET', $path); }
php
public function get($path, array $query = array()) { if (!empty($query)) { $query = http_build_query($query); $path .= '?' . $query; } return $this->request('GET', $path); }
[ "public", "function", "get", "(", "$", "path", ",", "array", "$", "query", "=", "array", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "query", ")", ")", "{", "$", "query", "=", "http_build_query", "(", "$", "query", ")", ";", "$", "path", ".=", "'?'", ".", "$", "query", ";", "}", "return", "$", "this", "->", "request", "(", "'GET'", ",", "$", "path", ")", ";", "}" ]
Performs a GET request. @param string $path The path of the request. @param array $query The filters of the request. @return array The data of the response. @throws ApiCommunicationException if an I/O error occurs. @throws DeserializeException if response cannot be deserialized. @throws ApiServerException if server was not able to respond. @throws ApiClientException if request is invalid.
[ "Performs", "a", "GET", "request", "." ]
42d1b5a4650b004733728f8a009df33e9b7eeff1
https://github.com/aplazame/php-sdk/blob/42d1b5a4650b004733728f8a009df33e9b7eeff1/src/Api/Client.php#L86-L94
30,933
dshanske/parse-this
includes/class-parse-this.php
Parse_This.set
public function set( $source_content, $url, $jf2 = false ) { $this->content = $source_content; if ( wp_http_validate_url( $url ) ) { $this->url = $url; $this->domain = wp_parse_url( $url, PHP_URL_HOST ); } if ( $jf2 ) { $this->jf2 = $source_content; } elseif ( is_string( $this->content ) ) { if ( class_exists( 'Masterminds\\HTML5' ) ) { $this->doc = new \Masterminds\HTML5( array( 'disable_html_ns' => true ) ); $this->doc = $this->doc->loadHTML( $this->content ); } else { $this->doc = new DOMDocument(); libxml_use_internal_errors( true ); $this->doc->loadHTML( mb_convert_encoding( $this->content, 'HTML-ENTITIES', mb_detect_encoding( $this->content ) ) ); libxml_use_internal_errors( false ); } } }
php
public function set( $source_content, $url, $jf2 = false ) { $this->content = $source_content; if ( wp_http_validate_url( $url ) ) { $this->url = $url; $this->domain = wp_parse_url( $url, PHP_URL_HOST ); } if ( $jf2 ) { $this->jf2 = $source_content; } elseif ( is_string( $this->content ) ) { if ( class_exists( 'Masterminds\\HTML5' ) ) { $this->doc = new \Masterminds\HTML5( array( 'disable_html_ns' => true ) ); $this->doc = $this->doc->loadHTML( $this->content ); } else { $this->doc = new DOMDocument(); libxml_use_internal_errors( true ); $this->doc->loadHTML( mb_convert_encoding( $this->content, 'HTML-ENTITIES', mb_detect_encoding( $this->content ) ) ); libxml_use_internal_errors( false ); } } }
[ "public", "function", "set", "(", "$", "source_content", ",", "$", "url", ",", "$", "jf2", "=", "false", ")", "{", "$", "this", "->", "content", "=", "$", "source_content", ";", "if", "(", "wp_http_validate_url", "(", "$", "url", ")", ")", "{", "$", "this", "->", "url", "=", "$", "url", ";", "$", "this", "->", "domain", "=", "wp_parse_url", "(", "$", "url", ",", "PHP_URL_HOST", ")", ";", "}", "if", "(", "$", "jf2", ")", "{", "$", "this", "->", "jf2", "=", "$", "source_content", ";", "}", "elseif", "(", "is_string", "(", "$", "this", "->", "content", ")", ")", "{", "if", "(", "class_exists", "(", "'Masterminds\\\\HTML5'", ")", ")", "{", "$", "this", "->", "doc", "=", "new", "\\", "Masterminds", "\\", "HTML5", "(", "array", "(", "'disable_html_ns'", "=>", "true", ")", ")", ";", "$", "this", "->", "doc", "=", "$", "this", "->", "doc", "->", "loadHTML", "(", "$", "this", "->", "content", ")", ";", "}", "else", "{", "$", "this", "->", "doc", "=", "new", "DOMDocument", "(", ")", ";", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "this", "->", "doc", "->", "loadHTML", "(", "mb_convert_encoding", "(", "$", "this", "->", "content", ",", "'HTML-ENTITIES'", ",", "mb_detect_encoding", "(", "$", "this", "->", "content", ")", ")", ")", ";", "libxml_use_internal_errors", "(", "false", ")", ";", "}", "}", "}" ]
Sets the source. @since x.x.x @access public @param string $source_content source content. @param string $url Source URL @param string $jf2 If set it passes the content directly as preparsed
[ "Sets", "the", "source", "." ]
722154e91fe47bca185256bd6388324de7bea012
https://github.com/dshanske/parse-this/blob/722154e91fe47bca185256bd6388324de7bea012/includes/class-parse-this.php#L46-L65
30,934
symbiote/silverstripe-datachange-tracker
src/Model/TrackedManyManyList.php
TrackedManyManyList.tableClass
private function tableClass($table) { $tables = DataObject::getSchema()->getTableNames(); $class = array_search($table, $tables, true); if ($class) { return $class; } return null; }
php
private function tableClass($table) { $tables = DataObject::getSchema()->getTableNames(); $class = array_search($table, $tables, true); if ($class) { return $class; } return null; }
[ "private", "function", "tableClass", "(", "$", "table", ")", "{", "$", "tables", "=", "DataObject", "::", "getSchema", "(", ")", "->", "getTableNames", "(", ")", ";", "$", "class", "=", "array_search", "(", "$", "table", ",", "$", "tables", ",", "true", ")", ";", "if", "(", "$", "class", ")", "{", "return", "$", "class", ";", "}", "return", "null", ";", "}" ]
Find the class for the given table. Stripped down version from framework that does not attempt to strip _Live and _versions postfixes as that throws errors in its preg_match(). (At least it did as of 2018-06-22 on SilverStripe 4.1.1) @param string $table @return string|null The FQN of the class, or null if not found
[ "Find", "the", "class", "for", "the", "given", "table", "." ]
4895935726ecb3209a502cfd63a4b2ccef7a9bf1
https://github.com/symbiote/silverstripe-datachange-tracker/blob/4895935726ecb3209a502cfd63a4b2ccef7a9bf1/src/Model/TrackedManyManyList.php#L76-L84
30,935
QuickenLoans/mcp-logger
src/Service/SyslogService.php
SyslogService.connect
private function connect() { $this->status = openlog( $this->config[self::CONFIG_IDENT], $this->config[self::CONFIG_OPTIONS], $this->config[self::CONFIG_FACILITY] ); }
php
private function connect() { $this->status = openlog( $this->config[self::CONFIG_IDENT], $this->config[self::CONFIG_OPTIONS], $this->config[self::CONFIG_FACILITY] ); }
[ "private", "function", "connect", "(", ")", "{", "$", "this", "->", "status", "=", "openlog", "(", "$", "this", "->", "config", "[", "self", "::", "CONFIG_IDENT", "]", ",", "$", "this", "->", "config", "[", "self", "::", "CONFIG_OPTIONS", "]", ",", "$", "this", "->", "config", "[", "self", "::", "CONFIG_FACILITY", "]", ")", ";", "}" ]
Attempt to connect to open syslog connection @return void
[ "Attempt", "to", "connect", "to", "open", "syslog", "connection" ]
ec0960fc32de1a4c583b2447b99d0ef8c801f1ae
https://github.com/QuickenLoans/mcp-logger/blob/ec0960fc32de1a4c583b2447b99d0ef8c801f1ae/src/Service/SyslogService.php#L78-L85
30,936
QuickenLoans/mcp-logger
src/Service/SyslogService.php
SyslogService.convertLogLevelFromPSRToSyslog
private function convertLogLevelFromPSRToSyslog($severity) { switch ($severity) { case LogLevel::DEBUG: return LOG_DEBUG; case LogLevel::INFO: return LOG_INFO; case LogLevel::NOTICE: return LOG_NOTICE; case LogLevel::WARNING: return LOG_WARNING; case LogLevel::ERROR: return LOG_ERR; case LogLevel::CRITICAL: return LOG_CRIT; case LogLevel::ALERT: return LOG_ALERT; case LogLevel::EMERGENCY: return LOG_EMERG; default: return LOG_ERR; } }
php
private function convertLogLevelFromPSRToSyslog($severity) { switch ($severity) { case LogLevel::DEBUG: return LOG_DEBUG; case LogLevel::INFO: return LOG_INFO; case LogLevel::NOTICE: return LOG_NOTICE; case LogLevel::WARNING: return LOG_WARNING; case LogLevel::ERROR: return LOG_ERR; case LogLevel::CRITICAL: return LOG_CRIT; case LogLevel::ALERT: return LOG_ALERT; case LogLevel::EMERGENCY: return LOG_EMERG; default: return LOG_ERR; } }
[ "private", "function", "convertLogLevelFromPSRToSyslog", "(", "$", "severity", ")", "{", "switch", "(", "$", "severity", ")", "{", "case", "LogLevel", "::", "DEBUG", ":", "return", "LOG_DEBUG", ";", "case", "LogLevel", "::", "INFO", ":", "return", "LOG_INFO", ";", "case", "LogLevel", "::", "NOTICE", ":", "return", "LOG_NOTICE", ";", "case", "LogLevel", "::", "WARNING", ":", "return", "LOG_WARNING", ";", "case", "LogLevel", "::", "ERROR", ":", "return", "LOG_ERR", ";", "case", "LogLevel", "::", "CRITICAL", ":", "return", "LOG_CRIT", ";", "case", "LogLevel", "::", "ALERT", ":", "return", "LOG_ALERT", ";", "case", "LogLevel", "::", "EMERGENCY", ":", "return", "LOG_EMERG", ";", "default", ":", "return", "LOG_ERR", ";", "}", "}" ]
Translate a PRS-3 log level to Syslog log level @param string $severity @return int
[ "Translate", "a", "PRS", "-", "3", "log", "level", "to", "Syslog", "log", "level" ]
ec0960fc32de1a4c583b2447b99d0ef8c801f1ae
https://github.com/QuickenLoans/mcp-logger/blob/ec0960fc32de1a4c583b2447b99d0ef8c801f1ae/src/Service/SyslogService.php#L94-L116
30,937
enygma/expose
src/Expose/Log/Mongo.php
Mongo.log
public function log($level, $message, array $context = array()) { $logger = new \Monolog\Logger('audit'); try { $handler = new \Monolog\Handler\MongoDBHandler( new \Mongo($this->getConnectString()), $this->getDbName(), $this->getDbCollection() ); } catch (\MongoConnectionException $e) { throw new \Exception('Cannot connect to Mongo - please check your server'); } $logger->pushHandler($handler); $logger->pushProcessor(function ($record) { $record['datetime'] = $record['datetime']->format('U'); return $record; }); return $logger->$level($message, $context); }
php
public function log($level, $message, array $context = array()) { $logger = new \Monolog\Logger('audit'); try { $handler = new \Monolog\Handler\MongoDBHandler( new \Mongo($this->getConnectString()), $this->getDbName(), $this->getDbCollection() ); } catch (\MongoConnectionException $e) { throw new \Exception('Cannot connect to Mongo - please check your server'); } $logger->pushHandler($handler); $logger->pushProcessor(function ($record) { $record['datetime'] = $record['datetime']->format('U'); return $record; }); return $logger->$level($message, $context); }
[ "public", "function", "log", "(", "$", "level", ",", "$", "message", ",", "array", "$", "context", "=", "array", "(", ")", ")", "{", "$", "logger", "=", "new", "\\", "Monolog", "\\", "Logger", "(", "'audit'", ")", ";", "try", "{", "$", "handler", "=", "new", "\\", "Monolog", "\\", "Handler", "\\", "MongoDBHandler", "(", "new", "\\", "Mongo", "(", "$", "this", "->", "getConnectString", "(", ")", ")", ",", "$", "this", "->", "getDbName", "(", ")", ",", "$", "this", "->", "getDbCollection", "(", ")", ")", ";", "}", "catch", "(", "\\", "MongoConnectionException", "$", "e", ")", "{", "throw", "new", "\\", "Exception", "(", "'Cannot connect to Mongo - please check your server'", ")", ";", "}", "$", "logger", "->", "pushHandler", "(", "$", "handler", ")", ";", "$", "logger", "->", "pushProcessor", "(", "function", "(", "$", "record", ")", "{", "$", "record", "[", "'datetime'", "]", "=", "$", "record", "[", "'datetime'", "]", "->", "format", "(", "'U'", ")", ";", "return", "$", "record", ";", "}", ")", ";", "return", "$", "logger", "->", "$", "level", "(", "$", "message", ",", "$", "context", ")", ";", "}" ]
Push the log message and context information into Mongo @param string $level Logging level (ex. info, debug, notice...) @param string $message Log message @param array $context Extra context information @return boolean Success/fail of logging
[ "Push", "the", "log", "message", "and", "context", "information", "into", "Mongo" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Log/Mongo.php#L201-L220
30,938
enygma/expose
src/Expose/Console/Command/ProcessQueueCommand.php
ProcessQueueCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $queueType = $input->getOption('queue-type'); $notifyEmail = $input->getOption('notify-email'); $manager = $this->getManager(); if ($notifyEmail !== false) { $notify = new \Expose\Notify\Email(); $notify->setToAddress($notifyEmail); $manager->setNotify($notify); } if ($queueType !== false) { $queueConnect = $input->getOption('queue-connect'); if ($queueConnect === false) { $output->writeln('<error>Queue connection string not provided</error>'); return; } // make the queue object with the right adapter $queueClass = '\\Expose\\Queue\\'.ucwords(strtolower($queueType)); if (!class_exists($queueClass)) { $output->writeln('<error>Invalid queue type "'.$queueType.'"</error>'); return; } $queue = new $queueClass(); $adapter = $this->buildAdapter($queueType, $queueConnect, $queue->getDatabase()); if ($adapter === false) { $output->writeln('<error>Invalid connection string</error>'); return; } $queue->setAdapter($adapter); } else { $output->writeln('<error>Queue type not defined</error>'); return; } $this->setQueue($queue); if ($input->getOption('list') !== false) { $output->writeln('<info>Current Queue Items Pending</info>'); $this->listQueue($manager, $queue); return true; } // by default process the current queue $reports = $this->processQueue($output); if (count($reports) == 0) { return; } $exportFile = $input->getOption('export-file'); if ($exportFile !== false) { $output->writeln('<info>Outputting results to file '.$exportFile.'</info>'); file_put_contents( $exportFile, '['.date('m.d.Y H:i:s').'] '.json_encode($reports), FILE_APPEND ); } else { echo json_encode($reports); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $queueType = $input->getOption('queue-type'); $notifyEmail = $input->getOption('notify-email'); $manager = $this->getManager(); if ($notifyEmail !== false) { $notify = new \Expose\Notify\Email(); $notify->setToAddress($notifyEmail); $manager->setNotify($notify); } if ($queueType !== false) { $queueConnect = $input->getOption('queue-connect'); if ($queueConnect === false) { $output->writeln('<error>Queue connection string not provided</error>'); return; } // make the queue object with the right adapter $queueClass = '\\Expose\\Queue\\'.ucwords(strtolower($queueType)); if (!class_exists($queueClass)) { $output->writeln('<error>Invalid queue type "'.$queueType.'"</error>'); return; } $queue = new $queueClass(); $adapter = $this->buildAdapter($queueType, $queueConnect, $queue->getDatabase()); if ($adapter === false) { $output->writeln('<error>Invalid connection string</error>'); return; } $queue->setAdapter($adapter); } else { $output->writeln('<error>Queue type not defined</error>'); return; } $this->setQueue($queue); if ($input->getOption('list') !== false) { $output->writeln('<info>Current Queue Items Pending</info>'); $this->listQueue($manager, $queue); return true; } // by default process the current queue $reports = $this->processQueue($output); if (count($reports) == 0) { return; } $exportFile = $input->getOption('export-file'); if ($exportFile !== false) { $output->writeln('<info>Outputting results to file '.$exportFile.'</info>'); file_put_contents( $exportFile, '['.date('m.d.Y H:i:s').'] '.json_encode($reports), FILE_APPEND ); } else { echo json_encode($reports); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "queueType", "=", "$", "input", "->", "getOption", "(", "'queue-type'", ")", ";", "$", "notifyEmail", "=", "$", "input", "->", "getOption", "(", "'notify-email'", ")", ";", "$", "manager", "=", "$", "this", "->", "getManager", "(", ")", ";", "if", "(", "$", "notifyEmail", "!==", "false", ")", "{", "$", "notify", "=", "new", "\\", "Expose", "\\", "Notify", "\\", "Email", "(", ")", ";", "$", "notify", "->", "setToAddress", "(", "$", "notifyEmail", ")", ";", "$", "manager", "->", "setNotify", "(", "$", "notify", ")", ";", "}", "if", "(", "$", "queueType", "!==", "false", ")", "{", "$", "queueConnect", "=", "$", "input", "->", "getOption", "(", "'queue-connect'", ")", ";", "if", "(", "$", "queueConnect", "===", "false", ")", "{", "$", "output", "->", "writeln", "(", "'<error>Queue connection string not provided</error>'", ")", ";", "return", ";", "}", "// make the queue object with the right adapter", "$", "queueClass", "=", "'\\\\Expose\\\\Queue\\\\'", ".", "ucwords", "(", "strtolower", "(", "$", "queueType", ")", ")", ";", "if", "(", "!", "class_exists", "(", "$", "queueClass", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<error>Invalid queue type \"'", ".", "$", "queueType", ".", "'\"</error>'", ")", ";", "return", ";", "}", "$", "queue", "=", "new", "$", "queueClass", "(", ")", ";", "$", "adapter", "=", "$", "this", "->", "buildAdapter", "(", "$", "queueType", ",", "$", "queueConnect", ",", "$", "queue", "->", "getDatabase", "(", ")", ")", ";", "if", "(", "$", "adapter", "===", "false", ")", "{", "$", "output", "->", "writeln", "(", "'<error>Invalid connection string</error>'", ")", ";", "return", ";", "}", "$", "queue", "->", "setAdapter", "(", "$", "adapter", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<error>Queue type not defined</error>'", ")", ";", "return", ";", "}", "$", "this", "->", "setQueue", "(", "$", "queue", ")", ";", "if", "(", "$", "input", "->", "getOption", "(", "'list'", ")", "!==", "false", ")", "{", "$", "output", "->", "writeln", "(", "'<info>Current Queue Items Pending</info>'", ")", ";", "$", "this", "->", "listQueue", "(", "$", "manager", ",", "$", "queue", ")", ";", "return", "true", ";", "}", "// by default process the current queue", "$", "reports", "=", "$", "this", "->", "processQueue", "(", "$", "output", ")", ";", "if", "(", "count", "(", "$", "reports", ")", "==", "0", ")", "{", "return", ";", "}", "$", "exportFile", "=", "$", "input", "->", "getOption", "(", "'export-file'", ")", ";", "if", "(", "$", "exportFile", "!==", "false", ")", "{", "$", "output", "->", "writeln", "(", "'<info>Outputting results to file '", ".", "$", "exportFile", ".", "'</info>'", ")", ";", "file_put_contents", "(", "$", "exportFile", ",", "'['", ".", "date", "(", "'m.d.Y H:i:s'", ")", ".", "'] '", ".", "json_encode", "(", "$", "reports", ")", ",", "FILE_APPEND", ")", ";", "}", "else", "{", "echo", "json_encode", "(", "$", "reports", ")", ";", "}", "}" ]
Execute the process-queue command @param InputInterface $input Input object @param OutputInterface $output Output object @return null
[ "Execute", "the", "process", "-", "queue", "command" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Console/Command/ProcessQueueCommand.php#L96-L159
30,939
enygma/expose
src/Expose/Console/Command/ProcessQueueCommand.php
ProcessQueueCommand.processQueue
protected function processQueue(OutputInterface &$output) { $manager = $this->getManager(); $queue = $this->getQueue(); $path = array(); $records = $queue->getPending(); $output->writeln('<info>'.count($records).' records found.</info>'); if (count($records) == 0) { $output->writeln('<error>No records found to process!</error>'); } else { $output->writeln('<info>Processing '.count($records).' records</info>'); } foreach ($records as $record) { $manager->runFilters($record['data'], $path); $queue->markProcessed($record['_id']); } $reports = $manager->getReports(); foreach ($reports as $index => $report) { $reports[$index] = $report->toArray(true); } return $reports; }
php
protected function processQueue(OutputInterface &$output) { $manager = $this->getManager(); $queue = $this->getQueue(); $path = array(); $records = $queue->getPending(); $output->writeln('<info>'.count($records).' records found.</info>'); if (count($records) == 0) { $output->writeln('<error>No records found to process!</error>'); } else { $output->writeln('<info>Processing '.count($records).' records</info>'); } foreach ($records as $record) { $manager->runFilters($record['data'], $path); $queue->markProcessed($record['_id']); } $reports = $manager->getReports(); foreach ($reports as $index => $report) { $reports[$index] = $report->toArray(true); } return $reports; }
[ "protected", "function", "processQueue", "(", "OutputInterface", "&", "$", "output", ")", "{", "$", "manager", "=", "$", "this", "->", "getManager", "(", ")", ";", "$", "queue", "=", "$", "this", "->", "getQueue", "(", ")", ";", "$", "path", "=", "array", "(", ")", ";", "$", "records", "=", "$", "queue", "->", "getPending", "(", ")", ";", "$", "output", "->", "writeln", "(", "'<info>'", ".", "count", "(", "$", "records", ")", ".", "' records found.</info>'", ")", ";", "if", "(", "count", "(", "$", "records", ")", "==", "0", ")", "{", "$", "output", "->", "writeln", "(", "'<error>No records found to process!</error>'", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<info>Processing '", ".", "count", "(", "$", "records", ")", ".", "' records</info>'", ")", ";", "}", "foreach", "(", "$", "records", "as", "$", "record", ")", "{", "$", "manager", "->", "runFilters", "(", "$", "record", "[", "'data'", "]", ",", "$", "path", ")", ";", "$", "queue", "->", "markProcessed", "(", "$", "record", "[", "'_id'", "]", ")", ";", "}", "$", "reports", "=", "$", "manager", "->", "getReports", "(", ")", ";", "foreach", "(", "$", "reports", "as", "$", "index", "=>", "$", "report", ")", "{", "$", "reports", "[", "$", "index", "]", "=", "$", "report", "->", "toArray", "(", "true", ")", ";", "}", "return", "$", "reports", ";", "}" ]
Run the queue processing @param OutputInterface $output Reference to output instance @return array Updated reports set
[ "Run", "the", "queue", "processing" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Console/Command/ProcessQueueCommand.php#L167-L191
30,940
enygma/expose
src/Expose/Console/Command/ProcessQueueCommand.php
ProcessQueueCommand.buildAdapter
protected function buildAdapter($queueType, $queueConnect, $databaseName) { preg_match('/(.+):(.+)@(.+)/', $queueConnect, $connect); if (count($connect) < 4) { return false; } list($full, $username, $password, $host) = $connect; unset($full); switch(strtolower($queueType)) { case 'mongo': if (!extension_loaded('mongo')) { return false; } $connectString = 'mongodb://'.$username.':'.$password.'@'.$host.'/'.$databaseName; $adapter = new \MongoClient($connectString); break; case 'mysql': if (!extension_loaded('mysqli')) { return false; } $adapter = new \mysqli($host, $username, $password, $databaseName); break; } return $adapter; }
php
protected function buildAdapter($queueType, $queueConnect, $databaseName) { preg_match('/(.+):(.+)@(.+)/', $queueConnect, $connect); if (count($connect) < 4) { return false; } list($full, $username, $password, $host) = $connect; unset($full); switch(strtolower($queueType)) { case 'mongo': if (!extension_loaded('mongo')) { return false; } $connectString = 'mongodb://'.$username.':'.$password.'@'.$host.'/'.$databaseName; $adapter = new \MongoClient($connectString); break; case 'mysql': if (!extension_loaded('mysqli')) { return false; } $adapter = new \mysqli($host, $username, $password, $databaseName); break; } return $adapter; }
[ "protected", "function", "buildAdapter", "(", "$", "queueType", ",", "$", "queueConnect", ",", "$", "databaseName", ")", "{", "preg_match", "(", "'/(.+):(.+)@(.+)/'", ",", "$", "queueConnect", ",", "$", "connect", ")", ";", "if", "(", "count", "(", "$", "connect", ")", "<", "4", ")", "{", "return", "false", ";", "}", "list", "(", "$", "full", ",", "$", "username", ",", "$", "password", ",", "$", "host", ")", "=", "$", "connect", ";", "unset", "(", "$", "full", ")", ";", "switch", "(", "strtolower", "(", "$", "queueType", ")", ")", "{", "case", "'mongo'", ":", "if", "(", "!", "extension_loaded", "(", "'mongo'", ")", ")", "{", "return", "false", ";", "}", "$", "connectString", "=", "'mongodb://'", ".", "$", "username", ".", "':'", ".", "$", "password", ".", "'@'", ".", "$", "host", ".", "'/'", ".", "$", "databaseName", ";", "$", "adapter", "=", "new", "\\", "MongoClient", "(", "$", "connectString", ")", ";", "break", ";", "case", "'mysql'", ":", "if", "(", "!", "extension_loaded", "(", "'mysqli'", ")", ")", "{", "return", "false", ";", "}", "$", "adapter", "=", "new", "\\", "mysqli", "(", "$", "host", ",", "$", "username", ",", "$", "password", ",", "$", "databaseName", ")", ";", "break", ";", "}", "return", "$", "adapter", ";", "}" ]
Build an adapter based on the type+connection string @param string $queueType Queue type (Ex. "mongo" or "mysql") @param string $queueConnect Queue connection string (format: user:pass@host) @param string $databaseName Database name @return object Connection adapter
[ "Build", "an", "adapter", "based", "on", "the", "type", "+", "connection", "string" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Console/Command/ProcessQueueCommand.php#L201-L227
30,941
enygma/expose
src/Expose/Converter/Converter.php
Converter.runAllConversions
public function runAllConversions($value) { $misc = new \Expose\Converter\ConvertMisc; $value = $misc->convertFromUrlEncode($value); $value = $misc->convertFromCommented($value); $value = $misc->convertFromWhiteSpace($value); $value = $misc->convertEntities($value); $value = $misc->convertQuotes($value); $value = $misc->convertFromControlChars($value); $value = $misc->convertFromNestedBase64($value); $value = $misc->convertFromOutOfRangeChars($value); $value = $misc->convertFromXML($value); $value = $misc->convertFromUTF7($value); $value = $misc->convertFromConcatenated($value); $value = $misc->convertFromProprietaryEncodings($value); $js = new \Expose\Converter\ConvertJS; $value = $js->convertFromJSCharcode($value); $value = $js->convertJSRegexModifiers($value); $value = $js->convertFromJSUnicode($value); $sql = new \Expose\Converter\ConvertSQL; $value = $sql->convertFromSQLHex($value); $value = $sql->convertFromSQLKeywords($value); $value = $sql->convertFromUrlencodeSqlComment($value); return $value; }
php
public function runAllConversions($value) { $misc = new \Expose\Converter\ConvertMisc; $value = $misc->convertFromUrlEncode($value); $value = $misc->convertFromCommented($value); $value = $misc->convertFromWhiteSpace($value); $value = $misc->convertEntities($value); $value = $misc->convertQuotes($value); $value = $misc->convertFromControlChars($value); $value = $misc->convertFromNestedBase64($value); $value = $misc->convertFromOutOfRangeChars($value); $value = $misc->convertFromXML($value); $value = $misc->convertFromUTF7($value); $value = $misc->convertFromConcatenated($value); $value = $misc->convertFromProprietaryEncodings($value); $js = new \Expose\Converter\ConvertJS; $value = $js->convertFromJSCharcode($value); $value = $js->convertJSRegexModifiers($value); $value = $js->convertFromJSUnicode($value); $sql = new \Expose\Converter\ConvertSQL; $value = $sql->convertFromSQLHex($value); $value = $sql->convertFromSQLKeywords($value); $value = $sql->convertFromUrlencodeSqlComment($value); return $value; }
[ "public", "function", "runAllConversions", "(", "$", "value", ")", "{", "$", "misc", "=", "new", "\\", "Expose", "\\", "Converter", "\\", "ConvertMisc", ";", "$", "value", "=", "$", "misc", "->", "convertFromUrlEncode", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromCommented", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromWhiteSpace", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertEntities", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertQuotes", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromControlChars", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromNestedBase64", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromOutOfRangeChars", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromXML", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromUTF7", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromConcatenated", "(", "$", "value", ")", ";", "$", "value", "=", "$", "misc", "->", "convertFromProprietaryEncodings", "(", "$", "value", ")", ";", "$", "js", "=", "new", "\\", "Expose", "\\", "Converter", "\\", "ConvertJS", ";", "$", "value", "=", "$", "js", "->", "convertFromJSCharcode", "(", "$", "value", ")", ";", "$", "value", "=", "$", "js", "->", "convertJSRegexModifiers", "(", "$", "value", ")", ";", "$", "value", "=", "$", "js", "->", "convertFromJSUnicode", "(", "$", "value", ")", ";", "$", "sql", "=", "new", "\\", "Expose", "\\", "Converter", "\\", "ConvertSQL", ";", "$", "value", "=", "$", "sql", "->", "convertFromSQLHex", "(", "$", "value", ")", ";", "$", "value", "=", "$", "sql", "->", "convertFromSQLKeywords", "(", "$", "value", ")", ";", "$", "value", "=", "$", "sql", "->", "convertFromUrlencodeSqlComment", "(", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Run all the existing conversion methods @param string $value the value to convert @return string
[ "Run", "all", "the", "existing", "conversion", "methods" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/Converter.php#L17-L44
30,942
enygma/expose
src/Expose/Filter.php
Filter.load
public function load($data) { if (is_object($data)) { $data = get_object_vars($data); } foreach ($data as $index => $value) { if ($index == 'tags' && !is_array($value)) { if (isset($value->tag)) { $value = (!is_array($value->tag)) ? array($value->tag) : $value->tag; } } $this->$index = $value; } }
php
public function load($data) { if (is_object($data)) { $data = get_object_vars($data); } foreach ($data as $index => $value) { if ($index == 'tags' && !is_array($value)) { if (isset($value->tag)) { $value = (!is_array($value->tag)) ? array($value->tag) : $value->tag; } } $this->$index = $value; } }
[ "public", "function", "load", "(", "$", "data", ")", "{", "if", "(", "is_object", "(", "$", "data", ")", ")", "{", "$", "data", "=", "get_object_vars", "(", "$", "data", ")", ";", "}", "foreach", "(", "$", "data", "as", "$", "index", "=>", "$", "value", ")", "{", "if", "(", "$", "index", "==", "'tags'", "&&", "!", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "isset", "(", "$", "value", "->", "tag", ")", ")", "{", "$", "value", "=", "(", "!", "is_array", "(", "$", "value", "->", "tag", ")", ")", "?", "array", "(", "$", "value", "->", "tag", ")", ":", "$", "value", "->", "tag", ";", "}", "}", "$", "this", "->", "$", "index", "=", "$", "value", ";", "}", "}" ]
Load the data into the filter object @param array $data Filter data
[ "Load", "the", "data", "into", "the", "filter", "object" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Filter.php#L54-L67
30,943
enygma/expose
src/Expose/Filter.php
Filter.toArray
public function toArray() { return array( 'id' => $this->getId(), 'rule' => $this->getRule(), 'description' => $this->getDescription(), 'tags' => implode(', ', $this->getTags()), 'impact' => $this->getImpact() ); }
php
public function toArray() { return array( 'id' => $this->getId(), 'rule' => $this->getRule(), 'description' => $this->getDescription(), 'tags' => implode(', ', $this->getTags()), 'impact' => $this->getImpact() ); }
[ "public", "function", "toArray", "(", ")", "{", "return", "array", "(", "'id'", "=>", "$", "this", "->", "getId", "(", ")", ",", "'rule'", "=>", "$", "this", "->", "getRule", "(", ")", ",", "'description'", "=>", "$", "this", "->", "getDescription", "(", ")", ",", "'tags'", "=>", "implode", "(", "', '", ",", "$", "this", "->", "getTags", "(", ")", ")", ",", "'impact'", "=>", "$", "this", "->", "getImpact", "(", ")", ")", ";", "}" ]
Return the current Filter's data as an array @return array Filter data
[ "Return", "the", "current", "Filter", "s", "data", "as", "an", "array" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Filter.php#L191-L200
30,944
enygma/expose
src/Expose/Converter/ConvertJS.php
ConvertJS.convertFromJSCharcode
public function convertFromJSCharcode($value) { $matches = array(); // check if value matches typical charCode pattern if (preg_match_all('/(?:[\d+\-=\/ \*]+(?:\s?,\s?\d+)){4,}/ms', $value, $matches)) { $converted = ''; $string = implode(',', $matches[0]); $string = preg_replace('/\s/', '', $string); $string = preg_replace('/\w+=/', '', $string); $charcode = explode(',', $string); foreach ($charcode as $char) { $char = preg_replace('/\W0/s', '', $char); if (preg_match_all('/\d*[+-\/\* ]\d+/', $char, $matches)) { $match = preg_split('/(\W?\d+)/', implode('', $matches[0]), null, PREG_SPLIT_DELIM_CAPTURE); if (array_sum($match) >= 20 && array_sum($match) <= 127) { $converted .= chr(array_sum($match)); } } elseif (!empty($char) && $char >= 20 && $char <= 127) { $converted .= chr($char); } } $value .= "\n" . $converted; } // check for octal charcode pattern if (preg_match_all('/(?:(?:[\\\]+\d+[ \t]*){8,})/ims', $value, $matches)) { $converted = ''; $charcode = explode('\\', preg_replace('/\s/', '', implode(',', $matches[0]))); foreach (array_map('octdec', array_filter($charcode)) as $char) { if (20 <= $char && $char <= 127) { $converted .= chr($char); } } $value .= "\n" . $converted; } // check for hexadecimal charcode pattern if (preg_match_all('/(?:(?:[\\\]+\w+\s*){8,})/ims', $value, $matches)) { $converted = ''; $charcode = explode('\\', preg_replace('/[ux]/', '', implode(',', $matches[0]))); foreach (array_map('hexdec', array_filter($charcode)) as $char) { if (20 <= $char && $char <= 127) { $converted .= chr($char); } } $value .= "\n" . $converted; } return $value; }
php
public function convertFromJSCharcode($value) { $matches = array(); // check if value matches typical charCode pattern if (preg_match_all('/(?:[\d+\-=\/ \*]+(?:\s?,\s?\d+)){4,}/ms', $value, $matches)) { $converted = ''; $string = implode(',', $matches[0]); $string = preg_replace('/\s/', '', $string); $string = preg_replace('/\w+=/', '', $string); $charcode = explode(',', $string); foreach ($charcode as $char) { $char = preg_replace('/\W0/s', '', $char); if (preg_match_all('/\d*[+-\/\* ]\d+/', $char, $matches)) { $match = preg_split('/(\W?\d+)/', implode('', $matches[0]), null, PREG_SPLIT_DELIM_CAPTURE); if (array_sum($match) >= 20 && array_sum($match) <= 127) { $converted .= chr(array_sum($match)); } } elseif (!empty($char) && $char >= 20 && $char <= 127) { $converted .= chr($char); } } $value .= "\n" . $converted; } // check for octal charcode pattern if (preg_match_all('/(?:(?:[\\\]+\d+[ \t]*){8,})/ims', $value, $matches)) { $converted = ''; $charcode = explode('\\', preg_replace('/\s/', '', implode(',', $matches[0]))); foreach (array_map('octdec', array_filter($charcode)) as $char) { if (20 <= $char && $char <= 127) { $converted .= chr($char); } } $value .= "\n" . $converted; } // check for hexadecimal charcode pattern if (preg_match_all('/(?:(?:[\\\]+\w+\s*){8,})/ims', $value, $matches)) { $converted = ''; $charcode = explode('\\', preg_replace('/[ux]/', '', implode(',', $matches[0]))); foreach (array_map('hexdec', array_filter($charcode)) as $char) { if (20 <= $char && $char <= 127) { $converted .= chr($char); } } $value .= "\n" . $converted; } return $value; }
[ "public", "function", "convertFromJSCharcode", "(", "$", "value", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "// check if value matches typical charCode pattern", "if", "(", "preg_match_all", "(", "'/(?:[\\d+\\-=\\/ \\*]+(?:\\s?,\\s?\\d+)){4,}/ms'", ",", "$", "value", ",", "$", "matches", ")", ")", "{", "$", "converted", "=", "''", ";", "$", "string", "=", "implode", "(", "','", ",", "$", "matches", "[", "0", "]", ")", ";", "$", "string", "=", "preg_replace", "(", "'/\\s/'", ",", "''", ",", "$", "string", ")", ";", "$", "string", "=", "preg_replace", "(", "'/\\w+=/'", ",", "''", ",", "$", "string", ")", ";", "$", "charcode", "=", "explode", "(", "','", ",", "$", "string", ")", ";", "foreach", "(", "$", "charcode", "as", "$", "char", ")", "{", "$", "char", "=", "preg_replace", "(", "'/\\W0/s'", ",", "''", ",", "$", "char", ")", ";", "if", "(", "preg_match_all", "(", "'/\\d*[+-\\/\\* ]\\d+/'", ",", "$", "char", ",", "$", "matches", ")", ")", "{", "$", "match", "=", "preg_split", "(", "'/(\\W?\\d+)/'", ",", "implode", "(", "''", ",", "$", "matches", "[", "0", "]", ")", ",", "null", ",", "PREG_SPLIT_DELIM_CAPTURE", ")", ";", "if", "(", "array_sum", "(", "$", "match", ")", ">=", "20", "&&", "array_sum", "(", "$", "match", ")", "<=", "127", ")", "{", "$", "converted", ".=", "chr", "(", "array_sum", "(", "$", "match", ")", ")", ";", "}", "}", "elseif", "(", "!", "empty", "(", "$", "char", ")", "&&", "$", "char", ">=", "20", "&&", "$", "char", "<=", "127", ")", "{", "$", "converted", ".=", "chr", "(", "$", "char", ")", ";", "}", "}", "$", "value", ".=", "\"\\n\"", ".", "$", "converted", ";", "}", "// check for octal charcode pattern", "if", "(", "preg_match_all", "(", "'/(?:(?:[\\\\\\]+\\d+[ \\t]*){8,})/ims'", ",", "$", "value", ",", "$", "matches", ")", ")", "{", "$", "converted", "=", "''", ";", "$", "charcode", "=", "explode", "(", "'\\\\'", ",", "preg_replace", "(", "'/\\s/'", ",", "''", ",", "implode", "(", "','", ",", "$", "matches", "[", "0", "]", ")", ")", ")", ";", "foreach", "(", "array_map", "(", "'octdec'", ",", "array_filter", "(", "$", "charcode", ")", ")", "as", "$", "char", ")", "{", "if", "(", "20", "<=", "$", "char", "&&", "$", "char", "<=", "127", ")", "{", "$", "converted", ".=", "chr", "(", "$", "char", ")", ";", "}", "}", "$", "value", ".=", "\"\\n\"", ".", "$", "converted", ";", "}", "// check for hexadecimal charcode pattern", "if", "(", "preg_match_all", "(", "'/(?:(?:[\\\\\\]+\\w+\\s*){8,})/ims'", ",", "$", "value", ",", "$", "matches", ")", ")", "{", "$", "converted", "=", "''", ";", "$", "charcode", "=", "explode", "(", "'\\\\'", ",", "preg_replace", "(", "'/[ux]/'", ",", "''", ",", "implode", "(", "','", ",", "$", "matches", "[", "0", "]", ")", ")", ")", ";", "foreach", "(", "array_map", "(", "'hexdec'", ",", "array_filter", "(", "$", "charcode", ")", ")", "as", "$", "char", ")", "{", "if", "(", "20", "<=", "$", "char", "&&", "$", "char", "<=", "127", ")", "{", "$", "converted", ".=", "chr", "(", "$", "char", ")", ";", "}", "}", "$", "value", ".=", "\"\\n\"", ".", "$", "converted", ";", "}", "return", "$", "value", ";", "}" ]
Checks for common charcode pattern and decodes them @param string $value the value to convert @return string
[ "Checks", "for", "common", "charcode", "pattern", "and", "decodes", "them" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertJS.php#L18-L64
30,945
enygma/expose
src/Expose/Converter/ConvertJS.php
ConvertJS.convertFromJSUnicode
public function convertFromJSUnicode($value) { $matches = array(); preg_match_all('/\\\u[0-9a-f]{4}/ims', $value, $matches); if (!empty($matches[0])) { foreach ($matches[0] as $match) { $chr = chr(hexdec(substr($match, 2, 4))); $value = str_replace($match, $chr, $value); } $value .= "\n\u0001"; } return $value; }
php
public function convertFromJSUnicode($value) { $matches = array(); preg_match_all('/\\\u[0-9a-f]{4}/ims', $value, $matches); if (!empty($matches[0])) { foreach ($matches[0] as $match) { $chr = chr(hexdec(substr($match, 2, 4))); $value = str_replace($match, $chr, $value); } $value .= "\n\u0001"; } return $value; }
[ "public", "function", "convertFromJSUnicode", "(", "$", "value", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "preg_match_all", "(", "'/\\\\\\u[0-9a-f]{4}/ims'", ",", "$", "value", ",", "$", "matches", ")", ";", "if", "(", "!", "empty", "(", "$", "matches", "[", "0", "]", ")", ")", "{", "foreach", "(", "$", "matches", "[", "0", "]", "as", "$", "match", ")", "{", "$", "chr", "=", "chr", "(", "hexdec", "(", "substr", "(", "$", "match", ",", "2", ",", "4", ")", ")", ")", ";", "$", "value", "=", "str_replace", "(", "$", "match", ",", "$", "chr", ",", "$", "value", ")", ";", "}", "$", "value", ".=", "\"\\n\\u0001\"", ";", "}", "return", "$", "value", ";", "}" ]
This method converts JS unicode code points to regular characters @param string $value the value to convert @return string
[ "This", "method", "converts", "JS", "unicode", "code", "points", "to", "regular", "characters" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertJS.php#L83-L95
30,946
enygma/expose
src/Expose/Notify/Email.php
Email.setToAddress
public function setToAddress($emailAddress) { if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) { throw new \InvalidArgumentException('Invalid email address: '.$emailAddress); } $this->toAddress = $emailAddress; }
php
public function setToAddress($emailAddress) { if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) { throw new \InvalidArgumentException('Invalid email address: '.$emailAddress); } $this->toAddress = $emailAddress; }
[ "public", "function", "setToAddress", "(", "$", "emailAddress", ")", "{", "if", "(", "filter_var", "(", "$", "emailAddress", ",", "FILTER_VALIDATE_EMAIL", ")", "!==", "$", "emailAddress", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid email address: '", ".", "$", "emailAddress", ")", ";", "}", "$", "this", "->", "toAddress", "=", "$", "emailAddress", ";", "}" ]
Set the "To" address for the notification @param string $emailAddress Email address
[ "Set", "the", "To", "address", "for", "the", "notification" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Notify/Email.php#L40-L46
30,947
enygma/expose
src/Expose/Notify/Email.php
Email.setFromAddress
public function setFromAddress($emailAddress) { if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) { throw new \InvalidArgumentException('Invalid email address: '.$emailAddress); } $this->fromAddress = $emailAddress; }
php
public function setFromAddress($emailAddress) { if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) { throw new \InvalidArgumentException('Invalid email address: '.$emailAddress); } $this->fromAddress = $emailAddress; }
[ "public", "function", "setFromAddress", "(", "$", "emailAddress", ")", "{", "if", "(", "filter_var", "(", "$", "emailAddress", ",", "FILTER_VALIDATE_EMAIL", ")", "!==", "$", "emailAddress", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid email address: '", ".", "$", "emailAddress", ")", ";", "}", "$", "this", "->", "fromAddress", "=", "$", "emailAddress", ";", "}" ]
Set the current "From" email address on notifications @param string $emailAddress Email address
[ "Set", "the", "current", "From", "email", "address", "on", "notifications" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Notify/Email.php#L63-L69
30,948
enygma/expose
src/Expose/Notify/Email.php
Email.send
public function send($filterMatches) { $toAddress = $this->getToAddress(); $fromAddress = $this->getFromAddress(); if ($toAddress === null) { throw new \InvalidArgumentException('Invalid "to" email address'); } if ($fromAddress === null) { throw new \InvalidArgumentException('Invalid "from" email address'); } $loader = new \Twig_Loader_Filesystem(__DIR__.'/../Template'); $twig = new \Twig_Environment($loader); $template = $twig->loadTemplate('Notify/Email.twig'); $headers = array( "From: ".$fromAddress, "Content-type: text/html; charset=iso-8859-1" ); $totalImpact = 0; $impactData = array(); foreach ($filterMatches as $match) { $impactData[] = array( 'impact' => $match->getImpact(), 'description' => $match->getDescription(), 'id' => $match->getId(), 'tags' => implode(', ', $match->getTags()) ); $totalImpact += $match->getImpact(); } $subject = 'Expose Notification - Impact Score '.$totalImpact; $body = $template->render(array( 'impactData' => $impactData, 'runTime' => date('r'), 'totalImpact' => $totalImpact )); return mail($toAddress, $subject, $body, implode("\r\n", $headers)); }
php
public function send($filterMatches) { $toAddress = $this->getToAddress(); $fromAddress = $this->getFromAddress(); if ($toAddress === null) { throw new \InvalidArgumentException('Invalid "to" email address'); } if ($fromAddress === null) { throw new \InvalidArgumentException('Invalid "from" email address'); } $loader = new \Twig_Loader_Filesystem(__DIR__.'/../Template'); $twig = new \Twig_Environment($loader); $template = $twig->loadTemplate('Notify/Email.twig'); $headers = array( "From: ".$fromAddress, "Content-type: text/html; charset=iso-8859-1" ); $totalImpact = 0; $impactData = array(); foreach ($filterMatches as $match) { $impactData[] = array( 'impact' => $match->getImpact(), 'description' => $match->getDescription(), 'id' => $match->getId(), 'tags' => implode(', ', $match->getTags()) ); $totalImpact += $match->getImpact(); } $subject = 'Expose Notification - Impact Score '.$totalImpact; $body = $template->render(array( 'impactData' => $impactData, 'runTime' => date('r'), 'totalImpact' => $totalImpact )); return mail($toAddress, $subject, $body, implode("\r\n", $headers)); }
[ "public", "function", "send", "(", "$", "filterMatches", ")", "{", "$", "toAddress", "=", "$", "this", "->", "getToAddress", "(", ")", ";", "$", "fromAddress", "=", "$", "this", "->", "getFromAddress", "(", ")", ";", "if", "(", "$", "toAddress", "===", "null", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid \"to\" email address'", ")", ";", "}", "if", "(", "$", "fromAddress", "===", "null", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid \"from\" email address'", ")", ";", "}", "$", "loader", "=", "new", "\\", "Twig_Loader_Filesystem", "(", "__DIR__", ".", "'/../Template'", ")", ";", "$", "twig", "=", "new", "\\", "Twig_Environment", "(", "$", "loader", ")", ";", "$", "template", "=", "$", "twig", "->", "loadTemplate", "(", "'Notify/Email.twig'", ")", ";", "$", "headers", "=", "array", "(", "\"From: \"", ".", "$", "fromAddress", ",", "\"Content-type: text/html; charset=iso-8859-1\"", ")", ";", "$", "totalImpact", "=", "0", ";", "$", "impactData", "=", "array", "(", ")", ";", "foreach", "(", "$", "filterMatches", "as", "$", "match", ")", "{", "$", "impactData", "[", "]", "=", "array", "(", "'impact'", "=>", "$", "match", "->", "getImpact", "(", ")", ",", "'description'", "=>", "$", "match", "->", "getDescription", "(", ")", ",", "'id'", "=>", "$", "match", "->", "getId", "(", ")", ",", "'tags'", "=>", "implode", "(", "', '", ",", "$", "match", "->", "getTags", "(", ")", ")", ")", ";", "$", "totalImpact", "+=", "$", "match", "->", "getImpact", "(", ")", ";", "}", "$", "subject", "=", "'Expose Notification - Impact Score '", ".", "$", "totalImpact", ";", "$", "body", "=", "$", "template", "->", "render", "(", "array", "(", "'impactData'", "=>", "$", "impactData", ",", "'runTime'", "=>", "date", "(", "'r'", ")", ",", "'totalImpact'", "=>", "$", "totalImpact", ")", ")", ";", "return", "mail", "(", "$", "toAddress", ",", "$", "subject", ",", "$", "body", ",", "implode", "(", "\"\\r\\n\"", ",", "$", "headers", ")", ")", ";", "}" ]
Send the notification to the given email address @param array $filterMatches Set of filter matches from execution @return boolean Success/fail of sending email
[ "Send", "the", "notification", "to", "the", "given", "email", "address" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Notify/Email.php#L87-L129
30,949
enygma/expose
src/Expose/Queue/Mongo.php
Mongo.getCollection
public function getCollection() { $queueDatabase = $this->database; $queueResource = $this->collection; $db = $this->getAdapter(); return $db->$queueDatabase->$queueResource; }
php
public function getCollection() { $queueDatabase = $this->database; $queueResource = $this->collection; $db = $this->getAdapter(); return $db->$queueDatabase->$queueResource; }
[ "public", "function", "getCollection", "(", ")", "{", "$", "queueDatabase", "=", "$", "this", "->", "database", ";", "$", "queueResource", "=", "$", "this", "->", "collection", ";", "$", "db", "=", "$", "this", "->", "getAdapter", "(", ")", ";", "return", "$", "db", "->", "$", "queueDatabase", "->", "$", "queueResource", ";", "}" ]
Get the queue collection @return \MongoCollection Collection instance
[ "Get", "the", "queue", "collection" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Queue/Mongo.php#L47-L54
30,950
enygma/expose
src/Expose/Queue/Mongo.php
Mongo.add
public function add($requestData) { $data = array( 'data' => $requestData, 'remote_ip' => (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : 0, 'datetime' => time(), 'processed' => false ); return $this->getCollection()->insert($data); }
php
public function add($requestData) { $data = array( 'data' => $requestData, 'remote_ip' => (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : 0, 'datetime' => time(), 'processed' => false ); return $this->getCollection()->insert($data); }
[ "public", "function", "add", "(", "$", "requestData", ")", "{", "$", "data", "=", "array", "(", "'data'", "=>", "$", "requestData", ",", "'remote_ip'", "=>", "(", "isset", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ")", ")", "?", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ":", "0", ",", "'datetime'", "=>", "time", "(", ")", ",", "'processed'", "=>", "false", ")", ";", "return", "$", "this", "->", "getCollection", "(", ")", "->", "insert", "(", "$", "data", ")", ";", "}" ]
Add a new record to the queue @param array $requestData Request data
[ "Add", "a", "new", "record", "to", "the", "queue" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Queue/Mongo.php#L61-L72
30,951
enygma/expose
src/Expose/Queue/Mongo.php
Mongo.getPending
public function getPending($limit = 10) { $results = $this->getCollection() ->find(array('processed' => false)) ->limit($limit); return iterator_to_array($results); }
php
public function getPending($limit = 10) { $results = $this->getCollection() ->find(array('processed' => false)) ->limit($limit); return iterator_to_array($results); }
[ "public", "function", "getPending", "(", "$", "limit", "=", "10", ")", "{", "$", "results", "=", "$", "this", "->", "getCollection", "(", ")", "->", "find", "(", "array", "(", "'processed'", "=>", "false", ")", ")", "->", "limit", "(", "$", "limit", ")", ";", "return", "iterator_to_array", "(", "$", "results", ")", ";", "}" ]
Get the current list of pending records @return array Record results
[ "Get", "the", "current", "list", "of", "pending", "records" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Queue/Mongo.php#L93-L100
30,952
enygma/expose
src/Expose/Config.php
Config.get
public function get($path) { $p = explode('.', $path); $cfg = &$this->config; $count = 1; foreach ($p as $part) { if (array_key_exists($part, $cfg)) { // see if it's the end if ($count == count($p)) { echo 'end'; return $cfg[$part]; } $cfg = &$cfg[$part]; } $count++; } return null; }
php
public function get($path) { $p = explode('.', $path); $cfg = &$this->config; $count = 1; foreach ($p as $part) { if (array_key_exists($part, $cfg)) { // see if it's the end if ($count == count($p)) { echo 'end'; return $cfg[$part]; } $cfg = &$cfg[$part]; } $count++; } return null; }
[ "public", "function", "get", "(", "$", "path", ")", "{", "$", "p", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "$", "cfg", "=", "&", "$", "this", "->", "config", ";", "$", "count", "=", "1", ";", "foreach", "(", "$", "p", "as", "$", "part", ")", "{", "if", "(", "array_key_exists", "(", "$", "part", ",", "$", "cfg", ")", ")", "{", "// see if it's the end", "if", "(", "$", "count", "==", "count", "(", "$", "p", ")", ")", "{", "echo", "'end'", ";", "return", "$", "cfg", "[", "$", "part", "]", ";", "}", "$", "cfg", "=", "&", "$", "cfg", "[", "$", "part", "]", ";", "}", "$", "count", "++", ";", "}", "return", "null", ";", "}" ]
Get the value from the config by "path" @param string $path Path to config option (Ex. "foo.bar.baz") @return mixed Either the found value or null if not found
[ "Get", "the", "value", "from", "the", "config", "by", "path" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Config.php#L43-L61
30,953
enygma/expose
src/Expose/Config.php
Config.set
public function set($path, $value) { $p = explode('.', $path); $cfg = &$this->config; $count = 1; foreach ($p as $part) { if ($count == count($p)) { $cfg[$part] = $value; continue; } if (array_key_exists($part, $cfg)) { $cfg = &$cfg[$part]; } else { // create the path $cfg[$part] = array(); $cfg = &$cfg[$part]; } $count++; } }
php
public function set($path, $value) { $p = explode('.', $path); $cfg = &$this->config; $count = 1; foreach ($p as $part) { if ($count == count($p)) { $cfg[$part] = $value; continue; } if (array_key_exists($part, $cfg)) { $cfg = &$cfg[$part]; } else { // create the path $cfg[$part] = array(); $cfg = &$cfg[$part]; } $count++; } }
[ "public", "function", "set", "(", "$", "path", ",", "$", "value", ")", "{", "$", "p", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "$", "cfg", "=", "&", "$", "this", "->", "config", ";", "$", "count", "=", "1", ";", "foreach", "(", "$", "p", "as", "$", "part", ")", "{", "if", "(", "$", "count", "==", "count", "(", "$", "p", ")", ")", "{", "$", "cfg", "[", "$", "part", "]", "=", "$", "value", ";", "continue", ";", "}", "if", "(", "array_key_exists", "(", "$", "part", ",", "$", "cfg", ")", ")", "{", "$", "cfg", "=", "&", "$", "cfg", "[", "$", "part", "]", ";", "}", "else", "{", "// create the path", "$", "cfg", "[", "$", "part", "]", "=", "array", "(", ")", ";", "$", "cfg", "=", "&", "$", "cfg", "[", "$", "part", "]", ";", "}", "$", "count", "++", ";", "}", "}" ]
Set the configuration option based on the "path" @param string $path Config "path" (Ex. "foo.bar.baz") @param mixed $value Value of config
[ "Set", "the", "configuration", "option", "based", "on", "the", "path" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Config.php#L69-L89
30,954
enygma/expose
src/Expose/FilterCollection.php
FilterCollection.setFilterImpact
public function setFilterImpact($filterId, $impact) { $filter = $this->getFilterData($filterId); if($filter === null) { return; } $filter->setImpact($impact); }
php
public function setFilterImpact($filterId, $impact) { $filter = $this->getFilterData($filterId); if($filter === null) { return; } $filter->setImpact($impact); }
[ "public", "function", "setFilterImpact", "(", "$", "filterId", ",", "$", "impact", ")", "{", "$", "filter", "=", "$", "this", "->", "getFilterData", "(", "$", "filterId", ")", ";", "if", "(", "$", "filter", "===", "null", ")", "{", "return", ";", "}", "$", "filter", "->", "setImpact", "(", "$", "impact", ")", ";", "}" ]
Alter the impact level of a specific filter id. @param integer $filterId @param integer $impact
[ "Alter", "the", "impact", "level", "of", "a", "specific", "filter", "id", "." ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/FilterCollection.php#L100-L107
30,955
enygma/expose
src/Expose/Console/Command/FilterCommand.php
FilterCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $col = new \Expose\FilterCollection(); $col->load(); $filters = $col->getFilterData(); $id = $input->getOption('id'); if ($id !== false) { $idList = explode(',', $id); foreach ($idList as $id) { if (array_key_exists($id, $filters)) { $detail = "[".$id."] ".$filters[$id]->getDescription()."\n"; $detail .= "\tRule: ".$filters[$id]->getRule()."\n"; $detail .= "\tTags: ".implode(', ', $filters[$id]->getTags())."\n"; $detail .= "\tImpact: ".$filters[$id]->getImpact()."\n"; $output->writeLn($detail); } else { $output->writeLn('Filter ID '.$id.' not found!'); } } return; } foreach ($filters as $filter) { echo $filter->getId().': '. $filter->getDescription()."\n"; } return; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $col = new \Expose\FilterCollection(); $col->load(); $filters = $col->getFilterData(); $id = $input->getOption('id'); if ($id !== false) { $idList = explode(',', $id); foreach ($idList as $id) { if (array_key_exists($id, $filters)) { $detail = "[".$id."] ".$filters[$id]->getDescription()."\n"; $detail .= "\tRule: ".$filters[$id]->getRule()."\n"; $detail .= "\tTags: ".implode(', ', $filters[$id]->getTags())."\n"; $detail .= "\tImpact: ".$filters[$id]->getImpact()."\n"; $output->writeLn($detail); } else { $output->writeLn('Filter ID '.$id.' not found!'); } } return; } foreach ($filters as $filter) { echo $filter->getId().': '. $filter->getDescription()."\n"; } return; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "col", "=", "new", "\\", "Expose", "\\", "FilterCollection", "(", ")", ";", "$", "col", "->", "load", "(", ")", ";", "$", "filters", "=", "$", "col", "->", "getFilterData", "(", ")", ";", "$", "id", "=", "$", "input", "->", "getOption", "(", "'id'", ")", ";", "if", "(", "$", "id", "!==", "false", ")", "{", "$", "idList", "=", "explode", "(", "','", ",", "$", "id", ")", ";", "foreach", "(", "$", "idList", "as", "$", "id", ")", "{", "if", "(", "array_key_exists", "(", "$", "id", ",", "$", "filters", ")", ")", "{", "$", "detail", "=", "\"[\"", ".", "$", "id", ".", "\"] \"", ".", "$", "filters", "[", "$", "id", "]", "->", "getDescription", "(", ")", ".", "\"\\n\"", ";", "$", "detail", ".=", "\"\\tRule: \"", ".", "$", "filters", "[", "$", "id", "]", "->", "getRule", "(", ")", ".", "\"\\n\"", ";", "$", "detail", ".=", "\"\\tTags: \"", ".", "implode", "(", "', '", ",", "$", "filters", "[", "$", "id", "]", "->", "getTags", "(", ")", ")", ".", "\"\\n\"", ";", "$", "detail", ".=", "\"\\tImpact: \"", ".", "$", "filters", "[", "$", "id", "]", "->", "getImpact", "(", ")", ".", "\"\\n\"", ";", "$", "output", "->", "writeLn", "(", "$", "detail", ")", ";", "}", "else", "{", "$", "output", "->", "writeLn", "(", "'Filter ID '", ".", "$", "id", ".", "' not found!'", ")", ";", "}", "}", "return", ";", "}", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "echo", "$", "filter", "->", "getId", "(", ")", ".", "': '", ".", "$", "filter", "->", "getDescription", "(", ")", ".", "\"\\n\"", ";", "}", "return", ";", "}" ]
Execute the filter command @param InputInterface $input Input object @param OutputInterface $output Output object @return null
[ "Execute", "the", "filter", "command" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Console/Command/FilterCommand.php#L31-L59
30,956
enygma/expose
src/Expose/Converter/ConvertMisc.php
ConvertMisc.convertFromUTF7
public function convertFromUTF7($value) { if (preg_match('/\+A\w+-?/m', $value)) { if (function_exists('mb_convert_encoding')) { if (version_compare(PHP_VERSION, '5.2.8', '<')) { $tmp_chars = str_split($value); $value = ''; foreach ($tmp_chars as $char) { if (ord($char) <= 127) { $value .= $char; } } } $value .= "\n" . mb_convert_encoding($value, 'UTF-8', 'UTF-7'); } else { //list of all critical UTF7 codepoints $schemes = array( '+ACI-' => '"', '+ADw-' => '<', '+AD4-' => '>', '+AFs-' => '[', '+AF0-' => ']', '+AHs-' => '{', '+AH0-' => '}', '+AFw-' => '\\', '+ADs-' => ';', '+ACM-' => '#', '+ACY-' => '&', '+ACU-' => '%', '+ACQ-' => '$', '+AD0-' => '=', '+AGA-' => '`', '+ALQ-' => '"', '+IBg-' => '"', '+IBk-' => '"', '+AHw-' => '|', '+ACo-' => '*', '+AF4-' => '^', '+ACIAPg-' => '">', '+ACIAPgA8-' => '">' ); $value = str_ireplace( array_keys($schemes), array_values($schemes), $value ); } } return $value; }
php
public function convertFromUTF7($value) { if (preg_match('/\+A\w+-?/m', $value)) { if (function_exists('mb_convert_encoding')) { if (version_compare(PHP_VERSION, '5.2.8', '<')) { $tmp_chars = str_split($value); $value = ''; foreach ($tmp_chars as $char) { if (ord($char) <= 127) { $value .= $char; } } } $value .= "\n" . mb_convert_encoding($value, 'UTF-8', 'UTF-7'); } else { //list of all critical UTF7 codepoints $schemes = array( '+ACI-' => '"', '+ADw-' => '<', '+AD4-' => '>', '+AFs-' => '[', '+AF0-' => ']', '+AHs-' => '{', '+AH0-' => '}', '+AFw-' => '\\', '+ADs-' => ';', '+ACM-' => '#', '+ACY-' => '&', '+ACU-' => '%', '+ACQ-' => '$', '+AD0-' => '=', '+AGA-' => '`', '+ALQ-' => '"', '+IBg-' => '"', '+IBk-' => '"', '+AHw-' => '|', '+ACo-' => '*', '+AF4-' => '^', '+ACIAPg-' => '">', '+ACIAPgA8-' => '">' ); $value = str_ireplace( array_keys($schemes), array_values($schemes), $value ); } } return $value; }
[ "public", "function", "convertFromUTF7", "(", "$", "value", ")", "{", "if", "(", "preg_match", "(", "'/\\+A\\w+-?/m'", ",", "$", "value", ")", ")", "{", "if", "(", "function_exists", "(", "'mb_convert_encoding'", ")", ")", "{", "if", "(", "version_compare", "(", "PHP_VERSION", ",", "'5.2.8'", ",", "'<'", ")", ")", "{", "$", "tmp_chars", "=", "str_split", "(", "$", "value", ")", ";", "$", "value", "=", "''", ";", "foreach", "(", "$", "tmp_chars", "as", "$", "char", ")", "{", "if", "(", "ord", "(", "$", "char", ")", "<=", "127", ")", "{", "$", "value", ".=", "$", "char", ";", "}", "}", "}", "$", "value", ".=", "\"\\n\"", ".", "mb_convert_encoding", "(", "$", "value", ",", "'UTF-8'", ",", "'UTF-7'", ")", ";", "}", "else", "{", "//list of all critical UTF7 codepoints", "$", "schemes", "=", "array", "(", "'+ACI-'", "=>", "'\"'", ",", "'+ADw-'", "=>", "'<'", ",", "'+AD4-'", "=>", "'>'", ",", "'+AFs-'", "=>", "'['", ",", "'+AF0-'", "=>", "']'", ",", "'+AHs-'", "=>", "'{'", ",", "'+AH0-'", "=>", "'}'", ",", "'+AFw-'", "=>", "'\\\\'", ",", "'+ADs-'", "=>", "';'", ",", "'+ACM-'", "=>", "'#'", ",", "'+ACY-'", "=>", "'&'", ",", "'+ACU-'", "=>", "'%'", ",", "'+ACQ-'", "=>", "'$'", ",", "'+AD0-'", "=>", "'='", ",", "'+AGA-'", "=>", "'`'", ",", "'+ALQ-'", "=>", "'\"'", ",", "'+IBg-'", "=>", "'\"'", ",", "'+IBk-'", "=>", "'\"'", ",", "'+AHw-'", "=>", "'|'", ",", "'+ACo-'", "=>", "'*'", ",", "'+AF4-'", "=>", "'^'", ",", "'+ACIAPg-'", "=>", "'\">'", ",", "'+ACIAPgA8-'", "=>", "'\">'", ")", ";", "$", "value", "=", "str_ireplace", "(", "array_keys", "(", "$", "schemes", ")", ",", "array_values", "(", "$", "schemes", ")", ",", "$", "value", ")", ";", "}", "}", "return", "$", "value", ";", "}" ]
Converts relevant UTF-7 tags to UTF-8 @param string $value the value to convert @return string
[ "Converts", "relevant", "UTF", "-", "7", "tags", "to", "UTF", "-", "8" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertMisc.php#L222-L271
30,957
enygma/expose
src/Expose/Converter/ConvertMisc.php
ConvertMisc.convertFromUrlEncode
public function convertFromUrlEncode($value) { $converted = urldecode($value); if (!$converted || $converted === $value) { return $value; } else { return $value . "\n" . $converted; } }
php
public function convertFromUrlEncode($value) { $converted = urldecode($value); if (!$converted || $converted === $value) { return $value; } else { return $value . "\n" . $converted; } }
[ "public", "function", "convertFromUrlEncode", "(", "$", "value", ")", "{", "$", "converted", "=", "urldecode", "(", "$", "value", ")", ";", "if", "(", "!", "$", "converted", "||", "$", "converted", "===", "$", "value", ")", "{", "return", "$", "value", ";", "}", "else", "{", "return", "$", "value", ".", "\"\\n\"", ".", "$", "converted", ";", "}", "}" ]
Check for basic urlencoded information @param string $value the value to convert @return string
[ "Check", "for", "basic", "urlencoded", "information" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertMisc.php#L371-L379
30,958
enygma/expose
src/Expose/Manager.php
Manager.processFilters
protected function processFilters($value, $index, $path) { $filterMatches = array(); $filters = $this->getFilters(); $filters->rewind(); while($filters->valid() && !$this->impactLimitReached()) { $filter = $filters->current(); $filters->next(); if ($filter->execute($value) === true) { $filterMatches[] = $filter; $this->getLogger()->info( 'Match found on Filter ID '.$filter->getId(), array($filter->toArray()) ); $report = new \Expose\Report($index, $value, $path); $report->addFilterMatch($filter); $this->reports[] = $report; $this->impact += $filter->getImpact(); } } return $filterMatches; }
php
protected function processFilters($value, $index, $path) { $filterMatches = array(); $filters = $this->getFilters(); $filters->rewind(); while($filters->valid() && !$this->impactLimitReached()) { $filter = $filters->current(); $filters->next(); if ($filter->execute($value) === true) { $filterMatches[] = $filter; $this->getLogger()->info( 'Match found on Filter ID '.$filter->getId(), array($filter->toArray()) ); $report = new \Expose\Report($index, $value, $path); $report->addFilterMatch($filter); $this->reports[] = $report; $this->impact += $filter->getImpact(); } } return $filterMatches; }
[ "protected", "function", "processFilters", "(", "$", "value", ",", "$", "index", ",", "$", "path", ")", "{", "$", "filterMatches", "=", "array", "(", ")", ";", "$", "filters", "=", "$", "this", "->", "getFilters", "(", ")", ";", "$", "filters", "->", "rewind", "(", ")", ";", "while", "(", "$", "filters", "->", "valid", "(", ")", "&&", "!", "$", "this", "->", "impactLimitReached", "(", ")", ")", "{", "$", "filter", "=", "$", "filters", "->", "current", "(", ")", ";", "$", "filters", "->", "next", "(", ")", ";", "if", "(", "$", "filter", "->", "execute", "(", "$", "value", ")", "===", "true", ")", "{", "$", "filterMatches", "[", "]", "=", "$", "filter", ";", "$", "this", "->", "getLogger", "(", ")", "->", "info", "(", "'Match found on Filter ID '", ".", "$", "filter", "->", "getId", "(", ")", ",", "array", "(", "$", "filter", "->", "toArray", "(", ")", ")", ")", ";", "$", "report", "=", "new", "\\", "Expose", "\\", "Report", "(", "$", "index", ",", "$", "value", ",", "$", "path", ")", ";", "$", "report", "->", "addFilterMatch", "(", "$", "filter", ")", ";", "$", "this", "->", "reports", "[", "]", "=", "$", "report", ";", "$", "this", "->", "impact", "+=", "$", "filter", "->", "getImpact", "(", ")", ";", "}", "}", "return", "$", "filterMatches", ";", "}" ]
Runs value through all filters @param $value @param $index @param $path
[ "Runs", "value", "through", "all", "filters" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L239-L262
30,959
enygma/expose
src/Expose/Manager.php
Manager.impactLimitReached
protected function impactLimitReached() { if ($this->impactLimit < 1) { return false; } $reached = $this->impact >= $this->impactLimit; if ($reached) { $this->getLogger()->info( 'Reached Impact limit' ); } return $reached; }
php
protected function impactLimitReached() { if ($this->impactLimit < 1) { return false; } $reached = $this->impact >= $this->impactLimit; if ($reached) { $this->getLogger()->info( 'Reached Impact limit' ); } return $reached; }
[ "protected", "function", "impactLimitReached", "(", ")", "{", "if", "(", "$", "this", "->", "impactLimit", "<", "1", ")", "{", "return", "false", ";", "}", "$", "reached", "=", "$", "this", "->", "impact", ">=", "$", "this", "->", "impactLimit", ";", "if", "(", "$", "reached", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "info", "(", "'Reached Impact limit'", ")", ";", "}", "return", "$", "reached", ";", "}" ]
Tests if the impact limit has been reached @return bool
[ "Tests", "if", "the", "impact", "limit", "has", "been", "reached" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L269-L282
30,960
enygma/expose
src/Expose/Manager.php
Manager.notify
public function notify(array $filterMatches) { $notify = $this->getNotify(); if ($notify === null) { throw new \InvalidArgumentException( 'Invalid notification method' ); } $notify->send($filterMatches); }
php
public function notify(array $filterMatches) { $notify = $this->getNotify(); if ($notify === null) { throw new \InvalidArgumentException( 'Invalid notification method' ); } $notify->send($filterMatches); }
[ "public", "function", "notify", "(", "array", "$", "filterMatches", ")", "{", "$", "notify", "=", "$", "this", "->", "getNotify", "(", ")", ";", "if", "(", "$", "notify", "===", "null", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid notification method'", ")", ";", "}", "$", "notify", "->", "send", "(", "$", "filterMatches", ")", ";", "}" ]
If enabled, send the notification of the test run @param array $filterMatches Set of matches against filters @throws \InvalidArgumentException If notify type is inavlid
[ "If", "enabled", "send", "the", "notification", "of", "the", "test", "run" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L300-L309
30,961
enygma/expose
src/Expose/Manager.php
Manager.isException
public function isException($path) { $isException = false; foreach ($this->exceptions as $exception) { if ($isException === false) { if ($path === $exception || preg_match('/^'.$exception.'$/', $path) !== 0) { $isException = true; } } } return $isException; }
php
public function isException($path) { $isException = false; foreach ($this->exceptions as $exception) { if ($isException === false) { if ($path === $exception || preg_match('/^'.$exception.'$/', $path) !== 0) { $isException = true; } } } return $isException; }
[ "public", "function", "isException", "(", "$", "path", ")", "{", "$", "isException", "=", "false", ";", "foreach", "(", "$", "this", "->", "exceptions", "as", "$", "exception", ")", "{", "if", "(", "$", "isException", "===", "false", ")", "{", "if", "(", "$", "path", "===", "$", "exception", "||", "preg_match", "(", "'/^'", ".", "$", "exception", ".", "'$/'", ",", "$", "path", ")", "!==", "0", ")", "{", "$", "isException", "=", "true", ";", "}", "}", "}", "return", "$", "isException", ";", "}" ]
Test to see if a variable is an exception Checks can be exceptions, so we preg_match it @param string $path Variable "path" (Ex. "POST.foo.bar") @return boolean Found/not found
[ "Test", "to", "see", "if", "a", "variable", "is", "an", "exception", "Checks", "can", "be", "exceptions", "so", "we", "preg_match", "it" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L522-L534
30,962
enygma/expose
src/Expose/Manager.php
Manager.setConfig
public function setConfig($config) { if (is_array($config)) { $this->config = new Config($config); } else { // see if it's a file path if (is_file($config)) { $cfg = parse_ini_file($config, true); $this->config = new Config($cfg); } else { throw new \InvalidArgumentException( 'Could not load configuration file '.$config ); } } }
php
public function setConfig($config) { if (is_array($config)) { $this->config = new Config($config); } else { // see if it's a file path if (is_file($config)) { $cfg = parse_ini_file($config, true); $this->config = new Config($cfg); } else { throw new \InvalidArgumentException( 'Could not load configuration file '.$config ); } } }
[ "public", "function", "setConfig", "(", "$", "config", ")", "{", "if", "(", "is_array", "(", "$", "config", ")", ")", "{", "$", "this", "->", "config", "=", "new", "Config", "(", "$", "config", ")", ";", "}", "else", "{", "// see if it's a file path", "if", "(", "is_file", "(", "$", "config", ")", ")", "{", "$", "cfg", "=", "parse_ini_file", "(", "$", "config", ",", "true", ")", ";", "$", "this", "->", "config", "=", "new", "Config", "(", "$", "cfg", ")", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Could not load configuration file '", ".", "$", "config", ")", ";", "}", "}", "}" ]
Set the configuration for the object @param array|string $config Either an array of config settings or the path to the config file @throws \InvalidArgumentException If config file doesn't exist
[ "Set", "the", "configuration", "for", "the", "object" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L567-L582
30,963
enygma/expose
src/Expose/Manager.php
Manager.export
public function export($format = 'text') { $className = '\\Expose\\Export\\'.ucwords(strtolower($format)); if (class_exists($className)) { $export = new $className($this->getReports()); return $export->render(); } return null; }
php
public function export($format = 'text') { $className = '\\Expose\\Export\\'.ucwords(strtolower($format)); if (class_exists($className)) { $export = new $className($this->getReports()); return $export->render(); } return null; }
[ "public", "function", "export", "(", "$", "format", "=", "'text'", ")", "{", "$", "className", "=", "'\\\\Expose\\\\Export\\\\'", ".", "ucwords", "(", "strtolower", "(", "$", "format", ")", ")", ";", "if", "(", "class_exists", "(", "$", "className", ")", ")", "{", "$", "export", "=", "new", "$", "className", "(", "$", "this", "->", "getReports", "(", ")", ")", ";", "return", "$", "export", "->", "render", "(", ")", ";", "}", "return", "null", ";", "}" ]
Expose the current set of reports in the given format @param string $format Fromat for the export @return mixed Report output (or null if the export type isn't found)
[ "Expose", "the", "current", "set", "of", "reports", "in", "the", "given", "format" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L640-L648
30,964
enygma/expose
src/Expose/Cache/File.php
File.save
public function save($key, $data) { $hash = md5($key); $cacheFile = $this->getPath().'/'.$hash.'.cache'; return file_put_contents($cacheFile, serialize($data)); }
php
public function save($key, $data) { $hash = md5($key); $cacheFile = $this->getPath().'/'.$hash.'.cache'; return file_put_contents($cacheFile, serialize($data)); }
[ "public", "function", "save", "(", "$", "key", ",", "$", "data", ")", "{", "$", "hash", "=", "md5", "(", "$", "key", ")", ";", "$", "cacheFile", "=", "$", "this", "->", "getPath", "(", ")", ".", "'/'", ".", "$", "hash", ".", "'.cache'", ";", "return", "file_put_contents", "(", "$", "cacheFile", ",", "serialize", "(", "$", "data", ")", ")", ";", "}" ]
Save the cache data to a file @param string $key Identifier key (used in filename) @param mixed $data Data to cache @return boolean Success/fail of save
[ "Save", "the", "cache", "data", "to", "a", "file" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Cache/File.php#L20-L26
30,965
enygma/expose
src/Expose/Cache/File.php
File.get
public function get($key) { $hash = md5($key); $cacheFile = $this->getPath().'/'.$hash.'.cache'; if (!is_file($cacheFile)) { return null; } return unserialize(file_get_contents($cacheFile)); }
php
public function get($key) { $hash = md5($key); $cacheFile = $this->getPath().'/'.$hash.'.cache'; if (!is_file($cacheFile)) { return null; } return unserialize(file_get_contents($cacheFile)); }
[ "public", "function", "get", "(", "$", "key", ")", "{", "$", "hash", "=", "md5", "(", "$", "key", ")", ";", "$", "cacheFile", "=", "$", "this", "->", "getPath", "(", ")", ".", "'/'", ".", "$", "hash", ".", "'.cache'", ";", "if", "(", "!", "is_file", "(", "$", "cacheFile", ")", ")", "{", "return", "null", ";", "}", "return", "unserialize", "(", "file_get_contents", "(", "$", "cacheFile", ")", ")", ";", "}" ]
Get the record identified by the given key @param string $key Cache identifier key @return mixed Returns either data or null if not found
[ "Get", "the", "record", "identified", "by", "the", "given", "key" ]
07ee1ebe5af6a23029d4d30147463141df724fc5
https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Cache/File.php#L34-L43
30,966
Brain-WP/Cortex
src/Cortex/Router/Router.php
Router.ensurePreviewVars
private function ensurePreviewVars(array $vars, array $uriVars) { if (! is_user_logged_in()) { return $vars; } foreach (['preview', 'preview_id', 'preview_nonce'] as $var) { if (! isset($vars[$var]) && isset($uriVars[$var])) { $vars[$var] = $uriVars[$var]; } } return $vars; }
php
private function ensurePreviewVars(array $vars, array $uriVars) { if (! is_user_logged_in()) { return $vars; } foreach (['preview', 'preview_id', 'preview_nonce'] as $var) { if (! isset($vars[$var]) && isset($uriVars[$var])) { $vars[$var] = $uriVars[$var]; } } return $vars; }
[ "private", "function", "ensurePreviewVars", "(", "array", "$", "vars", ",", "array", "$", "uriVars", ")", "{", "if", "(", "!", "is_user_logged_in", "(", ")", ")", "{", "return", "$", "vars", ";", "}", "foreach", "(", "[", "'preview'", ",", "'preview_id'", ",", "'preview_nonce'", "]", "as", "$", "var", ")", "{", "if", "(", "!", "isset", "(", "$", "vars", "[", "$", "var", "]", ")", "&&", "isset", "(", "$", "uriVars", "[", "$", "var", "]", ")", ")", "{", "$", "vars", "[", "$", "var", "]", "=", "$", "uriVars", "[", "$", "var", "]", ";", "}", "}", "return", "$", "vars", ";", "}" ]
To ensure preview works, we need to merge preview-related query string to query arguments. @param array $vars @param array $uriVars @return array
[ "To", "ensure", "preview", "works", "we", "need", "to", "merge", "preview", "-", "related", "query", "string", "to", "query", "arguments", "." ]
4c9cf21d3f25775cbd6faf6a75638b1c11ac0368
https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Router/Router.php#L278-L291
30,967
Brain-WP/Cortex
src/Cortex/Uri/PsrUri.php
PsrUri.marshallFromServer
private function marshallFromServer() { $scheme = is_ssl() ? 'https' : 'http'; $host = $this->marshallHostFromServer() ? : parse_url(home_url(), PHP_URL_HOST); $host = trim($host, '/'); $pathArray = explode('?', $this->marshallPathFromServer(), 2); $path = trim($pathArray[0], '/'); empty($path) and $path = '/'; $query_string = ''; if (isset($this->server['QUERY_STRING'])) { $query_string = ltrim($this->server['QUERY_STRING'], '?'); } $this->storage = compact('scheme', 'host', 'path', 'query_string'); $this->parsed = true; }
php
private function marshallFromServer() { $scheme = is_ssl() ? 'https' : 'http'; $host = $this->marshallHostFromServer() ? : parse_url(home_url(), PHP_URL_HOST); $host = trim($host, '/'); $pathArray = explode('?', $this->marshallPathFromServer(), 2); $path = trim($pathArray[0], '/'); empty($path) and $path = '/'; $query_string = ''; if (isset($this->server['QUERY_STRING'])) { $query_string = ltrim($this->server['QUERY_STRING'], '?'); } $this->storage = compact('scheme', 'host', 'path', 'query_string'); $this->parsed = true; }
[ "private", "function", "marshallFromServer", "(", ")", "{", "$", "scheme", "=", "is_ssl", "(", ")", "?", "'https'", ":", "'http'", ";", "$", "host", "=", "$", "this", "->", "marshallHostFromServer", "(", ")", "?", ":", "parse_url", "(", "home_url", "(", ")", ",", "PHP_URL_HOST", ")", ";", "$", "host", "=", "trim", "(", "$", "host", ",", "'/'", ")", ";", "$", "pathArray", "=", "explode", "(", "'?'", ",", "$", "this", "->", "marshallPathFromServer", "(", ")", ",", "2", ")", ";", "$", "path", "=", "trim", "(", "$", "pathArray", "[", "0", "]", ",", "'/'", ")", ";", "empty", "(", "$", "path", ")", "and", "$", "path", "=", "'/'", ";", "$", "query_string", "=", "''", ";", "if", "(", "isset", "(", "$", "this", "->", "server", "[", "'QUERY_STRING'", "]", ")", ")", "{", "$", "query_string", "=", "ltrim", "(", "$", "this", "->", "server", "[", "'QUERY_STRING'", "]", ",", "'?'", ")", ";", "}", "$", "this", "->", "storage", "=", "compact", "(", "'scheme'", ",", "'host'", ",", "'path'", ",", "'query_string'", ")", ";", "$", "this", "->", "parsed", "=", "true", ";", "}" ]
Parse server array to find url components.
[ "Parse", "server", "array", "to", "find", "url", "components", "." ]
4c9cf21d3f25775cbd6faf6a75638b1c11ac0368
https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Uri/PsrUri.php#L222-L241
30,968
Brain-WP/Cortex
src/Cortex/Uri/PsrUri.php
PsrUri.marshallHostFromServer
private function marshallHostFromServer() { $host = isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : ''; if (empty($host)) { return isset($this->server['SERVER_NAME']) ? $this->server['SERVER_NAME'] : ''; } if (is_string($host) && preg_match('|\:(\d+)$|', $host, $matches)) { $host = substr($host, 0, -1 * (strlen($matches[1]) + 1)); } return $host; }
php
private function marshallHostFromServer() { $host = isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : ''; if (empty($host)) { return isset($this->server['SERVER_NAME']) ? $this->server['SERVER_NAME'] : ''; } if (is_string($host) && preg_match('|\:(\d+)$|', $host, $matches)) { $host = substr($host, 0, -1 * (strlen($matches[1]) + 1)); } return $host; }
[ "private", "function", "marshallHostFromServer", "(", ")", "{", "$", "host", "=", "isset", "(", "$", "this", "->", "server", "[", "'HTTP_HOST'", "]", ")", "?", "$", "this", "->", "server", "[", "'HTTP_HOST'", "]", ":", "''", ";", "if", "(", "empty", "(", "$", "host", ")", ")", "{", "return", "isset", "(", "$", "this", "->", "server", "[", "'SERVER_NAME'", "]", ")", "?", "$", "this", "->", "server", "[", "'SERVER_NAME'", "]", ":", "''", ";", "}", "if", "(", "is_string", "(", "$", "host", ")", "&&", "preg_match", "(", "'|\\:(\\d+)$|'", ",", "$", "host", ",", "$", "matches", ")", ")", "{", "$", "host", "=", "substr", "(", "$", "host", ",", "0", ",", "-", "1", "*", "(", "strlen", "(", "$", "matches", "[", "1", "]", ")", "+", "1", ")", ")", ";", "}", "return", "$", "host", ";", "}" ]
Parse server array to find url host. Contains code from Zend\Diactoros\ServerRequestFactory @copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com) @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License @return string
[ "Parse", "server", "array", "to", "find", "url", "host", "." ]
4c9cf21d3f25775cbd6faf6a75638b1c11ac0368
https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Uri/PsrUri.php#L254-L266
30,969
Brain-WP/Cortex
src/Cortex/Uri/PsrUri.php
PsrUri.marshallPathFromServer
private function marshallPathFromServer() { $get = function ($key, array $values, $default = null) { return array_key_exists($key, $values) ? $values[$key] : $default; }; // IIS7 with URL Rewrite: make sure we get the unencoded url // (double slash problem). $iisUrlRewritten = $get('IIS_WasUrlRewritten', $this->server); $unencodedUrl = $get('UNENCODED_URL', $this->server, ''); if ('1' == $iisUrlRewritten && ! empty($unencodedUrl)) { return $unencodedUrl; } $requestUri = $get('REQUEST_URI', $this->server); // Check this first so IIS will catch. $httpXRewriteUrl = $get('HTTP_X_REWRITE_URL', $this->server); if ($httpXRewriteUrl !== null) { $requestUri = $httpXRewriteUrl; } // Check for IIS 7.0 or later with ISAPI_Rewrite $httpXOriginalUrl = $get('HTTP_X_ORIGINAL_URL', $this->server); if ($httpXOriginalUrl !== null) { $requestUri = $httpXOriginalUrl; } if ($requestUri !== null) { return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri); } $origPathInfo = $get('ORIG_PATH_INFO', $this->server); return empty($origPathInfo) ? '/' : $origPathInfo; }
php
private function marshallPathFromServer() { $get = function ($key, array $values, $default = null) { return array_key_exists($key, $values) ? $values[$key] : $default; }; // IIS7 with URL Rewrite: make sure we get the unencoded url // (double slash problem). $iisUrlRewritten = $get('IIS_WasUrlRewritten', $this->server); $unencodedUrl = $get('UNENCODED_URL', $this->server, ''); if ('1' == $iisUrlRewritten && ! empty($unencodedUrl)) { return $unencodedUrl; } $requestUri = $get('REQUEST_URI', $this->server); // Check this first so IIS will catch. $httpXRewriteUrl = $get('HTTP_X_REWRITE_URL', $this->server); if ($httpXRewriteUrl !== null) { $requestUri = $httpXRewriteUrl; } // Check for IIS 7.0 or later with ISAPI_Rewrite $httpXOriginalUrl = $get('HTTP_X_ORIGINAL_URL', $this->server); if ($httpXOriginalUrl !== null) { $requestUri = $httpXOriginalUrl; } if ($requestUri !== null) { return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri); } $origPathInfo = $get('ORIG_PATH_INFO', $this->server); return empty($origPathInfo) ? '/' : $origPathInfo; }
[ "private", "function", "marshallPathFromServer", "(", ")", "{", "$", "get", "=", "function", "(", "$", "key", ",", "array", "$", "values", ",", "$", "default", "=", "null", ")", "{", "return", "array_key_exists", "(", "$", "key", ",", "$", "values", ")", "?", "$", "values", "[", "$", "key", "]", ":", "$", "default", ";", "}", ";", "// IIS7 with URL Rewrite: make sure we get the unencoded url", "// (double slash problem).", "$", "iisUrlRewritten", "=", "$", "get", "(", "'IIS_WasUrlRewritten'", ",", "$", "this", "->", "server", ")", ";", "$", "unencodedUrl", "=", "$", "get", "(", "'UNENCODED_URL'", ",", "$", "this", "->", "server", ",", "''", ")", ";", "if", "(", "'1'", "==", "$", "iisUrlRewritten", "&&", "!", "empty", "(", "$", "unencodedUrl", ")", ")", "{", "return", "$", "unencodedUrl", ";", "}", "$", "requestUri", "=", "$", "get", "(", "'REQUEST_URI'", ",", "$", "this", "->", "server", ")", ";", "// Check this first so IIS will catch.", "$", "httpXRewriteUrl", "=", "$", "get", "(", "'HTTP_X_REWRITE_URL'", ",", "$", "this", "->", "server", ")", ";", "if", "(", "$", "httpXRewriteUrl", "!==", "null", ")", "{", "$", "requestUri", "=", "$", "httpXRewriteUrl", ";", "}", "// Check for IIS 7.0 or later with ISAPI_Rewrite", "$", "httpXOriginalUrl", "=", "$", "get", "(", "'HTTP_X_ORIGINAL_URL'", ",", "$", "this", "->", "server", ")", ";", "if", "(", "$", "httpXOriginalUrl", "!==", "null", ")", "{", "$", "requestUri", "=", "$", "httpXOriginalUrl", ";", "}", "if", "(", "$", "requestUri", "!==", "null", ")", "{", "return", "preg_replace", "(", "'#^[^/:]+://[^/]+#'", ",", "''", ",", "$", "requestUri", ")", ";", "}", "$", "origPathInfo", "=", "$", "get", "(", "'ORIG_PATH_INFO'", ",", "$", "this", "->", "server", ")", ";", "return", "empty", "(", "$", "origPathInfo", ")", "?", "'/'", ":", "$", "origPathInfo", ";", "}" ]
Parse server array to find url path. Contains code from Zend\Diactoros\ServerRequestFactory @copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com) @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License @return string
[ "Parse", "server", "array", "to", "find", "url", "path", "." ]
4c9cf21d3f25775cbd6faf6a75638b1c11ac0368
https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Uri/PsrUri.php#L279-L314
30,970
huyanping/simple-fork-php
src/Queue/SystemVMessageQueue.php
SystemVMessageQueue.setStatus
public function setStatus($key, $value) { $this->checkSetPrivilege($key); if ($key == 'msg_qbytes') return $this->setMaxQueueSize($value); $queue_status[$key] = $value; return \msg_set_queue($this->queue, $queue_status); }
php
public function setStatus($key, $value) { $this->checkSetPrivilege($key); if ($key == 'msg_qbytes') return $this->setMaxQueueSize($value); $queue_status[$key] = $value; return \msg_set_queue($this->queue, $queue_status); }
[ "public", "function", "setStatus", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "checkSetPrivilege", "(", "$", "key", ")", ";", "if", "(", "$", "key", "==", "'msg_qbytes'", ")", "return", "$", "this", "->", "setMaxQueueSize", "(", "$", "value", ")", ";", "$", "queue_status", "[", "$", "key", "]", "=", "$", "value", ";", "return", "\\", "msg_set_queue", "(", "$", "this", "->", "queue", ",", "$", "queue_status", ")", ";", "}" ]
allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure @param string $key status key @param int $value status value @return bool
[ "allows", "you", "to", "change", "the", "values", "of", "the", "msg_perm", ".", "uid", "msg_perm", ".", "gid", "msg_perm", ".", "mode", "and", "msg_qbytes", "fields", "of", "the", "underlying", "message", "queue", "data", "structure" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/SystemVMessageQueue.php#L213-L221
30,971
huyanping/simple-fork-php
src/Queue/Pipe.php
Pipe.read
public function read($size = 1024) { if (!is_resource($this->read)) { $this->read = fopen($this->filename, 'r+'); if (!is_resource($this->read)) { throw new \RuntimeException('open file failed'); } if (!$this->block) { $set = stream_set_blocking($this->read, false); if (!$set) { throw new \RuntimeException('stream_set_blocking failed'); } } } return fread($this->read, $size); }
php
public function read($size = 1024) { if (!is_resource($this->read)) { $this->read = fopen($this->filename, 'r+'); if (!is_resource($this->read)) { throw new \RuntimeException('open file failed'); } if (!$this->block) { $set = stream_set_blocking($this->read, false); if (!$set) { throw new \RuntimeException('stream_set_blocking failed'); } } } return fread($this->read, $size); }
[ "public", "function", "read", "(", "$", "size", "=", "1024", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "read", ")", ")", "{", "$", "this", "->", "read", "=", "fopen", "(", "$", "this", "->", "filename", ",", "'r+'", ")", ";", "if", "(", "!", "is_resource", "(", "$", "this", "->", "read", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'open file failed'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "block", ")", "{", "$", "set", "=", "stream_set_blocking", "(", "$", "this", "->", "read", ",", "false", ")", ";", "if", "(", "!", "$", "set", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'stream_set_blocking failed'", ")", ";", "}", "}", "}", "return", "fread", "(", "$", "this", "->", "read", ",", "$", "size", ")", ";", "}" ]
if the stream is blocking, you would better set the value of size, it will not return until the data size is equal to the value of param size @param int $size @return string
[ "if", "the", "stream", "is", "blocking", "you", "would", "better", "set", "the", "value", "of", "size", "it", "will", "not", "return", "until", "the", "data", "size", "is", "equal", "to", "the", "value", "of", "param", "size" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/Pipe.php#L78-L94
30,972
huyanping/simple-fork-php
src/FixedPool.php
FixedPool.wait
public function wait($block = false, $interval = 100) { do { if ($this->isFinished()) { return; } parent::wait(false); if ($this->aliveCount() < $this->max) { foreach ($this->processes as $process) { if ($process->isStarted()) continue; $process->start(); if ($this->aliveCount() >= $this->max) break; } } $block ? usleep($interval) : null; } while ($block); }
php
public function wait($block = false, $interval = 100) { do { if ($this->isFinished()) { return; } parent::wait(false); if ($this->aliveCount() < $this->max) { foreach ($this->processes as $process) { if ($process->isStarted()) continue; $process->start(); if ($this->aliveCount() >= $this->max) break; } } $block ? usleep($interval) : null; } while ($block); }
[ "public", "function", "wait", "(", "$", "block", "=", "false", ",", "$", "interval", "=", "100", ")", "{", "do", "{", "if", "(", "$", "this", "->", "isFinished", "(", ")", ")", "{", "return", ";", "}", "parent", "::", "wait", "(", "false", ")", ";", "if", "(", "$", "this", "->", "aliveCount", "(", ")", "<", "$", "this", "->", "max", ")", "{", "foreach", "(", "$", "this", "->", "processes", "as", "$", "process", ")", "{", "if", "(", "$", "process", "->", "isStarted", "(", ")", ")", "continue", ";", "$", "process", "->", "start", "(", ")", ";", "if", "(", "$", "this", "->", "aliveCount", "(", ")", ">=", "$", "this", "->", "max", ")", "break", ";", "}", "}", "$", "block", "?", "usleep", "(", "$", "interval", ")", ":", "null", ";", "}", "while", "(", "$", "block", ")", ";", "}" ]
wait for all process done @param bool $block block the master process to keep the sub process count all the time @param int $interval check time interval
[ "wait", "for", "all", "process", "done" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/FixedPool.php#L49-L65
30,973
huyanping/simple-fork-php
src/Utils.php
Utils.checkOverwriteRunMethod
public static function checkOverwriteRunMethod($child_class) { $parent_class = '\\Jenner\\SimpleFork\\Process'; if ($child_class == $parent_class) { $message = "you should extend the `{$parent_class}`" . ' and overwrite the run method'; throw new \RuntimeException($message); } $child = new \ReflectionClass($child_class); if ($child->getParentClass() === false) { $message = "you should extend the `{$parent_class}`" . ' and overwrite the run method'; throw new \RuntimeException($message); } $parent_methods = $child->getParentClass()->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($parent_methods as $parent_method) { if ($parent_method->getName() !== 'run') continue; $declaring_class = $child->getMethod($parent_method->getName()) ->getDeclaringClass() ->getName(); if ($declaring_class === $parent_class) { throw new \RuntimeException('you must overwrite the run method'); } } }
php
public static function checkOverwriteRunMethod($child_class) { $parent_class = '\\Jenner\\SimpleFork\\Process'; if ($child_class == $parent_class) { $message = "you should extend the `{$parent_class}`" . ' and overwrite the run method'; throw new \RuntimeException($message); } $child = new \ReflectionClass($child_class); if ($child->getParentClass() === false) { $message = "you should extend the `{$parent_class}`" . ' and overwrite the run method'; throw new \RuntimeException($message); } $parent_methods = $child->getParentClass()->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($parent_methods as $parent_method) { if ($parent_method->getName() !== 'run') continue; $declaring_class = $child->getMethod($parent_method->getName()) ->getDeclaringClass() ->getName(); if ($declaring_class === $parent_class) { throw new \RuntimeException('you must overwrite the run method'); } } }
[ "public", "static", "function", "checkOverwriteRunMethod", "(", "$", "child_class", ")", "{", "$", "parent_class", "=", "'\\\\Jenner\\\\SimpleFork\\\\Process'", ";", "if", "(", "$", "child_class", "==", "$", "parent_class", ")", "{", "$", "message", "=", "\"you should extend the `{$parent_class}`\"", ".", "' and overwrite the run method'", ";", "throw", "new", "\\", "RuntimeException", "(", "$", "message", ")", ";", "}", "$", "child", "=", "new", "\\", "ReflectionClass", "(", "$", "child_class", ")", ";", "if", "(", "$", "child", "->", "getParentClass", "(", ")", "===", "false", ")", "{", "$", "message", "=", "\"you should extend the `{$parent_class}`\"", ".", "' and overwrite the run method'", ";", "throw", "new", "\\", "RuntimeException", "(", "$", "message", ")", ";", "}", "$", "parent_methods", "=", "$", "child", "->", "getParentClass", "(", ")", "->", "getMethods", "(", "\\", "ReflectionMethod", "::", "IS_PUBLIC", ")", ";", "foreach", "(", "$", "parent_methods", "as", "$", "parent_method", ")", "{", "if", "(", "$", "parent_method", "->", "getName", "(", ")", "!==", "'run'", ")", "continue", ";", "$", "declaring_class", "=", "$", "child", "->", "getMethod", "(", "$", "parent_method", "->", "getName", "(", ")", ")", "->", "getDeclaringClass", "(", ")", "->", "getName", "(", ")", ";", "if", "(", "$", "declaring_class", "===", "$", "parent_class", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'you must overwrite the run method'", ")", ";", "}", "}", "}" ]
check if the sub class of Process has overwrite the run method @param $child_class
[ "check", "if", "the", "sub", "class", "of", "Process", "has", "overwrite", "the", "run", "method" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Utils.php#L18-L47
30,974
huyanping/simple-fork-php
src/Process.php
Process.initStatus
protected function initStatus() { $this->pid = null; $this->running = null; $this->term_signal = null; $this->stop_signal = null; $this->errno = null; $this->errmsg = null; }
php
protected function initStatus() { $this->pid = null; $this->running = null; $this->term_signal = null; $this->stop_signal = null; $this->errno = null; $this->errmsg = null; }
[ "protected", "function", "initStatus", "(", ")", "{", "$", "this", "->", "pid", "=", "null", ";", "$", "this", "->", "running", "=", "null", ";", "$", "this", "->", "term_signal", "=", "null", ";", "$", "this", "->", "stop_signal", "=", "null", ";", "$", "this", "->", "errno", "=", "null", ";", "$", "this", "->", "errmsg", "=", "null", ";", "}" ]
init process status
[ "init", "process", "status" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L99-L107
30,975
huyanping/simple-fork-php
src/Process.php
Process.start
public function start() { if (!empty($this->pid) && $this->isRunning()) { throw new \LogicException("the process is already running"); } $callback = $this->getCallable(); $pid = pcntl_fork(); if ($pid < 0) { throw new \RuntimeException("fork error"); } elseif ($pid > 0) { $this->pid = $pid; $this->running = true; $this->started = true; } else { $this->pid = getmypid(); $this->signal(); foreach ($this->signal_handlers as $signal => $handler) { pcntl_signal($signal, $handler); } call_user_func($callback); exit(0); } }
php
public function start() { if (!empty($this->pid) && $this->isRunning()) { throw new \LogicException("the process is already running"); } $callback = $this->getCallable(); $pid = pcntl_fork(); if ($pid < 0) { throw new \RuntimeException("fork error"); } elseif ($pid > 0) { $this->pid = $pid; $this->running = true; $this->started = true; } else { $this->pid = getmypid(); $this->signal(); foreach ($this->signal_handlers as $signal => $handler) { pcntl_signal($signal, $handler); } call_user_func($callback); exit(0); } }
[ "public", "function", "start", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "pid", ")", "&&", "$", "this", "->", "isRunning", "(", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"the process is already running\"", ")", ";", "}", "$", "callback", "=", "$", "this", "->", "getCallable", "(", ")", ";", "$", "pid", "=", "pcntl_fork", "(", ")", ";", "if", "(", "$", "pid", "<", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"fork error\"", ")", ";", "}", "elseif", "(", "$", "pid", ">", "0", ")", "{", "$", "this", "->", "pid", "=", "$", "pid", ";", "$", "this", "->", "running", "=", "true", ";", "$", "this", "->", "started", "=", "true", ";", "}", "else", "{", "$", "this", "->", "pid", "=", "getmypid", "(", ")", ";", "$", "this", "->", "signal", "(", ")", ";", "foreach", "(", "$", "this", "->", "signal_handlers", "as", "$", "signal", "=>", "$", "handler", ")", "{", "pcntl_signal", "(", "$", "signal", ",", "$", "handler", ")", ";", "}", "call_user_func", "(", "$", "callback", ")", ";", "exit", "(", "0", ")", ";", "}", "}" ]
start the sub process and run the callback @return string pid
[ "start", "the", "sub", "process", "and", "run", "the", "callback" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L189-L213
30,976
huyanping/simple-fork-php
src/Process.php
Process.updateStatus
protected function updateStatus($block = false) { if ($this->running !== true) { return; } if ($block) { $res = pcntl_waitpid($this->pid, $status); } else { $res = pcntl_waitpid($this->pid, $status, WNOHANG | WUNTRACED); } if ($res === -1) { throw new \RuntimeException('pcntl_waitpid failed. the process maybe available'); } elseif ($res === 0) { $this->running = true; } else { if (pcntl_wifsignaled($status)) { $this->term_signal = pcntl_wtermsig($status); } if (pcntl_wifstopped($status)) { $this->stop_signal = pcntl_wstopsig($status); } if (pcntl_wifexited($status)) { $this->errno = pcntl_wexitstatus($status); $this->errmsg = pcntl_strerror($this->errno); } else { $this->errno = pcntl_get_last_error(); $this->errmsg = pcntl_strerror($this->errno); } if (pcntl_wifsignaled($status)) { $this->if_signal = true; } else { $this->if_signal = false; } $this->running = false; } }
php
protected function updateStatus($block = false) { if ($this->running !== true) { return; } if ($block) { $res = pcntl_waitpid($this->pid, $status); } else { $res = pcntl_waitpid($this->pid, $status, WNOHANG | WUNTRACED); } if ($res === -1) { throw new \RuntimeException('pcntl_waitpid failed. the process maybe available'); } elseif ($res === 0) { $this->running = true; } else { if (pcntl_wifsignaled($status)) { $this->term_signal = pcntl_wtermsig($status); } if (pcntl_wifstopped($status)) { $this->stop_signal = pcntl_wstopsig($status); } if (pcntl_wifexited($status)) { $this->errno = pcntl_wexitstatus($status); $this->errmsg = pcntl_strerror($this->errno); } else { $this->errno = pcntl_get_last_error(); $this->errmsg = pcntl_strerror($this->errno); } if (pcntl_wifsignaled($status)) { $this->if_signal = true; } else { $this->if_signal = false; } $this->running = false; } }
[ "protected", "function", "updateStatus", "(", "$", "block", "=", "false", ")", "{", "if", "(", "$", "this", "->", "running", "!==", "true", ")", "{", "return", ";", "}", "if", "(", "$", "block", ")", "{", "$", "res", "=", "pcntl_waitpid", "(", "$", "this", "->", "pid", ",", "$", "status", ")", ";", "}", "else", "{", "$", "res", "=", "pcntl_waitpid", "(", "$", "this", "->", "pid", ",", "$", "status", ",", "WNOHANG", "|", "WUNTRACED", ")", ";", "}", "if", "(", "$", "res", "===", "-", "1", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'pcntl_waitpid failed. the process maybe available'", ")", ";", "}", "elseif", "(", "$", "res", "===", "0", ")", "{", "$", "this", "->", "running", "=", "true", ";", "}", "else", "{", "if", "(", "pcntl_wifsignaled", "(", "$", "status", ")", ")", "{", "$", "this", "->", "term_signal", "=", "pcntl_wtermsig", "(", "$", "status", ")", ";", "}", "if", "(", "pcntl_wifstopped", "(", "$", "status", ")", ")", "{", "$", "this", "->", "stop_signal", "=", "pcntl_wstopsig", "(", "$", "status", ")", ";", "}", "if", "(", "pcntl_wifexited", "(", "$", "status", ")", ")", "{", "$", "this", "->", "errno", "=", "pcntl_wexitstatus", "(", "$", "status", ")", ";", "$", "this", "->", "errmsg", "=", "pcntl_strerror", "(", "$", "this", "->", "errno", ")", ";", "}", "else", "{", "$", "this", "->", "errno", "=", "pcntl_get_last_error", "(", ")", ";", "$", "this", "->", "errmsg", "=", "pcntl_strerror", "(", "$", "this", "->", "errno", ")", ";", "}", "if", "(", "pcntl_wifsignaled", "(", "$", "status", ")", ")", "{", "$", "this", "->", "if_signal", "=", "true", ";", "}", "else", "{", "$", "this", "->", "if_signal", "=", "false", ";", "}", "$", "this", "->", "running", "=", "false", ";", "}", "}" ]
update the process status @param bool $block
[ "update", "the", "process", "status" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L231-L269
30,977
huyanping/simple-fork-php
src/Process.php
Process.getCallable
protected function getCallable() { $callback = null; if (is_object($this->runnable) && $this->runnable instanceof Runnable) { $callback = array($this->runnable, 'run'); } elseif (is_callable($this->runnable)) { $callback = $this->runnable; } else { $callback = array($this, 'run'); } return $callback; }
php
protected function getCallable() { $callback = null; if (is_object($this->runnable) && $this->runnable instanceof Runnable) { $callback = array($this->runnable, 'run'); } elseif (is_callable($this->runnable)) { $callback = $this->runnable; } else { $callback = array($this, 'run'); } return $callback; }
[ "protected", "function", "getCallable", "(", ")", "{", "$", "callback", "=", "null", ";", "if", "(", "is_object", "(", "$", "this", "->", "runnable", ")", "&&", "$", "this", "->", "runnable", "instanceof", "Runnable", ")", "{", "$", "callback", "=", "array", "(", "$", "this", "->", "runnable", ",", "'run'", ")", ";", "}", "elseif", "(", "is_callable", "(", "$", "this", "->", "runnable", ")", ")", "{", "$", "callback", "=", "$", "this", "->", "runnable", ";", "}", "else", "{", "$", "callback", "=", "array", "(", "$", "this", ",", "'run'", ")", ";", "}", "return", "$", "callback", ";", "}" ]
get sub process callback @return array|callable|null
[ "get", "sub", "process", "callback" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L276-L288
30,978
huyanping/simple-fork-php
src/Process.php
Process.wait
public function wait($block = true, $sleep = 100000) { while (true) { if ($this->isRunning() === false) { return; } if (!$block) { break; } usleep($sleep); } }
php
public function wait($block = true, $sleep = 100000) { while (true) { if ($this->isRunning() === false) { return; } if (!$block) { break; } usleep($sleep); } }
[ "public", "function", "wait", "(", "$", "block", "=", "true", ",", "$", "sleep", "=", "100000", ")", "{", "while", "(", "true", ")", "{", "if", "(", "$", "this", "->", "isRunning", "(", ")", "===", "false", ")", "{", "return", ";", "}", "if", "(", "!", "$", "block", ")", "{", "break", ";", "}", "usleep", "(", "$", "sleep", ")", ";", "}", "}" ]
waiting for the sub process exit @param bool|true $block if block the process @param int $sleep default 0.1s check sub process status every $sleep milliseconds.
[ "waiting", "for", "the", "sub", "process", "exit" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L330-L341
30,979
huyanping/simple-fork-php
src/Lock/Semaphore.php
Semaphore._stringToSemKey
protected function _stringToSemKey($identifier) { $md5 = md5($identifier); $key = 0; for ($i = 0; $i < 32; $i++) { $key += ord($md5{$i}) * $i; } return $key; }
php
protected function _stringToSemKey($identifier) { $md5 = md5($identifier); $key = 0; for ($i = 0; $i < 32; $i++) { $key += ord($md5{$i}) * $i; } return $key; }
[ "protected", "function", "_stringToSemKey", "(", "$", "identifier", ")", "{", "$", "md5", "=", "md5", "(", "$", "identifier", ")", ";", "$", "key", "=", "0", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "32", ";", "$", "i", "++", ")", "{", "$", "key", "+=", "ord", "(", "$", "md5", "{", "$", "i", "}", ")", "*", "$", "i", ";", "}", "return", "$", "key", ";", "}" ]
Semaphore requires a numeric value as the key @param $identifier @return int
[ "Semaphore", "requires", "a", "numeric", "value", "as", "the", "key" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Lock/Semaphore.php#L48-L56
30,980
huyanping/simple-fork-php
src/Lock/Semaphore.php
Semaphore.remove
public function remove() { if ($this->locked) { throw new \RuntimeException('can not remove a locked semaphore resource'); } if (!is_resource($this->lock_id)) { throw new \RuntimeException('can not remove a empty semaphore resource'); } if (!sem_release($this->lock_id)) { return false; } return true; }
php
public function remove() { if ($this->locked) { throw new \RuntimeException('can not remove a locked semaphore resource'); } if (!is_resource($this->lock_id)) { throw new \RuntimeException('can not remove a empty semaphore resource'); } if (!sem_release($this->lock_id)) { return false; } return true; }
[ "public", "function", "remove", "(", ")", "{", "if", "(", "$", "this", "->", "locked", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'can not remove a locked semaphore resource'", ")", ";", "}", "if", "(", "!", "is_resource", "(", "$", "this", "->", "lock_id", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'can not remove a empty semaphore resource'", ")", ";", "}", "if", "(", "!", "sem_release", "(", "$", "this", "->", "lock_id", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
remove the semaphore resource @return bool
[ "remove", "the", "semaphore", "resource" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Lock/Semaphore.php#L148-L162
30,981
huyanping/simple-fork-php
src/Cache/SharedMemory.php
SharedMemory.attach
public function attach($file = __FILE__) { if (!file_exists($file)) { $touch = touch($file); if (!$touch) { throw new \RuntimeException("file is not exists and it can not be created. file: {$file}"); } } $key = ftok($file, 'a'); $this->shm = shm_attach($key, $this->size); //allocate shared memory }
php
public function attach($file = __FILE__) { if (!file_exists($file)) { $touch = touch($file); if (!$touch) { throw new \RuntimeException("file is not exists and it can not be created. file: {$file}"); } } $key = ftok($file, 'a'); $this->shm = shm_attach($key, $this->size); //allocate shared memory }
[ "public", "function", "attach", "(", "$", "file", "=", "__FILE__", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "$", "touch", "=", "touch", "(", "$", "file", ")", ";", "if", "(", "!", "$", "touch", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"file is not exists and it can not be created. file: {$file}\"", ")", ";", "}", "}", "$", "key", "=", "ftok", "(", "$", "file", ",", "'a'", ")", ";", "$", "this", "->", "shm", "=", "shm_attach", "(", "$", "key", ",", "$", "this", "->", "size", ")", ";", "//allocate shared memory", "}" ]
connect shared memory @param string $file
[ "connect", "shared", "memory" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Cache/SharedMemory.php#L60-L70
30,982
huyanping/simple-fork-php
src/Cache/SharedMemory.php
SharedMemory.remove
public function remove() { //dallocate shared memory if (!shm_remove($this->shm)) { return false; } $this->dettach(); // shm_remove maybe not working. it likes a php bug. unset($this->shm); return true; }
php
public function remove() { //dallocate shared memory if (!shm_remove($this->shm)) { return false; } $this->dettach(); // shm_remove maybe not working. it likes a php bug. unset($this->shm); return true; }
[ "public", "function", "remove", "(", ")", "{", "//dallocate shared memory", "if", "(", "!", "shm_remove", "(", "$", "this", "->", "shm", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "dettach", "(", ")", ";", "// shm_remove maybe not working. it likes a php bug.", "unset", "(", "$", "this", "->", "shm", ")", ";", "return", "true", ";", "}" ]
remove shared memory. you should know that it maybe does not work. @return bool
[ "remove", "shared", "memory", ".", "you", "should", "know", "that", "it", "maybe", "does", "not", "work", "." ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Cache/SharedMemory.php#L78-L89
30,983
huyanping/simple-fork-php
src/Cache/SharedMemory.php
SharedMemory.has
public function has($key) { if (shm_has_var($this->shm, $this->shm_key($key))) { // check is isset return true; } else { return false; } }
php
public function has($key) { if (shm_has_var($this->shm, $this->shm_key($key))) { // check is isset return true; } else { return false; } }
[ "public", "function", "has", "(", "$", "key", ")", "{", "if", "(", "shm_has_var", "(", "$", "this", "->", "shm", ",", "$", "this", "->", "shm_key", "(", "$", "key", ")", ")", ")", "{", "// check is isset", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
has var ? @param $key @return bool
[ "has", "var", "?" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Cache/SharedMemory.php#L145-L152
30,984
huyanping/simple-fork-php
src/Pool.php
Pool.execute
public function execute(Process $process, $name = null) { if (!is_null($name)) { $process->name($name); } if (!$process->isStarted()) { $process->start(); } return array_push($this->processes, $process); }
php
public function execute(Process $process, $name = null) { if (!is_null($name)) { $process->name($name); } if (!$process->isStarted()) { $process->start(); } return array_push($this->processes, $process); }
[ "public", "function", "execute", "(", "Process", "$", "process", ",", "$", "name", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "name", ")", ")", "{", "$", "process", "->", "name", "(", "$", "name", ")", ";", "}", "if", "(", "!", "$", "process", "->", "isStarted", "(", ")", ")", "{", "$", "process", "->", "start", "(", ")", ";", "}", "return", "array_push", "(", "$", "this", "->", "processes", ",", "$", "process", ")", ";", "}" ]
add a process @param Process $process @param null|string $name process name @return int
[ "add", "a", "process" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Pool.php#L27-L37
30,985
huyanping/simple-fork-php
src/AbstractPool.php
AbstractPool.getProcessByPid
public function getProcessByPid($pid) { foreach ($this->processes as $process) { if ($process->getPid() == $pid) { return $process; } } return null; }
php
public function getProcessByPid($pid) { foreach ($this->processes as $process) { if ($process->getPid() == $pid) { return $process; } } return null; }
[ "public", "function", "getProcessByPid", "(", "$", "pid", ")", "{", "foreach", "(", "$", "this", "->", "processes", "as", "$", "process", ")", "{", "if", "(", "$", "process", "->", "getPid", "(", ")", "==", "$", "pid", ")", "{", "return", "$", "process", ";", "}", "}", "return", "null", ";", "}" ]
get process by pid @param $pid @return null|Process
[ "get", "process", "by", "pid" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L32-L41
30,986
huyanping/simple-fork-php
src/AbstractPool.php
AbstractPool.shutdown
public function shutdown($signal = SIGTERM) { foreach ($this->processes as $process) { if ($process->isRunning()) { $process->shutdown(true, $signal); } } }
php
public function shutdown($signal = SIGTERM) { foreach ($this->processes as $process) { if ($process->isRunning()) { $process->shutdown(true, $signal); } } }
[ "public", "function", "shutdown", "(", "$", "signal", "=", "SIGTERM", ")", "{", "foreach", "(", "$", "this", "->", "processes", "as", "$", "process", ")", "{", "if", "(", "$", "process", "->", "isRunning", "(", ")", ")", "{", "$", "process", "->", "shutdown", "(", "true", ",", "$", "signal", ")", ";", "}", "}", "}" ]
shutdown all process @param int $signal
[ "shutdown", "all", "process" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L57-L64
30,987
huyanping/simple-fork-php
src/AbstractPool.php
AbstractPool.wait
public function wait($block = true, $sleep = 100) { do { foreach ($this->processes as $process) { if (!$process->isRunning()) { continue; } } usleep($sleep); } while ($block && $this->aliveCount() > 0); }
php
public function wait($block = true, $sleep = 100) { do { foreach ($this->processes as $process) { if (!$process->isRunning()) { continue; } } usleep($sleep); } while ($block && $this->aliveCount() > 0); }
[ "public", "function", "wait", "(", "$", "block", "=", "true", ",", "$", "sleep", "=", "100", ")", "{", "do", "{", "foreach", "(", "$", "this", "->", "processes", "as", "$", "process", ")", "{", "if", "(", "!", "$", "process", "->", "isRunning", "(", ")", ")", "{", "continue", ";", "}", "}", "usleep", "(", "$", "sleep", ")", ";", "}", "while", "(", "$", "block", "&&", "$", "this", "->", "aliveCount", "(", ")", ">", "0", ")", ";", "}" ]
waiting for the sub processes to exit @param bool|true $block if true the parent process will be blocked until all sub processes exit. else it will check if there are processes that had been exited once and return. @param int $sleep when $block is true, it will check sub processes every $sleep minute
[ "waiting", "for", "the", "sub", "processes", "to", "exit" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L88-L98
30,988
huyanping/simple-fork-php
src/AbstractPool.php
AbstractPool.aliveCount
public function aliveCount() { $count = 0; foreach ($this->processes as $process) { if ($process->isRunning()) { $count++; } } return $count; }
php
public function aliveCount() { $count = 0; foreach ($this->processes as $process) { if ($process->isRunning()) { $count++; } } return $count; }
[ "public", "function", "aliveCount", "(", ")", "{", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "processes", "as", "$", "process", ")", "{", "if", "(", "$", "process", "->", "isRunning", "(", ")", ")", "{", "$", "count", "++", ";", "}", "}", "return", "$", "count", ";", "}" ]
get the count of running processes @return int
[ "get", "the", "count", "of", "running", "processes" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L105-L115
30,989
huyanping/simple-fork-php
src/AbstractPool.php
AbstractPool.getProcessByName
public function getProcessByName($name) { foreach ($this->processes as $process) { if ($process->name() == $name) { return $process; } } return null; }
php
public function getProcessByName($name) { foreach ($this->processes as $process) { if ($process->name() == $name) { return $process; } } return null; }
[ "public", "function", "getProcessByName", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "processes", "as", "$", "process", ")", "{", "if", "(", "$", "process", "->", "name", "(", ")", "==", "$", "name", ")", "{", "return", "$", "process", ";", "}", "}", "return", "null", ";", "}" ]
get process by name @param string $name process name @return Process|null
[ "get", "process", "by", "name" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L123-L132
30,990
huyanping/simple-fork-php
src/AbstractPool.php
AbstractPool.removeProcessByName
public function removeProcessByName($name) { foreach ($this->processes as $key => $process) { if ($process->name() == $name) { if ($process->isRunning()) { throw new \RuntimeException("can not remove a running process"); } unset($this->processes[$key]); } } }
php
public function removeProcessByName($name) { foreach ($this->processes as $key => $process) { if ($process->name() == $name) { if ($process->isRunning()) { throw new \RuntimeException("can not remove a running process"); } unset($this->processes[$key]); } } }
[ "public", "function", "removeProcessByName", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "processes", "as", "$", "key", "=>", "$", "process", ")", "{", "if", "(", "$", "process", "->", "name", "(", ")", "==", "$", "name", ")", "{", "if", "(", "$", "process", "->", "isRunning", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"can not remove a running process\"", ")", ";", "}", "unset", "(", "$", "this", "->", "processes", "[", "$", "key", "]", ")", ";", "}", "}", "}" ]
remove process by name @param string $name process name @throws \RuntimeException
[ "remove", "process", "by", "name" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L140-L150
30,991
huyanping/simple-fork-php
src/AbstractPool.php
AbstractPool.removeExitedProcess
public function removeExitedProcess() { foreach ($this->processes as $key => $process) { if ($process->isStopped()) { unset($this->processes[$key]); } } }
php
public function removeExitedProcess() { foreach ($this->processes as $key => $process) { if ($process->isStopped()) { unset($this->processes[$key]); } } }
[ "public", "function", "removeExitedProcess", "(", ")", "{", "foreach", "(", "$", "this", "->", "processes", "as", "$", "key", "=>", "$", "process", ")", "{", "if", "(", "$", "process", "->", "isStopped", "(", ")", ")", "{", "unset", "(", "$", "this", "->", "processes", "[", "$", "key", "]", ")", ";", "}", "}", "}" ]
remove exited process
[ "remove", "exited", "process" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L155-L162
30,992
huyanping/simple-fork-php
src/ParallelPool.php
ParallelPool.reload
public function reload($block = true) { $old_processes = $this->processes; for ($i = 0; $i < $this->max; $i++) { $process = new Process($this->runnable); $process->start(); $this->processes[$process->getPid()] = $process; } foreach ($old_processes as $process) { $process->shutdown(); $process->wait($block); unset($this->processes[$process->getPid()]); } }
php
public function reload($block = true) { $old_processes = $this->processes; for ($i = 0; $i < $this->max; $i++) { $process = new Process($this->runnable); $process->start(); $this->processes[$process->getPid()] = $process; } foreach ($old_processes as $process) { $process->shutdown(); $process->wait($block); unset($this->processes[$process->getPid()]); } }
[ "public", "function", "reload", "(", "$", "block", "=", "true", ")", "{", "$", "old_processes", "=", "$", "this", "->", "processes", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "this", "->", "max", ";", "$", "i", "++", ")", "{", "$", "process", "=", "new", "Process", "(", "$", "this", "->", "runnable", ")", ";", "$", "process", "->", "start", "(", ")", ";", "$", "this", "->", "processes", "[", "$", "process", "->", "getPid", "(", ")", "]", "=", "$", "process", ";", "}", "foreach", "(", "$", "old_processes", "as", "$", "process", ")", "{", "$", "process", "->", "shutdown", "(", ")", ";", "$", "process", "->", "wait", "(", "$", "block", ")", ";", "unset", "(", "$", "this", "->", "processes", "[", "$", "process", "->", "getPid", "(", ")", "]", ")", ";", "}", "}" ]
start the same number processes and kill the old sub process just like nginx -s reload this method will block until all the old process exit; @param bool $block
[ "start", "the", "same", "number", "processes", "and", "kill", "the", "old", "sub", "process", "just", "like", "nginx", "-", "s", "reload", "this", "method", "will", "block", "until", "all", "the", "old", "process", "exit", ";" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/ParallelPool.php#L50-L64
30,993
huyanping/simple-fork-php
src/ParallelPool.php
ParallelPool.keep
public function keep($block = false, $interval = 100) { do { $this->start(); // recycle sub process and delete the processes // which are not running from process list foreach ($this->processes as $process) { if (!$process->isRunning()) { unset($this->processes[$process->getPid()]); } } $block ? usleep($interval) : null; } while ($block); }
php
public function keep($block = false, $interval = 100) { do { $this->start(); // recycle sub process and delete the processes // which are not running from process list foreach ($this->processes as $process) { if (!$process->isRunning()) { unset($this->processes[$process->getPid()]); } } $block ? usleep($interval) : null; } while ($block); }
[ "public", "function", "keep", "(", "$", "block", "=", "false", ",", "$", "interval", "=", "100", ")", "{", "do", "{", "$", "this", "->", "start", "(", ")", ";", "// recycle sub process and delete the processes", "// which are not running from process list", "foreach", "(", "$", "this", "->", "processes", "as", "$", "process", ")", "{", "if", "(", "!", "$", "process", "->", "isRunning", "(", ")", ")", "{", "unset", "(", "$", "this", "->", "processes", "[", "$", "process", "->", "getPid", "(", ")", "]", ")", ";", "}", "}", "$", "block", "?", "usleep", "(", "$", "interval", ")", ":", "null", ";", "}", "while", "(", "$", "block", ")", ";", "}" ]
keep sub process count @param bool $block block the master process to keep the sub process count all the time @param int $interval check time interval
[ "keep", "sub", "process", "count" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/ParallelPool.php#L73-L88
30,994
huyanping/simple-fork-php
src/ParallelPool.php
ParallelPool.start
public function start() { $alive_count = $this->aliveCount(); // create sub process and run if ($alive_count < $this->max) { $need = $this->max - $alive_count; for ($i = 0; $i < $need; $i++) { $process = new Process($this->runnable); $process->start(); $this->processes[$process->getPid()] = $process; } } }
php
public function start() { $alive_count = $this->aliveCount(); // create sub process and run if ($alive_count < $this->max) { $need = $this->max - $alive_count; for ($i = 0; $i < $need; $i++) { $process = new Process($this->runnable); $process->start(); $this->processes[$process->getPid()] = $process; } } }
[ "public", "function", "start", "(", ")", "{", "$", "alive_count", "=", "$", "this", "->", "aliveCount", "(", ")", ";", "// create sub process and run", "if", "(", "$", "alive_count", "<", "$", "this", "->", "max", ")", "{", "$", "need", "=", "$", "this", "->", "max", "-", "$", "alive_count", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "need", ";", "$", "i", "++", ")", "{", "$", "process", "=", "new", "Process", "(", "$", "this", "->", "runnable", ")", ";", "$", "process", "->", "start", "(", ")", ";", "$", "this", "->", "processes", "[", "$", "process", "->", "getPid", "(", ")", "]", "=", "$", "process", ";", "}", "}", "}" ]
start the pool
[ "start", "the", "pool" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/ParallelPool.php#L93-L105
30,995
huyanping/simple-fork-php
src/Queue/PipeQueue.php
PipeQueue.put
public function put($value) { $len = strlen($value); if ($len > 2147483647) { throw new \RuntimeException('value is too long'); } $raw = pack('N', $len) . $value; $write_len = $this->pipe->write($raw); return $write_len == strlen($raw); }
php
public function put($value) { $len = strlen($value); if ($len > 2147483647) { throw new \RuntimeException('value is too long'); } $raw = pack('N', $len) . $value; $write_len = $this->pipe->write($raw); return $write_len == strlen($raw); }
[ "public", "function", "put", "(", "$", "value", ")", "{", "$", "len", "=", "strlen", "(", "$", "value", ")", ";", "if", "(", "$", "len", ">", "2147483647", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'value is too long'", ")", ";", "}", "$", "raw", "=", "pack", "(", "'N'", ",", "$", "len", ")", ".", "$", "value", ";", "$", "write_len", "=", "$", "this", "->", "pipe", "->", "write", "(", "$", "raw", ")", ";", "return", "$", "write_len", "==", "strlen", "(", "$", "raw", ")", ";", "}" ]
put value into the queue of channel @param $value @return bool
[ "put", "value", "into", "the", "queue", "of", "channel" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/PipeQueue.php#L42-L52
30,996
huyanping/simple-fork-php
src/Queue/PipeQueue.php
PipeQueue.get
public function get($block = false) { if ($this->block != $block) { $this->pipe->setBlock($block); $this->block = $block; } $len = $this->pipe->read(4); if ($len === false) { throw new \RuntimeException('read pipe failed'); } if (strlen($len) === 0) { return null; } $len = unpack('N', $len); if (empty($len) || !array_key_exists(1, $len) || empty($len[1])) { throw new \RuntimeException('data protocol error'); } $len = intval($len[1]); $value = ''; while (true) { $temp = $this->pipe->read($len); if (strlen($temp) == $len) { return $temp; } $value .= $temp; $len -= strlen($temp); if ($len == 0) { return $value; } } }
php
public function get($block = false) { if ($this->block != $block) { $this->pipe->setBlock($block); $this->block = $block; } $len = $this->pipe->read(4); if ($len === false) { throw new \RuntimeException('read pipe failed'); } if (strlen($len) === 0) { return null; } $len = unpack('N', $len); if (empty($len) || !array_key_exists(1, $len) || empty($len[1])) { throw new \RuntimeException('data protocol error'); } $len = intval($len[1]); $value = ''; while (true) { $temp = $this->pipe->read($len); if (strlen($temp) == $len) { return $temp; } $value .= $temp; $len -= strlen($temp); if ($len == 0) { return $value; } } }
[ "public", "function", "get", "(", "$", "block", "=", "false", ")", "{", "if", "(", "$", "this", "->", "block", "!=", "$", "block", ")", "{", "$", "this", "->", "pipe", "->", "setBlock", "(", "$", "block", ")", ";", "$", "this", "->", "block", "=", "$", "block", ";", "}", "$", "len", "=", "$", "this", "->", "pipe", "->", "read", "(", "4", ")", ";", "if", "(", "$", "len", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'read pipe failed'", ")", ";", "}", "if", "(", "strlen", "(", "$", "len", ")", "===", "0", ")", "{", "return", "null", ";", "}", "$", "len", "=", "unpack", "(", "'N'", ",", "$", "len", ")", ";", "if", "(", "empty", "(", "$", "len", ")", "||", "!", "array_key_exists", "(", "1", ",", "$", "len", ")", "||", "empty", "(", "$", "len", "[", "1", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'data protocol error'", ")", ";", "}", "$", "len", "=", "intval", "(", "$", "len", "[", "1", "]", ")", ";", "$", "value", "=", "''", ";", "while", "(", "true", ")", "{", "$", "temp", "=", "$", "this", "->", "pipe", "->", "read", "(", "$", "len", ")", ";", "if", "(", "strlen", "(", "$", "temp", ")", "==", "$", "len", ")", "{", "return", "$", "temp", ";", "}", "$", "value", ".=", "$", "temp", ";", "$", "len", "-=", "strlen", "(", "$", "temp", ")", ";", "if", "(", "$", "len", "==", "0", ")", "{", "return", "$", "value", ";", "}", "}", "}" ]
get value from the queue of channel @param bool $block if block when the queue is empty @return bool|string
[ "get", "value", "from", "the", "queue", "of", "channel" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/PipeQueue.php#L60-L92
30,997
huyanping/simple-fork-php
src/Queue/RedisQueue.php
RedisQueue.put
public function put($value) { if ($this->redis->lPush($this->channel, $value) !== false) { return true; } return false; }
php
public function put($value) { if ($this->redis->lPush($this->channel, $value) !== false) { return true; } return false; }
[ "public", "function", "put", "(", "$", "value", ")", "{", "if", "(", "$", "this", "->", "redis", "->", "lPush", "(", "$", "this", "->", "channel", ",", "$", "value", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
put value into the queue @param $value @return bool
[ "put", "value", "into", "the", "queue" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/RedisQueue.php#L76-L84
30,998
huyanping/simple-fork-php
src/Queue/RedisQueue.php
RedisQueue.get
public function get($block = false) { if (!$block) { return $this->redis->rPop($this->channel); } else { while (true) { $record = $this->redis->rPop($this->channel); if ($record === false) { usleep(1000); continue; } return $record; } } }
php
public function get($block = false) { if (!$block) { return $this->redis->rPop($this->channel); } else { while (true) { $record = $this->redis->rPop($this->channel); if ($record === false) { usleep(1000); continue; } return $record; } } }
[ "public", "function", "get", "(", "$", "block", "=", "false", ")", "{", "if", "(", "!", "$", "block", ")", "{", "return", "$", "this", "->", "redis", "->", "rPop", "(", "$", "this", "->", "channel", ")", ";", "}", "else", "{", "while", "(", "true", ")", "{", "$", "record", "=", "$", "this", "->", "redis", "->", "rPop", "(", "$", "this", "->", "channel", ")", ";", "if", "(", "$", "record", "===", "false", ")", "{", "usleep", "(", "1000", ")", ";", "continue", ";", "}", "return", "$", "record", ";", "}", "}", "}" ]
get value from the queue @param bool $block if block when the queue is empty @return bool|string
[ "get", "value", "from", "the", "queue" ]
4af8f61b283a612492ca9ab790472309ce681156
https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/RedisQueue.php#L92-L107
30,999
jkphl/micrometa
src/Micrometa/Ports/Item/Item.php
Item.getPropertyIndex
protected function getPropertyIndex(array $propertyValues, $index) { // If the property value index is out of bounds if (!isset($propertyValues[$index])) { throw new OutOfBoundsException( sprintf(OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX_STR, $index), OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX ); } return $this->getPropertyValue($propertyValues[$index]); }
php
protected function getPropertyIndex(array $propertyValues, $index) { // If the property value index is out of bounds if (!isset($propertyValues[$index])) { throw new OutOfBoundsException( sprintf(OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX_STR, $index), OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX ); } return $this->getPropertyValue($propertyValues[$index]); }
[ "protected", "function", "getPropertyIndex", "(", "array", "$", "propertyValues", ",", "$", "index", ")", "{", "// If the property value index is out of bounds", "if", "(", "!", "isset", "(", "$", "propertyValues", "[", "$", "index", "]", ")", ")", "{", "throw", "new", "OutOfBoundsException", "(", "sprintf", "(", "OutOfBoundsException", "::", "INVALID_PROPERTY_VALUE_INDEX_STR", ",", "$", "index", ")", ",", "OutOfBoundsException", "::", "INVALID_PROPERTY_VALUE_INDEX", ")", ";", "}", "return", "$", "this", "->", "getPropertyValue", "(", "$", "propertyValues", "[", "$", "index", "]", ")", ";", "}" ]
Return a particular property index @param ValueInterface[] $propertyValues Property values @param int $index Property value index @return ValueInterface|ItemInterface
[ "Return", "a", "particular", "property", "index" ]
eb7d5159a7f43b352d13b370a4269c17e1a23d3e
https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/Item.php#L124-L135