repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.lastOfQuarter
public function lastOfQuarter($dayOfWeek = null) { return $this->day(1)->month($this->quarter * ChronosInterface::MONTHS_PER_QUARTER)->lastOfMonth($dayOfWeek); }
php
public function lastOfQuarter($dayOfWeek = null) { return $this->day(1)->month($this->quarter * ChronosInterface::MONTHS_PER_QUARTER)->lastOfMonth($dayOfWeek); }
[ "public", "function", "lastOfQuarter", "(", "$", "dayOfWeek", "=", "null", ")", "{", "return", "$", "this", "->", "day", "(", "1", ")", "->", "month", "(", "$", "this", "->", "quarter", "*", "ChronosInterface", "::", "MONTHS_PER_QUARTER", ")", "->", "las...
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int|null $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "last", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "quarter", ".", "If", "no", "dayOfWeek", "is", "provided", "modify", "to", "the", "last", "day", "of", "the", "current", "quarter", ".", ...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L996-L999
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.nthOfQuarter
public function nthOfQuarter($nth, $dayOfWeek) { $dt = $this->copy()->day(1)->month($this->quarter * ChronosInterface::MONTHS_PER_QUARTER); $lastMonth = $dt->month; $year = $dt->year; $dt = $dt->firstOfQuarter()->modify("+$nth" . static::$days[$dayOfWeek]); return ($lastMonth < $dt->month || $year !== $dt->year) ? false : $dt; }
php
public function nthOfQuarter($nth, $dayOfWeek) { $dt = $this->copy()->day(1)->month($this->quarter * ChronosInterface::MONTHS_PER_QUARTER); $lastMonth = $dt->month; $year = $dt->year; $dt = $dt->firstOfQuarter()->modify("+$nth" . static::$days[$dayOfWeek]); return ($lastMonth < $dt->month || $year !== $dt->year) ? false : $dt; }
[ "public", "function", "nthOfQuarter", "(", "$", "nth", ",", "$", "dayOfWeek", ")", "{", "$", "dt", "=", "$", "this", "->", "copy", "(", ")", "->", "day", "(", "1", ")", "->", "month", "(", "$", "this", "->", "quarter", "*", "ChronosInterface", "::"...
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int $nth The offset to use. @param int $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "given", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "quarter", ".", "If", "the", "calculated", "occurrence", "is", "outside", "the", "scope", "of", "the", "current", "quarter", "then", "retu...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L1011-L1019
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.firstOfYear
public function firstOfYear($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("first $day of january, midnight"); }
php
public function firstOfYear($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("first $day of january, midnight"); }
[ "public", "function", "firstOfYear", "(", "$", "dayOfWeek", "=", "null", ")", "{", "$", "day", "=", "$", "dayOfWeek", "===", "null", "?", "'day'", ":", "static", "::", "$", "days", "[", "$", "dayOfWeek", "]", ";", "return", "$", "this", "->", "modify...
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int|null $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "first", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "year", ".", "If", "no", "dayOfWeek", "is", "provided", "modify", "to", "the", "first", "day", "of", "the", "current", "year", ".", "U...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L1030-L1035
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.lastOfYear
public function lastOfYear($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("last $day of december, midnight"); }
php
public function lastOfYear($dayOfWeek = null) { $day = $dayOfWeek === null ? 'day' : static::$days[$dayOfWeek]; return $this->modify("last $day of december, midnight"); }
[ "public", "function", "lastOfYear", "(", "$", "dayOfWeek", "=", "null", ")", "{", "$", "day", "=", "$", "dayOfWeek", "===", "null", "?", "'day'", ":", "static", "::", "$", "days", "[", "$", "dayOfWeek", "]", ";", "return", "$", "this", "->", "modify"...
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int|null $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "last", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "year", ".", "If", "no", "dayOfWeek", "is", "provided", "modify", "to", "the", "last", "day", "of", "the", "current", "year", ".", "Use...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L1046-L1051
cakephp/chronos
src/Traits/ModifierTrait.php
ModifierTrait.nthOfYear
public function nthOfYear($nth, $dayOfWeek) { $dt = $this->copy()->firstOfYear()->modify("+$nth " . static::$days[$dayOfWeek]); return $this->year === $dt->year ? $dt : false; }
php
public function nthOfYear($nth, $dayOfWeek) { $dt = $this->copy()->firstOfYear()->modify("+$nth " . static::$days[$dayOfWeek]); return $this->year === $dt->year ? $dt : false; }
[ "public", "function", "nthOfYear", "(", "$", "nth", ",", "$", "dayOfWeek", ")", "{", "$", "dt", "=", "$", "this", "->", "copy", "(", ")", "->", "firstOfYear", "(", ")", "->", "modify", "(", "\"+$nth \"", ".", "static", "::", "$", "days", "[", "$", ...
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. ChronosInterface::MONDAY. @param int $nth The offset to use. @param int $dayOfWeek The day of the week to move to. @return mixed
[ "Modify", "to", "the", "given", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "year", ".", "If", "the", "calculated", "occurrence", "is", "outside", "the", "scope", "of", "the", "current", "year", "then", "return", ...
train
https://github.com/cakephp/chronos/blob/7e14b9ed02ee756ba148e46b3851eb397dbc3f8f/src/Traits/ModifierTrait.php#L1063-L1068
guzzle/streams
src/LimitStream.php
LimitStream.setOffset
public function setOffset($offset) { $current = $this->stream->tell(); if ($current !== $offset) { // If the stream cannot seek to the offset position, then read to it if (!$this->stream->seek($offset)) { if ($current > $offset) { throw new SeekException($this, $offset); } else { $this->stream->read($offset - $current); } } } $this->offset = $offset; return $this; }
php
public function setOffset($offset) { $current = $this->stream->tell(); if ($current !== $offset) { // If the stream cannot seek to the offset position, then read to it if (!$this->stream->seek($offset)) { if ($current > $offset) { throw new SeekException($this, $offset); } else { $this->stream->read($offset - $current); } } } $this->offset = $offset; return $this; }
[ "public", "function", "setOffset", "(", "$", "offset", ")", "{", "$", "current", "=", "$", "this", "->", "stream", "->", "tell", "(", ")", ";", "if", "(", "$", "current", "!==", "$", "offset", ")", "{", "// If the stream cannot seek to the offset position, t...
Set the offset to start limiting from @param int $offset Offset to seek to and begin byte limiting from @return self @throws SeekException
[ "Set", "the", "offset", "to", "start", "limiting", "from" ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/LimitStream.php#L109-L127
guzzle/streams
src/Utils.php
Utils.open
public static function open($filename, $mode) { $ex = null; set_error_handler(function () use ($filename, $mode, &$ex) { $ex = new \RuntimeException(sprintf( 'Unable to open %s using mode %s: %s', $filename, $mode, func_get_args()[1] )); }); $handle = fopen($filename, $mode); restore_error_handler(); if ($ex) { /** @var $ex \RuntimeException */ throw $ex; } return $handle; }
php
public static function open($filename, $mode) { $ex = null; set_error_handler(function () use ($filename, $mode, &$ex) { $ex = new \RuntimeException(sprintf( 'Unable to open %s using mode %s: %s', $filename, $mode, func_get_args()[1] )); }); $handle = fopen($filename, $mode); restore_error_handler(); if ($ex) { /** @var $ex \RuntimeException */ throw $ex; } return $handle; }
[ "public", "static", "function", "open", "(", "$", "filename", ",", "$", "mode", ")", "{", "$", "ex", "=", "null", ";", "set_error_handler", "(", "function", "(", ")", "use", "(", "$", "filename", ",", "$", "mode", ",", "&", "$", "ex", ")", "{", "...
Safely opens a PHP stream resource using a filename. When fopen fails, PHP normally raises a warning. This function adds an error handler that checks for errors and throws an exception instead. @param string $filename File to open @param string $mode Mode used to open the file @return resource @throws \RuntimeException if the file cannot be opened
[ "Safely", "opens", "a", "PHP", "stream", "resource", "using", "a", "filename", "." ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/Utils.php#L24-L45
guzzle/streams
src/Utils.php
Utils.hash
public static function hash( StreamInterface $stream, $algo, $rawOutput = false ) { $pos = $stream->tell(); if ($pos > 0 && !$stream->seek(0)) { throw new SeekException($stream); } $ctx = hash_init($algo); while (!$stream->eof()) { hash_update($ctx, $stream->read(1048576)); } $out = hash_final($ctx, (bool) $rawOutput); $stream->seek($pos); return $out; }
php
public static function hash( StreamInterface $stream, $algo, $rawOutput = false ) { $pos = $stream->tell(); if ($pos > 0 && !$stream->seek(0)) { throw new SeekException($stream); } $ctx = hash_init($algo); while (!$stream->eof()) { hash_update($ctx, $stream->read(1048576)); } $out = hash_final($ctx, (bool) $rawOutput); $stream->seek($pos); return $out; }
[ "public", "static", "function", "hash", "(", "StreamInterface", "$", "stream", ",", "$", "algo", ",", "$", "rawOutput", "=", "false", ")", "{", "$", "pos", "=", "$", "stream", "->", "tell", "(", ")", ";", "if", "(", "$", "pos", ">", "0", "&&", "!...
Calculate a hash of a Stream @param StreamInterface $stream Stream to calculate the hash for @param string $algo Hash algorithm (e.g. md5, crc32, etc) @param bool $rawOutput Whether or not to use raw output @return string Returns the hash of the stream @throws SeekException
[ "Calculate", "a", "hash", "of", "a", "Stream" ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/Utils.php#L131-L151
guzzle/streams
src/Utils.php
Utils.readline
public static function readline(StreamInterface $stream, $maxLength = null, $eol = PHP_EOL) { $buffer = ''; $size = 0; $negEolLen = -strlen($eol); while (!$stream->eof()) { if (false === ($byte = $stream->read(1))) { return $buffer; } $buffer .= $byte; // Break when a new line is found or the max length - 1 is reached if (++$size == $maxLength || substr($buffer, $negEolLen) === $eol) { break; } } return $buffer; }
php
public static function readline(StreamInterface $stream, $maxLength = null, $eol = PHP_EOL) { $buffer = ''; $size = 0; $negEolLen = -strlen($eol); while (!$stream->eof()) { if (false === ($byte = $stream->read(1))) { return $buffer; } $buffer .= $byte; // Break when a new line is found or the max length - 1 is reached if (++$size == $maxLength || substr($buffer, $negEolLen) === $eol) { break; } } return $buffer; }
[ "public", "static", "function", "readline", "(", "StreamInterface", "$", "stream", ",", "$", "maxLength", "=", "null", ",", "$", "eol", "=", "PHP_EOL", ")", "{", "$", "buffer", "=", "''", ";", "$", "size", "=", "0", ";", "$", "negEolLen", "=", "-", ...
Read a line from the stream up to the maximum allowed buffer length @param StreamInterface $stream Stream to read from @param int $maxLength Maximum buffer length @param string $eol Line ending @return string|bool
[ "Read", "a", "line", "from", "the", "stream", "up", "to", "the", "maximum", "allowed", "buffer", "length" ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/Utils.php#L162-L180
guzzle/streams
src/AppendStream.php
AppendStream.close
public function close() { $this->pos = $this->current = 0; foreach ($this->streams as $stream) { $stream->close(); } $this->streams = []; }
php
public function close() { $this->pos = $this->current = 0; foreach ($this->streams as $stream) { $stream->close(); } $this->streams = []; }
[ "public", "function", "close", "(", ")", "{", "$", "this", "->", "pos", "=", "$", "this", "->", "current", "=", "0", ";", "foreach", "(", "$", "this", "->", "streams", "as", "$", "stream", ")", "{", "$", "stream", "->", "close", "(", ")", ";", ...
Closes each attached stream. {@inheritdoc}
[ "Closes", "each", "attached", "stream", "." ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/AppendStream.php#L73-L82
guzzle/streams
src/AppendStream.php
AppendStream.seek
public function seek($offset, $whence = SEEK_SET) { if (!$this->seekable || $whence !== SEEK_SET) { return false; } $success = true; $this->pos = $this->current = 0; // Rewind each stream foreach ($this->streams as $stream) { if (!$stream->seek(0)) { $success = false; } } if (!$success) { return false; } // Seek to the actual position by reading from each stream while ($this->pos < $offset && !$this->eof()) { $this->read(min(8096, $offset - $this->pos)); } return $this->pos == $offset; }
php
public function seek($offset, $whence = SEEK_SET) { if (!$this->seekable || $whence !== SEEK_SET) { return false; } $success = true; $this->pos = $this->current = 0; // Rewind each stream foreach ($this->streams as $stream) { if (!$stream->seek(0)) { $success = false; } } if (!$success) { return false; } // Seek to the actual position by reading from each stream while ($this->pos < $offset && !$this->eof()) { $this->read(min(8096, $offset - $this->pos)); } return $this->pos == $offset; }
[ "public", "function", "seek", "(", "$", "offset", ",", "$", "whence", "=", "SEEK_SET", ")", "{", "if", "(", "!", "$", "this", "->", "seekable", "||", "$", "whence", "!==", "SEEK_SET", ")", "{", "return", "false", ";", "}", "$", "success", "=", "tru...
Attempts to seek to the given position. Only supports SEEK_SET. {@inheritdoc}
[ "Attempts", "to", "seek", "to", "the", "given", "position", ".", "Only", "supports", "SEEK_SET", "." ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/AppendStream.php#L140-L166
guzzle/streams
src/AppendStream.php
AppendStream.read
public function read($length) { $buffer = ''; $total = count($this->streams) - 1; $remaining = $length; while ($remaining > 0) { // Progress to the next stream if needed. if ($this->streams[$this->current]->eof()) { if ($this->current == $total) { break; } $this->current++; } $buffer .= $this->streams[$this->current]->read($remaining); $remaining = $length - strlen($buffer); } $this->pos += strlen($buffer); return $buffer; }
php
public function read($length) { $buffer = ''; $total = count($this->streams) - 1; $remaining = $length; while ($remaining > 0) { // Progress to the next stream if needed. if ($this->streams[$this->current]->eof()) { if ($this->current == $total) { break; } $this->current++; } $buffer .= $this->streams[$this->current]->read($remaining); $remaining = $length - strlen($buffer); } $this->pos += strlen($buffer); return $buffer; }
[ "public", "function", "read", "(", "$", "length", ")", "{", "$", "buffer", "=", "''", ";", "$", "total", "=", "count", "(", "$", "this", "->", "streams", ")", "-", "1", ";", "$", "remaining", "=", "$", "length", ";", "while", "(", "$", "remaining...
Reads from all of the appended streams until the length is met or EOF. {@inheritdoc}
[ "Reads", "from", "all", "of", "the", "appended", "streams", "until", "the", "length", "is", "met", "or", "EOF", "." ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/AppendStream.php#L173-L194
guzzle/streams
src/BufferStream.php
BufferStream.write
public function write($string) { $this->buffer .= $string; if (strlen($this->buffer) >= $this->hwm) { return false; } return strlen($string); }
php
public function write($string) { $this->buffer .= $string; if (strlen($this->buffer) >= $this->hwm) { return false; } return strlen($string); }
[ "public", "function", "write", "(", "$", "string", ")", "{", "$", "this", "->", "buffer", ".=", "$", "string", ";", "if", "(", "strlen", "(", "$", "this", "->", "buffer", ")", ">=", "$", "this", "->", "hwm", ")", "{", "return", "false", ";", "}",...
Writes data to the buffer.
[ "Writes", "data", "to", "the", "buffer", "." ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/BufferStream.php#L119-L128
guzzle/streams
src/Stream.php
Stream.factory
public static function factory($resource = '', array $options = []) { $type = gettype($resource); if ($type == 'string') { $stream = fopen('php://temp', 'r+'); if ($resource !== '') { fwrite($stream, $resource); fseek($stream, 0); } return new self($stream, $options); } if ($type == 'resource') { return new self($resource, $options); } if ($resource instanceof StreamInterface) { return $resource; } if ($type == 'object' && method_exists($resource, '__toString')) { return self::factory((string) $resource, $options); } if (is_callable($resource)) { return new PumpStream($resource, $options); } if ($resource instanceof \Iterator) { return new PumpStream(function () use ($resource) { if (!$resource->valid()) { return false; } $result = $resource->current(); $resource->next(); return $result; }, $options); } throw new \InvalidArgumentException('Invalid resource type: ' . $type); }
php
public static function factory($resource = '', array $options = []) { $type = gettype($resource); if ($type == 'string') { $stream = fopen('php://temp', 'r+'); if ($resource !== '') { fwrite($stream, $resource); fseek($stream, 0); } return new self($stream, $options); } if ($type == 'resource') { return new self($resource, $options); } if ($resource instanceof StreamInterface) { return $resource; } if ($type == 'object' && method_exists($resource, '__toString')) { return self::factory((string) $resource, $options); } if (is_callable($resource)) { return new PumpStream($resource, $options); } if ($resource instanceof \Iterator) { return new PumpStream(function () use ($resource) { if (!$resource->valid()) { return false; } $result = $resource->current(); $resource->next(); return $result; }, $options); } throw new \InvalidArgumentException('Invalid resource type: ' . $type); }
[ "public", "static", "function", "factory", "(", "$", "resource", "=", "''", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "type", "=", "gettype", "(", "$", "resource", ")", ";", "if", "(", "$", "type", "==", "'string'", ")", "{", "$...
Create a new stream based on the input type. This factory accepts the same associative array of options as described in the constructor. @param resource|string|StreamInterface $resource Entity body data @param array $options Additional options @return Stream @throws \InvalidArgumentException if the $resource arg is not valid.
[ "Create", "a", "new", "stream", "based", "on", "the", "input", "type", "." ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/Stream.php#L45-L86
guzzle/streams
src/AsyncReadStream.php
AsyncReadStream.create
public static function create(array $options = []) { $maxBuffer = isset($options['max_buffer']) ? $options['max_buffer'] : null; if ($maxBuffer === 0) { $buffer = new NullStream(); } elseif (isset($options['buffer'])) { $buffer = $options['buffer']; } else { $hwm = isset($options['hwm']) ? $options['hwm'] : 16384; $buffer = new BufferStream($hwm); } if ($maxBuffer > 0) { $buffer = new DroppingStream($buffer, $options['max_buffer']); } // Call the on_write callback if an on_write function was provided. if (isset($options['write'])) { $onWrite = $options['write']; $buffer = FnStream::decorate($buffer, [ 'write' => function ($string) use ($buffer, $onWrite) { $result = $buffer->write($string); $onWrite($buffer, $string); return $result; } ]); } return [$buffer, new self($buffer, $options)]; }
php
public static function create(array $options = []) { $maxBuffer = isset($options['max_buffer']) ? $options['max_buffer'] : null; if ($maxBuffer === 0) { $buffer = new NullStream(); } elseif (isset($options['buffer'])) { $buffer = $options['buffer']; } else { $hwm = isset($options['hwm']) ? $options['hwm'] : 16384; $buffer = new BufferStream($hwm); } if ($maxBuffer > 0) { $buffer = new DroppingStream($buffer, $options['max_buffer']); } // Call the on_write callback if an on_write function was provided. if (isset($options['write'])) { $onWrite = $options['write']; $buffer = FnStream::decorate($buffer, [ 'write' => function ($string) use ($buffer, $onWrite) { $result = $buffer->write($string); $onWrite($buffer, $string); return $result; } ]); } return [$buffer, new self($buffer, $options)]; }
[ "public", "static", "function", "create", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "maxBuffer", "=", "isset", "(", "$", "options", "[", "'max_buffer'", "]", ")", "?", "$", "options", "[", "'max_buffer'", "]", ":", "null", ";", "if"...
Factory method used to create new async stream and an underlying buffer if no buffer is provided. This function accepts the same options as AsyncReadStream::__construct, but added the following key value pairs: - buffer: (StreamInterface) Buffer used to buffer data. If none is provided, a default buffer is created. - hwm: (int) High water mark to use if a buffer is created on your behalf. - max_buffer: (int) If provided, wraps the utilized buffer in a DroppingStream decorator to ensure that buffer does not exceed a given length. When exceeded, the stream will begin dropping data. Set the max_buffer to 0, to use a NullStream which does not store data. - write: (callable) A function that is invoked when data is written to the underlying buffer. The function accepts the buffer as the first argument, and the data being written as the second. The function MUST return the number of bytes that were written or false to let writers know to slow down. - drain: (callable) See constructor documentation. - pump: (callable) See constructor documentation. @param array $options Associative array of options. @return array Returns an array containing the buffer used to buffer data, followed by the ready to use AsyncReadStream object.
[ "Factory", "method", "used", "to", "create", "new", "async", "stream", "and", "an", "underlying", "buffer", "if", "no", "buffer", "is", "provided", "." ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/AsyncReadStream.php#L132-L164
guzzle/streams
src/CachingStream.php
CachingStream.seek
public function seek($offset, $whence = SEEK_SET) { if ($whence == SEEK_SET) { $byte = $offset; } elseif ($whence == SEEK_CUR) { $byte = $offset + $this->tell(); } else { return false; } // You cannot skip ahead past where you've read from the remote stream if ($byte > $this->stream->getSize()) { throw new SeekException( $this, $byte, sprintf('Cannot seek to byte %d when the buffered stream only' . ' contains %d bytes', $byte, $this->stream->getSize()) ); } return $this->stream->seek($byte); }
php
public function seek($offset, $whence = SEEK_SET) { if ($whence == SEEK_SET) { $byte = $offset; } elseif ($whence == SEEK_CUR) { $byte = $offset + $this->tell(); } else { return false; } // You cannot skip ahead past where you've read from the remote stream if ($byte > $this->stream->getSize()) { throw new SeekException( $this, $byte, sprintf('Cannot seek to byte %d when the buffered stream only' . ' contains %d bytes', $byte, $this->stream->getSize()) ); } return $this->stream->seek($byte); }
[ "public", "function", "seek", "(", "$", "offset", ",", "$", "whence", "=", "SEEK_SET", ")", "{", "if", "(", "$", "whence", "==", "SEEK_SET", ")", "{", "$", "byte", "=", "$", "offset", ";", "}", "elseif", "(", "$", "whence", "==", "SEEK_CUR", ")", ...
{@inheritdoc} @throws SeekException When seeking with SEEK_END or when seeking past the total size of the buffer stream
[ "{" ]
train
https://github.com/guzzle/streams/blob/d99a261c616210618ab94fd319cb17eda458cc3e/src/CachingStream.php#L44-L65
thephpleague/oauth1-client
src/Client/Signature/HmacSha1Signature.php
HmacSha1Signature.sign
public function sign($uri, array $parameters = array(), $method = 'POST') { $url = $this->createUrl($uri); $baseString = $this->baseString($url, $method, $parameters); return base64_encode($this->hash($baseString)); }
php
public function sign($uri, array $parameters = array(), $method = 'POST') { $url = $this->createUrl($uri); $baseString = $this->baseString($url, $method, $parameters); return base64_encode($this->hash($baseString)); }
[ "public", "function", "sign", "(", "$", "uri", ",", "array", "$", "parameters", "=", "array", "(", ")", ",", "$", "method", "=", "'POST'", ")", "{", "$", "url", "=", "$", "this", "->", "createUrl", "(", "$", "uri", ")", ";", "$", "baseString", "=...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Signature/HmacSha1Signature.php#L21-L28
thephpleague/oauth1-client
src/Client/Signature/HmacSha1Signature.php
HmacSha1Signature.baseString
protected function baseString(Uri $url, $method = 'POST', array $parameters = array()) { $baseString = rawurlencode($method).'&'; $schemeHostPath = Uri::fromParts(array( 'scheme' => $url->getScheme(), 'host' => $url->getHost(), 'path' => $url->getPath(), )); $baseString .= rawurlencode($schemeHostPath).'&'; $data = array(); parse_str($url->getQuery(), $query); $data = array_merge($query, $parameters); // normalize data key/values array_walk_recursive($data, function (&$key, &$value) { $key = rawurlencode(rawurldecode($key)); $value = rawurlencode(rawurldecode($value)); }); ksort($data); $baseString .= $this->queryStringFromData($data); return $baseString; }
php
protected function baseString(Uri $url, $method = 'POST', array $parameters = array()) { $baseString = rawurlencode($method).'&'; $schemeHostPath = Uri::fromParts(array( 'scheme' => $url->getScheme(), 'host' => $url->getHost(), 'path' => $url->getPath(), )); $baseString .= rawurlencode($schemeHostPath).'&'; $data = array(); parse_str($url->getQuery(), $query); $data = array_merge($query, $parameters); // normalize data key/values array_walk_recursive($data, function (&$key, &$value) { $key = rawurlencode(rawurldecode($key)); $value = rawurlencode(rawurldecode($value)); }); ksort($data); $baseString .= $this->queryStringFromData($data); return $baseString; }
[ "protected", "function", "baseString", "(", "Uri", "$", "url", ",", "$", "method", "=", "'POST'", ",", "array", "$", "parameters", "=", "array", "(", ")", ")", "{", "$", "baseString", "=", "rawurlencode", "(", "$", "method", ")", ".", "'&'", ";", "$"...
Generate a base string for a HMAC-SHA1 signature based on the given a url, method, and any parameters. @param Url $url @param string $method @param array $parameters @return string
[ "Generate", "a", "base", "string", "for", "a", "HMAC", "-", "SHA1", "signature", "based", "on", "the", "given", "a", "url", "method", "and", "any", "parameters", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Signature/HmacSha1Signature.php#L52-L78
thephpleague/oauth1-client
src/Client/Signature/HmacSha1Signature.php
HmacSha1Signature.queryStringFromData
protected function queryStringFromData($data, $queryParams = false, $prevKey = '') { if ($initial = (false === $queryParams)) { $queryParams = array(); } foreach ($data as $key => $value) { if ($prevKey) { $key = $prevKey.'['.$key.']'; // Handle multi-dimensional array } if (is_array($value)) { $queryParams = $this->queryStringFromData($value, $queryParams, $key); } else { $queryParams[] = rawurlencode($key.'='.$value); // join with equals sign } } if ($initial) { return implode('%26', $queryParams); // join with ampersand } return $queryParams; }
php
protected function queryStringFromData($data, $queryParams = false, $prevKey = '') { if ($initial = (false === $queryParams)) { $queryParams = array(); } foreach ($data as $key => $value) { if ($prevKey) { $key = $prevKey.'['.$key.']'; // Handle multi-dimensional array } if (is_array($value)) { $queryParams = $this->queryStringFromData($value, $queryParams, $key); } else { $queryParams[] = rawurlencode($key.'='.$value); // join with equals sign } } if ($initial) { return implode('%26', $queryParams); // join with ampersand } return $queryParams; }
[ "protected", "function", "queryStringFromData", "(", "$", "data", ",", "$", "queryParams", "=", "false", ",", "$", "prevKey", "=", "''", ")", "{", "if", "(", "$", "initial", "=", "(", "false", "===", "$", "queryParams", ")", ")", "{", "$", "queryParams...
Creates an array of rawurlencoded strings out of each array key/value pair Handles multi-demensional arrays recursively. @param array $data Array of parameters to convert. @param array $queryParams Array to extend. False by default. @param string $prevKey Optional Array key to append @return string rawurlencoded string version of data
[ "Creates", "an", "array", "of", "rawurlencoded", "strings", "out", "of", "each", "array", "key", "/", "value", "pair", "Handles", "multi", "-", "demensional", "arrays", "recursively", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Signature/HmacSha1Signature.php#L90-L112
thephpleague/oauth1-client
src/Client/Credentials/RsaClientCredentials.php
RsaClientCredentials.getRsaPublicKey
public function getRsaPublicKey() { if ($this->rsaPublicKey) { return $this->rsaPublicKey; } if (!file_exists($this->rsaPublicKeyFile)) { throw new CredentialsException('Could not read the public key file.'); } $this->rsaPublicKey = openssl_get_publickey(file_get_contents($this->rsaPublicKeyFile)); if (!$this->rsaPublicKey) { throw new CredentialsException('Cannot access public key for signing'); } return $this->rsaPublicKey; }
php
public function getRsaPublicKey() { if ($this->rsaPublicKey) { return $this->rsaPublicKey; } if (!file_exists($this->rsaPublicKeyFile)) { throw new CredentialsException('Could not read the public key file.'); } $this->rsaPublicKey = openssl_get_publickey(file_get_contents($this->rsaPublicKeyFile)); if (!$this->rsaPublicKey) { throw new CredentialsException('Cannot access public key for signing'); } return $this->rsaPublicKey; }
[ "public", "function", "getRsaPublicKey", "(", ")", "{", "if", "(", "$", "this", "->", "rsaPublicKey", ")", "{", "return", "$", "this", "->", "rsaPublicKey", ";", "}", "if", "(", "!", "file_exists", "(", "$", "this", "->", "rsaPublicKeyFile", ")", ")", ...
Gets the RSA public key. @throws CredentialsException when the key could not be loaded. @return resource
[ "Gets", "the", "RSA", "public", "key", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Credentials/RsaClientCredentials.php#L64-L81
thephpleague/oauth1-client
src/Client/Credentials/RsaClientCredentials.php
RsaClientCredentials.getRsaPrivateKey
public function getRsaPrivateKey() { if ($this->rsaPrivateKey) { return $this->rsaPrivateKey; } if (!file_exists($this->rsaPrivateKeyFile)) { throw new CredentialsException('Could not read the private key file.'); } $this->rsaPrivateKey = openssl_pkey_get_private(file_get_contents($this->rsaPrivateKeyFile)); if (!$this->rsaPrivateKey) { throw new CredentialsException('Cannot access private key for signing'); } return $this->rsaPrivateKey; }
php
public function getRsaPrivateKey() { if ($this->rsaPrivateKey) { return $this->rsaPrivateKey; } if (!file_exists($this->rsaPrivateKeyFile)) { throw new CredentialsException('Could not read the private key file.'); } $this->rsaPrivateKey = openssl_pkey_get_private(file_get_contents($this->rsaPrivateKeyFile)); if (!$this->rsaPrivateKey) { throw new CredentialsException('Cannot access private key for signing'); } return $this->rsaPrivateKey; }
[ "public", "function", "getRsaPrivateKey", "(", ")", "{", "if", "(", "$", "this", "->", "rsaPrivateKey", ")", "{", "return", "$", "this", "->", "rsaPrivateKey", ";", "}", "if", "(", "!", "file_exists", "(", "$", "this", "->", "rsaPrivateKeyFile", ")", ")"...
Gets the RSA private key. @throws CredentialsException when the key could not be loaded. @return resource
[ "Gets", "the", "RSA", "private", "key", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Credentials/RsaClientCredentials.php#L90-L107
thephpleague/oauth1-client
src/Client/Server/Magento.php
Magento.userDetails
public function userDetails($data, TokenCredentials $tokenCredentials) { if (!is_array($data) || !count($data)) { throw new \Exception('Not possible to get user info'); } $id = key($data); $data = current($data); $user = new User(); $user->uid = $id; $mapping = array( 'email' => 'email', 'firstName' => 'firstname', 'lastName' => 'lastname', ); foreach ($mapping as $userKey => $dataKey) { if (!isset($data[$dataKey])) { continue; } $user->{$userKey} = $data[$dataKey]; } $user->extra = array_diff_key($data, array_flip($mapping)); return $user; }
php
public function userDetails($data, TokenCredentials $tokenCredentials) { if (!is_array($data) || !count($data)) { throw new \Exception('Not possible to get user info'); } $id = key($data); $data = current($data); $user = new User(); $user->uid = $id; $mapping = array( 'email' => 'email', 'firstName' => 'firstname', 'lastName' => 'lastname', ); foreach ($mapping as $userKey => $dataKey) { if (!isset($data[$dataKey])) { continue; } $user->{$userKey} = $data[$dataKey]; } $user->extra = array_diff_key($data, array_flip($mapping)); return $user; }
[ "public", "function", "userDetails", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", "||", "!", "count", "(", "$", "data", ")", ")", "{", "throw", "new", "\\", "Exception"...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Magento.php#L98-L125
thephpleague/oauth1-client
src/Client/Server/Magento.php
Magento.userEmail
public function userEmail($data, TokenCredentials $tokenCredentials) { $data = current($data); if (!isset($data['email'])) { return; } return $data['email']; }
php
public function userEmail($data, TokenCredentials $tokenCredentials) { $data = current($data); if (!isset($data['email'])) { return; } return $data['email']; }
[ "public", "function", "userEmail", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "$", "data", "=", "current", "(", "$", "data", ")", ";", "if", "(", "!", "isset", "(", "$", "data", "[", "'email'", "]", ")", ")", "{", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Magento.php#L138-L145
thephpleague/oauth1-client
src/Client/Server/Magento.php
Magento.getTokenCredentials
public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier) { $this->verifier = $verifier; return parent::getTokenCredentials($temporaryCredentials, $temporaryIdentifier, $verifier); }
php
public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier) { $this->verifier = $verifier; return parent::getTokenCredentials($temporaryCredentials, $temporaryIdentifier, $verifier); }
[ "public", "function", "getTokenCredentials", "(", "TemporaryCredentials", "$", "temporaryCredentials", ",", "$", "temporaryIdentifier", ",", "$", "verifier", ")", "{", "$", "this", "->", "verifier", "=", "$", "verifier", ";", "return", "parent", "::", "getTokenCre...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Magento.php#L158-L163
thephpleague/oauth1-client
src/Client/Server/Magento.php
Magento.parseConfigurationArray
private function parseConfigurationArray(array $configuration = array()) { if (!isset($configuration['host'])) { throw new \Exception('Missing Magento Host'); } $url = parse_url($configuration['host']); $this->baseUri = sprintf('%s://%s', $url['scheme'], $url['host']); if (isset($url['port'])) { $this->baseUri .= ':'.$url['port']; } if (isset($url['path'])) { $this->baseUri .= '/'.trim($url['path'], '/'); } $this->isAdmin = !empty($configuration['admin']); if (!empty($configuration['adminUrl'])) { $this->adminUrl = $configuration['adminUrl'].'/oauth_authorize'; } else { $this->adminUrl = $this->baseUri.'/admin/oauth_authorize'; } }
php
private function parseConfigurationArray(array $configuration = array()) { if (!isset($configuration['host'])) { throw new \Exception('Missing Magento Host'); } $url = parse_url($configuration['host']); $this->baseUri = sprintf('%s://%s', $url['scheme'], $url['host']); if (isset($url['port'])) { $this->baseUri .= ':'.$url['port']; } if (isset($url['path'])) { $this->baseUri .= '/'.trim($url['path'], '/'); } $this->isAdmin = !empty($configuration['admin']); if (!empty($configuration['adminUrl'])) { $this->adminUrl = $configuration['adminUrl'].'/oauth_authorize'; } else { $this->adminUrl = $this->baseUri.'/admin/oauth_authorize'; } }
[ "private", "function", "parseConfigurationArray", "(", "array", "$", "configuration", "=", "array", "(", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "configuration", "[", "'host'", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Missi...
Parse configuration array to set attributes. @param array $configuration @throws \Exception
[ "Parse", "configuration", "array", "to", "set", "attributes", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Magento.php#L190-L211
thephpleague/oauth1-client
src/Client/Signature/Signature.php
Signature.key
protected function key() { $key = rawurlencode($this->clientCredentials->getSecret()).'&'; if ($this->credentials !== null) { $key .= rawurlencode($this->credentials->getSecret()); } return $key; }
php
protected function key() { $key = rawurlencode($this->clientCredentials->getSecret()).'&'; if ($this->credentials !== null) { $key .= rawurlencode($this->credentials->getSecret()); } return $key; }
[ "protected", "function", "key", "(", ")", "{", "$", "key", "=", "rawurlencode", "(", "$", "this", "->", "clientCredentials", "->", "getSecret", "(", ")", ")", ".", "'&'", ";", "if", "(", "$", "this", "->", "credentials", "!==", "null", ")", "{", "$",...
Generate a signing key. @return string
[ "Generate", "a", "signing", "key", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Signature/Signature.php#L45-L54
thephpleague/oauth1-client
src/Client/Server/Tumblr.php
Tumblr.userDetails
public function userDetails($data, TokenCredentials $tokenCredentials) { // If the API has broke, return nothing if (!isset($data['response']['user']) || !is_array($data['response']['user'])) { return; } $data = $data['response']['user']; $user = new User(); $user->nickname = $data['name']; // Save all extra data $used = array('name'); $user->extra = array_diff_key($data, array_flip($used)); return $user; }
php
public function userDetails($data, TokenCredentials $tokenCredentials) { // If the API has broke, return nothing if (!isset($data['response']['user']) || !is_array($data['response']['user'])) { return; } $data = $data['response']['user']; $user = new User(); $user->nickname = $data['name']; // Save all extra data $used = array('name'); $user->extra = array_diff_key($data, array_flip($used)); return $user; }
[ "public", "function", "userDetails", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "// If the API has broke, return nothing", "if", "(", "!", "isset", "(", "$", "data", "[", "'response'", "]", "[", "'user'", "]", ")", "||", "!",...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Tumblr.php#L44-L62
thephpleague/oauth1-client
src/Client/Server/Tumblr.php
Tumblr.userUid
public function userUid($data, TokenCredentials $tokenCredentials) { if (!isset($data['response']['user']) || !is_array($data['response']['user'])) { return; } $data = $data['response']['user']; return $data['name']; }
php
public function userUid($data, TokenCredentials $tokenCredentials) { if (!isset($data['response']['user']) || !is_array($data['response']['user'])) { return; } $data = $data['response']['user']; return $data['name']; }
[ "public", "function", "userUid", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'response'", "]", "[", "'user'", "]", ")", "||", "!", "is_array", "(", "$", "data", "[", "...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Tumblr.php#L67-L76
thephpleague/oauth1-client
src/Client/Server/Tumblr.php
Tumblr.userScreenName
public function userScreenName($data, TokenCredentials $tokenCredentials) { if (!isset($data['response']['user']) || !is_array($data['response']['user'])) { return; } $data = $data['response']['user']; return $data['name']; }
php
public function userScreenName($data, TokenCredentials $tokenCredentials) { if (!isset($data['response']['user']) || !is_array($data['response']['user'])) { return; } $data = $data['response']['user']; return $data['name']; }
[ "public", "function", "userScreenName", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'response'", "]", "[", "'user'", "]", ")", "||", "!", "is_array", "(", "$", "data", "...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Tumblr.php#L89-L98
thephpleague/oauth1-client
src/Client/Server/Twitter.php
Twitter.userDetails
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->uid = $data['id_str']; $user->nickname = $data['screen_name']; $user->name = $data['name']; $user->location = $data['location']; $user->description = $data['description']; $user->imageUrl = $data['profile_image_url']; $user->email = null; if (isset($data['email'])) { $user->email = $data['email']; } $used = array('id', 'screen_name', 'name', 'location', 'description', 'profile_image_url', 'email'); foreach ($data as $key => $value) { if (strpos($key, 'url') !== false) { if (!in_array($key, $used)) { $used[] = $key; } $user->urls[$key] = $value; } } // Save all extra data $user->extra = array_diff_key($data, array_flip($used)); return $user; }
php
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->uid = $data['id_str']; $user->nickname = $data['screen_name']; $user->name = $data['name']; $user->location = $data['location']; $user->description = $data['description']; $user->imageUrl = $data['profile_image_url']; $user->email = null; if (isset($data['email'])) { $user->email = $data['email']; } $used = array('id', 'screen_name', 'name', 'location', 'description', 'profile_image_url', 'email'); foreach ($data as $key => $value) { if (strpos($key, 'url') !== false) { if (!in_array($key, $used)) { $used[] = $key; } $user->urls[$key] = $value; } } // Save all extra data $user->extra = array_diff_key($data, array_flip($used)); return $user; }
[ "public", "function", "userDetails", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "$", "user", "=", "new", "User", "(", ")", ";", "$", "user", "->", "uid", "=", "$", "data", "[", "'id_str'", "]", ";", "$", "user", "->...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Twitter.php#L44-L75
thephpleague/oauth1-client
src/Client/Signature/RsaSha1Signature.php
RsaSha1Signature.sign
public function sign($uri, array $parameters = array(), $method = 'POST') { $url = $this->createUrl($uri); $baseString = $this->baseString($url, $method, $parameters); $privateKey = $this->clientCredentials->getRsaPrivateKey(); openssl_sign($baseString, $signature, $privateKey); return base64_encode($signature); }
php
public function sign($uri, array $parameters = array(), $method = 'POST') { $url = $this->createUrl($uri); $baseString = $this->baseString($url, $method, $parameters); $privateKey = $this->clientCredentials->getRsaPrivateKey(); openssl_sign($baseString, $signature, $privateKey); return base64_encode($signature); }
[ "public", "function", "sign", "(", "$", "uri", ",", "array", "$", "parameters", "=", "array", "(", ")", ",", "$", "method", "=", "'POST'", ")", "{", "$", "url", "=", "$", "this", "->", "createUrl", "(", "$", "uri", ")", ";", "$", "baseString", "=...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Signature/RsaSha1Signature.php#L23-L33
thephpleague/oauth1-client
src/Client/Server/Uservoice.php
Uservoice.userDetails
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->uid = $data['user']['id']; $user->name = $data['user']['name']; $user->imageUrl = $data['user']['avatar_url']; $user->email = $data['user']['email']; if ($data['user']['name']) { $parts = explode(' ', $data['user']['name']); if (count($parts) > 0) { $user->firstName = $parts[0]; } if (count($parts) > 1) { $user->lastName = $parts[1]; } } $user->urls[] = $data['user']['url']; return $user; }
php
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->uid = $data['user']['id']; $user->name = $data['user']['name']; $user->imageUrl = $data['user']['avatar_url']; $user->email = $data['user']['email']; if ($data['user']['name']) { $parts = explode(' ', $data['user']['name']); if (count($parts) > 0) { $user->firstName = $parts[0]; } if (count($parts) > 1) { $user->lastName = $parts[1]; } } $user->urls[] = $data['user']['url']; return $user; }
[ "public", "function", "userDetails", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "$", "user", "=", "new", "User", "(", ")", ";", "$", "user", "->", "uid", "=", "$", "data", "[", "'user'", "]", "[", "'id'", "]", ";", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Uservoice.php#L65-L89
thephpleague/oauth1-client
src/Client/Server/Bitbucket.php
Bitbucket.userDetails
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->uid = $data['user']['username']; $user->nickname = $data['user']['username']; $user->name = $data['user']['display_name']; $user->firstName = $data['user']['first_name']; $user->lastName = $data['user']['last_name']; $user->imageUrl = $data['user']['avatar']; $used = array('username', 'display_name', 'avatar'); foreach ($data as $key => $value) { if (strpos($key, 'url') !== false) { if (!in_array($key, $used)) { $used[] = $key; } $user->urls[$key] = $value; } } // Save all extra data $user->extra = array_diff_key($data, array_flip($used)); return $user; }
php
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->uid = $data['user']['username']; $user->nickname = $data['user']['username']; $user->name = $data['user']['display_name']; $user->firstName = $data['user']['first_name']; $user->lastName = $data['user']['last_name']; $user->imageUrl = $data['user']['avatar']; $used = array('username', 'display_name', 'avatar'); foreach ($data as $key => $value) { if (strpos($key, 'url') !== false) { if (!in_array($key, $used)) { $used[] = $key; } $user->urls[$key] = $value; } } // Save all extra data $user->extra = array_diff_key($data, array_flip($used)); return $user; }
[ "public", "function", "userDetails", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "$", "user", "=", "new", "User", "(", ")", ";", "$", "user", "->", "uid", "=", "$", "data", "[", "'user'", "]", "[", "'username'", "]", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Bitbucket.php#L44-L71
thephpleague/oauth1-client
src/Client/Server/Xing.php
Xing.userDetails
public function userDetails($data, TokenCredentials $tokenCredentials) { if (!isset($data['users'][0])) { throw new \Exception('Not possible to get user info'); } $data = $data['users'][0]; $user = new User(); $user->uid = $data['id']; $user->nickname = $data['display_name']; $user->name = $data['display_name']; $user->firstName = $data['first_name']; $user->lastName = $data['last_name']; $user->location = $data['private_address']['country']; if ($user->location == '') { $user->location = $data['business_address']['country']; } $user->description = $data['employment_status']; $user->imageUrl = $data['photo_urls']['maxi_thumb']; $user->email = $data['active_email']; $user->urls['permalink'] = $data['permalink']; return $user; }
php
public function userDetails($data, TokenCredentials $tokenCredentials) { if (!isset($data['users'][0])) { throw new \Exception('Not possible to get user info'); } $data = $data['users'][0]; $user = new User(); $user->uid = $data['id']; $user->nickname = $data['display_name']; $user->name = $data['display_name']; $user->firstName = $data['first_name']; $user->lastName = $data['last_name']; $user->location = $data['private_address']['country']; if ($user->location == '') { $user->location = $data['business_address']['country']; } $user->description = $data['employment_status']; $user->imageUrl = $data['photo_urls']['maxi_thumb']; $user->email = $data['active_email']; $user->urls['permalink'] = $data['permalink']; return $user; }
[ "public", "function", "userDetails", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'users'", "]", "[", "0", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Xing.php#L42-L67
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.getTemporaryCredentials
public function getTemporaryCredentials() { $uri = $this->urlTemporaryCredentials(); $client = $this->createHttpClient(); $header = $this->temporaryCredentialsProtocolHeader($uri); $authorizationHeader = array('Authorization' => $header); $headers = $this->buildHttpClientHeaders($authorizationHeader); try { $response = $client->post($uri, [ 'headers' => $headers, ]); } catch (BadResponseException $e) { return $this->handleTemporaryCredentialsBadResponse($e); } return $this->createTemporaryCredentials((string) $response->getBody()); }
php
public function getTemporaryCredentials() { $uri = $this->urlTemporaryCredentials(); $client = $this->createHttpClient(); $header = $this->temporaryCredentialsProtocolHeader($uri); $authorizationHeader = array('Authorization' => $header); $headers = $this->buildHttpClientHeaders($authorizationHeader); try { $response = $client->post($uri, [ 'headers' => $headers, ]); } catch (BadResponseException $e) { return $this->handleTemporaryCredentialsBadResponse($e); } return $this->createTemporaryCredentials((string) $response->getBody()); }
[ "public", "function", "getTemporaryCredentials", "(", ")", "{", "$", "uri", "=", "$", "this", "->", "urlTemporaryCredentials", "(", ")", ";", "$", "client", "=", "$", "this", "->", "createHttpClient", "(", ")", ";", "$", "header", "=", "$", "this", "->",...
Gets temporary credentials by performing a request to the server. @return TemporaryCredentials
[ "Gets", "temporary", "credentials", "by", "performing", "a", "request", "to", "the", "server", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L84-L103
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.getAuthorizationUrl
public function getAuthorizationUrl($temporaryIdentifier) { // Somebody can pass through an instance of temporary // credentials and we'll extract the identifier from there. if ($temporaryIdentifier instanceof TemporaryCredentials) { $temporaryIdentifier = $temporaryIdentifier->getIdentifier(); } $parameters = array('oauth_token' => $temporaryIdentifier); $url = $this->urlAuthorization(); $queryString = http_build_query($parameters); return $this->buildUrl($url, $queryString); }
php
public function getAuthorizationUrl($temporaryIdentifier) { // Somebody can pass through an instance of temporary // credentials and we'll extract the identifier from there. if ($temporaryIdentifier instanceof TemporaryCredentials) { $temporaryIdentifier = $temporaryIdentifier->getIdentifier(); } $parameters = array('oauth_token' => $temporaryIdentifier); $url = $this->urlAuthorization(); $queryString = http_build_query($parameters); return $this->buildUrl($url, $queryString); }
[ "public", "function", "getAuthorizationUrl", "(", "$", "temporaryIdentifier", ")", "{", "// Somebody can pass through an instance of temporary", "// credentials and we'll extract the identifier from there.", "if", "(", "$", "temporaryIdentifier", "instanceof", "TemporaryCredentials", ...
Get the authorization URL by passing in the temporary credentials identifier or an object instance. @param TemporaryCredentials|string $temporaryIdentifier @return string
[ "Get", "the", "authorization", "URL", "by", "passing", "in", "the", "temporary", "credentials", "identifier", "or", "an", "object", "instance", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L113-L127
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.getUserDetails
public function getUserDetails(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userDetails($data, $tokenCredentials); }
php
public function getUserDetails(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userDetails($data, $tokenCredentials); }
[ "public", "function", "getUserDetails", "(", "TokenCredentials", "$", "tokenCredentials", ",", "$", "force", "=", "false", ")", "{", "$", "data", "=", "$", "this", "->", "fetchUserDetails", "(", "$", "tokenCredentials", ",", "$", "force", ")", ";", "return",...
Get user details by providing valid token credentials. @param TokenCredentials $tokenCredentials @param bool $force @return \League\OAuth1\Client\Server\User
[ "Get", "user", "details", "by", "providing", "valid", "token", "credentials", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L190-L195
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.getUserUid
public function getUserUid(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userUid($data, $tokenCredentials); }
php
public function getUserUid(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userUid($data, $tokenCredentials); }
[ "public", "function", "getUserUid", "(", "TokenCredentials", "$", "tokenCredentials", ",", "$", "force", "=", "false", ")", "{", "$", "data", "=", "$", "this", "->", "fetchUserDetails", "(", "$", "tokenCredentials", ",", "$", "force", ")", ";", "return", "...
Get the user's unique identifier (primary key). @param TokenCredentials $tokenCredentials @param bool $force @return string|int
[ "Get", "the", "user", "s", "unique", "identifier", "(", "primary", "key", ")", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L205-L210
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.getUserEmail
public function getUserEmail(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userEmail($data, $tokenCredentials); }
php
public function getUserEmail(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userEmail($data, $tokenCredentials); }
[ "public", "function", "getUserEmail", "(", "TokenCredentials", "$", "tokenCredentials", ",", "$", "force", "=", "false", ")", "{", "$", "data", "=", "$", "this", "->", "fetchUserDetails", "(", "$", "tokenCredentials", ",", "$", "force", ")", ";", "return", ...
Get the user's email, if available. @param TokenCredentials $tokenCredentials @param bool $force @return string|null
[ "Get", "the", "user", "s", "email", "if", "available", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L220-L225
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.getUserScreenName
public function getUserScreenName(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userScreenName($data, $tokenCredentials); }
php
public function getUserScreenName(TokenCredentials $tokenCredentials, $force = false) { $data = $this->fetchUserDetails($tokenCredentials, $force); return $this->userScreenName($data, $tokenCredentials); }
[ "public", "function", "getUserScreenName", "(", "TokenCredentials", "$", "tokenCredentials", ",", "$", "force", "=", "false", ")", "{", "$", "data", "=", "$", "this", "->", "fetchUserDetails", "(", "$", "tokenCredentials", ",", "$", "force", ")", ";", "retur...
Get the user's screen name (username), if available. @param TokenCredentials $tokenCredentials @param bool $force @return string
[ "Get", "the", "user", "s", "screen", "name", "(", "username", ")", "if", "available", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L235-L240
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.fetchUserDetails
protected function fetchUserDetails(TokenCredentials $tokenCredentials, $force = true) { if (!$this->cachedUserDetailsResponse || $force) { $url = $this->urlUserDetails(); $client = $this->createHttpClient(); $headers = $this->getHeaders($tokenCredentials, 'GET', $url); try { $response = $client->get($url, [ 'headers' => $headers, ]); } catch (BadResponseException $e) { $response = $e->getResponse(); $body = $response->getBody(); $statusCode = $response->getStatusCode(); throw new \Exception( "Received error [$body] with status code [$statusCode] when retrieving token credentials." ); } switch ($this->responseType) { case 'json': $this->cachedUserDetailsResponse = json_decode((string) $response->getBody(), true); break; case 'xml': $this->cachedUserDetailsResponse = simplexml_load_string((string) $response->getBody()); break; case 'string': parse_str((string) $response->getBody(), $this->cachedUserDetailsResponse); break; default: throw new \InvalidArgumentException("Invalid response type [{$this->responseType}]."); } } return $this->cachedUserDetailsResponse; }
php
protected function fetchUserDetails(TokenCredentials $tokenCredentials, $force = true) { if (!$this->cachedUserDetailsResponse || $force) { $url = $this->urlUserDetails(); $client = $this->createHttpClient(); $headers = $this->getHeaders($tokenCredentials, 'GET', $url); try { $response = $client->get($url, [ 'headers' => $headers, ]); } catch (BadResponseException $e) { $response = $e->getResponse(); $body = $response->getBody(); $statusCode = $response->getStatusCode(); throw new \Exception( "Received error [$body] with status code [$statusCode] when retrieving token credentials." ); } switch ($this->responseType) { case 'json': $this->cachedUserDetailsResponse = json_decode((string) $response->getBody(), true); break; case 'xml': $this->cachedUserDetailsResponse = simplexml_load_string((string) $response->getBody()); break; case 'string': parse_str((string) $response->getBody(), $this->cachedUserDetailsResponse); break; default: throw new \InvalidArgumentException("Invalid response type [{$this->responseType}]."); } } return $this->cachedUserDetailsResponse; }
[ "protected", "function", "fetchUserDetails", "(", "TokenCredentials", "$", "tokenCredentials", ",", "$", "force", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "cachedUserDetailsResponse", "||", "$", "force", ")", "{", "$", "url", "=", "$", "th...
Fetch user details from the remote service. @param TokenCredentials $tokenCredentials @param bool $force @return array HTTP client response
[ "Fetch", "user", "details", "from", "the", "remote", "service", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L250-L291
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.getHeaders
public function getHeaders(CredentialsInterface $credentials, $method, $url, array $bodyParameters = array()) { $header = $this->protocolHeader(strtoupper($method), $url, $credentials, $bodyParameters); $authorizationHeader = array('Authorization' => $header); $headers = $this->buildHttpClientHeaders($authorizationHeader); return $headers; }
php
public function getHeaders(CredentialsInterface $credentials, $method, $url, array $bodyParameters = array()) { $header = $this->protocolHeader(strtoupper($method), $url, $credentials, $bodyParameters); $authorizationHeader = array('Authorization' => $header); $headers = $this->buildHttpClientHeaders($authorizationHeader); return $headers; }
[ "public", "function", "getHeaders", "(", "CredentialsInterface", "$", "credentials", ",", "$", "method", ",", "$", "url", ",", "array", "$", "bodyParameters", "=", "array", "(", ")", ")", "{", "$", "header", "=", "$", "this", "->", "protocolHeader", "(", ...
Get all headers required to created an authenticated request. @param CredentialsInterface $credentials @param string $method @param string $url @param array $bodyParameters @return array
[ "Get", "all", "headers", "required", "to", "created", "an", "authenticated", "request", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L347-L354
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.createClientCredentials
protected function createClientCredentials(array $clientCredentials) { $keys = array('identifier', 'secret'); foreach ($keys as $key) { if (!isset($clientCredentials[$key])) { throw new \InvalidArgumentException("Missing client credentials key [$key] from options."); } } if (isset($clientCredentials['rsa_private_key']) && isset($clientCredentials['rsa_public_key'])) { $_clientCredentials = new RsaClientCredentials(); $_clientCredentials->setRsaPrivateKey($clientCredentials['rsa_private_key']); $_clientCredentials->setRsaPublicKey($clientCredentials['rsa_public_key']); } else { $_clientCredentials = new ClientCredentials(); } $_clientCredentials->setIdentifier($clientCredentials['identifier']); $_clientCredentials->setSecret($clientCredentials['secret']); if (isset($clientCredentials['callback_uri'])) { $_clientCredentials->setCallbackUri($clientCredentials['callback_uri']); } return $_clientCredentials; }
php
protected function createClientCredentials(array $clientCredentials) { $keys = array('identifier', 'secret'); foreach ($keys as $key) { if (!isset($clientCredentials[$key])) { throw new \InvalidArgumentException("Missing client credentials key [$key] from options."); } } if (isset($clientCredentials['rsa_private_key']) && isset($clientCredentials['rsa_public_key'])) { $_clientCredentials = new RsaClientCredentials(); $_clientCredentials->setRsaPrivateKey($clientCredentials['rsa_private_key']); $_clientCredentials->setRsaPublicKey($clientCredentials['rsa_public_key']); } else { $_clientCredentials = new ClientCredentials(); } $_clientCredentials->setIdentifier($clientCredentials['identifier']); $_clientCredentials->setSecret($clientCredentials['secret']); if (isset($clientCredentials['callback_uri'])) { $_clientCredentials->setCallbackUri($clientCredentials['callback_uri']); } return $_clientCredentials; }
[ "protected", "function", "createClientCredentials", "(", "array", "$", "clientCredentials", ")", "{", "$", "keys", "=", "array", "(", "'identifier'", ",", "'secret'", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "!", "iss...
Creates a client credentials instance from an array of credentials. @param array $clientCredentials @return ClientCredentials
[ "Creates", "a", "client", "credentials", "instance", "from", "an", "array", "of", "credentials", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L390-L416
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.handleTemporaryCredentialsBadResponse
protected function handleTemporaryCredentialsBadResponse(BadResponseException $e) { $response = $e->getResponse(); $body = $response->getBody(); $statusCode = $response->getStatusCode(); throw new CredentialsException( "Received HTTP status code [$statusCode] with message \"$body\" when getting temporary credentials." ); }
php
protected function handleTemporaryCredentialsBadResponse(BadResponseException $e) { $response = $e->getResponse(); $body = $response->getBody(); $statusCode = $response->getStatusCode(); throw new CredentialsException( "Received HTTP status code [$statusCode] with message \"$body\" when getting temporary credentials." ); }
[ "protected", "function", "handleTemporaryCredentialsBadResponse", "(", "BadResponseException", "$", "e", ")", "{", "$", "response", "=", "$", "e", "->", "getResponse", "(", ")", ";", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "$", "...
Handle a bad response coming back when getting temporary credentials. @param BadResponseException $e @throws CredentialsException
[ "Handle", "a", "bad", "response", "coming", "back", "when", "getting", "temporary", "credentials", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L425-L434
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.createTemporaryCredentials
protected function createTemporaryCredentials($body) { parse_str($body, $data); if (!$data || !is_array($data)) { throw new CredentialsException('Unable to parse temporary credentials response.'); } if (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] != 'true') { throw new CredentialsException('Error in retrieving temporary credentials.'); } $temporaryCredentials = new TemporaryCredentials(); $temporaryCredentials->setIdentifier($data['oauth_token']); $temporaryCredentials->setSecret($data['oauth_token_secret']); return $temporaryCredentials; }
php
protected function createTemporaryCredentials($body) { parse_str($body, $data); if (!$data || !is_array($data)) { throw new CredentialsException('Unable to parse temporary credentials response.'); } if (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] != 'true') { throw new CredentialsException('Error in retrieving temporary credentials.'); } $temporaryCredentials = new TemporaryCredentials(); $temporaryCredentials->setIdentifier($data['oauth_token']); $temporaryCredentials->setSecret($data['oauth_token_secret']); return $temporaryCredentials; }
[ "protected", "function", "createTemporaryCredentials", "(", "$", "body", ")", "{", "parse_str", "(", "$", "body", ",", "$", "data", ")", ";", "if", "(", "!", "$", "data", "||", "!", "is_array", "(", "$", "data", ")", ")", "{", "throw", "new", "Creden...
Creates temporary credentials from the body response. @param string $body @return TemporaryCredentials
[ "Creates", "temporary", "credentials", "from", "the", "body", "response", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L443-L460
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.createTokenCredentials
protected function createTokenCredentials($body) { parse_str($body, $data); if (!$data || !is_array($data)) { throw new CredentialsException('Unable to parse token credentials response.'); } if (isset($data['error'])) { throw new CredentialsException("Error [{$data['error']}] in retrieving token credentials."); } $tokenCredentials = new TokenCredentials(); $tokenCredentials->setIdentifier($data['oauth_token']); $tokenCredentials->setSecret($data['oauth_token_secret']); return $tokenCredentials; }
php
protected function createTokenCredentials($body) { parse_str($body, $data); if (!$data || !is_array($data)) { throw new CredentialsException('Unable to parse token credentials response.'); } if (isset($data['error'])) { throw new CredentialsException("Error [{$data['error']}] in retrieving token credentials."); } $tokenCredentials = new TokenCredentials(); $tokenCredentials->setIdentifier($data['oauth_token']); $tokenCredentials->setSecret($data['oauth_token_secret']); return $tokenCredentials; }
[ "protected", "function", "createTokenCredentials", "(", "$", "body", ")", "{", "parse_str", "(", "$", "body", ",", "$", "data", ")", ";", "if", "(", "!", "$", "data", "||", "!", "is_array", "(", "$", "data", ")", ")", "{", "throw", "new", "Credential...
Creates token credentials from the body response. @param string $body @return TokenCredentials
[ "Creates", "token", "credentials", "from", "the", "body", "response", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L487-L504
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.baseProtocolParameters
protected function baseProtocolParameters() { $dateTime = new \DateTime(); return array( 'oauth_consumer_key' => $this->clientCredentials->getIdentifier(), 'oauth_nonce' => $this->nonce(), 'oauth_signature_method' => $this->signature->method(), 'oauth_timestamp' => $dateTime->format('U'), 'oauth_version' => '1.0', ); }
php
protected function baseProtocolParameters() { $dateTime = new \DateTime(); return array( 'oauth_consumer_key' => $this->clientCredentials->getIdentifier(), 'oauth_nonce' => $this->nonce(), 'oauth_signature_method' => $this->signature->method(), 'oauth_timestamp' => $dateTime->format('U'), 'oauth_version' => '1.0', ); }
[ "protected", "function", "baseProtocolParameters", "(", ")", "{", "$", "dateTime", "=", "new", "\\", "DateTime", "(", ")", ";", "return", "array", "(", "'oauth_consumer_key'", "=>", "$", "this", "->", "clientCredentials", "->", "getIdentifier", "(", ")", ",", ...
Get the base protocol parameters for an OAuth request. Each request builds on these parameters. @return array @see OAuth 1.0 RFC 5849 Section 3.1
[ "Get", "the", "base", "protocol", "parameters", "for", "an", "OAuth", "request", ".", "Each", "request", "builds", "on", "these", "parameters", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L514-L525
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.temporaryCredentialsProtocolHeader
protected function temporaryCredentialsProtocolHeader($uri) { $parameters = array_merge($this->baseProtocolParameters(), array( 'oauth_callback' => $this->clientCredentials->getCallbackUri(), )); $parameters['oauth_signature'] = $this->signature->sign($uri, $parameters, 'POST'); return $this->normalizeProtocolParameters($parameters); }
php
protected function temporaryCredentialsProtocolHeader($uri) { $parameters = array_merge($this->baseProtocolParameters(), array( 'oauth_callback' => $this->clientCredentials->getCallbackUri(), )); $parameters['oauth_signature'] = $this->signature->sign($uri, $parameters, 'POST'); return $this->normalizeProtocolParameters($parameters); }
[ "protected", "function", "temporaryCredentialsProtocolHeader", "(", "$", "uri", ")", "{", "$", "parameters", "=", "array_merge", "(", "$", "this", "->", "baseProtocolParameters", "(", ")", ",", "array", "(", "'oauth_callback'", "=>", "$", "this", "->", "clientCr...
Generate the OAuth protocol header for a temporary credentials request, based on the URI. @param string $uri @return string
[ "Generate", "the", "OAuth", "protocol", "header", "for", "a", "temporary", "credentials", "request", "based", "on", "the", "URI", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L546-L555
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.protocolHeader
protected function protocolHeader($method, $uri, CredentialsInterface $credentials, array $bodyParameters = array()) { $parameters = array_merge( $this->baseProtocolParameters(), $this->additionalProtocolParameters(), array( 'oauth_token' => $credentials->getIdentifier(), ) ); $this->signature->setCredentials($credentials); $parameters['oauth_signature'] = $this->signature->sign( $uri, array_merge($parameters, $bodyParameters), $method ); return $this->normalizeProtocolParameters($parameters); }
php
protected function protocolHeader($method, $uri, CredentialsInterface $credentials, array $bodyParameters = array()) { $parameters = array_merge( $this->baseProtocolParameters(), $this->additionalProtocolParameters(), array( 'oauth_token' => $credentials->getIdentifier(), ) ); $this->signature->setCredentials($credentials); $parameters['oauth_signature'] = $this->signature->sign( $uri, array_merge($parameters, $bodyParameters), $method ); return $this->normalizeProtocolParameters($parameters); }
[ "protected", "function", "protocolHeader", "(", "$", "method", ",", "$", "uri", ",", "CredentialsInterface", "$", "credentials", ",", "array", "$", "bodyParameters", "=", "array", "(", ")", ")", "{", "$", "parameters", "=", "array_merge", "(", "$", "this", ...
Generate the OAuth protocol header for requests other than temporary credentials, based on the URI, method, given credentials & body query string. @param string $method @param string $uri @param CredentialsInterface $credentials @param array $bodyParameters @return string
[ "Generate", "the", "OAuth", "protocol", "header", "for", "requests", "other", "than", "temporary", "credentials", "based", "on", "the", "URI", "method", "given", "credentials", "&", "body", "query", "string", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L569-L588
thephpleague/oauth1-client
src/Client/Server/Server.php
Server.normalizeProtocolParameters
protected function normalizeProtocolParameters(array $parameters) { array_walk($parameters, function (&$value, $key) { $value = rawurlencode($key).'="'.rawurlencode($value).'"'; }); return 'OAuth '.implode(', ', $parameters); }
php
protected function normalizeProtocolParameters(array $parameters) { array_walk($parameters, function (&$value, $key) { $value = rawurlencode($key).'="'.rawurlencode($value).'"'; }); return 'OAuth '.implode(', ', $parameters); }
[ "protected", "function", "normalizeProtocolParameters", "(", "array", "$", "parameters", ")", "{", "array_walk", "(", "$", "parameters", ",", "function", "(", "&", "$", "value", ",", "$", "key", ")", "{", "$", "value", "=", "rawurlencode", "(", "$", "key",...
Takes an array of protocol parameters and normalizes them to be used as a HTTP header. @param array $parameters @return string
[ "Takes", "an", "array", "of", "protocol", "parameters", "and", "normalizes", "them", "to", "be", "used", "as", "a", "HTTP", "header", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Server.php#L598-L605
thephpleague/oauth1-client
src/Client/Server/Trello.php
Trello.userDetails
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->nickname = $data['username']; $user->name = $data['fullName']; $user->imageUrl = null; $user->extra = (array) $data; return $user; }
php
public function userDetails($data, TokenCredentials $tokenCredentials) { $user = new User(); $user->nickname = $data['username']; $user->name = $data['fullName']; $user->imageUrl = null; $user->extra = (array) $data; return $user; }
[ "public", "function", "userDetails", "(", "$", "data", ",", "TokenCredentials", "$", "tokenCredentials", ")", "{", "$", "user", "=", "new", "User", "(", ")", ";", "$", "user", "->", "nickname", "=", "$", "data", "[", "'username'", "]", ";", "$", "user"...
{@inheritDoc}
[ "{" ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Trello.php#L178-L189
thephpleague/oauth1-client
src/Client/Server/Trello.php
Trello.buildAuthorizationQueryParameters
private function buildAuthorizationQueryParameters() { $params = array( 'response_type' => 'fragment', 'scope' => $this->getApplicationScope(), 'expiration' => $this->getApplicationExpiration(), 'name' => $this->getApplicationName(), ); return http_build_query($params); }
php
private function buildAuthorizationQueryParameters() { $params = array( 'response_type' => 'fragment', 'scope' => $this->getApplicationScope(), 'expiration' => $this->getApplicationExpiration(), 'name' => $this->getApplicationName(), ); return http_build_query($params); }
[ "private", "function", "buildAuthorizationQueryParameters", "(", ")", "{", "$", "params", "=", "array", "(", "'response_type'", "=>", "'fragment'", ",", "'scope'", "=>", "$", "this", "->", "getApplicationScope", "(", ")", ",", "'expiration'", "=>", "$", "this", ...
Build authorization query parameters. @return string
[ "Build", "authorization", "query", "parameters", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Trello.php#L220-L230
thephpleague/oauth1-client
src/Client/Server/Trello.php
Trello.parseConfiguration
private function parseConfiguration(array $configuration = array()) { $configToPropertyMap = array( 'identifier' => 'applicationKey', 'expiration' => 'applicationExpiration', 'name' => 'applicationName', 'scope' => 'applicationScope', ); foreach ($configToPropertyMap as $config => $property) { if (isset($configuration[$config])) { $this->$property = $configuration[$config]; } } }
php
private function parseConfiguration(array $configuration = array()) { $configToPropertyMap = array( 'identifier' => 'applicationKey', 'expiration' => 'applicationExpiration', 'name' => 'applicationName', 'scope' => 'applicationScope', ); foreach ($configToPropertyMap as $config => $property) { if (isset($configuration[$config])) { $this->$property = $configuration[$config]; } } }
[ "private", "function", "parseConfiguration", "(", "array", "$", "configuration", "=", "array", "(", ")", ")", "{", "$", "configToPropertyMap", "=", "array", "(", "'identifier'", "=>", "'applicationKey'", ",", "'expiration'", "=>", "'applicationExpiration'", ",", "...
Parse configuration array to set attributes. @param array $configuration
[ "Parse", "configuration", "array", "to", "set", "attributes", "." ]
train
https://github.com/thephpleague/oauth1-client/blob/7523d2aedceabe8ee2d9ab56cd1ff5ec67fbc676/src/Client/Server/Trello.php#L237-L251
doctrine/reflection
lib/Doctrine/Common/Reflection/Psr0FindFile.php
Psr0FindFile.findFile
public function findFile($class) { if ($class[0] === '\\') { $class = substr($class, 1); } $lastNsPos = strrpos($class, '\\'); if ($lastNsPos !== false) { // namespaced class name $classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $lastNsPos)) . DIRECTORY_SEPARATOR; $className = substr($class, $lastNsPos + 1); } else { // PEAR-like class name $classPath = null; $className = $class; } $classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; foreach ($this->prefixes as $prefix => $dirs) { if (strpos($class, $prefix) !== 0) { continue; } foreach ($dirs as $dir) { if (is_file($dir . DIRECTORY_SEPARATOR . $classPath)) { return $dir . DIRECTORY_SEPARATOR . $classPath; } } } return null; }
php
public function findFile($class) { if ($class[0] === '\\') { $class = substr($class, 1); } $lastNsPos = strrpos($class, '\\'); if ($lastNsPos !== false) { // namespaced class name $classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $lastNsPos)) . DIRECTORY_SEPARATOR; $className = substr($class, $lastNsPos + 1); } else { // PEAR-like class name $classPath = null; $className = $class; } $classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; foreach ($this->prefixes as $prefix => $dirs) { if (strpos($class, $prefix) !== 0) { continue; } foreach ($dirs as $dir) { if (is_file($dir . DIRECTORY_SEPARATOR . $classPath)) { return $dir . DIRECTORY_SEPARATOR . $classPath; } } } return null; }
[ "public", "function", "findFile", "(", "$", "class", ")", "{", "if", "(", "$", "class", "[", "0", "]", "===", "'\\\\'", ")", "{", "$", "class", "=", "substr", "(", "$", "class", ",", "1", ")", ";", "}", "$", "lastNsPos", "=", "strrpos", "(", "$...
{@inheritDoc}
[ "{" ]
train
https://github.com/doctrine/reflection/blob/4a97a22032919548b932482f36172ae3ea976632/lib/Doctrine/Common/Reflection/Psr0FindFile.php#L36-L69
doctrine/reflection
lib/Doctrine/Common/Reflection/StaticReflectionParser.php
StaticReflectionParser.getDocComment
public function getDocComment($type = 'class', $name = '') { $this->parse(); return $name ? $this->docComment[$type][$name] : $this->docComment[$type]; }
php
public function getDocComment($type = 'class', $name = '') { $this->parse(); return $name ? $this->docComment[$type][$name] : $this->docComment[$type]; }
[ "public", "function", "getDocComment", "(", "$", "type", "=", "'class'", ",", "$", "name", "=", "''", ")", "{", "$", "this", "->", "parse", "(", ")", ";", "return", "$", "name", "?", "$", "this", "->", "docComment", "[", "$", "type", "]", "[", "$...
Gets the doc comment. @param string $type The type: 'class', 'property' or 'method'. @param string $name The name of the property or method, not needed for 'class'. @return string The doc comment, empty string if none.
[ "Gets", "the", "doc", "comment", "." ]
train
https://github.com/doctrine/reflection/blob/4a97a22032919548b932482f36172ae3ea976632/lib/Doctrine/Common/Reflection/StaticReflectionParser.php#L300-L305
doctrine/reflection
lib/Doctrine/Common/Reflection/StaticReflectionParser.php
StaticReflectionParser.getStaticReflectionParserForDeclaringClass
public function getStaticReflectionParserForDeclaringClass($type, $name) { $this->parse(); if (isset($this->docComment[$type][$name])) { return $this; } if (! empty($this->parentClassName)) { return $this->getParentStaticReflectionParser()->getStaticReflectionParserForDeclaringClass($type, $name); } throw new ReflectionException('Invalid ' . $type . ' "' . $name . '"'); }
php
public function getStaticReflectionParserForDeclaringClass($type, $name) { $this->parse(); if (isset($this->docComment[$type][$name])) { return $this; } if (! empty($this->parentClassName)) { return $this->getParentStaticReflectionParser()->getStaticReflectionParserForDeclaringClass($type, $name); } throw new ReflectionException('Invalid ' . $type . ' "' . $name . '"'); }
[ "public", "function", "getStaticReflectionParserForDeclaringClass", "(", "$", "type", ",", "$", "name", ")", "{", "$", "this", "->", "parse", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "docComment", "[", "$", "type", "]", "[", "$", "nam...
Gets the PSR-0 parser for the declaring class. @param string $type The type: 'property' or 'method'. @param string $name The name of the property or method. @return StaticReflectionParser A static reflection parser for the declaring class. @throws ReflectionException
[ "Gets", "the", "PSR", "-", "0", "parser", "for", "the", "declaring", "class", "." ]
train
https://github.com/doctrine/reflection/blob/4a97a22032919548b932482f36172ae3ea976632/lib/Doctrine/Common/Reflection/StaticReflectionParser.php#L317-L327
doctrine/reflection
lib/Doctrine/Common/Reflection/RuntimePublicReflectionProperty.php
RuntimePublicReflectionProperty.getValue
public function getValue($object = null) { $name = $this->getName(); if ($object instanceof Proxy && ! $object->__isInitialized()) { $originalInitializer = $object->__getInitializer(); $object->__setInitializer(null); $val = $object->$name ?? null; $object->__setInitializer($originalInitializer); return $val; } return isset($object->$name) ? parent::getValue($object) : null; }
php
public function getValue($object = null) { $name = $this->getName(); if ($object instanceof Proxy && ! $object->__isInitialized()) { $originalInitializer = $object->__getInitializer(); $object->__setInitializer(null); $val = $object->$name ?? null; $object->__setInitializer($originalInitializer); return $val; } return isset($object->$name) ? parent::getValue($object) : null; }
[ "public", "function", "getValue", "(", "$", "object", "=", "null", ")", "{", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "$", "object", "instanceof", "Proxy", "&&", "!", "$", "object", "->", "__isInitialized", "(", ")", ...
{@inheritDoc} Checks is the value actually exist before fetching it. This is to avoid calling `__get` on the provided $object if it is a {@see \Doctrine\Common\Proxy\Proxy}.
[ "{", "@inheritDoc", "}" ]
train
https://github.com/doctrine/reflection/blob/4a97a22032919548b932482f36172ae3ea976632/lib/Doctrine/Common/Reflection/RuntimePublicReflectionProperty.php#L20-L34
doctrine/reflection
lib/Doctrine/Common/Reflection/RuntimePublicReflectionProperty.php
RuntimePublicReflectionProperty.setValue
public function setValue($object, $value = null) { if (! ($object instanceof Proxy && ! $object->__isInitialized())) { parent::setValue($object, $value); return; } $originalInitializer = $object->__getInitializer(); $object->__setInitializer(null); parent::setValue($object, $value); $object->__setInitializer($originalInitializer); }
php
public function setValue($object, $value = null) { if (! ($object instanceof Proxy && ! $object->__isInitialized())) { parent::setValue($object, $value); return; } $originalInitializer = $object->__getInitializer(); $object->__setInitializer(null); parent::setValue($object, $value); $object->__setInitializer($originalInitializer); }
[ "public", "function", "setValue", "(", "$", "object", ",", "$", "value", "=", "null", ")", "{", "if", "(", "!", "(", "$", "object", "instanceof", "Proxy", "&&", "!", "$", "object", "->", "__isInitialized", "(", ")", ")", ")", "{", "parent", "::", "...
{@inheritDoc} Avoids triggering lazy loading via `__set` if the provided object is a {@see \Doctrine\Common\Proxy\Proxy}. @link https://bugs.php.net/bug.php?id=63463
[ "{", "@inheritDoc", "}" ]
train
https://github.com/doctrine/reflection/blob/4a97a22032919548b932482f36172ae3ea976632/lib/Doctrine/Common/Reflection/RuntimePublicReflectionProperty.php#L44-L56
getsentry/sentry-symfony
src/ErrorTypesParser.php
ErrorTypesParser.parse
public function parse(): int { // convert constants to ints $this->expression = $this->convertErrorConstants($this->expression); $this->expression = str_replace( [',', ' '], ['.', ''], $this->expression ); return $this->compute($this->expression); }
php
public function parse(): int { // convert constants to ints $this->expression = $this->convertErrorConstants($this->expression); $this->expression = str_replace( [',', ' '], ['.', ''], $this->expression ); return $this->compute($this->expression); }
[ "public", "function", "parse", "(", ")", ":", "int", "{", "// convert constants to ints", "$", "this", "->", "expression", "=", "$", "this", "->", "convertErrorConstants", "(", "$", "this", "->", "expression", ")", ";", "$", "this", "->", "expression", "=", ...
Parse and compute the error types expression @return int the parsed expression @throws \InvalidArgumentException
[ "Parse", "and", "compute", "the", "error", "types", "expression" ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/ErrorTypesParser.php#L29-L40
getsentry/sentry-symfony
src/ErrorTypesParser.php
ErrorTypesParser.convertErrorConstants
private function convertErrorConstants(string $expression): string { $output = preg_replace_callback('/(E_[a-zA-Z_]+)/', function ($errorConstant) { if (defined($errorConstant[1])) { return constant($errorConstant[1]); } return $errorConstant[0]; }, $expression); if (null === $output) { throw new \InvalidArgumentException('Unable to parse error types string: ' . $expression); } return $output; }
php
private function convertErrorConstants(string $expression): string { $output = preg_replace_callback('/(E_[a-zA-Z_]+)/', function ($errorConstant) { if (defined($errorConstant[1])) { return constant($errorConstant[1]); } return $errorConstant[0]; }, $expression); if (null === $output) { throw new \InvalidArgumentException('Unable to parse error types string: ' . $expression); } return $output; }
[ "private", "function", "convertErrorConstants", "(", "string", "$", "expression", ")", ":", "string", "{", "$", "output", "=", "preg_replace_callback", "(", "'/(E_[a-zA-Z_]+)/'", ",", "function", "(", "$", "errorConstant", ")", "{", "if", "(", "defined", "(", ...
Converts error constants from string to int. @param string $expression e.g. E_ALL & ~E_DEPRECATED & ~E_NOTICE @return string converted expression e.g. 32767 & ~8192 & ~8
[ "Converts", "error", "constants", "from", "string", "to", "int", "." ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/ErrorTypesParser.php#L48-L63
getsentry/sentry-symfony
src/ErrorTypesParser.php
ErrorTypesParser.compute
private function compute(string $expression): int { // catch anything which could be a security issue if (0 !== preg_match("/[^\d.+*%^|&~<>\/()-]/", $this->expression)) { throw new \InvalidArgumentException('Wrong value in error types config value:' . $this->expression); } return 0 + (int)eval('return ' . $expression . ';'); }
php
private function compute(string $expression): int { // catch anything which could be a security issue if (0 !== preg_match("/[^\d.+*%^|&~<>\/()-]/", $this->expression)) { throw new \InvalidArgumentException('Wrong value in error types config value:' . $this->expression); } return 0 + (int)eval('return ' . $expression . ';'); }
[ "private", "function", "compute", "(", "string", "$", "expression", ")", ":", "int", "{", "// catch anything which could be a security issue", "if", "(", "0", "!==", "preg_match", "(", "\"/[^\\d.+*%^|&~<>\\/()-]/\"", ",", "$", "this", "->", "expression", ")", ")", ...
Let PHP compute the prepared expression for us. @param string $expression prepared expression e.g. 32767&~8192&~8 @return int computed expression e.g. 24567 @throws \InvalidArgumentException
[ "Let", "PHP", "compute", "the", "prepared", "expression", "for", "us", "." ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/ErrorTypesParser.php#L72-L80
getsentry/sentry-symfony
examples/symfony-3/var/SymfonyRequirements.php
SymfonyRequirements.getRealpathCacheSize
protected function getRealpathCacheSize() { $size = ini_get('realpath_cache_size'); $size = trim($size); $unit = strtolower(substr($size, -1, 1)); switch ($unit) { case 'g': return $size * 1024 * 1024 * 1024; case 'm': return $size * 1024 * 1024; case 'k': return $size * 1024; default: return (int) $size; } }
php
protected function getRealpathCacheSize() { $size = ini_get('realpath_cache_size'); $size = trim($size); $unit = strtolower(substr($size, -1, 1)); switch ($unit) { case 'g': return $size * 1024 * 1024 * 1024; case 'm': return $size * 1024 * 1024; case 'k': return $size * 1024; default: return (int) $size; } }
[ "protected", "function", "getRealpathCacheSize", "(", ")", "{", "$", "size", "=", "ini_get", "(", "'realpath_cache_size'", ")", ";", "$", "size", "=", "trim", "(", "$", "size", ")", ";", "$", "unit", "=", "strtolower", "(", "substr", "(", "$", "size", ...
Loads realpath_cache_size from php.ini and converts it to int. (e.g. 16k is converted to 16384 int) @return int
[ "Loads", "realpath_cache_size", "from", "php", ".", "ini", "and", "converts", "it", "to", "int", "." ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/examples/symfony-3/var/SymfonyRequirements.php#L758-L773
getsentry/sentry-symfony
src/DependencyInjection/SentryExtension.php
SentryExtension.load
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $processedConfiguration = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.xml'); $this->passConfigurationToOptions($container, $processedConfiguration); $container->getDefinition(ClientBuilderInterface::class) ->setConfigurator([ClientBuilderConfigurator::class, 'configure']); foreach ($processedConfiguration['listener_priorities'] as $key => $priority) { $container->setParameter('sentry.listener_priorities.' . $key, $priority); } $this->tagConsoleErrorListener($container); }
php
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $processedConfiguration = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.xml'); $this->passConfigurationToOptions($container, $processedConfiguration); $container->getDefinition(ClientBuilderInterface::class) ->setConfigurator([ClientBuilderConfigurator::class, 'configure']); foreach ($processedConfiguration['listener_priorities'] as $key => $priority) { $container->setParameter('sentry.listener_priorities.' . $key, $priority); } $this->tagConsoleErrorListener($container); }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "processedConfiguration", "=", "$", "this", "->", "processConfiguration", "(...
{@inheritDoc} @throws InvalidConfigurationException
[ "{", "@inheritDoc", "}" ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/DependencyInjection/SentryExtension.php#L30-L47
getsentry/sentry-symfony
src/DependencyInjection/SentryExtension.php
SentryExtension.tagConsoleErrorListener
private function tagConsoleErrorListener(ContainerBuilder $container): void { $listener = $container->getDefinition(ErrorListener::class); if (class_exists('Symfony\Component\Console\Event\ConsoleErrorEvent')) { $tagAttributes = [ 'event' => ConsoleEvents::ERROR, 'method' => 'onConsoleError', 'priority' => '%sentry.listener_priorities.console_error%', ]; } else { $tagAttributes = [ 'event' => ConsoleEvents::EXCEPTION, 'method' => 'onConsoleException', 'priority' => '%sentry.listener_priorities.console_error%', ]; } $listener->addTag('kernel.event_listener', $tagAttributes); }
php
private function tagConsoleErrorListener(ContainerBuilder $container): void { $listener = $container->getDefinition(ErrorListener::class); if (class_exists('Symfony\Component\Console\Event\ConsoleErrorEvent')) { $tagAttributes = [ 'event' => ConsoleEvents::ERROR, 'method' => 'onConsoleError', 'priority' => '%sentry.listener_priorities.console_error%', ]; } else { $tagAttributes = [ 'event' => ConsoleEvents::EXCEPTION, 'method' => 'onConsoleException', 'priority' => '%sentry.listener_priorities.console_error%', ]; } $listener->addTag('kernel.event_listener', $tagAttributes); }
[ "private", "function", "tagConsoleErrorListener", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "listener", "=", "$", "container", "->", "getDefinition", "(", "ErrorListener", "::", "class", ")", ";", "if", "(", "class_exists", "(", "'...
BC layer for Symfony < 3.3; see https://symfony.com/blog/new-in-symfony-3-3-better-handling-of-command-exceptions
[ "BC", "layer", "for", "Symfony", "<", "3", ".", "3", ";", "see", "https", ":", "//", "symfony", ".", "com", "/", "blog", "/", "new", "-", "in", "-", "symfony", "-", "3", "-", "3", "-", "better", "-", "handling", "-", "of", "-", "command", "-", ...
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/DependencyInjection/SentryExtension.php#L130-L149
getsentry/sentry-symfony
src/EventListener/RequestListener.php
RequestListener.onKernelRequest
public function onKernelRequest(GetResponseEvent $event): void { if (! $event->isMasterRequest()) { return; } $currentClient = Hub::getCurrent()->getClient(); if (null === $currentClient || ! $currentClient->getOptions()->shouldSendDefaultPii()) { return; } $token = null; if ($this->tokenStorage instanceof TokenStorageInterface) { $token = $this->tokenStorage->getToken(); } if ( null !== $token && null !== $this->authorizationChecker && $token->isAuthenticated() && $this->authorizationChecker->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED) ) { $userData = $this->getUserData($token->getUser()); } $userData['ip_address'] = $event->getRequest()->getClientIp(); Hub::getCurrent() ->configureScope(function (Scope $scope) use ($userData): void { $scope->setUser($userData); }); }
php
public function onKernelRequest(GetResponseEvent $event): void { if (! $event->isMasterRequest()) { return; } $currentClient = Hub::getCurrent()->getClient(); if (null === $currentClient || ! $currentClient->getOptions()->shouldSendDefaultPii()) { return; } $token = null; if ($this->tokenStorage instanceof TokenStorageInterface) { $token = $this->tokenStorage->getToken(); } if ( null !== $token && null !== $this->authorizationChecker && $token->isAuthenticated() && $this->authorizationChecker->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED) ) { $userData = $this->getUserData($token->getUser()); } $userData['ip_address'] = $event->getRequest()->getClientIp(); Hub::getCurrent() ->configureScope(function (Scope $scope) use ($userData): void { $scope->setUser($userData); }); }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", ":", "void", "{", "if", "(", "!", "$", "event", "->", "isMasterRequest", "(", ")", ")", "{", "return", ";", "}", "$", "currentClient", "=", "Hub", "::", "getCurrent", "(...
Set the username from the security context by listening on core.request @param GetResponseEvent $event
[ "Set", "the", "username", "from", "the", "security", "context", "by", "listening", "on", "core", ".", "request" ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/EventListener/RequestListener.php#L51-L83
getsentry/sentry-symfony
src/DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('sentry'); /** @var ArrayNodeDefinition $rootNode */ $rootNode = \method_exists(TreeBuilder::class, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('sentry'); // Basic Sentry configuration $rootNode->children() ->scalarNode('dsn') ->defaultNull() ->beforeNormalization() ->ifString() ->then($this->getTrimClosure()); // Options array (to be passed to Sentry\Options constructor) -- please keep alphabetical order! $optionsNode = $rootNode->children() ->arrayNode('options') ->addDefaultsIfNotSet(); $defaultValues = new Options(); $optionsChildNodes = $optionsNode->children(); $optionsChildNodes->booleanNode('attach_stacktrace'); $optionsChildNodes->variableNode('before_breadcrumb') ->validate() ->ifTrue($this->isNotAValidCallback()) ->thenInvalid('Expecting callable or service reference, got %s'); $optionsChildNodes->variableNode('before_send') ->validate() ->ifTrue($this->isNotAValidCallback()) ->thenInvalid('Expecting callable or service reference, got %s'); if (PrettyVersions::getVersion('sentry/sentry')->getPrettyVersion() !== '2.0.0') { $optionsChildNodes->booleanNode('capture_silenced_errors'); } $optionsChildNodes->integerNode('context_lines') ->min(0) ->max(99); $optionsChildNodes->booleanNode('default_integrations'); $optionsChildNodes->booleanNode('enable_compression'); $optionsChildNodes->scalarNode('environment') ->defaultValue('%kernel.environment%') ->cannotBeEmpty(); $optionsChildNodes->scalarNode('error_types'); $optionsChildNodes->arrayNode('in_app_exclude') ->defaultValue([ '%kernel.cache_dir%', $this->getProjectRoot() . '/vendor', ]) ->prototype('scalar'); $optionsChildNodes->arrayNode('excluded_exceptions') ->defaultValue($defaultValues->getExcludedExceptions()) ->prototype('scalar'); $optionsChildNodes->scalarNode('http_proxy'); $optionsChildNodes->arrayNode('integrations') ->prototype('scalar') ->validate() ->ifTrue(function ($value): bool { if (! is_string($value)) { return true; } return '@' !== substr($value, 0, 1); }) ->thenInvalid('Expecting service reference, got %s'); $optionsChildNodes->scalarNode('logger'); $optionsChildNodes->integerNode('max_breadcrumbs') ->min(1); $optionsChildNodes->integerNode('max_value_length') ->min(1); $optionsChildNodes->arrayNode('prefixes') ->defaultValue($defaultValues->getPrefixes()) ->prototype('scalar'); $optionsChildNodes->scalarNode('project_root') ->defaultValue($this->getProjectRoot()); $optionsChildNodes->scalarNode('release'); $optionsChildNodes->floatNode('sample_rate') ->min(0.0) ->max(1.0); $optionsChildNodes->integerNode('send_attempts') ->min(1); $optionsChildNodes->booleanNode('send_default_pii'); $optionsChildNodes->scalarNode('server_name'); $optionsChildNodes->arrayNode('tags') ->normalizeKeys(false) ->prototype('scalar'); // Bundle-specific configuration $listenerPriorities = $rootNode->children() ->arrayNode('listener_priorities') ->addDefaultsIfNotSet() ->children(); $listenerPriorities->scalarNode('request') ->defaultValue(1); $listenerPriorities->scalarNode('sub_request') ->defaultValue(1); $listenerPriorities->scalarNode('console') ->defaultValue(1); $listenerPriorities->scalarNode('request_error') ->defaultValue(128); $listenerPriorities->scalarNode('console_error') ->defaultValue(128); return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('sentry'); /** @var ArrayNodeDefinition $rootNode */ $rootNode = \method_exists(TreeBuilder::class, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('sentry'); // Basic Sentry configuration $rootNode->children() ->scalarNode('dsn') ->defaultNull() ->beforeNormalization() ->ifString() ->then($this->getTrimClosure()); // Options array (to be passed to Sentry\Options constructor) -- please keep alphabetical order! $optionsNode = $rootNode->children() ->arrayNode('options') ->addDefaultsIfNotSet(); $defaultValues = new Options(); $optionsChildNodes = $optionsNode->children(); $optionsChildNodes->booleanNode('attach_stacktrace'); $optionsChildNodes->variableNode('before_breadcrumb') ->validate() ->ifTrue($this->isNotAValidCallback()) ->thenInvalid('Expecting callable or service reference, got %s'); $optionsChildNodes->variableNode('before_send') ->validate() ->ifTrue($this->isNotAValidCallback()) ->thenInvalid('Expecting callable or service reference, got %s'); if (PrettyVersions::getVersion('sentry/sentry')->getPrettyVersion() !== '2.0.0') { $optionsChildNodes->booleanNode('capture_silenced_errors'); } $optionsChildNodes->integerNode('context_lines') ->min(0) ->max(99); $optionsChildNodes->booleanNode('default_integrations'); $optionsChildNodes->booleanNode('enable_compression'); $optionsChildNodes->scalarNode('environment') ->defaultValue('%kernel.environment%') ->cannotBeEmpty(); $optionsChildNodes->scalarNode('error_types'); $optionsChildNodes->arrayNode('in_app_exclude') ->defaultValue([ '%kernel.cache_dir%', $this->getProjectRoot() . '/vendor', ]) ->prototype('scalar'); $optionsChildNodes->arrayNode('excluded_exceptions') ->defaultValue($defaultValues->getExcludedExceptions()) ->prototype('scalar'); $optionsChildNodes->scalarNode('http_proxy'); $optionsChildNodes->arrayNode('integrations') ->prototype('scalar') ->validate() ->ifTrue(function ($value): bool { if (! is_string($value)) { return true; } return '@' !== substr($value, 0, 1); }) ->thenInvalid('Expecting service reference, got %s'); $optionsChildNodes->scalarNode('logger'); $optionsChildNodes->integerNode('max_breadcrumbs') ->min(1); $optionsChildNodes->integerNode('max_value_length') ->min(1); $optionsChildNodes->arrayNode('prefixes') ->defaultValue($defaultValues->getPrefixes()) ->prototype('scalar'); $optionsChildNodes->scalarNode('project_root') ->defaultValue($this->getProjectRoot()); $optionsChildNodes->scalarNode('release'); $optionsChildNodes->floatNode('sample_rate') ->min(0.0) ->max(1.0); $optionsChildNodes->integerNode('send_attempts') ->min(1); $optionsChildNodes->booleanNode('send_default_pii'); $optionsChildNodes->scalarNode('server_name'); $optionsChildNodes->arrayNode('tags') ->normalizeKeys(false) ->prototype('scalar'); // Bundle-specific configuration $listenerPriorities = $rootNode->children() ->arrayNode('listener_priorities') ->addDefaultsIfNotSet() ->children(); $listenerPriorities->scalarNode('request') ->defaultValue(1); $listenerPriorities->scalarNode('sub_request') ->defaultValue(1); $listenerPriorities->scalarNode('console') ->defaultValue(1); $listenerPriorities->scalarNode('request_error') ->defaultValue(128); $listenerPriorities->scalarNode('console_error') ->defaultValue(128); return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", "'sentry'", ")", ";", "/** @var ArrayNodeDefinition $rootNode */", "$", "rootNode", "=", "\\", "method_exists", "(", "TreeBuilder", "::", "class", ",", ...
{@inheritDoc} @throws \InvalidArgumentException @throws \RuntimeException
[ "{" ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/DependencyInjection/Configuration.php#L24-L129
getsentry/sentry-symfony
src/EventListener/ConsoleListener.php
ConsoleListener.onConsoleCommand
public function onConsoleCommand(ConsoleCommandEvent $event): void { $command = $event->getCommand(); Hub::getCurrent() ->configureScope(function (Scope $scope) use ($command): void { $scope->setTag('command', $command ? $command->getName() : 'N/A'); }); }
php
public function onConsoleCommand(ConsoleCommandEvent $event): void { $command = $event->getCommand(); Hub::getCurrent() ->configureScope(function (Scope $scope) use ($command): void { $scope->setTag('command', $command ? $command->getName() : 'N/A'); }); }
[ "public", "function", "onConsoleCommand", "(", "ConsoleCommandEvent", "$", "event", ")", ":", "void", "{", "$", "command", "=", "$", "event", "->", "getCommand", "(", ")", ";", "Hub", "::", "getCurrent", "(", ")", "->", "configureScope", "(", "function", "...
This method ensures that the client and error handlers are registered at the start of the command execution cycle, and not only on exceptions @param ConsoleCommandEvent $event @return void
[ "This", "method", "ensures", "that", "the", "client", "and", "error", "handlers", "are", "registered", "at", "the", "start", "of", "the", "command", "execution", "cycle", "and", "not", "only", "on", "exceptions" ]
train
https://github.com/getsentry/sentry-symfony/blob/2845df5cca172f720ba0be8fa2b0026f6f9f3b25/src/EventListener/ConsoleListener.php#L32-L40
mikeerickson/phpunit-pretty-result-printer
src/PrinterTrait8.php
PrinterTrait8.getConfigurationFile
public function getConfigurationFile($configFileName = 'phpunit-printer.yml') { $defaultConfigFilename = $this->getPackageRoot() . DIRECTORY_SEPARATOR . 'src/' .$configFileName; $configPath = getcwd(); $filename = ''; $continue = true; while (!file_exists($filename) && $continue) { $filename = $configPath . DIRECTORY_SEPARATOR . $configFileName; if (($this->isWindows() && \strlen($configPath) === 3) || $configPath === '/') { $filename = $defaultConfigFilename; $continue = false; } $configPath = \dirname($configPath); } return $filename; }
php
public function getConfigurationFile($configFileName = 'phpunit-printer.yml') { $defaultConfigFilename = $this->getPackageRoot() . DIRECTORY_SEPARATOR . 'src/' .$configFileName; $configPath = getcwd(); $filename = ''; $continue = true; while (!file_exists($filename) && $continue) { $filename = $configPath . DIRECTORY_SEPARATOR . $configFileName; if (($this->isWindows() && \strlen($configPath) === 3) || $configPath === '/') { $filename = $defaultConfigFilename; $continue = false; } $configPath = \dirname($configPath); } return $filename; }
[ "public", "function", "getConfigurationFile", "(", "$", "configFileName", "=", "'phpunit-printer.yml'", ")", "{", "$", "defaultConfigFilename", "=", "$", "this", "->", "getPackageRoot", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "'src/'", ".", "$", "configFileName",...
@param string $configFileName @return string
[ "@param", "string", "$configFileName" ]
train
https://github.com/mikeerickson/phpunit-pretty-result-printer/blob/d2edd5a7e2c23cc342628895205184897f1acee0/src/PrinterTrait8.php#L106-L124
mikeerickson/phpunit-pretty-result-printer
src/PrinterTrait8.php
PrinterTrait8.printClassName
protected function printClassName() { if ($this->hideClassName) { return; } if ($this->lastClassName === $this->className) { return; } echo PHP_EOL; $className = $this->formatClassName($this->className); $this->colorsTool ? $this->writeWithColor('fg-cyan,bold', $className, false) : $this->write($className); $this->column = \strlen($className) + 1; $this->lastClassName = $this->className; }
php
protected function printClassName() { if ($this->hideClassName) { return; } if ($this->lastClassName === $this->className) { return; } echo PHP_EOL; $className = $this->formatClassName($this->className); $this->colorsTool ? $this->writeWithColor('fg-cyan,bold', $className, false) : $this->write($className); $this->column = \strlen($className) + 1; $this->lastClassName = $this->className; }
[ "protected", "function", "printClassName", "(", ")", "{", "if", "(", "$", "this", "->", "hideClassName", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "lastClassName", "===", "$", "this", "->", "className", ")", "{", "return", ";", "}", ...
Prints the Class Name if it has changed.
[ "Prints", "the", "Class", "Name", "if", "it", "has", "changed", "." ]
train
https://github.com/mikeerickson/phpunit-pretty-result-printer/blob/d2edd5a7e2c23cc342628895205184897f1acee0/src/PrinterTrait8.php#L200-L214
mikeerickson/phpunit-pretty-result-printer
src/PrinterTrait8.php
PrinterTrait8.writeProgressWithColorEx
protected function writeProgressWithColorEx($color, $buffer) { if (!$this->debug) { $this->printClassName(); } $this->printTestCaseStatus($color, $buffer); }
php
protected function writeProgressWithColorEx($color, $buffer) { if (!$this->debug) { $this->printClassName(); } $this->printTestCaseStatus($color, $buffer); }
[ "protected", "function", "writeProgressWithColorEx", "(", "$", "color", ",", "$", "buffer", ")", "{", "if", "(", "!", "$", "this", "->", "debug", ")", "{", "$", "this", "->", "printClassName", "(", ")", ";", "}", "$", "this", "->", "printTestCaseStatus",...
{@inheritdoc}
[ "{" ]
train
https://github.com/mikeerickson/phpunit-pretty-result-printer/blob/d2edd5a7e2c23cc342628895205184897f1acee0/src/PrinterTrait8.php#L219-L226
mikeerickson/phpunit-pretty-result-printer
src/PrinterTrait8.php
PrinterTrait8.getConfigOption
private function getConfigOption($marker, $default = '') { if (isset($this->printerOptions['options'])) { if (isset($this->printerOptions['options'][$marker])) { return $this->printerOptions['options'][$marker]; } } return $this->defaultConfigOptions['options'][$marker]; }
php
private function getConfigOption($marker, $default = '') { if (isset($this->printerOptions['options'])) { if (isset($this->printerOptions['options'][$marker])) { return $this->printerOptions['options'][$marker]; } } return $this->defaultConfigOptions['options'][$marker]; }
[ "private", "function", "getConfigOption", "(", "$", "marker", ",", "$", "default", "=", "''", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "printerOptions", "[", "'options'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", ...
@param $marker @return mixed
[ "@param", "$marker" ]
train
https://github.com/mikeerickson/phpunit-pretty-result-printer/blob/d2edd5a7e2c23cc342628895205184897f1acee0/src/PrinterTrait8.php#L287-L296
mikeerickson/phpunit-pretty-result-printer
src/PrinterTrait8.php
PrinterTrait8.getConfigMarker
private function getConfigMarker($marker) { if (isset($this->printerOptions['markers'])) { if (isset($this->printerOptions['markers'][$marker])) { return $this->printerOptions['markers'][$marker]; } } return $this->defaultConfigOptions['markers'][$marker]; }
php
private function getConfigMarker($marker) { if (isset($this->printerOptions['markers'])) { if (isset($this->printerOptions['markers'][$marker])) { return $this->printerOptions['markers'][$marker]; } } return $this->defaultConfigOptions['markers'][$marker]; }
[ "private", "function", "getConfigMarker", "(", "$", "marker", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "printerOptions", "[", "'markers'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "printerOptions", "[", "'markers'", ...
@param $marker @return mixed
[ "@param", "$marker" ]
train
https://github.com/mikeerickson/phpunit-pretty-result-printer/blob/d2edd5a7e2c23cc342628895205184897f1acee0/src/PrinterTrait8.php#L303-L312
mikeerickson/phpunit-pretty-result-printer
src/PrinterTrait8.php
PrinterTrait8.getWidth
private function getWidth() { $width = 0; if ($this->isWindows()) { return 96; // create a default width to be used on windows } exec('stty size 2>/dev/null', $out, $exit); // 'stty size' output example: 36 120 if (\count($out) > 0) { $width = (int) explode(' ', array_pop($out))[1]; } // handle CircleCI case (probably the same with TravisCI as well) if ($width === 0) { $width = 96; } return $width; }
php
private function getWidth() { $width = 0; if ($this->isWindows()) { return 96; // create a default width to be used on windows } exec('stty size 2>/dev/null', $out, $exit); // 'stty size' output example: 36 120 if (\count($out) > 0) { $width = (int) explode(' ', array_pop($out))[1]; } // handle CircleCI case (probably the same with TravisCI as well) if ($width === 0) { $width = 96; } return $width; }
[ "private", "function", "getWidth", "(", ")", "{", "$", "width", "=", "0", ";", "if", "(", "$", "this", "->", "isWindows", "(", ")", ")", "{", "return", "96", ";", "// create a default width to be used on windows", "}", "exec", "(", "'stty size 2>/dev/null'", ...
Gets the terminal width. @return int
[ "Gets", "the", "terminal", "width", "." ]
train
https://github.com/mikeerickson/phpunit-pretty-result-printer/blob/d2edd5a7e2c23cc342628895205184897f1acee0/src/PrinterTrait8.php#L335-L355
mikeerickson/phpunit-pretty-result-printer
src/PrinterTrait8.php
PrinterTrait8.formatClassName
private function formatClassName($className) { $prefix = ' ==> '; $ellipsis = '...'; $suffix = ' '; if ($this->hideNamespace && strrpos($className, '\\')) { $className = substr($className, strrpos($className, '\\') + 1); } $formattedClassName = $prefix . $className . $suffix; if (\strlen($formattedClassName) <= $this->maxClassNameLength) { return $this->fillWithWhitespace($formattedClassName); } // maxLength of class, minus leading (...) and trailing space $maxLength = $this->maxClassNameLength - \strlen($prefix . $ellipsis . $suffix); // substring class name, providing space for ellipsis and one space at end // this result should be combined to equal $this->maxClassNameLength return $prefix . $ellipsis . substr($className, \strlen($className) - $maxLength, $maxLength) . $suffix; }
php
private function formatClassName($className) { $prefix = ' ==> '; $ellipsis = '...'; $suffix = ' '; if ($this->hideNamespace && strrpos($className, '\\')) { $className = substr($className, strrpos($className, '\\') + 1); } $formattedClassName = $prefix . $className . $suffix; if (\strlen($formattedClassName) <= $this->maxClassNameLength) { return $this->fillWithWhitespace($formattedClassName); } // maxLength of class, minus leading (...) and trailing space $maxLength = $this->maxClassNameLength - \strlen($prefix . $ellipsis . $suffix); // substring class name, providing space for ellipsis and one space at end // this result should be combined to equal $this->maxClassNameLength return $prefix . $ellipsis . substr($className, \strlen($className) - $maxLength, $maxLength) . $suffix; }
[ "private", "function", "formatClassName", "(", "$", "className", ")", "{", "$", "prefix", "=", "' ==> '", ";", "$", "ellipsis", "=", "'...'", ";", "$", "suffix", "=", "' '", ";", "if", "(", "$", "this", "->", "hideNamespace", "&&", "strrpos", "(", "$...
@param string $className @return string
[ "@param", "string", "$className" ]
train
https://github.com/mikeerickson/phpunit-pretty-result-printer/blob/d2edd5a7e2c23cc342628895205184897f1acee0/src/PrinterTrait8.php#L362-L382
spatie/laravel-cors
src/Cors.php
Cors.handle
public function handle($request, Closure $next) { if (! $this->isCorsRequest($request)) { return $next($request); } $this->corsProfile->setRequest($request); if (! $this->corsProfile->isAllowed()) { return $this->forbiddenResponse(); } if ($this->isPreflightRequest($request)) { return $this->handlePreflightRequest(); } $response = $next($request); return $this->corsProfile->addCorsHeaders($response); }
php
public function handle($request, Closure $next) { if (! $this->isCorsRequest($request)) { return $next($request); } $this->corsProfile->setRequest($request); if (! $this->corsProfile->isAllowed()) { return $this->forbiddenResponse(); } if ($this->isPreflightRequest($request)) { return $this->handlePreflightRequest(); } $response = $next($request); return $this->corsProfile->addCorsHeaders($response); }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ")", "{", "if", "(", "!", "$", "this", "->", "isCorsRequest", "(", "$", "request", ")", ")", "{", "return", "$", "next", "(", "$", "request", ")", ";", "}", "$", "t...
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/spatie/laravel-cors/blob/e20a929637f675fe309f3d4ad28f503d7ff6d266/src/Cors.php#L25-L44
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/Driver/GoutteFactory.php
GoutteFactory.configure
public function configure(ArrayNodeDefinition $builder) { $builder ->children() ->arrayNode('server_parameters') ->useAttributeAsKey('key') ->prototype('variable')->end() ->end() ->arrayNode('guzzle_parameters') ->useAttributeAsKey('key') ->prototype('variable')->end() ->info( "For Goutte 1.x, these are the second argument of the Guzzle3 client constructor.\n". 'For Goutte 2.x, these are the elements passed in the "defaults" key of the Guzzle4 config.' ) ->end() ->end() ; }
php
public function configure(ArrayNodeDefinition $builder) { $builder ->children() ->arrayNode('server_parameters') ->useAttributeAsKey('key') ->prototype('variable')->end() ->end() ->arrayNode('guzzle_parameters') ->useAttributeAsKey('key') ->prototype('variable')->end() ->info( "For Goutte 1.x, these are the second argument of the Guzzle3 client constructor.\n". 'For Goutte 2.x, these are the elements passed in the "defaults" key of the Guzzle4 config.' ) ->end() ->end() ; }
[ "public", "function", "configure", "(", "ArrayNodeDefinition", "$", "builder", ")", "{", "$", "builder", "->", "children", "(", ")", "->", "arrayNode", "(", "'server_parameters'", ")", "->", "useAttributeAsKey", "(", "'key'", ")", "->", "prototype", "(", "'var...
{@inheritdoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/Driver/GoutteFactory.php#L40-L58
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/Driver/GoutteFactory.php
GoutteFactory.buildDriver
public function buildDriver(array $config) { if (!class_exists('Behat\Mink\Driver\GoutteDriver')) { throw new \RuntimeException( 'Install MinkGoutteDriver in order to use goutte driver.' ); } if ($this->isGoutte1()) { $guzzleClient = $this->buildGuzzle3Client($config['guzzle_parameters']); } elseif ($this->isGuzzle6()) { $guzzleClient = $this->buildGuzzle6Client($config['guzzle_parameters']); } else { $guzzleClient = $this->buildGuzzle4Client($config['guzzle_parameters']); } $clientDefinition = new Definition('Behat\Mink\Driver\Goutte\Client', array( $config['server_parameters'], )); $clientDefinition->addMethodCall('setClient', array($guzzleClient)); return new Definition('Behat\Mink\Driver\GoutteDriver', array( $clientDefinition, )); }
php
public function buildDriver(array $config) { if (!class_exists('Behat\Mink\Driver\GoutteDriver')) { throw new \RuntimeException( 'Install MinkGoutteDriver in order to use goutte driver.' ); } if ($this->isGoutte1()) { $guzzleClient = $this->buildGuzzle3Client($config['guzzle_parameters']); } elseif ($this->isGuzzle6()) { $guzzleClient = $this->buildGuzzle6Client($config['guzzle_parameters']); } else { $guzzleClient = $this->buildGuzzle4Client($config['guzzle_parameters']); } $clientDefinition = new Definition('Behat\Mink\Driver\Goutte\Client', array( $config['server_parameters'], )); $clientDefinition->addMethodCall('setClient', array($guzzleClient)); return new Definition('Behat\Mink\Driver\GoutteDriver', array( $clientDefinition, )); }
[ "public", "function", "buildDriver", "(", "array", "$", "config", ")", "{", "if", "(", "!", "class_exists", "(", "'Behat\\Mink\\Driver\\GoutteDriver'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Install MinkGoutteDriver in order to use goutte driver...
{@inheritdoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/Driver/GoutteFactory.php#L63-L87
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/Driver/ZombieFactory.php
ZombieFactory.configure
public function configure(ArrayNodeDefinition $builder) { $builder ->children() ->scalarNode('host')->defaultValue('127.0.0.1')->end() ->scalarNode('port')->defaultValue(8124)->end() ->scalarNode('node_bin')->defaultValue('node')->end() ->scalarNode('server_path')->defaultNull()->end() ->scalarNode('threshold')->defaultValue(2000000)->end() ->scalarNode('node_modules_path')->defaultValue('')->end() ->end() ; }
php
public function configure(ArrayNodeDefinition $builder) { $builder ->children() ->scalarNode('host')->defaultValue('127.0.0.1')->end() ->scalarNode('port')->defaultValue(8124)->end() ->scalarNode('node_bin')->defaultValue('node')->end() ->scalarNode('server_path')->defaultNull()->end() ->scalarNode('threshold')->defaultValue(2000000)->end() ->scalarNode('node_modules_path')->defaultValue('')->end() ->end() ; }
[ "public", "function", "configure", "(", "ArrayNodeDefinition", "$", "builder", ")", "{", "$", "builder", "->", "children", "(", ")", "->", "scalarNode", "(", "'host'", ")", "->", "defaultValue", "(", "'127.0.0.1'", ")", "->", "end", "(", ")", "->", "scalar...
{@inheritdoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/Driver/ZombieFactory.php#L37-L49
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/Driver/ZombieFactory.php
ZombieFactory.buildDriver
public function buildDriver(array $config) { if (!class_exists('Behat\Mink\Driver\ZombieDriver')) { throw new \RuntimeException( 'Install MinkZombieDriver in order to use zombie driver.' ); } return new Definition('Behat\Mink\Driver\ZombieDriver', array( new Definition('Behat\Mink\Driver\NodeJS\Server\ZombieServer', array( $config['host'], $config['port'], $config['node_bin'], $config['server_path'], $config['threshold'], $config['node_modules_path'], )), )); }
php
public function buildDriver(array $config) { if (!class_exists('Behat\Mink\Driver\ZombieDriver')) { throw new \RuntimeException( 'Install MinkZombieDriver in order to use zombie driver.' ); } return new Definition('Behat\Mink\Driver\ZombieDriver', array( new Definition('Behat\Mink\Driver\NodeJS\Server\ZombieServer', array( $config['host'], $config['port'], $config['node_bin'], $config['server_path'], $config['threshold'], $config['node_modules_path'], )), )); }
[ "public", "function", "buildDriver", "(", "array", "$", "config", ")", "{", "if", "(", "!", "class_exists", "(", "'Behat\\Mink\\Driver\\ZombieDriver'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Install MinkZombieDriver in order to use zombie driver...
{@inheritdoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/Driver/ZombieFactory.php#L54-L72
Behat/MinkExtension
src/Behat/MinkExtension/Context/Initializer/MinkAwareInitializer.php
MinkAwareInitializer.initializeContext
public function initializeContext(Context $context) { if (!$context instanceof MinkAwareContext) { return; } $context->setMink($this->mink); $context->setMinkParameters($this->parameters); }
php
public function initializeContext(Context $context) { if (!$context instanceof MinkAwareContext) { return; } $context->setMink($this->mink); $context->setMinkParameters($this->parameters); }
[ "public", "function", "initializeContext", "(", "Context", "$", "context", ")", "{", "if", "(", "!", "$", "context", "instanceof", "MinkAwareContext", ")", "{", "return", ";", "}", "$", "context", "->", "setMink", "(", "$", "this", "->", "mink", ")", ";"...
Initializes provided context. @param Context $context
[ "Initializes", "provided", "context", "." ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/Initializer/MinkAwareInitializer.php#L47-L55
Behat/MinkExtension
src/Behat/MinkExtension/Context/RawMinkContext.php
RawMinkContext.getMinkParameter
public function getMinkParameter($name) { return isset($this->minkParameters[$name]) ? $this->minkParameters[$name] : null; }
php
public function getMinkParameter($name) { return isset($this->minkParameters[$name]) ? $this->minkParameters[$name] : null; }
[ "public", "function", "getMinkParameter", "(", "$", "name", ")", "{", "return", "isset", "(", "$", "this", "->", "minkParameters", "[", "$", "name", "]", ")", "?", "$", "this", "->", "minkParameters", "[", "$", "name", "]", ":", "null", ";", "}" ]
Returns specific mink parameter. @param string $name @return mixed
[ "Returns", "specific", "mink", "parameter", "." ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/RawMinkContext.php#L82-L85
Behat/MinkExtension
src/Behat/MinkExtension/Context/RawMinkContext.php
RawMinkContext.visitPath
public function visitPath($path, $sessionName = null) { $this->getSession($sessionName)->visit($this->locatePath($path)); }
php
public function visitPath($path, $sessionName = null) { $this->getSession($sessionName)->visit($this->locatePath($path)); }
[ "public", "function", "visitPath", "(", "$", "path", ",", "$", "sessionName", "=", "null", ")", "{", "$", "this", "->", "getSession", "(", "$", "sessionName", ")", "->", "visit", "(", "$", "this", "->", "locatePath", "(", "$", "path", ")", ")", ";", ...
Visits provided relative path using provided or default session. @param string $path @param string|null $sessionName
[ "Visits", "provided", "relative", "path", "using", "provided", "or", "default", "session", "." ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/RawMinkContext.php#L129-L132
Behat/MinkExtension
src/Behat/MinkExtension/Context/RawMinkContext.php
RawMinkContext.saveScreenshot
public function saveScreenshot($filename = null, $filepath = null) { // Under Cygwin, uniqid with more_entropy must be set to true. // No effect in other environments. $filename = $filename ?: sprintf('%s_%s_%s.%s', $this->getMinkParameter('browser_name'), date('c'), uniqid('', true), 'png'); $filepath = $filepath ?: (ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir()); file_put_contents($filepath . '/' . $filename, $this->getSession()->getScreenshot()); }
php
public function saveScreenshot($filename = null, $filepath = null) { // Under Cygwin, uniqid with more_entropy must be set to true. // No effect in other environments. $filename = $filename ?: sprintf('%s_%s_%s.%s', $this->getMinkParameter('browser_name'), date('c'), uniqid('', true), 'png'); $filepath = $filepath ?: (ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir()); file_put_contents($filepath . '/' . $filename, $this->getSession()->getScreenshot()); }
[ "public", "function", "saveScreenshot", "(", "$", "filename", "=", "null", ",", "$", "filepath", "=", "null", ")", "{", "// Under Cygwin, uniqid with more_entropy must be set to true.", "// No effect in other environments.", "$", "filename", "=", "$", "filename", "?", "...
Save a screenshot of the current window to the file system. @param string $filename Desired filename, defaults to <browser_name>_<ISO 8601 date>_<randomId>.png @param string $filepath Desired filepath, defaults to upload_tmp_dir, falls back to sys_get_temp_dir()
[ "Save", "a", "screenshot", "of", "the", "current", "window", "to", "the", "file", "system", "." ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/RawMinkContext.php#L157-L164
Behat/MinkExtension
src/Behat/MinkExtension/Listener/FailureShowListener.php
FailureShowListener.showFailedStepResponse
public function showFailedStepResponse(AfterStepTested $event) { $testResult = $event->getTestResult(); if (!$testResult instanceof ExceptionResult) { return; } if (!$testResult->getException() instanceof MinkException) { return; } if (null === $this->parameters['show_cmd']) { throw new \RuntimeException('Set "show_cmd" parameter in behat.yml to be able to open page in browser (ex.: "show_cmd: open %s")'); } $filename = rtrim($this->parameters['show_tmp_dir'], DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.uniqid().'.html'; file_put_contents($filename, $this->mink->getSession()->getPage()->getContent()); system(sprintf($this->parameters['show_cmd'], escapeshellarg($filename))); }
php
public function showFailedStepResponse(AfterStepTested $event) { $testResult = $event->getTestResult(); if (!$testResult instanceof ExceptionResult) { return; } if (!$testResult->getException() instanceof MinkException) { return; } if (null === $this->parameters['show_cmd']) { throw new \RuntimeException('Set "show_cmd" parameter in behat.yml to be able to open page in browser (ex.: "show_cmd: open %s")'); } $filename = rtrim($this->parameters['show_tmp_dir'], DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.uniqid().'.html'; file_put_contents($filename, $this->mink->getSession()->getPage()->getContent()); system(sprintf($this->parameters['show_cmd'], escapeshellarg($filename))); }
[ "public", "function", "showFailedStepResponse", "(", "AfterStepTested", "$", "event", ")", "{", "$", "testResult", "=", "$", "event", "->", "getTestResult", "(", ")", ";", "if", "(", "!", "$", "testResult", "instanceof", "ExceptionResult", ")", "{", "return", ...
Shows last response of failed step with preconfigured command. Configuration is based on `behat.yml`: `show_auto` enable this listener (default to false) `show_cmd` command to run (`open %s` to open default browser on Mac) `show_tmp_dir` folder where to store temp files (default is system temp) @param AfterStepTested $event @throws \RuntimeException if show_cmd is not configured
[ "Shows", "last", "response", "of", "failed", "step", "with", "preconfigured", "command", "." ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Listener/FailureShowListener.php#L66-L85
Behat/MinkExtension
src/Behat/MinkExtension/Listener/SessionsListener.php
SessionsListener.prepareDefaultMinkSession
public function prepareDefaultMinkSession(ScenarioLikeTested $event) { $scenario = $event->getScenario(); $feature = $event->getFeature(); $session = null; foreach (array_merge($feature->getTags(), $scenario->getTags()) as $tag) { if ('javascript' === $tag) { $session = $this->getJavascriptSession($event->getSuite()); } elseif (preg_match('/^mink\:(.+)/', $tag, $matches)) { $session = $matches[1]; } } if (null === $session) { $session = $this->getDefaultSession($event->getSuite()); } if ($scenario->hasTag('insulated') || $feature->hasTag('insulated')) { $this->mink->stopSessions(); } else { $this->mink->resetSessions(); } $this->mink->setDefaultSessionName($session); }
php
public function prepareDefaultMinkSession(ScenarioLikeTested $event) { $scenario = $event->getScenario(); $feature = $event->getFeature(); $session = null; foreach (array_merge($feature->getTags(), $scenario->getTags()) as $tag) { if ('javascript' === $tag) { $session = $this->getJavascriptSession($event->getSuite()); } elseif (preg_match('/^mink\:(.+)/', $tag, $matches)) { $session = $matches[1]; } } if (null === $session) { $session = $this->getDefaultSession($event->getSuite()); } if ($scenario->hasTag('insulated') || $feature->hasTag('insulated')) { $this->mink->stopSessions(); } else { $this->mink->resetSessions(); } $this->mink->setDefaultSessionName($session); }
[ "public", "function", "prepareDefaultMinkSession", "(", "ScenarioLikeTested", "$", "event", ")", "{", "$", "scenario", "=", "$", "event", "->", "getScenario", "(", ")", ";", "$", "feature", "=", "$", "event", "->", "getFeature", "(", ")", ";", "$", "sessio...
Configures default Mink session before each scenario. Configuration is based on provided scenario tags: `@javascript` tagged scenarios will get `javascript_session` as default session `@mink:CUSTOM_NAME tagged scenarios will get `CUSTOM_NAME` as default session Other scenarios get `default_session` as default session `@insulated` tag will cause Mink to stop current sessions before scenario instead of just soft-resetting them @param ScenarioLikeTested $event @throws ProcessingException when the @javascript tag is used without a javascript session
[ "Configures", "default", "Mink", "session", "before", "each", "scenario", ".", "Configuration", "is", "based", "on", "provided", "scenario", "tags", ":" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Listener/SessionsListener.php#L83-L108
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/Driver/AppiumFactory.php
AppiumFactory.buildDriver
public function buildDriver(array $config) { $host = $config['appium_host'].":".$config['appium_port']; $config['wd_host'] = sprintf('%s/wd/hub', $host); return parent::buildDriver($config); }
php
public function buildDriver(array $config) { $host = $config['appium_host'].":".$config['appium_port']; $config['wd_host'] = sprintf('%s/wd/hub', $host); return parent::buildDriver($config); }
[ "public", "function", "buildDriver", "(", "array", "$", "config", ")", "{", "$", "host", "=", "$", "config", "[", "'appium_host'", "]", ".", "\":\"", ".", "$", "config", "[", "'appium_port'", "]", ";", "$", "config", "[", "'wd_host'", "]", "=", "sprint...
{@inheritdoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/Driver/AppiumFactory.php#L36-L43
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/MinkExtension.php
MinkExtension.load
public function load(ContainerBuilder $container, array $config) { if (isset($config['mink_loader'])) { $basePath = $container->getParameter('paths.base'); if (file_exists($basePath.DIRECTORY_SEPARATOR.$config['mink_loader'])) { require($basePath.DIRECTORY_SEPARATOR.$config['mink_loader']); } else { require($config['mink_loader']); } } $this->loadMink($container); $this->loadContextInitializer($container); $this->loadSelectorsHandler($container); $this->loadSessions($container, $config); $this->loadSessionsListener($container); if ($config['show_auto']) { $this->loadFailureShowListener($container); } unset($config['sessions']); $container->setParameter('mink.parameters', $config); $container->setParameter('mink.base_url', $config['base_url']); $container->setParameter('mink.browser_name', $config['browser_name']); }
php
public function load(ContainerBuilder $container, array $config) { if (isset($config['mink_loader'])) { $basePath = $container->getParameter('paths.base'); if (file_exists($basePath.DIRECTORY_SEPARATOR.$config['mink_loader'])) { require($basePath.DIRECTORY_SEPARATOR.$config['mink_loader']); } else { require($config['mink_loader']); } } $this->loadMink($container); $this->loadContextInitializer($container); $this->loadSelectorsHandler($container); $this->loadSessions($container, $config); $this->loadSessionsListener($container); if ($config['show_auto']) { $this->loadFailureShowListener($container); } unset($config['sessions']); $container->setParameter('mink.parameters', $config); $container->setParameter('mink.base_url', $config['base_url']); $container->setParameter('mink.browser_name', $config['browser_name']); }
[ "public", "function", "load", "(", "ContainerBuilder", "$", "container", ",", "array", "$", "config", ")", "{", "if", "(", "isset", "(", "$", "config", "[", "'mink_loader'", "]", ")", ")", "{", "$", "basePath", "=", "$", "container", "->", "getParameter"...
{@inheritDoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/MinkExtension.php#L71-L98
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/MinkExtension.php
MinkExtension.configure
public function configure(ArrayNodeDefinition $builder) { // Rewrite keys to define a shortcut way without allowing conflicts with real keys $renamedKeys = array_diff( array_keys($this->driverFactories), array('mink_loader', 'base_url', 'files_path', 'show_auto', 'show_cmd', 'show_tmp_dir', 'default_session', 'javascript_session', 'browser_name', 'sessions') ); $builder ->beforeNormalization() ->always() ->then(function ($v) use ($renamedKeys) { foreach ($renamedKeys as $driverType) { if (!array_key_exists($driverType, $v) || isset($v['sessions'][$driverType])) { continue; } $v['sessions'][$driverType][$driverType] = $v[$driverType]; unset($v[$driverType]); } return $v; }) ->end() ->addDefaultsIfNotSet() ->children() ->scalarNode('mink_loader')->defaultNull()->end() ->scalarNode('base_url')->defaultNull()->end() ->scalarNode('files_path')->defaultNull()->end() ->booleanNode('show_auto')->defaultFalse()->end() ->scalarNode('show_cmd')->defaultNull()->end() ->scalarNode('show_tmp_dir')->defaultValue(sys_get_temp_dir())->end() ->scalarNode('default_session')->defaultNull()->info('Defaults to the first non-javascript session if any, or the first session otherwise')->end() ->scalarNode('javascript_session')->defaultNull()->info('Defaults to the first javascript session if any')->end() ->scalarNode('browser_name')->defaultValue('firefox')->end() ->end() ->end(); /** @var ArrayNodeDefinition $sessionsBuilder */ $sessionsBuilder = $builder ->children() ->arrayNode('sessions') ->isRequired() ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ; foreach ($this->driverFactories as $factory) { $factoryNode = $sessionsBuilder->children()->arrayNode($factory->getDriverName())->canBeUnset(); $factory->configure($factoryNode); } $sessionsBuilder ->validate() ->ifTrue(function ($v) {return count($v) > 1;}) ->thenInvalid('You cannot set multiple driver types for the same session') ->end() ->validate() ->ifTrue(function ($v) {return count($v) === 0;}) ->thenInvalid('You must set a driver definition for the session.') ->end() ; }
php
public function configure(ArrayNodeDefinition $builder) { // Rewrite keys to define a shortcut way without allowing conflicts with real keys $renamedKeys = array_diff( array_keys($this->driverFactories), array('mink_loader', 'base_url', 'files_path', 'show_auto', 'show_cmd', 'show_tmp_dir', 'default_session', 'javascript_session', 'browser_name', 'sessions') ); $builder ->beforeNormalization() ->always() ->then(function ($v) use ($renamedKeys) { foreach ($renamedKeys as $driverType) { if (!array_key_exists($driverType, $v) || isset($v['sessions'][$driverType])) { continue; } $v['sessions'][$driverType][$driverType] = $v[$driverType]; unset($v[$driverType]); } return $v; }) ->end() ->addDefaultsIfNotSet() ->children() ->scalarNode('mink_loader')->defaultNull()->end() ->scalarNode('base_url')->defaultNull()->end() ->scalarNode('files_path')->defaultNull()->end() ->booleanNode('show_auto')->defaultFalse()->end() ->scalarNode('show_cmd')->defaultNull()->end() ->scalarNode('show_tmp_dir')->defaultValue(sys_get_temp_dir())->end() ->scalarNode('default_session')->defaultNull()->info('Defaults to the first non-javascript session if any, or the first session otherwise')->end() ->scalarNode('javascript_session')->defaultNull()->info('Defaults to the first javascript session if any')->end() ->scalarNode('browser_name')->defaultValue('firefox')->end() ->end() ->end(); /** @var ArrayNodeDefinition $sessionsBuilder */ $sessionsBuilder = $builder ->children() ->arrayNode('sessions') ->isRequired() ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ; foreach ($this->driverFactories as $factory) { $factoryNode = $sessionsBuilder->children()->arrayNode($factory->getDriverName())->canBeUnset(); $factory->configure($factoryNode); } $sessionsBuilder ->validate() ->ifTrue(function ($v) {return count($v) > 1;}) ->thenInvalid('You cannot set multiple driver types for the same session') ->end() ->validate() ->ifTrue(function ($v) {return count($v) === 0;}) ->thenInvalid('You must set a driver definition for the session.') ->end() ; }
[ "public", "function", "configure", "(", "ArrayNodeDefinition", "$", "builder", ")", "{", "// Rewrite keys to define a shortcut way without allowing conflicts with real keys", "$", "renamedKeys", "=", "array_diff", "(", "array_keys", "(", "$", "this", "->", "driverFactories", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/MinkExtension.php#L103-L167
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/Driver/Selenium2Factory.php
Selenium2Factory.configure
public function configure(ArrayNodeDefinition $builder) { $builder ->children() ->scalarNode('browser')->defaultValue('%mink.browser_name%')->end() ->append($this->getCapabilitiesNode()) ->scalarNode('wd_host')->defaultValue('http://localhost:4444/wd/hub')->end() ->end() ; }
php
public function configure(ArrayNodeDefinition $builder) { $builder ->children() ->scalarNode('browser')->defaultValue('%mink.browser_name%')->end() ->append($this->getCapabilitiesNode()) ->scalarNode('wd_host')->defaultValue('http://localhost:4444/wd/hub')->end() ->end() ; }
[ "public", "function", "configure", "(", "ArrayNodeDefinition", "$", "builder", ")", "{", "$", "builder", "->", "children", "(", ")", "->", "scalarNode", "(", "'browser'", ")", "->", "defaultValue", "(", "'%mink.browser_name%'", ")", "->", "end", "(", ")", "-...
{@inheritdoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/Driver/Selenium2Factory.php#L37-L46
Behat/MinkExtension
src/Behat/MinkExtension/ServiceContainer/Driver/Selenium2Factory.php
Selenium2Factory.buildDriver
public function buildDriver(array $config) { if (!class_exists('Behat\Mink\Driver\Selenium2Driver')) { throw new \RuntimeException(sprintf( 'Install MinkSelenium2Driver in order to use %s driver.', $this->getDriverName() )); } $extraCapabilities = $config['capabilities']['extra_capabilities']; unset($config['capabilities']['extra_capabilities']); if (getenv('TRAVIS_JOB_NUMBER')) { $guessedCapabilities = array( 'tunnel-identifier' => getenv('TRAVIS_JOB_NUMBER'), 'build' => getenv('TRAVIS_BUILD_NUMBER'), 'tags' => array('Travis-CI', 'PHP '.phpversion()), ); } elseif (getenv('JENKINS_HOME')) { $guessedCapabilities = array( 'tunnel-identifier' => getenv('JOB_NAME'), 'build' => getenv('BUILD_NUMBER'), 'tags' => array('Jenkins', 'PHP '.phpversion(), getenv('BUILD_TAG')), ); } else { $guessedCapabilities = array( 'tags' => array(php_uname('n'), 'PHP '.phpversion()), ); } return new Definition('Behat\Mink\Driver\Selenium2Driver', array( $config['browser'], array_replace($guessedCapabilities, $extraCapabilities, $config['capabilities']), $config['wd_host'], )); }
php
public function buildDriver(array $config) { if (!class_exists('Behat\Mink\Driver\Selenium2Driver')) { throw new \RuntimeException(sprintf( 'Install MinkSelenium2Driver in order to use %s driver.', $this->getDriverName() )); } $extraCapabilities = $config['capabilities']['extra_capabilities']; unset($config['capabilities']['extra_capabilities']); if (getenv('TRAVIS_JOB_NUMBER')) { $guessedCapabilities = array( 'tunnel-identifier' => getenv('TRAVIS_JOB_NUMBER'), 'build' => getenv('TRAVIS_BUILD_NUMBER'), 'tags' => array('Travis-CI', 'PHP '.phpversion()), ); } elseif (getenv('JENKINS_HOME')) { $guessedCapabilities = array( 'tunnel-identifier' => getenv('JOB_NAME'), 'build' => getenv('BUILD_NUMBER'), 'tags' => array('Jenkins', 'PHP '.phpversion(), getenv('BUILD_TAG')), ); } else { $guessedCapabilities = array( 'tags' => array(php_uname('n'), 'PHP '.phpversion()), ); } return new Definition('Behat\Mink\Driver\Selenium2Driver', array( $config['browser'], array_replace($guessedCapabilities, $extraCapabilities, $config['capabilities']), $config['wd_host'], )); }
[ "public", "function", "buildDriver", "(", "array", "$", "config", ")", "{", "if", "(", "!", "class_exists", "(", "'Behat\\Mink\\Driver\\Selenium2Driver'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Install MinkSelenium2Driver in ...
{@inheritdoc}
[ "{" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/ServiceContainer/Driver/Selenium2Factory.php#L51-L86
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.pressButton
public function pressButton($button) { $button = $this->fixStepArgument($button); $this->getSession()->getPage()->pressButton($button); }
php
public function pressButton($button) { $button = $this->fixStepArgument($button); $this->getSession()->getPage()->pressButton($button); }
[ "public", "function", "pressButton", "(", "$", "button", ")", "{", "$", "button", "=", "$", "this", "->", "fixStepArgument", "(", "$", "button", ")", ";", "$", "this", "->", "getSession", "(", ")", "->", "getPage", "(", ")", "->", "pressButton", "(", ...
Presses button with specified id|name|title|alt|value Example: When I press "Log In" Example: And I press "Log In" @When /^(?:|I )press "(?P<button>(?:[^"]|\\")*)"$/
[ "Presses", "button", "with", "specified", "id|name|title|alt|value", "Example", ":", "When", "I", "press", "Log", "In", "Example", ":", "And", "I", "press", "Log", "In" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L93-L97
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.clickLink
public function clickLink($link) { $link = $this->fixStepArgument($link); $this->getSession()->getPage()->clickLink($link); }
php
public function clickLink($link) { $link = $this->fixStepArgument($link); $this->getSession()->getPage()->clickLink($link); }
[ "public", "function", "clickLink", "(", "$", "link", ")", "{", "$", "link", "=", "$", "this", "->", "fixStepArgument", "(", "$", "link", ")", ";", "$", "this", "->", "getSession", "(", ")", "->", "getPage", "(", ")", "->", "clickLink", "(", "$", "l...
Clicks link with specified id|title|alt|text Example: When I follow "Log In" Example: And I follow "Log In" @When /^(?:|I )follow "(?P<link>(?:[^"]|\\")*)"$/
[ "Clicks", "link", "with", "specified", "id|title|alt|text", "Example", ":", "When", "I", "follow", "Log", "In", "Example", ":", "And", "I", "follow", "Log", "In" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L106-L110
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.fillField
public function fillField($field, $value) { $field = $this->fixStepArgument($field); $value = $this->fixStepArgument($value); $this->getSession()->getPage()->fillField($field, $value); }
php
public function fillField($field, $value) { $field = $this->fixStepArgument($field); $value = $this->fixStepArgument($value); $this->getSession()->getPage()->fillField($field, $value); }
[ "public", "function", "fillField", "(", "$", "field", ",", "$", "value", ")", "{", "$", "field", "=", "$", "this", "->", "fixStepArgument", "(", "$", "field", ")", ";", "$", "value", "=", "$", "this", "->", "fixStepArgument", "(", "$", "value", ")", ...
Fills in form field with specified id|name|label|value Example: When I fill in "username" with: "bwayne" Example: And I fill in "bwayne" for "username" @When /^(?:|I )fill in "(?P<field>(?:[^"]|\\")*)" with "(?P<value>(?:[^"]|\\")*)"$/ @When /^(?:|I )fill in "(?P<field>(?:[^"]|\\")*)" with:$/ @When /^(?:|I )fill in "(?P<value>(?:[^"]|\\")*)" for "(?P<field>(?:[^"]|\\")*)"$/
[ "Fills", "in", "form", "field", "with", "specified", "id|name|label|value", "Example", ":", "When", "I", "fill", "in", "username", "with", ":", "bwayne", "Example", ":", "And", "I", "fill", "in", "bwayne", "for", "username" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L121-L126
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.fillFields
public function fillFields(TableNode $fields) { foreach ($fields->getRowsHash() as $field => $value) { $this->fillField($field, $value); } }
php
public function fillFields(TableNode $fields) { foreach ($fields->getRowsHash() as $field => $value) { $this->fillField($field, $value); } }
[ "public", "function", "fillFields", "(", "TableNode", "$", "fields", ")", "{", "foreach", "(", "$", "fields", "->", "getRowsHash", "(", ")", "as", "$", "field", "=>", "$", "value", ")", "{", "$", "this", "->", "fillField", "(", "$", "field", ",", "$"...
Fills in form fields with provided table Example: When I fill in the following" | username | bruceWayne | | password | iLoveBats123 | Example: And I fill in the following" | username | bruceWayne | | password | iLoveBats123 | @When /^(?:|I )fill in the following:$/
[ "Fills", "in", "form", "fields", "with", "provided", "table", "Example", ":", "When", "I", "fill", "in", "the", "following", "|", "username", "|", "bruceWayne", "|", "|", "password", "|", "iLoveBats123", "|", "Example", ":", "And", "I", "fill", "in", "th...
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L139-L144
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.selectOption
public function selectOption($select, $option) { $select = $this->fixStepArgument($select); $option = $this->fixStepArgument($option); $this->getSession()->getPage()->selectFieldOption($select, $option); }
php
public function selectOption($select, $option) { $select = $this->fixStepArgument($select); $option = $this->fixStepArgument($option); $this->getSession()->getPage()->selectFieldOption($select, $option); }
[ "public", "function", "selectOption", "(", "$", "select", ",", "$", "option", ")", "{", "$", "select", "=", "$", "this", "->", "fixStepArgument", "(", "$", "select", ")", ";", "$", "option", "=", "$", "this", "->", "fixStepArgument", "(", "$", "option"...
Selects option in select field with specified id|name|label|value Example: When I select "Bats" from "user_fears" Example: And I select "Bats" from "user_fears" @When /^(?:|I )select "(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)"$/
[ "Selects", "option", "in", "select", "field", "with", "specified", "id|name|label|value", "Example", ":", "When", "I", "select", "Bats", "from", "user_fears", "Example", ":", "And", "I", "select", "Bats", "from", "user_fears" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L153-L158
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.additionallySelectOption
public function additionallySelectOption($select, $option) { $select = $this->fixStepArgument($select); $option = $this->fixStepArgument($option); $this->getSession()->getPage()->selectFieldOption($select, $option, true); }
php
public function additionallySelectOption($select, $option) { $select = $this->fixStepArgument($select); $option = $this->fixStepArgument($option); $this->getSession()->getPage()->selectFieldOption($select, $option, true); }
[ "public", "function", "additionallySelectOption", "(", "$", "select", ",", "$", "option", ")", "{", "$", "select", "=", "$", "this", "->", "fixStepArgument", "(", "$", "select", ")", ";", "$", "option", "=", "$", "this", "->", "fixStepArgument", "(", "$"...
Selects additional option in select field with specified id|name|label|value Example: When I additionally select "Deceased" from "parents_alive_status" Example: And I additionally select "Deceased" from "parents_alive_status" @When /^(?:|I )additionally select "(?P<option>(?:[^"]|\\")*)" from "(?P<select>(?:[^"]|\\")*)"$/
[ "Selects", "additional", "option", "in", "select", "field", "with", "specified", "id|name|label|value", "Example", ":", "When", "I", "additionally", "select", "Deceased", "from", "parents_alive_status", "Example", ":", "And", "I", "additionally", "select", "Deceased",...
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L167-L172
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.checkOption
public function checkOption($option) { $option = $this->fixStepArgument($option); $this->getSession()->getPage()->checkField($option); }
php
public function checkOption($option) { $option = $this->fixStepArgument($option); $this->getSession()->getPage()->checkField($option); }
[ "public", "function", "checkOption", "(", "$", "option", ")", "{", "$", "option", "=", "$", "this", "->", "fixStepArgument", "(", "$", "option", ")", ";", "$", "this", "->", "getSession", "(", ")", "->", "getPage", "(", ")", "->", "checkField", "(", ...
Checks checkbox with specified id|name|label|value Example: When I check "Pearl Necklace" Example: And I check "Pearl Necklace" @When /^(?:|I )check "(?P<option>(?:[^"]|\\")*)"$/
[ "Checks", "checkbox", "with", "specified", "id|name|label|value", "Example", ":", "When", "I", "check", "Pearl", "Necklace", "Example", ":", "And", "I", "check", "Pearl", "Necklace" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L181-L185
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.uncheckOption
public function uncheckOption($option) { $option = $this->fixStepArgument($option); $this->getSession()->getPage()->uncheckField($option); }
php
public function uncheckOption($option) { $option = $this->fixStepArgument($option); $this->getSession()->getPage()->uncheckField($option); }
[ "public", "function", "uncheckOption", "(", "$", "option", ")", "{", "$", "option", "=", "$", "this", "->", "fixStepArgument", "(", "$", "option", ")", ";", "$", "this", "->", "getSession", "(", ")", "->", "getPage", "(", ")", "->", "uncheckField", "("...
Unchecks checkbox with specified id|name|label|value Example: When I uncheck "Broadway Plays" Example: And I uncheck "Broadway Plays" @When /^(?:|I )uncheck "(?P<option>(?:[^"]|\\")*)"$/
[ "Unchecks", "checkbox", "with", "specified", "id|name|label|value", "Example", ":", "When", "I", "uncheck", "Broadway", "Plays", "Example", ":", "And", "I", "uncheck", "Broadway", "Plays" ]
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L194-L198
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.attachFileToField
public function attachFileToField($field, $path) { $field = $this->fixStepArgument($field); if ($this->getMinkParameter('files_path')) { $fullPath = rtrim(realpath($this->getMinkParameter('files_path')), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$path; if (is_file($fullPath)) { $path = $fullPath; } } $this->getSession()->getPage()->attachFileToField($field, $path); }
php
public function attachFileToField($field, $path) { $field = $this->fixStepArgument($field); if ($this->getMinkParameter('files_path')) { $fullPath = rtrim(realpath($this->getMinkParameter('files_path')), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$path; if (is_file($fullPath)) { $path = $fullPath; } } $this->getSession()->getPage()->attachFileToField($field, $path); }
[ "public", "function", "attachFileToField", "(", "$", "field", ",", "$", "path", ")", "{", "$", "field", "=", "$", "this", "->", "fixStepArgument", "(", "$", "field", ")", ";", "if", "(", "$", "this", "->", "getMinkParameter", "(", "'files_path'", ")", ...
Attaches file to field with specified id|name|label|value Example: When I attach "bwayne_profile.png" to "profileImageUpload" Example: And I attach "bwayne_profile.png" to "profileImageUpload" @When /^(?:|I )attach the file "(?P<path>[^"]*)" to "(?P<field>(?:[^"]|\\")*)"$/
[ "Attaches", "file", "to", "field", "with", "specified", "id|name|label|value", "Example", ":", "When", "I", "attach", "bwayne_profile", ".", "png", "to", "profileImageUpload", "Example", ":", "And", "I", "attach", "bwayne_profile", ".", "png", "to", "profileImageU...
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L207-L219
Behat/MinkExtension
src/Behat/MinkExtension/Context/MinkContext.php
MinkContext.assertElementContainsText
public function assertElementContainsText($element, $text) { $this->assertSession()->elementTextContains('css', $element, $this->fixStepArgument($text)); }
php
public function assertElementContainsText($element, $text) { $this->assertSession()->elementTextContains('css', $element, $this->fixStepArgument($text)); }
[ "public", "function", "assertElementContainsText", "(", "$", "element", ",", "$", "text", ")", "{", "$", "this", "->", "assertSession", "(", ")", "->", "elementTextContains", "(", "'css'", ",", "$", "element", ",", "$", "this", "->", "fixStepArgument", "(", ...
Checks, that element with specified CSS contains specified text Example: Then I should see "Batman" in the "heroes_list" element Example: And I should see "Batman" in the "heroes_list" element @Then /^(?:|I )should see "(?P<text>(?:[^"]|\\")*)" in the "(?P<element>[^"]*)" element$/
[ "Checks", "that", "element", "with", "specified", "CSS", "contains", "specified", "text", "Example", ":", "Then", "I", "should", "see", "Batman", "in", "the", "heroes_list", "element", "Example", ":", "And", "I", "should", "see", "Batman", "in", "the", "hero...
train
https://github.com/Behat/MinkExtension/blob/80f7849ba53867181b7e412df9210e12fba50177/src/Behat/MinkExtension/Context/MinkContext.php#L362-L365