id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
32,800
spiral/reactor
src/Traits/UsesTrait.php
UsesTrait.addUses
public function addUses(array $uses): self { foreach ($uses as $class => $alias) { $this->addUse($class, $alias); } return $this; }
php
public function addUses(array $uses): self { foreach ($uses as $class => $alias) { $this->addUse($class, $alias); } return $this; }
[ "public", "function", "addUses", "(", "array", "$", "uses", ")", ":", "self", "{", "foreach", "(", "$", "uses", "as", "$", "class", "=>", "$", "alias", ")", "{", "$", "this", "->", "addUse", "(", "$", "class", ",", "$", "alias", ")", ";", "}", "return", "$", "this", ";", "}" ]
Add additional set of uses. @param array $uses @return self
[ "Add", "additional", "set", "of", "uses", "." ]
222a70249127f1c515238358f2ee0a91d00f9a51
https://github.com/spiral/reactor/blob/222a70249127f1c515238358f2ee0a91d00f9a51/src/Traits/UsesTrait.php#L55-L62
32,801
spiral/reactor
src/Partial/Source.php
Source.fromString
public static function fromString(string $string, bool $cutIndents = false): Source { $source = new self(); return $source->setString($string, $cutIndents); }
php
public static function fromString(string $string, bool $cutIndents = false): Source { $source = new self(); return $source->setString($string, $cutIndents); }
[ "public", "static", "function", "fromString", "(", "string", "$", "string", ",", "bool", "$", "cutIndents", "=", "false", ")", ":", "Source", "{", "$", "source", "=", "new", "self", "(", ")", ";", "return", "$", "source", "->", "setString", "(", "$", "string", ",", "$", "cutIndents", ")", ";", "}" ]
Create version of source cut from specific string location. @param string $string @param bool $cutIndents Function Strings::normalizeIndents will be applied. @return Source
[ "Create", "version", "of", "source", "cut", "from", "specific", "string", "location", "." ]
222a70249127f1c515238358f2ee0a91d00f9a51
https://github.com/spiral/reactor/blob/222a70249127f1c515238358f2ee0a91d00f9a51/src/Partial/Source.php#L120-L125
32,802
spiral/reactor
src/Partial/Source.php
Source.fetchLines
protected function fetchLines(string $string, bool $cutIndents): array { if ($cutIndents) { $string = self::normalizeIndents($string, ""); } $lines = explode("\n", self::normalizeEndings($string, false)); //Pre-processing return array_map([$this, 'prepareLine'], $lines); }
php
protected function fetchLines(string $string, bool $cutIndents): array { if ($cutIndents) { $string = self::normalizeIndents($string, ""); } $lines = explode("\n", self::normalizeEndings($string, false)); //Pre-processing return array_map([$this, 'prepareLine'], $lines); }
[ "protected", "function", "fetchLines", "(", "string", "$", "string", ",", "bool", "$", "cutIndents", ")", ":", "array", "{", "if", "(", "$", "cutIndents", ")", "{", "$", "string", "=", "self", "::", "normalizeIndents", "(", "$", "string", ",", "\"\"", ")", ";", "}", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "self", "::", "normalizeEndings", "(", "$", "string", ",", "false", ")", ")", ";", "//Pre-processing", "return", "array_map", "(", "[", "$", "this", ",", "'prepareLine'", "]", ",", "$", "lines", ")", ";", "}" ]
Converts input string into set of lines. @param string $string @param bool $cutIndents @return array
[ "Converts", "input", "string", "into", "set", "of", "lines", "." ]
222a70249127f1c515238358f2ee0a91d00f9a51
https://github.com/spiral/reactor/blob/222a70249127f1c515238358f2ee0a91d00f9a51/src/Partial/Source.php#L135-L145
32,803
spiral/reactor
src/Partial/Source.php
Source.normalizeEndings
public static function normalizeEndings(string $string, bool $joinMultiple = true): string { if (!$joinMultiple) { return str_replace("\r\n", "\n", $string); } return preg_replace('/[\n\r]+/', "\n", $string); }
php
public static function normalizeEndings(string $string, bool $joinMultiple = true): string { if (!$joinMultiple) { return str_replace("\r\n", "\n", $string); } return preg_replace('/[\n\r]+/', "\n", $string); }
[ "public", "static", "function", "normalizeEndings", "(", "string", "$", "string", ",", "bool", "$", "joinMultiple", "=", "true", ")", ":", "string", "{", "if", "(", "!", "$", "joinMultiple", ")", "{", "return", "str_replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ",", "$", "string", ")", ";", "}", "return", "preg_replace", "(", "'/[\\n\\r]+/'", ",", "\"\\n\"", ",", "$", "string", ")", ";", "}" ]
Normalize string endings to avoid EOL problem. Replace \n\r and multiply new lines with single \n. @param string $string String to be normalized. @param bool $joinMultiple Join multiple new lines into one. @return string
[ "Normalize", "string", "endings", "to", "avoid", "EOL", "problem", ".", "Replace", "\\", "n", "\\", "r", "and", "multiply", "new", "lines", "with", "single", "\\", "n", "." ]
222a70249127f1c515238358f2ee0a91d00f9a51
https://github.com/spiral/reactor/blob/222a70249127f1c515238358f2ee0a91d00f9a51/src/Partial/Source.php#L168-L175
32,804
spiral/reactor
src/Partial/Source.php
Source.normalizeIndents
public static function normalizeIndents(string $string, string $tabulationCost = " "): string { $string = self::normalizeEndings($string, false); $lines = explode("\n", $string); $minIndent = null; foreach ($lines as $line) { if (!trim($line)) { continue; } $line = str_replace("\t", $tabulationCost, $line); //Getting indent size if (!preg_match("/^( +)/", $line, $matches)) { //Some line has no indent return $string; } if ($minIndent === null) { $minIndent = strlen($matches[1]); } $minIndent = min($minIndent, strlen($matches[1])); } //Fixing indent foreach ($lines as &$line) { if (empty($line)) { continue; } //Getting line indent preg_match("/^([ \t]+)/", $line, $matches); $indent = $matches[1]; if (!trim($line)) { $line = ''; continue; } //Getting new indent $useIndent = str_repeat( " ", strlen(str_replace("\t", $tabulationCost, $indent)) - $minIndent ); $line = $useIndent . substr($line, strlen($indent)); unset($line); } return join("\n", $lines); }
php
public static function normalizeIndents(string $string, string $tabulationCost = " "): string { $string = self::normalizeEndings($string, false); $lines = explode("\n", $string); $minIndent = null; foreach ($lines as $line) { if (!trim($line)) { continue; } $line = str_replace("\t", $tabulationCost, $line); //Getting indent size if (!preg_match("/^( +)/", $line, $matches)) { //Some line has no indent return $string; } if ($minIndent === null) { $minIndent = strlen($matches[1]); } $minIndent = min($minIndent, strlen($matches[1])); } //Fixing indent foreach ($lines as &$line) { if (empty($line)) { continue; } //Getting line indent preg_match("/^([ \t]+)/", $line, $matches); $indent = $matches[1]; if (!trim($line)) { $line = ''; continue; } //Getting new indent $useIndent = str_repeat( " ", strlen(str_replace("\t", $tabulationCost, $indent)) - $minIndent ); $line = $useIndent . substr($line, strlen($indent)); unset($line); } return join("\n", $lines); }
[ "public", "static", "function", "normalizeIndents", "(", "string", "$", "string", ",", "string", "$", "tabulationCost", "=", "\" \"", ")", ":", "string", "{", "$", "string", "=", "self", "::", "normalizeEndings", "(", "$", "string", ",", "false", ")", ";", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "$", "string", ")", ";", "$", "minIndent", "=", "null", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "if", "(", "!", "trim", "(", "$", "line", ")", ")", "{", "continue", ";", "}", "$", "line", "=", "str_replace", "(", "\"\\t\"", ",", "$", "tabulationCost", ",", "$", "line", ")", ";", "//Getting indent size", "if", "(", "!", "preg_match", "(", "\"/^( +)/\"", ",", "$", "line", ",", "$", "matches", ")", ")", "{", "//Some line has no indent", "return", "$", "string", ";", "}", "if", "(", "$", "minIndent", "===", "null", ")", "{", "$", "minIndent", "=", "strlen", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "$", "minIndent", "=", "min", "(", "$", "minIndent", ",", "strlen", "(", "$", "matches", "[", "1", "]", ")", ")", ";", "}", "//Fixing indent", "foreach", "(", "$", "lines", "as", "&", "$", "line", ")", "{", "if", "(", "empty", "(", "$", "line", ")", ")", "{", "continue", ";", "}", "//Getting line indent", "preg_match", "(", "\"/^([ \\t]+)/\"", ",", "$", "line", ",", "$", "matches", ")", ";", "$", "indent", "=", "$", "matches", "[", "1", "]", ";", "if", "(", "!", "trim", "(", "$", "line", ")", ")", "{", "$", "line", "=", "''", ";", "continue", ";", "}", "//Getting new indent", "$", "useIndent", "=", "str_repeat", "(", "\" \"", ",", "strlen", "(", "str_replace", "(", "\"\\t\"", ",", "$", "tabulationCost", ",", "$", "indent", ")", ")", "-", "$", "minIndent", ")", ";", "$", "line", "=", "$", "useIndent", ".", "substr", "(", "$", "line", ",", "strlen", "(", "$", "indent", ")", ")", ";", "unset", "(", "$", "line", ")", ";", "}", "return", "join", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Shift all string lines to have minimum indent size set to 0. Example: |-a |--b |--c |---d Output: |a |-b |-c |--d @param string $string Input string with multiple lines. @param string $tabulationCost How to treat \t symbols relatively to spaces. By default, this is set to 4 spaces. @return string
[ "Shift", "all", "string", "lines", "to", "have", "minimum", "indent", "size", "set", "to", "0", "." ]
222a70249127f1c515238358f2ee0a91d00f9a51
https://github.com/spiral/reactor/blob/222a70249127f1c515238358f2ee0a91d00f9a51/src/Partial/Source.php#L198-L240
32,805
zicht/menu-bundle
src/Zicht/Bundle/MenuBundle/Url/AliasingStrategy.php
AliasingStrategy.generatePublicAlias
public function generatePublicAlias($subject, $currentAlias = '') { $path = $this->urlProvider->url($subject); $menuItem = $this->menuManager->getItemBy(array(':path' => $path)); if (!empty($menuItem)) { $parts = array(); for ($item = $menuItem; !is_null($item->getParent()); $item = $item->getParent()) { $parts [] = Str::systemize($item->getTitle()); } $alias = '/' . join('/', array_reverse($parts)); } else { $alias = parent::generatePublicAlias($subject); } return $alias; }
php
public function generatePublicAlias($subject, $currentAlias = '') { $path = $this->urlProvider->url($subject); $menuItem = $this->menuManager->getItemBy(array(':path' => $path)); if (!empty($menuItem)) { $parts = array(); for ($item = $menuItem; !is_null($item->getParent()); $item = $item->getParent()) { $parts [] = Str::systemize($item->getTitle()); } $alias = '/' . join('/', array_reverse($parts)); } else { $alias = parent::generatePublicAlias($subject); } return $alias; }
[ "public", "function", "generatePublicAlias", "(", "$", "subject", ",", "$", "currentAlias", "=", "''", ")", "{", "$", "path", "=", "$", "this", "->", "urlProvider", "->", "url", "(", "$", "subject", ")", ";", "$", "menuItem", "=", "$", "this", "->", "menuManager", "->", "getItemBy", "(", "array", "(", "':path'", "=>", "$", "path", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "menuItem", ")", ")", "{", "$", "parts", "=", "array", "(", ")", ";", "for", "(", "$", "item", "=", "$", "menuItem", ";", "!", "is_null", "(", "$", "item", "->", "getParent", "(", ")", ")", ";", "$", "item", "=", "$", "item", "->", "getParent", "(", ")", ")", "{", "$", "parts", "[", "]", "=", "Str", "::", "systemize", "(", "$", "item", "->", "getTitle", "(", ")", ")", ";", "}", "$", "alias", "=", "'/'", ".", "join", "(", "'/'", ",", "array_reverse", "(", "$", "parts", ")", ")", ";", "}", "else", "{", "$", "alias", "=", "parent", "::", "generatePublicAlias", "(", "$", "subject", ")", ";", "}", "return", "$", "alias", ";", "}" ]
Generate a public alias for the passed object @param mixed $subject @param string $currentAlias @return string
[ "Generate", "a", "public", "alias", "for", "the", "passed", "object" ]
b6f22d50025297ad686c8f3afb7b6afe736b7f97
https://github.com/zicht/menu-bundle/blob/b6f22d50025297ad686c8f3afb7b6afe736b7f97/src/Zicht/Bundle/MenuBundle/Url/AliasingStrategy.php#L51-L66
32,806
unicodeveloper/laravel-emoji
src/Emoji.php
Emoji.findByAlias
public function findByAlias($emojiName = null) : string { if (is_null($emojiName)) { throw IsNull::create("Please provide the name of the emoji you are looking for"); } $emoji = strtolower($emojiName); if (! array_key_exists($emoji, $this->getEmojis())) { throw UnknownEmoji::create($emoji); } return $this->getEmojis()[$emoji]; }
php
public function findByAlias($emojiName = null) : string { if (is_null($emojiName)) { throw IsNull::create("Please provide the name of the emoji you are looking for"); } $emoji = strtolower($emojiName); if (! array_key_exists($emoji, $this->getEmojis())) { throw UnknownEmoji::create($emoji); } return $this->getEmojis()[$emoji]; }
[ "public", "function", "findByAlias", "(", "$", "emojiName", "=", "null", ")", ":", "string", "{", "if", "(", "is_null", "(", "$", "emojiName", ")", ")", "{", "throw", "IsNull", "::", "create", "(", "\"Please provide the name of the emoji you are looking for\"", ")", ";", "}", "$", "emoji", "=", "strtolower", "(", "$", "emojiName", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "emoji", ",", "$", "this", "->", "getEmojis", "(", ")", ")", ")", "{", "throw", "UnknownEmoji", "::", "create", "(", "$", "emoji", ")", ";", "}", "return", "$", "this", "->", "getEmojis", "(", ")", "[", "$", "emoji", "]", ";", "}" ]
Get the emoji by passing the commonly used emoji name @param string $emojiName @return unicode @throws \Unicodeveloper\Emoji\Exceptions\IsNull @throws \Unicodeveloper\Emoji\Exceptions\UnknownUnicode
[ "Get", "the", "emoji", "by", "passing", "the", "commonly", "used", "emoji", "name" ]
d79dcaed5e6d2ca21886deb7bf5a5036d53d872d
https://github.com/unicodeveloper/laravel-emoji/blob/d79dcaed5e6d2ca21886deb7bf5a5036d53d872d/src/Emoji.php#L34-L47
32,807
unicodeveloper/laravel-emoji
src/Emoji.php
Emoji.findByUnicode
public function findByUnicode($unicode = null) : string { if (is_null($unicode)) { throw IsNull::create("Please provide a valid UTF-8 Unicode value"); } $emojis = array_flip($this->getEmojis()); if (! array_key_exists($unicode, $emojis)) { throw UnknownUnicode::create($unicode); } return $emojis[$unicode]; }
php
public function findByUnicode($unicode = null) : string { if (is_null($unicode)) { throw IsNull::create("Please provide a valid UTF-8 Unicode value"); } $emojis = array_flip($this->getEmojis()); if (! array_key_exists($unicode, $emojis)) { throw UnknownUnicode::create($unicode); } return $emojis[$unicode]; }
[ "public", "function", "findByUnicode", "(", "$", "unicode", "=", "null", ")", ":", "string", "{", "if", "(", "is_null", "(", "$", "unicode", ")", ")", "{", "throw", "IsNull", "::", "create", "(", "\"Please provide a valid UTF-8 Unicode value\"", ")", ";", "}", "$", "emojis", "=", "array_flip", "(", "$", "this", "->", "getEmojis", "(", ")", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "unicode", ",", "$", "emojis", ")", ")", "{", "throw", "UnknownUnicode", "::", "create", "(", "$", "unicode", ")", ";", "}", "return", "$", "emojis", "[", "$", "unicode", "]", ";", "}" ]
Get the emoji name by passing the unicode value @param string $unicode @return string @throws \Unicodeveloper\Emoji\Exceptions\IsNull @throws \Unicodeveloper\Emoji\Exceptions\UnknownUnicode
[ "Get", "the", "emoji", "name", "by", "passing", "the", "unicode", "value" ]
d79dcaed5e6d2ca21886deb7bf5a5036d53d872d
https://github.com/unicodeveloper/laravel-emoji/blob/d79dcaed5e6d2ca21886deb7bf5a5036d53d872d/src/Emoji.php#L67-L80
32,808
thomastkim/laravel-online-users
src/Kim/Activity/Traits/ActivitySorter.php
ActivitySorter.scopeOrderByUsers
public function scopeOrderByUsers($query, $column, $dir = 'ASC') { $table = $this->getTable(); $userModel = config('auth.providers.users.model'); $user = new $userModel; $userTable = $user->getTable(); $userKey = $user->getKeyName(); return $query->join($userTable, "{$table}.user_id", '=', "{$userTable}.{$userKey}")->orderBy("{$userTable}.{$column}", $dir); }
php
public function scopeOrderByUsers($query, $column, $dir = 'ASC') { $table = $this->getTable(); $userModel = config('auth.providers.users.model'); $user = new $userModel; $userTable = $user->getTable(); $userKey = $user->getKeyName(); return $query->join($userTable, "{$table}.user_id", '=', "{$userTable}.{$userKey}")->orderBy("{$userTable}.{$column}", $dir); }
[ "public", "function", "scopeOrderByUsers", "(", "$", "query", ",", "$", "column", ",", "$", "dir", "=", "'ASC'", ")", "{", "$", "table", "=", "$", "this", "->", "getTable", "(", ")", ";", "$", "userModel", "=", "config", "(", "'auth.providers.users.model'", ")", ";", "$", "user", "=", "new", "$", "userModel", ";", "$", "userTable", "=", "$", "user", "->", "getTable", "(", ")", ";", "$", "userKey", "=", "$", "user", "->", "getKeyName", "(", ")", ";", "return", "$", "query", "->", "join", "(", "$", "userTable", ",", "\"{$table}.user_id\"", ",", "'='", ",", "\"{$userTable}.{$userKey}\"", ")", "->", "orderBy", "(", "\"{$userTable}.{$column}\"", ",", "$", "dir", ")", ";", "}" ]
Use joins to order by the users' column attributes. @param \Illuminate\Database\Query\Builder $query @param string $column @return \Illuminate\Database\Query\Builder|static
[ "Use", "joins", "to", "order", "by", "the", "users", "column", "attributes", "." ]
8564a3822fcaad2772d3df403adcdfd56de999e0
https://github.com/thomastkim/laravel-online-users/blob/8564a3822fcaad2772d3df403adcdfd56de999e0/src/Kim/Activity/Traits/ActivitySorter.php#L38-L48
32,809
odan/phinx-migrations-generator
src/Migration/Adapter/Generator/PhinxMySqlGenerator.php
PhinxMySqlGenerator.eq
protected function eq($arr, $arr2, $keys): bool { $val1 = $this->find($arr, $keys); $val2 = $this->find($arr2, $keys); return $val1 === $val2; }
php
protected function eq($arr, $arr2, $keys): bool { $val1 = $this->find($arr, $keys); $val2 = $this->find($arr2, $keys); return $val1 === $val2; }
[ "protected", "function", "eq", "(", "$", "arr", ",", "$", "arr2", ",", "$", "keys", ")", ":", "bool", "{", "$", "val1", "=", "$", "this", "->", "find", "(", "$", "arr", ",", "$", "keys", ")", ";", "$", "val2", "=", "$", "this", "->", "find", "(", "$", "arr2", ",", "$", "keys", ")", ";", "return", "$", "val1", "===", "$", "val2", ";", "}" ]
Compare array. @param array $arr @param array $arr2 @param array $keys @return bool
[ "Compare", "array", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Generator/PhinxMySqlGenerator.php#L208-L214
32,810
odan/phinx-migrations-generator
src/Migration/Adapter/Generator/PhinxMySqlGenerator.php
PhinxMySqlGenerator.getPhinxTablePrimaryKey
protected function getPhinxTablePrimaryKey(array $attributes, array $table): array { $primaryKeys = $this->getPrimaryKeys($table); $attributes['id'] = false; if (!empty($primaryKeys)) { $attributes['primary_key'] = $primaryKeys; } return $attributes; }
php
protected function getPhinxTablePrimaryKey(array $attributes, array $table): array { $primaryKeys = $this->getPrimaryKeys($table); $attributes['id'] = false; if (!empty($primaryKeys)) { $attributes['primary_key'] = $primaryKeys; } return $attributes; }
[ "protected", "function", "getPhinxTablePrimaryKey", "(", "array", "$", "attributes", ",", "array", "$", "table", ")", ":", "array", "{", "$", "primaryKeys", "=", "$", "this", "->", "getPrimaryKeys", "(", "$", "table", ")", ";", "$", "attributes", "[", "'id'", "]", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "primaryKeys", ")", ")", "{", "$", "attributes", "[", "'primary_key'", "]", "=", "$", "primaryKeys", ";", "}", "return", "$", "attributes", ";", "}" ]
Define table id value. @param array $attributes @param array $table @return array Attributes
[ "Define", "table", "id", "value", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Generator/PhinxMySqlGenerator.php#L375-L385
32,811
odan/phinx-migrations-generator
src/Migration/Adapter/Generator/PhinxMySqlGenerator.php
PhinxMySqlGenerator.getPrimaryKeys
protected function getPrimaryKeys(array $table): array { $primaryKeys = []; foreach ($table['columns'] as $column) { $columnName = $column['COLUMN_NAME']; $columnKey = $column['COLUMN_KEY']; if ($columnKey !== 'PRI') { continue; } $primaryKeys[] = $columnName; } return $primaryKeys; }
php
protected function getPrimaryKeys(array $table): array { $primaryKeys = []; foreach ($table['columns'] as $column) { $columnName = $column['COLUMN_NAME']; $columnKey = $column['COLUMN_KEY']; if ($columnKey !== 'PRI') { continue; } $primaryKeys[] = $columnName; } return $primaryKeys; }
[ "protected", "function", "getPrimaryKeys", "(", "array", "$", "table", ")", ":", "array", "{", "$", "primaryKeys", "=", "[", "]", ";", "foreach", "(", "$", "table", "[", "'columns'", "]", "as", "$", "column", ")", "{", "$", "columnName", "=", "$", "column", "[", "'COLUMN_NAME'", "]", ";", "$", "columnKey", "=", "$", "column", "[", "'COLUMN_KEY'", "]", ";", "if", "(", "$", "columnKey", "!==", "'PRI'", ")", "{", "continue", ";", "}", "$", "primaryKeys", "[", "]", "=", "$", "columnName", ";", "}", "return", "$", "primaryKeys", ";", "}" ]
Collect alternate primary keys. @param array $table @return array
[ "Collect", "alternate", "primary", "keys", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Generator/PhinxMySqlGenerator.php#L394-L407
32,812
odan/phinx-migrations-generator
src/Migration/Adapter/Generator/PhinxMySqlGenerator.php
PhinxMySqlGenerator.getColumnUpdate
protected function getColumnUpdate(array $schema, string $table, string $columnName): string { $columns = $schema['tables'][$table]['columns']; $columnData = $columns[$columnName]; $phinxType = $this->getPhinxColumnType($columnData); $columnAttributes = $this->getPhinxColumnOptions($phinxType, $columnData, $columns); $result = sprintf("%s->changeColumn('%s', '%s', $columnAttributes)", $this->ind2, $columnName, $phinxType, $columnAttributes); return $result; }
php
protected function getColumnUpdate(array $schema, string $table, string $columnName): string { $columns = $schema['tables'][$table]['columns']; $columnData = $columns[$columnName]; $phinxType = $this->getPhinxColumnType($columnData); $columnAttributes = $this->getPhinxColumnOptions($phinxType, $columnData, $columns); $result = sprintf("%s->changeColumn('%s', '%s', $columnAttributes)", $this->ind2, $columnName, $phinxType, $columnAttributes); return $result; }
[ "protected", "function", "getColumnUpdate", "(", "array", "$", "schema", ",", "string", "$", "table", ",", "string", "$", "columnName", ")", ":", "string", "{", "$", "columns", "=", "$", "schema", "[", "'tables'", "]", "[", "$", "table", "]", "[", "'columns'", "]", ";", "$", "columnData", "=", "$", "columns", "[", "$", "columnName", "]", ";", "$", "phinxType", "=", "$", "this", "->", "getPhinxColumnType", "(", "$", "columnData", ")", ";", "$", "columnAttributes", "=", "$", "this", "->", "getPhinxColumnOptions", "(", "$", "phinxType", ",", "$", "columnData", ",", "$", "columns", ")", ";", "$", "result", "=", "sprintf", "(", "\"%s->changeColumn('%s', '%s', $columnAttributes)\"", ",", "$", "this", "->", "ind2", ",", "$", "columnName", ",", "$", "phinxType", ",", "$", "columnAttributes", ")", ";", "return", "$", "result", ";", "}" ]
Generate column update. @param array $schema @param string $table @param string $columnName @return string
[ "Generate", "column", "update", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Generator/PhinxMySqlGenerator.php#L1001-L1011
32,813
odan/phinx-migrations-generator
src/Migration/Adapter/Generator/PhinxMySqlGenerator.php
PhinxMySqlGenerator.getForeignKeyRuleValue
protected function getForeignKeyRuleValue(string $value): string { $value = strtolower($value); if ($value == 'no action') { return 'NO_ACTION'; } if ($value == 'cascade') { return 'CASCADE'; } if ($value == 'restrict') { return 'RESTRICT'; } if ($value == 'set null') { return 'SET_NULL'; } return 'NO_ACTION'; }
php
protected function getForeignKeyRuleValue(string $value): string { $value = strtolower($value); if ($value == 'no action') { return 'NO_ACTION'; } if ($value == 'cascade') { return 'CASCADE'; } if ($value == 'restrict') { return 'RESTRICT'; } if ($value == 'set null') { return 'SET_NULL'; } return 'NO_ACTION'; }
[ "protected", "function", "getForeignKeyRuleValue", "(", "string", "$", "value", ")", ":", "string", "{", "$", "value", "=", "strtolower", "(", "$", "value", ")", ";", "if", "(", "$", "value", "==", "'no action'", ")", "{", "return", "'NO_ACTION'", ";", "}", "if", "(", "$", "value", "==", "'cascade'", ")", "{", "return", "'CASCADE'", ";", "}", "if", "(", "$", "value", "==", "'restrict'", ")", "{", "return", "'RESTRICT'", ";", "}", "if", "(", "$", "value", "==", "'set null'", ")", "{", "return", "'SET_NULL'", ";", "}", "return", "'NO_ACTION'", ";", "}" ]
Generate foreign key rule value. @param string $value @return string
[ "Generate", "foreign", "key", "rule", "value", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Generator/PhinxMySqlGenerator.php#L1297-L1314
32,814
odan/phinx-migrations-generator
src/Migration/Adapter/Generator/PhinxMySqlGenerator.php
PhinxMySqlGenerator.prettifyArray
protected function prettifyArray(array $variable, int $tabCount): string { $encoder = new PHPEncoder(); return $encoder->encode($variable, [ 'array.base' => $tabCount * 4, 'array.inline' => true, 'array.indent' => 4, 'array.eol' => "\n", ]); }
php
protected function prettifyArray(array $variable, int $tabCount): string { $encoder = new PHPEncoder(); return $encoder->encode($variable, [ 'array.base' => $tabCount * 4, 'array.inline' => true, 'array.indent' => 4, 'array.eol' => "\n", ]); }
[ "protected", "function", "prettifyArray", "(", "array", "$", "variable", ",", "int", "$", "tabCount", ")", ":", "string", "{", "$", "encoder", "=", "new", "PHPEncoder", "(", ")", ";", "return", "$", "encoder", "->", "encode", "(", "$", "variable", ",", "[", "'array.base'", "=>", "$", "tabCount", "*", "4", ",", "'array.inline'", "=>", "true", ",", "'array.indent'", "=>", "4", ",", "'array.eol'", "=>", "\"\\n\"", ",", "]", ")", ";", "}" ]
Prettify array. @param array $variable Array to prettify @param int $tabCount Initial tab count @return string
[ "Prettify", "array", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Generator/PhinxMySqlGenerator.php#L1365-L1375
32,815
odan/phinx-migrations-generator
src/Migration/Generator/MigrationGenerator.php
MigrationGenerator.createClassName
protected function createClassName(string $name): string { $result = str_replace('_', ' ', $name); return str_replace(' ', '', ucwords($result)); }
php
protected function createClassName(string $name): string { $result = str_replace('_', ' ', $name); return str_replace(' ', '', ucwords($result)); }
[ "protected", "function", "createClassName", "(", "string", "$", "name", ")", ":", "string", "{", "$", "result", "=", "str_replace", "(", "'_'", ",", "' '", ",", "$", "name", ")", ";", "return", "str_replace", "(", "' '", ",", "''", ",", "ucwords", "(", "$", "result", ")", ")", ";", "}" ]
Create a class name. @param string $name Name @return string Class name
[ "Create", "a", "class", "name", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Generator/MigrationGenerator.php#L336-L341
32,816
odan/phinx-migrations-generator
src/Migration/Utility/ArrayUtil.php
ArrayUtil.unsetArrayKeys
public function unsetArrayKeys(array &$array, string $unwantedKey): void { unset($array[$unwantedKey]); foreach ($array as &$value) { if (is_array($value)) { $this->unsetArrayKeys($value, $unwantedKey); } } }
php
public function unsetArrayKeys(array &$array, string $unwantedKey): void { unset($array[$unwantedKey]); foreach ($array as &$value) { if (is_array($value)) { $this->unsetArrayKeys($value, $unwantedKey); } } }
[ "public", "function", "unsetArrayKeys", "(", "array", "&", "$", "array", ",", "string", "$", "unwantedKey", ")", ":", "void", "{", "unset", "(", "$", "array", "[", "$", "unwantedKey", "]", ")", ";", "foreach", "(", "$", "array", "as", "&", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "this", "->", "unsetArrayKeys", "(", "$", "value", ",", "$", "unwantedKey", ")", ";", "}", "}", "}" ]
Unset array keys. @param array $array The array @param string $unwantedKey The key to remove @return void
[ "Unset", "array", "keys", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Utility/ArrayUtil.php#L18-L27
32,817
odan/phinx-migrations-generator
src/Migration/Adapter/Database/MySqlSchemaAdapter.php
MySqlSchemaAdapter.createQueryStatement
protected function createQueryStatement(string $sql): PDOStatement { $statement = $this->pdo->query($sql); if (!$statement instanceof PDOStatement) { throw new RuntimeException('Invalid statement'); } return $statement; }
php
protected function createQueryStatement(string $sql): PDOStatement { $statement = $this->pdo->query($sql); if (!$statement instanceof PDOStatement) { throw new RuntimeException('Invalid statement'); } return $statement; }
[ "protected", "function", "createQueryStatement", "(", "string", "$", "sql", ")", ":", "PDOStatement", "{", "$", "statement", "=", "$", "this", "->", "pdo", "->", "query", "(", "$", "sql", ")", ";", "if", "(", "!", "$", "statement", "instanceof", "PDOStatement", ")", "{", "throw", "new", "RuntimeException", "(", "'Invalid statement'", ")", ";", "}", "return", "$", "statement", ";", "}" ]
Create a new PDO statement. @param string $sql The sql @return PDOStatement The statement
[ "Create", "a", "new", "PDO", "statement", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Database/MySqlSchemaAdapter.php#L68-L77
32,818
odan/phinx-migrations-generator
src/Migration/Adapter/Database/MySqlSchemaAdapter.php
MySqlSchemaAdapter.queryFetchAll
protected function queryFetchAll(string $sql): array { $statement = $this->createQueryStatement($sql); $rows = $statement->fetchAll(PDO::FETCH_ASSOC); if (!$rows) { return []; } return $rows; }
php
protected function queryFetchAll(string $sql): array { $statement = $this->createQueryStatement($sql); $rows = $statement->fetchAll(PDO::FETCH_ASSOC); if (!$rows) { return []; } return $rows; }
[ "protected", "function", "queryFetchAll", "(", "string", "$", "sql", ")", ":", "array", "{", "$", "statement", "=", "$", "this", "->", "createQueryStatement", "(", "$", "sql", ")", ";", "$", "rows", "=", "$", "statement", "->", "fetchAll", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "if", "(", "!", "$", "rows", ")", "{", "return", "[", "]", ";", "}", "return", "$", "rows", ";", "}" ]
Fetch all rows as array. @param string $sql The sql @return array The rows
[ "Fetch", "all", "rows", "as", "array", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Database/MySqlSchemaAdapter.php#L86-L96
32,819
odan/phinx-migrations-generator
src/Migration/Adapter/Database/MySqlSchemaAdapter.php
MySqlSchemaAdapter.quote
public function quote(?string $value): string { if ($value === null) { return 'NULL'; } return $this->pdo->quote($value); }
php
public function quote(?string $value): string { if ($value === null) { return 'NULL'; } return $this->pdo->quote($value); }
[ "public", "function", "quote", "(", "?", "string", "$", "value", ")", ":", "string", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", "'NULL'", ";", "}", "return", "$", "this", "->", "pdo", "->", "quote", "(", "$", "value", ")", ";", "}" ]
Quote value. @param string|null $value @return string
[ "Quote", "value", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Database/MySqlSchemaAdapter.php#L155-L162
32,820
odan/phinx-migrations-generator
src/Migration/Adapter/Database/MySqlSchemaAdapter.php
MySqlSchemaAdapter.esc
public function esc(?string $value): string { if ($value === null) { return 'NULL'; } $value = substr($this->pdo->quote($value), 1, -1); return $value; }
php
public function esc(?string $value): string { if ($value === null) { return 'NULL'; } $value = substr($this->pdo->quote($value), 1, -1); return $value; }
[ "public", "function", "esc", "(", "?", "string", "$", "value", ")", ":", "string", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", "'NULL'", ";", "}", "$", "value", "=", "substr", "(", "$", "this", "->", "pdo", "->", "quote", "(", "$", "value", ")", ",", "1", ",", "-", "1", ")", ";", "return", "$", "value", ";", "}" ]
Escape value. @param string|null $value @return string
[ "Escape", "value", "." ]
06db032b2ba0c3861361f849d1e16e6c1d6ce271
https://github.com/odan/phinx-migrations-generator/blob/06db032b2ba0c3861361f849d1e16e6c1d6ce271/src/Migration/Adapter/Database/MySqlSchemaAdapter.php#L328-L337
32,821
sobstel/sesshin
src/Session.php
Session.create
public function create() { $this->getIdHandler()->generateId(); $this->values = array(); $this->firstTrace = time(); $this->updateLastTrace(); $this->requestsCount = 1; $this->regenerationTrace = time(); $this->fingerprint = $this->generateFingerprint(); $this->opened = true; return $this->opened; }
php
public function create() { $this->getIdHandler()->generateId(); $this->values = array(); $this->firstTrace = time(); $this->updateLastTrace(); $this->requestsCount = 1; $this->regenerationTrace = time(); $this->fingerprint = $this->generateFingerprint(); $this->opened = true; return $this->opened; }
[ "public", "function", "create", "(", ")", "{", "$", "this", "->", "getIdHandler", "(", ")", "->", "generateId", "(", ")", ";", "$", "this", "->", "values", "=", "array", "(", ")", ";", "$", "this", "->", "firstTrace", "=", "time", "(", ")", ";", "$", "this", "->", "updateLastTrace", "(", ")", ";", "$", "this", "->", "requestsCount", "=", "1", ";", "$", "this", "->", "regenerationTrace", "=", "time", "(", ")", ";", "$", "this", "->", "fingerprint", "=", "$", "this", "->", "generateFingerprint", "(", ")", ";", "$", "this", "->", "opened", "=", "true", ";", "return", "$", "this", "->", "opened", ";", "}" ]
Creates new session It should be called only once at the beginning. If called for existing session it ovewrites it (clears all values etc). It can be replaced with {@link self::open()} (called with "true" argument) @return bool Session opened?
[ "Creates", "new", "session" ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L81-L98
32,822
sobstel/sesshin
src/Session.php
Session.close
public function close() { if ($this->opened) { if ($this->shouldRegenerateId()) { $this->regenerateId(); } $this->updateLastTrace(); $this->save(); $this->values = array(); $this->opened = false; } }
php
public function close() { if ($this->opened) { if ($this->shouldRegenerateId()) { $this->regenerateId(); } $this->updateLastTrace(); $this->save(); $this->values = array(); $this->opened = false; } }
[ "public", "function", "close", "(", ")", "{", "if", "(", "$", "this", "->", "opened", ")", "{", "if", "(", "$", "this", "->", "shouldRegenerateId", "(", ")", ")", "{", "$", "this", "->", "regenerateId", "(", ")", ";", "}", "$", "this", "->", "updateLastTrace", "(", ")", ";", "$", "this", "->", "save", "(", ")", ";", "$", "this", "->", "values", "=", "array", "(", ")", ";", "$", "this", "->", "opened", "=", "false", ";", "}", "}" ]
Close the session.
[ "Close", "the", "session", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L170-L183
32,823
sobstel/sesshin
src/Session.php
Session.regenerateId
public function regenerateId() { if (!$this->idRegenerated) { $this->getStore()->delete($this->getId()); $this->getIdHandler()->generateId(); $this->regenerationTrace = time(); $this->idRegenerated = true; return true; } return false; }
php
public function regenerateId() { if (!$this->idRegenerated) { $this->getStore()->delete($this->getId()); $this->getIdHandler()->generateId(); $this->regenerationTrace = time(); $this->idRegenerated = true; return true; } return false; }
[ "public", "function", "regenerateId", "(", ")", "{", "if", "(", "!", "$", "this", "->", "idRegenerated", ")", "{", "$", "this", "->", "getStore", "(", ")", "->", "delete", "(", "$", "this", "->", "getId", "(", ")", ")", ";", "$", "this", "->", "getIdHandler", "(", ")", "->", "generateId", "(", ")", ";", "$", "this", "->", "regenerationTrace", "=", "time", "(", ")", ";", "$", "this", "->", "idRegenerated", "=", "true", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Regenerates session id. Destroys current session in store and generates new id, which will be saved at the end of script execution (together with values). Id is regenerated at the most once per script execution (even if called a few times). Mitigates Session Fixation - use it whenever the user's privilege level changes.
[ "Regenerates", "session", "id", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L215-L228
32,824
sobstel/sesshin
src/Session.php
Session.getValue
public function getValue($name, $namespace = self::DEFAULT_NAMESPACE) { return isset($this->values[$namespace][$name]) ? $this->values[$namespace][$name] : null; }
php
public function getValue($name, $namespace = self::DEFAULT_NAMESPACE) { return isset($this->values[$namespace][$name]) ? $this->values[$namespace][$name] : null; }
[ "public", "function", "getValue", "(", "$", "name", ",", "$", "namespace", "=", "self", "::", "DEFAULT_NAMESPACE", ")", "{", "return", "isset", "(", "$", "this", "->", "values", "[", "$", "namespace", "]", "[", "$", "name", "]", ")", "?", "$", "this", "->", "values", "[", "$", "namespace", "]", "[", "$", "name", "]", ":", "null", ";", "}" ]
Gets session value from given or default namespace @param string $name @param string $namespace @return mixed
[ "Gets", "session", "value", "from", "given", "or", "default", "namespace" ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L412-L415
32,825
sobstel/sesshin
src/Session.php
Session.load
protected function load() { $id = $this->getId(); $values = $this->getStore()->fetch($id); if ($values === false) { return false; } // metadata $metadata = $values[self::METADATA_NAMESPACE]; $this->firstTrace = $metadata['firstTrace']; $this->lastTrace = $metadata['lastTrace']; $this->regenerationTrace = $metadata['regenerationTrace']; $this->requestsCount = $metadata['requestsCount']; $this->fingerprint = $metadata['fingerprint']; // values $this->values = $values; return true; }
php
protected function load() { $id = $this->getId(); $values = $this->getStore()->fetch($id); if ($values === false) { return false; } // metadata $metadata = $values[self::METADATA_NAMESPACE]; $this->firstTrace = $metadata['firstTrace']; $this->lastTrace = $metadata['lastTrace']; $this->regenerationTrace = $metadata['regenerationTrace']; $this->requestsCount = $metadata['requestsCount']; $this->fingerprint = $metadata['fingerprint']; // values $this->values = $values; return true; }
[ "protected", "function", "load", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getId", "(", ")", ";", "$", "values", "=", "$", "this", "->", "getStore", "(", ")", "->", "fetch", "(", "$", "id", ")", ";", "if", "(", "$", "values", "===", "false", ")", "{", "return", "false", ";", "}", "// metadata", "$", "metadata", "=", "$", "values", "[", "self", "::", "METADATA_NAMESPACE", "]", ";", "$", "this", "->", "firstTrace", "=", "$", "metadata", "[", "'firstTrace'", "]", ";", "$", "this", "->", "lastTrace", "=", "$", "metadata", "[", "'lastTrace'", "]", ";", "$", "this", "->", "regenerationTrace", "=", "$", "metadata", "[", "'regenerationTrace'", "]", ";", "$", "this", "->", "requestsCount", "=", "$", "metadata", "[", "'requestsCount'", "]", ";", "$", "this", "->", "fingerprint", "=", "$", "metadata", "[", "'fingerprint'", "]", ";", "// values", "$", "this", "->", "values", "=", "$", "values", ";", "return", "true", ";", "}" ]
Loads session data from defined store. @return bool
[ "Loads", "session", "data", "from", "defined", "store", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L514-L535
32,826
sobstel/sesshin
src/Session.php
Session.save
protected function save() { $this->flash()->ageFlashData(); $values = $this->values; $values[self::METADATA_NAMESPACE] = [ 'firstTrace' => $this->getFirstTrace(), 'lastTrace' => $this->getLastTrace(), 'regenerationTrace' => $this->getRegenerationTrace(), 'requestsCount' => $this->getRequestsCount(), 'fingerprint' => $this->getFingerprint(), ]; return $this->getStore()->save($this->getId(), $values, $this->ttl); }
php
protected function save() { $this->flash()->ageFlashData(); $values = $this->values; $values[self::METADATA_NAMESPACE] = [ 'firstTrace' => $this->getFirstTrace(), 'lastTrace' => $this->getLastTrace(), 'regenerationTrace' => $this->getRegenerationTrace(), 'requestsCount' => $this->getRequestsCount(), 'fingerprint' => $this->getFingerprint(), ]; return $this->getStore()->save($this->getId(), $values, $this->ttl); }
[ "protected", "function", "save", "(", ")", "{", "$", "this", "->", "flash", "(", ")", "->", "ageFlashData", "(", ")", ";", "$", "values", "=", "$", "this", "->", "values", ";", "$", "values", "[", "self", "::", "METADATA_NAMESPACE", "]", "=", "[", "'firstTrace'", "=>", "$", "this", "->", "getFirstTrace", "(", ")", ",", "'lastTrace'", "=>", "$", "this", "->", "getLastTrace", "(", ")", ",", "'regenerationTrace'", "=>", "$", "this", "->", "getRegenerationTrace", "(", ")", ",", "'requestsCount'", "=>", "$", "this", "->", "getRequestsCount", "(", ")", ",", "'fingerprint'", "=>", "$", "this", "->", "getFingerprint", "(", ")", ",", "]", ";", "return", "$", "this", "->", "getStore", "(", ")", "->", "save", "(", "$", "this", "->", "getId", "(", ")", ",", "$", "values", ",", "$", "this", "->", "ttl", ")", ";", "}" ]
Saves session data into defined store. @return bool
[ "Saves", "session", "data", "into", "defined", "store", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L542-L557
32,827
sobstel/sesshin
src/Session.php
Session.push
public function push($key, $value) { $array = $this->getValue($key); $array[] = $value; $this->setValue($key, $array); }
php
public function push($key, $value) { $array = $this->getValue($key); $array[] = $value; $this->setValue($key, $array); }
[ "public", "function", "push", "(", "$", "key", ",", "$", "value", ")", "{", "$", "array", "=", "$", "this", "->", "getValue", "(", "$", "key", ")", ";", "$", "array", "[", "]", "=", "$", "value", ";", "$", "this", "->", "setValue", "(", "$", "key", ",", "$", "array", ")", ";", "}" ]
Push a value onto a session array. @param string $key @param mixed $value @return void
[ "Push", "a", "value", "onto", "a", "session", "array", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L585-L590
32,828
sobstel/sesshin
src/Session.php
Session.flash
public function flash() { if (is_null($this->flash)) { $this->flash = new SessionFlash($this); } return $this->flash; }
php
public function flash() { if (is_null($this->flash)) { $this->flash = new SessionFlash($this); } return $this->flash; }
[ "public", "function", "flash", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "flash", ")", ")", "{", "$", "this", "->", "flash", "=", "new", "SessionFlash", "(", "$", "this", ")", ";", "}", "return", "$", "this", "->", "flash", ";", "}" ]
Call the flash session handler. @return SessionFlash
[ "Call", "the", "flash", "session", "handler", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/Session.php#L614-L621
32,829
sobstel/sesshin
src/SessionFlash.php
SessionFlash.getCurrentData
public function getCurrentData() { $current_data = $this->session->getValue($this->key_name); return isset($current_data) ? $current_data : $current_data = array(); }
php
public function getCurrentData() { $current_data = $this->session->getValue($this->key_name); return isset($current_data) ? $current_data : $current_data = array(); }
[ "public", "function", "getCurrentData", "(", ")", "{", "$", "current_data", "=", "$", "this", "->", "session", "->", "getValue", "(", "$", "this", "->", "key_name", ")", ";", "return", "isset", "(", "$", "current_data", ")", "?", "$", "current_data", ":", "$", "current_data", "=", "array", "(", ")", ";", "}" ]
Get all the data or data of a type. @return mixed
[ "Get", "all", "the", "data", "or", "data", "of", "a", "type", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/SessionFlash.php#L103-L108
32,830
sobstel/sesshin
src/SessionFlash.php
SessionFlash.reflash
public function reflash() { $this->mergeNewFlashes($this->session->getValue($this->key_name.'.old')); $this->session->setValue($this->key_name.'.old', []); }
php
public function reflash() { $this->mergeNewFlashes($this->session->getValue($this->key_name.'.old')); $this->session->setValue($this->key_name.'.old', []); }
[ "public", "function", "reflash", "(", ")", "{", "$", "this", "->", "mergeNewFlashes", "(", "$", "this", "->", "session", "->", "getValue", "(", "$", "this", "->", "key_name", ".", "'.old'", ")", ")", ";", "$", "this", "->", "session", "->", "setValue", "(", "$", "this", "->", "key_name", ".", "'.old'", ",", "[", "]", ")", ";", "}" ]
Reflash all of the session flash data. @return void
[ "Reflash", "all", "of", "the", "session", "flash", "data", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/SessionFlash.php#L115-L119
32,831
sobstel/sesshin
src/SessionFlash.php
SessionFlash.removeFromOldFlashData
protected function removeFromOldFlashData(array $keys) { $old_data = $this->session->getValue($this->key_name.'.old'); if (! is_array($old_data)) { $old_data = array(); } $this->session->setValue($this->key_name.'.old', array_diff($old_data, $keys)); }
php
protected function removeFromOldFlashData(array $keys) { $old_data = $this->session->getValue($this->key_name.'.old'); if (! is_array($old_data)) { $old_data = array(); } $this->session->setValue($this->key_name.'.old', array_diff($old_data, $keys)); }
[ "protected", "function", "removeFromOldFlashData", "(", "array", "$", "keys", ")", "{", "$", "old_data", "=", "$", "this", "->", "session", "->", "getValue", "(", "$", "this", "->", "key_name", ".", "'.old'", ")", ";", "if", "(", "!", "is_array", "(", "$", "old_data", ")", ")", "{", "$", "old_data", "=", "array", "(", ")", ";", "}", "$", "this", "->", "session", "->", "setValue", "(", "$", "this", "->", "key_name", ".", "'.old'", ",", "array_diff", "(", "$", "old_data", ",", "$", "keys", ")", ")", ";", "}" ]
Remove the given keys from the old flash data. @param array $keys @return void
[ "Remove", "the", "given", "keys", "from", "the", "old", "flash", "data", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/SessionFlash.php#L153-L161
32,832
sobstel/sesshin
src/SessionFlash.php
SessionFlash.singleton
static function singleton(Session $session = null) { if (self::$singleton == null) { self::$singleton = new SessionFlash($session); } return self::$singleton; }
php
static function singleton(Session $session = null) { if (self::$singleton == null) { self::$singleton = new SessionFlash($session); } return self::$singleton; }
[ "static", "function", "singleton", "(", "Session", "$", "session", "=", "null", ")", "{", "if", "(", "self", "::", "$", "singleton", "==", "null", ")", "{", "self", "::", "$", "singleton", "=", "new", "SessionFlash", "(", "$", "session", ")", ";", "}", "return", "self", "::", "$", "singleton", ";", "}" ]
Calling this class in a singleton way. @param Session|null $session @return SessionFlash
[ "Calling", "this", "class", "in", "a", "singleton", "way", "." ]
ed95c8128edd31cceb7c440bf9accea6d4a83ad3
https://github.com/sobstel/sesshin/blob/ed95c8128edd31cceb7c440bf9accea6d4a83ad3/src/SessionFlash.php#L196-L203
32,833
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.call
public function call($resource, $args = array()) { $headers = array('Content-Type: application/json'); $payload = json_encode(array( 'call' => $resource, 'args' => $args, )); $statusCode = null; try { $result = json_decode( $this->oauthRequest( $this->apiEndpointUrl, $payload, $this->getAccessToken(), $headers, $statusCode ), true ); } catch (DailymotionAuthException $e) { if ($e->error === 'invalid_token') { // Retry by forcing the refresh of the access token $result = json_decode( $this->oauthRequest( $this->apiEndpointUrl, $payload, $this->getAccessToken(true), $headers, $statusCode ), true ); } else { throw $e; } } if (empty($result)) { throw new DailymotionApiException('Invalid API server response'); } elseif ($statusCode !== 200) { throw new DailymotionApiException("Unknown error: {$statusCode}", $statusCode); } elseif (is_array($result) && isset($result['error'])) { $message = isset($result['error']['message']) ? $result['error']['message'] : null; $code = isset($result['error']['code']) ? $result['error']['code'] : null; if ($code === 403) { throw new DailymotionAuthRequiredException($message, $code); } else { throw new DailymotionApiException($message, $code); } } elseif (!isset($result['result'])) { throw new DailymotionApiException("Invalid API server response: no `result` key found."); } return $result['result']; }
php
public function call($resource, $args = array()) { $headers = array('Content-Type: application/json'); $payload = json_encode(array( 'call' => $resource, 'args' => $args, )); $statusCode = null; try { $result = json_decode( $this->oauthRequest( $this->apiEndpointUrl, $payload, $this->getAccessToken(), $headers, $statusCode ), true ); } catch (DailymotionAuthException $e) { if ($e->error === 'invalid_token') { // Retry by forcing the refresh of the access token $result = json_decode( $this->oauthRequest( $this->apiEndpointUrl, $payload, $this->getAccessToken(true), $headers, $statusCode ), true ); } else { throw $e; } } if (empty($result)) { throw new DailymotionApiException('Invalid API server response'); } elseif ($statusCode !== 200) { throw new DailymotionApiException("Unknown error: {$statusCode}", $statusCode); } elseif (is_array($result) && isset($result['error'])) { $message = isset($result['error']['message']) ? $result['error']['message'] : null; $code = isset($result['error']['code']) ? $result['error']['code'] : null; if ($code === 403) { throw new DailymotionAuthRequiredException($message, $code); } else { throw new DailymotionApiException($message, $code); } } elseif (!isset($result['result'])) { throw new DailymotionApiException("Invalid API server response: no `result` key found."); } return $result['result']; }
[ "public", "function", "call", "(", "$", "resource", ",", "$", "args", "=", "array", "(", ")", ")", "{", "$", "headers", "=", "array", "(", "'Content-Type: application/json'", ")", ";", "$", "payload", "=", "json_encode", "(", "array", "(", "'call'", "=>", "$", "resource", ",", "'args'", "=>", "$", "args", ",", ")", ")", ";", "$", "statusCode", "=", "null", ";", "try", "{", "$", "result", "=", "json_decode", "(", "$", "this", "->", "oauthRequest", "(", "$", "this", "->", "apiEndpointUrl", ",", "$", "payload", ",", "$", "this", "->", "getAccessToken", "(", ")", ",", "$", "headers", ",", "$", "statusCode", ")", ",", "true", ")", ";", "}", "catch", "(", "DailymotionAuthException", "$", "e", ")", "{", "if", "(", "$", "e", "->", "error", "===", "'invalid_token'", ")", "{", "// Retry by forcing the refresh of the access token", "$", "result", "=", "json_decode", "(", "$", "this", "->", "oauthRequest", "(", "$", "this", "->", "apiEndpointUrl", ",", "$", "payload", ",", "$", "this", "->", "getAccessToken", "(", "true", ")", ",", "$", "headers", ",", "$", "statusCode", ")", ",", "true", ")", ";", "}", "else", "{", "throw", "$", "e", ";", "}", "}", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "throw", "new", "DailymotionApiException", "(", "'Invalid API server response'", ")", ";", "}", "elseif", "(", "$", "statusCode", "!==", "200", ")", "{", "throw", "new", "DailymotionApiException", "(", "\"Unknown error: {$statusCode}\"", ",", "$", "statusCode", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "result", ")", "&&", "isset", "(", "$", "result", "[", "'error'", "]", ")", ")", "{", "$", "message", "=", "isset", "(", "$", "result", "[", "'error'", "]", "[", "'message'", "]", ")", "?", "$", "result", "[", "'error'", "]", "[", "'message'", "]", ":", "null", ";", "$", "code", "=", "isset", "(", "$", "result", "[", "'error'", "]", "[", "'code'", "]", ")", "?", "$", "result", "[", "'error'", "]", "[", "'code'", "]", ":", "null", ";", "if", "(", "$", "code", "===", "403", ")", "{", "throw", "new", "DailymotionAuthRequiredException", "(", "$", "message", ",", "$", "code", ")", ";", "}", "else", "{", "throw", "new", "DailymotionApiException", "(", "$", "message", ",", "$", "code", ")", ";", "}", "}", "elseif", "(", "!", "isset", "(", "$", "result", "[", "'result'", "]", ")", ")", "{", "throw", "new", "DailymotionApiException", "(", "\"Invalid API server response: no `result` key found.\"", ")", ";", "}", "return", "$", "result", "[", "'result'", "]", ";", "}" ]
Call a remote endpoint on the API. @param string $resource API endpoint to call. @param array $args Associative array of arguments. @throws DailymotionApiException If the API itself returned an error. @throws DailymotionAuthException If we can't authenticate the request. @throws DailymotionAuthRequiredException If no authentication info is available. @throws DailymotionTransportException If a network error occurs during the request. @return mixed Endpoint call response
[ "Call", "a", "remote", "endpoint", "on", "the", "API", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L390-L459
32,834
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.getSession
public function getSession() { if (empty($this->session)) { $this->session = $this->readSession(); } return $this->session; }
php
public function getSession() { if (empty($this->session)) { $this->session = $this->readSession(); } return $this->session; }
[ "public", "function", "getSession", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "session", ")", ")", "{", "$", "this", "->", "session", "=", "$", "this", "->", "readSession", "(", ")", ";", "}", "return", "$", "this", "->", "session", ";", "}" ]
Get the session if any. @return array Current session or an empty array if none found.
[ "Get", "the", "session", "if", "any", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L625-L632
32,835
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.readSession
protected function readSession() { $session = array(); $cookieName = sprintf(self::SESSION_COOKIE, $this->grantInfo['key']); $cookieValue = filter_input(INPUT_COOKIE, $cookieName); if (!empty($cookieValue)) { parse_str( trim((get_magic_quotes_gpc() ? stripslashes($cookieValue) : $cookieValue), '"'), $session ); } return $session; }
php
protected function readSession() { $session = array(); $cookieName = sprintf(self::SESSION_COOKIE, $this->grantInfo['key']); $cookieValue = filter_input(INPUT_COOKIE, $cookieName); if (!empty($cookieValue)) { parse_str( trim((get_magic_quotes_gpc() ? stripslashes($cookieValue) : $cookieValue), '"'), $session ); } return $session; }
[ "protected", "function", "readSession", "(", ")", "{", "$", "session", "=", "array", "(", ")", ";", "$", "cookieName", "=", "sprintf", "(", "self", "::", "SESSION_COOKIE", ",", "$", "this", "->", "grantInfo", "[", "'key'", "]", ")", ";", "$", "cookieValue", "=", "filter_input", "(", "INPUT_COOKIE", ",", "$", "cookieName", ")", ";", "if", "(", "!", "empty", "(", "$", "cookieValue", ")", ")", "{", "parse_str", "(", "trim", "(", "(", "get_magic_quotes_gpc", "(", ")", "?", "stripslashes", "(", "$", "cookieValue", ")", ":", "$", "cookieValue", ")", ",", "'\"'", ")", ",", "$", "session", ")", ";", "}", "return", "$", "session", ";", "}" ]
Read the session from the session store. Default storage is cookie, subclass can implement another storage type if needed. Information stored in the session are useless without the API secret. Storing these information on the client should thus be safe as long as the API secret is kept... secret. @return array Stored session or an empty array if none found.
[ "Read", "the", "session", "from", "the", "session", "store", ".", "Default", "storage", "is", "cookie", "subclass", "can", "implement", "another", "storage", "type", "if", "needed", ".", "Information", "stored", "in", "the", "session", "are", "useless", "without", "the", "API", "secret", ".", "Storing", "these", "information", "on", "the", "client", "should", "thus", "be", "safe", "as", "long", "as", "the", "API", "secret", "is", "kept", "...", "secret", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L652-L666
32,836
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.storeSession
protected function storeSession(array $session = array()) { if (headers_sent()) { if (php_sapi_name() !== 'cli') { error_log('Could not set session in cookie: headers already sent.'); } return $this; } $cookieName = sprintf(self::SESSION_COOKIE, $this->grantInfo['key']); if (!empty($session)) { $value = '"' . http_build_query($session, null, '&') . '"'; $expires = time() + $this->cookieLifeTime; } else { $cookieValue = filter_input(INPUT_COOKIE, $cookieName); if (empty($cookieValue)) { // No need to remove an unexisting cookie return $this; } $value = 'deleted'; $expires = time() - 3600; } setcookie($cookieName, $value, $expires, '/', $this->cookieDomain); return $this; }
php
protected function storeSession(array $session = array()) { if (headers_sent()) { if (php_sapi_name() !== 'cli') { error_log('Could not set session in cookie: headers already sent.'); } return $this; } $cookieName = sprintf(self::SESSION_COOKIE, $this->grantInfo['key']); if (!empty($session)) { $value = '"' . http_build_query($session, null, '&') . '"'; $expires = time() + $this->cookieLifeTime; } else { $cookieValue = filter_input(INPUT_COOKIE, $cookieName); if (empty($cookieValue)) { // No need to remove an unexisting cookie return $this; } $value = 'deleted'; $expires = time() - 3600; } setcookie($cookieName, $value, $expires, '/', $this->cookieDomain); return $this; }
[ "protected", "function", "storeSession", "(", "array", "$", "session", "=", "array", "(", ")", ")", "{", "if", "(", "headers_sent", "(", ")", ")", "{", "if", "(", "php_sapi_name", "(", ")", "!==", "'cli'", ")", "{", "error_log", "(", "'Could not set session in cookie: headers already sent.'", ")", ";", "}", "return", "$", "this", ";", "}", "$", "cookieName", "=", "sprintf", "(", "self", "::", "SESSION_COOKIE", ",", "$", "this", "->", "grantInfo", "[", "'key'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "session", ")", ")", "{", "$", "value", "=", "'\"'", ".", "http_build_query", "(", "$", "session", ",", "null", ",", "'&'", ")", ".", "'\"'", ";", "$", "expires", "=", "time", "(", ")", "+", "$", "this", "->", "cookieLifeTime", ";", "}", "else", "{", "$", "cookieValue", "=", "filter_input", "(", "INPUT_COOKIE", ",", "$", "cookieName", ")", ";", "if", "(", "empty", "(", "$", "cookieValue", ")", ")", "{", "// No need to remove an unexisting cookie", "return", "$", "this", ";", "}", "$", "value", "=", "'deleted'", ";", "$", "expires", "=", "time", "(", ")", "-", "3600", ";", "}", "setcookie", "(", "$", "cookieName", ",", "$", "value", ",", "$", "expires", ",", "'/'", ",", "$", "this", "->", "cookieDomain", ")", ";", "return", "$", "this", ";", "}" ]
Store the given session to the session store. Default storage is cookie, subclass can implement another storage type if needed. Information stored in the session are useless without the API secret. Storing these information on the client should thus be safe as long as the API secret is kept... secret. @param array $session Session to store, if nothing is passed, the current session is removed from the session store. @return Dailymotion `$this`
[ "Store", "the", "given", "session", "to", "the", "session", "store", ".", "Default", "storage", "is", "cookie", "subclass", "can", "implement", "another", "storage", "type", "if", "needed", ".", "Information", "stored", "in", "the", "session", "are", "useless", "without", "the", "API", "secret", ".", "Storing", "these", "information", "on", "the", "client", "should", "thus", "be", "safe", "as", "long", "as", "the", "API", "secret", "is", "kept", "...", "secret", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L677-L706
32,837
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.oauthTokenRequest
protected function oauthTokenRequest(array $args) { $statusCode = null; $responseHeaders = array(); $result = json_decode( $response = $this->httpRequest( $this->oauthTokenEndpointUrl, $args, null, $statusCode, $responseHeaders, true ), true ); if (empty($result)) { throw new DailymotionAuthException("Invalid token server response: {$response}"); } elseif (isset($result['error'])) { $message = isset($result['error_description']) ? $result['error_description'] : null; $e = new DailymotionAuthException($message); $e->error = $result['error']; throw $e; } elseif (isset($result['access_token'])) { return array( 'access_token' => $result['access_token'], 'expires' => time() + $result['expires_in'], 'refresh_token' => isset($result['refresh_token']) ? $result['refresh_token'] : null, 'scope' => isset($result['scope']) ? explode(chr(32), $result['scope']) : array(), ); } else { throw new DailymotionAuthException('No access token found in the token server response'); } }
php
protected function oauthTokenRequest(array $args) { $statusCode = null; $responseHeaders = array(); $result = json_decode( $response = $this->httpRequest( $this->oauthTokenEndpointUrl, $args, null, $statusCode, $responseHeaders, true ), true ); if (empty($result)) { throw new DailymotionAuthException("Invalid token server response: {$response}"); } elseif (isset($result['error'])) { $message = isset($result['error_description']) ? $result['error_description'] : null; $e = new DailymotionAuthException($message); $e->error = $result['error']; throw $e; } elseif (isset($result['access_token'])) { return array( 'access_token' => $result['access_token'], 'expires' => time() + $result['expires_in'], 'refresh_token' => isset($result['refresh_token']) ? $result['refresh_token'] : null, 'scope' => isset($result['scope']) ? explode(chr(32), $result['scope']) : array(), ); } else { throw new DailymotionAuthException('No access token found in the token server response'); } }
[ "protected", "function", "oauthTokenRequest", "(", "array", "$", "args", ")", "{", "$", "statusCode", "=", "null", ";", "$", "responseHeaders", "=", "array", "(", ")", ";", "$", "result", "=", "json_decode", "(", "$", "response", "=", "$", "this", "->", "httpRequest", "(", "$", "this", "->", "oauthTokenEndpointUrl", ",", "$", "args", ",", "null", ",", "$", "statusCode", ",", "$", "responseHeaders", ",", "true", ")", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "throw", "new", "DailymotionAuthException", "(", "\"Invalid token server response: {$response}\"", ")", ";", "}", "elseif", "(", "isset", "(", "$", "result", "[", "'error'", "]", ")", ")", "{", "$", "message", "=", "isset", "(", "$", "result", "[", "'error_description'", "]", ")", "?", "$", "result", "[", "'error_description'", "]", ":", "null", ";", "$", "e", "=", "new", "DailymotionAuthException", "(", "$", "message", ")", ";", "$", "e", "->", "error", "=", "$", "result", "[", "'error'", "]", ";", "throw", "$", "e", ";", "}", "elseif", "(", "isset", "(", "$", "result", "[", "'access_token'", "]", ")", ")", "{", "return", "array", "(", "'access_token'", "=>", "$", "result", "[", "'access_token'", "]", ",", "'expires'", "=>", "time", "(", ")", "+", "$", "result", "[", "'expires_in'", "]", ",", "'refresh_token'", "=>", "isset", "(", "$", "result", "[", "'refresh_token'", "]", ")", "?", "$", "result", "[", "'refresh_token'", "]", ":", "null", ",", "'scope'", "=>", "isset", "(", "$", "result", "[", "'scope'", "]", ")", "?", "explode", "(", "chr", "(", "32", ")", ",", "$", "result", "[", "'scope'", "]", ")", ":", "array", "(", ")", ",", ")", ";", "}", "else", "{", "throw", "new", "DailymotionAuthException", "(", "'No access token found in the token server response'", ")", ";", "}", "}" ]
Perform a request to a token server complient with the OAuth 2.0 specification. @param array $args Arguments to send to the token server. @throws DailymotionAuthException If the token server sends an error or invalid response. @return array Cconfigured session.
[ "Perform", "a", "request", "to", "a", "token", "server", "complient", "with", "the", "OAuth", "2", ".", "0", "specification", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L715-L754
32,838
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.oauthRequest
protected function oauthRequest($url, $payload, $accessToken = null, $headers = array(), &$statusCode = null, &$responseHeaders = array()) { if ($accessToken !== null) { $headers[] = "Authorization: Bearer {$accessToken}"; } $result = $this->httpRequest( $url, $payload, $headers, $statusCode, $responseHeaders ); switch ($statusCode) { case 401: // Invalid or expired token case 400: // Invalid request case 403: // Insufficient scope $error = null; $message = null; $match = array(); if (preg_match('/error="(.*?)"(?:, error_description="(.*?)")?/', $responseHeaders['www-authenticate'], $match)) { $error = $match[1]; $message = $match[2]; } $e = new DailymotionAuthException($message); $e->error = $error; throw $e; } return $result; }
php
protected function oauthRequest($url, $payload, $accessToken = null, $headers = array(), &$statusCode = null, &$responseHeaders = array()) { if ($accessToken !== null) { $headers[] = "Authorization: Bearer {$accessToken}"; } $result = $this->httpRequest( $url, $payload, $headers, $statusCode, $responseHeaders ); switch ($statusCode) { case 401: // Invalid or expired token case 400: // Invalid request case 403: // Insufficient scope $error = null; $message = null; $match = array(); if (preg_match('/error="(.*?)"(?:, error_description="(.*?)")?/', $responseHeaders['www-authenticate'], $match)) { $error = $match[1]; $message = $match[2]; } $e = new DailymotionAuthException($message); $e->error = $error; throw $e; } return $result; }
[ "protected", "function", "oauthRequest", "(", "$", "url", ",", "$", "payload", ",", "$", "accessToken", "=", "null", ",", "$", "headers", "=", "array", "(", ")", ",", "&", "$", "statusCode", "=", "null", ",", "&", "$", "responseHeaders", "=", "array", "(", ")", ")", "{", "if", "(", "$", "accessToken", "!==", "null", ")", "{", "$", "headers", "[", "]", "=", "\"Authorization: Bearer {$accessToken}\"", ";", "}", "$", "result", "=", "$", "this", "->", "httpRequest", "(", "$", "url", ",", "$", "payload", ",", "$", "headers", ",", "$", "statusCode", ",", "$", "responseHeaders", ")", ";", "switch", "(", "$", "statusCode", ")", "{", "case", "401", ":", "// Invalid or expired token", "case", "400", ":", "// Invalid request", "case", "403", ":", "// Insufficient scope", "$", "error", "=", "null", ";", "$", "message", "=", "null", ";", "$", "match", "=", "array", "(", ")", ";", "if", "(", "preg_match", "(", "'/error=\"(.*?)\"(?:, error_description=\"(.*?)\")?/'", ",", "$", "responseHeaders", "[", "'www-authenticate'", "]", ",", "$", "match", ")", ")", "{", "$", "error", "=", "$", "match", "[", "1", "]", ";", "$", "message", "=", "$", "match", "[", "2", "]", ";", "}", "$", "e", "=", "new", "DailymotionAuthException", "(", "$", "message", ")", ";", "$", "e", "->", "error", "=", "$", "error", ";", "throw", "$", "e", ";", "}", "return", "$", "result", ";", "}" ]
Perform an OAuth 2.0 authenticated request. @param string $url the URL to perform the HTTP request to. @param string $payload Encoded method request to POST. @param string $accessToken OAuth access token to authenticate the request with. @param array $headers List of headers to send with the request (format `array('Header-Name: header value')`). @param int &$statusCode Reference variable to store the response status code. @param array &$responseHeaders Reference variable to store the response headers. @throws DailymotionAuthException If an OAuth error occurs. @throws DailymotionTransportException If a network error occurs during the request. @return string Response body.
[ "Perform", "an", "OAuth", "2", ".", "0", "authenticated", "request", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L771-L803
32,839
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.httpRequest
protected function httpRequest($url, $payload, $headers = null, &$statusCode = null, &$responseHeaders = array(), $encodePayload = false) { $payload = (is_array($payload) && (true === $encodePayload)) ? http_build_query($payload, null, '&') : $payload; // Force removal of the Expect: 100-continue header automatically added by cURL $headers[] = 'Expect:'; // cURL options $options = array( CURLOPT_CONNECTTIMEOUT => $this->connectionTimeout, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_PROXY => $this->proxy, CURLOPT_PROXYUSERPWD => $this->proxyCredentials, CURLOPT_USERAGENT => sprintf('Dailymotion-PHP/%s (PHP %s; %s)', self::VERSION, PHP_VERSION, php_sapi_name()), CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $payload, CURLOPT_NOPROGRESS => !($this->debug && is_array($payload) && array_key_exists('file', $payload)), ); // There is no constructor to this class and I don't intend to add one just for this (PHP 4 legacy and all). if (is_null($this->followRedirects)) { // We use filter_var() here because depending on PHP's version, these ini_get() may or may not return: // true/false or even the strings 'on', 'off', 'true' or 'false' or folder paths... better safe than sorry. $this->followRedirects = (false === filter_var(ini_get('open_basedir'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) && (false === filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)); } // If the current server supports it, we follow redirects if ($this->followRedirects === true) { $options[CURLOPT_FOLLOWLOCATION] = true; $options[CURLOPT_MAXREDIRS] = self::CURLOPT_MAXREDIRS; } $this->debugRequest($url, $payload, $headers); // Execute the cURL request $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); // CURLE_SSL_CACERT error if (curl_errno($ch) == 60) { error_log('Invalid or no certificate authority found, using bundled information'); curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/dm_ca_chain_bundle.crt'); $response = curl_exec($ch); } // Invalid empty response if ($response === false) { $e = new DailymotionTransportException(curl_error($ch), curl_errno($ch)); curl_close($ch); throw $e; } $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); list($responseHeadersString, $payload) = explode("\r\n\r\n", $response, 2); strtok($responseHeadersString, "\r\n"); // skip status code while(($name = trim(strtok(":"))) && ($value = trim(strtok("\r\n")))) { $responseHeaders[strtolower($name)] = (isset($responseHeaders[$name]) ? $responseHeaders[$name] . '; ' : null) . $value; } $this->debugResponse($url, $payload, $responseHeaders); return $payload; }
php
protected function httpRequest($url, $payload, $headers = null, &$statusCode = null, &$responseHeaders = array(), $encodePayload = false) { $payload = (is_array($payload) && (true === $encodePayload)) ? http_build_query($payload, null, '&') : $payload; // Force removal of the Expect: 100-continue header automatically added by cURL $headers[] = 'Expect:'; // cURL options $options = array( CURLOPT_CONNECTTIMEOUT => $this->connectionTimeout, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_PROXY => $this->proxy, CURLOPT_PROXYUSERPWD => $this->proxyCredentials, CURLOPT_USERAGENT => sprintf('Dailymotion-PHP/%s (PHP %s; %s)', self::VERSION, PHP_VERSION, php_sapi_name()), CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $payload, CURLOPT_NOPROGRESS => !($this->debug && is_array($payload) && array_key_exists('file', $payload)), ); // There is no constructor to this class and I don't intend to add one just for this (PHP 4 legacy and all). if (is_null($this->followRedirects)) { // We use filter_var() here because depending on PHP's version, these ini_get() may or may not return: // true/false or even the strings 'on', 'off', 'true' or 'false' or folder paths... better safe than sorry. $this->followRedirects = (false === filter_var(ini_get('open_basedir'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) && (false === filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)); } // If the current server supports it, we follow redirects if ($this->followRedirects === true) { $options[CURLOPT_FOLLOWLOCATION] = true; $options[CURLOPT_MAXREDIRS] = self::CURLOPT_MAXREDIRS; } $this->debugRequest($url, $payload, $headers); // Execute the cURL request $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); // CURLE_SSL_CACERT error if (curl_errno($ch) == 60) { error_log('Invalid or no certificate authority found, using bundled information'); curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/dm_ca_chain_bundle.crt'); $response = curl_exec($ch); } // Invalid empty response if ($response === false) { $e = new DailymotionTransportException(curl_error($ch), curl_errno($ch)); curl_close($ch); throw $e; } $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); list($responseHeadersString, $payload) = explode("\r\n\r\n", $response, 2); strtok($responseHeadersString, "\r\n"); // skip status code while(($name = trim(strtok(":"))) && ($value = trim(strtok("\r\n")))) { $responseHeaders[strtolower($name)] = (isset($responseHeaders[$name]) ? $responseHeaders[$name] . '; ' : null) . $value; } $this->debugResponse($url, $payload, $responseHeaders); return $payload; }
[ "protected", "function", "httpRequest", "(", "$", "url", ",", "$", "payload", ",", "$", "headers", "=", "null", ",", "&", "$", "statusCode", "=", "null", ",", "&", "$", "responseHeaders", "=", "array", "(", ")", ",", "$", "encodePayload", "=", "false", ")", "{", "$", "payload", "=", "(", "is_array", "(", "$", "payload", ")", "&&", "(", "true", "===", "$", "encodePayload", ")", ")", "?", "http_build_query", "(", "$", "payload", ",", "null", ",", "'&'", ")", ":", "$", "payload", ";", "// Force removal of the Expect: 100-continue header automatically added by cURL", "$", "headers", "[", "]", "=", "'Expect:'", ";", "// cURL options", "$", "options", "=", "array", "(", "CURLOPT_CONNECTTIMEOUT", "=>", "$", "this", "->", "connectionTimeout", ",", "CURLOPT_TIMEOUT", "=>", "$", "this", "->", "timeout", ",", "CURLOPT_PROXY", "=>", "$", "this", "->", "proxy", ",", "CURLOPT_PROXYUSERPWD", "=>", "$", "this", "->", "proxyCredentials", ",", "CURLOPT_USERAGENT", "=>", "sprintf", "(", "'Dailymotion-PHP/%s (PHP %s; %s)'", ",", "self", "::", "VERSION", ",", "PHP_VERSION", ",", "php_sapi_name", "(", ")", ")", ",", "CURLOPT_HEADER", "=>", "true", ",", "CURLOPT_RETURNTRANSFER", "=>", "true", ",", "CURLOPT_URL", "=>", "$", "url", ",", "CURLOPT_HTTPHEADER", "=>", "$", "headers", ",", "CURLOPT_POSTFIELDS", "=>", "$", "payload", ",", "CURLOPT_NOPROGRESS", "=>", "!", "(", "$", "this", "->", "debug", "&&", "is_array", "(", "$", "payload", ")", "&&", "array_key_exists", "(", "'file'", ",", "$", "payload", ")", ")", ",", ")", ";", "// There is no constructor to this class and I don't intend to add one just for this (PHP 4 legacy and all).", "if", "(", "is_null", "(", "$", "this", "->", "followRedirects", ")", ")", "{", "// We use filter_var() here because depending on PHP's version, these ini_get() may or may not return:", "// true/false or even the strings 'on', 'off', 'true' or 'false' or folder paths... better safe than sorry.", "$", "this", "->", "followRedirects", "=", "(", "false", "===", "filter_var", "(", "ini_get", "(", "'open_basedir'", ")", ",", "FILTER_VALIDATE_BOOLEAN", ",", "FILTER_NULL_ON_FAILURE", ")", ")", "&&", "(", "false", "===", "filter_var", "(", "ini_get", "(", "'safe_mode'", ")", ",", "FILTER_VALIDATE_BOOLEAN", ",", "FILTER_NULL_ON_FAILURE", ")", ")", ";", "}", "// If the current server supports it, we follow redirects", "if", "(", "$", "this", "->", "followRedirects", "===", "true", ")", "{", "$", "options", "[", "CURLOPT_FOLLOWLOCATION", "]", "=", "true", ";", "$", "options", "[", "CURLOPT_MAXREDIRS", "]", "=", "self", "::", "CURLOPT_MAXREDIRS", ";", "}", "$", "this", "->", "debugRequest", "(", "$", "url", ",", "$", "payload", ",", "$", "headers", ")", ";", "// Execute the cURL request", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt_array", "(", "$", "ch", ",", "$", "options", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "// CURLE_SSL_CACERT error", "if", "(", "curl_errno", "(", "$", "ch", ")", "==", "60", ")", "{", "error_log", "(", "'Invalid or no certificate authority found, using bundled information'", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CAINFO", ",", "__DIR__", ".", "'/dm_ca_chain_bundle.crt'", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "}", "// Invalid empty response", "if", "(", "$", "response", "===", "false", ")", "{", "$", "e", "=", "new", "DailymotionTransportException", "(", "curl_error", "(", "$", "ch", ")", ",", "curl_errno", "(", "$", "ch", ")", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "throw", "$", "e", ";", "}", "$", "statusCode", "=", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HTTP_CODE", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "list", "(", "$", "responseHeadersString", ",", "$", "payload", ")", "=", "explode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "response", ",", "2", ")", ";", "strtok", "(", "$", "responseHeadersString", ",", "\"\\r\\n\"", ")", ";", "// skip status code", "while", "(", "(", "$", "name", "=", "trim", "(", "strtok", "(", "\":\"", ")", ")", ")", "&&", "(", "$", "value", "=", "trim", "(", "strtok", "(", "\"\\r\\n\"", ")", ")", ")", ")", "{", "$", "responseHeaders", "[", "strtolower", "(", "$", "name", ")", "]", "=", "(", "isset", "(", "$", "responseHeaders", "[", "$", "name", "]", ")", "?", "$", "responseHeaders", "[", "$", "name", "]", ".", "'; '", ":", "null", ")", ".", "$", "value", ";", "}", "$", "this", "->", "debugResponse", "(", "$", "url", ",", "$", "payload", ",", "$", "responseHeaders", ")", ";", "return", "$", "payload", ";", "}" ]
Perform an HTTP request by posting the given payload and returning the result. Override this method if you don't want to use cURL. @param string $url URL to perform the HTTP request to. @param mixed $payload Data to POST. If it's an associative array and `$encodePayload` is set to true, it will be url-encoded and the `Content-Type` header will automatically be set to `multipart/form-data`. If it's a string make sure you set the correct `Content-Type` header yourself. @param array $headers List of headers to send with the request (format `array('Header-Name: header value')`). @param int &$statusCode Reference variable to store the response status code. @param array &$responseHeaders Reference variable to store the response headers. @param boolean $encodePayload Whether or not to encode the payload if it's an associative array. @throws DailymotionTransportException If a network error occurs during the request. @return string Response body
[ "Perform", "an", "HTTP", "request", "by", "posting", "the", "given", "payload", "and", "returning", "the", "result", ".", "Override", "this", "method", "if", "you", "don", "t", "want", "to", "use", "cURL", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L822-L895
32,840
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.getCurrentUrl
protected function getCurrentUrl() { $filters = array( 'HTTPS' => FILTER_VALIDATE_BOOLEAN, 'HTTP_SSL_HTTPS' => FILTER_VALIDATE_BOOLEAN, 'HTTP_X_FORWARDED_PROTO' => FILTER_SANITIZE_STRING, 'HTTP_HOST' => FILTER_SANITIZE_STRING, 'REQUEST_URI' => FILTER_SANITIZE_STRING, ); // FastCGI seems to cause strange side-effects with unexpected NULL values when using INPUT_SERVER and // INPUT_ENV with the filter_input() and filter_input_array() functions, so we're using a workaround there. // See: http://fr2.php.net/manual/en/function.filter-input.php#77307 if (PHP_SAPI === 'cgi-fcgi') { $values = $filters; array_walk($values, function (&$value, $key) { $value = isset($_SERVER[$key]) ? $_SERVER[$key] : null; }); $values = filter_var_array($values, $filters); } else { $values = filter_input_array(INPUT_SERVER, $filters); } $secure = ($values['HTTPS'] || $values['HTTP_SSL_HTTPS'] || (strtolower($values['HTTP_X_FORWARDED_PROTO']) === 'https')); $scheme = $secure ? 'https://' : 'http://'; $currentUrl = $scheme . $values['HTTP_HOST'] . $values['REQUEST_URI']; $parts = parse_url($currentUrl); // Remove OAuth callback params $query = null; if (!empty($parts['query'])) { $parameters = array(); parse_str($parts['query'], $parameters); foreach(self::$DROP_QUERY_PARAMS as $name) { unset($parameters[$name]); } if (count($parameters) > 0) { $query = '?' . http_build_query($parameters, null, '&'); } } // Use port if non default $port = (!empty($parts['port']) && (($secure) ? ($parts['port'] !== 80) : ($parts['port'] !== 443))) ? ":{$parts['port']}" : null; // Rebuild return $scheme . $parts['host'] . $port . $parts['path'] . $query; }
php
protected function getCurrentUrl() { $filters = array( 'HTTPS' => FILTER_VALIDATE_BOOLEAN, 'HTTP_SSL_HTTPS' => FILTER_VALIDATE_BOOLEAN, 'HTTP_X_FORWARDED_PROTO' => FILTER_SANITIZE_STRING, 'HTTP_HOST' => FILTER_SANITIZE_STRING, 'REQUEST_URI' => FILTER_SANITIZE_STRING, ); // FastCGI seems to cause strange side-effects with unexpected NULL values when using INPUT_SERVER and // INPUT_ENV with the filter_input() and filter_input_array() functions, so we're using a workaround there. // See: http://fr2.php.net/manual/en/function.filter-input.php#77307 if (PHP_SAPI === 'cgi-fcgi') { $values = $filters; array_walk($values, function (&$value, $key) { $value = isset($_SERVER[$key]) ? $_SERVER[$key] : null; }); $values = filter_var_array($values, $filters); } else { $values = filter_input_array(INPUT_SERVER, $filters); } $secure = ($values['HTTPS'] || $values['HTTP_SSL_HTTPS'] || (strtolower($values['HTTP_X_FORWARDED_PROTO']) === 'https')); $scheme = $secure ? 'https://' : 'http://'; $currentUrl = $scheme . $values['HTTP_HOST'] . $values['REQUEST_URI']; $parts = parse_url($currentUrl); // Remove OAuth callback params $query = null; if (!empty($parts['query'])) { $parameters = array(); parse_str($parts['query'], $parameters); foreach(self::$DROP_QUERY_PARAMS as $name) { unset($parameters[$name]); } if (count($parameters) > 0) { $query = '?' . http_build_query($parameters, null, '&'); } } // Use port if non default $port = (!empty($parts['port']) && (($secure) ? ($parts['port'] !== 80) : ($parts['port'] !== 443))) ? ":{$parts['port']}" : null; // Rebuild return $scheme . $parts['host'] . $port . $parts['path'] . $query; }
[ "protected", "function", "getCurrentUrl", "(", ")", "{", "$", "filters", "=", "array", "(", "'HTTPS'", "=>", "FILTER_VALIDATE_BOOLEAN", ",", "'HTTP_SSL_HTTPS'", "=>", "FILTER_VALIDATE_BOOLEAN", ",", "'HTTP_X_FORWARDED_PROTO'", "=>", "FILTER_SANITIZE_STRING", ",", "'HTTP_HOST'", "=>", "FILTER_SANITIZE_STRING", ",", "'REQUEST_URI'", "=>", "FILTER_SANITIZE_STRING", ",", ")", ";", "// FastCGI seems to cause strange side-effects with unexpected NULL values when using INPUT_SERVER and", "// INPUT_ENV with the filter_input() and filter_input_array() functions, so we're using a workaround there.", "// See: http://fr2.php.net/manual/en/function.filter-input.php#77307", "if", "(", "PHP_SAPI", "===", "'cgi-fcgi'", ")", "{", "$", "values", "=", "$", "filters", ";", "array_walk", "(", "$", "values", ",", "function", "(", "&", "$", "value", ",", "$", "key", ")", "{", "$", "value", "=", "isset", "(", "$", "_SERVER", "[", "$", "key", "]", ")", "?", "$", "_SERVER", "[", "$", "key", "]", ":", "null", ";", "}", ")", ";", "$", "values", "=", "filter_var_array", "(", "$", "values", ",", "$", "filters", ")", ";", "}", "else", "{", "$", "values", "=", "filter_input_array", "(", "INPUT_SERVER", ",", "$", "filters", ")", ";", "}", "$", "secure", "=", "(", "$", "values", "[", "'HTTPS'", "]", "||", "$", "values", "[", "'HTTP_SSL_HTTPS'", "]", "||", "(", "strtolower", "(", "$", "values", "[", "'HTTP_X_FORWARDED_PROTO'", "]", ")", "===", "'https'", ")", ")", ";", "$", "scheme", "=", "$", "secure", "?", "'https://'", ":", "'http://'", ";", "$", "currentUrl", "=", "$", "scheme", ".", "$", "values", "[", "'HTTP_HOST'", "]", ".", "$", "values", "[", "'REQUEST_URI'", "]", ";", "$", "parts", "=", "parse_url", "(", "$", "currentUrl", ")", ";", "// Remove OAuth callback params", "$", "query", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "parts", "[", "'query'", "]", ")", ")", "{", "$", "parameters", "=", "array", "(", ")", ";", "parse_str", "(", "$", "parts", "[", "'query'", "]", ",", "$", "parameters", ")", ";", "foreach", "(", "self", "::", "$", "DROP_QUERY_PARAMS", "as", "$", "name", ")", "{", "unset", "(", "$", "parameters", "[", "$", "name", "]", ")", ";", "}", "if", "(", "count", "(", "$", "parameters", ")", ">", "0", ")", "{", "$", "query", "=", "'?'", ".", "http_build_query", "(", "$", "parameters", ",", "null", ",", "'&'", ")", ";", "}", "}", "// Use port if non default", "$", "port", "=", "(", "!", "empty", "(", "$", "parts", "[", "'port'", "]", ")", "&&", "(", "(", "$", "secure", ")", "?", "(", "$", "parts", "[", "'port'", "]", "!==", "80", ")", ":", "(", "$", "parts", "[", "'port'", "]", "!==", "443", ")", ")", ")", "?", "\":{$parts['port']}\"", ":", "null", ";", "// Rebuild", "return", "$", "scheme", ".", "$", "parts", "[", "'host'", "]", ".", "$", "port", ".", "$", "parts", "[", "'path'", "]", ".", "$", "query", ";", "}" ]
Returns the current URL, stripping if of known OAuth parameters that should not persist. @return string Current URL.
[ "Returns", "the", "current", "URL", "stripping", "if", "of", "known", "OAuth", "parameters", "that", "should", "not", "persist", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L901-L952
32,841
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.debugRequest
protected function debugRequest($url, $payload, array $headers) { if ($this->debug) { // debug for xterm-compliant cli if (php_sapi_name() === 'cli') { echo PHP_EOL; echo "\e[1;33m>>>\e[0;33m [{$url}] \e[1;33m>>>\e[00m" . PHP_EOL; foreach ($headers as $value) { $matches = array(); preg_match('#^(?P<key>[^:\s]+)\s*:\s*(?P<value>.*)$#S', $value, $matches); echo "\e[1;34m{$matches['key']}: \e[0;34m{$matches['value']}\e[00m" . PHP_EOL; } echo PHP_EOL; echo (is_array($payload)) ? json_encode($payload, JSON_PRETTY_PRINT) : ((is_null($json = json_decode($payload))) ? $payload : json_encode($json, JSON_PRETTY_PRINT) ); echo PHP_EOL; } // debug for the rest else { echo ">>> [{$url}] >>>" . PHP_EOL; $message = print_r(is_null($json = json_decode($payload)) ? $payload : $json, true); echo $message . (strpos($message, PHP_EOL) ? null : PHP_EOL); } } }
php
protected function debugRequest($url, $payload, array $headers) { if ($this->debug) { // debug for xterm-compliant cli if (php_sapi_name() === 'cli') { echo PHP_EOL; echo "\e[1;33m>>>\e[0;33m [{$url}] \e[1;33m>>>\e[00m" . PHP_EOL; foreach ($headers as $value) { $matches = array(); preg_match('#^(?P<key>[^:\s]+)\s*:\s*(?P<value>.*)$#S', $value, $matches); echo "\e[1;34m{$matches['key']}: \e[0;34m{$matches['value']}\e[00m" . PHP_EOL; } echo PHP_EOL; echo (is_array($payload)) ? json_encode($payload, JSON_PRETTY_PRINT) : ((is_null($json = json_decode($payload))) ? $payload : json_encode($json, JSON_PRETTY_PRINT) ); echo PHP_EOL; } // debug for the rest else { echo ">>> [{$url}] >>>" . PHP_EOL; $message = print_r(is_null($json = json_decode($payload)) ? $payload : $json, true); echo $message . (strpos($message, PHP_EOL) ? null : PHP_EOL); } } }
[ "protected", "function", "debugRequest", "(", "$", "url", ",", "$", "payload", ",", "array", "$", "headers", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "{", "// debug for xterm-compliant cli", "if", "(", "php_sapi_name", "(", ")", "===", "'cli'", ")", "{", "echo", "PHP_EOL", ";", "echo", "\"\\e[1;33m>>>\\e[0;33m [{$url}] \\e[1;33m>>>\\e[00m\"", ".", "PHP_EOL", ";", "foreach", "(", "$", "headers", "as", "$", "value", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "preg_match", "(", "'#^(?P<key>[^:\\s]+)\\s*:\\s*(?P<value>.*)$#S'", ",", "$", "value", ",", "$", "matches", ")", ";", "echo", "\"\\e[1;34m{$matches['key']}: \\e[0;34m{$matches['value']}\\e[00m\"", ".", "PHP_EOL", ";", "}", "echo", "PHP_EOL", ";", "echo", "(", "is_array", "(", "$", "payload", ")", ")", "?", "json_encode", "(", "$", "payload", ",", "JSON_PRETTY_PRINT", ")", ":", "(", "(", "is_null", "(", "$", "json", "=", "json_decode", "(", "$", "payload", ")", ")", ")", "?", "$", "payload", ":", "json_encode", "(", "$", "json", ",", "JSON_PRETTY_PRINT", ")", ")", ";", "echo", "PHP_EOL", ";", "}", "// debug for the rest", "else", "{", "echo", "\">>> [{$url}] >>>\"", ".", "PHP_EOL", ";", "$", "message", "=", "print_r", "(", "is_null", "(", "$", "json", "=", "json_decode", "(", "$", "payload", ")", ")", "?", "$", "payload", ":", "$", "json", ",", "true", ")", ";", "echo", "$", "message", ".", "(", "strpos", "(", "$", "message", ",", "PHP_EOL", ")", "?", "null", ":", "PHP_EOL", ")", ";", "}", "}", "}" ]
Debug an HTTP request on the current output. @param string $url URL of the request. @param mixed $payload Payload sent with the request. @param array $headers Headers sent with the request.
[ "Debug", "an", "HTTP", "request", "on", "the", "current", "output", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L961-L995
32,842
dailymotion/dailymotion-sdk-php
Dailymotion.php
Dailymotion.debugResponse
protected function debugResponse($url, $payload, array $headers) { if ($this->debug) { // debug for xterm-compliant cli if (php_sapi_name() === 'cli') { echo PHP_EOL; echo "\e[1;33m<<<\e[0;33m [{$url}] \e[1;33m<<<\e[00m" . PHP_EOL; foreach ($headers as $key => $value) { echo "\e[1;34m{$key}: \e[0;34m{$value}\e[00m" . PHP_EOL; } echo PHP_EOL; echo ($json = json_decode($payload, true)) == NULL ? $payload : json_encode($json, JSON_PRETTY_PRINT); echo PHP_EOL; } // debug for the rest else { echo "<<< [{$url}] <<<" . PHP_EOL; print_r(($json = json_decode($payload)) == NULL ? $payload : $json); echo PHP_EOL; } } }
php
protected function debugResponse($url, $payload, array $headers) { if ($this->debug) { // debug for xterm-compliant cli if (php_sapi_name() === 'cli') { echo PHP_EOL; echo "\e[1;33m<<<\e[0;33m [{$url}] \e[1;33m<<<\e[00m" . PHP_EOL; foreach ($headers as $key => $value) { echo "\e[1;34m{$key}: \e[0;34m{$value}\e[00m" . PHP_EOL; } echo PHP_EOL; echo ($json = json_decode($payload, true)) == NULL ? $payload : json_encode($json, JSON_PRETTY_PRINT); echo PHP_EOL; } // debug for the rest else { echo "<<< [{$url}] <<<" . PHP_EOL; print_r(($json = json_decode($payload)) == NULL ? $payload : $json); echo PHP_EOL; } } }
[ "protected", "function", "debugResponse", "(", "$", "url", ",", "$", "payload", ",", "array", "$", "headers", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "{", "// debug for xterm-compliant cli", "if", "(", "php_sapi_name", "(", ")", "===", "'cli'", ")", "{", "echo", "PHP_EOL", ";", "echo", "\"\\e[1;33m<<<\\e[0;33m [{$url}] \\e[1;33m<<<\\e[00m\"", ".", "PHP_EOL", ";", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "$", "value", ")", "{", "echo", "\"\\e[1;34m{$key}: \\e[0;34m{$value}\\e[00m\"", ".", "PHP_EOL", ";", "}", "echo", "PHP_EOL", ";", "echo", "(", "$", "json", "=", "json_decode", "(", "$", "payload", ",", "true", ")", ")", "==", "NULL", "?", "$", "payload", ":", "json_encode", "(", "$", "json", ",", "JSON_PRETTY_PRINT", ")", ";", "echo", "PHP_EOL", ";", "}", "// debug for the rest", "else", "{", "echo", "\"<<< [{$url}] <<<\"", ".", "PHP_EOL", ";", "print_r", "(", "(", "$", "json", "=", "json_decode", "(", "$", "payload", ")", ")", "==", "NULL", "?", "$", "payload", ":", "$", "json", ")", ";", "echo", "PHP_EOL", ";", "}", "}", "}" ]
Debug an HTTP response on the current output. @param string $url URL of the request. @param mixed $payload Payload sent with the request. @param array $headers Headers sent with the request.
[ "Debug", "an", "HTTP", "response", "on", "the", "current", "output", "." ]
0f558978785f9a6ab9e59c393041d4896550973b
https://github.com/dailymotion/dailymotion-sdk-php/blob/0f558978785f9a6ab9e59c393041d4896550973b/Dailymotion.php#L1004-L1029
32,843
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.setOptions
public function setOptions($options) { if ($this->step !== null) { throw new \RuntimeException('Cannot change encoding options during encoding'); } $this->options = (int) $options; return $this; }
php
public function setOptions($options) { if ($this->step !== null) { throw new \RuntimeException('Cannot change encoding options during encoding'); } $this->options = (int) $options; return $this; }
[ "public", "function", "setOptions", "(", "$", "options", ")", "{", "if", "(", "$", "this", "->", "step", "!==", "null", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot change encoding options during encoding'", ")", ";", "}", "$", "this", "->", "options", "=", "(", "int", ")", "$", "options", ";", "return", "$", "this", ";", "}" ]
Sets the JSON encoding options. @param int $options The JSON encoding options that are used by json_encode @return $this Returns self for call chaining @throws \RuntimeException If changing encoding options during encoding operation
[ "Sets", "the", "JSON", "encoding", "options", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L68-L76
32,844
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.setIndent
public function setIndent($indent) { if ($this->step !== null) { throw new \RuntimeException('Cannot change indent during encoding'); } $this->indent = is_int($indent) ? str_repeat(' ', $indent) : (string) $indent; return $this; }
php
public function setIndent($indent) { if ($this->step !== null) { throw new \RuntimeException('Cannot change indent during encoding'); } $this->indent = is_int($indent) ? str_repeat(' ', $indent) : (string) $indent; return $this; }
[ "public", "function", "setIndent", "(", "$", "indent", ")", "{", "if", "(", "$", "this", "->", "step", "!==", "null", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot change indent during encoding'", ")", ";", "}", "$", "this", "->", "indent", "=", "is_int", "(", "$", "indent", ")", "?", "str_repeat", "(", "' '", ",", "$", "indent", ")", ":", "(", "string", ")", "$", "indent", ";", "return", "$", "this", ";", "}" ]
Sets the indent for the JSON output. @param string|int $indent A string to use as indent or the number of spaces @return $this Returns self for call chaining @throws \RuntimeException If changing indent during encoding operation
[ "Sets", "the", "indent", "for", "the", "JSON", "output", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L84-L92
32,845
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.rewind
public function rewind() { if ($this->step === 0) { return; } $this->stack = []; $this->stackType = []; $this->valueStack = []; $this->errors = []; $this->newLine = false; $this->first = true; $this->line = 1; $this->column = 1; $this->step = 0; $this->processValue($this->initialValue); }
php
public function rewind() { if ($this->step === 0) { return; } $this->stack = []; $this->stackType = []; $this->valueStack = []; $this->errors = []; $this->newLine = false; $this->first = true; $this->line = 1; $this->column = 1; $this->step = 0; $this->processValue($this->initialValue); }
[ "public", "function", "rewind", "(", ")", "{", "if", "(", "$", "this", "->", "step", "===", "0", ")", "{", "return", ";", "}", "$", "this", "->", "stack", "=", "[", "]", ";", "$", "this", "->", "stackType", "=", "[", "]", ";", "$", "this", "->", "valueStack", "=", "[", "]", ";", "$", "this", "->", "errors", "=", "[", "]", ";", "$", "this", "->", "newLine", "=", "false", ";", "$", "this", "->", "first", "=", "true", ";", "$", "this", "->", "line", "=", "1", ";", "$", "this", "->", "column", "=", "1", ";", "$", "this", "->", "step", "=", "0", ";", "$", "this", "->", "processValue", "(", "$", "this", "->", "initialValue", ")", ";", "}" ]
Returns the JSON encoding to the beginning.
[ "Returns", "the", "JSON", "encoding", "to", "the", "beginning", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L153-L170
32,846
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.next
public function next() { $this->initialize(); if (!empty($this->stack)) { $this->step++; $iterator = end($this->stack); if ($iterator->valid()) { $this->processStack($iterator, end($this->stackType)); $iterator->next(); } else { $this->popStack(); } } else { $this->step = null; } }
php
public function next() { $this->initialize(); if (!empty($this->stack)) { $this->step++; $iterator = end($this->stack); if ($iterator->valid()) { $this->processStack($iterator, end($this->stackType)); $iterator->next(); } else { $this->popStack(); } } else { $this->step = null; } }
[ "public", "function", "next", "(", ")", "{", "$", "this", "->", "initialize", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "stack", ")", ")", "{", "$", "this", "->", "step", "++", ";", "$", "iterator", "=", "end", "(", "$", "this", "->", "stack", ")", ";", "if", "(", "$", "iterator", "->", "valid", "(", ")", ")", "{", "$", "this", "->", "processStack", "(", "$", "iterator", ",", "end", "(", "$", "this", "->", "stackType", ")", ")", ";", "$", "iterator", "->", "next", "(", ")", ";", "}", "else", "{", "$", "this", "->", "popStack", "(", ")", ";", "}", "}", "else", "{", "$", "this", "->", "step", "=", "null", ";", "}", "}" ]
Iterates the next token or tokens to the output stream.
[ "Iterates", "the", "next", "token", "or", "tokens", "to", "the", "output", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L175-L192
32,847
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.processStack
private function processStack(\Iterator $iterator, $isObject) { if ($isObject) { if (!$this->processKey($iterator->key())) { return; } } elseif (!$this->first) { $this->outputLine(',', JsonToken::T_COMMA); } $this->first = false; $this->processValue($iterator->current()); }
php
private function processStack(\Iterator $iterator, $isObject) { if ($isObject) { if (!$this->processKey($iterator->key())) { return; } } elseif (!$this->first) { $this->outputLine(',', JsonToken::T_COMMA); } $this->first = false; $this->processValue($iterator->current()); }
[ "private", "function", "processStack", "(", "\\", "Iterator", "$", "iterator", ",", "$", "isObject", ")", "{", "if", "(", "$", "isObject", ")", "{", "if", "(", "!", "$", "this", "->", "processKey", "(", "$", "iterator", "->", "key", "(", ")", ")", ")", "{", "return", ";", "}", "}", "elseif", "(", "!", "$", "this", "->", "first", ")", "{", "$", "this", "->", "outputLine", "(", "','", ",", "JsonToken", "::", "T_COMMA", ")", ";", "}", "$", "this", "->", "first", "=", "false", ";", "$", "this", "->", "processValue", "(", "$", "iterator", "->", "current", "(", ")", ")", ";", "}" ]
Handles the next value from the iterator to be encoded as JSON. @param \Iterator $iterator The iterator used to generate the next value @param bool $isObject True if the iterator is being handled as an object, false if not
[ "Handles", "the", "next", "value", "from", "the", "iterator", "to", "be", "encoded", "as", "JSON", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L199-L211
32,848
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.processKey
private function processKey($key) { if (!is_int($key) && !is_string($key)) { $this->addError('Only string or integer keys are supported'); return false; } if (!$this->first) { $this->outputLine(',', JsonToken::T_COMMA); } $this->outputJson((string) $key, JsonToken::T_NAME); $this->output(':', JsonToken::T_COLON); if ($this->options & JSON_PRETTY_PRINT) { $this->output(' ', JsonToken::T_WHITESPACE); } return true; }
php
private function processKey($key) { if (!is_int($key) && !is_string($key)) { $this->addError('Only string or integer keys are supported'); return false; } if (!$this->first) { $this->outputLine(',', JsonToken::T_COMMA); } $this->outputJson((string) $key, JsonToken::T_NAME); $this->output(':', JsonToken::T_COLON); if ($this->options & JSON_PRETTY_PRINT) { $this->output(' ', JsonToken::T_WHITESPACE); } return true; }
[ "private", "function", "processKey", "(", "$", "key", ")", "{", "if", "(", "!", "is_int", "(", "$", "key", ")", "&&", "!", "is_string", "(", "$", "key", ")", ")", "{", "$", "this", "->", "addError", "(", "'Only string or integer keys are supported'", ")", ";", "return", "false", ";", "}", "if", "(", "!", "$", "this", "->", "first", ")", "{", "$", "this", "->", "outputLine", "(", "','", ",", "JsonToken", "::", "T_COMMA", ")", ";", "}", "$", "this", "->", "outputJson", "(", "(", "string", ")", "$", "key", ",", "JsonToken", "::", "T_NAME", ")", ";", "$", "this", "->", "output", "(", "':'", ",", "JsonToken", "::", "T_COLON", ")", ";", "if", "(", "$", "this", "->", "options", "&", "JSON_PRETTY_PRINT", ")", "{", "$", "this", "->", "output", "(", "' '", ",", "JsonToken", "::", "T_WHITESPACE", ")", ";", "}", "return", "true", ";", "}" ]
Handles the given value key into JSON. @param mixed $key The key to process @return bool True if the key is valid, false if not
[ "Handles", "the", "given", "value", "key", "into", "JSON", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L218-L237
32,849
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.processValue
private function processValue($value) { $this->valueStack[] = $value; $value = $this->resolveValue($value); if (is_array($value) || is_object($value)) { $this->pushStack($value); } else { $this->outputJson($value, JsonToken::T_VALUE); array_pop($this->valueStack); } }
php
private function processValue($value) { $this->valueStack[] = $value; $value = $this->resolveValue($value); if (is_array($value) || is_object($value)) { $this->pushStack($value); } else { $this->outputJson($value, JsonToken::T_VALUE); array_pop($this->valueStack); } }
[ "private", "function", "processValue", "(", "$", "value", ")", "{", "$", "this", "->", "valueStack", "[", "]", "=", "$", "value", ";", "$", "value", "=", "$", "this", "->", "resolveValue", "(", "$", "value", ")", ";", "if", "(", "is_array", "(", "$", "value", ")", "||", "is_object", "(", "$", "value", ")", ")", "{", "$", "this", "->", "pushStack", "(", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "outputJson", "(", "$", "value", ",", "JsonToken", "::", "T_VALUE", ")", ";", "array_pop", "(", "$", "this", "->", "valueStack", ")", ";", "}", "}" ]
Handles the given JSON value appropriately depending on it's type. @param mixed $value The value that should be encoded as JSON
[ "Handles", "the", "given", "JSON", "value", "appropriately", "depending", "on", "it", "s", "type", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L243-L254
32,850
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.resolveValue
protected function resolveValue($value) { do { if ($value instanceof \JsonSerializable) { $value = $value->jsonSerialize(); } elseif ($value instanceof \Closure) { $value = $value(); } else { break; } } while (true); return $value; }
php
protected function resolveValue($value) { do { if ($value instanceof \JsonSerializable) { $value = $value->jsonSerialize(); } elseif ($value instanceof \Closure) { $value = $value(); } else { break; } } while (true); return $value; }
[ "protected", "function", "resolveValue", "(", "$", "value", ")", "{", "do", "{", "if", "(", "$", "value", "instanceof", "\\", "JsonSerializable", ")", "{", "$", "value", "=", "$", "value", "->", "jsonSerialize", "(", ")", ";", "}", "elseif", "(", "$", "value", "instanceof", "\\", "Closure", ")", "{", "$", "value", "=", "$", "value", "(", ")", ";", "}", "else", "{", "break", ";", "}", "}", "while", "(", "true", ")", ";", "return", "$", "value", ";", "}" ]
Resolves the actual value of any given value that is about to be processed. @param mixed $value The value to resolve @return mixed The resolved value
[ "Resolves", "the", "actual", "value", "of", "any", "given", "value", "that", "is", "about", "to", "be", "processed", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L261-L274
32,851
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.addError
private function addError($message) { $errorMessage = sprintf('Line %d, column %d: %s', $this->line, $this->column, $message); $this->errors[] = $errorMessage; if ($this->options & JSON_PARTIAL_OUTPUT_ON_ERROR) { return; } $this->stack = []; $this->step = null; throw new EncodingException($errorMessage); }
php
private function addError($message) { $errorMessage = sprintf('Line %d, column %d: %s', $this->line, $this->column, $message); $this->errors[] = $errorMessage; if ($this->options & JSON_PARTIAL_OUTPUT_ON_ERROR) { return; } $this->stack = []; $this->step = null; throw new EncodingException($errorMessage); }
[ "private", "function", "addError", "(", "$", "message", ")", "{", "$", "errorMessage", "=", "sprintf", "(", "'Line %d, column %d: %s'", ",", "$", "this", "->", "line", ",", "$", "this", "->", "column", ",", "$", "message", ")", ";", "$", "this", "->", "errors", "[", "]", "=", "$", "errorMessage", ";", "if", "(", "$", "this", "->", "options", "&", "JSON_PARTIAL_OUTPUT_ON_ERROR", ")", "{", "return", ";", "}", "$", "this", "->", "stack", "=", "[", "]", ";", "$", "this", "->", "step", "=", "null", ";", "throw", "new", "EncodingException", "(", "$", "errorMessage", ")", ";", "}" ]
Adds an JSON encoding error to the list of errors. @param string $message The error message to add @throws EncodingException If the encoding should not continue due to the error
[ "Adds", "an", "JSON", "encoding", "error", "to", "the", "list", "of", "errors", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L281-L294
32,852
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.pushStack
private function pushStack($iterable) { $iterator = $this->getIterator($iterable); $isObject = $this->isObject($iterable, $iterator); if ($isObject) { $this->outputLine('{', JsonToken::T_LEFT_BRACE); } else { $this->outputLine('[', JsonToken::T_LEFT_BRACKET); } $this->first = true; $this->stack[] = $iterator; $this->stackType[] = $isObject; }
php
private function pushStack($iterable) { $iterator = $this->getIterator($iterable); $isObject = $this->isObject($iterable, $iterator); if ($isObject) { $this->outputLine('{', JsonToken::T_LEFT_BRACE); } else { $this->outputLine('[', JsonToken::T_LEFT_BRACKET); } $this->first = true; $this->stack[] = $iterator; $this->stackType[] = $isObject; }
[ "private", "function", "pushStack", "(", "$", "iterable", ")", "{", "$", "iterator", "=", "$", "this", "->", "getIterator", "(", "$", "iterable", ")", ";", "$", "isObject", "=", "$", "this", "->", "isObject", "(", "$", "iterable", ",", "$", "iterator", ")", ";", "if", "(", "$", "isObject", ")", "{", "$", "this", "->", "outputLine", "(", "'{'", ",", "JsonToken", "::", "T_LEFT_BRACE", ")", ";", "}", "else", "{", "$", "this", "->", "outputLine", "(", "'['", ",", "JsonToken", "::", "T_LEFT_BRACKET", ")", ";", "}", "$", "this", "->", "first", "=", "true", ";", "$", "this", "->", "stack", "[", "]", "=", "$", "iterator", ";", "$", "this", "->", "stackType", "[", "]", "=", "$", "isObject", ";", "}" ]
Pushes the given iterable to the value stack. @param object|array $iterable The iterable value to push to the stack
[ "Pushes", "the", "given", "iterable", "to", "the", "value", "stack", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L300-L314
32,853
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.isObject
private function isObject($iterable, \Iterator $iterator) { if ($this->options & JSON_FORCE_OBJECT) { return true; } if ($iterable instanceof \Traversable) { return $iterator->valid() && $iterator->key() !== 0; } return is_object($iterable) || $this->isAssociative($iterable); }
php
private function isObject($iterable, \Iterator $iterator) { if ($this->options & JSON_FORCE_OBJECT) { return true; } if ($iterable instanceof \Traversable) { return $iterator->valid() && $iterator->key() !== 0; } return is_object($iterable) || $this->isAssociative($iterable); }
[ "private", "function", "isObject", "(", "$", "iterable", ",", "\\", "Iterator", "$", "iterator", ")", "{", "if", "(", "$", "this", "->", "options", "&", "JSON_FORCE_OBJECT", ")", "{", "return", "true", ";", "}", "if", "(", "$", "iterable", "instanceof", "\\", "Traversable", ")", "{", "return", "$", "iterator", "->", "valid", "(", ")", "&&", "$", "iterator", "->", "key", "(", ")", "!==", "0", ";", "}", "return", "is_object", "(", "$", "iterable", ")", "||", "$", "this", "->", "isAssociative", "(", "$", "iterable", ")", ";", "}" ]
Tells if the given iterable should be handled as a JSON object or not. @param object|array $iterable The iterable value to test @param \Iterator $iterator An Iterator created from the iterable value @return bool True if the given iterable should be treated as object, false if not
[ "Tells", "if", "the", "given", "iterable", "should", "be", "handled", "as", "a", "JSON", "object", "or", "not", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L334-L345
32,854
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.isAssociative
private function isAssociative(array $array) { if ($array === []) { return false; } $expected = 0; foreach ($array as $key => $_) { if ($key !== $expected++) { return true; } } return false; }
php
private function isAssociative(array $array) { if ($array === []) { return false; } $expected = 0; foreach ($array as $key => $_) { if ($key !== $expected++) { return true; } } return false; }
[ "private", "function", "isAssociative", "(", "array", "$", "array", ")", "{", "if", "(", "$", "array", "===", "[", "]", ")", "{", "return", "false", ";", "}", "$", "expected", "=", "0", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "_", ")", "{", "if", "(", "$", "key", "!==", "$", "expected", "++", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Tells if the given array is an associative array. @param array $array The array to test @return bool True if the array is associative, false if not
[ "Tells", "if", "the", "given", "array", "is", "an", "associative", "array", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L352-L367
32,855
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.popStack
private function popStack() { if (!$this->first) { $this->newLine = true; } $this->first = false; array_pop($this->stack); if (array_pop($this->stackType)) { $this->output('}', JsonToken::T_RIGHT_BRACE); } else { $this->output(']', JsonToken::T_RIGHT_BRACKET); } array_pop($this->valueStack); }
php
private function popStack() { if (!$this->first) { $this->newLine = true; } $this->first = false; array_pop($this->stack); if (array_pop($this->stackType)) { $this->output('}', JsonToken::T_RIGHT_BRACE); } else { $this->output(']', JsonToken::T_RIGHT_BRACKET); } array_pop($this->valueStack); }
[ "private", "function", "popStack", "(", ")", "{", "if", "(", "!", "$", "this", "->", "first", ")", "{", "$", "this", "->", "newLine", "=", "true", ";", "}", "$", "this", "->", "first", "=", "false", ";", "array_pop", "(", "$", "this", "->", "stack", ")", ";", "if", "(", "array_pop", "(", "$", "this", "->", "stackType", ")", ")", "{", "$", "this", "->", "output", "(", "'}'", ",", "JsonToken", "::", "T_RIGHT_BRACE", ")", ";", "}", "else", "{", "$", "this", "->", "output", "(", "']'", ",", "JsonToken", "::", "T_RIGHT_BRACKET", ")", ";", "}", "array_pop", "(", "$", "this", "->", "valueStack", ")", ";", "}" ]
Removes the top element of the value stack.
[ "Removes", "the", "top", "element", "of", "the", "value", "stack", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L372-L388
32,856
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.outputJson
private function outputJson($value, $token) { $encoded = json_encode($value, $this->options); $error = json_last_error(); if ($error !== JSON_ERROR_NONE) { $this->addError(sprintf('%s (%s)', json_last_error_msg(), $this->getJsonErrorName($error))); } $this->output($encoded, $token); }
php
private function outputJson($value, $token) { $encoded = json_encode($value, $this->options); $error = json_last_error(); if ($error !== JSON_ERROR_NONE) { $this->addError(sprintf('%s (%s)', json_last_error_msg(), $this->getJsonErrorName($error))); } $this->output($encoded, $token); }
[ "private", "function", "outputJson", "(", "$", "value", ",", "$", "token", ")", "{", "$", "encoded", "=", "json_encode", "(", "$", "value", ",", "$", "this", "->", "options", ")", ";", "$", "error", "=", "json_last_error", "(", ")", ";", "if", "(", "$", "error", "!==", "JSON_ERROR_NONE", ")", "{", "$", "this", "->", "addError", "(", "sprintf", "(", "'%s (%s)'", ",", "json_last_error_msg", "(", ")", ",", "$", "this", "->", "getJsonErrorName", "(", "$", "error", ")", ")", ")", ";", "}", "$", "this", "->", "output", "(", "$", "encoded", ",", "$", "token", ")", ";", "}" ]
Encodes the given value as JSON and passes it to output stream. @param mixed $value The value to output as JSON @param int $token The token type of the value
[ "Encodes", "the", "given", "value", "as", "JSON", "and", "passes", "it", "to", "output", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L395-L405
32,857
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.getJsonErrorName
private function getJsonErrorName($error) { $matches = array_keys(get_defined_constants(), $error, true); $prefix = 'JSON_ERROR_'; $prefixLength = strlen($prefix); $name = 'UNKNOWN_ERROR'; foreach ($matches as $match) { if (is_string($match) && strncmp($match, $prefix, $prefixLength) === 0) { $name = $match; break; } } return $name; }
php
private function getJsonErrorName($error) { $matches = array_keys(get_defined_constants(), $error, true); $prefix = 'JSON_ERROR_'; $prefixLength = strlen($prefix); $name = 'UNKNOWN_ERROR'; foreach ($matches as $match) { if (is_string($match) && strncmp($match, $prefix, $prefixLength) === 0) { $name = $match; break; } } return $name; }
[ "private", "function", "getJsonErrorName", "(", "$", "error", ")", "{", "$", "matches", "=", "array_keys", "(", "get_defined_constants", "(", ")", ",", "$", "error", ",", "true", ")", ";", "$", "prefix", "=", "'JSON_ERROR_'", ";", "$", "prefixLength", "=", "strlen", "(", "$", "prefix", ")", ";", "$", "name", "=", "'UNKNOWN_ERROR'", ";", "foreach", "(", "$", "matches", "as", "$", "match", ")", "{", "if", "(", "is_string", "(", "$", "match", ")", "&&", "strncmp", "(", "$", "match", ",", "$", "prefix", ",", "$", "prefixLength", ")", "===", "0", ")", "{", "$", "name", "=", "$", "match", ";", "break", ";", "}", "}", "return", "$", "name", ";", "}" ]
Returns the name of the JSON error constant. @param int $error The error code to find @return string The name for the error code
[ "Returns", "the", "name", "of", "the", "JSON", "error", "constant", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L412-L427
32,858
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.outputLine
private function outputLine($string, $token) { $this->output($string, $token); $this->newLine = true; }
php
private function outputLine($string, $token) { $this->output($string, $token); $this->newLine = true; }
[ "private", "function", "outputLine", "(", "$", "string", ",", "$", "token", ")", "{", "$", "this", "->", "output", "(", "$", "string", ",", "$", "token", ")", ";", "$", "this", "->", "newLine", "=", "true", ";", "}" ]
Passes the given token to the output stream and ensures the next token is preceded by a newline. @param string $string The token to write to the output stream @param int $token The type of the token
[ "Passes", "the", "given", "token", "to", "the", "output", "stream", "and", "ensures", "the", "next", "token", "is", "preceded", "by", "a", "newline", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L434-L438
32,859
violet-php/streaming-json-encoder
src/AbstractJsonEncoder.php
AbstractJsonEncoder.output
private function output($string, $token) { if ($this->newLine && $this->options & JSON_PRETTY_PRINT) { $indent = str_repeat($this->indent, count($this->stack)); $this->write("\n", JsonToken::T_WHITESPACE); if ($indent !== '') { $this->write($indent, JsonToken::T_WHITESPACE); } $this->line++; $this->column = strlen($indent) + 1; } $this->newLine = false; $this->write($string, $token); $this->column += strlen($string); }
php
private function output($string, $token) { if ($this->newLine && $this->options & JSON_PRETTY_PRINT) { $indent = str_repeat($this->indent, count($this->stack)); $this->write("\n", JsonToken::T_WHITESPACE); if ($indent !== '') { $this->write($indent, JsonToken::T_WHITESPACE); } $this->line++; $this->column = strlen($indent) + 1; } $this->newLine = false; $this->write($string, $token); $this->column += strlen($string); }
[ "private", "function", "output", "(", "$", "string", ",", "$", "token", ")", "{", "if", "(", "$", "this", "->", "newLine", "&&", "$", "this", "->", "options", "&", "JSON_PRETTY_PRINT", ")", "{", "$", "indent", "=", "str_repeat", "(", "$", "this", "->", "indent", ",", "count", "(", "$", "this", "->", "stack", ")", ")", ";", "$", "this", "->", "write", "(", "\"\\n\"", ",", "JsonToken", "::", "T_WHITESPACE", ")", ";", "if", "(", "$", "indent", "!==", "''", ")", "{", "$", "this", "->", "write", "(", "$", "indent", ",", "JsonToken", "::", "T_WHITESPACE", ")", ";", "}", "$", "this", "->", "line", "++", ";", "$", "this", "->", "column", "=", "strlen", "(", "$", "indent", ")", "+", "1", ";", "}", "$", "this", "->", "newLine", "=", "false", ";", "$", "this", "->", "write", "(", "$", "string", ",", "$", "token", ")", ";", "$", "this", "->", "column", "+=", "strlen", "(", "$", "string", ")", ";", "}" ]
Passes the given token to the output stream. @param string $string The token to write to the output stream @param int $token The type of the token
[ "Passes", "the", "given", "token", "to", "the", "output", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/AbstractJsonEncoder.php#L445-L462
32,860
violet-php/streaming-json-encoder
src/JsonStream.php
JsonStream.seek
public function seek($offset, $whence = SEEK_SET) { $position = $this->calculatePosition($offset, $whence); if (!isset($this->cursor) || $position < $this->cursor) { $this->getEncoder()->rewind(); $this->buffer = ''; $this->cursor = 0; } $this->forward($position); }
php
public function seek($offset, $whence = SEEK_SET) { $position = $this->calculatePosition($offset, $whence); if (!isset($this->cursor) || $position < $this->cursor) { $this->getEncoder()->rewind(); $this->buffer = ''; $this->cursor = 0; } $this->forward($position); }
[ "public", "function", "seek", "(", "$", "offset", ",", "$", "whence", "=", "SEEK_SET", ")", "{", "$", "position", "=", "$", "this", "->", "calculatePosition", "(", "$", "offset", ",", "$", "whence", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "cursor", ")", "||", "$", "position", "<", "$", "this", "->", "cursor", ")", "{", "$", "this", "->", "getEncoder", "(", ")", "->", "rewind", "(", ")", ";", "$", "this", "->", "buffer", "=", "''", ";", "$", "this", "->", "cursor", "=", "0", ";", "}", "$", "this", "->", "forward", "(", "$", "position", ")", ";", "}" ]
Seeks the given cursor position in the JSON stream. If the provided seek position is less than the current cursor position, a rewind operation is performed on the underlying JSON encoder. Whether this works or not depends on whether the encoded value supports rewinding. Note that since it's not possible to determine the end of the JSON stream without encoding the entire value, it's not possible to set the cursor using SEEK_END constant and doing so will result in an exception. @param int $offset The offset for the cursor @param int $whence Either SEEK_CUR or SEEK_SET to determine new cursor position @throws \RuntimeException If SEEK_END is used to determine the cursor position
[ "Seeks", "the", "given", "cursor", "position", "in", "the", "JSON", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/JsonStream.php#L143-L154
32,861
violet-php/streaming-json-encoder
src/JsonStream.php
JsonStream.calculatePosition
private function calculatePosition($offset, $whence) { if ($whence === SEEK_CUR) { return max(0, $this->cursor + (int) $offset); } elseif ($whence === SEEK_SET) { return max(0, (int) $offset); } elseif ($whence === SEEK_END) { throw new \RuntimeException('Cannot set cursor position from the end of a JSON stream'); } throw new \InvalidArgumentException("Invalid cursor relative position '$whence'"); }
php
private function calculatePosition($offset, $whence) { if ($whence === SEEK_CUR) { return max(0, $this->cursor + (int) $offset); } elseif ($whence === SEEK_SET) { return max(0, (int) $offset); } elseif ($whence === SEEK_END) { throw new \RuntimeException('Cannot set cursor position from the end of a JSON stream'); } throw new \InvalidArgumentException("Invalid cursor relative position '$whence'"); }
[ "private", "function", "calculatePosition", "(", "$", "offset", ",", "$", "whence", ")", "{", "if", "(", "$", "whence", "===", "SEEK_CUR", ")", "{", "return", "max", "(", "0", ",", "$", "this", "->", "cursor", "+", "(", "int", ")", "$", "offset", ")", ";", "}", "elseif", "(", "$", "whence", "===", "SEEK_SET", ")", "{", "return", "max", "(", "0", ",", "(", "int", ")", "$", "offset", ")", ";", "}", "elseif", "(", "$", "whence", "===", "SEEK_END", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set cursor position from the end of a JSON stream'", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Invalid cursor relative position '$whence'\"", ")", ";", "}" ]
Calculates new position for the cursor based on offset and whence. @param int $offset The cursor offset @param int $whence One of the SEEK_* constants @return int The new cursor position @throws \RuntimeException If SEEK_END is used to determine the cursor position
[ "Calculates", "new", "position", "for", "the", "cursor", "based", "on", "offset", "and", "whence", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/JsonStream.php#L163-L174
32,862
violet-php/streaming-json-encoder
src/JsonStream.php
JsonStream.forward
private function forward($position) { $encoder = $this->getEncoder(); while ($this->cursor < $position) { $length = strlen($this->buffer); if ($this->cursor + $length > $position) { $this->buffer = substr($this->buffer, $position - $this->cursor); $this->cursor = $position; break; } $this->cursor += $length; $this->buffer = ''; if (!$encoder->valid()) { $this->buffer = null; break; } $this->buffer = $encoder->current(); $encoder->next(); } }
php
private function forward($position) { $encoder = $this->getEncoder(); while ($this->cursor < $position) { $length = strlen($this->buffer); if ($this->cursor + $length > $position) { $this->buffer = substr($this->buffer, $position - $this->cursor); $this->cursor = $position; break; } $this->cursor += $length; $this->buffer = ''; if (!$encoder->valid()) { $this->buffer = null; break; } $this->buffer = $encoder->current(); $encoder->next(); } }
[ "private", "function", "forward", "(", "$", "position", ")", "{", "$", "encoder", "=", "$", "this", "->", "getEncoder", "(", ")", ";", "while", "(", "$", "this", "->", "cursor", "<", "$", "position", ")", "{", "$", "length", "=", "strlen", "(", "$", "this", "->", "buffer", ")", ";", "if", "(", "$", "this", "->", "cursor", "+", "$", "length", ">", "$", "position", ")", "{", "$", "this", "->", "buffer", "=", "substr", "(", "$", "this", "->", "buffer", ",", "$", "position", "-", "$", "this", "->", "cursor", ")", ";", "$", "this", "->", "cursor", "=", "$", "position", ";", "break", ";", "}", "$", "this", "->", "cursor", "+=", "$", "length", ";", "$", "this", "->", "buffer", "=", "''", ";", "if", "(", "!", "$", "encoder", "->", "valid", "(", ")", ")", "{", "$", "this", "->", "buffer", "=", "null", ";", "break", ";", "}", "$", "this", "->", "buffer", "=", "$", "encoder", "->", "current", "(", ")", ";", "$", "encoder", "->", "next", "(", ")", ";", "}", "}" ]
Forwards the JSON stream reading cursor to the given position or to the end of stream. @param int $position The new position of the cursor
[ "Forwards", "the", "JSON", "stream", "reading", "cursor", "to", "the", "given", "position", "or", "to", "the", "end", "of", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/JsonStream.php#L180-L204
32,863
violet-php/streaming-json-encoder
src/JsonStream.php
JsonStream.read
public function read($length) { $length = max(0, (int) $length); $encoder = $this->getEncoder(); while (strlen($this->buffer) < $length && $encoder->valid()) { $this->buffer .= $encoder->current(); $encoder->next(); } if (strlen($this->buffer) > $length || $encoder->valid()) { $output = substr($this->buffer, 0, $length); $this->buffer = substr($this->buffer, $length); } else { $output = (string) $this->buffer; $this->buffer = null; } $this->cursor += strlen($output); return $output; }
php
public function read($length) { $length = max(0, (int) $length); $encoder = $this->getEncoder(); while (strlen($this->buffer) < $length && $encoder->valid()) { $this->buffer .= $encoder->current(); $encoder->next(); } if (strlen($this->buffer) > $length || $encoder->valid()) { $output = substr($this->buffer, 0, $length); $this->buffer = substr($this->buffer, $length); } else { $output = (string) $this->buffer; $this->buffer = null; } $this->cursor += strlen($output); return $output; }
[ "public", "function", "read", "(", "$", "length", ")", "{", "$", "length", "=", "max", "(", "0", ",", "(", "int", ")", "$", "length", ")", ";", "$", "encoder", "=", "$", "this", "->", "getEncoder", "(", ")", ";", "while", "(", "strlen", "(", "$", "this", "->", "buffer", ")", "<", "$", "length", "&&", "$", "encoder", "->", "valid", "(", ")", ")", "{", "$", "this", "->", "buffer", ".=", "$", "encoder", "->", "current", "(", ")", ";", "$", "encoder", "->", "next", "(", ")", ";", "}", "if", "(", "strlen", "(", "$", "this", "->", "buffer", ")", ">", "$", "length", "||", "$", "encoder", "->", "valid", "(", ")", ")", "{", "$", "output", "=", "substr", "(", "$", "this", "->", "buffer", ",", "0", ",", "$", "length", ")", ";", "$", "this", "->", "buffer", "=", "substr", "(", "$", "this", "->", "buffer", ",", "$", "length", ")", ";", "}", "else", "{", "$", "output", "=", "(", "string", ")", "$", "this", "->", "buffer", ";", "$", "this", "->", "buffer", "=", "null", ";", "}", "$", "this", "->", "cursor", "+=", "strlen", "(", "$", "output", ")", ";", "return", "$", "output", ";", "}" ]
Returns the given number of bytes from the JSON stream. The underlying value is encoded into JSON until enough bytes have been generated to fulfill the requested number of bytes. The extraneous bytes are then buffered for the next read from the JSON stream. The stream may return fewer number of bytes if the entire value has been encoded and there are no more bytes to return. @param int $length The number of bytes to return @return string The bytes read from the JSON stream
[ "Returns", "the", "given", "number", "of", "bytes", "from", "the", "JSON", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/JsonStream.php#L262-L283
32,864
violet-php/streaming-json-encoder
src/JsonStream.php
JsonStream.getContents
public function getContents() { $encoder = $this->getEncoder(); $output = ''; while ($encoder->valid()) { $output .= $encoder->current(); $encoder->next(); } $this->cursor += strlen($output); $this->buffer = null; return $output; }
php
public function getContents() { $encoder = $this->getEncoder(); $output = ''; while ($encoder->valid()) { $output .= $encoder->current(); $encoder->next(); } $this->cursor += strlen($output); $this->buffer = null; return $output; }
[ "public", "function", "getContents", "(", ")", "{", "$", "encoder", "=", "$", "this", "->", "getEncoder", "(", ")", ";", "$", "output", "=", "''", ";", "while", "(", "$", "encoder", "->", "valid", "(", ")", ")", "{", "$", "output", ".=", "$", "encoder", "->", "current", "(", ")", ";", "$", "encoder", "->", "next", "(", ")", ";", "}", "$", "this", "->", "cursor", "+=", "strlen", "(", "$", "output", ")", ";", "$", "this", "->", "buffer", "=", "null", ";", "return", "$", "output", ";", "}" ]
Returns the remaining bytes from the JSON stream. @return string The remaining bytes from JSON stream
[ "Returns", "the", "remaining", "bytes", "from", "the", "JSON", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/JsonStream.php#L289-L303
32,865
violet-php/streaming-json-encoder
src/JsonStream.php
JsonStream.getMetadata
public function getMetadata($key = null) { $meta = [ 'timed_out' => false, 'blocked' => true, 'eof' => $this->eof(), 'unread_bytes' => strlen($this->buffer), 'stream_type' => get_class($this->encoder), 'wrapper_type' => 'OBJECT', 'wrapper_data' => [ 'step' => $this->encoder->key(), 'errors' => $this->encoder->getErrors(), ], 'mode' => 'r', 'seekable' => true, 'uri' => '', ]; return $key === null ? $meta : (isset($meta[$key]) ? $meta[$key] : null); }
php
public function getMetadata($key = null) { $meta = [ 'timed_out' => false, 'blocked' => true, 'eof' => $this->eof(), 'unread_bytes' => strlen($this->buffer), 'stream_type' => get_class($this->encoder), 'wrapper_type' => 'OBJECT', 'wrapper_data' => [ 'step' => $this->encoder->key(), 'errors' => $this->encoder->getErrors(), ], 'mode' => 'r', 'seekable' => true, 'uri' => '', ]; return $key === null ? $meta : (isset($meta[$key]) ? $meta[$key] : null); }
[ "public", "function", "getMetadata", "(", "$", "key", "=", "null", ")", "{", "$", "meta", "=", "[", "'timed_out'", "=>", "false", ",", "'blocked'", "=>", "true", ",", "'eof'", "=>", "$", "this", "->", "eof", "(", ")", ",", "'unread_bytes'", "=>", "strlen", "(", "$", "this", "->", "buffer", ")", ",", "'stream_type'", "=>", "get_class", "(", "$", "this", "->", "encoder", ")", ",", "'wrapper_type'", "=>", "'OBJECT'", ",", "'wrapper_data'", "=>", "[", "'step'", "=>", "$", "this", "->", "encoder", "->", "key", "(", ")", ",", "'errors'", "=>", "$", "this", "->", "encoder", "->", "getErrors", "(", ")", ",", "]", ",", "'mode'", "=>", "'r'", ",", "'seekable'", "=>", "true", ",", "'uri'", "=>", "''", ",", "]", ";", "return", "$", "key", "===", "null", "?", "$", "meta", ":", "(", "isset", "(", "$", "meta", "[", "$", "key", "]", ")", "?", "$", "meta", "[", "$", "key", "]", ":", "null", ")", ";", "}" ]
Returns the metadata related to the JSON stream. No underlying PHP resource exists for the stream, but this method will still return relevant information regarding the stream that is similar to PHP stream meta data. @param string|null $key The key of the value to return @return array|mixed|null The meta data array, a specific value or null if not defined
[ "Returns", "the", "metadata", "related", "to", "the", "JSON", "stream", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/JsonStream.php#L315-L334
32,866
violet-php/streaming-json-encoder
src/StreamJsonEncoder.php
StreamJsonEncoder.write
protected function write($string, $token) { if ($this->stream === null) { echo $string; } else { $callback = $this->stream; $callback($string, $token); } $this->bytes += strlen($string); }
php
protected function write($string, $token) { if ($this->stream === null) { echo $string; } else { $callback = $this->stream; $callback($string, $token); } $this->bytes += strlen($string); }
[ "protected", "function", "write", "(", "$", "string", ",", "$", "token", ")", "{", "if", "(", "$", "this", "->", "stream", "===", "null", ")", "{", "echo", "$", "string", ";", "}", "else", "{", "$", "callback", "=", "$", "this", "->", "stream", ";", "$", "callback", "(", "$", "string", ",", "$", "token", ")", ";", "}", "$", "this", "->", "bytes", "+=", "strlen", "(", "$", "string", ")", ";", "}" ]
Echoes to given string or passes it to the stream callback. @param string $string The string to output @param int $token The type of the string
[ "Echoes", "to", "given", "string", "or", "passes", "it", "to", "the", "stream", "callback", "." ]
12b3b808b1f9d0fae74b5be38255aca1846836ce
https://github.com/violet-php/streaming-json-encoder/blob/12b3b808b1f9d0fae74b5be38255aca1846836ce/src/StreamJsonEncoder.php#L85-L95
32,867
leroy-merlin-br/mongolid-laravel
src/Validation/Rules.php
Rules.message
public function message(string $message, string $attribute, string $rule): string { if ("validation.{$rule}" !== $message) { return $message; } return $this->getTranslatedMessageFallback( str_replace('mongolid_', '', $rule), $attribute ); }
php
public function message(string $message, string $attribute, string $rule): string { if ("validation.{$rule}" !== $message) { return $message; } return $this->getTranslatedMessageFallback( str_replace('mongolid_', '', $rule), $attribute ); }
[ "public", "function", "message", "(", "string", "$", "message", ",", "string", "$", "attribute", ",", "string", "$", "rule", ")", ":", "string", "{", "if", "(", "\"validation.{$rule}\"", "!==", "$", "message", ")", "{", "return", "$", "message", ";", "}", "return", "$", "this", "->", "getTranslatedMessageFallback", "(", "str_replace", "(", "'mongolid_'", ",", "''", ",", "$", "rule", ")", ",", "$", "attribute", ")", ";", "}" ]
Error message with fallback from Laravel rules 'unique' and 'exists'.
[ "Error", "message", "with", "fallback", "from", "Laravel", "rules", "unique", "and", "exists", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/Validation/Rules.php#L80-L90
32,868
leroy-merlin-br/mongolid-laravel
src/Validation/Rules.php
Rules.requireParameterCount
private function requireParameterCount(int $count, array $parameters, string $rule): void { if (count($parameters) < $count) { throw new InvalidArgumentException("Validation rule {$rule} requires at least {$count} parameters."); } }
php
private function requireParameterCount(int $count, array $parameters, string $rule): void { if (count($parameters) < $count) { throw new InvalidArgumentException("Validation rule {$rule} requires at least {$count} parameters."); } }
[ "private", "function", "requireParameterCount", "(", "int", "$", "count", ",", "array", "$", "parameters", ",", "string", "$", "rule", ")", ":", "void", "{", "if", "(", "count", "(", "$", "parameters", ")", "<", "$", "count", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Validation rule {$rule} requires at least {$count} parameters.\"", ")", ";", "}", "}" ]
Require a certain number of parameters to be present. @throws InvalidArgumentException
[ "Require", "a", "certain", "number", "of", "parameters", "to", "be", "present", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/Validation/Rules.php#L126-L131
32,869
leroy-merlin-br/mongolid-laravel
src/Validation/Rules.php
Rules.hasResults
private function hasResults(string $collection, array $query): bool { $mongolidConnection = $this->pool->getConnection(); $connection = $mongolidConnection->getRawConnection(); $database = $mongolidConnection->defaultDatabase; return (bool) $connection->$database->$collection->count($query); }
php
private function hasResults(string $collection, array $query): bool { $mongolidConnection = $this->pool->getConnection(); $connection = $mongolidConnection->getRawConnection(); $database = $mongolidConnection->defaultDatabase; return (bool) $connection->$database->$collection->count($query); }
[ "private", "function", "hasResults", "(", "string", "$", "collection", ",", "array", "$", "query", ")", ":", "bool", "{", "$", "mongolidConnection", "=", "$", "this", "->", "pool", "->", "getConnection", "(", ")", ";", "$", "connection", "=", "$", "mongolidConnection", "->", "getRawConnection", "(", ")", ";", "$", "database", "=", "$", "mongolidConnection", "->", "defaultDatabase", ";", "return", "(", "bool", ")", "$", "connection", "->", "$", "database", "->", "$", "collection", "->", "count", "(", "$", "query", ")", ";", "}" ]
Run query on database and check for a result count.
[ "Run", "query", "on", "database", "and", "check", "for", "a", "result", "count", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/Validation/Rules.php#L136-L143
32,870
leroy-merlin-br/mongolid-laravel
src/Validation/Rules.php
Rules.getTranslatedMessageFallback
private function getTranslatedMessageFallback(string $rule, string $attribute): string { $attributeKey = "validation.attributes.$attribute"; $attributeTranslation = trans($attributeKey); $attribute = $attributeTranslation === $attributeKey ? $attribute : $attributeTranslation; return trans("validation.{$rule}", compact('attribute')); }
php
private function getTranslatedMessageFallback(string $rule, string $attribute): string { $attributeKey = "validation.attributes.$attribute"; $attributeTranslation = trans($attributeKey); $attribute = $attributeTranslation === $attributeKey ? $attribute : $attributeTranslation; return trans("validation.{$rule}", compact('attribute')); }
[ "private", "function", "getTranslatedMessageFallback", "(", "string", "$", "rule", ",", "string", "$", "attribute", ")", ":", "string", "{", "$", "attributeKey", "=", "\"validation.attributes.$attribute\"", ";", "$", "attributeTranslation", "=", "trans", "(", "$", "attributeKey", ")", ";", "$", "attribute", "=", "$", "attributeTranslation", "===", "$", "attributeKey", "?", "$", "attribute", ":", "$", "attributeTranslation", ";", "return", "trans", "(", "\"validation.{$rule}\"", ",", "compact", "(", "'attribute'", ")", ")", ";", "}" ]
If the user has not created a translation for 'mongolid_unique' rule, this method will attempt to get the translation for 'unique' rule. The same with 'mongolid_exists' and 'exists'. Since it is not easy to use the framework to make this message, this is a simple approach.
[ "If", "the", "user", "has", "not", "created", "a", "translation", "for", "mongolid_unique", "rule", "this", "method", "will", "attempt", "to", "get", "the", "translation", "for", "unique", "rule", ".", "The", "same", "with", "mongolid_exists", "and", "exists", ".", "Since", "it", "is", "not", "easy", "to", "use", "the", "framework", "to", "make", "this", "message", "this", "is", "a", "simple", "approach", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/Validation/Rules.php#L166-L174
32,871
leroy-merlin-br/mongolid-laravel
src/FailedJobsService.php
FailedJobsService.rawCollection
protected function rawCollection(): Collection { $conn = $this->connPool->getConnection(); $database = $conn->defaultDatabase; return $conn->getRawConnection()->$database->{$this->collection}; }
php
protected function rawCollection(): Collection { $conn = $this->connPool->getConnection(); $database = $conn->defaultDatabase; return $conn->getRawConnection()->$database->{$this->collection}; }
[ "protected", "function", "rawCollection", "(", ")", ":", "Collection", "{", "$", "conn", "=", "$", "this", "->", "connPool", "->", "getConnection", "(", ")", ";", "$", "database", "=", "$", "conn", "->", "defaultDatabase", ";", "return", "$", "conn", "->", "getRawConnection", "(", ")", "->", "$", "database", "->", "{", "$", "this", "->", "collection", "}", ";", "}" ]
Get the actual MongoDB Collection object.
[ "Get", "the", "actual", "MongoDB", "Collection", "object", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/FailedJobsService.php#L89-L95
32,872
leroy-merlin-br/mongolid-laravel
src/MongolidFailedJobProvider.php
MongolidFailedJobProvider.all
public function all() { foreach ($this->failedJobs->all() as $job) { $jobs[] = $this->presentJob($job); } return $jobs ?? []; }
php
public function all() { foreach ($this->failedJobs->all() as $job) { $jobs[] = $this->presentJob($job); } return $jobs ?? []; }
[ "public", "function", "all", "(", ")", "{", "foreach", "(", "$", "this", "->", "failedJobs", "->", "all", "(", ")", "as", "$", "job", ")", "{", "$", "jobs", "[", "]", "=", "$", "this", "->", "presentJob", "(", "$", "job", ")", ";", "}", "return", "$", "jobs", "??", "[", "]", ";", "}" ]
Get a list of all of the failed jobs. @return array
[ "Get", "a", "list", "of", "all", "of", "the", "failed", "jobs", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidFailedJobProvider.php#L54-L61
32,873
leroy-merlin-br/mongolid-laravel
src/MongolidFailedJobProvider.php
MongolidFailedJobProvider.presentJob
private function presentJob($job) { $job = (array) $job; return (object) [ 'id' => (string) $job['_id'], 'connection' => $job['connection'], 'queue' => $job['queue'], 'payload' => $job['payload'], 'exception' => $job['exception'], 'failed_at' => LocalDateTime::format($job['failed_at'], DateTime::ATOM), ]; }
php
private function presentJob($job) { $job = (array) $job; return (object) [ 'id' => (string) $job['_id'], 'connection' => $job['connection'], 'queue' => $job['queue'], 'payload' => $job['payload'], 'exception' => $job['exception'], 'failed_at' => LocalDateTime::format($job['failed_at'], DateTime::ATOM), ]; }
[ "private", "function", "presentJob", "(", "$", "job", ")", "{", "$", "job", "=", "(", "array", ")", "$", "job", ";", "return", "(", "object", ")", "[", "'id'", "=>", "(", "string", ")", "$", "job", "[", "'_id'", "]", ",", "'connection'", "=>", "$", "job", "[", "'connection'", "]", ",", "'queue'", "=>", "$", "job", "[", "'queue'", "]", ",", "'payload'", "=>", "$", "job", "[", "'payload'", "]", ",", "'exception'", "=>", "$", "job", "[", "'exception'", "]", ",", "'failed_at'", "=>", "LocalDateTime", "::", "format", "(", "$", "job", "[", "'failed_at'", "]", ",", "DateTime", "::", "ATOM", ")", ",", "]", ";", "}" ]
Prepare job to be consumed by Laravel Commands. @param object $job @return object
[ "Prepare", "job", "to", "be", "consumed", "by", "Laravel", "Commands", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidFailedJobProvider.php#L104-L116
32,874
leroy-merlin-br/mongolid-laravel
src/MongolidModel.php
MongolidModel.save
public function save(bool $force = false) { if ($this->localMockHasExpectationsFor('save')) { return $this->getLocalMock()->save(); } if ($force || $this->isValid()) { $this->hashAttributes(); return parent::save(); } return false; }
php
public function save(bool $force = false) { if ($this->localMockHasExpectationsFor('save')) { return $this->getLocalMock()->save(); } if ($force || $this->isValid()) { $this->hashAttributes(); return parent::save(); } return false; }
[ "public", "function", "save", "(", "bool", "$", "force", "=", "false", ")", "{", "if", "(", "$", "this", "->", "localMockHasExpectationsFor", "(", "'save'", ")", ")", "{", "return", "$", "this", "->", "getLocalMock", "(", ")", "->", "save", "(", ")", ";", "}", "if", "(", "$", "force", "||", "$", "this", "->", "isValid", "(", ")", ")", "{", "$", "this", "->", "hashAttributes", "(", ")", ";", "return", "parent", "::", "save", "(", ")", ";", "}", "return", "false", ";", "}" ]
Save the model to the database if it's valid. This method also checks for the presence of the localMock in order to call the save method into the existing Mock in order not to touch the database. @param bool $force force save even if the object is invalid @return bool
[ "Save", "the", "model", "to", "the", "database", "if", "it", "s", "valid", ".", "This", "method", "also", "checks", "for", "the", "presence", "of", "the", "localMock", "in", "order", "to", "call", "the", "save", "method", "into", "the", "existing", "Mock", "in", "order", "not", "to", "touch", "the", "database", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidModel.php#L74-L87
32,875
leroy-merlin-br/mongolid-laravel
src/MongolidModel.php
MongolidModel.hashAttributes
protected function hashAttributes() { foreach ($this->hashedAttributes as $attr) { // Hash attribute if changed if (!isset($this->original[$attr]) || $this->$attr != $this->original[$attr]) { $this->$attr = app(Hasher::class)->make($this->$attr); } // Removes any confirmation field before saving it into the database $confirmationField = $attr.'_confirmation'; if ($this->$confirmationField) { unset($this->$confirmationField); } } }
php
protected function hashAttributes() { foreach ($this->hashedAttributes as $attr) { // Hash attribute if changed if (!isset($this->original[$attr]) || $this->$attr != $this->original[$attr]) { $this->$attr = app(Hasher::class)->make($this->$attr); } // Removes any confirmation field before saving it into the database $confirmationField = $attr.'_confirmation'; if ($this->$confirmationField) { unset($this->$confirmationField); } } }
[ "protected", "function", "hashAttributes", "(", ")", "{", "foreach", "(", "$", "this", "->", "hashedAttributes", "as", "$", "attr", ")", "{", "// Hash attribute if changed", "if", "(", "!", "isset", "(", "$", "this", "->", "original", "[", "$", "attr", "]", ")", "||", "$", "this", "->", "$", "attr", "!=", "$", "this", "->", "original", "[", "$", "attr", "]", ")", "{", "$", "this", "->", "$", "attr", "=", "app", "(", "Hasher", "::", "class", ")", "->", "make", "(", "$", "this", "->", "$", "attr", ")", ";", "}", "// Removes any confirmation field before saving it into the database", "$", "confirmationField", "=", "$", "attr", ".", "'_confirmation'", ";", "if", "(", "$", "this", "->", "$", "confirmationField", ")", "{", "unset", "(", "$", "this", "->", "$", "confirmationField", ")", ";", "}", "}", "}" ]
Hashes the attributes specified in the hashedAttributes array.
[ "Hashes", "the", "attributes", "specified", "in", "the", "hashedAttributes", "array", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidModel.php#L202-L216
32,876
leroy-merlin-br/mongolid-laravel
src/MongolidModel.php
MongolidModel.localMockHasExpectationsFor
protected function localMockHasExpectationsFor(string $method): bool { return $this->hasLocalMock() && $this->getLocalMock()->mockery_getExpectationsFor($method); }
php
protected function localMockHasExpectationsFor(string $method): bool { return $this->hasLocalMock() && $this->getLocalMock()->mockery_getExpectationsFor($method); }
[ "protected", "function", "localMockHasExpectationsFor", "(", "string", "$", "method", ")", ":", "bool", "{", "return", "$", "this", "->", "hasLocalMock", "(", ")", "&&", "$", "this", "->", "getLocalMock", "(", ")", "->", "mockery_getExpectationsFor", "(", "$", "method", ")", ";", "}" ]
Check for a expectation for given method on local mock. @param string $method name of the method being checked
[ "Check", "for", "a", "expectation", "for", "given", "method", "on", "local", "mock", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidModel.php#L295-L298
32,877
leroy-merlin-br/mongolid-laravel
src/MongolidModel.php
MongolidModel.callMockOrParent
protected static function callMockOrParent(string $method, array $arguments) { $classToCall = 'parent'; $class = get_called_class(); $mock = static::$mock[$class] ?? null; if ($mock && $mock->mockery_getExpectationsFor($method)) { $classToCall = $mock; } return call_user_func_array([$classToCall, $method], $arguments); }
php
protected static function callMockOrParent(string $method, array $arguments) { $classToCall = 'parent'; $class = get_called_class(); $mock = static::$mock[$class] ?? null; if ($mock && $mock->mockery_getExpectationsFor($method)) { $classToCall = $mock; } return call_user_func_array([$classToCall, $method], $arguments); }
[ "protected", "static", "function", "callMockOrParent", "(", "string", "$", "method", ",", "array", "$", "arguments", ")", "{", "$", "classToCall", "=", "'parent'", ";", "$", "class", "=", "get_called_class", "(", ")", ";", "$", "mock", "=", "static", "::", "$", "mock", "[", "$", "class", "]", "??", "null", ";", "if", "(", "$", "mock", "&&", "$", "mock", "->", "mockery_getExpectationsFor", "(", "$", "method", ")", ")", "{", "$", "classToCall", "=", "$", "mock", ";", "}", "return", "call_user_func_array", "(", "[", "$", "classToCall", ",", "$", "method", "]", ",", "$", "arguments", ")", ";", "}" ]
Calls mock method if its have expectations. Calls parent method otherwise. @param string $method name of the method being called @param array $arguments arguments to pass in method call @return mixed See parent implementation
[ "Calls", "mock", "method", "if", "its", "have", "expectations", ".", "Calls", "parent", "method", "otherwise", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidModel.php#L385-L396
32,878
leroy-merlin-br/mongolid-laravel
src/MongolidServiceProvider.php
MongolidServiceProvider.registerConnector
public function registerConnector() { MongolidIoc::setContainer($this->app); $this->app->singleton( Pool::class, function ($app) { $config = $app['config']->get('database.mongodb.default') ?? []; $connectionString = $this->buildConnectionString($config); $options = $config['options'] ?? []; $driverOptions = $config['driver_options'] ?? []; $connection = new Connection($connectionString, $options, $driverOptions); $connection->defaultDatabase = $config['database'] ?? 'mongolid'; $pool = new Pool(); $pool->addConnection($connection); return $pool; } ); $this->app->singleton( EventTriggerService::class, function ($app) { $eventService = new EventTriggerService(); $eventService->registerEventDispatcher($app->make(LaravelEventTrigger::class)); return $eventService; } ); $this->app->singleton( CacheComponentInterface::class, function ($app) { return new LaravelCacheComponent($app[CacheRepository::class]); } ); }
php
public function registerConnector() { MongolidIoc::setContainer($this->app); $this->app->singleton( Pool::class, function ($app) { $config = $app['config']->get('database.mongodb.default') ?? []; $connectionString = $this->buildConnectionString($config); $options = $config['options'] ?? []; $driverOptions = $config['driver_options'] ?? []; $connection = new Connection($connectionString, $options, $driverOptions); $connection->defaultDatabase = $config['database'] ?? 'mongolid'; $pool = new Pool(); $pool->addConnection($connection); return $pool; } ); $this->app->singleton( EventTriggerService::class, function ($app) { $eventService = new EventTriggerService(); $eventService->registerEventDispatcher($app->make(LaravelEventTrigger::class)); return $eventService; } ); $this->app->singleton( CacheComponentInterface::class, function ($app) { return new LaravelCacheComponent($app[CacheRepository::class]); } ); }
[ "public", "function", "registerConnector", "(", ")", "{", "MongolidIoc", "::", "setContainer", "(", "$", "this", "->", "app", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "Pool", "::", "class", ",", "function", "(", "$", "app", ")", "{", "$", "config", "=", "$", "app", "[", "'config'", "]", "->", "get", "(", "'database.mongodb.default'", ")", "??", "[", "]", ";", "$", "connectionString", "=", "$", "this", "->", "buildConnectionString", "(", "$", "config", ")", ";", "$", "options", "=", "$", "config", "[", "'options'", "]", "??", "[", "]", ";", "$", "driverOptions", "=", "$", "config", "[", "'driver_options'", "]", "??", "[", "]", ";", "$", "connection", "=", "new", "Connection", "(", "$", "connectionString", ",", "$", "options", ",", "$", "driverOptions", ")", ";", "$", "connection", "->", "defaultDatabase", "=", "$", "config", "[", "'database'", "]", "??", "'mongolid'", ";", "$", "pool", "=", "new", "Pool", "(", ")", ";", "$", "pool", "->", "addConnection", "(", "$", "connection", ")", ";", "return", "$", "pool", ";", "}", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "EventTriggerService", "::", "class", ",", "function", "(", "$", "app", ")", "{", "$", "eventService", "=", "new", "EventTriggerService", "(", ")", ";", "$", "eventService", "->", "registerEventDispatcher", "(", "$", "app", "->", "make", "(", "LaravelEventTrigger", "::", "class", ")", ")", ";", "return", "$", "eventService", ";", "}", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "CacheComponentInterface", "::", "class", ",", "function", "(", "$", "app", ")", "{", "return", "new", "LaravelCacheComponent", "(", "$", "app", "[", "CacheRepository", "::", "class", "]", ")", ";", "}", ")", ";", "}" ]
Register MongoDbConnector within the application.
[ "Register", "MongoDbConnector", "within", "the", "application", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidServiceProvider.php#L47-L83
32,879
leroy-merlin-br/mongolid-laravel
src/MongolidServiceProvider.php
MongolidServiceProvider.replaceQueueFailer
private function replaceQueueFailer() { $this->app->extend( 'queue.failer', function ($concrete, $app) { $collection = $app['config']['queue.failed.collection']; return isset($collection) ? $this->buildMongolidFailedJobProvider($app, $collection) : new NullFailedJobProvider(); } ); }
php
private function replaceQueueFailer() { $this->app->extend( 'queue.failer', function ($concrete, $app) { $collection = $app['config']['queue.failed.collection']; return isset($collection) ? $this->buildMongolidFailedJobProvider($app, $collection) : new NullFailedJobProvider(); } ); }
[ "private", "function", "replaceQueueFailer", "(", ")", "{", "$", "this", "->", "app", "->", "extend", "(", "'queue.failer'", ",", "function", "(", "$", "concrete", ",", "$", "app", ")", "{", "$", "collection", "=", "$", "app", "[", "'config'", "]", "[", "'queue.failed.collection'", "]", ";", "return", "isset", "(", "$", "collection", ")", "?", "$", "this", "->", "buildMongolidFailedJobProvider", "(", "$", "app", ",", "$", "collection", ")", ":", "new", "NullFailedJobProvider", "(", ")", ";", "}", ")", ";", "}" ]
Rebind Laravel Failed Queue Job Provider to use Mongolid.
[ "Rebind", "Laravel", "Failed", "Queue", "Job", "Provider", "to", "use", "Mongolid", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/MongolidServiceProvider.php#L173-L185
32,880
leroy-merlin-br/mongolid-laravel
src/Migrations/Commands/FreshCommand.php
FreshCommand.dropDatabase
protected function dropDatabase($database) { $connection = $this->pool->getConnection(); $database = $database ?? $connection->defaultDatabase; $connection->getRawConnection()->dropDatabase($database); }
php
protected function dropDatabase($database) { $connection = $this->pool->getConnection(); $database = $database ?? $connection->defaultDatabase; $connection->getRawConnection()->dropDatabase($database); }
[ "protected", "function", "dropDatabase", "(", "$", "database", ")", "{", "$", "connection", "=", "$", "this", "->", "pool", "->", "getConnection", "(", ")", ";", "$", "database", "=", "$", "database", "??", "$", "connection", "->", "defaultDatabase", ";", "$", "connection", "->", "getRawConnection", "(", ")", "->", "dropDatabase", "(", "$", "database", ")", ";", "}" ]
Drop all of the database collections. @param string $database
[ "Drop", "all", "of", "the", "database", "collections", "." ]
ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf
https://github.com/leroy-merlin-br/mongolid-laravel/blob/ac0998085ea95fe58c7d0b76bc8e8a714f6eadcf/src/Migrations/Commands/FreshCommand.php#L79-L85
32,881
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/TraceEntry.php
TraceEntry.assignAttributes
protected function assignAttributes() { $parsed = $this->parser->parseTraceEntry($this->content); foreach ($parsed as $key => $value) { $this->{$key} = $value; } }
php
protected function assignAttributes() { $parsed = $this->parser->parseTraceEntry($this->content); foreach ($parsed as $key => $value) { $this->{$key} = $value; } }
[ "protected", "function", "assignAttributes", "(", ")", "{", "$", "parsed", "=", "$", "this", "->", "parser", "->", "parseTraceEntry", "(", "$", "this", "->", "content", ")", ";", "foreach", "(", "$", "parsed", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "{", "$", "key", "}", "=", "$", "value", ";", "}", "}" ]
Parses content of the trace entry and assigns each information to the corresponding attribute in the trace entry. @return void
[ "Parses", "content", "of", "the", "trace", "entry", "and", "assigns", "each", "information", "to", "the", "corresponding", "attribute", "in", "the", "trace", "entry", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/TraceEntry.php#L82-L89
32,882
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/LogEntry.php
LogEntry.getAttribute
public function getAttribute($key) { $key = $this->reFormatForCompatibility($key); return (property_exists($this, $key)) ? $this->{$key} : null; }
php
public function getAttribute($key) { $key = $this->reFormatForCompatibility($key); return (property_exists($this, $key)) ? $this->{$key} : null; }
[ "public", "function", "getAttribute", "(", "$", "key", ")", "{", "$", "key", "=", "$", "this", "->", "reFormatForCompatibility", "(", "$", "key", ")", ";", "return", "(", "property_exists", "(", "$", "this", ",", "$", "key", ")", ")", "?", "$", "this", "->", "{", "$", "key", "}", ":", "null", ";", "}" ]
Retrieves an attribute of the log entry @param $key @return mixed
[ "Retrieves", "an", "attribute", "of", "the", "log", "entry" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/LogEntry.php#L127-L132
32,883
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/LogEntry.php
LogEntry.getOriginal
public function getOriginal($key) { $key = $this->reFormatForCompatibility($key); return (array_key_exists($key, $this->attributes)) ? $this->attributes[$key] : null; }
php
public function getOriginal($key) { $key = $this->reFormatForCompatibility($key); return (array_key_exists($key, $this->attributes)) ? $this->attributes[$key] : null; }
[ "public", "function", "getOriginal", "(", "$", "key", ")", "{", "$", "key", "=", "$", "this", "->", "reFormatForCompatibility", "(", "$", "key", ")", ";", "return", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "attributes", ")", ")", "?", "$", "this", "->", "attributes", "[", "$", "key", "]", ":", "null", ";", "}" ]
Get original value of an property of the log entry @param string $key @return void
[ "Get", "original", "value", "of", "an", "property", "of", "the", "log", "entry" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/LogEntry.php#L141-L146
32,884
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/LogEntry.php
LogEntry.delete
public function delete() { $rawContent = $this->getRawContent(); $filePath = $this->attributes['file_path']; $logContent = file_get_contents($filePath); $logContent = str_replace($rawContent, '', $logContent); file_put_contents($filePath, $logContent); return true; }
php
public function delete() { $rawContent = $this->getRawContent(); $filePath = $this->attributes['file_path']; $logContent = file_get_contents($filePath); $logContent = str_replace($rawContent, '', $logContent); file_put_contents($filePath, $logContent); return true; }
[ "public", "function", "delete", "(", ")", "{", "$", "rawContent", "=", "$", "this", "->", "getRawContent", "(", ")", ";", "$", "filePath", "=", "$", "this", "->", "attributes", "[", "'file_path'", "]", ";", "$", "logContent", "=", "file_get_contents", "(", "$", "filePath", ")", ";", "$", "logContent", "=", "str_replace", "(", "$", "rawContent", ",", "''", ",", "$", "logContent", ")", ";", "file_put_contents", "(", "$", "filePath", ",", "$", "logContent", ")", ";", "return", "true", ";", "}" ]
Removes the current entry from the log file. @return bool
[ "Removes", "the", "current", "entry", "from", "the", "log", "file", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/LogEntry.php#L191-L201
32,885
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/LogEntry.php
LogEntry.setContext
protected function setContext($context = null) { if ($context) { $this->context = new LogContext($this->parser, $context); } }
php
protected function setContext($context = null) { if ($context) { $this->context = new LogContext($this->parser, $context); } }
[ "protected", "function", "setContext", "(", "$", "context", "=", "null", ")", "{", "if", "(", "$", "context", ")", "{", "$", "this", "->", "context", "=", "new", "LogContext", "(", "$", "this", "->", "parser", ",", "$", "context", ")", ";", "}", "}" ]
Sets the log entry's context property. @param string $context @return void
[ "Sets", "the", "log", "entry", "s", "context", "property", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/LogEntry.php#L310-L315
32,886
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/LogEntry.php
LogEntry.setStackTraces
protected function setStackTraces($stackTraces = null) { $traces = $this->parser->parseStackTrace($stackTraces); $output = []; foreach ($traces as $trace) { $output[] = new TraceEntry($this->parser, $trace); } $this->stack_traces = new Collection($output); }
php
protected function setStackTraces($stackTraces = null) { $traces = $this->parser->parseStackTrace($stackTraces); $output = []; foreach ($traces as $trace) { $output[] = new TraceEntry($this->parser, $trace); } $this->stack_traces = new Collection($output); }
[ "protected", "function", "setStackTraces", "(", "$", "stackTraces", "=", "null", ")", "{", "$", "traces", "=", "$", "this", "->", "parser", "->", "parseStackTrace", "(", "$", "stackTraces", ")", ";", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "traces", "as", "$", "trace", ")", "{", "$", "output", "[", "]", "=", "new", "TraceEntry", "(", "$", "this", "->", "parser", ",", "$", "trace", ")", ";", "}", "$", "this", "->", "stack_traces", "=", "new", "Collection", "(", "$", "output", ")", ";", "}" ]
Sets the log entry's level property. @param $stackTraces @return void
[ "Sets", "the", "log", "entry", "s", "level", "property", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/LogEntry.php#L324-L335
32,887
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/LogEntry.php
LogEntry.assignAttributes
protected function assignAttributes() { $bodyParsed = $this->parser->parseLogBody($this->attributes['body']); $this->attributes['context'] = $bodyParsed['context']; $this->attributes['stack_traces'] = $bodyParsed['stack_traces']; $this->setId($this->generateId()); $this->setDate($this->attributes['date']); $this->setEnvironment($this->attributes['environment']); $this->setLevel($this->attributes['level']); $this->setFilePath($this->attributes['file_path']); $this->setContext($this->attributes['context']); $this->setStackTraces($this->attributes['stack_traces']); }
php
protected function assignAttributes() { $bodyParsed = $this->parser->parseLogBody($this->attributes['body']); $this->attributes['context'] = $bodyParsed['context']; $this->attributes['stack_traces'] = $bodyParsed['stack_traces']; $this->setId($this->generateId()); $this->setDate($this->attributes['date']); $this->setEnvironment($this->attributes['environment']); $this->setLevel($this->attributes['level']); $this->setFilePath($this->attributes['file_path']); $this->setContext($this->attributes['context']); $this->setStackTraces($this->attributes['stack_traces']); }
[ "protected", "function", "assignAttributes", "(", ")", "{", "$", "bodyParsed", "=", "$", "this", "->", "parser", "->", "parseLogBody", "(", "$", "this", "->", "attributes", "[", "'body'", "]", ")", ";", "$", "this", "->", "attributes", "[", "'context'", "]", "=", "$", "bodyParsed", "[", "'context'", "]", ";", "$", "this", "->", "attributes", "[", "'stack_traces'", "]", "=", "$", "bodyParsed", "[", "'stack_traces'", "]", ";", "$", "this", "->", "setId", "(", "$", "this", "->", "generateId", "(", ")", ")", ";", "$", "this", "->", "setDate", "(", "$", "this", "->", "attributes", "[", "'date'", "]", ")", ";", "$", "this", "->", "setEnvironment", "(", "$", "this", "->", "attributes", "[", "'environment'", "]", ")", ";", "$", "this", "->", "setLevel", "(", "$", "this", "->", "attributes", "[", "'level'", "]", ")", ";", "$", "this", "->", "setFilePath", "(", "$", "this", "->", "attributes", "[", "'file_path'", "]", ")", ";", "$", "this", "->", "setContext", "(", "$", "this", "->", "attributes", "[", "'context'", "]", ")", ";", "$", "this", "->", "setStackTraces", "(", "$", "this", "->", "attributes", "[", "'stack_traces'", "]", ")", ";", "}" ]
Assigns the valid keys in the attributes array to the properties in the log entry. @return void
[ "Assigns", "the", "valid", "keys", "in", "the", "attributes", "array", "to", "the", "properties", "in", "the", "log", "entry", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/LogEntry.php#L357-L370
32,888
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Entities/LogEntry.php
LogEntry.reFormatForCompatibility
protected function reFormatForCompatibility($property) { switch (true) { case ($property == 'header'): $property = 'context'; break; case ($property == 'stack'): $property = 'stack_traces'; break; case ($property == 'filePath'): $property = 'file_path'; break; default: # code... break; } return $property; }
php
protected function reFormatForCompatibility($property) { switch (true) { case ($property == 'header'): $property = 'context'; break; case ($property == 'stack'): $property = 'stack_traces'; break; case ($property == 'filePath'): $property = 'file_path'; break; default: # code... break; } return $property; }
[ "protected", "function", "reFormatForCompatibility", "(", "$", "property", ")", "{", "switch", "(", "true", ")", "{", "case", "(", "$", "property", "==", "'header'", ")", ":", "$", "property", "=", "'context'", ";", "break", ";", "case", "(", "$", "property", "==", "'stack'", ")", ":", "$", "property", "=", "'stack_traces'", ";", "break", ";", "case", "(", "$", "property", "==", "'filePath'", ")", ":", "$", "property", "=", "'file_path'", ";", "break", ";", "default", ":", "# code...", "break", ";", "}", "return", "$", "property", ";", "}" ]
Convert the property strings to be compatible with older version @param string $property @return string
[ "Convert", "the", "property", "strings", "to", "be", "compatible", "with", "older", "version" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Entities/LogEntry.php#L379-L400
32,889
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Levelable.php
Levelable.filter
public function filter($level, $allowed) { if (empty($allowed)) { return true; } if (is_array($allowed)) { $merges = array_values(array_uintersect($this->levels, $allowed, "strcasecmp")); if (in_array(strtolower($level), $merges)) { return true; } } return false; }
php
public function filter($level, $allowed) { if (empty($allowed)) { return true; } if (is_array($allowed)) { $merges = array_values(array_uintersect($this->levels, $allowed, "strcasecmp")); if (in_array(strtolower($level), $merges)) { return true; } } return false; }
[ "public", "function", "filter", "(", "$", "level", ",", "$", "allowed", ")", "{", "if", "(", "empty", "(", "$", "allowed", ")", ")", "{", "return", "true", ";", "}", "if", "(", "is_array", "(", "$", "allowed", ")", ")", "{", "$", "merges", "=", "array_values", "(", "array_uintersect", "(", "$", "this", "->", "levels", ",", "$", "allowed", ",", "\"strcasecmp\"", ")", ")", ";", "if", "(", "in_array", "(", "strtolower", "(", "$", "level", ")", ",", "$", "merges", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Filter logs by level @param string $level Level need to check @param array $allowed Strict levels to filter @return bool
[ "Filter", "logs", "by", "level" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Levelable.php#L49-L63
32,890
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.level
public function level($level) { if (empty($level)) { $level = []; } elseif (is_string($level)) { $level = explode(',', str_replace(' ', '', $level)); } else { $level = is_array($level) ? $level : func_get_args(); } $this->setLevel($level); return $this; }
php
public function level($level) { if (empty($level)) { $level = []; } elseif (is_string($level)) { $level = explode(',', str_replace(' ', '', $level)); } else { $level = is_array($level) ? $level : func_get_args(); } $this->setLevel($level); return $this; }
[ "public", "function", "level", "(", "$", "level", ")", "{", "if", "(", "empty", "(", "$", "level", ")", ")", "{", "$", "level", "=", "[", "]", ";", "}", "elseif", "(", "is_string", "(", "$", "level", ")", ")", "{", "$", "level", "=", "explode", "(", "','", ",", "str_replace", "(", "' '", ",", "''", ",", "$", "level", ")", ")", ";", "}", "else", "{", "$", "level", "=", "is_array", "(", "$", "level", ")", "?", "$", "level", ":", "func_get_args", "(", ")", ";", "}", "$", "this", "->", "setLevel", "(", "$", "level", ")", ";", "return", "$", "this", ";", "}" ]
Sets the level to sort the log entries by. @param mixed $level @return \Jackiedo\LogReader\LogReader
[ "Sets", "the", "level", "to", "sort", "the", "log", "entries", "by", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L264-L277
32,891
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.orderBy
public function orderBy($field, $direction = 'asc') { $this->setOrderByField($field); $this->setOrderByDirection($direction); return $this; }
php
public function orderBy($field, $direction = 'asc') { $this->setOrderByField($field); $this->setOrderByDirection($direction); return $this; }
[ "public", "function", "orderBy", "(", "$", "field", ",", "$", "direction", "=", "'asc'", ")", "{", "$", "this", "->", "setOrderByField", "(", "$", "field", ")", ";", "$", "this", "->", "setOrderByDirection", "(", "$", "direction", ")", ";", "return", "$", "this", ";", "}" ]
Sets the direction to return the log entries in. @param string $field @param string $direction @return \Jackiedo\LogReader\LogReader
[ "Sets", "the", "direction", "to", "return", "the", "log", "entries", "in", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L323-L329
32,892
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.get
public function get() { $entries = []; $files = $this->getLogFiles(); if (! is_array($files)) { throw new UnableToRetrieveLogFilesException('Unable to retrieve files from path: '.$this->getLogPath()); } foreach ($files as $log) { /* * Set the current log path for easy manipulation * of the file if needed */ $this->setCurrentLogPath($log['path']); /* * Parse the log into an array of entries, passing in the level * so it can be filtered */ $parsedLog = $this->parseLog($log['contents'], $this->getEnvironment(), $this->getLevel()); /* * Create a new LogEntry object for each parsed log entry */ foreach ($parsedLog as $entry) { $newEntry = new LogEntry($this->parser, $this->cache, $entry); /* * Check if the entry has already been read, * and if read entries should be included. * * If includeRead is false, and the entry is read, * then continue processing. */ if (!$this->includeRead && $newEntry->isRead()) { continue; } $entries[$newEntry->id] = $newEntry; } } return $this->postCollectionModifiers(new Collection($entries)); }
php
public function get() { $entries = []; $files = $this->getLogFiles(); if (! is_array($files)) { throw new UnableToRetrieveLogFilesException('Unable to retrieve files from path: '.$this->getLogPath()); } foreach ($files as $log) { /* * Set the current log path for easy manipulation * of the file if needed */ $this->setCurrentLogPath($log['path']); /* * Parse the log into an array of entries, passing in the level * so it can be filtered */ $parsedLog = $this->parseLog($log['contents'], $this->getEnvironment(), $this->getLevel()); /* * Create a new LogEntry object for each parsed log entry */ foreach ($parsedLog as $entry) { $newEntry = new LogEntry($this->parser, $this->cache, $entry); /* * Check if the entry has already been read, * and if read entries should be included. * * If includeRead is false, and the entry is read, * then continue processing. */ if (!$this->includeRead && $newEntry->isRead()) { continue; } $entries[$newEntry->id] = $newEntry; } } return $this->postCollectionModifiers(new Collection($entries)); }
[ "public", "function", "get", "(", ")", "{", "$", "entries", "=", "[", "]", ";", "$", "files", "=", "$", "this", "->", "getLogFiles", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "files", ")", ")", "{", "throw", "new", "UnableToRetrieveLogFilesException", "(", "'Unable to retrieve files from path: '", ".", "$", "this", "->", "getLogPath", "(", ")", ")", ";", "}", "foreach", "(", "$", "files", "as", "$", "log", ")", "{", "/*\n * Set the current log path for easy manipulation\n * of the file if needed\n */", "$", "this", "->", "setCurrentLogPath", "(", "$", "log", "[", "'path'", "]", ")", ";", "/*\n * Parse the log into an array of entries, passing in the level\n * so it can be filtered\n */", "$", "parsedLog", "=", "$", "this", "->", "parseLog", "(", "$", "log", "[", "'contents'", "]", ",", "$", "this", "->", "getEnvironment", "(", ")", ",", "$", "this", "->", "getLevel", "(", ")", ")", ";", "/*\n * Create a new LogEntry object for each parsed log entry\n */", "foreach", "(", "$", "parsedLog", "as", "$", "entry", ")", "{", "$", "newEntry", "=", "new", "LogEntry", "(", "$", "this", "->", "parser", ",", "$", "this", "->", "cache", ",", "$", "entry", ")", ";", "/*\n * Check if the entry has already been read,\n * and if read entries should be included.\n *\n * If includeRead is false, and the entry is read,\n * then continue processing.\n */", "if", "(", "!", "$", "this", "->", "includeRead", "&&", "$", "newEntry", "->", "isRead", "(", ")", ")", "{", "continue", ";", "}", "$", "entries", "[", "$", "newEntry", "->", "id", "]", "=", "$", "newEntry", ";", "}", "}", "return", "$", "this", "->", "postCollectionModifiers", "(", "new", "Collection", "(", "$", "entries", ")", ")", ";", "}" ]
Returns a Laravel collection of log entries. @throws \Jackiedo\LogReader\Exceptions\UnableToRetrieveLogFilesException @return Collection
[ "Returns", "a", "Laravel", "collection", "of", "log", "entries", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L338-L383
32,893
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.markAsRead
public function markAsRead() { $entries = $this->get(); $count = 0; foreach ($entries as $entry) { if ($entry->markAsRead()) { ++$count; } } return $count; }
php
public function markAsRead() { $entries = $this->get(); $count = 0; foreach ($entries as $entry) { if ($entry->markAsRead()) { ++$count; } } return $count; }
[ "public", "function", "markAsRead", "(", ")", "{", "$", "entries", "=", "$", "this", "->", "get", "(", ")", ";", "$", "count", "=", "0", ";", "foreach", "(", "$", "entries", "as", "$", "entry", ")", "{", "if", "(", "$", "entry", "->", "markAsRead", "(", ")", ")", "{", "++", "$", "count", ";", "}", "}", "return", "$", "count", ";", "}" ]
Marks all retrieved log entries as read and returns the number of entries that have been marked. @return int
[ "Marks", "all", "retrieved", "log", "entries", "as", "read", "and", "returns", "the", "number", "of", "entries", "that", "have", "been", "marked", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L413-L426
32,894
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.paginate
public function paginate($perPage = 25, $currentPage = null, array $options = []) { $currentPage = $this->getPageFromInput($currentPage, $options); $offset = ($currentPage - 1) * $perPage; $total = $this->count(); $entries = $this->get()->slice($offset, $perPage)->all(); return new LengthAwarePaginator($entries, $total, $perPage, $currentPage, $options); }
php
public function paginate($perPage = 25, $currentPage = null, array $options = []) { $currentPage = $this->getPageFromInput($currentPage, $options); $offset = ($currentPage - 1) * $perPage; $total = $this->count(); $entries = $this->get()->slice($offset, $perPage)->all(); return new LengthAwarePaginator($entries, $total, $perPage, $currentPage, $options); }
[ "public", "function", "paginate", "(", "$", "perPage", "=", "25", ",", "$", "currentPage", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "currentPage", "=", "$", "this", "->", "getPageFromInput", "(", "$", "currentPage", ",", "$", "options", ")", ";", "$", "offset", "=", "(", "$", "currentPage", "-", "1", ")", "*", "$", "perPage", ";", "$", "total", "=", "$", "this", "->", "count", "(", ")", ";", "$", "entries", "=", "$", "this", "->", "get", "(", ")", "->", "slice", "(", "$", "offset", ",", "$", "perPage", ")", "->", "all", "(", ")", ";", "return", "new", "LengthAwarePaginator", "(", "$", "entries", ",", "$", "total", ",", "$", "perPage", ",", "$", "currentPage", ",", "$", "options", ")", ";", "}" ]
Paginates the returned log entries. @param int $perPage @param int $currentPage @param array $options [path => '', query => [], fragment => '', pageName => ''] @return mixed
[ "Paginates", "the", "returned", "log", "entries", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L489-L497
32,895
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.getLogFilenameList
public function getLogFilenameList($filename = null) { $data = []; if (empty($filename)) { $filename = '*.*'; } $files = $this->getLogFileList($filename); if (is_array($files)) { foreach ($files as $file) { $basename = pathinfo($file, PATHINFO_BASENAME); $data[$basename] = $file; } } return $data; }
php
public function getLogFilenameList($filename = null) { $data = []; if (empty($filename)) { $filename = '*.*'; } $files = $this->getLogFileList($filename); if (is_array($files)) { foreach ($files as $file) { $basename = pathinfo($file, PATHINFO_BASENAME); $data[$basename] = $file; } } return $data; }
[ "public", "function", "getLogFilenameList", "(", "$", "filename", "=", "null", ")", "{", "$", "data", "=", "[", "]", ";", "if", "(", "empty", "(", "$", "filename", ")", ")", "{", "$", "filename", "=", "'*.*'", ";", "}", "$", "files", "=", "$", "this", "->", "getLogFileList", "(", "$", "filename", ")", ";", "if", "(", "is_array", "(", "$", "files", ")", ")", "{", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "basename", "=", "pathinfo", "(", "$", "file", ",", "PATHINFO_BASENAME", ")", ";", "$", "data", "[", "$", "basename", "]", "=", "$", "file", ";", "}", "}", "return", "$", "data", ";", "}" ]
Returns an array of log filenames. @param null|string $filename @return array
[ "Returns", "an", "array", "of", "log", "filenames", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L506-L524
32,896
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.setOrderByField
protected function setOrderByField($field) { $field = strtolower($field); $acceptedFields = [ 'id', 'date', 'level', 'environment', 'file_path' ]; if (in_array($field, $acceptedFields)) { $this->orderByField = $field; } }
php
protected function setOrderByField($field) { $field = strtolower($field); $acceptedFields = [ 'id', 'date', 'level', 'environment', 'file_path' ]; if (in_array($field, $acceptedFields)) { $this->orderByField = $field; } }
[ "protected", "function", "setOrderByField", "(", "$", "field", ")", "{", "$", "field", "=", "strtolower", "(", "$", "field", ")", ";", "$", "acceptedFields", "=", "[", "'id'", ",", "'date'", ",", "'level'", ",", "'environment'", ",", "'file_path'", "]", ";", "if", "(", "in_array", "(", "$", "field", ",", "$", "acceptedFields", ")", ")", "{", "$", "this", "->", "orderByField", "=", "$", "field", ";", "}", "}" ]
Sets the orderByField property to the specified field. @param string $field @return void
[ "Sets", "the", "orderByField", "property", "to", "the", "specified", "field", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L562-L577
32,897
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.setOrderByDirection
protected function setOrderByDirection($direction) { $direction = strtolower($direction); if ($direction == 'desc' || $direction == 'asc') { $this->orderByDirection = $direction; } }
php
protected function setOrderByDirection($direction) { $direction = strtolower($direction); if ($direction == 'desc' || $direction == 'asc') { $this->orderByDirection = $direction; } }
[ "protected", "function", "setOrderByDirection", "(", "$", "direction", ")", "{", "$", "direction", "=", "strtolower", "(", "$", "direction", ")", ";", "if", "(", "$", "direction", "==", "'desc'", "||", "$", "direction", "==", "'asc'", ")", "{", "$", "this", "->", "orderByDirection", "=", "$", "direction", ";", "}", "}" ]
Sets the orderByDirection property to the specified direction. @param string $direction @return void
[ "Sets", "the", "orderByDirection", "property", "to", "the", "specified", "direction", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L586-L593
32,898
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.postCollectionModifiers
protected function postCollectionModifiers(Collection $collection) { if ($this->getOrderByField() && $this->getOrderByDirection()) { $field = $this->getOrderByField(); $desc = false; if ($this->getOrderByDirection() === 'desc') { $desc = true; } $sorted = $collection->sortBy(function ($entry) use ($field) { if (property_exists($entry, $field)) { return $entry->{$field}; } }, SORT_NATURAL, $desc); return $sorted; } return $collection; }
php
protected function postCollectionModifiers(Collection $collection) { if ($this->getOrderByField() && $this->getOrderByDirection()) { $field = $this->getOrderByField(); $desc = false; if ($this->getOrderByDirection() === 'desc') { $desc = true; } $sorted = $collection->sortBy(function ($entry) use ($field) { if (property_exists($entry, $field)) { return $entry->{$field}; } }, SORT_NATURAL, $desc); return $sorted; } return $collection; }
[ "protected", "function", "postCollectionModifiers", "(", "Collection", "$", "collection", ")", "{", "if", "(", "$", "this", "->", "getOrderByField", "(", ")", "&&", "$", "this", "->", "getOrderByDirection", "(", ")", ")", "{", "$", "field", "=", "$", "this", "->", "getOrderByField", "(", ")", ";", "$", "desc", "=", "false", ";", "if", "(", "$", "this", "->", "getOrderByDirection", "(", ")", "===", "'desc'", ")", "{", "$", "desc", "=", "true", ";", "}", "$", "sorted", "=", "$", "collection", "->", "sortBy", "(", "function", "(", "$", "entry", ")", "use", "(", "$", "field", ")", "{", "if", "(", "property_exists", "(", "$", "entry", ",", "$", "field", ")", ")", "{", "return", "$", "entry", "->", "{", "$", "field", "}", ";", "}", "}", ",", "SORT_NATURAL", ",", "$", "desc", ")", ";", "return", "$", "sorted", ";", "}", "return", "$", "collection", ";", "}" ]
Modifies and returns the collection result if modifiers are set such as an orderBy. @param Collection $collection @return Collection
[ "Modifies", "and", "returns", "the", "collection", "result", "if", "modifiers", "are", "set", "such", "as", "an", "orderBy", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L641-L661
32,899
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.getPageFromInput
protected function getPageFromInput($currentPage = null, array $options = []) { if (is_numeric($currentPage)) { return intval($currentPage); } $pageName = (array_key_exists('pageName', $options)) ? $options['pageName'] : 'page'; $page = $this->request->input($pageName); if (is_numeric($page)) { return intval($page); } return 1; }
php
protected function getPageFromInput($currentPage = null, array $options = []) { if (is_numeric($currentPage)) { return intval($currentPage); } $pageName = (array_key_exists('pageName', $options)) ? $options['pageName'] : 'page'; $page = $this->request->input($pageName); if (is_numeric($page)) { return intval($page); } return 1; }
[ "protected", "function", "getPageFromInput", "(", "$", "currentPage", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "is_numeric", "(", "$", "currentPage", ")", ")", "{", "return", "intval", "(", "$", "currentPage", ")", ";", "}", "$", "pageName", "=", "(", "array_key_exists", "(", "'pageName'", ",", "$", "options", ")", ")", "?", "$", "options", "[", "'pageName'", "]", ":", "'page'", ";", "$", "page", "=", "$", "this", "->", "request", "->", "input", "(", "$", "pageName", ")", ";", "if", "(", "is_numeric", "(", "$", "page", ")", ")", "{", "return", "intval", "(", "$", "page", ")", ";", "}", "return", "1", ";", "}" ]
Returns the current page from the current input. Used for pagination. @param int $currentPage @param array $options [path => '', query => [], fragment => '', pageName => ''] @return int
[ "Returns", "the", "current", "page", "from", "the", "current", "input", ".", "Used", "for", "pagination", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L671-L686