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
partition
stringclasses
1 value
thephpleague/url
src/Components/AbstractComponent.php
AbstractComponent.sanitizeComponent
protected function sanitizeComponent($str) { if (is_null($str)) { return $str; } $str = filter_var((string) $str, FILTER_UNSAFE_RAW, array('flags' => FILTER_FLAG_STRIP_LOW)); $str = trim($str); return $str; }
php
protected function sanitizeComponent($str) { if (is_null($str)) { return $str; } $str = filter_var((string) $str, FILTER_UNSAFE_RAW, array('flags' => FILTER_FLAG_STRIP_LOW)); $str = trim($str); return $str; }
[ "protected", "function", "sanitizeComponent", "(", "$", "str", ")", "{", "if", "(", "is_null", "(", "$", "str", ")", ")", "{", "return", "$", "str", ";", "}", "$", "str", "=", "filter_var", "(", "(", "string", ")", "$", "str", ",", "FILTER_UNSAFE_RAW...
Sanitize a string component @param mixed $str @return string|null
[ "Sanitize", "a", "string", "component" ]
45f5529ea879ffc166cc4e4ffa478a212c183628
https://github.com/thephpleague/url/blob/45f5529ea879ffc166cc4e4ffa478a212c183628/src/Components/AbstractComponent.php#L99-L108
train
thephpleague/url
src/Components/AbstractSegment.php
AbstractSegment.sanitizeValue
protected function sanitizeValue($str) { if (is_array($str)) { foreach ($str as &$value) { $value = $this->sanitizeValue($value); } unset($value); return $str; } $str = filter_var((string) $str, FILTER_UNSAFE_RAW, array('flags' => FILTER_FLAG_STRIP_LOW)); $str = trim($str); return $str; }
php
protected function sanitizeValue($str) { if (is_array($str)) { foreach ($str as &$value) { $value = $this->sanitizeValue($value); } unset($value); return $str; } $str = filter_var((string) $str, FILTER_UNSAFE_RAW, array('flags' => FILTER_FLAG_STRIP_LOW)); $str = trim($str); return $str; }
[ "protected", "function", "sanitizeValue", "(", "$", "str", ")", "{", "if", "(", "is_array", "(", "$", "str", ")", ")", "{", "foreach", "(", "$", "str", "as", "&", "$", "value", ")", "{", "$", "value", "=", "$", "this", "->", "sanitizeValue", "(", ...
Sanitize a string component recursively @param mixed $str @return mixed
[ "Sanitize", "a", "string", "component", "recursively" ]
45f5529ea879ffc166cc4e4ffa478a212c183628
https://github.com/thephpleague/url/blob/45f5529ea879ffc166cc4e4ffa478a212c183628/src/Components/AbstractSegment.php#L95-L110
train
thephpleague/url
src/Components/AbstractSegment.php
AbstractSegment.offsetSet
public function offsetSet($offset, $value) { $data = $this->data; if (is_null($offset)) { $data[] = $value; $this->set($data); return; } $offset = filter_var($offset, FILTER_VALIDATE_INT, array('min_range' => 0)); if (false === $offset) { throw new InvalidArgumentException('Offset must be an integer'); } $data[$offset] = $value; $this->set($data); }
php
public function offsetSet($offset, $value) { $data = $this->data; if (is_null($offset)) { $data[] = $value; $this->set($data); return; } $offset = filter_var($offset, FILTER_VALIDATE_INT, array('min_range' => 0)); if (false === $offset) { throw new InvalidArgumentException('Offset must be an integer'); } $data[$offset] = $value; $this->set($data); }
[ "public", "function", "offsetSet", "(", "$", "offset", ",", "$", "value", ")", "{", "$", "data", "=", "$", "this", "->", "data", ";", "if", "(", "is_null", "(", "$", "offset", ")", ")", "{", "$", "data", "[", "]", "=", "$", "value", ";", "$", ...
ArrayAccess Interface method @param int|string $offset @param mixed $value
[ "ArrayAccess", "Interface", "method" ]
45f5529ea879ffc166cc4e4ffa478a212c183628
https://github.com/thephpleague/url/blob/45f5529ea879ffc166cc4e4ffa478a212c183628/src/Components/AbstractSegment.php#L118-L133
train
thephpleague/url
src/Components/AbstractSegment.php
AbstractSegment.validateSegment
protected function validateSegment($data) { $delimiter = $this->delimiter; return $this->convertToArray($data, function ($str) use ($delimiter) { if ('' == $str) { return array(); } if ($delimiter == $str[0]) { $str = substr($str, 1); } return explode($delimiter, $str); }); }
php
protected function validateSegment($data) { $delimiter = $this->delimiter; return $this->convertToArray($data, function ($str) use ($delimiter) { if ('' == $str) { return array(); } if ($delimiter == $str[0]) { $str = substr($str, 1); } return explode($delimiter, $str); }); }
[ "protected", "function", "validateSegment", "(", "$", "data", ")", "{", "$", "delimiter", "=", "$", "this", "->", "delimiter", ";", "return", "$", "this", "->", "convertToArray", "(", "$", "data", ",", "function", "(", "$", "str", ")", "use", "(", "$",...
Validate data before insertion into a URL segment based component @param mixed $data the data to insert @return array @throws \RuntimeException if the data is not valid
[ "Validate", "data", "before", "insertion", "into", "a", "URL", "segment", "based", "component" ]
45f5529ea879ffc166cc4e4ffa478a212c183628
https://github.com/thephpleague/url/blob/45f5529ea879ffc166cc4e4ffa478a212c183628/src/Components/AbstractSegment.php#L199-L213
train
thephpleague/url
src/Components/AbstractSegment.php
AbstractSegment.appendSegment
protected function appendSegment(array $left, array $value, $whence = null, $whence_index = null) { $right = array(); if (null !== $whence && count($found = array_keys($left, $whence))) { array_reverse($found); $index = $found[0]; if (array_key_exists($whence_index, $found)) { $index = $found[$whence_index]; } $right = array_slice($left, $index+1); $left = array_slice($left, 0, $index+1); } return array_merge($left, $value, $right); }
php
protected function appendSegment(array $left, array $value, $whence = null, $whence_index = null) { $right = array(); if (null !== $whence && count($found = array_keys($left, $whence))) { array_reverse($found); $index = $found[0]; if (array_key_exists($whence_index, $found)) { $index = $found[$whence_index]; } $right = array_slice($left, $index+1); $left = array_slice($left, 0, $index+1); } return array_merge($left, $value, $right); }
[ "protected", "function", "appendSegment", "(", "array", "$", "left", ",", "array", "$", "value", ",", "$", "whence", "=", "null", ",", "$", "whence_index", "=", "null", ")", "{", "$", "right", "=", "array", "(", ")", ";", "if", "(", "null", "!==", ...
Append some data to a given array @param array $left the original array @param array $value the data to prepend @param string $whence the value of the data to prepend before @param integer $whence_index the occurrence index for $whence @return array
[ "Append", "some", "data", "to", "a", "given", "array" ]
45f5529ea879ffc166cc4e4ffa478a212c183628
https://github.com/thephpleague/url/blob/45f5529ea879ffc166cc4e4ffa478a212c183628/src/Components/AbstractSegment.php#L225-L239
train
thephpleague/url
src/Components/AbstractSegment.php
AbstractSegment.fetchRemainingSegment
protected function fetchRemainingSegment(array $data, $value) { $segment = implode($this->delimiter, $data); if ('' == $value) { if ($index = array_search('', $data, true)) { $left = array_slice($data, 0, $index); $right = array_slice($data, $index+1); return implode($this->delimiter, array_merge($left, $right)); } return $segment; } $part = implode($this->delimiter, $this->formatRemoveSegment($value)); $regexStart = '@(:?^|\\'.$this->delimiter.')'; if (! preg_match($regexStart.preg_quote($part, '@').'@', $segment, $matches, PREG_OFFSET_CAPTURE)) { return null; } $pos = $matches[0][1]; return substr($segment, 0, $pos).substr($segment, $pos + strlen($part) + 1); }
php
protected function fetchRemainingSegment(array $data, $value) { $segment = implode($this->delimiter, $data); if ('' == $value) { if ($index = array_search('', $data, true)) { $left = array_slice($data, 0, $index); $right = array_slice($data, $index+1); return implode($this->delimiter, array_merge($left, $right)); } return $segment; } $part = implode($this->delimiter, $this->formatRemoveSegment($value)); $regexStart = '@(:?^|\\'.$this->delimiter.')'; if (! preg_match($regexStart.preg_quote($part, '@').'@', $segment, $matches, PREG_OFFSET_CAPTURE)) { return null; } $pos = $matches[0][1]; return substr($segment, 0, $pos).substr($segment, $pos + strlen($part) + 1); }
[ "protected", "function", "fetchRemainingSegment", "(", "array", "$", "data", ",", "$", "value", ")", "{", "$", "segment", "=", "implode", "(", "$", "this", "->", "delimiter", ",", "$", "data", ")", ";", "if", "(", "''", "==", "$", "value", ")", "{", ...
Remove some data from a given array @param array $data the original array @param mixed $value the data to be removed (can be an array or a single segment) @return string|null @throws \RuntimeException If $value is invalid
[ "Remove", "some", "data", "from", "a", "given", "array" ]
45f5529ea879ffc166cc4e4ffa478a212c183628
https://github.com/thephpleague/url/blob/45f5529ea879ffc166cc4e4ffa478a212c183628/src/Components/AbstractSegment.php#L276-L301
train
pear/Log
Log/composite.php
Log_composite.open
function open() { /* Attempt to open each of our children. */ $this->_opened = true; foreach ($this->_children as $child) { $this->_opened &= $child->open(); } /* If all children were opened, return success. */ return $this->_opened; }
php
function open() { /* Attempt to open each of our children. */ $this->_opened = true; foreach ($this->_children as $child) { $this->_opened &= $child->open(); } /* If all children were opened, return success. */ return $this->_opened; }
[ "function", "open", "(", ")", "{", "/* Attempt to open each of our children. */", "$", "this", "->", "_opened", "=", "true", ";", "foreach", "(", "$", "this", "->", "_children", "as", "$", "child", ")", "{", "$", "this", "->", "_opened", "&=", "$", "child"...
Opens all of the child instances. @return True if all of the child instances were successfully opened. @access public
[ "Opens", "all", "of", "the", "child", "instances", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/composite.php#L58-L68
train
pear/Log
Log/composite.php
Log_composite.close
function close() { /* If we haven't been opened, there's nothing more to do. */ if (!$this->_opened) { return true; } /* Attempt to close each of our children. */ $closed = true; foreach ($this->_children as $child) { if ($child->_opened) { $closed &= $child->close(); } } /* Clear the opened state for consistency. */ $this->_opened = false; /* If all children were closed, return success. */ return $closed; }
php
function close() { /* If we haven't been opened, there's nothing more to do. */ if (!$this->_opened) { return true; } /* Attempt to close each of our children. */ $closed = true; foreach ($this->_children as $child) { if ($child->_opened) { $closed &= $child->close(); } } /* Clear the opened state for consistency. */ $this->_opened = false; /* If all children were closed, return success. */ return $closed; }
[ "function", "close", "(", ")", "{", "/* If we haven't been opened, there's nothing more to do. */", "if", "(", "!", "$", "this", "->", "_opened", ")", "{", "return", "true", ";", "}", "/* Attempt to close each of our children. */", "$", "closed", "=", "true", ";", "...
Closes all open child instances. @return True if all of the opened child instances were successfully closed. @access public
[ "Closes", "all", "open", "child", "instances", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/composite.php#L78-L98
train
pear/Log
Log/composite.php
Log_composite.flush
function flush() { /* Attempt to flush each of our children. */ $flushed = true; foreach ($this->_children as $child) { $flushed &= $child->flush(); } /* If all children were flushed, return success. */ return $flushed; }
php
function flush() { /* Attempt to flush each of our children. */ $flushed = true; foreach ($this->_children as $child) { $flushed &= $child->flush(); } /* If all children were flushed, return success. */ return $flushed; }
[ "function", "flush", "(", ")", "{", "/* Attempt to flush each of our children. */", "$", "flushed", "=", "true", ";", "foreach", "(", "$", "this", "->", "_children", "as", "$", "child", ")", "{", "$", "flushed", "&=", "$", "child", "->", "flush", "(", ")",...
Flushes all child instances. It is assumed that all of the children have been successfully opened. @return True if all of the child instances were successfully flushed. @access public @since Log 1.8.2
[ "Flushes", "all", "child", "instances", ".", "It", "is", "assumed", "that", "all", "of", "the", "children", "have", "been", "successfully", "opened", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/composite.php#L109-L119
train
pear/Log
Log/composite.php
Log_composite.setIdent
function setIdent($ident) { /* Call our base class's setIdent() method. */ parent::setIdent($ident); /* ... and then call setIdent() on all of our children. */ foreach ($this->_children as $child) { $child->setIdent($ident); } }
php
function setIdent($ident) { /* Call our base class's setIdent() method. */ parent::setIdent($ident); /* ... and then call setIdent() on all of our children. */ foreach ($this->_children as $child) { $child->setIdent($ident); } }
[ "function", "setIdent", "(", "$", "ident", ")", "{", "/* Call our base class's setIdent() method. */", "parent", "::", "setIdent", "(", "$", "ident", ")", ";", "/* ... and then call setIdent() on all of our children. */", "foreach", "(", "$", "this", "->", "_children", ...
Sets this identification string for all of this composite's children. @param string $ident The new identification string. @access public @since Log 1.6.7
[ "Sets", "this", "identification", "string", "for", "all", "of", "this", "composite", "s", "children", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/composite.php#L222-L231
train
pear/Log
Log/composite.php
Log_composite.addChild
function addChild(&$child) { /* Make sure this is a Log instance. */ if (!is_a($child, 'Log')) { return false; } $this->_children[$child->_id] = $child; return true; }
php
function addChild(&$child) { /* Make sure this is a Log instance. */ if (!is_a($child, 'Log')) { return false; } $this->_children[$child->_id] = $child; return true; }
[ "function", "addChild", "(", "&", "$", "child", ")", "{", "/* Make sure this is a Log instance. */", "if", "(", "!", "is_a", "(", "$", "child", ",", "'Log'", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "_children", "[", "$", "child", ...
Adds a Log instance to the list of children. @param object $child The Log instance to add. @return boolean True if the Log instance was successfully added. @access public
[ "Adds", "a", "Log", "instance", "to", "the", "list", "of", "children", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/composite.php#L242-L252
train
pear/Log
Log/composite.php
Log_composite.removeChild
function removeChild($child) { if (!is_a($child, 'Log') || !isset($this->_children[$child->_id])) { return false; } unset($this->_children[$child->_id]); return true; }
php
function removeChild($child) { if (!is_a($child, 'Log') || !isset($this->_children[$child->_id])) { return false; } unset($this->_children[$child->_id]); return true; }
[ "function", "removeChild", "(", "$", "child", ")", "{", "if", "(", "!", "is_a", "(", "$", "child", ",", "'Log'", ")", "||", "!", "isset", "(", "$", "this", "->", "_children", "[", "$", "child", "->", "_id", "]", ")", ")", "{", "return", "false", ...
Removes a Log instance from the list of children. @param object $child The Log instance to remove. @return boolean True if the Log instance was successfully removed. @access public
[ "Removes", "a", "Log", "instance", "from", "the", "list", "of", "children", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/composite.php#L263-L272
train
pear/Log
Log/observer.php
Log_observer.&
function &factory($type, $priority = PEAR_LOG_INFO, $conf = array()) { $type = strtolower($type); $class = 'Log_observer_' . $type; /* * If the desired class already exists (because the caller has supplied * it from some custom location), simply instantiate and return a new * instance. */ if (class_exists($class)) { $object = new $class($priority, $conf); return $object; } /* Support both the new-style and old-style file naming conventions. */ $newstyle = true; $classfile = dirname(__FILE__) . '/observer_' . $type . '.php'; if (!file_exists($classfile)) { $classfile = 'Log/' . $type . '.php'; $newstyle = false; } /* * Attempt to include our version of the named class, but don't treat * a failure as fatal. The caller may have already included their own * version of the named class. */ @include_once $classfile; /* If the class exists, return a new instance of it. */ if (class_exists($class)) { /* Support both new-style and old-style construction. */ if ($newstyle) { $object = new $class($priority, $conf); } else { $object = new $class($priority); } return $object; } $null = null; return $null; }
php
function &factory($type, $priority = PEAR_LOG_INFO, $conf = array()) { $type = strtolower($type); $class = 'Log_observer_' . $type; /* * If the desired class already exists (because the caller has supplied * it from some custom location), simply instantiate and return a new * instance. */ if (class_exists($class)) { $object = new $class($priority, $conf); return $object; } /* Support both the new-style and old-style file naming conventions. */ $newstyle = true; $classfile = dirname(__FILE__) . '/observer_' . $type . '.php'; if (!file_exists($classfile)) { $classfile = 'Log/' . $type . '.php'; $newstyle = false; } /* * Attempt to include our version of the named class, but don't treat * a failure as fatal. The caller may have already included their own * version of the named class. */ @include_once $classfile; /* If the class exists, return a new instance of it. */ if (class_exists($class)) { /* Support both new-style and old-style construction. */ if ($newstyle) { $object = new $class($priority, $conf); } else { $object = new $class($priority); } return $object; } $null = null; return $null; }
[ "function", "&", "factory", "(", "$", "type", ",", "$", "priority", "=", "PEAR_LOG_INFO", ",", "$", "conf", "=", "array", "(", ")", ")", "{", "$", "type", "=", "strtolower", "(", "$", "type", ")", ";", "$", "class", "=", "'Log_observer_'", ".", "$"...
Attempts to return a new concrete Log_observer instance of the requested type. @param string $type The type of concreate Log_observer subclass to return. @param integer $priority The highest priority at which to receive log event notifications. @param array $conf Optional associative array of additional configuration values. @return object The newly created concrete Log_observer instance, or null on an error.
[ "Attempts", "to", "return", "a", "new", "concrete", "Log_observer", "instance", "of", "the", "requested", "type", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/observer.php#L70-L114
train
pear/Log
Log/win.php
Log_win.close
function close() { /* * If there are still lines waiting to be written, open the output * window so that we can drain the buffer. */ if (!$this->_opened && (count($this->_buffer) > 0)) { $this->open(); } if ($this->_opened) { $this->_writeln('</table>'); $this->_writeln('</body></html>'); $this->_drainBuffer(); $this->_opened = false; } return ($this->_opened === false); }
php
function close() { /* * If there are still lines waiting to be written, open the output * window so that we can drain the buffer. */ if (!$this->_opened && (count($this->_buffer) > 0)) { $this->open(); } if ($this->_opened) { $this->_writeln('</table>'); $this->_writeln('</body></html>'); $this->_drainBuffer(); $this->_opened = false; } return ($this->_opened === false); }
[ "function", "close", "(", ")", "{", "/*\n * If there are still lines waiting to be written, open the output\n * window so that we can drain the buffer.\n */", "if", "(", "!", "$", "this", "->", "_opened", "&&", "(", "count", "(", "$", "this", "->", "_b...
Closes the output stream if it is open. If there are still pending lines in the output buffer, the output window will be opened so that the buffer can be drained. @access public
[ "Closes", "the", "output", "stream", "if", "it", "is", "open", ".", "If", "there", "are", "still", "pending", "lines", "in", "the", "output", "buffer", "the", "output", "window", "will", "be", "opened", "so", "that", "the", "buffer", "can", "be", "draine...
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/win.php#L173-L191
train
pear/Log
Log/win.php
Log_win._drainBuffer
function _drainBuffer() { $win = $this->_name; foreach ($this->_buffer as $line) { echo "<script language='JavaScript'>\n"; echo "$win.document.writeln('" . addslashes($line) . "');\n"; echo "self.focus();\n"; echo "</script>\n"; } /* Now that the buffer has been drained, clear it. */ $this->_buffer = array(); }
php
function _drainBuffer() { $win = $this->_name; foreach ($this->_buffer as $line) { echo "<script language='JavaScript'>\n"; echo "$win.document.writeln('" . addslashes($line) . "');\n"; echo "self.focus();\n"; echo "</script>\n"; } /* Now that the buffer has been drained, clear it. */ $this->_buffer = array(); }
[ "function", "_drainBuffer", "(", ")", "{", "$", "win", "=", "$", "this", "->", "_name", ";", "foreach", "(", "$", "this", "->", "_buffer", "as", "$", "line", ")", "{", "echo", "\"<script language='JavaScript'>\\n\"", ";", "echo", "\"$win.document.writeln('\"",...
Writes the contents of the output buffer to the output window. @access private
[ "Writes", "the", "contents", "of", "the", "output", "buffer", "to", "the", "output", "window", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/win.php#L198-L210
train
pear/Log
Log/win.php
Log_win._writeln
function _writeln($line) { /* Add this line to our output buffer. */ $this->_buffer[] = $line; /* Buffer the output until this page's headers have been sent. */ if (!headers_sent()) { return; } /* If we haven't already opened the output window, do so now. */ if (!$this->_opened && !$this->open()) { return; } /* Drain the buffer to the output window. */ $this->_drainBuffer(); }
php
function _writeln($line) { /* Add this line to our output buffer. */ $this->_buffer[] = $line; /* Buffer the output until this page's headers have been sent. */ if (!headers_sent()) { return; } /* If we haven't already opened the output window, do so now. */ if (!$this->_opened && !$this->open()) { return; } /* Drain the buffer to the output window. */ $this->_drainBuffer(); }
[ "function", "_writeln", "(", "$", "line", ")", "{", "/* Add this line to our output buffer. */", "$", "this", "->", "_buffer", "[", "]", "=", "$", "line", ";", "/* Buffer the output until this page's headers have been sent. */", "if", "(", "!", "headers_sent", "(", ")...
Writes a single line of text to the output buffer. @param string $line The line of text to write. @access private
[ "Writes", "a", "single", "line", "of", "text", "to", "the", "output", "buffer", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/win.php#L219-L236
train
pear/Log
Log.php
Log._extractMessage
function _extractMessage($message) { /* * If we've been given an object, attempt to extract the message using * a known method. If we can't find such a method, default to the * "human-readable" version of the object. * * We also use the human-readable format for arrays. */ if (is_object($message)) { if (method_exists($message, 'getmessage')) { $message = $message->getMessage(); } else if (method_exists($message, 'tostring')) { $message = $message->toString(); } else if (method_exists($message, '__tostring')) { $message = (string)$message; } else { $message = var_export($message, true); } } else if (is_array($message)) { if (isset($message['message'])) { if (is_scalar($message['message'])) { $message = $message['message']; } else { $message = var_export($message['message'], true); } } else { $message = var_export($message, true); } } else if (is_bool($message) || $message === NULL) { $message = var_export($message, true); } /* Otherwise, we assume the message is a string. */ return $message; }
php
function _extractMessage($message) { /* * If we've been given an object, attempt to extract the message using * a known method. If we can't find such a method, default to the * "human-readable" version of the object. * * We also use the human-readable format for arrays. */ if (is_object($message)) { if (method_exists($message, 'getmessage')) { $message = $message->getMessage(); } else if (method_exists($message, 'tostring')) { $message = $message->toString(); } else if (method_exists($message, '__tostring')) { $message = (string)$message; } else { $message = var_export($message, true); } } else if (is_array($message)) { if (isset($message['message'])) { if (is_scalar($message['message'])) { $message = $message['message']; } else { $message = var_export($message['message'], true); } } else { $message = var_export($message, true); } } else if (is_bool($message) || $message === NULL) { $message = var_export($message, true); } /* Otherwise, we assume the message is a string. */ return $message; }
[ "function", "_extractMessage", "(", "$", "message", ")", "{", "/*\n * If we've been given an object, attempt to extract the message using\n * a known method. If we can't find such a method, default to the\n * \"human-readable\" version of the object.\n *\n * We...
Returns the string representation of the message data. If $message is an object, _extractMessage() will attempt to extract the message text using a known method (such as a PEAR_Error object's getMessage() method). If a known method, cannot be found, the serialized representation of the object will be returned. If the message data is already a string, it will be returned unchanged. @param mixed $message The original message data. This may be a string or any object. @return string The string representation of the message. @access protected
[ "Returns", "the", "string", "representation", "of", "the", "message", "data", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log.php#L409-L444
train
pear/Log
Log.php
Log._format
function _format($format, $timestamp, $priority, $message) { /* * If the format string references any of the backtrace-driven * variables (%5 %6,%7,%8), generate the backtrace and fetch them. */ if (preg_match('/%[5678]/', $format)) { /* Plus 2 to account for our internal function calls. */ $d = $this->_backtrace_depth + 2; list($file, $line, $func, $class) = $this->_getBacktraceVars($d); } /* * Build the formatted string. We use the sprintf() function's * "argument swapping" capability to dynamically select and position * the variables which will ultimately appear in the log string. */ return sprintf($format, $timestamp, $this->_ident, $this->priorityToString($priority), $message, isset($file) ? $file : '', isset($line) ? $line : '', isset($func) ? $func : '', isset($class) ? $class : ''); }
php
function _format($format, $timestamp, $priority, $message) { /* * If the format string references any of the backtrace-driven * variables (%5 %6,%7,%8), generate the backtrace and fetch them. */ if (preg_match('/%[5678]/', $format)) { /* Plus 2 to account for our internal function calls. */ $d = $this->_backtrace_depth + 2; list($file, $line, $func, $class) = $this->_getBacktraceVars($d); } /* * Build the formatted string. We use the sprintf() function's * "argument swapping" capability to dynamically select and position * the variables which will ultimately appear in the log string. */ return sprintf($format, $timestamp, $this->_ident, $this->priorityToString($priority), $message, isset($file) ? $file : '', isset($line) ? $line : '', isset($func) ? $func : '', isset($class) ? $class : ''); }
[ "function", "_format", "(", "$", "format", ",", "$", "timestamp", ",", "$", "priority", ",", "$", "message", ")", "{", "/*\n * If the format string references any of the backtrace-driven\n * variables (%5 %6,%7,%8), generate the backtrace and fetch them.\n */"...
Produces a formatted log line based on a format string and a set of variables representing the current log record and state. @return string Formatted log string. @access protected @since Log 1.9.4
[ "Produces", "a", "formatted", "log", "line", "based", "on", "a", "format", "string", "and", "a", "set", "of", "variables", "representing", "the", "current", "log", "record", "and", "state", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log.php#L542-L568
train
pear/Log
Log.php
Log.attach
function attach(&$observer) { if (!is_a($observer, 'Log_observer')) { return false; } $this->_listeners[$observer->_id] = &$observer; return true; }
php
function attach(&$observer) { if (!is_a($observer, 'Log_observer')) { return false; } $this->_listeners[$observer->_id] = &$observer; return true; }
[ "function", "attach", "(", "&", "$", "observer", ")", "{", "if", "(", "!", "is_a", "(", "$", "observer", ",", "'Log_observer'", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "_listeners", "[", "$", "observer", "->", "_id", "]", "="...
Adds a Log_observer instance to the list of observers that are listening for messages emitted by this Log instance. @param object $observer The Log_observer instance to attach as a listener. @return boolean True if the observer is successfully attached. @access public @since Log 1.0
[ "Adds", "a", "Log_observer", "instance", "to", "the", "list", "of", "observers", "that", "are", "listening", "for", "messages", "emitted", "by", "this", "Log", "instance", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log.php#L783-L792
train
pear/Log
Log.php
Log.detach
function detach($observer) { if (!is_a($observer, 'Log_observer') || !isset($this->_listeners[$observer->_id])) { return false; } unset($this->_listeners[$observer->_id]); return true; }
php
function detach($observer) { if (!is_a($observer, 'Log_observer') || !isset($this->_listeners[$observer->_id])) { return false; } unset($this->_listeners[$observer->_id]); return true; }
[ "function", "detach", "(", "$", "observer", ")", "{", "if", "(", "!", "is_a", "(", "$", "observer", ",", "'Log_observer'", ")", "||", "!", "isset", "(", "$", "this", "->", "_listeners", "[", "$", "observer", "->", "_id", "]", ")", ")", "{", "return...
Removes a Log_observer instance from the list of observers. @param object $observer The Log_observer instance to detach from the list of listeners. @return boolean True if the observer is successfully detached. @access public @since Log 1.0
[ "Removes", "a", "Log_observer", "instance", "from", "the", "list", "of", "observers", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log.php#L805-L815
train
pear/Log
Log.php
Log._announce
function _announce($event) { foreach ($this->_listeners as $id => $listener) { if ($event['priority'] <= $this->_listeners[$id]->_priority) { $this->_listeners[$id]->notify($event); } } }
php
function _announce($event) { foreach ($this->_listeners as $id => $listener) { if ($event['priority'] <= $this->_listeners[$id]->_priority) { $this->_listeners[$id]->notify($event); } } }
[ "function", "_announce", "(", "$", "event", ")", "{", "foreach", "(", "$", "this", "->", "_listeners", "as", "$", "id", "=>", "$", "listener", ")", "{", "if", "(", "$", "event", "[", "'priority'", "]", "<=", "$", "this", "->", "_listeners", "[", "$...
Informs each registered observer instance that a new message has been logged. @param array $event A hash describing the log event. @access protected
[ "Informs", "each", "registered", "observer", "instance", "that", "a", "new", "message", "has", "been", "logged", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log.php#L825-L832
train
pear/Log
Log/sqlite.php
Log_sqlite._createTable
function _createTable() { $q = "SELECT name FROM sqlite_master WHERE name='" . $this->_table . "' AND type='table'"; $res = sqlite_query($this->_db, $q); if (sqlite_num_rows($res) == 0) { $q = 'CREATE TABLE [' . $this->_table . '] (' . 'id INTEGER PRIMARY KEY NOT NULL, ' . 'logtime NOT NULL, ' . 'ident CHAR(16) NOT NULL, ' . 'priority INT NOT NULL, ' . 'message)'; if (!($res = sqlite_unbuffered_query($this->_db, $q))) { return false; } } return true; }
php
function _createTable() { $q = "SELECT name FROM sqlite_master WHERE name='" . $this->_table . "' AND type='table'"; $res = sqlite_query($this->_db, $q); if (sqlite_num_rows($res) == 0) { $q = 'CREATE TABLE [' . $this->_table . '] (' . 'id INTEGER PRIMARY KEY NOT NULL, ' . 'logtime NOT NULL, ' . 'ident CHAR(16) NOT NULL, ' . 'priority INT NOT NULL, ' . 'message)'; if (!($res = sqlite_unbuffered_query($this->_db, $q))) { return false; } } return true; }
[ "function", "_createTable", "(", ")", "{", "$", "q", "=", "\"SELECT name FROM sqlite_master WHERE name='\"", ".", "$", "this", "->", "_table", ".", "\"' AND type='table'\"", ";", "$", "res", "=", "sqlite_query", "(", "$", "this", "->", "_db", ",", "$", "q", ...
Checks whether the log table exists and creates it if necessary. @return boolean True on success or false on failure. @access private
[ "Checks", "whether", "the", "log", "table", "exists", "and", "creates", "it", "if", "necessary", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/sqlite.php#L201-L222
train
pear/Log
Log/null.php
Log_null.log
function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; }
php
function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; }
[ "function", "log", "(", "$", "message", ",", "$", "priority", "=", "null", ")", "{", "/* If a priority hasn't been specified, use the default value. */", "if", "(", "$", "priority", "===", "null", ")", "{", "$", "priority", "=", "$", "this", "->", "_priority", ...
Simply consumes the log event. The message will still be passed along to any Log_observer instances that are observing this Log. @param mixed $message String or object containing the message to log. @param string $priority The priority of the message. Valid values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. @return boolean True on success or false on failure. @access public
[ "Simply", "consumes", "the", "log", "event", ".", "The", "message", "will", "still", "be", "passed", "along", "to", "any", "Log_observer", "instances", "that", "are", "observing", "this", "Log", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/null.php#L74-L89
train
pear/Log
Log/console.php
Log_console.close
function close() { $this->flush(); $this->_opened = false; if ($this->_closeResource === true && is_resource($this->_stream)) { fclose($this->_stream); } return true; }
php
function close() { $this->flush(); $this->_opened = false; if ($this->_closeResource === true && is_resource($this->_stream)) { fclose($this->_stream); } return true; }
[ "function", "close", "(", ")", "{", "$", "this", "->", "flush", "(", ")", ";", "$", "this", "->", "_opened", "=", "false", ";", "if", "(", "$", "this", "->", "_closeResource", "===", "true", "&&", "is_resource", "(", "$", "this", "->", "_stream", "...
Closes the output stream. This results in a call to flush(). @access public @since Log 1.9.0
[ "Closes", "the", "output", "stream", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/console.php#L141-L149
train
pear/Log
Log/mcal.php
Log_mcal.close
function close() { if ($this->_opened) { mcal_close($this->_stream); $this->_opened = false; } return ($this->_opened === false); }
php
function close() { if ($this->_opened) { mcal_close($this->_stream); $this->_opened = false; } return ($this->_opened === false); }
[ "function", "close", "(", ")", "{", "if", "(", "$", "this", "->", "_opened", ")", "{", "mcal_close", "(", "$", "this", "->", "_stream", ")", ";", "$", "this", "->", "_opened", "=", "false", ";", "}", "return", "(", "$", "this", "->", "_opened", "...
Closes the calendar stream, if it is open. @access public
[ "Closes", "the", "calendar", "stream", "if", "it", "is", "open", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/mcal.php#L106-L114
train
pear/Log
Log/mdb2.php
Log_mdb2._createTable
function _createTable() { $this->_db->loadModule('Manager', null, true); $result = $this->_db->manager->createTable( $this->_table, array( 'id' => array('type' => $this->_types['id']), 'logtime' => array('type' => $this->_types['logtime']), 'ident' => array('type' => $this->_types['ident']), 'priority' => array('type' => $this->_types['priority']), 'message' => array('type' => $this->_types['message']) ) ); if (PEAR::isError($result)) { return false; } $result = $this->_db->manager->createIndex( $this->_table, 'unique_id', array('fields' => array('id' => true), 'unique' => true) ); if (PEAR::isError($result)) { return false; } return true; }
php
function _createTable() { $this->_db->loadModule('Manager', null, true); $result = $this->_db->manager->createTable( $this->_table, array( 'id' => array('type' => $this->_types['id']), 'logtime' => array('type' => $this->_types['logtime']), 'ident' => array('type' => $this->_types['ident']), 'priority' => array('type' => $this->_types['priority']), 'message' => array('type' => $this->_types['message']) ) ); if (PEAR::isError($result)) { return false; } $result = $this->_db->manager->createIndex( $this->_table, 'unique_id', array('fields' => array('id' => true), 'unique' => true) ); if (PEAR::isError($result)) { return false; } return true; }
[ "function", "_createTable", "(", ")", "{", "$", "this", "->", "_db", "->", "loadModule", "(", "'Manager'", ",", "null", ",", "true", ")", ";", "$", "result", "=", "$", "this", "->", "_db", "->", "manager", "->", "createTable", "(", "$", "this", "->",...
Create the log table in the database. @return boolean True on success or false on failure. @access private
[ "Create", "the", "log", "table", "in", "the", "database", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/mdb2.php#L310-L337
train
pear/Log
Log/file.php
Log_file._mkpath
function _mkpath($path, $mode = 0700) { /* Separate the last pathname component from the rest of the path. */ $head = dirname($path); $tail = basename($path); /* Make sure we've split the path into two complete components. */ if (empty($tail)) { $head = dirname($path); $tail = basename($path); } /* Recurse up the path if our current segment does not exist. */ if (!empty($head) && !empty($tail) && !is_dir($head)) { $this->_mkpath($head, $mode); } /* Create this segment of the path. */ return @mkdir($head, $mode); }
php
function _mkpath($path, $mode = 0700) { /* Separate the last pathname component from the rest of the path. */ $head = dirname($path); $tail = basename($path); /* Make sure we've split the path into two complete components. */ if (empty($tail)) { $head = dirname($path); $tail = basename($path); } /* Recurse up the path if our current segment does not exist. */ if (!empty($head) && !empty($tail) && !is_dir($head)) { $this->_mkpath($head, $mode); } /* Create this segment of the path. */ return @mkdir($head, $mode); }
[ "function", "_mkpath", "(", "$", "path", ",", "$", "mode", "=", "0700", ")", "{", "/* Separate the last pathname component from the rest of the path. */", "$", "head", "=", "dirname", "(", "$", "path", ")", ";", "$", "tail", "=", "basename", "(", "$", "path", ...
Creates the given directory path. If the parent directories don't already exist, they will be created, too. This implementation is inspired by Python's os.makedirs function. @param string $path The full directory path to create. @param integer $mode The permissions mode with which the directories will be created. @return True if the full path is successfully created or already exists. @access private
[ "Creates", "the", "given", "directory", "path", ".", "If", "the", "parent", "directories", "don", "t", "already", "exist", "they", "will", "be", "created", "too", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/file.php#L174-L193
train
pear/Log
Log/file.php
Log_file.open
function open() { if (!$this->_opened) { /* If the log file's directory doesn't exist, create it. */ if (!is_dir(dirname($this->_filename))) { $this->_mkpath($this->_filename, $this->_dirmode); } /* Determine whether the log file needs to be created. */ $creating = !file_exists($this->_filename); /* Obtain a handle to the log file. */ $this->_fp = fopen($this->_filename, ($this->_append) ? 'a' : 'w'); /* We consider the file "opened" if we have a valid file pointer. */ $this->_opened = ($this->_fp !== false); /* Attempt to set the file's permissions if we just created it. */ if ($creating && $this->_opened) { chmod($this->_filename, $this->_mode); } } return $this->_opened; }
php
function open() { if (!$this->_opened) { /* If the log file's directory doesn't exist, create it. */ if (!is_dir(dirname($this->_filename))) { $this->_mkpath($this->_filename, $this->_dirmode); } /* Determine whether the log file needs to be created. */ $creating = !file_exists($this->_filename); /* Obtain a handle to the log file. */ $this->_fp = fopen($this->_filename, ($this->_append) ? 'a' : 'w'); /* We consider the file "opened" if we have a valid file pointer. */ $this->_opened = ($this->_fp !== false); /* Attempt to set the file's permissions if we just created it. */ if ($creating && $this->_opened) { chmod($this->_filename, $this->_mode); } } return $this->_opened; }
[ "function", "open", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_opened", ")", "{", "/* If the log file's directory doesn't exist, create it. */", "if", "(", "!", "is_dir", "(", "dirname", "(", "$", "this", "->", "_filename", ")", ")", ")", "{", "$"...
Opens the log file for output. If the specified log file does not already exist, it will be created. By default, new log entries are appended to the end of the log file. This is implicitly called by log(), if necessary. @access public
[ "Opens", "the", "log", "file", "for", "output", ".", "If", "the", "specified", "log", "file", "does", "not", "already", "exist", "it", "will", "be", "created", ".", "By", "default", "new", "log", "entries", "are", "appended", "to", "the", "end", "of", ...
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/file.php#L204-L228
train
pear/Log
Log/file.php
Log_file.close
function close() { /* If the log file is open, close it. */ if ($this->_opened && fclose($this->_fp)) { $this->_opened = false; } return ($this->_opened === false); }
php
function close() { /* If the log file is open, close it. */ if ($this->_opened && fclose($this->_fp)) { $this->_opened = false; } return ($this->_opened === false); }
[ "function", "close", "(", ")", "{", "/* If the log file is open, close it. */", "if", "(", "$", "this", "->", "_opened", "&&", "fclose", "(", "$", "this", "->", "_fp", ")", ")", "{", "$", "this", "->", "_opened", "=", "false", ";", "}", "return", "(", ...
Closes the log file if it is open. @access public
[ "Closes", "the", "log", "file", "if", "it", "is", "open", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/file.php#L235-L243
train
pear/Log
Log/mail.php
Log_mail.close
function close() { if ($this->_opened) { if ($this->_shouldSend && !empty($this->_message)) { if ($this->_mailBackend === '') { // use mail() $headers = "From: $this->_from\r\n"; $headers .= 'User-Agent: PEAR Log Package'; if (mail($this->_recipients, $this->_subject, $this->_message, $headers) == false) { return false; } } else { // use PEAR::Mail include_once 'Mail.php'; $headers = array('From' => $this->_from, 'To' => $this->_recipients, 'User-Agent' => 'PEAR Log Package', 'Subject' => $this->_subject); $mailer = &Mail::factory($this->_mailBackend, $this->_mailParams); $res = $mailer->send($this->_recipients, $headers, $this->_message); if (PEAR::isError($res)) { return false; } } /* Clear the message string now that the email has been sent. */ $this->_message = ''; $this->_shouldSend = false; } $this->_opened = false; } return ($this->_opened === false); }
php
function close() { if ($this->_opened) { if ($this->_shouldSend && !empty($this->_message)) { if ($this->_mailBackend === '') { // use mail() $headers = "From: $this->_from\r\n"; $headers .= 'User-Agent: PEAR Log Package'; if (mail($this->_recipients, $this->_subject, $this->_message, $headers) == false) { return false; } } else { // use PEAR::Mail include_once 'Mail.php'; $headers = array('From' => $this->_from, 'To' => $this->_recipients, 'User-Agent' => 'PEAR Log Package', 'Subject' => $this->_subject); $mailer = &Mail::factory($this->_mailBackend, $this->_mailParams); $res = $mailer->send($this->_recipients, $headers, $this->_message); if (PEAR::isError($res)) { return false; } } /* Clear the message string now that the email has been sent. */ $this->_message = ''; $this->_shouldSend = false; } $this->_opened = false; } return ($this->_opened === false); }
[ "function", "close", "(", ")", "{", "if", "(", "$", "this", "->", "_opened", ")", "{", "if", "(", "$", "this", "->", "_shouldSend", "&&", "!", "empty", "(", "$", "this", "->", "_message", ")", ")", "{", "if", "(", "$", "this", "->", "_mailBackend...
Closes the message, if it is open, and sends the mail. This is implicitly called by the destructor, if necessary. @access public
[ "Closes", "the", "message", "if", "it", "is", "open", "and", "sends", "the", "mail", ".", "This", "is", "implicitly", "called", "by", "the", "destructor", "if", "necessary", "." ]
bde9c8e735c4941839eafaa86e69edb590be1d60
https://github.com/pear/Log/blob/bde9c8e735c4941839eafaa86e69edb590be1d60/Log/mail.php#L198-L232
train
GinoPane/PHPolyglot
src/API/Supplemental/Yandex/YandexApiTrait.php
YandexApiTrait.filterYandexSpecificErrors
public function filterYandexSpecificErrors(array $responseArray): void { if (isset($responseArray['code'])) { if (($responseArray['code'] !== YandexApiStatusesInterface::STATUS_SUCCESS) && isset(self::$customStatusMessages[$responseArray['code']]) ) { $errorMessage = $responseArray['message'] ?? self::$customStatusMessages[$responseArray['code']]; throw new BadResponseContextException($errorMessage, $responseArray['code']); } } }
php
public function filterYandexSpecificErrors(array $responseArray): void { if (isset($responseArray['code'])) { if (($responseArray['code'] !== YandexApiStatusesInterface::STATUS_SUCCESS) && isset(self::$customStatusMessages[$responseArray['code']]) ) { $errorMessage = $responseArray['message'] ?? self::$customStatusMessages[$responseArray['code']]; throw new BadResponseContextException($errorMessage, $responseArray['code']); } } }
[ "public", "function", "filterYandexSpecificErrors", "(", "array", "$", "responseArray", ")", ":", "void", "{", "if", "(", "isset", "(", "$", "responseArray", "[", "'code'", "]", ")", ")", "{", "if", "(", "(", "$", "responseArray", "[", "'code'", "]", "!=...
Checks for Yandex-specific errors and throws exception if error detected @param array $responseArray @throws BadResponseContextException
[ "Checks", "for", "Yandex", "-", "specific", "errors", "and", "throws", "exception", "if", "error", "detected" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Supplemental/Yandex/YandexApiTrait.php#L52-L64
train
GinoPane/PHPolyglot
src/API/Implementation/SpellCheck/SpellCheckApiAbstract.php
SpellCheckApiAbstract.checkTexts
public function checkTexts(array $texts, Language $languageFrom): SpellCheckResponse { /** @var SpellCheckResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
php
public function checkTexts(array $texts, Language $languageFrom): SpellCheckResponse { /** @var SpellCheckResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
[ "public", "function", "checkTexts", "(", "array", "$", "texts", ",", "Language", "$", "languageFrom", ")", ":", "SpellCheckResponse", "{", "/** @var SpellCheckResponse $response */", "$", "response", "=", "$", "this", "->", "callApi", "(", "__FUNCTION__", ",", "fu...
Check spelling for multiple text strings @param array $texts @param Language $languageFrom @throws TransportException @throws ResponseContextException @throws BadResponseContextException @throws MethodDoesNotExistException @return SpellCheckResponse
[ "Check", "spelling", "for", "multiple", "text", "strings" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/SpellCheck/SpellCheckApiAbstract.php#L35-L41
train
GinoPane/PHPolyglot
src/API/Implementation/TTS/IbmWatson/AudioFormat/IbmWatsonAudioFormatsTrait.php
IbmWatsonAudioFormatsTrait.getAcceptParameter
public function getAcceptParameter(TtsAudioFormat $format, array $additionalData = []): string { $audioFormat = self::$formatMapping[$format->getFormat()] ?? ''; if (empty($audioFormat)) { throw new InvalidAudioFormatCodeException($format->getFormat()); } $accept = array_merge([$audioFormat], $this->processAdditionalParameters($format, $additionalData)); return implode(";", $accept); }
php
public function getAcceptParameter(TtsAudioFormat $format, array $additionalData = []): string { $audioFormat = self::$formatMapping[$format->getFormat()] ?? ''; if (empty($audioFormat)) { throw new InvalidAudioFormatCodeException($format->getFormat()); } $accept = array_merge([$audioFormat], $this->processAdditionalParameters($format, $additionalData)); return implode(";", $accept); }
[ "public", "function", "getAcceptParameter", "(", "TtsAudioFormat", "$", "format", ",", "array", "$", "additionalData", "=", "[", "]", ")", ":", "string", "{", "$", "audioFormat", "=", "self", "::", "$", "formatMapping", "[", "$", "format", "->", "getFormat",...
Returns the string containing the accept parameter required for TTS. It specifies audio format, sample rate and additional params if any @param TtsAudioFormat $format @param array $additionalData @throws InvalidAudioFormatCodeException @throws InvalidAudioFormatParameterException @return string
[ "Returns", "the", "string", "containing", "the", "accept", "parameter", "required", "for", "TTS", ".", "It", "specifies", "audio", "format", "sample", "rate", "and", "additional", "params", "if", "any" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/TTS/IbmWatson/AudioFormat/IbmWatsonAudioFormatsTrait.php#L49-L60
train
GinoPane/PHPolyglot
src/API/Implementation/Dictionary/DictionaryApiAbstract.php
DictionaryApiAbstract.getTextAlternatives
public function getTextAlternatives( string $text, Language $language ): DictionaryResponse { /** @var DictionaryResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
php
public function getTextAlternatives( string $text, Language $language ): DictionaryResponse { /** @var DictionaryResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
[ "public", "function", "getTextAlternatives", "(", "string", "$", "text", ",", "Language", "$", "language", ")", ":", "DictionaryResponse", "{", "/** @var DictionaryResponse $response */", "$", "response", "=", "$", "this", "->", "callApi", "(", "__FUNCTION__", ",", ...
Gets text alternatives @param string $text @param Language $language @throws TransportException @throws ResponseContextException @throws BadResponseContextException @throws MethodDoesNotExistException @return DictionaryResponse
[ "Gets", "text", "alternatives" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/Dictionary/DictionaryApiAbstract.php#L35-L43
train
GinoPane/PHPolyglot
src/API/Implementation/Dictionary/DictionaryApiAbstract.php
DictionaryApiAbstract.getTranslateAlternatives
public function getTranslateAlternatives( string $text, Language $languageTo, Language $languageFrom ): DictionaryResponse { /** @var DictionaryResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
php
public function getTranslateAlternatives( string $text, Language $languageTo, Language $languageFrom ): DictionaryResponse { /** @var DictionaryResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
[ "public", "function", "getTranslateAlternatives", "(", "string", "$", "text", ",", "Language", "$", "languageTo", ",", "Language", "$", "languageFrom", ")", ":", "DictionaryResponse", "{", "/** @var DictionaryResponse $response */", "$", "response", "=", "$", "this", ...
Gets text translate alternatives @param string $text @param Language $languageTo @param Language $languageFrom @throws TransportException @throws ResponseContextException @throws BadResponseContextException @throws MethodDoesNotExistException @return DictionaryResponse
[ "Gets", "text", "translate", "alternatives" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/Dictionary/DictionaryApiAbstract.php#L59-L68
train
GinoPane/PHPolyglot
src/API/Implementation/TTS/IbmWatson/IbmWatsonTtsApi.php
IbmWatsonTtsApi.createTextToSpeechContext
protected function createTextToSpeechContext( string $text, Language $language, TtsAudioFormat $format, array $additionalData = [] ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TEXT_TO_SPEECH_API_PATH))) ->setRequestParameters( array_filter( [ 'accept' => $this->getAcceptParameter($format, $additionalData), 'voice' => $this->getVoiceParameter($language, $additionalData) ] ) ) ->setData(json_encode(['text' => $text])) ->setMethod(RequestContext::METHOD_POST) ->setContentType(RequestContext::CONTENT_TYPE_JSON) ->setResponseContextClass(DummyResponseContext::class); return $this->authorizeRequest($requestContext); }
php
protected function createTextToSpeechContext( string $text, Language $language, TtsAudioFormat $format, array $additionalData = [] ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TEXT_TO_SPEECH_API_PATH))) ->setRequestParameters( array_filter( [ 'accept' => $this->getAcceptParameter($format, $additionalData), 'voice' => $this->getVoiceParameter($language, $additionalData) ] ) ) ->setData(json_encode(['text' => $text])) ->setMethod(RequestContext::METHOD_POST) ->setContentType(RequestContext::CONTENT_TYPE_JSON) ->setResponseContextClass(DummyResponseContext::class); return $this->authorizeRequest($requestContext); }
[ "protected", "function", "createTextToSpeechContext", "(", "string", "$", "text", ",", "Language", "$", "language", ",", "TtsAudioFormat", "$", "format", ",", "array", "$", "additionalData", "=", "[", "]", ")", ":", "RequestContext", "{", "$", "requestContext", ...
Create request context for text-to-speech request @param string $text @param Language $language @param TtsAudioFormat $format @param array $additionalData @return RequestContext @throws RequestContextException @throws InvalidVoiceCodeException @throws InvalidAudioFormatCodeException @throws InvalidVoiceParametersException @throws InvalidAudioFormatParameterException
[ "Create", "request", "context", "for", "text", "-", "to", "-", "speech", "request" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/TTS/IbmWatson/IbmWatsonTtsApi.php#L87-L108
train
GinoPane/PHPolyglot
src/API/Implementation/TTS/IbmWatson/IbmWatsonTtsApi.php
IbmWatsonTtsApi.prepareTextToSpeechResponse
protected function prepareTextToSpeechResponse(ResponseContextAbstract $context): TtsResponse { $response = new TtsResponse( $context->getRaw(), $this->getAudioFormatByContentTypeHeader($context->headers()), json_decode($context->getRequestContext()->getData(), true)['text'] ); return $response; }
php
protected function prepareTextToSpeechResponse(ResponseContextAbstract $context): TtsResponse { $response = new TtsResponse( $context->getRaw(), $this->getAudioFormatByContentTypeHeader($context->headers()), json_decode($context->getRequestContext()->getData(), true)['text'] ); return $response; }
[ "protected", "function", "prepareTextToSpeechResponse", "(", "ResponseContextAbstract", "$", "context", ")", ":", "TtsResponse", "{", "$", "response", "=", "new", "TtsResponse", "(", "$", "context", "->", "getRaw", "(", ")", ",", "$", "this", "->", "getAudioForm...
Process response of text-to-speech request and prepare valid response @param ResponseContextAbstract $context @throws InvalidContentTypeException @return TtsResponse
[ "Process", "response", "of", "text", "-", "to", "-", "speech", "request", "and", "prepare", "valid", "response" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/TTS/IbmWatson/IbmWatsonTtsApi.php#L119-L128
train
krzysztof-gzocha/searcher
src/KGzocha/Searcher/Chain/ChainSearch.php
ChainSearch.search
public function search( CriteriaCollectionInterface $criteriaCollection ): ResultCollection { $previousCriteria = $criteriaCollection; $previousResults = null; $result = new ResultCollection(); /** @var CellInterface $cell */ foreach ($this->cellCollection as $name => $cell) { if ($cell->getTransformer()->skip($previousResults)) { continue; } $previousResults = $cell->getSearcher()->search($previousCriteria); $previousCriteria = $this->getNewCriteria( $cell, $previousCriteria, $previousResults ); $result->addNamedItem((string) $name, $previousResults); } return $result; }
php
public function search( CriteriaCollectionInterface $criteriaCollection ): ResultCollection { $previousCriteria = $criteriaCollection; $previousResults = null; $result = new ResultCollection(); /** @var CellInterface $cell */ foreach ($this->cellCollection as $name => $cell) { if ($cell->getTransformer()->skip($previousResults)) { continue; } $previousResults = $cell->getSearcher()->search($previousCriteria); $previousCriteria = $this->getNewCriteria( $cell, $previousCriteria, $previousResults ); $result->addNamedItem((string) $name, $previousResults); } return $result; }
[ "public", "function", "search", "(", "CriteriaCollectionInterface", "$", "criteriaCollection", ")", ":", "ResultCollection", "{", "$", "previousCriteria", "=", "$", "criteriaCollection", ";", "$", "previousResults", "=", "null", ";", "$", "result", "=", "new", "Re...
Will perform multiple sub-searches. Results from first search will be transformed and passed as CriteriaCollection to another sub-search. Whole process will return collection of results from each sub-search. @param CriteriaCollectionInterface $criteriaCollection @return ResultCollection
[ "Will", "perform", "multiple", "sub", "-", "searches", ".", "Results", "from", "first", "search", "will", "be", "transformed", "and", "passed", "as", "CriteriaCollection", "to", "another", "sub", "-", "search", ".", "Whole", "process", "will", "return", "colle...
f44eb27fdaa7b45fa2f90221899970e2fd061829
https://github.com/krzysztof-gzocha/searcher/blob/f44eb27fdaa7b45fa2f90221899970e2fd061829/src/KGzocha/Searcher/Chain/ChainSearch.php#L44-L68
train
krzysztof-gzocha/searcher
src/KGzocha/Searcher/Criteria/Adapter/ImmutablePaginationAdapter.php
ImmutablePaginationAdapter.setItemsPerPage
public function setItemsPerPage(int $itemsPerPage = null) { return $this ->pagination ->setItemsPerPage( $this->pagination->getItemsPerPage() ); }
php
public function setItemsPerPage(int $itemsPerPage = null) { return $this ->pagination ->setItemsPerPage( $this->pagination->getItemsPerPage() ); }
[ "public", "function", "setItemsPerPage", "(", "int", "$", "itemsPerPage", "=", "null", ")", "{", "return", "$", "this", "->", "pagination", "->", "setItemsPerPage", "(", "$", "this", "->", "pagination", "->", "getItemsPerPage", "(", ")", ")", ";", "}" ]
This method will not allow to change items per page. On each call it will set the same value. {@inheritdoc}
[ "This", "method", "will", "not", "allow", "to", "change", "items", "per", "page", ".", "On", "each", "call", "it", "will", "set", "the", "same", "value", "." ]
f44eb27fdaa7b45fa2f90221899970e2fd061829
https://github.com/krzysztof-gzocha/searcher/blob/f44eb27fdaa7b45fa2f90221899970e2fd061829/src/KGzocha/Searcher/Criteria/Adapter/ImmutablePaginationAdapter.php#L59-L66
train
GinoPane/PHPolyglot
src/Supplemental/Language/Language.php
Language.assertLanguageIsValid
private function assertLanguageIsValid(string $language): void { if (!$this->codeIsValid($language)) { throw new InvalidLanguageCodeException( sprintf("Language code \"%s\" is invalid", $language) ); } }
php
private function assertLanguageIsValid(string $language): void { if (!$this->codeIsValid($language)) { throw new InvalidLanguageCodeException( sprintf("Language code \"%s\" is invalid", $language) ); } }
[ "private", "function", "assertLanguageIsValid", "(", "string", "$", "language", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "codeIsValid", "(", "$", "language", ")", ")", "{", "throw", "new", "InvalidLanguageCodeException", "(", "sprintf", "(",...
Checks that specified language code is valid @param string $language @throws InvalidLanguageCodeException
[ "Checks", "that", "specified", "language", "code", "is", "valid" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/Supplemental/Language/Language.php#L88-L95
train
GinoPane/PHPolyglot
src/Supplemental/GetConstantsTrait.php
GetConstantsTrait.getConstants
private function getConstants(): array { if (empty(self::$constants)) { self::$constants = (new ReflectionClass($this))->getConstants(); } return self::$constants; }
php
private function getConstants(): array { if (empty(self::$constants)) { self::$constants = (new ReflectionClass($this))->getConstants(); } return self::$constants; }
[ "private", "function", "getConstants", "(", ")", ":", "array", "{", "if", "(", "empty", "(", "self", "::", "$", "constants", ")", ")", "{", "self", "::", "$", "constants", "=", "(", "new", "ReflectionClass", "(", "$", "this", ")", ")", "->", "getCons...
Fills constants array if it is empty and returns it @return array
[ "Fills", "constants", "array", "if", "it", "is", "empty", "and", "returns", "it" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/Supplemental/GetConstantsTrait.php#L28-L35
train
GinoPane/PHPolyglot
src/API/Implementation/SpellCheck/Yandex/YandexSpellCheckApi.php
YandexSpellCheckApi.createCheckTextsContext
protected function createCheckTextsContext( array $texts, Language $languageFrom ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::CHECK_TEXTS_API_PATH))) ->setRequestParameters( [ 'lang' => $languageFrom->getCode() ] ) ->setData(['text' => $texts]) ->setMethod(RequestContext::METHOD_POST) ->setEncodeArraysUsingDuplication(true) ->setContentType(RequestContext::CONTENT_TYPE_FORM_URLENCODED) ->setResponseContextClass(JsonResponseContext::class); return $requestContext; }
php
protected function createCheckTextsContext( array $texts, Language $languageFrom ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::CHECK_TEXTS_API_PATH))) ->setRequestParameters( [ 'lang' => $languageFrom->getCode() ] ) ->setData(['text' => $texts]) ->setMethod(RequestContext::METHOD_POST) ->setEncodeArraysUsingDuplication(true) ->setContentType(RequestContext::CONTENT_TYPE_FORM_URLENCODED) ->setResponseContextClass(JsonResponseContext::class); return $requestContext; }
[ "protected", "function", "createCheckTextsContext", "(", "array", "$", "texts", ",", "Language", "$", "languageFrom", ")", ":", "RequestContext", "{", "$", "requestContext", "=", "(", "new", "RequestContext", "(", "sprintf", "(", "\"%s/%s\"", ",", "$", "this", ...
Create request context for spell-check request @param array $texts @param Language $languageFrom @throws RequestContextException @return RequestContext
[ "Create", "request", "context", "for", "spell", "-", "check", "request" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/SpellCheck/Yandex/YandexSpellCheckApi.php#L44-L61
train
GinoPane/PHPolyglot
src/API/Implementation/SpellCheck/Yandex/YandexSpellCheckApi.php
YandexSpellCheckApi.prepareCheckTextsResponse
protected function prepareCheckTextsResponse(ResponseContextAbstract $context): SpellCheckResponse { $response = new SpellCheckResponse(); $corrections = []; foreach ($context->getArray() as $wordCorrections) { $corrected = []; foreach ($wordCorrections as $wordCorrection) { if (!empty($wordCorrection['s']) && !empty($wordCorrection['word'])) { $corrected[$wordCorrection['word']] = (array)$wordCorrection['s']; } } $corrections[] = $corrected; } $response->setCorrections($corrections); return $response; }
php
protected function prepareCheckTextsResponse(ResponseContextAbstract $context): SpellCheckResponse { $response = new SpellCheckResponse(); $corrections = []; foreach ($context->getArray() as $wordCorrections) { $corrected = []; foreach ($wordCorrections as $wordCorrection) { if (!empty($wordCorrection['s']) && !empty($wordCorrection['word'])) { $corrected[$wordCorrection['word']] = (array)$wordCorrection['s']; } } $corrections[] = $corrected; } $response->setCorrections($corrections); return $response; }
[ "protected", "function", "prepareCheckTextsResponse", "(", "ResponseContextAbstract", "$", "context", ")", ":", "SpellCheckResponse", "{", "$", "response", "=", "new", "SpellCheckResponse", "(", ")", ";", "$", "corrections", "=", "[", "]", ";", "foreach", "(", "...
Process response of spell-check request and prepare valid response @param ResponseContextAbstract $context @return SpellCheckResponse
[ "Process", "response", "of", "spell", "-", "check", "request", "and", "prepare", "valid", "response" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/SpellCheck/Yandex/YandexSpellCheckApi.php#L70-L91
train
GinoPane/PHPolyglot
src/API/Implementation/Dictionary/Yandex/YandexDictionaryApi.php
YandexDictionaryApi.createGetTextAlternativesContext
protected function createGetTextAlternativesContext( string $text, Language $language ): RequestContext { $requestContext = $this->getLookupRequest($text, $language, $language); return $this->fillGeneralRequestSettings($requestContext); }
php
protected function createGetTextAlternativesContext( string $text, Language $language ): RequestContext { $requestContext = $this->getLookupRequest($text, $language, $language); return $this->fillGeneralRequestSettings($requestContext); }
[ "protected", "function", "createGetTextAlternativesContext", "(", "string", "$", "text", ",", "Language", "$", "language", ")", ":", "RequestContext", "{", "$", "requestContext", "=", "$", "this", "->", "getLookupRequest", "(", "$", "text", ",", "$", "language",...
Create request context for get-text-alternatives request @param string $text @param Language $language @throws RequestContextException @return RequestContext
[ "Create", "request", "context", "for", "get", "-", "text", "-", "alternatives", "request" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/Dictionary/Yandex/YandexDictionaryApi.php#L79-L86
train
GinoPane/PHPolyglot
src/API/Implementation/Dictionary/Yandex/YandexDictionaryApi.php
YandexDictionaryApi.createGetTranslateAlternativesContext
protected function createGetTranslateAlternativesContext( string $text, Language $languageTo, Language $languageFrom ): RequestContext { $requestContext = $this->getLookupRequest($text, $languageTo, $languageFrom); return $this->fillGeneralRequestSettings($requestContext); }
php
protected function createGetTranslateAlternativesContext( string $text, Language $languageTo, Language $languageFrom ): RequestContext { $requestContext = $this->getLookupRequest($text, $languageTo, $languageFrom); return $this->fillGeneralRequestSettings($requestContext); }
[ "protected", "function", "createGetTranslateAlternativesContext", "(", "string", "$", "text", ",", "Language", "$", "languageTo", ",", "Language", "$", "languageFrom", ")", ":", "RequestContext", "{", "$", "requestContext", "=", "$", "this", "->", "getLookupRequest"...
Create request context for get-translate-alternatives request @param string $text @param Language $languageTo @param Language $languageFrom @throws RequestContextException @return RequestContext
[ "Create", "request", "context", "for", "get", "-", "translate", "-", "alternatives", "request" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/Dictionary/Yandex/YandexDictionaryApi.php#L111-L119
train
GinoPane/PHPolyglot
src/API/Implementation/Translate/Yandex/YandexTranslateApi.php
YandexTranslateApi.createTranslateContext
protected function createTranslateContext( string $text, Language $languageTo, Language $languageFrom ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TRANSLATE_API_PATH))) ->setRequestParameters( [ 'lang' => $this->getLanguageString($languageTo, $languageFrom) ] + $this->getAuthData() ) ->setData(['text' => $text]) ->setMethod(RequestContext::METHOD_POST); return $this->fillGeneralRequestSettings($requestContext); }
php
protected function createTranslateContext( string $text, Language $languageTo, Language $languageFrom ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TRANSLATE_API_PATH))) ->setRequestParameters( [ 'lang' => $this->getLanguageString($languageTo, $languageFrom) ] + $this->getAuthData() ) ->setData(['text' => $text]) ->setMethod(RequestContext::METHOD_POST); return $this->fillGeneralRequestSettings($requestContext); }
[ "protected", "function", "createTranslateContext", "(", "string", "$", "text", ",", "Language", "$", "languageTo", ",", "Language", "$", "languageFrom", ")", ":", "RequestContext", "{", "$", "requestContext", "=", "(", "new", "RequestContext", "(", "sprintf", "(...
Create request context for translate request @param string $text @param Language $languageTo @param Language $languageFrom @throws RequestContextException @return RequestContext
[ "Create", "request", "context", "for", "translate", "request" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/Translate/Yandex/YandexTranslateApi.php#L68-L83
train
GinoPane/PHPolyglot
src/API/Implementation/Translate/Yandex/YandexTranslateApi.php
YandexTranslateApi.createTranslateBulkContext
protected function createTranslateBulkContext( array $texts, Language $languageTo, Language $languageFrom ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TRANSLATE_API_PATH))) ->setRequestParameters( [ 'lang' => $this->getLanguageString($languageTo, $languageFrom) ] + $this->getAuthData() ) ->setData(['text' => $texts]) ->setMethod(RequestContext::METHOD_POST) ->setEncodeArraysUsingDuplication(true); return $this->fillGeneralRequestSettings($requestContext); }
php
protected function createTranslateBulkContext( array $texts, Language $languageTo, Language $languageFrom ): RequestContext { $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TRANSLATE_API_PATH))) ->setRequestParameters( [ 'lang' => $this->getLanguageString($languageTo, $languageFrom) ] + $this->getAuthData() ) ->setData(['text' => $texts]) ->setMethod(RequestContext::METHOD_POST) ->setEncodeArraysUsingDuplication(true); return $this->fillGeneralRequestSettings($requestContext); }
[ "protected", "function", "createTranslateBulkContext", "(", "array", "$", "texts", ",", "Language", "$", "languageTo", ",", "Language", "$", "languageFrom", ")", ":", "RequestContext", "{", "$", "requestContext", "=", "(", "new", "RequestContext", "(", "sprintf", ...
Create request context for bulk translate request @param array $texts @param Language $languageTo @param Language $languageFrom @throws RequestContextException @return RequestContext
[ "Create", "request", "context", "for", "bulk", "translate", "request" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/Translate/Yandex/YandexTranslateApi.php#L108-L124
train
GinoPane/PHPolyglot
src/API/Implementation/ApiAbstract.php
ApiAbstract.callApi
protected function callApi(string $apiClassMethod, array $arguments = []): ApiResponseInterface { $requestContext = $this->getApiRequestContext($apiClassMethod, $arguments); $responseContext = $this->getApiResponseContext($requestContext); $apiResponse = $this->prepareApiResponse($responseContext, $apiClassMethod); return $apiResponse; }
php
protected function callApi(string $apiClassMethod, array $arguments = []): ApiResponseInterface { $requestContext = $this->getApiRequestContext($apiClassMethod, $arguments); $responseContext = $this->getApiResponseContext($requestContext); $apiResponse = $this->prepareApiResponse($responseContext, $apiClassMethod); return $apiResponse; }
[ "protected", "function", "callApi", "(", "string", "$", "apiClassMethod", ",", "array", "$", "arguments", "=", "[", "]", ")", ":", "ApiResponseInterface", "{", "$", "requestContext", "=", "$", "this", "->", "getApiRequestContext", "(", "$", "apiClassMethod", "...
Call API method by creating RequestContext, sending it, filtering the result and preparing the response @param string $apiClassMethod @param array $arguments Arguments that need to be passed to API-related methods @throws TransportException @throws ResponseContextException @throws BadResponseContextException @throws MethodDoesNotExistException @return ApiResponseInterface
[ "Call", "API", "method", "by", "creating", "RequestContext", "sending", "it", "filtering", "the", "result", "and", "preparing", "the", "response" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/ApiAbstract.php#L78-L87
train
GinoPane/PHPolyglot
src/API/Implementation/ApiAbstract.php
ApiAbstract.initPropertiesFromEnvironment
protected function initPropertiesFromEnvironment(): void { foreach ($this->envProperties as $property => $env) { if (!property_exists($this, $property)) { throw new InvalidPropertyException( sprintf("Property \"%s\" does not exist within the class \"%s\"", $property, get_class($this)) ); } if (false === ($envSetting = getenv($env))) { throw new InvalidEnvironmentException( sprintf("Required environment variable \"%s\" is not set", $env) ); } $this->{$property} = $envSetting; } }
php
protected function initPropertiesFromEnvironment(): void { foreach ($this->envProperties as $property => $env) { if (!property_exists($this, $property)) { throw new InvalidPropertyException( sprintf("Property \"%s\" does not exist within the class \"%s\"", $property, get_class($this)) ); } if (false === ($envSetting = getenv($env))) { throw new InvalidEnvironmentException( sprintf("Required environment variable \"%s\" is not set", $env) ); } $this->{$property} = $envSetting; } }
[ "protected", "function", "initPropertiesFromEnvironment", "(", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "envProperties", "as", "$", "property", "=>", "$", "env", ")", "{", "if", "(", "!", "property_exists", "(", "$", "this", ",", "$", "p...
Fills specified properties using environment variables @throws InvalidPropertyException @throws InvalidEnvironmentException
[ "Fills", "specified", "properties", "using", "environment", "variables" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/ApiAbstract.php#L114-L131
train
GinoPane/PHPolyglot
src/API/Implementation/ApiAbstract.php
ApiAbstract.getApiResponseContext
private function getApiResponseContext(RequestContext $requestContext): ResponseContextAbstract { $responseContext = $this->httpClient->sendRequest( $requestContext ); $this->processApiResponseContextErrors($responseContext); return $responseContext; }
php
private function getApiResponseContext(RequestContext $requestContext): ResponseContextAbstract { $responseContext = $this->httpClient->sendRequest( $requestContext ); $this->processApiResponseContextErrors($responseContext); return $responseContext; }
[ "private", "function", "getApiResponseContext", "(", "RequestContext", "$", "requestContext", ")", ":", "ResponseContextAbstract", "{", "$", "responseContext", "=", "$", "this", "->", "httpClient", "->", "sendRequest", "(", "$", "requestContext", ")", ";", "$", "t...
Accepts RequestContext and sends it to API to get ResponseContext @param RequestContext $requestContext @throws TransportException @throws ResponseContextException @throws BadResponseContextException @return ResponseContextAbstract
[ "Accepts", "RequestContext", "and", "sends", "it", "to", "API", "to", "get", "ResponseContext" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/ApiAbstract.php#L144-L153
train
GinoPane/PHPolyglot
src/API/Implementation/ApiAbstract.php
ApiAbstract.getApiRequestContext
private function getApiRequestContext(string $apiClassMethod, array $arguments = []): RequestContext { $getRequestContext = sprintf("create%sContext", ucfirst($apiClassMethod)); $this->assertMethodExists($getRequestContext); $requestContext = $this->{$getRequestContext}(...$arguments); return $requestContext; }
php
private function getApiRequestContext(string $apiClassMethod, array $arguments = []): RequestContext { $getRequestContext = sprintf("create%sContext", ucfirst($apiClassMethod)); $this->assertMethodExists($getRequestContext); $requestContext = $this->{$getRequestContext}(...$arguments); return $requestContext; }
[ "private", "function", "getApiRequestContext", "(", "string", "$", "apiClassMethod", ",", "array", "$", "arguments", "=", "[", "]", ")", ":", "RequestContext", "{", "$", "getRequestContext", "=", "sprintf", "(", "\"create%sContext\"", ",", "ucfirst", "(", "$", ...
Gets RequestContext for sending @param string $apiClassMethod @param array $arguments Arguments that need to be passed to API-related methods @return RequestContext @throws MethodDoesNotExistException
[ "Gets", "RequestContext", "for", "sending" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/ApiAbstract.php#L165-L174
train
GinoPane/PHPolyglot
src/API/Implementation/ApiAbstract.php
ApiAbstract.prepareApiResponse
private function prepareApiResponse( ResponseContextAbstract $responseContext, string $apiClassMethod ): ApiResponseInterface { $prepareApiResponse = sprintf("prepare%sResponse", ucfirst($apiClassMethod)); $this->assertMethodExists($prepareApiResponse); $apiResponse = $this->{$prepareApiResponse}($responseContext); return $apiResponse; }
php
private function prepareApiResponse( ResponseContextAbstract $responseContext, string $apiClassMethod ): ApiResponseInterface { $prepareApiResponse = sprintf("prepare%sResponse", ucfirst($apiClassMethod)); $this->assertMethodExists($prepareApiResponse); $apiResponse = $this->{$prepareApiResponse}($responseContext); return $apiResponse; }
[ "private", "function", "prepareApiResponse", "(", "ResponseContextAbstract", "$", "responseContext", ",", "string", "$", "apiClassMethod", ")", ":", "ApiResponseInterface", "{", "$", "prepareApiResponse", "=", "sprintf", "(", "\"prepare%sResponse\"", ",", "ucfirst", "("...
Prepares API response by processing ResponseContext @param ResponseContextAbstract $responseContext @param string $apiClassMethod @throws MethodDoesNotExistException @return ApiResponseInterface
[ "Prepares", "API", "response", "by", "processing", "ResponseContext" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/ApiAbstract.php#L186-L197
train
GinoPane/PHPolyglot
src/API/Implementation/ApiAbstract.php
ApiAbstract.assertMethodExists
private function assertMethodExists(string $method): void { if (!method_exists($this, $method)) { throw new MethodDoesNotExistException( sprintf("Specified method \"%s\" does not exist", $method) ); } }
php
private function assertMethodExists(string $method): void { if (!method_exists($this, $method)) { throw new MethodDoesNotExistException( sprintf("Specified method \"%s\" does not exist", $method) ); } }
[ "private", "function", "assertMethodExists", "(", "string", "$", "method", ")", ":", "void", "{", "if", "(", "!", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "throw", "new", "MethodDoesNotExistException", "(", "sprintf", "(", "\"S...
Throws exception if method does not exist @param string $method @throws MethodDoesNotExistException @return void
[ "Throws", "exception", "if", "method", "does", "not", "exist" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/ApiAbstract.php#L208-L215
train
GinoPane/PHPolyglot
src/API/Factory/ApiFactoryAbstract.php
ApiFactoryAbstract.assertConfigIsValid
protected function assertConfigIsValid(): void { foreach ($this->configProperties as $property) { if (empty(self::$config[$this->configSectionName][$property])) { throw new InvalidConfigException( sprintf( "Config section does not exist or is not filled properly: %s (\"%s\" is missing)", $this->configSectionName, $property ) ); } } $this->assertApiClassImplementsInterface($this->apiInterface); }
php
protected function assertConfigIsValid(): void { foreach ($this->configProperties as $property) { if (empty(self::$config[$this->configSectionName][$property])) { throw new InvalidConfigException( sprintf( "Config section does not exist or is not filled properly: %s (\"%s\" is missing)", $this->configSectionName, $property ) ); } } $this->assertApiClassImplementsInterface($this->apiInterface); }
[ "protected", "function", "assertConfigIsValid", "(", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "configProperties", "as", "$", "property", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "config", "[", "$", "this", "->", "configSecti...
Performs basic validation of config structure. This method is to be overridden by custom implementations if required @throws InvalidConfigException @throws InvalidApiClassException
[ "Performs", "basic", "validation", "of", "config", "structure", ".", "This", "method", "is", "to", "be", "overridden", "by", "custom", "implementations", "if", "required" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Factory/ApiFactoryAbstract.php#L174-L189
train
GinoPane/PHPolyglot
src/API/Factory/ApiFactoryAbstract.php
ApiFactoryAbstract.initEnvironment
protected function initEnvironment(): void { $envFile = $this->getRootRelatedPath($this->getEnvFileName()); $this->assertFileIsReadable($envFile); self::$envIsSet = (bool)(new Dotenv($this->getRootDirectory(), $this->getEnvFileName()))->load(); }
php
protected function initEnvironment(): void { $envFile = $this->getRootRelatedPath($this->getEnvFileName()); $this->assertFileIsReadable($envFile); self::$envIsSet = (bool)(new Dotenv($this->getRootDirectory(), $this->getEnvFileName()))->load(); }
[ "protected", "function", "initEnvironment", "(", ")", ":", "void", "{", "$", "envFile", "=", "$", "this", "->", "getRootRelatedPath", "(", "$", "this", "->", "getEnvFileName", "(", ")", ")", ";", "$", "this", "->", "assertFileIsReadable", "(", "$", "envFil...
Initialize environment variables @throws InvalidPathException
[ "Initialize", "environment", "variables" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Factory/ApiFactoryAbstract.php#L218-L225
train
GinoPane/PHPolyglot
src/API/Factory/ApiFactoryAbstract.php
ApiFactoryAbstract.initConfig
protected function initConfig(): void { $configFile = $this->getRootRelatedPath($this->getConfigFileName()); $this->assertFileIsReadable($configFile); self::$config = (array)(include $configFile); }
php
protected function initConfig(): void { $configFile = $this->getRootRelatedPath($this->getConfigFileName()); $this->assertFileIsReadable($configFile); self::$config = (array)(include $configFile); }
[ "protected", "function", "initConfig", "(", ")", ":", "void", "{", "$", "configFile", "=", "$", "this", "->", "getRootRelatedPath", "(", "$", "this", "->", "getConfigFileName", "(", ")", ")", ";", "$", "this", "->", "assertFileIsReadable", "(", "$", "confi...
Initialize config variables @throws InvalidPathException
[ "Initialize", "config", "variables" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Factory/ApiFactoryAbstract.php#L232-L239
train
GinoPane/PHPolyglot
src/PHPolyglot.php
PHPolyglot.lookup
public function lookup(string $text, string $languageFrom, string $languageTo = ''): DictionaryResponse { if ($languageTo) { $response = $this->getDictionaryApi()->getTranslateAlternatives( $text, //@codeCoverageIgnore new Language($languageTo), new Language($languageFrom) ); } else { $response = $this->getDictionaryApi()->getTextAlternatives($text, new Language($languageFrom)); } return $response; }
php
public function lookup(string $text, string $languageFrom, string $languageTo = ''): DictionaryResponse { if ($languageTo) { $response = $this->getDictionaryApi()->getTranslateAlternatives( $text, //@codeCoverageIgnore new Language($languageTo), new Language($languageFrom) ); } else { $response = $this->getDictionaryApi()->getTextAlternatives($text, new Language($languageFrom)); } return $response; }
[ "public", "function", "lookup", "(", "string", "$", "text", ",", "string", "$", "languageFrom", ",", "string", "$", "languageTo", "=", "''", ")", ":", "DictionaryResponse", "{", "if", "(", "$", "languageTo", ")", "{", "$", "response", "=", "$", "this", ...
The most common use of `lookup` is look up of the word in the same language, that's why the first language parameter of `lookup` method is language-from, language-to is optional, which differs from the language parameters order for translation @param string $text @param string $languageFrom @param string $languageTo @return DictionaryResponse
[ "The", "most", "common", "use", "of", "lookup", "is", "look", "up", "of", "the", "word", "in", "the", "same", "language", "that", "s", "why", "the", "first", "language", "parameter", "of", "lookup", "method", "is", "language", "-", "from", "language", "-...
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/PHPolyglot.php#L80-L93
train
GinoPane/PHPolyglot
src/API/Implementation/TTS/TtsApiAbstract.php
TtsApiAbstract.textToSpeech
public function textToSpeech( string $text, Language $language, TtsAudioFormat $format, array $additionalData = [] ): TtsResponse { /** @var TtsResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
php
public function textToSpeech( string $text, Language $language, TtsAudioFormat $format, array $additionalData = [] ): TtsResponse { /** @var TtsResponse $response */ $response = $this->callApi(__FUNCTION__, func_get_args()); return $response; }
[ "public", "function", "textToSpeech", "(", "string", "$", "text", ",", "Language", "$", "language", ",", "TtsAudioFormat", "$", "format", ",", "array", "$", "additionalData", "=", "[", "]", ")", ":", "TtsResponse", "{", "/** @var TtsResponse $response */", "$", ...
Gets TTS raw data, that can be saved afterwards @param string $text @param Language $language @param TtsAudioFormat $format @param array $additionalData @throws TransportException @throws ResponseContextException @throws BadResponseContextException @throws MethodDoesNotExistException @return TtsResponse
[ "Gets", "TTS", "raw", "data", "that", "can", "be", "saved", "afterwards" ]
0fca65e3390532482e0a00ab7c51e281ad323556
https://github.com/GinoPane/PHPolyglot/blob/0fca65e3390532482e0a00ab7c51e281ad323556/src/API/Implementation/TTS/TtsApiAbstract.php#L38-L48
train
phpforce/soap-client
src/Phpforce/SoapClient/Client.php
Client.getLoginResult
public function getLoginResult() { if (null === $this->loginResult) { $this->login($this->username, $this->password, $this->token); } return $this->loginResult; }
php
public function getLoginResult() { if (null === $this->loginResult) { $this->login($this->username, $this->password, $this->token); } return $this->loginResult; }
[ "public", "function", "getLoginResult", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "loginResult", ")", "{", "$", "this", "->", "login", "(", "$", "this", "->", "username", ",", "$", "this", "->", "password", ",", "$", "this", "->", ...
Get login result @return Result\LoginResult
[ "Get", "login", "result" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Client.php#L234-L241
train
phpforce/soap-client
src/Phpforce/SoapClient/Client.php
Client.createSoapVars
protected function createSoapVars(array $objects, $type) { $soapVars = array(); foreach ($objects as $object) { $sObject = $this->createSObject($object, $type); $xml = ''; if (isset($sObject->fieldsToNull)) { foreach ($sObject->fieldsToNull as $fieldToNull) { $xml .= '<fieldsToNull>' . $fieldToNull . '</fieldsToNull>'; } $fieldsToNullVar = new \SoapVar(new \SoapVar($xml, XSD_ANYXML), SOAP_ENC_ARRAY); $sObject->fieldsToNull = $fieldsToNullVar; } $soapVar = new \SoapVar($sObject, SOAP_ENC_OBJECT, $type, self::SOAP_NAMESPACE); $soapVars[] = $soapVar; } return $soapVars; }
php
protected function createSoapVars(array $objects, $type) { $soapVars = array(); foreach ($objects as $object) { $sObject = $this->createSObject($object, $type); $xml = ''; if (isset($sObject->fieldsToNull)) { foreach ($sObject->fieldsToNull as $fieldToNull) { $xml .= '<fieldsToNull>' . $fieldToNull . '</fieldsToNull>'; } $fieldsToNullVar = new \SoapVar(new \SoapVar($xml, XSD_ANYXML), SOAP_ENC_ARRAY); $sObject->fieldsToNull = $fieldsToNullVar; } $soapVar = new \SoapVar($sObject, SOAP_ENC_OBJECT, $type, self::SOAP_NAMESPACE); $soapVars[] = $soapVar; } return $soapVars; }
[ "protected", "function", "createSoapVars", "(", "array", "$", "objects", ",", "$", "type", ")", "{", "$", "soapVars", "=", "array", "(", ")", ";", "foreach", "(", "$", "objects", "as", "$", "object", ")", "{", "$", "sObject", "=", "$", "this", "->", ...
Turn Sobjects into \SoapVars @param array $objects Array of objects @param string $type Object type @return \SoapVar[]
[ "Turn", "Sobjects", "into", "\\", "SoapVars" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Client.php#L459-L481
train
phpforce/soap-client
src/Phpforce/SoapClient/Client.php
Client.fixFieldsToNullXml
protected function fixFieldsToNullXml(\SoapVar $object) { if (isset($object->enc_value->fieldsToNull) && is_array($object->enc_value->fieldsToNull) && count($object->enc_value->fieldsToNull) > 0) { $xml = ''; foreach ($object->enc_value->fieldsToNull as $fieldToNull) { $xml .= '<fieldsToNull>' . $fieldToNull . '</fieldsToNull>'; } return new \SoapVar(new \SoapVar($xml, XSD_ANYXML), SOAP_ENC_ARRAY); } }
php
protected function fixFieldsToNullXml(\SoapVar $object) { if (isset($object->enc_value->fieldsToNull) && is_array($object->enc_value->fieldsToNull) && count($object->enc_value->fieldsToNull) > 0) { $xml = ''; foreach ($object->enc_value->fieldsToNull as $fieldToNull) { $xml .= '<fieldsToNull>' . $fieldToNull . '</fieldsToNull>'; } return new \SoapVar(new \SoapVar($xml, XSD_ANYXML), SOAP_ENC_ARRAY); } }
[ "protected", "function", "fixFieldsToNullXml", "(", "\\", "SoapVar", "$", "object", ")", "{", "if", "(", "isset", "(", "$", "object", "->", "enc_value", "->", "fieldsToNull", ")", "&&", "is_array", "(", "$", "object", "->", "enc_value", "->", "fieldsToNull",...
Fix the fieldsToNull property for sObjects @param \SoapVar $object @return \SoapVar
[ "Fix", "the", "fieldsToNull", "property", "for", "sObjects" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Client.php#L489-L501
train
phpforce/soap-client
src/Phpforce/SoapClient/Client.php
Client.checkResult
protected function checkResult(array $results, array $params) { $exceptions = new Exception\SaveException(); for ($i = 0; $i < count($results); $i++) { // If the param was an (s)object, set it’s Id field if (is_object($params[$i]) && (!isset($params[$i]->Id) || null === $params[$i]->Id) && $results[$i] instanceof Result\SaveResult) { $params[$i]->Id = $results[$i]->getId(); } if (!$results[$i]->isSuccess()) { $results[$i]->setParam($params[$i]); $exceptions->add($results[$i]); } } if ($exceptions->count() > 0) { throw $exceptions; } return $results; }
php
protected function checkResult(array $results, array $params) { $exceptions = new Exception\SaveException(); for ($i = 0; $i < count($results); $i++) { // If the param was an (s)object, set it’s Id field if (is_object($params[$i]) && (!isset($params[$i]->Id) || null === $params[$i]->Id) && $results[$i] instanceof Result\SaveResult) { $params[$i]->Id = $results[$i]->getId(); } if (!$results[$i]->isSuccess()) { $results[$i]->setParam($params[$i]); $exceptions->add($results[$i]); } } if ($exceptions->count() > 0) { throw $exceptions; } return $results; }
[ "protected", "function", "checkResult", "(", "array", "$", "results", ",", "array", "$", "params", ")", "{", "$", "exceptions", "=", "new", "Exception", "\\", "SaveException", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count"...
Check response for errors Add each submitted object to its corresponding success or error message @param array $results Results @param array $params Parameters @throws Exception\SaveException When Salesforce returned an error @return array
[ "Check", "response", "for", "errors" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Client.php#L514-L538
train
phpforce/soap-client
src/Phpforce/SoapClient/Client.php
Client.setSoapHeaders
protected function setSoapHeaders(array $headers) { $soapHeaderObjects = array(); foreach ($headers as $key => $value) { $soapHeaderObjects[] = new \SoapHeader(self::SOAP_NAMESPACE, $key, $value); } $this->soapClient->__setSoapHeaders($soapHeaderObjects); }
php
protected function setSoapHeaders(array $headers) { $soapHeaderObjects = array(); foreach ($headers as $key => $value) { $soapHeaderObjects[] = new \SoapHeader(self::SOAP_NAMESPACE, $key, $value); } $this->soapClient->__setSoapHeaders($soapHeaderObjects); }
[ "protected", "function", "setSoapHeaders", "(", "array", "$", "headers", ")", "{", "$", "soapHeaderObjects", "=", "array", "(", ")", ";", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "soapHeaderObjects", "[", "]", ...
Set soap headers @param array $headers
[ "Set", "soap", "headers" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Client.php#L598-L606
train
phpforce/soap-client
src/Phpforce/SoapClient/Client.php
Client.createSObject
protected function createSObject($object, $objectType) { $sObject = new \stdClass(); foreach (get_object_vars($object) as $field => $value) { $type = $this->soapClient->getSoapElementType($objectType, $field); if ($field != 'Id' && !$type) { continue; } if ($value === null) { $sObject->fieldsToNull[] = $field; continue; } // As PHP \DateTime to SOAP dateTime conversion is not done // automatically with the SOAP typemap for sObjects, we do it here. switch ($type) { case 'date': if ($value instanceof \DateTime) { $value = $value->format('Y-m-d'); } break; case 'dateTime': if ($value instanceof \DateTime) { $value = $value->format('Y-m-d\TH:i:sP'); } break; case 'base64Binary': $value = base64_encode($value); break; } $sObject->$field = $value; } return $sObject; }
php
protected function createSObject($object, $objectType) { $sObject = new \stdClass(); foreach (get_object_vars($object) as $field => $value) { $type = $this->soapClient->getSoapElementType($objectType, $field); if ($field != 'Id' && !$type) { continue; } if ($value === null) { $sObject->fieldsToNull[] = $field; continue; } // As PHP \DateTime to SOAP dateTime conversion is not done // automatically with the SOAP typemap for sObjects, we do it here. switch ($type) { case 'date': if ($value instanceof \DateTime) { $value = $value->format('Y-m-d'); } break; case 'dateTime': if ($value instanceof \DateTime) { $value = $value->format('Y-m-d\TH:i:sP'); } break; case 'base64Binary': $value = base64_encode($value); break; } $sObject->$field = $value; } return $sObject; }
[ "protected", "function", "createSObject", "(", "$", "object", ",", "$", "objectType", ")", "{", "$", "sObject", "=", "new", "\\", "stdClass", "(", ")", ";", "foreach", "(", "get_object_vars", "(", "$", "object", ")", "as", "$", "field", "=>", "$", "val...
Create a Salesforce object Converts PHP \DateTimes to their SOAP equivalents. @param object $object Any object with public properties @param string $objectType Salesforce object type @return object
[ "Create", "a", "Salesforce", "object" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Client.php#L662-L699
train
phpforce/soap-client
src/Phpforce/SoapClient/Result/RecordIterator.php
RecordIterator.getObjectAt
protected function getObjectAt($pointer) { if ($this->queryResult->getRecord($pointer)) { $this->current = $this->queryResult->getRecord($pointer); foreach ($this->current as $key => &$value) { if ($value instanceof QueryResult) { $value = new RecordIterator($this->client, $value); } } return $this->current; } // If no record was found at pointer, see if there are more records // available for querying if (!$this->queryResult->isDone()) { $this->queryMore(); return $this->getObjectAt($this->pointer); } }
php
protected function getObjectAt($pointer) { if ($this->queryResult->getRecord($pointer)) { $this->current = $this->queryResult->getRecord($pointer); foreach ($this->current as $key => &$value) { if ($value instanceof QueryResult) { $value = new RecordIterator($this->client, $value); } } return $this->current; } // If no record was found at pointer, see if there are more records // available for querying if (!$this->queryResult->isDone()) { $this->queryMore(); return $this->getObjectAt($this->pointer); } }
[ "protected", "function", "getObjectAt", "(", "$", "pointer", ")", "{", "if", "(", "$", "this", "->", "queryResult", "->", "getRecord", "(", "$", "pointer", ")", ")", "{", "$", "this", "->", "current", "=", "$", "this", "->", "queryResult", "->", "getRe...
Get record at pointer, or, if there is no record, try to query Salesforce for more records @param int $pointer @return object
[ "Get", "record", "at", "pointer", "or", "if", "there", "is", "no", "record", "try", "to", "query", "Salesforce", "for", "more", "records" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Result/RecordIterator.php#L74-L95
train
phpforce/soap-client
src/Phpforce/SoapClient/Result/RecordIterator.php
RecordIterator.queryMore
protected function queryMore() { $result = $this->client->queryMore($this->queryResult->getQueryLocator()); $this->setQueryResult($result); $this->rewind(); }
php
protected function queryMore() { $result = $this->client->queryMore($this->queryResult->getQueryLocator()); $this->setQueryResult($result); $this->rewind(); }
[ "protected", "function", "queryMore", "(", ")", "{", "$", "result", "=", "$", "this", "->", "client", "->", "queryMore", "(", "$", "this", "->", "queryResult", "->", "getQueryLocator", "(", ")", ")", ";", "$", "this", "->", "setQueryResult", "(", "$", ...
Query Salesforce for more records and rewind iterator
[ "Query", "Salesforce", "for", "more", "records", "and", "rewind", "iterator" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Result/RecordIterator.php#L161-L166
train
phpforce/soap-client
src/Phpforce/SoapClient/Result/RecordIterator.php
RecordIterator.sort
public function sort($by) { $by = ucfirst($by); $array = $this->queryResult->getRecords(); usort($array, function($a, $b) use ($by) { // These two ifs take care of moving empty values to the end of the // array instead of the beginning if (!isset($a->$by) || !$a->$by) { return 1; } if (!isset($b->$by) || !$b->$by) { return -1; } return strcmp($a->$by, $b->$by); }); return new \ArrayIterator($array); }
php
public function sort($by) { $by = ucfirst($by); $array = $this->queryResult->getRecords(); usort($array, function($a, $b) use ($by) { // These two ifs take care of moving empty values to the end of the // array instead of the beginning if (!isset($a->$by) || !$a->$by) { return 1; } if (!isset($b->$by) || !$b->$by) { return -1; } return strcmp($a->$by, $b->$by); }); return new \ArrayIterator($array); }
[ "public", "function", "sort", "(", "$", "by", ")", "{", "$", "by", "=", "ucfirst", "(", "$", "by", ")", ";", "$", "array", "=", "$", "this", "->", "queryResult", "->", "getRecords", "(", ")", ";", "usort", "(", "$", "array", ",", "function", "(",...
Get sorted result iterator for the records on the current page Note: this method will not query Salesforce for records outside the current page. If you wish to sort larger sets of Salesforce records, do so in the select query you issue to the Salesforce API. @param string $by @return \ArrayIterator
[ "Get", "sorted", "result", "iterator", "for", "the", "records", "on", "the", "current", "page" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Result/RecordIterator.php#L197-L216
train
phpforce/soap-client
src/Phpforce/SoapClient/Soap/SoapClient.php
SoapClient.getSoapTypes
public function getSoapTypes() { if (null === $this->types) { $soapTypes = $this->__getTypes(); foreach ($soapTypes as $soapType) { $properties = array(); $lines = explode("\n", $soapType); if (!preg_match('/struct (.*) {/', $lines[0], $matches)) { continue; } $typeName = $matches[1]; foreach (array_slice($lines, 1) as $line) { if ($line == '}') { continue; } preg_match('/\s* (.*) (.*);/', $line, $matches); $properties[$matches[2]] = $matches[1]; } // Since every object extends sObject, need to append sObject elements to all native and custom objects if ($typeName !== 'sObject' && array_key_exists('sObject', $this->types)) { $properties = array_merge($properties, $this->types['sObject']); } $this->types[$typeName] = $properties; } } return $this->types; }
php
public function getSoapTypes() { if (null === $this->types) { $soapTypes = $this->__getTypes(); foreach ($soapTypes as $soapType) { $properties = array(); $lines = explode("\n", $soapType); if (!preg_match('/struct (.*) {/', $lines[0], $matches)) { continue; } $typeName = $matches[1]; foreach (array_slice($lines, 1) as $line) { if ($line == '}') { continue; } preg_match('/\s* (.*) (.*);/', $line, $matches); $properties[$matches[2]] = $matches[1]; } // Since every object extends sObject, need to append sObject elements to all native and custom objects if ($typeName !== 'sObject' && array_key_exists('sObject', $this->types)) { $properties = array_merge($properties, $this->types['sObject']); } $this->types[$typeName] = $properties; } } return $this->types; }
[ "public", "function", "getSoapTypes", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "types", ")", "{", "$", "soapTypes", "=", "$", "this", "->", "__getTypes", "(", ")", ";", "foreach", "(", "$", "soapTypes", "as", "$", "soapType", ")", ...
Retrieve SOAP types from the WSDL and parse them @return array Array of types and their properties
[ "Retrieve", "SOAP", "types", "from", "the", "WSDL", "and", "parse", "them" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Soap/SoapClient.php#L23-L54
train
phpforce/soap-client
src/Phpforce/SoapClient/Soap/SoapClient.php
SoapClient.getSoapElements
public function getSoapElements($complexType) { $types = $this->getSoapTypes(); if (isset($types[$complexType])) { return $types[$complexType]; } }
php
public function getSoapElements($complexType) { $types = $this->getSoapTypes(); if (isset($types[$complexType])) { return $types[$complexType]; } }
[ "public", "function", "getSoapElements", "(", "$", "complexType", ")", "{", "$", "types", "=", "$", "this", "->", "getSoapTypes", "(", ")", ";", "if", "(", "isset", "(", "$", "types", "[", "$", "complexType", "]", ")", ")", "{", "return", "$", "types...
Get SOAP elements for a complexType @param string $complexType Name of SOAP complexType @return array Names of elements and their types
[ "Get", "SOAP", "elements", "for", "a", "complexType" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Soap/SoapClient.php#L70-L76
train
phpforce/soap-client
src/Phpforce/SoapClient/ClientBuilder.php
ClientBuilder.build
public function build() { $soapClientFactory = new SoapClientFactory(); $soapClient = $soapClientFactory->factory($this->wsdl, $this->soapOptions); $client = new Client($soapClient, $this->username, $this->password, $this->token); if ($this->log) { $logPlugin = new LogPlugin($this->log); $client->getEventDispatcher()->addSubscriber($logPlugin); } return $client; }
php
public function build() { $soapClientFactory = new SoapClientFactory(); $soapClient = $soapClientFactory->factory($this->wsdl, $this->soapOptions); $client = new Client($soapClient, $this->username, $this->password, $this->token); if ($this->log) { $logPlugin = new LogPlugin($this->log); $client->getEventDispatcher()->addSubscriber($logPlugin); } return $client; }
[ "public", "function", "build", "(", ")", "{", "$", "soapClientFactory", "=", "new", "SoapClientFactory", "(", ")", ";", "$", "soapClient", "=", "$", "soapClientFactory", "->", "factory", "(", "$", "this", "->", "wsdl", ",", "$", "this", "->", "soapOptions"...
Build the Salesforce SOAP client @return Client
[ "Build", "the", "Salesforce", "SOAP", "client" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/ClientBuilder.php#L54-L67
train
phpforce/soap-client
src/Phpforce/SoapClient/Soap/TypeConverter/TypeConverterCollection.php
TypeConverterCollection.getTypemap
public function getTypemap() { $typemap = array(); foreach ($this->converters as $converter) { $typemap[] = array( 'type_name' => $converter->getTypeName(), 'type_ns' => $converter->getTypeNamespace(), 'from_xml' => function($input) use ($converter) { return $converter->convertXmlToPhp($input); }, 'to_xml' => function($input) use ($converter) { return $converter->convertPhpToXml($input); }, ); } return $typemap; }
php
public function getTypemap() { $typemap = array(); foreach ($this->converters as $converter) { $typemap[] = array( 'type_name' => $converter->getTypeName(), 'type_ns' => $converter->getTypeNamespace(), 'from_xml' => function($input) use ($converter) { return $converter->convertXmlToPhp($input); }, 'to_xml' => function($input) use ($converter) { return $converter->convertPhpToXml($input); }, ); } return $typemap; }
[ "public", "function", "getTypemap", "(", ")", "{", "$", "typemap", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "converters", "as", "$", "converter", ")", "{", "$", "typemap", "[", "]", "=", "array", "(", "'type_name'", "=>", "$", ...
Get this collection as a typemap that can be used in PHP's \SoapClient @return array
[ "Get", "this", "collection", "as", "a", "typemap", "that", "can", "be", "used", "in", "PHP", "s", "\\", "SoapClient" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/Soap/TypeConverter/TypeConverterCollection.php#L83-L101
train
phpforce/soap-client
src/Phpforce/SoapClient/BulkSaver.php
BulkSaver.save
public function save($record, $objectType, $matchField = null) { if ($matchField) { $this->addBulkUpsertRecord($record, $objectType, $matchField); } elseif (isset($record->Id) && null !== $record->Id) { $this->addBulkUpdateRecord($record, $objectType); } else { $this->addBulkCreateRecord($record, $objectType); } return $this; }
php
public function save($record, $objectType, $matchField = null) { if ($matchField) { $this->addBulkUpsertRecord($record, $objectType, $matchField); } elseif (isset($record->Id) && null !== $record->Id) { $this->addBulkUpdateRecord($record, $objectType); } else { $this->addBulkCreateRecord($record, $objectType); } return $this; }
[ "public", "function", "save", "(", "$", "record", ",", "$", "objectType", ",", "$", "matchField", "=", "null", ")", "{", "if", "(", "$", "matchField", ")", "{", "$", "this", "->", "addBulkUpsertRecord", "(", "$", "record", ",", "$", "objectType", ",", ...
Save a record in bulk @param mixed $record @param string $objectType The record type, e.g., Account @param string $matchField Optional match field for upserts @return BulkSaver
[ "Save", "a", "record", "in", "bulk" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/BulkSaver.php#L61-L72
train
phpforce/soap-client
src/Phpforce/SoapClient/BulkSaver.php
BulkSaver.addBulkCreateRecord
private function addBulkCreateRecord($record, $objectType) { if (isset($this->bulkCreateRecords[$objectType]) && count($this->bulkCreateRecords[$objectType]) == $this->bulkSaveLimit) { $this->flushCreates($objectType); } $this->bulkCreateRecords[$objectType][] = $record; }
php
private function addBulkCreateRecord($record, $objectType) { if (isset($this->bulkCreateRecords[$objectType]) && count($this->bulkCreateRecords[$objectType]) == $this->bulkSaveLimit) { $this->flushCreates($objectType); } $this->bulkCreateRecords[$objectType][] = $record; }
[ "private", "function", "addBulkCreateRecord", "(", "$", "record", ",", "$", "objectType", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "bulkCreateRecords", "[", "$", "objectType", "]", ")", "&&", "count", "(", "$", "this", "->", "bulkCreateRecords...
Add a record to the create queue @param sObject $sObject @param type $objectType
[ "Add", "a", "record", "to", "the", "create", "queue" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/BulkSaver.php#L171-L179
train
phpforce/soap-client
src/Phpforce/SoapClient/BulkSaver.php
BulkSaver.addBulkDeleteRecord
private function addBulkDeleteRecord($record) { if ($this->bulkDeleteLimit === count($this->bulkDeleteRecords)) { $this->flushDeletes(); } $this->bulkDeleteRecords[] = $record; }
php
private function addBulkDeleteRecord($record) { if ($this->bulkDeleteLimit === count($this->bulkDeleteRecords)) { $this->flushDeletes(); } $this->bulkDeleteRecords[] = $record; }
[ "private", "function", "addBulkDeleteRecord", "(", "$", "record", ")", "{", "if", "(", "$", "this", "->", "bulkDeleteLimit", "===", "count", "(", "$", "this", "->", "bulkDeleteRecords", ")", ")", "{", "$", "this", "->", "flushDeletes", "(", ")", ";", "}"...
Add a record id to the bulk delete queue (Delete calls @param string $id
[ "Add", "a", "record", "id", "to", "the", "bulk", "delete", "queue" ]
df1d06533d28b34bf7e1a8eb4c6b43316ea25b56
https://github.com/phpforce/soap-client/blob/df1d06533d28b34bf7e1a8eb4c6b43316ea25b56/src/Phpforce/SoapClient/BulkSaver.php#L188-L195
train
alt3/cakephp-swagger
src/Shell/SwaggerShell.php
SwaggerShell.getOptionParser
public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addSubcommand('makedocs', [ 'description' => __('Crawl-generate fresh swagger file system documents for all entries found in the library.') ]) ->addArgument('host', [ 'help' => __("Swagger host FQDN (without protocol) as to be inserted into the swagger doc property 'host'"), 'required' => true ]); return $parser; }
php
public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addSubcommand('makedocs', [ 'description' => __('Crawl-generate fresh swagger file system documents for all entries found in the library.') ]) ->addArgument('host', [ 'help' => __("Swagger host FQDN (without protocol) as to be inserted into the swagger doc property 'host'"), 'required' => true ]); return $parser; }
[ "public", "function", "getOptionParser", "(", ")", "{", "$", "parser", "=", "parent", "::", "getOptionParser", "(", ")", ";", "$", "parser", "->", "addSubcommand", "(", "'makedocs'", ",", "[", "'description'", "=>", "__", "(", "'Crawl-generate fresh swagger file...
Define available subcommands, arguments and options. @return \Cake\Console\ConsoleOptionParser @throws \Aura\Intl\Exception
[ "Define", "available", "subcommands", "arguments", "and", "options", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Shell/SwaggerShell.php#L20-L33
train
alt3/cakephp-swagger
src/Shell/SwaggerShell.php
SwaggerShell.makedocs
public function makedocs($host) { // make same configuration as used by the API availble inside the lib if (Configure::read('Swagger')) { $this->config = Hash::merge(AppController::$defaultConfig, Configure::read('Swagger')); } $this->out('Crawl-generating swagger documents...'); SwaggerTools::makeDocs($host); $this->out('Command completed successfully.'); }
php
public function makedocs($host) { // make same configuration as used by the API availble inside the lib if (Configure::read('Swagger')) { $this->config = Hash::merge(AppController::$defaultConfig, Configure::read('Swagger')); } $this->out('Crawl-generating swagger documents...'); SwaggerTools::makeDocs($host); $this->out('Command completed successfully.'); }
[ "public", "function", "makedocs", "(", "$", "host", ")", "{", "// make same configuration as used by the API availble inside the lib", "if", "(", "Configure", "::", "read", "(", "'Swagger'", ")", ")", "{", "$", "this", "->", "config", "=", "Hash", "::", "merge", ...
Generate fresh filesystem documents for all entries found in the library. @param string $host Hostname of system serving swagger documents (without protocol) @return void
[ "Generate", "fresh", "filesystem", "documents", "for", "all", "entries", "found", "in", "the", "library", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Shell/SwaggerShell.php#L41-L51
train
alt3/cakephp-swagger
src/Controller/UiController.php
UiController.index
public function index() { $this->viewBuilder()->setLayout(false); $this->set('uiConfig', $this->config['ui']); $this->set('url', $this->getDefaultDocumentUrl()); }
php
public function index() { $this->viewBuilder()->setLayout(false); $this->set('uiConfig', $this->config['ui']); $this->set('url', $this->getDefaultDocumentUrl()); }
[ "public", "function", "index", "(", ")", "{", "$", "this", "->", "viewBuilder", "(", ")", "->", "setLayout", "(", "false", ")", ";", "$", "this", "->", "set", "(", "'uiConfig'", ",", "$", "this", "->", "config", "[", "'ui'", "]", ")", ";", "$", "...
Index action used for setting template variables. @return void
[ "Index", "action", "used", "for", "setting", "template", "variables", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Controller/UiController.php#L16-L21
train
alt3/cakephp-swagger
src/Controller/DocsController.php
DocsController.addCorsHeaders
protected function addCorsHeaders() { // set CORS headers if specified in config if (!isset($this->config['docs']['cors'])) { return false; } if (!count($this->config['docs']['cors'])) { return false; } foreach ($this->config['docs']['cors'] as $header => $value) { $this->response = $this->response->withHeader($header, $value); } }
php
protected function addCorsHeaders() { // set CORS headers if specified in config if (!isset($this->config['docs']['cors'])) { return false; } if (!count($this->config['docs']['cors'])) { return false; } foreach ($this->config['docs']['cors'] as $header => $value) { $this->response = $this->response->withHeader($header, $value); } }
[ "protected", "function", "addCorsHeaders", "(", ")", "{", "// set CORS headers if specified in config", "if", "(", "!", "isset", "(", "$", "this", "->", "config", "[", "'docs'", "]", "[", "'cors'", "]", ")", ")", "{", "return", "false", ";", "}", "if", "("...
Set CORS headers if found in configuration. @return bool|void
[ "Set", "CORS", "headers", "if", "found", "in", "configuration", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Controller/DocsController.php#L83-L97
train
alt3/cakephp-swagger
src/Controller/DocsController.php
DocsController.jsonResponse
protected function jsonResponse($json) { $this->set('json', $json); $this->viewBuilder()->setLayout(false); $this->addCorsHeaders(); $this->response = $this->response->withType('json'); }
php
protected function jsonResponse($json) { $this->set('json', $json); $this->viewBuilder()->setLayout(false); $this->addCorsHeaders(); $this->response = $this->response->withType('json'); }
[ "protected", "function", "jsonResponse", "(", "$", "json", ")", "{", "$", "this", "->", "set", "(", "'json'", ",", "$", "json", ")", ";", "$", "this", "->", "viewBuilder", "(", ")", "->", "setLayout", "(", "false", ")", ";", "$", "this", "->", "add...
Configures the json response before calling the index view. @param string $json JSON encoded string @return void
[ "Configures", "the", "json", "response", "before", "calling", "the", "index", "view", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Controller/DocsController.php#L105-L111
train
alt3/cakephp-swagger
src/Lib/SwaggerTools.php
SwaggerTools.getSwaggerDocument
public static function getSwaggerDocument($id, $host) { // load document from filesystem $filePath = CACHE . self::$filePrefix . $id . '.json'; if (!Configure::read('Swagger.docs.crawl')) { if (!file_exists($filePath)) { throw new NotFoundException("Swagger json document was not found on filesystem: $filePath"); } $fh = new File($filePath); return $fh->read(); } // otherwise crawl-generate a fresh document $swaggerOptions = []; if (Configure::read("Swagger.library.$id.exclude")) { $swaggerOptions = [ 'exclude' => Configure::read("Swagger.library.$id.exclude") ]; } if (Configure::read('Swagger.analyser')) { $swaggerOptions['analyser'] = Configure::read('Swagger.analyser'); } $swagger = \Swagger\scan(Configure::read("Swagger.library.$id.include"), $swaggerOptions); // set object properties required by UI to generate the BASE URL $swagger->host = $host; if (empty($swagger->basePath)) { $swagger->basePath = '/' . Configure::read('App.base'); } $swagger->schemes = Configure::read('Swagger.ui.schemes'); // write document to filesystem self::writeSwaggerDocumentToFile($filePath, $swagger); return $swagger; }
php
public static function getSwaggerDocument($id, $host) { // load document from filesystem $filePath = CACHE . self::$filePrefix . $id . '.json'; if (!Configure::read('Swagger.docs.crawl')) { if (!file_exists($filePath)) { throw new NotFoundException("Swagger json document was not found on filesystem: $filePath"); } $fh = new File($filePath); return $fh->read(); } // otherwise crawl-generate a fresh document $swaggerOptions = []; if (Configure::read("Swagger.library.$id.exclude")) { $swaggerOptions = [ 'exclude' => Configure::read("Swagger.library.$id.exclude") ]; } if (Configure::read('Swagger.analyser')) { $swaggerOptions['analyser'] = Configure::read('Swagger.analyser'); } $swagger = \Swagger\scan(Configure::read("Swagger.library.$id.include"), $swaggerOptions); // set object properties required by UI to generate the BASE URL $swagger->host = $host; if (empty($swagger->basePath)) { $swagger->basePath = '/' . Configure::read('App.base'); } $swagger->schemes = Configure::read('Swagger.ui.schemes'); // write document to filesystem self::writeSwaggerDocumentToFile($filePath, $swagger); return $swagger; }
[ "public", "static", "function", "getSwaggerDocument", "(", "$", "id", ",", "$", "host", ")", "{", "// load document from filesystem", "$", "filePath", "=", "CACHE", ".", "self", "::", "$", "filePrefix", ".", "$", "id", ".", "'.json'", ";", "if", "(", "!", ...
Returns a single swagger document from filesystem or crawl-generates a fresh one. @param string $id Name of the document @param string $host Hostname of system serving swagger documents (without protocol) @throws \InvalidArgumentException @return string
[ "Returns", "a", "single", "swagger", "document", "from", "filesystem", "or", "crawl", "-", "generates", "a", "fresh", "one", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Lib/SwaggerTools.php#L26-L62
train
alt3/cakephp-swagger
src/Lib/SwaggerTools.php
SwaggerTools.writeSwaggerDocumentToFile
protected static function writeSwaggerDocumentToFile($path, $content) { $fh = new File($path, true); if (!$fh->write($content)) { throw new InternalErrorException('Error writing Swagger json document to filesystem'); } return true; }
php
protected static function writeSwaggerDocumentToFile($path, $content) { $fh = new File($path, true); if (!$fh->write($content)) { throw new InternalErrorException('Error writing Swagger json document to filesystem'); } return true; }
[ "protected", "static", "function", "writeSwaggerDocumentToFile", "(", "$", "path", ",", "$", "content", ")", "{", "$", "fh", "=", "new", "File", "(", "$", "path", ",", "true", ")", ";", "if", "(", "!", "$", "fh", "->", "write", "(", "$", "content", ...
Write swagger document to filesystem. @param string $path Full path to the json document including filename @param string $content Swagger content @throws \Cake\Http\Exception\InternalErrorException @return bool
[ "Write", "swagger", "document", "to", "filesystem", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Lib/SwaggerTools.php#L72-L80
train
alt3/cakephp-swagger
src/Lib/SwaggerTools.php
SwaggerTools.makeDocs
public static function makeDocs($host) { if (!Configure::read('Swagger.library')) { throw new \InvalidArgumentException('Swagger configuration file does not contain a library section'); } // make sure documents will be crawled and not read from filesystem Configure::write('Swagger.docs.crawl', true); // generate docs foreach (array_keys(Configure::read('Swagger.library')) as $doc) { self::getSwaggerDocument($doc, $host); } return true; }
php
public static function makeDocs($host) { if (!Configure::read('Swagger.library')) { throw new \InvalidArgumentException('Swagger configuration file does not contain a library section'); } // make sure documents will be crawled and not read from filesystem Configure::write('Swagger.docs.crawl', true); // generate docs foreach (array_keys(Configure::read('Swagger.library')) as $doc) { self::getSwaggerDocument($doc, $host); } return true; }
[ "public", "static", "function", "makeDocs", "(", "$", "host", ")", "{", "if", "(", "!", "Configure", "::", "read", "(", "'Swagger.library'", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Swagger configuration file does not contain a library...
Convenience function used by the shell to create filesystem documents for all entries found in the library. @param string $host Hostname of system serving swagger documents (without protocol) @throws \InvalidArgumentException @return bool true if successful, false on all errors
[ "Convenience", "function", "used", "by", "the", "shell", "to", "create", "filesystem", "documents", "for", "all", "entries", "found", "in", "the", "library", "." ]
8cc7b03d0bd560e080d3001e381bcd3d22e85ceb
https://github.com/alt3/cakephp-swagger/blob/8cc7b03d0bd560e080d3001e381bcd3d22e85ceb/src/Lib/SwaggerTools.php#L90-L105
train
rainlab/location-plugin
models/Country.php
Country.getFromIp
public static function getFromIp($ipAddress) { try { $body = (string) Http::get('http://ip2c.org/?ip='.$ipAddress); if (substr($body, 0, 1) === '1') { $code = explode(';', $body)[1]; return static::where('code', $code)->first(); } } catch (Exception $e) {} }
php
public static function getFromIp($ipAddress) { try { $body = (string) Http::get('http://ip2c.org/?ip='.$ipAddress); if (substr($body, 0, 1) === '1') { $code = explode(';', $body)[1]; return static::where('code', $code)->first(); } } catch (Exception $e) {} }
[ "public", "static", "function", "getFromIp", "(", "$", "ipAddress", ")", "{", "try", "{", "$", "body", "=", "(", "string", ")", "Http", "::", "get", "(", "'http://ip2c.org/?ip='", ".", "$", "ipAddress", ")", ";", "if", "(", "substr", "(", "$", "body", ...
Attempts to find a country from the IP address. @param string $ipAddress @return self
[ "Attempts", "to", "find", "a", "country", "from", "the", "IP", "address", "." ]
fe80d08c8f1e4a4415c608e2df2a28fd0d8bd3a3
https://github.com/rainlab/location-plugin/blob/fe80d08c8f1e4a4415c608e2df2a28fd0d8bd3a3/models/Country.php#L96-L107
train
rainlab/location-plugin
behaviors/LocationModel.php
LocationModel.setCountryCodeAttribute
public function setCountryCodeAttribute($code) { if (!$country = Country::whereCode($code)->first()) { return; } $this->model->country = $country; }
php
public function setCountryCodeAttribute($code) { if (!$country = Country::whereCode($code)->first()) { return; } $this->model->country = $country; }
[ "public", "function", "setCountryCodeAttribute", "(", "$", "code", ")", "{", "if", "(", "!", "$", "country", "=", "Country", "::", "whereCode", "(", "$", "code", ")", "->", "first", "(", ")", ")", "{", "return", ";", "}", "$", "this", "->", "model", ...
Sets the "country" relation with the code specified, model lookup used. @param string $code
[ "Sets", "the", "country", "relation", "with", "the", "code", "specified", "model", "lookup", "used", "." ]
fe80d08c8f1e4a4415c608e2df2a28fd0d8bd3a3
https://github.com/rainlab/location-plugin/blob/fe80d08c8f1e4a4415c608e2df2a28fd0d8bd3a3/behaviors/LocationModel.php#L62-L69
train
rainlab/location-plugin
behaviors/LocationModel.php
LocationModel.setStateCodeAttribute
public function setStateCodeAttribute($code) { if (!$state = State::whereCode($code)->first()) { return; } $this->model->state = $state; }
php
public function setStateCodeAttribute($code) { if (!$state = State::whereCode($code)->first()) { return; } $this->model->state = $state; }
[ "public", "function", "setStateCodeAttribute", "(", "$", "code", ")", "{", "if", "(", "!", "$", "state", "=", "State", "::", "whereCode", "(", "$", "code", ")", "->", "first", "(", ")", ")", "{", "return", ";", "}", "$", "this", "->", "model", "->"...
Sets the "state" relation with the code specified, model lookup used. @param string $code
[ "Sets", "the", "state", "relation", "with", "the", "code", "specified", "model", "lookup", "used", "." ]
fe80d08c8f1e4a4415c608e2df2a28fd0d8bd3a3
https://github.com/rainlab/location-plugin/blob/fe80d08c8f1e4a4415c608e2df2a28fd0d8bd3a3/behaviors/LocationModel.php#L75-L82
train
himiklab/yii2-sitemap-module
Sitemap.php
Sitemap.buildSitemap
public function buildSitemap() { $urls = $this->urls; foreach ($this->models as $modelName) { /** @var behaviors\SitemapBehavior|\yii\db\ActiveRecord $model */ if (is_array($modelName)) { $model = new $modelName['class']; if (isset($modelName['behaviors'])) { $model->attachBehaviors($modelName['behaviors']); } } else { $model = new $modelName; } $urls = array_merge($urls, $model->generateSiteMap()); } $sitemapData = $this->createControllerByID('default')->renderPartial('index', ['urls' => $urls]); if ($this->enableGzipedCache) { $sitemapData = gzencode($sitemapData); } $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire); return $sitemapData; }
php
public function buildSitemap() { $urls = $this->urls; foreach ($this->models as $modelName) { /** @var behaviors\SitemapBehavior|\yii\db\ActiveRecord $model */ if (is_array($modelName)) { $model = new $modelName['class']; if (isset($modelName['behaviors'])) { $model->attachBehaviors($modelName['behaviors']); } } else { $model = new $modelName; } $urls = array_merge($urls, $model->generateSiteMap()); } $sitemapData = $this->createControllerByID('default')->renderPartial('index', ['urls' => $urls]); if ($this->enableGzipedCache) { $sitemapData = gzencode($sitemapData); } $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire); return $sitemapData; }
[ "public", "function", "buildSitemap", "(", ")", "{", "$", "urls", "=", "$", "this", "->", "urls", ";", "foreach", "(", "$", "this", "->", "models", "as", "$", "modelName", ")", "{", "/** @var behaviors\\SitemapBehavior|\\yii\\db\\ActiveRecord $model */", "if", "...
Build and cache a site map. @return string @throws \yii\base\InvalidConfigException @throws \yii\base\InvalidParamException
[ "Build", "and", "cache", "a", "site", "map", "." ]
e680cb50049102c47342d27f497f77d8c0e447b3
https://github.com/himiklab/yii2-sitemap-module/blob/e680cb50049102c47342d27f497f77d8c0e447b3/Sitemap.php#L65-L89
train
pantheon-systems/terminus-rsync-plugin
src/Commands/RsyncCommand.php
RsyncCommand.rsyncCommand
public function rsyncCommand($src, $dest, array $rsyncOptions) { if (strpos($src, ':') !== false) { $site_env_id = $this->getSiteEnvIdFromPath($src); $src = $this->removeSiteEnvIdFromPath($src); } else { $site_env_id = $this->getSiteEnvIdFromPath($dest); $dest = $this->removeSiteEnvIdFromPath($dest); } return $this->rsync($site_env_id, $src, $dest, $rsyncOptions); }
php
public function rsyncCommand($src, $dest, array $rsyncOptions) { if (strpos($src, ':') !== false) { $site_env_id = $this->getSiteEnvIdFromPath($src); $src = $this->removeSiteEnvIdFromPath($src); } else { $site_env_id = $this->getSiteEnvIdFromPath($dest); $dest = $this->removeSiteEnvIdFromPath($dest); } return $this->rsync($site_env_id, $src, $dest, $rsyncOptions); }
[ "public", "function", "rsyncCommand", "(", "$", "src", ",", "$", "dest", ",", "array", "$", "rsyncOptions", ")", "{", "if", "(", "strpos", "(", "$", "src", ",", "':'", ")", "!==", "false", ")", "{", "$", "site_env_id", "=", "$", "this", "->", "getS...
Call rsync on a Pantheon site @command remote:rsync @aliases rsync @param string $src Source path @param string $dest Destination path @param array $rsyncOptions All of the options after -- (passed to rsync)
[ "Call", "rsync", "on", "a", "Pantheon", "site" ]
2b94a3197409aece9a07303263ec26f521fa7ad7
https://github.com/pantheon-systems/terminus-rsync-plugin/blob/2b94a3197409aece9a07303263ec26f521fa7ad7/src/Commands/RsyncCommand.php#L45-L56
train
pantheon-systems/terminus-rsync-plugin
src/Commands/RsyncCommand.php
RsyncCommand.rsync
protected function rsync($site_env_id, $src, $dest, array $rsyncOptions) { list($site, $env) = $this->getSiteEnv($site_env_id); $env_id = $env->getName(); $siteInfo = $site->serialize(); $site_id = $siteInfo['id']; // Stipulate the temporary directory to use iff the destination is remote. $tmpdir = ''; if ($dest[0] == ':') { $tmpdir = '~/tmp'; } $siteAddress = "$env_id.$site_id@appserver.$env_id.$site_id.drush.in:"; $src = preg_replace('/^:/', $siteAddress, $src); $dest = preg_replace('/^:/', $siteAddress, $dest); // Get the rsync options string. If the user did not pass // in any mode options (e.g. '-r'), then add in the default. $rsyncOptionString = implode(' ', $rsyncOptions); if (!preg_match('/(^| )-[^-]/', $rsyncOptionString)) { $rsyncOptionString = "-rlIpz $rsyncOptionString"; } // Add in a tmp-dir option if one was not already specified if (!empty($tmpdir) && !preg_match('/(^| )--temp-dir/', $rsyncOptionString)) { $rsyncOptionString = "$rsyncOptionString --temp-dir=$tmpdir --delay-updates"; } $this->log()->notice('Running {cmd}', ['cmd' => "rsync $rsyncOptionString $src $dest"]); $this->passthru("rsync $rsyncOptionString --ipv4 --exclude=.git -e 'ssh -p 2222' '$src' '$dest' "); }
php
protected function rsync($site_env_id, $src, $dest, array $rsyncOptions) { list($site, $env) = $this->getSiteEnv($site_env_id); $env_id = $env->getName(); $siteInfo = $site->serialize(); $site_id = $siteInfo['id']; // Stipulate the temporary directory to use iff the destination is remote. $tmpdir = ''; if ($dest[0] == ':') { $tmpdir = '~/tmp'; } $siteAddress = "$env_id.$site_id@appserver.$env_id.$site_id.drush.in:"; $src = preg_replace('/^:/', $siteAddress, $src); $dest = preg_replace('/^:/', $siteAddress, $dest); // Get the rsync options string. If the user did not pass // in any mode options (e.g. '-r'), then add in the default. $rsyncOptionString = implode(' ', $rsyncOptions); if (!preg_match('/(^| )-[^-]/', $rsyncOptionString)) { $rsyncOptionString = "-rlIpz $rsyncOptionString"; } // Add in a tmp-dir option if one was not already specified if (!empty($tmpdir) && !preg_match('/(^| )--temp-dir/', $rsyncOptionString)) { $rsyncOptionString = "$rsyncOptionString --temp-dir=$tmpdir --delay-updates"; } $this->log()->notice('Running {cmd}', ['cmd' => "rsync $rsyncOptionString $src $dest"]); $this->passthru("rsync $rsyncOptionString --ipv4 --exclude=.git -e 'ssh -p 2222' '$src' '$dest' "); }
[ "protected", "function", "rsync", "(", "$", "site_env_id", ",", "$", "src", ",", "$", "dest", ",", "array", "$", "rsyncOptions", ")", "{", "list", "(", "$", "site", ",", "$", "env", ")", "=", "$", "this", "->", "getSiteEnv", "(", "$", "site_env_id", ...
Call rsync to or from the specified site. @param string $site_env_id Remote site @param string $src Source path to copy from. Start with ":" for remote. @param string $dest Destination path to copy to. Start with ":" for remote.
[ "Call", "rsync", "to", "or", "from", "the", "specified", "site", "." ]
2b94a3197409aece9a07303263ec26f521fa7ad7
https://github.com/pantheon-systems/terminus-rsync-plugin/blob/2b94a3197409aece9a07303263ec26f521fa7ad7/src/Commands/RsyncCommand.php#L65-L97
train
wp-cli/wp-cli-tests
features/bootstrap/FeatureContext.php
FeatureContext.get_vendor_dir
private static function get_vendor_dir() { static $vendor_dir = null; if ( null !== $vendor_dir ) { return $vendor_dir; } $paths = [ dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) . '/bin/wp', dirname( dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) ) . '/bin/wp', dirname( dirname( __DIR__ ) ) . '/vendor/bin/wp', ]; foreach ( $paths as $path ) { if ( file_exists( $path ) && is_executable( $path ) ) { $vendor_dir = (string) realpath( dirname( $path ) ); break; } } if ( null === $vendor_dir ) { // Did not detect WP-CLI binary, so make a random guess. $vendor_dir = '/usr/local/bin'; } return $vendor_dir; }
php
private static function get_vendor_dir() { static $vendor_dir = null; if ( null !== $vendor_dir ) { return $vendor_dir; } $paths = [ dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) . '/bin/wp', dirname( dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) ) . '/bin/wp', dirname( dirname( __DIR__ ) ) . '/vendor/bin/wp', ]; foreach ( $paths as $path ) { if ( file_exists( $path ) && is_executable( $path ) ) { $vendor_dir = (string) realpath( dirname( $path ) ); break; } } if ( null === $vendor_dir ) { // Did not detect WP-CLI binary, so make a random guess. $vendor_dir = '/usr/local/bin'; } return $vendor_dir; }
[ "private", "static", "function", "get_vendor_dir", "(", ")", "{", "static", "$", "vendor_dir", "=", "null", ";", "if", "(", "null", "!==", "$", "vendor_dir", ")", "{", "return", "$", "vendor_dir", ";", "}", "$", "paths", "=", "[", "dirname", "(", "dirn...
Get the path to the Composer vendor folder. @return string Absolute path to the Composer vendor folder.
[ "Get", "the", "path", "to", "the", "Composer", "vendor", "folder", "." ]
83b636fc7cb69ff257e025d1c855c190143a45db
https://github.com/wp-cli/wp-cli-tests/blob/83b636fc7cb69ff257e025d1c855c190143a45db/features/bootstrap/FeatureContext.php#L176-L202
train
wp-cli/wp-cli-tests
features/bootstrap/FeatureContext.php
FeatureContext.get_behat_internal_variables
private static function get_behat_internal_variables() { static $variables = null; if ( null !== $variables ) { return $variables; } $paths = [ dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) . '/wp-cli/wp-cli/VERSION', dirname( dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) ) . '/VERSION', dirname( dirname( __DIR__ ) ) . '/vendor/wp-cli/wp-cli/VERSION', ]; $framework_root = dirname( dirname( __DIR__ ) ); foreach ( $paths as $path ) { if ( file_exists( $path ) ) { $framework_root = (string) realpath( dirname( $path ) ); break; } } $variables = [ 'FRAMEWORK_ROOT' => realpath( $framework_root ), 'SRC_DIR' => realpath( dirname( dirname( __DIR__ ) ) ), 'PROJECT_DIR' => realpath( dirname( dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) ) ), ]; return $variables; }
php
private static function get_behat_internal_variables() { static $variables = null; if ( null !== $variables ) { return $variables; } $paths = [ dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) . '/wp-cli/wp-cli/VERSION', dirname( dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) ) . '/VERSION', dirname( dirname( __DIR__ ) ) . '/vendor/wp-cli/wp-cli/VERSION', ]; $framework_root = dirname( dirname( __DIR__ ) ); foreach ( $paths as $path ) { if ( file_exists( $path ) ) { $framework_root = (string) realpath( dirname( $path ) ); break; } } $variables = [ 'FRAMEWORK_ROOT' => realpath( $framework_root ), 'SRC_DIR' => realpath( dirname( dirname( __DIR__ ) ) ), 'PROJECT_DIR' => realpath( dirname( dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) ) ), ]; return $variables; }
[ "private", "static", "function", "get_behat_internal_variables", "(", ")", "{", "static", "$", "variables", "=", "null", ";", "if", "(", "null", "!==", "$", "variables", ")", "{", "return", "$", "variables", ";", "}", "$", "paths", "=", "[", "dirname", "...
Get the internal variables to use within tests. @return array Associative array of internal variables that will be mapped into tests.
[ "Get", "the", "internal", "variables", "to", "use", "within", "tests", "." ]
83b636fc7cb69ff257e025d1c855c190143a45db
https://github.com/wp-cli/wp-cli-tests/blob/83b636fc7cb69ff257e025d1c855c190143a45db/features/bootstrap/FeatureContext.php#L261-L289
train
wp-cli/wp-cli-tests
features/bootstrap/FeatureContext.php
FeatureContext.cache_wp_files
private static function cache_wp_files() { $wp_version = getenv( 'WP_VERSION' ); $wp_version_suffix = ( false !== $wp_version ) ? "-$wp_version" : ''; self::$cache_dir = sys_get_temp_dir() . '/wp-cli-test-core-download-cache' . $wp_version_suffix; if ( is_readable( self::$cache_dir . '/wp-config-sample.php' ) ) { return; } $cmd = Utils\esc_cmd( 'wp core download --force --path=%s', self::$cache_dir ); if ( $wp_version ) { $cmd .= Utils\esc_cmd( ' --version=%s', $wp_version ); } Process::create( $cmd, null, self::get_process_env_variables() )->run_check(); }
php
private static function cache_wp_files() { $wp_version = getenv( 'WP_VERSION' ); $wp_version_suffix = ( false !== $wp_version ) ? "-$wp_version" : ''; self::$cache_dir = sys_get_temp_dir() . '/wp-cli-test-core-download-cache' . $wp_version_suffix; if ( is_readable( self::$cache_dir . '/wp-config-sample.php' ) ) { return; } $cmd = Utils\esc_cmd( 'wp core download --force --path=%s', self::$cache_dir ); if ( $wp_version ) { $cmd .= Utils\esc_cmd( ' --version=%s', $wp_version ); } Process::create( $cmd, null, self::get_process_env_variables() )->run_check(); }
[ "private", "static", "function", "cache_wp_files", "(", ")", "{", "$", "wp_version", "=", "getenv", "(", "'WP_VERSION'", ")", ";", "$", "wp_version_suffix", "=", "(", "false", "!==", "$", "wp_version", ")", "?", "\"-$wp_version\"", ":", "''", ";", "self", ...
We cache the results of `wp core download` to improve test performance. Ideally, we'd cache at the HTTP layer for more reliable tests.
[ "We", "cache", "the", "results", "of", "wp", "core", "download", "to", "improve", "test", "performance", ".", "Ideally", "we", "d", "cache", "at", "the", "HTTP", "layer", "for", "more", "reliable", "tests", "." ]
83b636fc7cb69ff257e025d1c855c190143a45db
https://github.com/wp-cli/wp-cli-tests/blob/83b636fc7cb69ff257e025d1c855c190143a45db/features/bootstrap/FeatureContext.php#L295-L309
train
wp-cli/wp-cli-tests
features/bootstrap/FeatureContext.php
FeatureContext.terminate_proc
private static function terminate_proc( $master_pid ) { $output = `ps -o ppid,pid,command | grep $master_pid`; foreach ( explode( PHP_EOL, $output ) as $line ) { if ( preg_match( '/^\s*(\d+)\s+(\d+)/', $line, $matches ) ) { $parent = $matches[1]; $child = $matches[2]; if ( (int) $parent === (int) $master_pid ) { self::terminate_proc( $child ); } } } if ( ! posix_kill( (int) $master_pid, 9 ) ) { $errno = posix_get_last_error(); // Ignore "No such process" error as that's what we want. if ( 3 /*ESRCH*/ !== $errno ) { throw new RuntimeException( posix_strerror( $errno ) ); } } }
php
private static function terminate_proc( $master_pid ) { $output = `ps -o ppid,pid,command | grep $master_pid`; foreach ( explode( PHP_EOL, $output ) as $line ) { if ( preg_match( '/^\s*(\d+)\s+(\d+)/', $line, $matches ) ) { $parent = $matches[1]; $child = $matches[2]; if ( (int) $parent === (int) $master_pid ) { self::terminate_proc( $child ); } } } if ( ! posix_kill( (int) $master_pid, 9 ) ) { $errno = posix_get_last_error(); // Ignore "No such process" error as that's what we want. if ( 3 /*ESRCH*/ !== $errno ) { throw new RuntimeException( posix_strerror( $errno ) ); } } }
[ "private", "static", "function", "terminate_proc", "(", "$", "master_pid", ")", "{", "$", "output", "=", "`ps -o ppid,pid,command | grep $master_pid`", ";", "foreach", "(", "explode", "(", "PHP_EOL", ",", "$", "output", ")", "as", "$", "line", ")", "{", "if", ...
Terminate a process and any of its children.
[ "Terminate", "a", "process", "and", "any", "of", "its", "children", "." ]
83b636fc7cb69ff257e025d1c855c190143a45db
https://github.com/wp-cli/wp-cli-tests/blob/83b636fc7cb69ff257e025d1c855c190143a45db/features/bootstrap/FeatureContext.php#L425-L447
train
wp-cli/wp-cli-tests
features/bootstrap/FeatureContext.php
FeatureContext.create_cache_dir
public static function create_cache_dir() { if ( self::$suite_cache_dir ) { self::remove_dir( self::$suite_cache_dir ); } self::$suite_cache_dir = sys_get_temp_dir() . '/' . uniqid( 'wp-cli-test-suite-cache-' . self::$temp_dir_infix . '-', true ); mkdir( self::$suite_cache_dir ); return self::$suite_cache_dir; }
php
public static function create_cache_dir() { if ( self::$suite_cache_dir ) { self::remove_dir( self::$suite_cache_dir ); } self::$suite_cache_dir = sys_get_temp_dir() . '/' . uniqid( 'wp-cli-test-suite-cache-' . self::$temp_dir_infix . '-', true ); mkdir( self::$suite_cache_dir ); return self::$suite_cache_dir; }
[ "public", "static", "function", "create_cache_dir", "(", ")", "{", "if", "(", "self", "::", "$", "suite_cache_dir", ")", "{", "self", "::", "remove_dir", "(", "self", "::", "$", "suite_cache_dir", ")", ";", "}", "self", "::", "$", "suite_cache_dir", "=", ...
Create a temporary WP_CLI_CACHE_DIR. Exposed as SUITE_CACHE_DIR in "Given an empty cache" step.
[ "Create", "a", "temporary", "WP_CLI_CACHE_DIR", ".", "Exposed", "as", "SUITE_CACHE_DIR", "in", "Given", "an", "empty", "cache", "step", "." ]
83b636fc7cb69ff257e025d1c855c190143a45db
https://github.com/wp-cli/wp-cli-tests/blob/83b636fc7cb69ff257e025d1c855c190143a45db/features/bootstrap/FeatureContext.php#L452-L459
train
guzzle/cache-subscriber
src/CacheStorage.php
CacheStorage.getCacheKey
private function getCacheKey(RequestInterface $request, array $vary = []) { $key = $request->getMethod() . ' ' . $request->getUrl(); // If Vary headers have been passed in, fetch each header and add it to // the cache key. foreach ($vary as $header) { $key .= " $header: " . $request->getHeader($header); } return $this->keyPrefix . md5($key); }
php
private function getCacheKey(RequestInterface $request, array $vary = []) { $key = $request->getMethod() . ' ' . $request->getUrl(); // If Vary headers have been passed in, fetch each header and add it to // the cache key. foreach ($vary as $header) { $key .= " $header: " . $request->getHeader($header); } return $this->keyPrefix . md5($key); }
[ "private", "function", "getCacheKey", "(", "RequestInterface", "$", "request", ",", "array", "$", "vary", "=", "[", "]", ")", "{", "$", "key", "=", "$", "request", "->", "getMethod", "(", ")", ".", "' '", ".", "$", "request", "->", "getUrl", "(", ")"...
Hash a request URL into a string that returns cache metadata. @param RequestInterface $request The Request to generate the cache key for. @param array $vary (optional) An array of headers to vary the cache key by. @return string
[ "Hash", "a", "request", "URL", "into", "a", "string", "that", "returns", "cache", "metadata", "." ]
1377567481d6d96224c9bd66aac475fbfbeec776
https://github.com/guzzle/cache-subscriber/blob/1377567481d6d96224c9bd66aac475fbfbeec776/src/CacheStorage.php#L192-L203
train
guzzle/cache-subscriber
src/CacheStorage.php
CacheStorage.getBodyKey
private function getBodyKey($url, StreamInterface $body) { return $this->keyPrefix . md5($url) . Stream\Utils::hash($body, 'md5'); }
php
private function getBodyKey($url, StreamInterface $body) { return $this->keyPrefix . md5($url) . Stream\Utils::hash($body, 'md5'); }
[ "private", "function", "getBodyKey", "(", "$", "url", ",", "StreamInterface", "$", "body", ")", "{", "return", "$", "this", "->", "keyPrefix", ".", "md5", "(", "$", "url", ")", ".", "Stream", "\\", "Utils", "::", "hash", "(", "$", "body", ",", "'md5'...
Create a cache key for a response's body. @param string $url URL of the entry @param StreamInterface $body Response body @return string
[ "Create", "a", "cache", "key", "for", "a", "response", "s", "body", "." ]
1377567481d6d96224c9bd66aac475fbfbeec776
https://github.com/guzzle/cache-subscriber/blob/1377567481d6d96224c9bd66aac475fbfbeec776/src/CacheStorage.php#L213-L216
train
guzzle/cache-subscriber
src/CacheStorage.php
CacheStorage.persistHeaders
private function persistHeaders(MessageInterface $message) { // Clone the response to not destroy any necessary headers when caching $headers = array_diff_key($message->getHeaders(), self::$noCache); // Cast the headers to a string foreach ($headers as &$value) { $value = implode(', ', $value); } return $headers; }
php
private function persistHeaders(MessageInterface $message) { // Clone the response to not destroy any necessary headers when caching $headers = array_diff_key($message->getHeaders(), self::$noCache); // Cast the headers to a string foreach ($headers as &$value) { $value = implode(', ', $value); } return $headers; }
[ "private", "function", "persistHeaders", "(", "MessageInterface", "$", "message", ")", "{", "// Clone the response to not destroy any necessary headers when caching", "$", "headers", "=", "array_diff_key", "(", "$", "message", "->", "getHeaders", "(", ")", ",", "self", ...
Creates an array of cacheable and normalized message headers. @param MessageInterface $message @return array
[ "Creates", "an", "array", "of", "cacheable", "and", "normalized", "message", "headers", "." ]
1377567481d6d96224c9bd66aac475fbfbeec776
https://github.com/guzzle/cache-subscriber/blob/1377567481d6d96224c9bd66aac475fbfbeec776/src/CacheStorage.php#L250-L261
train
guzzle/cache-subscriber
src/CacheStorage.php
CacheStorage.getTtl
private function getTtl(ResponseInterface $response) { $ttl = 0; if ($cacheControl = $response->getHeader('Cache-Control')) { $maxAge = Utils::getDirective($response, 'max-age'); if (is_numeric($maxAge)) { $ttl += $maxAge; } // According to RFC5861 stale headers are *in addition* to any // max-age values. $stale = Utils::getDirective($response, 'stale-if-error'); if (is_numeric($stale)) { $ttl += $stale; } } elseif ($expires = $response->getHeader('Expires')) { $ttl += strtotime($expires) - time(); } return $ttl ?: $this->defaultTtl; }
php
private function getTtl(ResponseInterface $response) { $ttl = 0; if ($cacheControl = $response->getHeader('Cache-Control')) { $maxAge = Utils::getDirective($response, 'max-age'); if (is_numeric($maxAge)) { $ttl += $maxAge; } // According to RFC5861 stale headers are *in addition* to any // max-age values. $stale = Utils::getDirective($response, 'stale-if-error'); if (is_numeric($stale)) { $ttl += $stale; } } elseif ($expires = $response->getHeader('Expires')) { $ttl += strtotime($expires) - time(); } return $ttl ?: $this->defaultTtl; }
[ "private", "function", "getTtl", "(", "ResponseInterface", "$", "response", ")", "{", "$", "ttl", "=", "0", ";", "if", "(", "$", "cacheControl", "=", "$", "response", "->", "getHeader", "(", "'Cache-Control'", ")", ")", "{", "$", "maxAge", "=", "Utils", ...
Return the TTL to use when caching a Response. @param ResponseInterface $response The response being cached. @return int The TTL in seconds.
[ "Return", "the", "TTL", "to", "use", "when", "caching", "a", "Response", "." ]
1377567481d6d96224c9bd66aac475fbfbeec776
https://github.com/guzzle/cache-subscriber/blob/1377567481d6d96224c9bd66aac475fbfbeec776/src/CacheStorage.php#L270-L291
train
guzzle/cache-subscriber
src/CacheStorage.php
CacheStorage.normalizeVary
private function normalizeVary(ResponseInterface $response) { $parts = AbstractMessage::normalizeHeader($response, 'vary'); sort($parts); return $parts; }
php
private function normalizeVary(ResponseInterface $response) { $parts = AbstractMessage::normalizeHeader($response, 'vary'); sort($parts); return $parts; }
[ "private", "function", "normalizeVary", "(", "ResponseInterface", "$", "response", ")", "{", "$", "parts", "=", "AbstractMessage", "::", "normalizeHeader", "(", "$", "response", ",", "'vary'", ")", ";", "sort", "(", "$", "parts", ")", ";", "return", "$", "...
Return a sorted list of Vary headers. While headers are case-insensitive, header values are not. We can only normalize the order of headers to combine cache entries. @param ResponseInterface $response The Response with Vary headers. @return array An array of sorted headers.
[ "Return", "a", "sorted", "list", "of", "Vary", "headers", "." ]
1377567481d6d96224c9bd66aac475fbfbeec776
https://github.com/guzzle/cache-subscriber/blob/1377567481d6d96224c9bd66aac475fbfbeec776/src/CacheStorage.php#L337-L343
train
guzzle/cache-subscriber
src/CacheStorage.php
CacheStorage.cacheVary
private function cacheVary( RequestInterface $request, ResponseInterface $response ) { $key = $this->getVaryKey($request); $this->cache->save($key, $this->normalizeVary($response), $this->getTtl($response)); }
php
private function cacheVary( RequestInterface $request, ResponseInterface $response ) { $key = $this->getVaryKey($request); $this->cache->save($key, $this->normalizeVary($response), $this->getTtl($response)); }
[ "private", "function", "cacheVary", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "key", "=", "$", "this", "->", "getVaryKey", "(", "$", "request", ")", ";", "$", "this", "->", "cache", "->", "save", "...
Cache the Vary headers from a response. @param RequestInterface $request The Request that generated the Vary headers. @param ResponseInterface $response The Response with Vary headers.
[ "Cache", "the", "Vary", "headers", "from", "a", "response", "." ]
1377567481d6d96224c9bd66aac475fbfbeec776
https://github.com/guzzle/cache-subscriber/blob/1377567481d6d96224c9bd66aac475fbfbeec776/src/CacheStorage.php#L352-L358
train
guzzle/cache-subscriber
src/CacheStorage.php
CacheStorage.fetchVary
private function fetchVary(RequestInterface $request) { $key = $this->getVaryKey($request); $varyHeaders = $this->cache->fetch($key); return is_array($varyHeaders) ? $varyHeaders : []; }
php
private function fetchVary(RequestInterface $request) { $key = $this->getVaryKey($request); $varyHeaders = $this->cache->fetch($key); return is_array($varyHeaders) ? $varyHeaders : []; }
[ "private", "function", "fetchVary", "(", "RequestInterface", "$", "request", ")", "{", "$", "key", "=", "$", "this", "->", "getVaryKey", "(", "$", "request", ")", ";", "$", "varyHeaders", "=", "$", "this", "->", "cache", "->", "fetch", "(", "$", "key",...
Fetch the Vary headers associated with a request, if they exist. Only responses, and not requests, contain Vary headers. However, we need to be able to determine what Vary headers were set for a given URL and request method on a future request. @param RequestInterface $request The Request to fetch headers for. @return array An array of headers.
[ "Fetch", "the", "Vary", "headers", "associated", "with", "a", "request", "if", "they", "exist", "." ]
1377567481d6d96224c9bd66aac475fbfbeec776
https://github.com/guzzle/cache-subscriber/blob/1377567481d6d96224c9bd66aac475fbfbeec776/src/CacheStorage.php#L371-L377
train