repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
cakephp/phinx
src/Phinx/Config/Config.php
Config.recurseArrayForTokens
protected function recurseArrayForTokens($arr, $tokens) { $out = []; foreach ($arr as $name => $value) { if (is_array($value)) { $out[$name] = $this->recurseArrayForTokens($value, $tokens); continue; } if (is_string($value)) { foreach ($tokens as $token => $tval) { $value = str_replace($token, $tval, $value); } $out[$name] = $value; continue; } $out[$name] = $value; } return $out; }
php
protected function recurseArrayForTokens($arr, $tokens) { $out = []; foreach ($arr as $name => $value) { if (is_array($value)) { $out[$name] = $this->recurseArrayForTokens($value, $tokens); continue; } if (is_string($value)) { foreach ($tokens as $token => $tval) { $value = str_replace($token, $tval, $value); } $out[$name] = $value; continue; } $out[$name] = $value; } return $out; }
[ "protected", "function", "recurseArrayForTokens", "(", "$", "arr", ",", "$", "tokens", ")", "{", "$", "out", "=", "[", "]", ";", "foreach", "(", "$", "arr", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "out", "[", "$", "name", "]", "=", "$", "this", "->", "recurseArrayForTokens", "(", "$", "value", ",", "$", "tokens", ")", ";", "continue", ";", "}", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "tokens", "as", "$", "token", "=>", "$", "tval", ")", "{", "$", "value", "=", "str_replace", "(", "$", "token", ",", "$", "tval", ",", "$", "value", ")", ";", "}", "$", "out", "[", "$", "name", "]", "=", "$", "value", ";", "continue", ";", "}", "$", "out", "[", "$", "name", "]", "=", "$", "value", ";", "}", "return", "$", "out", ";", "}" ]
Recurse an array for the specified tokens and replace them. @param array $arr Array to recurse @param array $tokens Array of tokens to search for @return array
[ "Recurse", "an", "array", "for", "the", "specified", "tokens", "and", "replace", "them", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Config/Config.php#L388-L407
train
cakephp/phinx
src/Phinx/Console/Command/Migrate.php
Migrate.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->bootstrap($input, $output); $version = $input->getOption('target'); $environment = $input->getOption('environment'); $date = $input->getOption('date'); $fake = (bool)$input->getOption('fake'); if ($environment === null) { $environment = $this->getConfig()->getDefaultEnvironment(); $output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment); } else { $output->writeln('<info>using environment</info> ' . $environment); } $envOptions = $this->getConfig()->getEnvironment($environment); if (isset($envOptions['adapter'])) { $output->writeln('<info>using adapter</info> ' . $envOptions['adapter']); } if (isset($envOptions['wrapper'])) { $output->writeln('<info>using wrapper</info> ' . $envOptions['wrapper']); } if (isset($envOptions['name'])) { $output->writeln('<info>using database</info> ' . $envOptions['name']); } else { $output->writeln('<error>Could not determine database name! Please specify a database name in your config file.</error>'); return 1; } if (isset($envOptions['table_prefix'])) { $output->writeln('<info>using table prefix</info> ' . $envOptions['table_prefix']); } if (isset($envOptions['table_suffix'])) { $output->writeln('<info>using table suffix</info> ' . $envOptions['table_suffix']); } if ($fake) { $output->writeln('<comment>warning</comment> performing fake migrations'); } try { // run the migrations $start = microtime(true); if ($date !== null) { $this->getManager()->migrateToDateTime($environment, new \DateTime($date), $fake); } else { $this->getManager()->migrate($environment, $version, $fake); } $end = microtime(true); } catch (\Exception $e) { $output->writeln('<error>' . $e->__toString() . '</error>'); return 1; } catch (\Throwable $e) { $output->writeln('<error>' . $e->__toString() . '</error>'); return 1; } $output->writeln(''); $output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>'); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->bootstrap($input, $output); $version = $input->getOption('target'); $environment = $input->getOption('environment'); $date = $input->getOption('date'); $fake = (bool)$input->getOption('fake'); if ($environment === null) { $environment = $this->getConfig()->getDefaultEnvironment(); $output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment); } else { $output->writeln('<info>using environment</info> ' . $environment); } $envOptions = $this->getConfig()->getEnvironment($environment); if (isset($envOptions['adapter'])) { $output->writeln('<info>using adapter</info> ' . $envOptions['adapter']); } if (isset($envOptions['wrapper'])) { $output->writeln('<info>using wrapper</info> ' . $envOptions['wrapper']); } if (isset($envOptions['name'])) { $output->writeln('<info>using database</info> ' . $envOptions['name']); } else { $output->writeln('<error>Could not determine database name! Please specify a database name in your config file.</error>'); return 1; } if (isset($envOptions['table_prefix'])) { $output->writeln('<info>using table prefix</info> ' . $envOptions['table_prefix']); } if (isset($envOptions['table_suffix'])) { $output->writeln('<info>using table suffix</info> ' . $envOptions['table_suffix']); } if ($fake) { $output->writeln('<comment>warning</comment> performing fake migrations'); } try { // run the migrations $start = microtime(true); if ($date !== null) { $this->getManager()->migrateToDateTime($environment, new \DateTime($date), $fake); } else { $this->getManager()->migrate($environment, $version, $fake); } $end = microtime(true); } catch (\Exception $e) { $output->writeln('<error>' . $e->__toString() . '</error>'); return 1; } catch (\Throwable $e) { $output->writeln('<error>' . $e->__toString() . '</error>'); return 1; } $output->writeln(''); $output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>'); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "bootstrap", "(", "$", "input", ",", "$", "output", ")", ";", "$", "version", "=", "$", "input", "->", "getOption", "(", "'target'", ")", ";", "$", "environment", "=", "$", "input", "->", "getOption", "(", "'environment'", ")", ";", "$", "date", "=", "$", "input", "->", "getOption", "(", "'date'", ")", ";", "$", "fake", "=", "(", "bool", ")", "$", "input", "->", "getOption", "(", "'fake'", ")", ";", "if", "(", "$", "environment", "===", "null", ")", "{", "$", "environment", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getDefaultEnvironment", "(", ")", ";", "$", "output", "->", "writeln", "(", "'<comment>warning</comment> no environment specified, defaulting to: '", ".", "$", "environment", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<info>using environment</info> '", ".", "$", "environment", ")", ";", "}", "$", "envOptions", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getEnvironment", "(", "$", "environment", ")", ";", "if", "(", "isset", "(", "$", "envOptions", "[", "'adapter'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>using adapter</info> '", ".", "$", "envOptions", "[", "'adapter'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "envOptions", "[", "'wrapper'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>using wrapper</info> '", ".", "$", "envOptions", "[", "'wrapper'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "envOptions", "[", "'name'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>using database</info> '", ".", "$", "envOptions", "[", "'name'", "]", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<error>Could not determine database name! Please specify a database name in your config file.</error>'", ")", ";", "return", "1", ";", "}", "if", "(", "isset", "(", "$", "envOptions", "[", "'table_prefix'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>using table prefix</info> '", ".", "$", "envOptions", "[", "'table_prefix'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "envOptions", "[", "'table_suffix'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>using table suffix</info> '", ".", "$", "envOptions", "[", "'table_suffix'", "]", ")", ";", "}", "if", "(", "$", "fake", ")", "{", "$", "output", "->", "writeln", "(", "'<comment>warning</comment> performing fake migrations'", ")", ";", "}", "try", "{", "// run the migrations", "$", "start", "=", "microtime", "(", "true", ")", ";", "if", "(", "$", "date", "!==", "null", ")", "{", "$", "this", "->", "getManager", "(", ")", "->", "migrateToDateTime", "(", "$", "environment", ",", "new", "\\", "DateTime", "(", "$", "date", ")", ",", "$", "fake", ")", ";", "}", "else", "{", "$", "this", "->", "getManager", "(", ")", "->", "migrate", "(", "$", "environment", ",", "$", "version", ",", "$", "fake", ")", ";", "}", "$", "end", "=", "microtime", "(", "true", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "e", "->", "__toString", "(", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "e", "->", "__toString", "(", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "$", "output", "->", "writeln", "(", "''", ")", ";", "$", "output", "->", "writeln", "(", "'<comment>All Done. Took '", ".", "sprintf", "(", "'%.4fs'", ",", "$", "end", "-", "$", "start", ")", ".", "'</comment>'", ")", ";", "return", "0", ";", "}" ]
Migrate the database. @param \Symfony\Component\Console\Input\InputInterface $input @param \Symfony\Component\Console\Output\OutputInterface $output @return int integer 0 on success, or an error code.
[ "Migrate", "the", "database", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Console/Command/Migrate.php#L72-L137
train
cakephp/phinx
src/Phinx/Db/Adapter/PdoAdapter.php
PdoAdapter.verboseLog
protected function verboseLog($message) { if (!$this->isDryRunEnabled() && $this->getOutput()->getVerbosity() < OutputInterface::VERBOSITY_VERY_VERBOSE) { return; } $this->getOutput()->writeln($message); }
php
protected function verboseLog($message) { if (!$this->isDryRunEnabled() && $this->getOutput()->getVerbosity() < OutputInterface::VERBOSITY_VERY_VERBOSE) { return; } $this->getOutput()->writeln($message); }
[ "protected", "function", "verboseLog", "(", "$", "message", ")", "{", "if", "(", "!", "$", "this", "->", "isDryRunEnabled", "(", ")", "&&", "$", "this", "->", "getOutput", "(", ")", "->", "getVerbosity", "(", ")", "<", "OutputInterface", "::", "VERBOSITY_VERY_VERBOSE", ")", "{", "return", ";", "}", "$", "this", "->", "getOutput", "(", ")", "->", "writeln", "(", "$", "message", ")", ";", "}" ]
Writes a message to stdout if verbose output is on @param string $message The message to show @return void
[ "Writes", "a", "message", "to", "stdout", "if", "verbose", "output", "is", "on" ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Adapter/PdoAdapter.php#L70-L78
train
cakephp/phinx
src/Phinx/Db/Adapter/PdoAdapter.php
PdoAdapter.quoteValue
private function quoteValue($value) { if (is_numeric($value)) { return $value; } if ($value === null) { return 'null'; } return $this->getConnection()->quote($value); }
php
private function quoteValue($value) { if (is_numeric($value)) { return $value; } if ($value === null) { return 'null'; } return $this->getConnection()->quote($value); }
[ "private", "function", "quoteValue", "(", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "if", "(", "$", "value", "===", "null", ")", "{", "return", "'null'", ";", "}", "return", "$", "this", "->", "getConnection", "(", ")", "->", "quote", "(", "$", "value", ")", ";", "}" ]
Quotes a database value. @param mixed $value The value to quote @return mixed
[ "Quotes", "a", "database", "value", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Adapter/PdoAdapter.php#L255-L266
train
cakephp/phinx
src/Phinx/Db/Adapter/PdoAdapter.php
PdoAdapter.executeAlterSteps
protected function executeAlterSteps($tableName, AlterInstructions $instructions) { $alter = sprintf('ALTER TABLE %s %%s', $this->quoteTableName($tableName)); $instructions->execute($alter, [$this, 'execute']); }
php
protected function executeAlterSteps($tableName, AlterInstructions $instructions) { $alter = sprintf('ALTER TABLE %s %%s', $this->quoteTableName($tableName)); $instructions->execute($alter, [$this, 'execute']); }
[ "protected", "function", "executeAlterSteps", "(", "$", "tableName", ",", "AlterInstructions", "$", "instructions", ")", "{", "$", "alter", "=", "sprintf", "(", "'ALTER TABLE %s %%s'", ",", "$", "this", "->", "quoteTableName", "(", "$", "tableName", ")", ")", ";", "$", "instructions", "->", "execute", "(", "$", "alter", ",", "[", "$", "this", ",", "'execute'", "]", ")", ";", "}" ]
Executes all the ALTER TABLE instructions passed for the given table @param string $tableName The table name to use in the ALTER statement @param AlterInstructions $instructions The object containing the alter sequence @return void
[ "Executes", "all", "the", "ALTER", "TABLE", "instructions", "passed", "for", "the", "given", "table" ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Adapter/PdoAdapter.php#L517-L521
train
cakephp/phinx
src/Phinx/Db/Plan/Intent.php
Intent.merge
public function merge(Intent $another) { $this->actions = array_merge($this->actions, $another->getActions()); }
php
public function merge(Intent $another) { $this->actions = array_merge($this->actions, $another->getActions()); }
[ "public", "function", "merge", "(", "Intent", "$", "another", ")", "{", "$", "this", "->", "actions", "=", "array_merge", "(", "$", "this", "->", "actions", ",", "$", "another", "->", "getActions", "(", ")", ")", ";", "}" ]
Merges another Intent object with this one @param Intent $another The other intent to merge in @return void
[ "Merges", "another", "Intent", "object", "with", "this", "one" ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Plan/Intent.php#L70-L73
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.changePrimaryKey
public function changePrimaryKey($columns) { $this->actions->addAction(new ChangePrimaryKey($this->table, $columns)); return $this; }
php
public function changePrimaryKey($columns) { $this->actions->addAction(new ChangePrimaryKey($this->table, $columns)); return $this; }
[ "public", "function", "changePrimaryKey", "(", "$", "columns", ")", "{", "$", "this", "->", "actions", "->", "addAction", "(", "new", "ChangePrimaryKey", "(", "$", "this", "->", "table", ",", "$", "columns", ")", ")", ";", "return", "$", "this", ";", "}" ]
Changes the primary key of the database table. @param string|array|null $columns Column name(s) to belong to the primary key, or null to drop the key @return $this
[ "Changes", "the", "primary", "key", "of", "the", "database", "table", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L201-L206
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.changeComment
public function changeComment($comment) { $this->actions->addAction(new ChangeComment($this->table, $comment)); return $this; }
php
public function changeComment($comment) { $this->actions->addAction(new ChangeComment($this->table, $comment)); return $this; }
[ "public", "function", "changeComment", "(", "$", "comment", ")", "{", "$", "this", "->", "actions", "->", "addAction", "(", "new", "ChangeComment", "(", "$", "this", "->", "table", ",", "$", "comment", ")", ")", ";", "return", "$", "this", ";", "}" ]
Changes the comment of the database table. @param string|null $comment New comment string, or null to drop the comment @return $this
[ "Changes", "the", "comment", "of", "the", "database", "table", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L214-L219
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.getColumn
public function getColumn($name) { $columns = array_filter( $this->getColumns(), function ($column) use ($name) { return $column->getName() === $name; } ); return array_pop($columns); }
php
public function getColumn($name) { $columns = array_filter( $this->getColumns(), function ($column) use ($name) { return $column->getName() === $name; } ); return array_pop($columns); }
[ "public", "function", "getColumn", "(", "$", "name", ")", "{", "$", "columns", "=", "array_filter", "(", "$", "this", "->", "getColumns", "(", ")", ",", "function", "(", "$", "column", ")", "use", "(", "$", "name", ")", "{", "return", "$", "column", "->", "getName", "(", ")", "===", "$", "name", ";", "}", ")", ";", "return", "array_pop", "(", "$", "columns", ")", ";", "}" ]
Gets a table column if it exists. @param string $name Column name @return \Phinx\Db\Table\Column|null
[ "Gets", "a", "table", "column", "if", "it", "exists", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L237-L247
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.removeColumn
public function removeColumn($columnName) { $action = RemoveColumn::build($this->table, $columnName); $this->actions->addAction($action); return $this; }
php
public function removeColumn($columnName) { $action = RemoveColumn::build($this->table, $columnName); $this->actions->addAction($action); return $this; }
[ "public", "function", "removeColumn", "(", "$", "columnName", ")", "{", "$", "action", "=", "RemoveColumn", "::", "build", "(", "$", "this", "->", "table", ",", "$", "columnName", ")", ";", "$", "this", "->", "actions", "->", "addAction", "(", "$", "action", ")", ";", "return", "$", "this", ";", "}" ]
Remove a table column. @param string $columnName Column Name @return \Phinx\Db\Table
[ "Remove", "a", "table", "column", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L336-L342
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.removeIndex
public function removeIndex($columns) { $action = DropIndex::build($this->table, is_string($columns) ? [$columns] : $columns); $this->actions->addAction($action); return $this; }
php
public function removeIndex($columns) { $action = DropIndex::build($this->table, is_string($columns) ? [$columns] : $columns); $this->actions->addAction($action); return $this; }
[ "public", "function", "removeIndex", "(", "$", "columns", ")", "{", "$", "action", "=", "DropIndex", "::", "build", "(", "$", "this", "->", "table", ",", "is_string", "(", "$", "columns", ")", "?", "[", "$", "columns", "]", ":", "$", "columns", ")", ";", "$", "this", "->", "actions", "->", "addAction", "(", "$", "action", ")", ";", "return", "$", "this", ";", "}" ]
Removes the given index from a table. @param string|array $columns Columns @return \Phinx\Db\Table
[ "Removes", "the", "given", "index", "from", "a", "table", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L413-L419
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.removeIndexByName
public function removeIndexByName($name) { $action = DropIndex::buildFromName($this->table, $name); $this->actions->addAction($action); return $this; }
php
public function removeIndexByName($name) { $action = DropIndex::buildFromName($this->table, $name); $this->actions->addAction($action); return $this; }
[ "public", "function", "removeIndexByName", "(", "$", "name", ")", "{", "$", "action", "=", "DropIndex", "::", "buildFromName", "(", "$", "this", "->", "table", ",", "$", "name", ")", ";", "$", "this", "->", "actions", "->", "addAction", "(", "$", "action", ")", ";", "return", "$", "this", ";", "}" ]
Removes the given index identified by its name from a table. @param string $name Index name @return \Phinx\Db\Table
[ "Removes", "the", "given", "index", "identified", "by", "its", "name", "from", "a", "table", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L427-L433
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.addForeignKeyWithName
public function addForeignKeyWithName($name, $columns, $referencedTable, $referencedColumns = ['id'], $options = []) { $action = AddForeignKey::build( $this->table, $columns, $referencedTable, $referencedColumns, $options, $name ); $this->actions->addAction($action); return $this; }
php
public function addForeignKeyWithName($name, $columns, $referencedTable, $referencedColumns = ['id'], $options = []) { $action = AddForeignKey::build( $this->table, $columns, $referencedTable, $referencedColumns, $options, $name ); $this->actions->addAction($action); return $this; }
[ "public", "function", "addForeignKeyWithName", "(", "$", "name", ",", "$", "columns", ",", "$", "referencedTable", ",", "$", "referencedColumns", "=", "[", "'id'", "]", ",", "$", "options", "=", "[", "]", ")", "{", "$", "action", "=", "AddForeignKey", "::", "build", "(", "$", "this", "->", "table", ",", "$", "columns", ",", "$", "referencedTable", ",", "$", "referencedColumns", ",", "$", "options", ",", "$", "name", ")", ";", "$", "this", "->", "actions", "->", "addAction", "(", "$", "action", ")", ";", "return", "$", "this", ";", "}" ]
Add a foreign key to a database table with a given name. In $options you can specify on_delete|on_delete = cascade|no_action .., on_update, constraint = constraint name. @param string $name The constraint name @param string|array $columns Columns @param string|\Phinx\Db\Table $referencedTable Referenced Table @param string|array $referencedColumns Referenced Columns @param array $options Options @return \Phinx\Db\Table
[ "Add", "a", "foreign", "key", "to", "a", "database", "table", "with", "a", "given", "name", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L490-L503
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.hasForeignKey
public function hasForeignKey($columns, $constraint = null) { return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint); }
php
public function hasForeignKey($columns, $constraint = null) { return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint); }
[ "public", "function", "hasForeignKey", "(", "$", "columns", ",", "$", "constraint", "=", "null", ")", "{", "return", "$", "this", "->", "getAdapter", "(", ")", "->", "hasForeignKey", "(", "$", "this", "->", "getName", "(", ")", ",", "$", "columns", ",", "$", "constraint", ")", ";", "}" ]
Checks to see if a foreign key exists. @param string|array $columns Column(s) @param null|string $constraint Constraint names @return bool
[ "Checks", "to", "see", "if", "a", "foreign", "key", "exists", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L527-L530
train
cakephp/phinx
src/Phinx/Db/Table.php
Table.executeActions
protected function executeActions($exists) { // Renaming a table is tricky, specially when running a reversible migration // down. We will just assume the table already exists if the user commands a // table rename. $renamed = collection($this->actions->getActions()) ->filter(function ($action) { return $action instanceof RenameTable; }) ->first(); if ($renamed) { $exists = true; } // If the table does not exist, the last command in the chain needs to be // a CreateTable action. if (!$exists) { $this->actions->addAction(new CreateTable($this->table)); } $plan = new Plan($this->actions); $plan->execute($this->getAdapter()); }
php
protected function executeActions($exists) { // Renaming a table is tricky, specially when running a reversible migration // down. We will just assume the table already exists if the user commands a // table rename. $renamed = collection($this->actions->getActions()) ->filter(function ($action) { return $action instanceof RenameTable; }) ->first(); if ($renamed) { $exists = true; } // If the table does not exist, the last command in the chain needs to be // a CreateTable action. if (!$exists) { $this->actions->addAction(new CreateTable($this->table)); } $plan = new Plan($this->actions); $plan->execute($this->getAdapter()); }
[ "protected", "function", "executeActions", "(", "$", "exists", ")", "{", "// Renaming a table is tricky, specially when running a reversible migration", "// down. We will just assume the table already exists if the user commands a", "// table rename.", "$", "renamed", "=", "collection", "(", "$", "this", "->", "actions", "->", "getActions", "(", ")", ")", "->", "filter", "(", "function", "(", "$", "action", ")", "{", "return", "$", "action", "instanceof", "RenameTable", ";", "}", ")", "->", "first", "(", ")", ";", "if", "(", "$", "renamed", ")", "{", "$", "exists", "=", "true", ";", "}", "// If the table does not exist, the last command in the chain needs to be", "// a CreateTable action.", "if", "(", "!", "$", "exists", ")", "{", "$", "this", "->", "actions", "->", "addAction", "(", "new", "CreateTable", "(", "$", "this", "->", "table", ")", ")", ";", "}", "$", "plan", "=", "new", "Plan", "(", "$", "this", "->", "actions", ")", ";", "$", "plan", "->", "execute", "(", "$", "this", "->", "getAdapter", "(", ")", ")", ";", "}" ]
Executes all the pending actions for this table @param bool $exists Whether or not the table existed prior to executing this method @return void
[ "Executes", "all", "the", "pending", "actions", "for", "this", "table" ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Table.php#L697-L720
train
cakephp/phinx
src/Phinx/Db/Action/DropForeignKey.php
DropForeignKey.build
public static function build(Table $table, $columns, $constraint = null) { if (is_string($columns)) { $columns = [$columns]; } $foreignKey = new ForeignKey(); $foreignKey->setColumns($columns); if ($constraint) { $foreignKey->setConstraint($constraint); } return new static($table, $foreignKey); }
php
public static function build(Table $table, $columns, $constraint = null) { if (is_string($columns)) { $columns = [$columns]; } $foreignKey = new ForeignKey(); $foreignKey->setColumns($columns); if ($constraint) { $foreignKey->setConstraint($constraint); } return new static($table, $foreignKey); }
[ "public", "static", "function", "build", "(", "Table", "$", "table", ",", "$", "columns", ",", "$", "constraint", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "columns", ")", ")", "{", "$", "columns", "=", "[", "$", "columns", "]", ";", "}", "$", "foreignKey", "=", "new", "ForeignKey", "(", ")", ";", "$", "foreignKey", "->", "setColumns", "(", "$", "columns", ")", ";", "if", "(", "$", "constraint", ")", "{", "$", "foreignKey", "->", "setConstraint", "(", "$", "constraint", ")", ";", "}", "return", "new", "static", "(", "$", "table", ",", "$", "foreignKey", ")", ";", "}" ]
Creates a new DropForeignKey object after building the ForeignKey definition out of the passed arguments. @param Table $table The table to delete the foreign key from @param string|string[] $columns The columns participating in the foreign key @param string|null $constraint The constraint name @return DropForeignKey
[ "Creates", "a", "new", "DropForeignKey", "object", "after", "building", "the", "ForeignKey", "definition", "out", "of", "the", "passed", "arguments", "." ]
229d02f174a904d9ee2a49e95dfb434e73e53e04
https://github.com/cakephp/phinx/blob/229d02f174a904d9ee2a49e95dfb434e73e53e04/src/Phinx/Db/Action/DropForeignKey.php#L61-L75
train
lorisleiva/laravel-deployer
src/LaravelDeployer/ConfigFileBuilder.php
ConfigFileBuilder.add
public function add($key, $value) { $array = array_get($this->configs, $key); if (is_array($array)) { $array[] = $value; array_set($this->configs, $key, $array); } return $this; }
php
public function add($key, $value) { $array = array_get($this->configs, $key); if (is_array($array)) { $array[] = $value; array_set($this->configs, $key, $array); } return $this; }
[ "public", "function", "add", "(", "$", "key", ",", "$", "value", ")", "{", "$", "array", "=", "array_get", "(", "$", "this", "->", "configs", ",", "$", "key", ")", ";", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "$", "array", "[", "]", "=", "$", "value", ";", "array_set", "(", "$", "this", "->", "configs", ",", "$", "key", ",", "$", "array", ")", ";", "}", "return", "$", "this", ";", "}" ]
Append the given value to the configuration array at the given key. @return ConfigFileGenerator
[ "Append", "the", "given", "value", "to", "the", "configuration", "array", "at", "the", "given", "key", "." ]
8d014534ea9b9b639fde34e21e8cc86c0b76c34e
https://github.com/lorisleiva/laravel-deployer/blob/8d014534ea9b9b639fde34e21e8cc86c0b76c34e/src/LaravelDeployer/ConfigFileBuilder.php#L84-L95
train
lorisleiva/laravel-deployer
src/LaravelDeployer/ConfigFileBuilder.php
ConfigFileBuilder.useForge
public function useForge($phpVersion = self::DEFAULT_PHP_VERSION) { $this->reloadFpm($phpVersion); $this->setHost('deploy_path', '/home/forge/' . $this->getHostname()); $this->setHost('user', 'forge'); return $this; }
php
public function useForge($phpVersion = self::DEFAULT_PHP_VERSION) { $this->reloadFpm($phpVersion); $this->setHost('deploy_path', '/home/forge/' . $this->getHostname()); $this->setHost('user', 'forge'); return $this; }
[ "public", "function", "useForge", "(", "$", "phpVersion", "=", "self", "::", "DEFAULT_PHP_VERSION", ")", "{", "$", "this", "->", "reloadFpm", "(", "$", "phpVersion", ")", ";", "$", "this", "->", "setHost", "(", "'deploy_path'", ",", "'/home/forge/'", ".", "$", "this", "->", "getHostname", "(", ")", ")", ";", "$", "this", "->", "setHost", "(", "'user'", ",", "'forge'", ")", ";", "return", "$", "this", ";", "}" ]
Set up defaults values more suitable for forge servers. @return ConfigFileGenerator
[ "Set", "up", "defaults", "values", "more", "suitable", "for", "forge", "servers", "." ]
8d014534ea9b9b639fde34e21e8cc86c0b76c34e
https://github.com/lorisleiva/laravel-deployer/blob/8d014534ea9b9b639fde34e21e8cc86c0b76c34e/src/LaravelDeployer/ConfigFileBuilder.php#L147-L154
train
lorisleiva/laravel-deployer
src/LaravelDeployer/ConfigFile.php
ConfigFile.store
public function store($path = 'config' . DIRECTORY_SEPARATOR . 'deploy.php') { $path = base_path($path); if (! is_dir(dirname($path))) { mkdir(dirname($path), 0777, true); } $this->filesystem->put($path, (string) $this); return $path; }
php
public function store($path = 'config' . DIRECTORY_SEPARATOR . 'deploy.php') { $path = base_path($path); if (! is_dir(dirname($path))) { mkdir(dirname($path), 0777, true); } $this->filesystem->put($path, (string) $this); return $path; }
[ "public", "function", "store", "(", "$", "path", "=", "'config'", ".", "DIRECTORY_SEPARATOR", ".", "'deploy.php'", ")", "{", "$", "path", "=", "base_path", "(", "$", "path", ")", ";", "if", "(", "!", "is_dir", "(", "dirname", "(", "$", "path", ")", ")", ")", "{", "mkdir", "(", "dirname", "(", "$", "path", ")", ",", "0777", ",", "true", ")", ";", "}", "$", "this", "->", "filesystem", "->", "put", "(", "$", "path", ",", "(", "string", ")", "$", "this", ")", ";", "return", "$", "path", ";", "}" ]
Parse the `config.stub` file and copy its content onto a new `deploy.php` file in the config folder of the Laravel project. @return string
[ "Parse", "the", "config", ".", "stub", "file", "and", "copy", "its", "content", "onto", "a", "new", "deploy", ".", "php", "file", "in", "the", "config", "folder", "of", "the", "Laravel", "project", "." ]
8d014534ea9b9b639fde34e21e8cc86c0b76c34e
https://github.com/lorisleiva/laravel-deployer/blob/8d014534ea9b9b639fde34e21e8cc86c0b76c34e/src/LaravelDeployer/ConfigFile.php#L59-L70
train
PHPGangsta/GoogleAuthenticator
PHPGangsta/GoogleAuthenticator.php
PHPGangsta_GoogleAuthenticator._base32Decode
protected function _base32Decode($secret) { if (empty($secret)) { return ''; } $base32chars = $this->_getBase32LookupTable(); $base32charsFlipped = array_flip($base32chars); $paddingCharCount = substr_count($secret, $base32chars[32]); $allowedValues = array(6, 4, 3, 1, 0); if (!in_array($paddingCharCount, $allowedValues)) { return false; } for ($i = 0; $i < 4; ++$i) { if ($paddingCharCount == $allowedValues[$i] && substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) { return false; } } $secret = str_replace('=', '', $secret); $secret = str_split($secret); $binaryString = ''; for ($i = 0; $i < count($secret); $i = $i + 8) { $x = ''; if (!in_array($secret[$i], $base32chars)) { return false; } for ($j = 0; $j < 8; ++$j) { $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT); } $eightBits = str_split($x, 8); for ($z = 0; $z < count($eightBits); ++$z) { $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : ''; } } return $binaryString; }
php
protected function _base32Decode($secret) { if (empty($secret)) { return ''; } $base32chars = $this->_getBase32LookupTable(); $base32charsFlipped = array_flip($base32chars); $paddingCharCount = substr_count($secret, $base32chars[32]); $allowedValues = array(6, 4, 3, 1, 0); if (!in_array($paddingCharCount, $allowedValues)) { return false; } for ($i = 0; $i < 4; ++$i) { if ($paddingCharCount == $allowedValues[$i] && substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) { return false; } } $secret = str_replace('=', '', $secret); $secret = str_split($secret); $binaryString = ''; for ($i = 0; $i < count($secret); $i = $i + 8) { $x = ''; if (!in_array($secret[$i], $base32chars)) { return false; } for ($j = 0; $j < 8; ++$j) { $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT); } $eightBits = str_split($x, 8); for ($z = 0; $z < count($eightBits); ++$z) { $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : ''; } } return $binaryString; }
[ "protected", "function", "_base32Decode", "(", "$", "secret", ")", "{", "if", "(", "empty", "(", "$", "secret", ")", ")", "{", "return", "''", ";", "}", "$", "base32chars", "=", "$", "this", "->", "_getBase32LookupTable", "(", ")", ";", "$", "base32charsFlipped", "=", "array_flip", "(", "$", "base32chars", ")", ";", "$", "paddingCharCount", "=", "substr_count", "(", "$", "secret", ",", "$", "base32chars", "[", "32", "]", ")", ";", "$", "allowedValues", "=", "array", "(", "6", ",", "4", ",", "3", ",", "1", ",", "0", ")", ";", "if", "(", "!", "in_array", "(", "$", "paddingCharCount", ",", "$", "allowedValues", ")", ")", "{", "return", "false", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "4", ";", "++", "$", "i", ")", "{", "if", "(", "$", "paddingCharCount", "==", "$", "allowedValues", "[", "$", "i", "]", "&&", "substr", "(", "$", "secret", ",", "-", "(", "$", "allowedValues", "[", "$", "i", "]", ")", ")", "!=", "str_repeat", "(", "$", "base32chars", "[", "32", "]", ",", "$", "allowedValues", "[", "$", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "$", "secret", "=", "str_replace", "(", "'='", ",", "''", ",", "$", "secret", ")", ";", "$", "secret", "=", "str_split", "(", "$", "secret", ")", ";", "$", "binaryString", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "secret", ")", ";", "$", "i", "=", "$", "i", "+", "8", ")", "{", "$", "x", "=", "''", ";", "if", "(", "!", "in_array", "(", "$", "secret", "[", "$", "i", "]", ",", "$", "base32chars", ")", ")", "{", "return", "false", ";", "}", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "8", ";", "++", "$", "j", ")", "{", "$", "x", ".=", "str_pad", "(", "base_convert", "(", "@", "$", "base32charsFlipped", "[", "@", "$", "secret", "[", "$", "i", "+", "$", "j", "]", "]", ",", "10", ",", "2", ")", ",", "5", ",", "'0'", ",", "STR_PAD_LEFT", ")", ";", "}", "$", "eightBits", "=", "str_split", "(", "$", "x", ",", "8", ")", ";", "for", "(", "$", "z", "=", "0", ";", "$", "z", "<", "count", "(", "$", "eightBits", ")", ";", "++", "$", "z", ")", "{", "$", "binaryString", ".=", "(", "(", "$", "y", "=", "chr", "(", "base_convert", "(", "$", "eightBits", "[", "$", "z", "]", ",", "2", ",", "10", ")", ")", ")", "||", "ord", "(", "$", "y", ")", "==", "48", ")", "?", "$", "y", ":", "''", ";", "}", "}", "return", "$", "binaryString", ";", "}" ]
Helper class to decode base32. @param $secret @return bool|string
[ "Helper", "class", "to", "decode", "base32", "." ]
505c2af8337b559b33557f37cda38e5f843f3768
https://github.com/PHPGangsta/GoogleAuthenticator/blob/505c2af8337b559b33557f37cda38e5f843f3768/PHPGangsta/GoogleAuthenticator.php#L166-L204
train
illuminate/database
Schema/PostgresBuilder.php
PostgresBuilder.getAllTables
public function getAllTables() { return $this->connection->select( $this->grammar->compileGetAllTables($this->connection->getConfig('schema')) ); }
php
public function getAllTables() { return $this->connection->select( $this->grammar->compileGetAllTables($this->connection->getConfig('schema')) ); }
[ "public", "function", "getAllTables", "(", ")", "{", "return", "$", "this", "->", "connection", "->", "select", "(", "$", "this", "->", "grammar", "->", "compileGetAllTables", "(", "$", "this", "->", "connection", "->", "getConfig", "(", "'schema'", ")", ")", ")", ";", "}" ]
Get all of the table names for the database. @return array
[ "Get", "all", "of", "the", "table", "names", "for", "the", "database", "." ]
149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439
https://github.com/illuminate/database/blob/149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439/Schema/PostgresBuilder.php#L83-L88
train
illuminate/database
Concerns/BuildsQueries.php
BuildsQueries.eachById
public function eachById(callable $callback, $count = 1000, $column = null, $alias = null) { return $this->chunkById($count, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($value, $key) === false) { return false; } } }, $column, $alias); }
php
public function eachById(callable $callback, $count = 1000, $column = null, $alias = null) { return $this->chunkById($count, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($value, $key) === false) { return false; } } }, $column, $alias); }
[ "public", "function", "eachById", "(", "callable", "$", "callback", ",", "$", "count", "=", "1000", ",", "$", "column", "=", "null", ",", "$", "alias", "=", "null", ")", "{", "return", "$", "this", "->", "chunkById", "(", "$", "count", ",", "function", "(", "$", "results", ")", "use", "(", "$", "callback", ")", "{", "foreach", "(", "$", "results", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "callback", "(", "$", "value", ",", "$", "key", ")", "===", "false", ")", "{", "return", "false", ";", "}", "}", "}", ",", "$", "column", ",", "$", "alias", ")", ";", "}" ]
Execute a callback over each item while chunking by id. @param callable $callback @param int $count @param string $column @param string $alias @return bool
[ "Execute", "a", "callback", "over", "each", "item", "while", "chunking", "by", "id", "." ]
149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439
https://github.com/illuminate/database/blob/149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439/Concerns/BuildsQueries.php#L124-L133
train
illuminate/database
Eloquent/Relations/HasOneOrMany.php
HasOneOrMany.createMany
public function createMany(iterable $records) { $instances = $this->related->newCollection(); foreach ($records as $record) { $instances->push($this->create($record)); } return $instances; }
php
public function createMany(iterable $records) { $instances = $this->related->newCollection(); foreach ($records as $record) { $instances->push($this->create($record)); } return $instances; }
[ "public", "function", "createMany", "(", "iterable", "$", "records", ")", "{", "$", "instances", "=", "$", "this", "->", "related", "->", "newCollection", "(", ")", ";", "foreach", "(", "$", "records", "as", "$", "record", ")", "{", "$", "instances", "->", "push", "(", "$", "this", "->", "create", "(", "$", "record", ")", ")", ";", "}", "return", "$", "instances", ";", "}" ]
Create a Collection of new instances of the related model. @param iterable $records @return \Illuminate\Database\Eloquent\Collection
[ "Create", "a", "Collection", "of", "new", "instances", "of", "the", "related", "model", "." ]
149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439
https://github.com/illuminate/database/blob/149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439/Eloquent/Relations/HasOneOrMany.php#L291-L300
train
illuminate/database
Query/Builder.php
Builder.fromSub
public function fromSub($query, $as) { [$query, $bindings] = $this->createSub($query); return $this->fromRaw('('.$query.') as '.$this->grammar->wrap($as), $bindings); }
php
public function fromSub($query, $as) { [$query, $bindings] = $this->createSub($query); return $this->fromRaw('('.$query.') as '.$this->grammar->wrap($as), $bindings); }
[ "public", "function", "fromSub", "(", "$", "query", ",", "$", "as", ")", "{", "[", "$", "query", ",", "$", "bindings", "]", "=", "$", "this", "->", "createSub", "(", "$", "query", ")", ";", "return", "$", "this", "->", "fromRaw", "(", "'('", ".", "$", "query", ".", "') as '", ".", "$", "this", "->", "grammar", "->", "wrap", "(", "$", "as", ")", ",", "$", "bindings", ")", ";", "}" ]
Makes "from" fetch from a subquery. @param \Closure|\Illuminate\Database\Query\Builder|string $query @param string $as @return \Illuminate\Database\Query\Builder|static @throws \InvalidArgumentException
[ "Makes", "from", "fetch", "from", "a", "subquery", "." ]
149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439
https://github.com/illuminate/database/blob/149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439/Query/Builder.php#L272-L277
train
illuminate/database
Query/Builder.php
Builder.joinSub
public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false) { [$query, $bindings] = $this->createSub($query); $expression = '('.$query.') as '.$this->grammar->wrap($as); $this->addBinding($bindings, 'join'); return $this->join(new Expression($expression), $first, $operator, $second, $type, $where); }
php
public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false) { [$query, $bindings] = $this->createSub($query); $expression = '('.$query.') as '.$this->grammar->wrap($as); $this->addBinding($bindings, 'join'); return $this->join(new Expression($expression), $first, $operator, $second, $type, $where); }
[ "public", "function", "joinSub", "(", "$", "query", ",", "$", "as", ",", "$", "first", ",", "$", "operator", "=", "null", ",", "$", "second", "=", "null", ",", "$", "type", "=", "'inner'", ",", "$", "where", "=", "false", ")", "{", "[", "$", "query", ",", "$", "bindings", "]", "=", "$", "this", "->", "createSub", "(", "$", "query", ")", ";", "$", "expression", "=", "'('", ".", "$", "query", ".", "') as '", ".", "$", "this", "->", "grammar", "->", "wrap", "(", "$", "as", ")", ";", "$", "this", "->", "addBinding", "(", "$", "bindings", ",", "'join'", ")", ";", "return", "$", "this", "->", "join", "(", "new", "Expression", "(", "$", "expression", ")", ",", "$", "first", ",", "$", "operator", ",", "$", "second", ",", "$", "type", ",", "$", "where", ")", ";", "}" ]
Add a subquery join clause to the query. @param \Closure|\Illuminate\Database\Query\Builder|string $query @param string $as @param \Closure|string $first @param string|null $operator @param string|null $second @param string $type @param bool $where @return \Illuminate\Database\Query\Builder|static @throws \InvalidArgumentException
[ "Add", "a", "subquery", "join", "clause", "to", "the", "query", "." ]
149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439
https://github.com/illuminate/database/blob/149db0a3c17a12e7160e4bf53ae1fdf5c6e6f439/Query/Builder.php#L441-L450
train
KnpLabs/snappy
src/Knp/Snappy/AbstractGenerator.php
AbstractGenerator.setOptions
public function setOptions(array $options) { foreach ($options as $name => $value) { $this->setOption($name, $value); } }
php
public function setOptions(array $options) { foreach ($options as $name => $value) { $this->setOption($name, $value); } }
[ "public", "function", "setOptions", "(", "array", "$", "options", ")", "{", "foreach", "(", "$", "options", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "this", "->", "setOption", "(", "$", "name", ",", "$", "value", ")", ";", "}", "}" ]
Sets an array of options. @param array $options An associative array of options as name/value
[ "Sets", "an", "array", "of", "options", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/AbstractGenerator.php#L135-L140
train
KnpLabs/snappy
src/Knp/Snappy/AbstractGenerator.php
AbstractGenerator.getCommand
public function getCommand($input, $output, array $options = []) { $options = $this->mergeOptions($options); return $this->buildCommand($this->binary, $input, $output, $options); }
php
public function getCommand($input, $output, array $options = []) { $options = $this->mergeOptions($options); return $this->buildCommand($this->binary, $input, $output, $options); }
[ "public", "function", "getCommand", "(", "$", "input", ",", "$", "output", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "$", "this", "->", "mergeOptions", "(", "$", "options", ")", ";", "return", "$", "this", "->", "buildCommand", "(", "$", "this", "->", "binary", ",", "$", "input", ",", "$", "output", ",", "$", "options", ")", ";", "}" ]
Returns the command for the given input and output files. @param array|string $input The input file @param string $output The ouput file @param array $options An optional array of options that will be used only for this command @return string
[ "Returns", "the", "command", "for", "the", "given", "input", "and", "output", "files", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/AbstractGenerator.php#L277-L282
train
KnpLabs/snappy
src/Knp/Snappy/AbstractGenerator.php
AbstractGenerator.mergeOptions
protected function mergeOptions(array $options) { $mergedOptions = $this->options; foreach ($options as $name => $value) { if (!array_key_exists($name, $mergedOptions)) { throw new \InvalidArgumentException(sprintf('The option \'%s\' does not exist.', $name)); } $mergedOptions[$name] = $value; } return $mergedOptions; }
php
protected function mergeOptions(array $options) { $mergedOptions = $this->options; foreach ($options as $name => $value) { if (!array_key_exists($name, $mergedOptions)) { throw new \InvalidArgumentException(sprintf('The option \'%s\' does not exist.', $name)); } $mergedOptions[$name] = $value; } return $mergedOptions; }
[ "protected", "function", "mergeOptions", "(", "array", "$", "options", ")", "{", "$", "mergedOptions", "=", "$", "this", "->", "options", ";", "foreach", "(", "$", "options", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "mergedOptions", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The option \\'%s\\' does not exist.'", ",", "$", "name", ")", ")", ";", "}", "$", "mergedOptions", "[", "$", "name", "]", "=", "$", "value", ";", "}", "return", "$", "mergedOptions", ";", "}" ]
Merges the given array of options to the instance options and returns the result options array. It does NOT change the instance options. @param array $options @throws \InvalidArgumentException @return array
[ "Merges", "the", "given", "array", "of", "options", "to", "the", "instance", "options", "and", "returns", "the", "result", "options", "array", ".", "It", "does", "NOT", "change", "the", "instance", "options", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/AbstractGenerator.php#L323-L336
train
KnpLabs/snappy
src/Knp/Snappy/AbstractGenerator.php
AbstractGenerator.checkOutput
protected function checkOutput($output, $command) { // the output file must exist if (!$this->fileExists($output)) { throw new \RuntimeException(sprintf( 'The file \'%s\' was not created (command: %s).', $output, $command )); } // the output file must not be empty if (0 === $this->filesize($output)) { throw new \RuntimeException(sprintf( 'The file \'%s\' was created but is empty (command: %s).', $output, $command )); } }
php
protected function checkOutput($output, $command) { // the output file must exist if (!$this->fileExists($output)) { throw new \RuntimeException(sprintf( 'The file \'%s\' was not created (command: %s).', $output, $command )); } // the output file must not be empty if (0 === $this->filesize($output)) { throw new \RuntimeException(sprintf( 'The file \'%s\' was created but is empty (command: %s).', $output, $command )); } }
[ "protected", "function", "checkOutput", "(", "$", "output", ",", "$", "command", ")", "{", "// the output file must exist", "if", "(", "!", "$", "this", "->", "fileExists", "(", "$", "output", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'The file \\'%s\\' was not created (command: %s).'", ",", "$", "output", ",", "$", "command", ")", ")", ";", "}", "// the output file must not be empty", "if", "(", "0", "===", "$", "this", "->", "filesize", "(", "$", "output", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'The file \\'%s\\' was created but is empty (command: %s).'", ",", "$", "output", ",", "$", "command", ")", ")", ";", "}", "}" ]
Checks the specified output. @param string $output The output filename @param string $command The generation command @throws \RuntimeException if the output file generation failed
[ "Checks", "the", "specified", "output", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/AbstractGenerator.php#L346-L363
train
KnpLabs/snappy
src/Knp/Snappy/AbstractGenerator.php
AbstractGenerator.buildCommand
protected function buildCommand($binary, $input, $output, array $options = []) { $command = $binary; $escapedBinary = escapeshellarg($binary); if (is_executable($escapedBinary)) { $command = $escapedBinary; } foreach ($options as $key => $option) { if (null !== $option && false !== $option) { if (true === $option) { // Dont't put '--' if option is 'toc'. if ($key == 'toc') { $command .= ' ' . $key; } else { $command .= ' --' . $key; } } elseif (is_array($option)) { if ($this->isAssociativeArray($option)) { foreach ($option as $k => $v) { $command .= ' --' . $key . ' ' . escapeshellarg($k) . ' ' . escapeshellarg($v); } } else { foreach ($option as $v) { $command .= ' --' . $key . ' ' . escapeshellarg($v); } } } else { // Dont't add '--' if option is "cover" or "toc". if (in_array($key, ['toc', 'cover'])) { $command .= ' ' . $key . ' ' . escapeshellarg($option); } elseif (in_array($key, ['image-dpi', 'image-quality'])) { $command .= ' --' . $key . ' ' . (int) $option; } else { $command .= ' --' . $key . ' ' . escapeshellarg($option); } } } } if (is_array($input)) { foreach ($input as $i) { $command .= ' ' . escapeshellarg($i) . ' '; } $command .= escapeshellarg($output); } else { $command .= ' ' . escapeshellarg($input) . ' ' . escapeshellarg($output); } return $command; }
php
protected function buildCommand($binary, $input, $output, array $options = []) { $command = $binary; $escapedBinary = escapeshellarg($binary); if (is_executable($escapedBinary)) { $command = $escapedBinary; } foreach ($options as $key => $option) { if (null !== $option && false !== $option) { if (true === $option) { // Dont't put '--' if option is 'toc'. if ($key == 'toc') { $command .= ' ' . $key; } else { $command .= ' --' . $key; } } elseif (is_array($option)) { if ($this->isAssociativeArray($option)) { foreach ($option as $k => $v) { $command .= ' --' . $key . ' ' . escapeshellarg($k) . ' ' . escapeshellarg($v); } } else { foreach ($option as $v) { $command .= ' --' . $key . ' ' . escapeshellarg($v); } } } else { // Dont't add '--' if option is "cover" or "toc". if (in_array($key, ['toc', 'cover'])) { $command .= ' ' . $key . ' ' . escapeshellarg($option); } elseif (in_array($key, ['image-dpi', 'image-quality'])) { $command .= ' --' . $key . ' ' . (int) $option; } else { $command .= ' --' . $key . ' ' . escapeshellarg($option); } } } } if (is_array($input)) { foreach ($input as $i) { $command .= ' ' . escapeshellarg($i) . ' '; } $command .= escapeshellarg($output); } else { $command .= ' ' . escapeshellarg($input) . ' ' . escapeshellarg($output); } return $command; }
[ "protected", "function", "buildCommand", "(", "$", "binary", ",", "$", "input", ",", "$", "output", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "command", "=", "$", "binary", ";", "$", "escapedBinary", "=", "escapeshellarg", "(", "$", "binary", ")", ";", "if", "(", "is_executable", "(", "$", "escapedBinary", ")", ")", "{", "$", "command", "=", "$", "escapedBinary", ";", "}", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "option", ")", "{", "if", "(", "null", "!==", "$", "option", "&&", "false", "!==", "$", "option", ")", "{", "if", "(", "true", "===", "$", "option", ")", "{", "// Dont't put '--' if option is 'toc'.", "if", "(", "$", "key", "==", "'toc'", ")", "{", "$", "command", ".=", "' '", ".", "$", "key", ";", "}", "else", "{", "$", "command", ".=", "' --'", ".", "$", "key", ";", "}", "}", "elseif", "(", "is_array", "(", "$", "option", ")", ")", "{", "if", "(", "$", "this", "->", "isAssociativeArray", "(", "$", "option", ")", ")", "{", "foreach", "(", "$", "option", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "command", ".=", "' --'", ".", "$", "key", ".", "' '", ".", "escapeshellarg", "(", "$", "k", ")", ".", "' '", ".", "escapeshellarg", "(", "$", "v", ")", ";", "}", "}", "else", "{", "foreach", "(", "$", "option", "as", "$", "v", ")", "{", "$", "command", ".=", "' --'", ".", "$", "key", ".", "' '", ".", "escapeshellarg", "(", "$", "v", ")", ";", "}", "}", "}", "else", "{", "// Dont't add '--' if option is \"cover\" or \"toc\".", "if", "(", "in_array", "(", "$", "key", ",", "[", "'toc'", ",", "'cover'", "]", ")", ")", "{", "$", "command", ".=", "' '", ".", "$", "key", ".", "' '", ".", "escapeshellarg", "(", "$", "option", ")", ";", "}", "elseif", "(", "in_array", "(", "$", "key", ",", "[", "'image-dpi'", ",", "'image-quality'", "]", ")", ")", "{", "$", "command", ".=", "' --'", ".", "$", "key", ".", "' '", ".", "(", "int", ")", "$", "option", ";", "}", "else", "{", "$", "command", ".=", "' --'", ".", "$", "key", ".", "' '", ".", "escapeshellarg", "(", "$", "option", ")", ";", "}", "}", "}", "}", "if", "(", "is_array", "(", "$", "input", ")", ")", "{", "foreach", "(", "$", "input", "as", "$", "i", ")", "{", "$", "command", ".=", "' '", ".", "escapeshellarg", "(", "$", "i", ")", ".", "' '", ";", "}", "$", "command", ".=", "escapeshellarg", "(", "$", "output", ")", ";", "}", "else", "{", "$", "command", ".=", "' '", ".", "escapeshellarg", "(", "$", "input", ")", ".", "' '", ".", "escapeshellarg", "(", "$", "output", ")", ";", "}", "return", "$", "command", ";", "}" ]
Builds the command string. @param string $binary The binary path/name @param string/array $input Url(s) or file location(s) of the page(s) to process @param string $output File location to the image-to-be @param array $options An array of options @return string
[ "Builds", "the", "command", "string", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/AbstractGenerator.php#L444-L494
train
KnpLabs/snappy
src/Knp/Snappy/AbstractGenerator.php
AbstractGenerator.executeCommand
protected function executeCommand($command) { if (method_exists(Process::class, 'fromShellCommandline')) { $process = Process::fromShellCommandline($command, null, $this->env); } else { $process = new Process($command, null, $this->env); } if (false !== $this->timeout) { $process->setTimeout($this->timeout); } $process->run(); return [ $process->getExitCode(), $process->getOutput(), $process->getErrorOutput(), ]; }
php
protected function executeCommand($command) { if (method_exists(Process::class, 'fromShellCommandline')) { $process = Process::fromShellCommandline($command, null, $this->env); } else { $process = new Process($command, null, $this->env); } if (false !== $this->timeout) { $process->setTimeout($this->timeout); } $process->run(); return [ $process->getExitCode(), $process->getOutput(), $process->getErrorOutput(), ]; }
[ "protected", "function", "executeCommand", "(", "$", "command", ")", "{", "if", "(", "method_exists", "(", "Process", "::", "class", ",", "'fromShellCommandline'", ")", ")", "{", "$", "process", "=", "Process", "::", "fromShellCommandline", "(", "$", "command", ",", "null", ",", "$", "this", "->", "env", ")", ";", "}", "else", "{", "$", "process", "=", "new", "Process", "(", "$", "command", ",", "null", ",", "$", "this", "->", "env", ")", ";", "}", "if", "(", "false", "!==", "$", "this", "->", "timeout", ")", "{", "$", "process", "->", "setTimeout", "(", "$", "this", "->", "timeout", ")", ";", "}", "$", "process", "->", "run", "(", ")", ";", "return", "[", "$", "process", "->", "getExitCode", "(", ")", ",", "$", "process", "->", "getOutput", "(", ")", ",", "$", "process", "->", "getErrorOutput", "(", ")", ",", "]", ";", "}" ]
Executes the given command via shell and returns the complete output as a string. @param string $command @return array(status, stdout, stderr)
[ "Executes", "the", "given", "command", "via", "shell", "and", "returns", "the", "complete", "output", "as", "a", "string", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/AbstractGenerator.php#L517-L536
train
KnpLabs/snappy
src/Knp/Snappy/AbstractGenerator.php
AbstractGenerator.prepareOutput
protected function prepareOutput($filename, $overwrite) { $directory = dirname($filename); if ($this->fileExists($filename)) { if (!$this->isFile($filename)) { throw new \InvalidArgumentException(sprintf( 'The output file \'%s\' already exists and it is a %s.', $filename, $this->isDir($filename) ? 'directory' : 'link' )); } elseif (false === $overwrite) { throw new Exceptions\FileAlreadyExistsException(sprintf( 'The output file \'%s\' already exists.', $filename )); } elseif (!$this->unlink($filename)) { throw new \RuntimeException(sprintf( 'Could not delete already existing output file \'%s\'.', $filename )); } } elseif (!$this->isDir($directory) && !$this->mkdir($directory)) { throw new \RuntimeException(sprintf( 'The output file\'s directory \'%s\' could not be created.', $directory )); } }
php
protected function prepareOutput($filename, $overwrite) { $directory = dirname($filename); if ($this->fileExists($filename)) { if (!$this->isFile($filename)) { throw new \InvalidArgumentException(sprintf( 'The output file \'%s\' already exists and it is a %s.', $filename, $this->isDir($filename) ? 'directory' : 'link' )); } elseif (false === $overwrite) { throw new Exceptions\FileAlreadyExistsException(sprintf( 'The output file \'%s\' already exists.', $filename )); } elseif (!$this->unlink($filename)) { throw new \RuntimeException(sprintf( 'Could not delete already existing output file \'%s\'.', $filename )); } } elseif (!$this->isDir($directory) && !$this->mkdir($directory)) { throw new \RuntimeException(sprintf( 'The output file\'s directory \'%s\' could not be created.', $directory )); } }
[ "protected", "function", "prepareOutput", "(", "$", "filename", ",", "$", "overwrite", ")", "{", "$", "directory", "=", "dirname", "(", "$", "filename", ")", ";", "if", "(", "$", "this", "->", "fileExists", "(", "$", "filename", ")", ")", "{", "if", "(", "!", "$", "this", "->", "isFile", "(", "$", "filename", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The output file \\'%s\\' already exists and it is a %s.'", ",", "$", "filename", ",", "$", "this", "->", "isDir", "(", "$", "filename", ")", "?", "'directory'", ":", "'link'", ")", ")", ";", "}", "elseif", "(", "false", "===", "$", "overwrite", ")", "{", "throw", "new", "Exceptions", "\\", "FileAlreadyExistsException", "(", "sprintf", "(", "'The output file \\'%s\\' already exists.'", ",", "$", "filename", ")", ")", ";", "}", "elseif", "(", "!", "$", "this", "->", "unlink", "(", "$", "filename", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Could not delete already existing output file \\'%s\\'.'", ",", "$", "filename", ")", ")", ";", "}", "}", "elseif", "(", "!", "$", "this", "->", "isDir", "(", "$", "directory", ")", "&&", "!", "$", "this", "->", "mkdir", "(", "$", "directory", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'The output file\\'s directory \\'%s\\' could not be created.'", ",", "$", "directory", ")", ")", ";", "}", "}" ]
Prepares the specified output. @param string $filename The output filename @param bool $overwrite Whether to overwrite the file if it already exist @throws Exception\FileAlreadyExistsException @throws \RuntimeException @throws \InvalidArgumentException
[ "Prepares", "the", "specified", "output", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/AbstractGenerator.php#L549-L576
train
KnpLabs/snappy
src/Knp/Snappy/Pdf.php
Pdf.handleOptions
protected function handleOptions(array $options = []) { foreach ($options as $option => $value) { if (null === $value) { unset($options[$option]); continue; } if (!empty($value) && array_key_exists($option, $this->optionsWithContentCheck)) { $saveToTempFile = !$this->isFile($value) && !$this->isOptionUrl($value); $fetchUrlContent = $option === 'xsl-style-sheet' && $this->isOptionUrl($value); if ($saveToTempFile || $fetchUrlContent) { $fileContent = $fetchUrlContent ? file_get_contents($value) : $value; $options[$option] = $this->createTemporaryFile($fileContent, $this->optionsWithContentCheck[$option]); } } } return $options; }
php
protected function handleOptions(array $options = []) { foreach ($options as $option => $value) { if (null === $value) { unset($options[$option]); continue; } if (!empty($value) && array_key_exists($option, $this->optionsWithContentCheck)) { $saveToTempFile = !$this->isFile($value) && !$this->isOptionUrl($value); $fetchUrlContent = $option === 'xsl-style-sheet' && $this->isOptionUrl($value); if ($saveToTempFile || $fetchUrlContent) { $fileContent = $fetchUrlContent ? file_get_contents($value) : $value; $options[$option] = $this->createTemporaryFile($fileContent, $this->optionsWithContentCheck[$option]); } } } return $options; }
[ "protected", "function", "handleOptions", "(", "array", "$", "options", "=", "[", "]", ")", "{", "foreach", "(", "$", "options", "as", "$", "option", "=>", "$", "value", ")", "{", "if", "(", "null", "===", "$", "value", ")", "{", "unset", "(", "$", "options", "[", "$", "option", "]", ")", ";", "continue", ";", "}", "if", "(", "!", "empty", "(", "$", "value", ")", "&&", "array_key_exists", "(", "$", "option", ",", "$", "this", "->", "optionsWithContentCheck", ")", ")", "{", "$", "saveToTempFile", "=", "!", "$", "this", "->", "isFile", "(", "$", "value", ")", "&&", "!", "$", "this", "->", "isOptionUrl", "(", "$", "value", ")", ";", "$", "fetchUrlContent", "=", "$", "option", "===", "'xsl-style-sheet'", "&&", "$", "this", "->", "isOptionUrl", "(", "$", "value", ")", ";", "if", "(", "$", "saveToTempFile", "||", "$", "fetchUrlContent", ")", "{", "$", "fileContent", "=", "$", "fetchUrlContent", "?", "file_get_contents", "(", "$", "value", ")", ":", "$", "value", ";", "$", "options", "[", "$", "option", "]", "=", "$", "this", "->", "createTemporaryFile", "(", "$", "fileContent", ",", "$", "this", "->", "optionsWithContentCheck", "[", "$", "option", "]", ")", ";", "}", "}", "}", "return", "$", "options", ";", "}" ]
Handle options to transform HTML strings into temporary files containing HTML. @param array $options @return array $options Transformed options
[ "Handle", "options", "to", "transform", "HTML", "strings", "into", "temporary", "files", "containing", "HTML", "." ]
ea037298d3c613454da77ecb9588cf0397d695e1
https://github.com/KnpLabs/snappy/blob/ea037298d3c613454da77ecb9588cf0397d695e1/src/Knp/Snappy/Pdf.php#L34-L54
train
thephpleague/flysystem
src/MountManager.php
MountManager.listWith
public function listWith(array $keys = [], $directory = '', $recursive = false) { list($prefix, $directory) = $this->getPrefixAndPath($directory); $arguments = [$keys, $directory, $recursive]; return $this->invokePluginOnFilesystem('listWith', $arguments, $prefix); }
php
public function listWith(array $keys = [], $directory = '', $recursive = false) { list($prefix, $directory) = $this->getPrefixAndPath($directory); $arguments = [$keys, $directory, $recursive]; return $this->invokePluginOnFilesystem('listWith', $arguments, $prefix); }
[ "public", "function", "listWith", "(", "array", "$", "keys", "=", "[", "]", ",", "$", "directory", "=", "''", ",", "$", "recursive", "=", "false", ")", "{", "list", "(", "$", "prefix", ",", "$", "directory", ")", "=", "$", "this", "->", "getPrefixAndPath", "(", "$", "directory", ")", ";", "$", "arguments", "=", "[", "$", "keys", ",", "$", "directory", ",", "$", "recursive", "]", ";", "return", "$", "this", "->", "invokePluginOnFilesystem", "(", "'listWith'", ",", "$", "arguments", ",", "$", "prefix", ")", ";", "}" ]
List with plugin adapter. @param array $keys @param string $directory @param bool $recursive @throws InvalidArgumentException @throws FilesystemNotFoundException @return array
[ "List", "with", "plugin", "adapter", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/MountManager.php#L213-L219
train
thephpleague/flysystem
src/MountManager.php
MountManager.invokePluginOnFilesystem
public function invokePluginOnFilesystem($method, $arguments, $prefix) { $filesystem = $this->getFilesystem($prefix); try { return $this->invokePlugin($method, $arguments, $filesystem); } catch (PluginNotFoundException $e) { // Let it pass, it's ok, don't panic. } $callback = [$filesystem, $method]; return call_user_func_array($callback, $arguments); }
php
public function invokePluginOnFilesystem($method, $arguments, $prefix) { $filesystem = $this->getFilesystem($prefix); try { return $this->invokePlugin($method, $arguments, $filesystem); } catch (PluginNotFoundException $e) { // Let it pass, it's ok, don't panic. } $callback = [$filesystem, $method]; return call_user_func_array($callback, $arguments); }
[ "public", "function", "invokePluginOnFilesystem", "(", "$", "method", ",", "$", "arguments", ",", "$", "prefix", ")", "{", "$", "filesystem", "=", "$", "this", "->", "getFilesystem", "(", "$", "prefix", ")", ";", "try", "{", "return", "$", "this", "->", "invokePlugin", "(", "$", "method", ",", "$", "arguments", ",", "$", "filesystem", ")", ";", "}", "catch", "(", "PluginNotFoundException", "$", "e", ")", "{", "// Let it pass, it's ok, don't panic.", "}", "$", "callback", "=", "[", "$", "filesystem", ",", "$", "method", "]", ";", "return", "call_user_func_array", "(", "$", "callback", ",", "$", "arguments", ")", ";", "}" ]
Invoke a plugin on a filesystem mounted on a given prefix. @param string $method @param array $arguments @param string $prefix @throws FilesystemNotFoundException @return mixed
[ "Invoke", "a", "plugin", "on", "a", "filesystem", "mounted", "on", "a", "given", "prefix", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/MountManager.php#L269-L282
train
thephpleague/flysystem
src/Config.php
Config.get
public function get($key, $default = null) { if ( ! array_key_exists($key, $this->settings)) { return $this->getDefault($key, $default); } return $this->settings[$key]; }
php
public function get($key, $default = null) { if ( ! array_key_exists($key, $this->settings)) { return $this->getDefault($key, $default); } return $this->settings[$key]; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "settings", ")", ")", "{", "return", "$", "this", "->", "getDefault", "(", "$", "key", ",", "$", "default", ")", ";", "}", "return", "$", "this", "->", "settings", "[", "$", "key", "]", ";", "}" ]
Get a setting. @param string $key @param mixed $default @return mixed config setting or default when not found
[ "Get", "a", "setting", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Config.php#L35-L42
train
thephpleague/flysystem
src/Config.php
Config.has
public function has($key) { if (array_key_exists($key, $this->settings)) { return true; } return $this->fallback instanceof Config ? $this->fallback->has($key) : false; }
php
public function has($key) { if (array_key_exists($key, $this->settings)) { return true; } return $this->fallback instanceof Config ? $this->fallback->has($key) : false; }
[ "public", "function", "has", "(", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "settings", ")", ")", "{", "return", "true", ";", "}", "return", "$", "this", "->", "fallback", "instanceof", "Config", "?", "$", "this", "->", "fallback", "->", "has", "(", "$", "key", ")", ":", "false", ";", "}" ]
Check if an item exists by key. @param string $key @return bool
[ "Check", "if", "an", "item", "exists", "by", "key", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Config.php#L51-L60
train
thephpleague/flysystem
src/Util/ContentListingFormatter.php
ContentListingFormatter.residesInDirectory
private function residesInDirectory(array $entry) { if ($this->directory === '') { return true; } return $this->caseSensitive ? strpos($entry['path'], $this->directory . '/') === 0 : stripos($entry['path'], $this->directory . '/') === 0; }
php
private function residesInDirectory(array $entry) { if ($this->directory === '') { return true; } return $this->caseSensitive ? strpos($entry['path'], $this->directory . '/') === 0 : stripos($entry['path'], $this->directory . '/') === 0; }
[ "private", "function", "residesInDirectory", "(", "array", "$", "entry", ")", "{", "if", "(", "$", "this", "->", "directory", "===", "''", ")", "{", "return", "true", ";", "}", "return", "$", "this", "->", "caseSensitive", "?", "strpos", "(", "$", "entry", "[", "'path'", "]", ",", "$", "this", "->", "directory", ".", "'/'", ")", "===", "0", ":", "stripos", "(", "$", "entry", "[", "'path'", "]", ",", "$", "this", "->", "directory", ".", "'/'", ")", "===", "0", ";", "}" ]
Check if the entry resides within the parent directory. @param array $entry @return bool
[ "Check", "if", "the", "entry", "resides", "within", "the", "parent", "directory", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Util/ContentListingFormatter.php#L84-L93
train
thephpleague/flysystem
src/Util/ContentListingFormatter.php
ContentListingFormatter.isDirectChild
private function isDirectChild(array $entry) { return $this->caseSensitive ? $entry['dirname'] === $this->directory : strcasecmp($this->directory, $entry['dirname']) === 0; }
php
private function isDirectChild(array $entry) { return $this->caseSensitive ? $entry['dirname'] === $this->directory : strcasecmp($this->directory, $entry['dirname']) === 0; }
[ "private", "function", "isDirectChild", "(", "array", "$", "entry", ")", "{", "return", "$", "this", "->", "caseSensitive", "?", "$", "entry", "[", "'dirname'", "]", "===", "$", "this", "->", "directory", ":", "strcasecmp", "(", "$", "this", "->", "directory", ",", "$", "entry", "[", "'dirname'", "]", ")", "===", "0", ";", "}" ]
Check if the entry is a direct child of the directory. @param array $entry @return bool
[ "Check", "if", "the", "entry", "is", "a", "direct", "child", "of", "the", "directory", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Util/ContentListingFormatter.php#L102-L107
train
thephpleague/flysystem
src/Util.php
Util.pathinfo
public static function pathinfo($path) { $pathinfo = compact('path'); if ('' !== $dirname = dirname($path)) { $pathinfo['dirname'] = static::normalizeDirname($dirname); } $pathinfo['basename'] = static::basename($path); $pathinfo += pathinfo($pathinfo['basename']); return $pathinfo + ['dirname' => '']; }
php
public static function pathinfo($path) { $pathinfo = compact('path'); if ('' !== $dirname = dirname($path)) { $pathinfo['dirname'] = static::normalizeDirname($dirname); } $pathinfo['basename'] = static::basename($path); $pathinfo += pathinfo($pathinfo['basename']); return $pathinfo + ['dirname' => '']; }
[ "public", "static", "function", "pathinfo", "(", "$", "path", ")", "{", "$", "pathinfo", "=", "compact", "(", "'path'", ")", ";", "if", "(", "''", "!==", "$", "dirname", "=", "dirname", "(", "$", "path", ")", ")", "{", "$", "pathinfo", "[", "'dirname'", "]", "=", "static", "::", "normalizeDirname", "(", "$", "dirname", ")", ";", "}", "$", "pathinfo", "[", "'basename'", "]", "=", "static", "::", "basename", "(", "$", "path", ")", ";", "$", "pathinfo", "+=", "pathinfo", "(", "$", "pathinfo", "[", "'basename'", "]", ")", ";", "return", "$", "pathinfo", "+", "[", "'dirname'", "=>", "''", "]", ";", "}" ]
Get normalized pathinfo. @param string $path @return array pathinfo
[ "Get", "normalized", "pathinfo", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Util.php#L17-L30
train
thephpleague/flysystem
src/Util.php
Util.map
public static function map(array $object, array $map) { $result = []; foreach ($map as $from => $to) { if ( ! isset($object[$from])) { continue; } $result[$to] = $object[$from]; } return $result; }
php
public static function map(array $object, array $map) { $result = []; foreach ($map as $from => $to) { if ( ! isset($object[$from])) { continue; } $result[$to] = $object[$from]; } return $result; }
[ "public", "static", "function", "map", "(", "array", "$", "object", ",", "array", "$", "map", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "map", "as", "$", "from", "=>", "$", "to", ")", "{", "if", "(", "!", "isset", "(", "$", "object", "[", "$", "from", "]", ")", ")", "{", "continue", ";", "}", "$", "result", "[", "$", "to", "]", "=", "$", "object", "[", "$", "from", "]", ";", "}", "return", "$", "result", ";", "}" ]
Map result arrays. @param array $object @param array $map @return array mapped result
[ "Map", "result", "arrays", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Util.php#L64-L77
train
thephpleague/flysystem
src/Util.php
Util.ensureConfig
public static function ensureConfig($config) { if ($config === null) { return new Config(); } if ($config instanceof Config) { return $config; } if (is_array($config)) { return new Config($config); } throw new LogicException('A config should either be an array or a Flysystem\Config object.'); }
php
public static function ensureConfig($config) { if ($config === null) { return new Config(); } if ($config instanceof Config) { return $config; } if (is_array($config)) { return new Config($config); } throw new LogicException('A config should either be an array or a Flysystem\Config object.'); }
[ "public", "static", "function", "ensureConfig", "(", "$", "config", ")", "{", "if", "(", "$", "config", "===", "null", ")", "{", "return", "new", "Config", "(", ")", ";", "}", "if", "(", "$", "config", "instanceof", "Config", ")", "{", "return", "$", "config", ";", "}", "if", "(", "is_array", "(", "$", "config", ")", ")", "{", "return", "new", "Config", "(", "$", "config", ")", ";", "}", "throw", "new", "LogicException", "(", "'A config should either be an array or a Flysystem\\Config object.'", ")", ";", "}" ]
Ensure a Config instance. @param null|array|Config $config @return Config config instance @throw LogicException
[ "Ensure", "a", "Config", "instance", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Util.php#L228-L243
train
thephpleague/flysystem
src/Util.php
Util.basename
private static function basename($path) { $separators = DIRECTORY_SEPARATOR === '/' ? '/' : '\/'; $path = rtrim($path, $separators); $basename = preg_replace('#.*?([^' . preg_quote($separators, '#') . ']+$)#', '$1', $path); if (DIRECTORY_SEPARATOR === '/') { return $basename; } // @codeCoverageIgnoreStart // Extra Windows path munging. This is tested via AppVeyor, but code // coverage is not reported. // Handle relative paths with drive letters. c:file.txt. while (preg_match('#^[a-zA-Z]{1}:[^\\\/]#', $basename)) { $basename = substr($basename, 2); } // Remove colon for standalone drive letter names. if (preg_match('#^[a-zA-Z]{1}:$#', $basename)) { $basename = rtrim($basename, ':'); } return $basename; // @codeCoverageIgnoreEnd }
php
private static function basename($path) { $separators = DIRECTORY_SEPARATOR === '/' ? '/' : '\/'; $path = rtrim($path, $separators); $basename = preg_replace('#.*?([^' . preg_quote($separators, '#') . ']+$)#', '$1', $path); if (DIRECTORY_SEPARATOR === '/') { return $basename; } // @codeCoverageIgnoreStart // Extra Windows path munging. This is tested via AppVeyor, but code // coverage is not reported. // Handle relative paths with drive letters. c:file.txt. while (preg_match('#^[a-zA-Z]{1}:[^\\\/]#', $basename)) { $basename = substr($basename, 2); } // Remove colon for standalone drive letter names. if (preg_match('#^[a-zA-Z]{1}:$#', $basename)) { $basename = rtrim($basename, ':'); } return $basename; // @codeCoverageIgnoreEnd }
[ "private", "static", "function", "basename", "(", "$", "path", ")", "{", "$", "separators", "=", "DIRECTORY_SEPARATOR", "===", "'/'", "?", "'/'", ":", "'\\/'", ";", "$", "path", "=", "rtrim", "(", "$", "path", ",", "$", "separators", ")", ";", "$", "basename", "=", "preg_replace", "(", "'#.*?([^'", ".", "preg_quote", "(", "$", "separators", ",", "'#'", ")", ".", "']+$)#'", ",", "'$1'", ",", "$", "path", ")", ";", "if", "(", "DIRECTORY_SEPARATOR", "===", "'/'", ")", "{", "return", "$", "basename", ";", "}", "// @codeCoverageIgnoreStart", "// Extra Windows path munging. This is tested via AppVeyor, but code", "// coverage is not reported.", "// Handle relative paths with drive letters. c:file.txt.", "while", "(", "preg_match", "(", "'#^[a-zA-Z]{1}:[^\\\\\\/]#'", ",", "$", "basename", ")", ")", "{", "$", "basename", "=", "substr", "(", "$", "basename", ",", "2", ")", ";", "}", "// Remove colon for standalone drive letter names.", "if", "(", "preg_match", "(", "'#^[a-zA-Z]{1}:$#'", ",", "$", "basename", ")", ")", "{", "$", "basename", "=", "rtrim", "(", "$", "basename", ",", "':'", ")", ";", "}", "return", "$", "basename", ";", "// @codeCoverageIgnoreEnd", "}" ]
Returns the trailing name component of the path. @param string $path @return string
[ "Returns", "the", "trailing", "name", "component", "of", "the", "path", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Util.php#L320-L347
train
thephpleague/flysystem
src/Adapter/Ftp.php
Ftp.setUtf8Mode
protected function setUtf8Mode() { if ($this->utf8) { $response = ftp_raw($this->connection, "OPTS UTF8 ON"); if (substr($response[0], 0, 3) !== '200') { throw new RuntimeException( 'Could not set UTF-8 mode for connection: ' . $this->getHost() . '::' . $this->getPort() ); } } }
php
protected function setUtf8Mode() { if ($this->utf8) { $response = ftp_raw($this->connection, "OPTS UTF8 ON"); if (substr($response[0], 0, 3) !== '200') { throw new RuntimeException( 'Could not set UTF-8 mode for connection: ' . $this->getHost() . '::' . $this->getPort() ); } } }
[ "protected", "function", "setUtf8Mode", "(", ")", "{", "if", "(", "$", "this", "->", "utf8", ")", "{", "$", "response", "=", "ftp_raw", "(", "$", "this", "->", "connection", ",", "\"OPTS UTF8 ON\"", ")", ";", "if", "(", "substr", "(", "$", "response", "[", "0", "]", ",", "0", ",", "3", ")", "!==", "'200'", ")", "{", "throw", "new", "RuntimeException", "(", "'Could not set UTF-8 mode for connection: '", ".", "$", "this", "->", "getHost", "(", ")", ".", "'::'", ".", "$", "this", "->", "getPort", "(", ")", ")", ";", "}", "}", "}" ]
Set the connection to UTF-8 mode.
[ "Set", "the", "connection", "to", "UTF", "-", "8", "mode", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Adapter/Ftp.php#L151-L161
train
thephpleague/flysystem
src/Adapter/Ftp.php
Ftp.ftpRawlist
protected function ftpRawlist($options, $path) { $connection = $this->getConnection(); if ($this->isPureFtpd) { $path = str_replace(' ', '\ ', $path); } return ftp_rawlist($connection, $options . ' ' . $path); }
php
protected function ftpRawlist($options, $path) { $connection = $this->getConnection(); if ($this->isPureFtpd) { $path = str_replace(' ', '\ ', $path); } return ftp_rawlist($connection, $options . ' ' . $path); }
[ "protected", "function", "ftpRawlist", "(", "$", "options", ",", "$", "path", ")", "{", "$", "connection", "=", "$", "this", "->", "getConnection", "(", ")", ";", "if", "(", "$", "this", "->", "isPureFtpd", ")", "{", "$", "path", "=", "str_replace", "(", "' '", ",", "'\\ '", ",", "$", "path", ")", ";", "}", "return", "ftp_rawlist", "(", "$", "connection", ",", "$", "options", ".", "' '", ".", "$", "path", ")", ";", "}" ]
The ftp_rawlist function with optional escaping. @param string $options @param string $path @return array
[ "The", "ftp_rawlist", "function", "with", "optional", "escaping", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Adapter/Ftp.php#L558-L566
train
thephpleague/flysystem
src/ConfigAwareTrait.php
ConfigAwareTrait.prepareConfig
protected function prepareConfig(array $config) { $config = new Config($config); $config->setFallback($this->getConfig()); return $config; }
php
protected function prepareConfig(array $config) { $config = new Config($config); $config->setFallback($this->getConfig()); return $config; }
[ "protected", "function", "prepareConfig", "(", "array", "$", "config", ")", "{", "$", "config", "=", "new", "Config", "(", "$", "config", ")", ";", "$", "config", "->", "setFallback", "(", "$", "this", "->", "getConfig", "(", ")", ")", ";", "return", "$", "config", ";", "}" ]
Convert a config array to a Config object with the correct fallback. @param array $config @return Config
[ "Convert", "a", "config", "array", "to", "a", "Config", "object", "with", "the", "correct", "fallback", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/ConfigAwareTrait.php#L42-L48
train
thephpleague/flysystem
src/Plugin/PluggableTrait.php
PluggableTrait.findPlugin
protected function findPlugin($method) { if ( ! isset($this->plugins[$method])) { throw new PluginNotFoundException('Plugin not found for method: ' . $method); } return $this->plugins[$method]; }
php
protected function findPlugin($method) { if ( ! isset($this->plugins[$method])) { throw new PluginNotFoundException('Plugin not found for method: ' . $method); } return $this->plugins[$method]; }
[ "protected", "function", "findPlugin", "(", "$", "method", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "plugins", "[", "$", "method", "]", ")", ")", "{", "throw", "new", "PluginNotFoundException", "(", "'Plugin not found for method: '", ".", "$", "method", ")", ";", "}", "return", "$", "this", "->", "plugins", "[", "$", "method", "]", ";", "}" ]
Find a specific plugin. @param string $method @throws PluginNotFoundException @return PluginInterface
[ "Find", "a", "specific", "plugin", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Plugin/PluggableTrait.php#L46-L53
train
thephpleague/flysystem
src/Plugin/PluggableTrait.php
PluggableTrait.invokePlugin
protected function invokePlugin($method, array $arguments, FilesystemInterface $filesystem) { $plugin = $this->findPlugin($method); $plugin->setFilesystem($filesystem); $callback = [$plugin, 'handle']; return call_user_func_array($callback, $arguments); }
php
protected function invokePlugin($method, array $arguments, FilesystemInterface $filesystem) { $plugin = $this->findPlugin($method); $plugin->setFilesystem($filesystem); $callback = [$plugin, 'handle']; return call_user_func_array($callback, $arguments); }
[ "protected", "function", "invokePlugin", "(", "$", "method", ",", "array", "$", "arguments", ",", "FilesystemInterface", "$", "filesystem", ")", "{", "$", "plugin", "=", "$", "this", "->", "findPlugin", "(", "$", "method", ")", ";", "$", "plugin", "->", "setFilesystem", "(", "$", "filesystem", ")", ";", "$", "callback", "=", "[", "$", "plugin", ",", "'handle'", "]", ";", "return", "call_user_func_array", "(", "$", "callback", ",", "$", "arguments", ")", ";", "}" ]
Invoke a plugin by method name. @param string $method @param array $arguments @param FilesystemInterface $filesystem @throws PluginNotFoundException @return mixed
[ "Invoke", "a", "plugin", "by", "method", "name", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Plugin/PluggableTrait.php#L66-L73
train
thephpleague/flysystem
src/Adapter/Polyfill/StreamedWritingTrait.php
StreamedWritingTrait.writeStream
public function writeStream($path, $resource, Config $config) { return $this->stream($path, $resource, $config, 'write'); }
php
public function writeStream($path, $resource, Config $config) { return $this->stream($path, $resource, $config, 'write'); }
[ "public", "function", "writeStream", "(", "$", "path", ",", "$", "resource", ",", "Config", "$", "config", ")", "{", "return", "$", "this", "->", "stream", "(", "$", "path", ",", "$", "resource", ",", "$", "config", ",", "'write'", ")", ";", "}" ]
Write using a stream. @param string $path @param resource $resource @param Config $config @return mixed false or file metadata
[ "Write", "using", "a", "stream", "." ]
23f2326367dd04f1d2adbb2f0ecdd1f90d847c74
https://github.com/thephpleague/flysystem/blob/23f2326367dd04f1d2adbb2f0ecdd1f90d847c74/src/Adapter/Polyfill/StreamedWritingTrait.php#L38-L41
train
lexik/LexikJWTAuthenticationBundle
Services/JWTManager.php
JWTManager.addUserIdentityToPayload
protected function addUserIdentityToPayload(UserInterface $user, array &$payload) { $accessor = PropertyAccess::createPropertyAccessor(); $payload[$this->userIdClaim ?: $this->userIdentityField] = $accessor->getValue($user, $this->userIdentityField); }
php
protected function addUserIdentityToPayload(UserInterface $user, array &$payload) { $accessor = PropertyAccess::createPropertyAccessor(); $payload[$this->userIdClaim ?: $this->userIdentityField] = $accessor->getValue($user, $this->userIdentityField); }
[ "protected", "function", "addUserIdentityToPayload", "(", "UserInterface", "$", "user", ",", "array", "&", "$", "payload", ")", "{", "$", "accessor", "=", "PropertyAccess", "::", "createPropertyAccessor", "(", ")", ";", "$", "payload", "[", "$", "this", "->", "userIdClaim", "?", ":", "$", "this", "->", "userIdentityField", "]", "=", "$", "accessor", "->", "getValue", "(", "$", "user", ",", "$", "this", "->", "userIdentityField", ")", ";", "}" ]
Add user identity to payload, username by default. Override this if you need to identify it by another property. @param UserInterface $user @param array &$payload
[ "Add", "user", "identity", "to", "payload", "username", "by", "default", ".", "Override", "this", "if", "you", "need", "to", "identify", "it", "by", "another", "property", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/Services/JWTManager.php#L121-L125
train
lexik/LexikJWTAuthenticationBundle
Signature/LoadedJWS.php
LoadedJWS.checkExpiration
private function checkExpiration() { if (!$this->hasLifetime) { return; } if (!isset($this->payload['exp']) || !is_numeric($this->payload['exp'])) { return $this->state = self::INVALID; } if ($this->clockSkew <= (new \DateTime())->format('U') - $this->payload['exp']) { $this->state = self::EXPIRED; } }
php
private function checkExpiration() { if (!$this->hasLifetime) { return; } if (!isset($this->payload['exp']) || !is_numeric($this->payload['exp'])) { return $this->state = self::INVALID; } if ($this->clockSkew <= (new \DateTime())->format('U') - $this->payload['exp']) { $this->state = self::EXPIRED; } }
[ "private", "function", "checkExpiration", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasLifetime", ")", "{", "return", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "payload", "[", "'exp'", "]", ")", "||", "!", "is_numeric", "(", "$", "this", "->", "payload", "[", "'exp'", "]", ")", ")", "{", "return", "$", "this", "->", "state", "=", "self", "::", "INVALID", ";", "}", "if", "(", "$", "this", "->", "clockSkew", "<=", "(", "new", "\\", "DateTime", "(", ")", ")", "->", "format", "(", "'U'", ")", "-", "$", "this", "->", "payload", "[", "'exp'", "]", ")", "{", "$", "this", "->", "state", "=", "self", "::", "EXPIRED", ";", "}", "}" ]
Ensures that the signature is not expired.
[ "Ensures", "that", "the", "signature", "is", "not", "expired", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/Signature/LoadedJWS.php#L111-L124
train
lexik/LexikJWTAuthenticationBundle
Signature/LoadedJWS.php
LoadedJWS.checkIssuedAt
private function checkIssuedAt() { if (isset($this->payload['iat']) && (int) $this->payload['iat'] - $this->clockSkew > time()) { return $this->state = self::INVALID; } }
php
private function checkIssuedAt() { if (isset($this->payload['iat']) && (int) $this->payload['iat'] - $this->clockSkew > time()) { return $this->state = self::INVALID; } }
[ "private", "function", "checkIssuedAt", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "payload", "[", "'iat'", "]", ")", "&&", "(", "int", ")", "$", "this", "->", "payload", "[", "'iat'", "]", "-", "$", "this", "->", "clockSkew", ">", "time", "(", ")", ")", "{", "return", "$", "this", "->", "state", "=", "self", "::", "INVALID", ";", "}", "}" ]
Ensures that the iat claim is not in the future.
[ "Ensures", "that", "the", "iat", "claim", "is", "not", "in", "the", "future", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/Signature/LoadedJWS.php#L129-L134
train
lexik/LexikJWTAuthenticationBundle
DependencyInjection/Security/Factory/JWTFactory.php
JWTFactory.createEntryPoint
protected function createEntryPoint(ContainerBuilder $container, $id, $defaultEntryPoint) { $entryPointId = 'lexik_jwt_authentication.security.authentication.entry_point.'.$id; $container->setDefinition($entryPointId, $this->createChildDefinition('lexik_jwt_authentication.security.authentication.entry_point')); return $entryPointId; }
php
protected function createEntryPoint(ContainerBuilder $container, $id, $defaultEntryPoint) { $entryPointId = 'lexik_jwt_authentication.security.authentication.entry_point.'.$id; $container->setDefinition($entryPointId, $this->createChildDefinition('lexik_jwt_authentication.security.authentication.entry_point')); return $entryPointId; }
[ "protected", "function", "createEntryPoint", "(", "ContainerBuilder", "$", "container", ",", "$", "id", ",", "$", "defaultEntryPoint", ")", "{", "$", "entryPointId", "=", "'lexik_jwt_authentication.security.authentication.entry_point.'", ".", "$", "id", ";", "$", "container", "->", "setDefinition", "(", "$", "entryPointId", ",", "$", "this", "->", "createChildDefinition", "(", "'lexik_jwt_authentication.security.authentication.entry_point'", ")", ")", ";", "return", "$", "entryPointId", ";", "}" ]
Create an entry point, by default it sends a 401 header and ends the request. @param ContainerBuilder $container @param string $id @param mixed $defaultEntryPoint @return string
[ "Create", "an", "entry", "point", "by", "default", "it", "sends", "a", "401", "header", "and", "ends", "the", "request", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/DependencyInjection/Security/Factory/JWTFactory.php#L157-L163
train
lexik/LexikJWTAuthenticationBundle
TokenExtractor/ChainTokenExtractor.php
ChainTokenExtractor.removeExtractor
public function removeExtractor(\Closure $filter) { $filtered = array_filter($this->map, $filter); if (!$extractorToUnmap = current($filtered)) { return false; } $key = array_search($extractorToUnmap, $this->map); unset($this->map[$key]); return true; }
php
public function removeExtractor(\Closure $filter) { $filtered = array_filter($this->map, $filter); if (!$extractorToUnmap = current($filtered)) { return false; } $key = array_search($extractorToUnmap, $this->map); unset($this->map[$key]); return true; }
[ "public", "function", "removeExtractor", "(", "\\", "Closure", "$", "filter", ")", "{", "$", "filtered", "=", "array_filter", "(", "$", "this", "->", "map", ",", "$", "filter", ")", ";", "if", "(", "!", "$", "extractorToUnmap", "=", "current", "(", "$", "filtered", ")", ")", "{", "return", "false", ";", "}", "$", "key", "=", "array_search", "(", "$", "extractorToUnmap", ",", "$", "this", "->", "map", ")", ";", "unset", "(", "$", "this", "->", "map", "[", "$", "key", "]", ")", ";", "return", "true", ";", "}" ]
Removes a token extractor from the map. @param Closure $filter A function taking an extractor as argument, used to find the extractor to remove, @return bool True in case of success, false otherwise
[ "Removes", "a", "token", "extractor", "from", "the", "map", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/TokenExtractor/ChainTokenExtractor.php#L49-L61
train
lexik/LexikJWTAuthenticationBundle
Security/Guard/JWTTokenAuthenticator.php
JWTTokenAuthenticator.getCredentials
public function getCredentials(Request $request) { $tokenExtractor = $this->getTokenExtractor(); if (!$tokenExtractor instanceof TokenExtractorInterface) { throw new \RuntimeException(sprintf('Method "%s::getTokenExtractor()" must return an instance of "%s".', __CLASS__, TokenExtractorInterface::class)); } if (false === ($jsonWebToken = $tokenExtractor->extract($request))) { return; } $preAuthToken = new PreAuthenticationJWTUserToken($jsonWebToken); try { if (!$payload = $this->jwtManager->decode($preAuthToken)) { throw new InvalidTokenException('Invalid JWT Token'); } $preAuthToken->setPayload($payload); } catch (JWTDecodeFailureException $e) { if (JWTDecodeFailureException::EXPIRED_TOKEN === $e->getReason()) { throw new ExpiredTokenException(); } throw new InvalidTokenException('Invalid JWT Token', 0, $e); } return $preAuthToken; }
php
public function getCredentials(Request $request) { $tokenExtractor = $this->getTokenExtractor(); if (!$tokenExtractor instanceof TokenExtractorInterface) { throw new \RuntimeException(sprintf('Method "%s::getTokenExtractor()" must return an instance of "%s".', __CLASS__, TokenExtractorInterface::class)); } if (false === ($jsonWebToken = $tokenExtractor->extract($request))) { return; } $preAuthToken = new PreAuthenticationJWTUserToken($jsonWebToken); try { if (!$payload = $this->jwtManager->decode($preAuthToken)) { throw new InvalidTokenException('Invalid JWT Token'); } $preAuthToken->setPayload($payload); } catch (JWTDecodeFailureException $e) { if (JWTDecodeFailureException::EXPIRED_TOKEN === $e->getReason()) { throw new ExpiredTokenException(); } throw new InvalidTokenException('Invalid JWT Token', 0, $e); } return $preAuthToken; }
[ "public", "function", "getCredentials", "(", "Request", "$", "request", ")", "{", "$", "tokenExtractor", "=", "$", "this", "->", "getTokenExtractor", "(", ")", ";", "if", "(", "!", "$", "tokenExtractor", "instanceof", "TokenExtractorInterface", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Method \"%s::getTokenExtractor()\" must return an instance of \"%s\".'", ",", "__CLASS__", ",", "TokenExtractorInterface", "::", "class", ")", ")", ";", "}", "if", "(", "false", "===", "(", "$", "jsonWebToken", "=", "$", "tokenExtractor", "->", "extract", "(", "$", "request", ")", ")", ")", "{", "return", ";", "}", "$", "preAuthToken", "=", "new", "PreAuthenticationJWTUserToken", "(", "$", "jsonWebToken", ")", ";", "try", "{", "if", "(", "!", "$", "payload", "=", "$", "this", "->", "jwtManager", "->", "decode", "(", "$", "preAuthToken", ")", ")", "{", "throw", "new", "InvalidTokenException", "(", "'Invalid JWT Token'", ")", ";", "}", "$", "preAuthToken", "->", "setPayload", "(", "$", "payload", ")", ";", "}", "catch", "(", "JWTDecodeFailureException", "$", "e", ")", "{", "if", "(", "JWTDecodeFailureException", "::", "EXPIRED_TOKEN", "===", "$", "e", "->", "getReason", "(", ")", ")", "{", "throw", "new", "ExpiredTokenException", "(", ")", ";", "}", "throw", "new", "InvalidTokenException", "(", "'Invalid JWT Token'", ",", "0", ",", "$", "e", ")", ";", "}", "return", "$", "preAuthToken", ";", "}" ]
Returns a decoded JWT token extracted from a request. {@inheritdoc} @return PreAuthenticationJWTUserToken @throws InvalidTokenException If an error occur while decoding the token @throws ExpiredTokenException If the request token is expired
[ "Returns", "a", "decoded", "JWT", "token", "extracted", "from", "a", "request", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/Security/Guard/JWTTokenAuthenticator.php#L95-L124
train
lexik/LexikJWTAuthenticationBundle
Security/Guard/JWTTokenAuthenticator.php
JWTTokenAuthenticator.getUser
public function getUser($preAuthToken, UserProviderInterface $userProvider) { if (!$preAuthToken instanceof PreAuthenticationJWTUserToken) { throw new \InvalidArgumentException( sprintf('The first argument of the "%s()" method must be an instance of "%s".', __METHOD__, PreAuthenticationJWTUserToken::class) ); } $payload = $preAuthToken->getPayload(); $idClaim = $this->jwtManager->getUserIdClaim(); if (!isset($payload[$idClaim])) { throw new InvalidPayloadException($idClaim); } $identity = $payload[$idClaim]; try { $user = $this->loadUser($userProvider, $payload, $identity); } catch (UsernameNotFoundException $e) { throw new UserNotFoundException($idClaim, $identity); } $this->preAuthenticationTokenStorage->setToken($preAuthToken); return $user; }
php
public function getUser($preAuthToken, UserProviderInterface $userProvider) { if (!$preAuthToken instanceof PreAuthenticationJWTUserToken) { throw new \InvalidArgumentException( sprintf('The first argument of the "%s()" method must be an instance of "%s".', __METHOD__, PreAuthenticationJWTUserToken::class) ); } $payload = $preAuthToken->getPayload(); $idClaim = $this->jwtManager->getUserIdClaim(); if (!isset($payload[$idClaim])) { throw new InvalidPayloadException($idClaim); } $identity = $payload[$idClaim]; try { $user = $this->loadUser($userProvider, $payload, $identity); } catch (UsernameNotFoundException $e) { throw new UserNotFoundException($idClaim, $identity); } $this->preAuthenticationTokenStorage->setToken($preAuthToken); return $user; }
[ "public", "function", "getUser", "(", "$", "preAuthToken", ",", "UserProviderInterface", "$", "userProvider", ")", "{", "if", "(", "!", "$", "preAuthToken", "instanceof", "PreAuthenticationJWTUserToken", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The first argument of the \"%s()\" method must be an instance of \"%s\".'", ",", "__METHOD__", ",", "PreAuthenticationJWTUserToken", "::", "class", ")", ")", ";", "}", "$", "payload", "=", "$", "preAuthToken", "->", "getPayload", "(", ")", ";", "$", "idClaim", "=", "$", "this", "->", "jwtManager", "->", "getUserIdClaim", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "payload", "[", "$", "idClaim", "]", ")", ")", "{", "throw", "new", "InvalidPayloadException", "(", "$", "idClaim", ")", ";", "}", "$", "identity", "=", "$", "payload", "[", "$", "idClaim", "]", ";", "try", "{", "$", "user", "=", "$", "this", "->", "loadUser", "(", "$", "userProvider", ",", "$", "payload", ",", "$", "identity", ")", ";", "}", "catch", "(", "UsernameNotFoundException", "$", "e", ")", "{", "throw", "new", "UserNotFoundException", "(", "$", "idClaim", ",", "$", "identity", ")", ";", "}", "$", "this", "->", "preAuthenticationTokenStorage", "->", "setToken", "(", "$", "preAuthToken", ")", ";", "return", "$", "user", ";", "}" ]
Returns an user object loaded from a JWT token. {@inheritdoc} @param PreAuthenticationJWTUserToken Implementation of the (Security) TokenInterface @throws \InvalidArgumentException If preAuthToken is not of the good type @throws InvalidPayloadException If the user identity field is not a key of the payload @throws UserNotFoundException If no user can be loaded from the given token
[ "Returns", "an", "user", "object", "loaded", "from", "a", "JWT", "token", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/Security/Guard/JWTTokenAuthenticator.php#L137-L164
train
lexik/LexikJWTAuthenticationBundle
Security/Guard/JWTTokenAuthenticator.php
JWTTokenAuthenticator.loadUser
protected function loadUser(UserProviderInterface $userProvider, array $payload, $identity) { if ($userProvider instanceof PayloadAwareUserProviderInterface) { return $userProvider->loadUserByUsernameAndPayload($identity, $payload); } return $userProvider->loadUserByUsername($identity); }
php
protected function loadUser(UserProviderInterface $userProvider, array $payload, $identity) { if ($userProvider instanceof PayloadAwareUserProviderInterface) { return $userProvider->loadUserByUsernameAndPayload($identity, $payload); } return $userProvider->loadUserByUsername($identity); }
[ "protected", "function", "loadUser", "(", "UserProviderInterface", "$", "userProvider", ",", "array", "$", "payload", ",", "$", "identity", ")", "{", "if", "(", "$", "userProvider", "instanceof", "PayloadAwareUserProviderInterface", ")", "{", "return", "$", "userProvider", "->", "loadUserByUsernameAndPayload", "(", "$", "identity", ",", "$", "payload", ")", ";", "}", "return", "$", "userProvider", "->", "loadUserByUsername", "(", "$", "identity", ")", ";", "}" ]
Loads the user to authenticate. @param UserProviderInterface $userProvider An user provider @param array $payload The token payload @param string $identity The key from which to retrieve the user "username" @return UserInterface
[ "Loads", "the", "user", "to", "authenticate", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/Security/Guard/JWTTokenAuthenticator.php#L282-L289
train
lexik/LexikJWTAuthenticationBundle
Security/Authentication/Provider/JWTProvider.php
JWTProvider.getUserFromPayload
protected function getUserFromPayload(array $payload) { if (!isset($payload[$this->userIdClaim])) { throw $this->createAuthenticationException(); } return $this->userProvider->loadUserByUsername($payload[$this->userIdClaim]); }
php
protected function getUserFromPayload(array $payload) { if (!isset($payload[$this->userIdClaim])) { throw $this->createAuthenticationException(); } return $this->userProvider->loadUserByUsername($payload[$this->userIdClaim]); }
[ "protected", "function", "getUserFromPayload", "(", "array", "$", "payload", ")", "{", "if", "(", "!", "isset", "(", "$", "payload", "[", "$", "this", "->", "userIdClaim", "]", ")", ")", "{", "throw", "$", "this", "->", "createAuthenticationException", "(", ")", ";", "}", "return", "$", "this", "->", "userProvider", "->", "loadUserByUsername", "(", "$", "payload", "[", "$", "this", "->", "userIdClaim", "]", ")", ";", "}" ]
Load user from payload, using username by default. Override this to load by another property. @param array $payload @return \Symfony\Component\Security\Core\User\UserInterface
[ "Load", "user", "from", "payload", "using", "username", "by", "default", ".", "Override", "this", "to", "load", "by", "another", "property", "." ]
eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3
https://github.com/lexik/LexikJWTAuthenticationBundle/blob/eb304aedddb8a2789bf7bcf62d2d0829f5c3c5a3/Security/Authentication/Provider/JWTProvider.php#L106-L113
train
rectorphp/rector
packages/ConsoleDiffer/src/MarkdownDifferAndFormatter.php
MarkdownDifferAndFormatter.removeTrailingWhitespaces
private function removeTrailingWhitespaces(string $diff): string { $diff = Strings::replace($diff, '#( ){1,}\n#', PHP_EOL); return rtrim($diff); }
php
private function removeTrailingWhitespaces(string $diff): string { $diff = Strings::replace($diff, '#( ){1,}\n#', PHP_EOL); return rtrim($diff); }
[ "private", "function", "removeTrailingWhitespaces", "(", "string", "$", "diff", ")", ":", "string", "{", "$", "diff", "=", "Strings", "::", "replace", "(", "$", "diff", ",", "'#( ){1,}\\n#'", ",", "PHP_EOL", ")", ";", "return", "rtrim", "(", "$", "diff", ")", ";", "}" ]
Removes UnifiedDiffOutputBuilder generated pre-spaces " \n" => "\n"
[ "Removes", "UnifiedDiffOutputBuilder", "generated", "pre", "-", "spaces", "\\", "n", "=", ">", "\\", "n" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/ConsoleDiffer/src/MarkdownDifferAndFormatter.php#L37-L42
train
rectorphp/rector
src/Configuration/Configuration.php
Configuration.resolveFromInput
public function resolveFromInput(InputInterface $input): void { $this->isDryRun = (bool) $input->getOption(Option::OPTION_DRY_RUN); $this->source = (array) $input->getArgument(Option::SOURCE); $this->hideAutoloadErrors = (bool) $input->getOption(Option::HIDE_AUTOLOAD_ERRORS); $this->withStyle = (bool) $input->getOption(Option::OPTION_WITH_STYLE); }
php
public function resolveFromInput(InputInterface $input): void { $this->isDryRun = (bool) $input->getOption(Option::OPTION_DRY_RUN); $this->source = (array) $input->getArgument(Option::SOURCE); $this->hideAutoloadErrors = (bool) $input->getOption(Option::HIDE_AUTOLOAD_ERRORS); $this->withStyle = (bool) $input->getOption(Option::OPTION_WITH_STYLE); }
[ "public", "function", "resolveFromInput", "(", "InputInterface", "$", "input", ")", ":", "void", "{", "$", "this", "->", "isDryRun", "=", "(", "bool", ")", "$", "input", "->", "getOption", "(", "Option", "::", "OPTION_DRY_RUN", ")", ";", "$", "this", "->", "source", "=", "(", "array", ")", "$", "input", "->", "getArgument", "(", "Option", "::", "SOURCE", ")", ";", "$", "this", "->", "hideAutoloadErrors", "=", "(", "bool", ")", "$", "input", "->", "getOption", "(", "Option", "::", "HIDE_AUTOLOAD_ERRORS", ")", ";", "$", "this", "->", "withStyle", "=", "(", "bool", ")", "$", "input", "->", "getOption", "(", "Option", "::", "OPTION_WITH_STYLE", ")", ";", "}" ]
Needs to run in the start of the life cycle, since the rest of workflow uses it.
[ "Needs", "to", "run", "in", "the", "start", "of", "the", "life", "cycle", "since", "the", "rest", "of", "workflow", "uses", "it", "." ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/Configuration/Configuration.php#L33-L39
train
rectorphp/rector
src/PhpParser/NodeTraverser/RectorNodeTraverser.php
RectorNodeTraverser.configureEnabledRectorsOnly
private function configureEnabledRectorsOnly(): void { $this->visitors = []; $enabledRectors = $this->enabledRectorsProvider->getEnabledRectors(); foreach ($enabledRectors as $enabledRector => $configuration) { foreach ($this->allPhpRectors as $phpRector) { if (! is_a($phpRector, $enabledRector, true)) { continue; } $this->addRectorConfiguration($configuration, $phpRector); $this->addVisitor($phpRector); continue 2; } } }
php
private function configureEnabledRectorsOnly(): void { $this->visitors = []; $enabledRectors = $this->enabledRectorsProvider->getEnabledRectors(); foreach ($enabledRectors as $enabledRector => $configuration) { foreach ($this->allPhpRectors as $phpRector) { if (! is_a($phpRector, $enabledRector, true)) { continue; } $this->addRectorConfiguration($configuration, $phpRector); $this->addVisitor($phpRector); continue 2; } } }
[ "private", "function", "configureEnabledRectorsOnly", "(", ")", ":", "void", "{", "$", "this", "->", "visitors", "=", "[", "]", ";", "$", "enabledRectors", "=", "$", "this", "->", "enabledRectorsProvider", "->", "getEnabledRectors", "(", ")", ";", "foreach", "(", "$", "enabledRectors", "as", "$", "enabledRector", "=>", "$", "configuration", ")", "{", "foreach", "(", "$", "this", "->", "allPhpRectors", "as", "$", "phpRector", ")", "{", "if", "(", "!", "is_a", "(", "$", "phpRector", ",", "$", "enabledRector", ",", "true", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "addRectorConfiguration", "(", "$", "configuration", ",", "$", "phpRector", ")", ";", "$", "this", "->", "addVisitor", "(", "$", "phpRector", ")", ";", "continue", "2", ";", "}", "}", "}" ]
Mostly used for testing
[ "Mostly", "used", "for", "testing" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/PhpParser/NodeTraverser/RectorNodeTraverser.php#L71-L88
train
rectorphp/rector
packages/PhpSpecToPHPUnit/src/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php
PhpSpecMocksToPHPUnitMocksRector.createCreateMockCall
private function createCreateMockCall(Param $param, Name $name): ?Expression { /** @var Class_ $classNode */ $classNode = $param->getAttribute(AttributeKey::CLASS_NODE); $classMocks = $this->phpSpecMockCollector->resolveClassMocksFromParam($classNode); $variable = $this->getName($param->var); $method = $param->getAttribute(AttributeKey::METHOD_NAME); $methodsWithWThisMock = $classMocks[$variable]; // single use: "$mock = $this->createMock()" if (! $this->phpSpecMockCollector->isVariableMockInProperty($param->var)) { return $this->createNewMockVariableAssign($param, $name); } $reversedMethodsWithThisMock = array_flip($methodsWithWThisMock); // first use of many: "$this->mock = $this->createMock()" if ($reversedMethodsWithThisMock[$method] === 0) { return $this->createPropertyFetchMockVariableAssign($param, $name); } return null; }
php
private function createCreateMockCall(Param $param, Name $name): ?Expression { /** @var Class_ $classNode */ $classNode = $param->getAttribute(AttributeKey::CLASS_NODE); $classMocks = $this->phpSpecMockCollector->resolveClassMocksFromParam($classNode); $variable = $this->getName($param->var); $method = $param->getAttribute(AttributeKey::METHOD_NAME); $methodsWithWThisMock = $classMocks[$variable]; // single use: "$mock = $this->createMock()" if (! $this->phpSpecMockCollector->isVariableMockInProperty($param->var)) { return $this->createNewMockVariableAssign($param, $name); } $reversedMethodsWithThisMock = array_flip($methodsWithWThisMock); // first use of many: "$this->mock = $this->createMock()" if ($reversedMethodsWithThisMock[$method] === 0) { return $this->createPropertyFetchMockVariableAssign($param, $name); } return null; }
[ "private", "function", "createCreateMockCall", "(", "Param", "$", "param", ",", "Name", "$", "name", ")", ":", "?", "Expression", "{", "/** @var Class_ $classNode */", "$", "classNode", "=", "$", "param", "->", "getAttribute", "(", "AttributeKey", "::", "CLASS_NODE", ")", ";", "$", "classMocks", "=", "$", "this", "->", "phpSpecMockCollector", "->", "resolveClassMocksFromParam", "(", "$", "classNode", ")", ";", "$", "variable", "=", "$", "this", "->", "getName", "(", "$", "param", "->", "var", ")", ";", "$", "method", "=", "$", "param", "->", "getAttribute", "(", "AttributeKey", "::", "METHOD_NAME", ")", ";", "$", "methodsWithWThisMock", "=", "$", "classMocks", "[", "$", "variable", "]", ";", "// single use: \"$mock = $this->createMock()\"", "if", "(", "!", "$", "this", "->", "phpSpecMockCollector", "->", "isVariableMockInProperty", "(", "$", "param", "->", "var", ")", ")", "{", "return", "$", "this", "->", "createNewMockVariableAssign", "(", "$", "param", ",", "$", "name", ")", ";", "}", "$", "reversedMethodsWithThisMock", "=", "array_flip", "(", "$", "methodsWithWThisMock", ")", ";", "// first use of many: \"$this->mock = $this->createMock()\"", "if", "(", "$", "reversedMethodsWithThisMock", "[", "$", "method", "]", "===", "0", ")", "{", "return", "$", "this", "->", "createPropertyFetchMockVariableAssign", "(", "$", "param", ",", "$", "name", ")", ";", "}", "return", "null", ";", "}" ]
Variable or property fetch, based on number of present params in whole class
[ "Variable", "or", "property", "fetch", "based", "on", "number", "of", "present", "params", "in", "whole", "class" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/PhpSpecToPHPUnit/src/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php#L80-L105
train
rectorphp/rector
packages/BetterPhpDocParser/src/PhpDocInfo/PhpDocInfoFactory.php
PhpDocInfoFactory.setPositionOfLastToken
private function setPositionOfLastToken( AttributeAwarePhpDocNode $attributeAwarePhpDocNode ): AttributeAwarePhpDocNode { if ($attributeAwarePhpDocNode->children === []) { return $attributeAwarePhpDocNode; } /** @var AttributeAwareNodeInterface $lastChildNode */ $phpDocChildNodes = $attributeAwarePhpDocNode->children; $lastChildNode = array_pop($phpDocChildNodes); $phpDocNodeInfo = $lastChildNode->getAttribute(Attribute::PHP_DOC_NODE_INFO); if ($phpDocNodeInfo !== null) { $attributeAwarePhpDocNode->setAttribute(Attribute::LAST_TOKEN_POSITION, $phpDocNodeInfo->getEnd()); } return $attributeAwarePhpDocNode; }
php
private function setPositionOfLastToken( AttributeAwarePhpDocNode $attributeAwarePhpDocNode ): AttributeAwarePhpDocNode { if ($attributeAwarePhpDocNode->children === []) { return $attributeAwarePhpDocNode; } /** @var AttributeAwareNodeInterface $lastChildNode */ $phpDocChildNodes = $attributeAwarePhpDocNode->children; $lastChildNode = array_pop($phpDocChildNodes); $phpDocNodeInfo = $lastChildNode->getAttribute(Attribute::PHP_DOC_NODE_INFO); if ($phpDocNodeInfo !== null) { $attributeAwarePhpDocNode->setAttribute(Attribute::LAST_TOKEN_POSITION, $phpDocNodeInfo->getEnd()); } return $attributeAwarePhpDocNode; }
[ "private", "function", "setPositionOfLastToken", "(", "AttributeAwarePhpDocNode", "$", "attributeAwarePhpDocNode", ")", ":", "AttributeAwarePhpDocNode", "{", "if", "(", "$", "attributeAwarePhpDocNode", "->", "children", "===", "[", "]", ")", "{", "return", "$", "attributeAwarePhpDocNode", ";", "}", "/** @var AttributeAwareNodeInterface $lastChildNode */", "$", "phpDocChildNodes", "=", "$", "attributeAwarePhpDocNode", "->", "children", ";", "$", "lastChildNode", "=", "array_pop", "(", "$", "phpDocChildNodes", ")", ";", "$", "phpDocNodeInfo", "=", "$", "lastChildNode", "->", "getAttribute", "(", "Attribute", "::", "PHP_DOC_NODE_INFO", ")", ";", "if", "(", "$", "phpDocNodeInfo", "!==", "null", ")", "{", "$", "attributeAwarePhpDocNode", "->", "setAttribute", "(", "Attribute", "::", "LAST_TOKEN_POSITION", ",", "$", "phpDocNodeInfo", "->", "getEnd", "(", ")", ")", ";", "}", "return", "$", "attributeAwarePhpDocNode", ";", "}" ]
Needed for printing
[ "Needed", "for", "printing" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/BetterPhpDocParser/src/PhpDocInfo/PhpDocInfoFactory.php#L64-L81
train
rectorphp/rector
src/Console/Command/ShowCommand.php
ShowCommand.resolveConfiguration
private function resolveConfiguration(RectorInterface $rector): array { $rectorReflection = new ReflectionClass($rector); $constructorReflection = $rectorReflection->getConstructor(); if ($constructorReflection === null) { return []; } $configuration = []; foreach ($constructorReflection->getParameters() as $reflectionParameter) { $parameterType = (string) $reflectionParameter->getType(); if (! $this->typeAnalyzer->isPhpReservedType($parameterType)) { continue; } if (! $rectorReflection->hasProperty($reflectionParameter->getName())) { continue; } $propertyReflection = $rectorReflection->getProperty($reflectionParameter->getName()); $propertyReflection->setAccessible(true); $configurationValue = $propertyReflection->getValue($rector); $configuration[$reflectionParameter->getName()] = $configurationValue; } return $configuration; }
php
private function resolveConfiguration(RectorInterface $rector): array { $rectorReflection = new ReflectionClass($rector); $constructorReflection = $rectorReflection->getConstructor(); if ($constructorReflection === null) { return []; } $configuration = []; foreach ($constructorReflection->getParameters() as $reflectionParameter) { $parameterType = (string) $reflectionParameter->getType(); if (! $this->typeAnalyzer->isPhpReservedType($parameterType)) { continue; } if (! $rectorReflection->hasProperty($reflectionParameter->getName())) { continue; } $propertyReflection = $rectorReflection->getProperty($reflectionParameter->getName()); $propertyReflection->setAccessible(true); $configurationValue = $propertyReflection->getValue($rector); $configuration[$reflectionParameter->getName()] = $configurationValue; } return $configuration; }
[ "private", "function", "resolveConfiguration", "(", "RectorInterface", "$", "rector", ")", ":", "array", "{", "$", "rectorReflection", "=", "new", "ReflectionClass", "(", "$", "rector", ")", ";", "$", "constructorReflection", "=", "$", "rectorReflection", "->", "getConstructor", "(", ")", ";", "if", "(", "$", "constructorReflection", "===", "null", ")", "{", "return", "[", "]", ";", "}", "$", "configuration", "=", "[", "]", ";", "foreach", "(", "$", "constructorReflection", "->", "getParameters", "(", ")", "as", "$", "reflectionParameter", ")", "{", "$", "parameterType", "=", "(", "string", ")", "$", "reflectionParameter", "->", "getType", "(", ")", ";", "if", "(", "!", "$", "this", "->", "typeAnalyzer", "->", "isPhpReservedType", "(", "$", "parameterType", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "$", "rectorReflection", "->", "hasProperty", "(", "$", "reflectionParameter", "->", "getName", "(", ")", ")", ")", "{", "continue", ";", "}", "$", "propertyReflection", "=", "$", "rectorReflection", "->", "getProperty", "(", "$", "reflectionParameter", "->", "getName", "(", ")", ")", ";", "$", "propertyReflection", "->", "setAccessible", "(", "true", ")", ";", "$", "configurationValue", "=", "$", "propertyReflection", "->", "getValue", "(", "$", "rector", ")", ";", "$", "configuration", "[", "$", "reflectionParameter", "->", "getName", "(", ")", "]", "=", "$", "configurationValue", ";", "}", "return", "$", "configuration", ";", "}" ]
Resolve configuration by convention @return mixed[]
[ "Resolve", "configuration", "by", "convention" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/Console/Command/ShowCommand.php#L78-L106
train
rectorphp/rector
packages/NodeTypeResolver/src/ComplexNodeTypeResolver.php
ComplexNodeTypeResolver.resolvePropertyTypeInfo
public function resolvePropertyTypeInfo(Property $property): ?VarTypeInfo { $types = []; $propertyDefault = $property->props[0]->default; if ($propertyDefault !== null) { $types[] = $this->nodeToStringTypeResolver->resolver($propertyDefault); } $classNode = $property->getAttribute(AttributeKey::CLASS_NODE); if (! $classNode instanceof Class_) { throw new ShouldNotHappenException(); } $propertyName = $this->nameResolver->resolve($property); if ($propertyName === null) { return null; } /** @var Assign[] $propertyAssignNodes */ $propertyAssignNodes = $this->betterNodeFinder->find([$classNode], function (Node $node) use ( $propertyName ): bool { if ($node instanceof Assign && $node->var instanceof PropertyFetch) { // is property match return $this->nameResolver->isName($node->var, $propertyName); } return false; }); foreach ($propertyAssignNodes as $propertyAssignNode) { $types = array_merge( $types, $this->nodeTypeResolver->resolveSingleTypeToStrings($propertyAssignNode->expr) ); } $types = array_filter($types); return new VarTypeInfo($types, $this->typeAnalyzer, $types, true); }
php
public function resolvePropertyTypeInfo(Property $property): ?VarTypeInfo { $types = []; $propertyDefault = $property->props[0]->default; if ($propertyDefault !== null) { $types[] = $this->nodeToStringTypeResolver->resolver($propertyDefault); } $classNode = $property->getAttribute(AttributeKey::CLASS_NODE); if (! $classNode instanceof Class_) { throw new ShouldNotHappenException(); } $propertyName = $this->nameResolver->resolve($property); if ($propertyName === null) { return null; } /** @var Assign[] $propertyAssignNodes */ $propertyAssignNodes = $this->betterNodeFinder->find([$classNode], function (Node $node) use ( $propertyName ): bool { if ($node instanceof Assign && $node->var instanceof PropertyFetch) { // is property match return $this->nameResolver->isName($node->var, $propertyName); } return false; }); foreach ($propertyAssignNodes as $propertyAssignNode) { $types = array_merge( $types, $this->nodeTypeResolver->resolveSingleTypeToStrings($propertyAssignNode->expr) ); } $types = array_filter($types); return new VarTypeInfo($types, $this->typeAnalyzer, $types, true); }
[ "public", "function", "resolvePropertyTypeInfo", "(", "Property", "$", "property", ")", ":", "?", "VarTypeInfo", "{", "$", "types", "=", "[", "]", ";", "$", "propertyDefault", "=", "$", "property", "->", "props", "[", "0", "]", "->", "default", ";", "if", "(", "$", "propertyDefault", "!==", "null", ")", "{", "$", "types", "[", "]", "=", "$", "this", "->", "nodeToStringTypeResolver", "->", "resolver", "(", "$", "propertyDefault", ")", ";", "}", "$", "classNode", "=", "$", "property", "->", "getAttribute", "(", "AttributeKey", "::", "CLASS_NODE", ")", ";", "if", "(", "!", "$", "classNode", "instanceof", "Class_", ")", "{", "throw", "new", "ShouldNotHappenException", "(", ")", ";", "}", "$", "propertyName", "=", "$", "this", "->", "nameResolver", "->", "resolve", "(", "$", "property", ")", ";", "if", "(", "$", "propertyName", "===", "null", ")", "{", "return", "null", ";", "}", "/** @var Assign[] $propertyAssignNodes */", "$", "propertyAssignNodes", "=", "$", "this", "->", "betterNodeFinder", "->", "find", "(", "[", "$", "classNode", "]", ",", "function", "(", "Node", "$", "node", ")", "use", "(", "$", "propertyName", ")", ":", "bool", "{", "if", "(", "$", "node", "instanceof", "Assign", "&&", "$", "node", "->", "var", "instanceof", "PropertyFetch", ")", "{", "// is property match", "return", "$", "this", "->", "nameResolver", "->", "isName", "(", "$", "node", "->", "var", ",", "$", "propertyName", ")", ";", "}", "return", "false", ";", "}", ")", ";", "foreach", "(", "$", "propertyAssignNodes", "as", "$", "propertyAssignNode", ")", "{", "$", "types", "=", "array_merge", "(", "$", "types", ",", "$", "this", "->", "nodeTypeResolver", "->", "resolveSingleTypeToStrings", "(", "$", "propertyAssignNode", "->", "expr", ")", ")", ";", "}", "$", "types", "=", "array_filter", "(", "$", "types", ")", ";", "return", "new", "VarTypeInfo", "(", "$", "types", ",", "$", "this", "->", "typeAnalyzer", ",", "$", "types", ",", "true", ")", ";", "}" ]
Based on static analysis of code, looking for property assigns
[ "Based", "on", "static", "analysis", "of", "code", "looking", "for", "property", "assigns" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/NodeTypeResolver/src/ComplexNodeTypeResolver.php#L62-L103
train
rectorphp/rector
packages/NodeTypeResolver/src/PhpDoc/NodeAnalyzer/DocBlockManipulator.php
DocBlockManipulator.getParamTypeInfos
public function getParamTypeInfos(Node $node): array { if ($node->getDocComment() === null) { return []; } $phpDocInfo = $this->createPhpDocInfoFromNode($node); $types = $phpDocInfo->getParamTagValues(); if ($types === []) { return []; } $fqnTypes = $phpDocInfo->getParamTagValues(); $paramTypeInfos = []; /** @var AttributeAwareParamTagValueNode $paramTagValueNode */ foreach ($types as $i => $paramTagValueNode) { $fqnParamTagValueNode = $fqnTypes[$i]; $paramTypeInfo = new ParamTypeInfo( $paramTagValueNode->parameterName, $this->typeAnalyzer, $paramTagValueNode->getAttribute(Attribute::TYPE_AS_ARRAY), $fqnParamTagValueNode->getAttribute(Attribute::RESOLVED_NAMES) ); $paramTypeInfos[$paramTypeInfo->getName()] = $paramTypeInfo; } return $paramTypeInfos; }
php
public function getParamTypeInfos(Node $node): array { if ($node->getDocComment() === null) { return []; } $phpDocInfo = $this->createPhpDocInfoFromNode($node); $types = $phpDocInfo->getParamTagValues(); if ($types === []) { return []; } $fqnTypes = $phpDocInfo->getParamTagValues(); $paramTypeInfos = []; /** @var AttributeAwareParamTagValueNode $paramTagValueNode */ foreach ($types as $i => $paramTagValueNode) { $fqnParamTagValueNode = $fqnTypes[$i]; $paramTypeInfo = new ParamTypeInfo( $paramTagValueNode->parameterName, $this->typeAnalyzer, $paramTagValueNode->getAttribute(Attribute::TYPE_AS_ARRAY), $fqnParamTagValueNode->getAttribute(Attribute::RESOLVED_NAMES) ); $paramTypeInfos[$paramTypeInfo->getName()] = $paramTypeInfo; } return $paramTypeInfos; }
[ "public", "function", "getParamTypeInfos", "(", "Node", "$", "node", ")", ":", "array", "{", "if", "(", "$", "node", "->", "getDocComment", "(", ")", "===", "null", ")", "{", "return", "[", "]", ";", "}", "$", "phpDocInfo", "=", "$", "this", "->", "createPhpDocInfoFromNode", "(", "$", "node", ")", ";", "$", "types", "=", "$", "phpDocInfo", "->", "getParamTagValues", "(", ")", ";", "if", "(", "$", "types", "===", "[", "]", ")", "{", "return", "[", "]", ";", "}", "$", "fqnTypes", "=", "$", "phpDocInfo", "->", "getParamTagValues", "(", ")", ";", "$", "paramTypeInfos", "=", "[", "]", ";", "/** @var AttributeAwareParamTagValueNode $paramTagValueNode */", "foreach", "(", "$", "types", "as", "$", "i", "=>", "$", "paramTagValueNode", ")", "{", "$", "fqnParamTagValueNode", "=", "$", "fqnTypes", "[", "$", "i", "]", ";", "$", "paramTypeInfo", "=", "new", "ParamTypeInfo", "(", "$", "paramTagValueNode", "->", "parameterName", ",", "$", "this", "->", "typeAnalyzer", ",", "$", "paramTagValueNode", "->", "getAttribute", "(", "Attribute", "::", "TYPE_AS_ARRAY", ")", ",", "$", "fqnParamTagValueNode", "->", "getAttribute", "(", "Attribute", "::", "RESOLVED_NAMES", ")", ")", ";", "$", "paramTypeInfos", "[", "$", "paramTypeInfo", "->", "getName", "(", ")", "]", "=", "$", "paramTypeInfo", ";", "}", "return", "$", "paramTypeInfos", ";", "}" ]
With "name" as key @return ParamTypeInfo[]
[ "With", "name", "as", "key" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/NodeTypeResolver/src/PhpDoc/NodeAnalyzer/DocBlockManipulator.php#L207-L238
train
rectorphp/rector
src/PhpParser/Printer/BetterStandardPrinter.php
BetterStandardPrinter.pScalar_String
protected function pScalar_String(String_ $node): string { $kind = $node->getAttribute('kind', String_::KIND_SINGLE_QUOTED); if ($kind === String_::KIND_DOUBLE_QUOTED && $node->getAttribute('is_regular_pattern')) { return '"' . $node->value . '"'; } return parent::pScalar_String($node); }
php
protected function pScalar_String(String_ $node): string { $kind = $node->getAttribute('kind', String_::KIND_SINGLE_QUOTED); if ($kind === String_::KIND_DOUBLE_QUOTED && $node->getAttribute('is_regular_pattern')) { return '"' . $node->value . '"'; } return parent::pScalar_String($node); }
[ "protected", "function", "pScalar_String", "(", "String_", "$", "node", ")", ":", "string", "{", "$", "kind", "=", "$", "node", "->", "getAttribute", "(", "'kind'", ",", "String_", "::", "KIND_SINGLE_QUOTED", ")", ";", "if", "(", "$", "kind", "===", "String_", "::", "KIND_DOUBLE_QUOTED", "&&", "$", "node", "->", "getAttribute", "(", "'is_regular_pattern'", ")", ")", "{", "return", "'\"'", ".", "$", "node", "->", "value", ".", "'\"'", ";", "}", "return", "parent", "::", "pScalar_String", "(", "$", "node", ")", ";", "}" ]
Fixes escaping of regular patterns
[ "Fixes", "escaping", "of", "regular", "patterns" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/PhpParser/Printer/BetterStandardPrinter.php#L150-L158
train
rectorphp/rector
src/PhpParser/Printer/BetterStandardPrinter.php
BetterStandardPrinter.pStmt_Class
protected function pStmt_Class(Class_ $class): string { $shouldReindex = false; foreach ($class->stmts as $key => $stmt) { if ($stmt instanceof TraitUse) { // remove empty ones if (count($stmt->traits) === 0) { unset($class->stmts[$key]); $shouldReindex = true; } } } if ($shouldReindex) { $class->stmts = array_values($class->stmts); } return parent::pStmt_Class($class); }
php
protected function pStmt_Class(Class_ $class): string { $shouldReindex = false; foreach ($class->stmts as $key => $stmt) { if ($stmt instanceof TraitUse) { // remove empty ones if (count($stmt->traits) === 0) { unset($class->stmts[$key]); $shouldReindex = true; } } } if ($shouldReindex) { $class->stmts = array_values($class->stmts); } return parent::pStmt_Class($class); }
[ "protected", "function", "pStmt_Class", "(", "Class_", "$", "class", ")", ":", "string", "{", "$", "shouldReindex", "=", "false", ";", "foreach", "(", "$", "class", "->", "stmts", "as", "$", "key", "=>", "$", "stmt", ")", "{", "if", "(", "$", "stmt", "instanceof", "TraitUse", ")", "{", "// remove empty ones", "if", "(", "count", "(", "$", "stmt", "->", "traits", ")", "===", "0", ")", "{", "unset", "(", "$", "class", "->", "stmts", "[", "$", "key", "]", ")", ";", "$", "shouldReindex", "=", "true", ";", "}", "}", "}", "if", "(", "$", "shouldReindex", ")", "{", "$", "class", "->", "stmts", "=", "array_values", "(", "$", "class", "->", "stmts", ")", ";", "}", "return", "parent", "::", "pStmt_Class", "(", "$", "class", ")", ";", "}" ]
Clean class and trait from empty "use x;" for traits causing invalid code
[ "Clean", "class", "and", "trait", "from", "empty", "use", "x", ";", "for", "traits", "causing", "invalid", "code" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/PhpParser/Printer/BetterStandardPrinter.php#L179-L198
train
rectorphp/rector
packages/Symfony/src/Rector/Yaml/ParseFileRector.php
ParseFileRector.refactor
public function refactor(Node $node): ?Node { if (! $this->isName($node, 'parse')) { return null; } if (! $this->isType($node->class, 'Symfony\Component\Yaml\Yaml')) { return null; } if (! $this->isArgumentYamlFile($node)) { return null; } $fileGetContentsFunCallNode = $this->createFunction('file_get_contents', [$node->args[0]]); $node->args[0] = new Arg($fileGetContentsFunCallNode); return $node; }
php
public function refactor(Node $node): ?Node { if (! $this->isName($node, 'parse')) { return null; } if (! $this->isType($node->class, 'Symfony\Component\Yaml\Yaml')) { return null; } if (! $this->isArgumentYamlFile($node)) { return null; } $fileGetContentsFunCallNode = $this->createFunction('file_get_contents', [$node->args[0]]); $node->args[0] = new Arg($fileGetContentsFunCallNode); return $node; }
[ "public", "function", "refactor", "(", "Node", "$", "node", ")", ":", "?", "Node", "{", "if", "(", "!", "$", "this", "->", "isName", "(", "$", "node", ",", "'parse'", ")", ")", "{", "return", "null", ";", "}", "if", "(", "!", "$", "this", "->", "isType", "(", "$", "node", "->", "class", ",", "'Symfony\\Component\\Yaml\\Yaml'", ")", ")", "{", "return", "null", ";", "}", "if", "(", "!", "$", "this", "->", "isArgumentYamlFile", "(", "$", "node", ")", ")", "{", "return", "null", ";", "}", "$", "fileGetContentsFunCallNode", "=", "$", "this", "->", "createFunction", "(", "'file_get_contents'", ",", "[", "$", "node", "->", "args", "[", "0", "]", "]", ")", ";", "$", "node", "->", "args", "[", "0", "]", "=", "new", "Arg", "(", "$", "fileGetContentsFunCallNode", ")", ";", "return", "$", "node", ";", "}" ]
Process Node of matched type @param StaticCall $node
[ "Process", "Node", "of", "matched", "type" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/Symfony/src/Rector/Yaml/ParseFileRector.php#L39-L57
train
rectorphp/rector
packages/PHPUnit/src/Rector/SpecificMethod/AssertCompareToSpecificMethodRector.php
AssertCompareToSpecificMethodRector.moveFunctionArgumentsUp
private function moveFunctionArgumentsUp(Node $node): void { /** @var FuncCall $secondArgument */ $secondArgument = $node->args[1]->value; $node->args[1] = $secondArgument->args[0]; }
php
private function moveFunctionArgumentsUp(Node $node): void { /** @var FuncCall $secondArgument */ $secondArgument = $node->args[1]->value; $node->args[1] = $secondArgument->args[0]; }
[ "private", "function", "moveFunctionArgumentsUp", "(", "Node", "$", "node", ")", ":", "void", "{", "/** @var FuncCall $secondArgument */", "$", "secondArgument", "=", "$", "node", "->", "args", "[", "1", "]", "->", "value", ";", "$", "node", "->", "args", "[", "1", "]", "=", "$", "secondArgument", "->", "args", "[", "0", "]", ";", "}" ]
Handles custom error messages to not be overwrite by function with multiple args. @param StaticCall|MethodCall $node
[ "Handles", "custom", "error", "messages", "to", "not", "be", "overwrite", "by", "function", "with", "multiple", "args", "." ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/PHPUnit/src/Rector/SpecificMethod/AssertCompareToSpecificMethodRector.php#L115-L120
train
rectorphp/rector
packages/Sensio/src/Rector/FrameworkExtraBundle/TemplateAnnotationRector.php
TemplateAnnotationRector.resolveArgumentsFromMethodCall
private function resolveArgumentsFromMethodCall(Return_ $returnNode): array { $arguments = []; if ($returnNode->expr instanceof MethodCall) { foreach ($returnNode->expr->args as $arg) { if ($arg->value instanceof Array_) { $arguments[] = $arg->value; } } } return $arguments; }
php
private function resolveArgumentsFromMethodCall(Return_ $returnNode): array { $arguments = []; if ($returnNode->expr instanceof MethodCall) { foreach ($returnNode->expr->args as $arg) { if ($arg->value instanceof Array_) { $arguments[] = $arg->value; } } } return $arguments; }
[ "private", "function", "resolveArgumentsFromMethodCall", "(", "Return_", "$", "returnNode", ")", ":", "array", "{", "$", "arguments", "=", "[", "]", ";", "if", "(", "$", "returnNode", "->", "expr", "instanceof", "MethodCall", ")", "{", "foreach", "(", "$", "returnNode", "->", "expr", "->", "args", "as", "$", "arg", ")", "{", "if", "(", "$", "arg", "->", "value", "instanceof", "Array_", ")", "{", "$", "arguments", "[", "]", "=", "$", "arg", "->", "value", ";", "}", "}", "}", "return", "$", "arguments", ";", "}" ]
Already existing method call @return mixed[]
[ "Already", "existing", "method", "call" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/Sensio/src/Rector/FrameworkExtraBundle/TemplateAnnotationRector.php#L147-L159
train
rectorphp/rector
packages/BetterPhpDocParser/src/Printer/PhpDocInfoPrinter.php
PhpDocInfoPrinter.printFormatPreserving
public function printFormatPreserving(PhpDocInfo $phpDocInfo): string { $this->attributeAwarePhpDocNode = $phpDocInfo->getPhpDocNode(); $this->tokens = $phpDocInfo->getTokens(); $this->tokenCount = count($phpDocInfo->getTokens()); $this->phpDocInfo = $phpDocInfo; $this->currentTokenPosition = 0; $this->removedNodePositions = []; return $this->printPhpDocNode($this->attributeAwarePhpDocNode); }
php
public function printFormatPreserving(PhpDocInfo $phpDocInfo): string { $this->attributeAwarePhpDocNode = $phpDocInfo->getPhpDocNode(); $this->tokens = $phpDocInfo->getTokens(); $this->tokenCount = count($phpDocInfo->getTokens()); $this->phpDocInfo = $phpDocInfo; $this->currentTokenPosition = 0; $this->removedNodePositions = []; return $this->printPhpDocNode($this->attributeAwarePhpDocNode); }
[ "public", "function", "printFormatPreserving", "(", "PhpDocInfo", "$", "phpDocInfo", ")", ":", "string", "{", "$", "this", "->", "attributeAwarePhpDocNode", "=", "$", "phpDocInfo", "->", "getPhpDocNode", "(", ")", ";", "$", "this", "->", "tokens", "=", "$", "phpDocInfo", "->", "getTokens", "(", ")", ";", "$", "this", "->", "tokenCount", "=", "count", "(", "$", "phpDocInfo", "->", "getTokens", "(", ")", ")", ";", "$", "this", "->", "phpDocInfo", "=", "$", "phpDocInfo", ";", "$", "this", "->", "currentTokenPosition", "=", "0", ";", "$", "this", "->", "removedNodePositions", "=", "[", "]", ";", "return", "$", "this", "->", "printPhpDocNode", "(", "$", "this", "->", "attributeAwarePhpDocNode", ")", ";", "}" ]
As in php-parser ref: https://github.com/nikic/PHP-Parser/issues/487#issuecomment-375986259 - Tokens[node.startPos .. subnode1.startPos] - Print(subnode1) - Tokens[subnode1.endPos .. subnode2.startPos] - Print(subnode2) - Tokens[subnode2.endPos .. node.endPos]
[ "As", "in", "php", "-", "parser" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/BetterPhpDocParser/src/Printer/PhpDocInfoPrinter.php#L69-L80
train
rectorphp/rector
src/PhpParser/Node/Manipulator/FunctionLikeManipulator.php
FunctionLikeManipulator.resolveStaticReturnTypeInfo
public function resolveStaticReturnTypeInfo(FunctionLike $functionLike): ?ReturnTypeInfo { if ($this->shouldSkip($functionLike)) { return null; } /** @var Return_[] $returnNodes */ $returnNodes = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Return_::class); $isVoid = true; $types = []; foreach ($returnNodes as $returnNode) { if ($returnNode->expr === null) { continue; } $types = array_merge($types, $this->nodeTypeResolver->resolveSingleTypeToStrings($returnNode->expr)); $isVoid = false; } if ($isVoid) { return new ReturnTypeInfo(['void'], $this->typeAnalyzer); } $types = array_filter($types); return new ReturnTypeInfo($types, $this->typeAnalyzer); }
php
public function resolveStaticReturnTypeInfo(FunctionLike $functionLike): ?ReturnTypeInfo { if ($this->shouldSkip($functionLike)) { return null; } /** @var Return_[] $returnNodes */ $returnNodes = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Return_::class); $isVoid = true; $types = []; foreach ($returnNodes as $returnNode) { if ($returnNode->expr === null) { continue; } $types = array_merge($types, $this->nodeTypeResolver->resolveSingleTypeToStrings($returnNode->expr)); $isVoid = false; } if ($isVoid) { return new ReturnTypeInfo(['void'], $this->typeAnalyzer); } $types = array_filter($types); return new ReturnTypeInfo($types, $this->typeAnalyzer); }
[ "public", "function", "resolveStaticReturnTypeInfo", "(", "FunctionLike", "$", "functionLike", ")", ":", "?", "ReturnTypeInfo", "{", "if", "(", "$", "this", "->", "shouldSkip", "(", "$", "functionLike", ")", ")", "{", "return", "null", ";", "}", "/** @var Return_[] $returnNodes */", "$", "returnNodes", "=", "$", "this", "->", "betterNodeFinder", "->", "findInstanceOf", "(", "(", "array", ")", "$", "functionLike", "->", "stmts", ",", "Return_", "::", "class", ")", ";", "$", "isVoid", "=", "true", ";", "$", "types", "=", "[", "]", ";", "foreach", "(", "$", "returnNodes", "as", "$", "returnNode", ")", "{", "if", "(", "$", "returnNode", "->", "expr", "===", "null", ")", "{", "continue", ";", "}", "$", "types", "=", "array_merge", "(", "$", "types", ",", "$", "this", "->", "nodeTypeResolver", "->", "resolveSingleTypeToStrings", "(", "$", "returnNode", "->", "expr", ")", ")", ";", "$", "isVoid", "=", "false", ";", "}", "if", "(", "$", "isVoid", ")", "{", "return", "new", "ReturnTypeInfo", "(", "[", "'void'", "]", ",", "$", "this", "->", "typeAnalyzer", ")", ";", "}", "$", "types", "=", "array_filter", "(", "$", "types", ")", ";", "return", "new", "ReturnTypeInfo", "(", "$", "types", ",", "$", "this", "->", "typeAnalyzer", ")", ";", "}" ]
Based on static analysis of code, looking for return types @param ClassMethod|Function_ $functionLike
[ "Based", "on", "static", "analysis", "of", "code", "looking", "for", "return", "types" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/PhpParser/Node/Manipulator/FunctionLikeManipulator.php#L47-L75
train
rectorphp/rector
packages/PhpSpecToPHPUnit/src/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php
PhpSpecClassToPHPUnitClassRector.removeSelfTypeMethod
private function removeSelfTypeMethod(Class_ $node): Class_ { foreach ((array) $node->stmts as $key => $stmt) { if (! $stmt instanceof ClassMethod) { continue; } if (count((array) $stmt->stmts) !== 1) { continue; } $innerClassMethodStmt = $stmt->stmts[0] instanceof Expression ? $stmt->stmts[0]->expr : $stmt->stmts[0]; if (! $innerClassMethodStmt instanceof MethodCall) { continue; } if (! $this->isName($innerClassMethodStmt, 'shouldHaveType')) { continue; } // not the tested type if (! $this->isValue($innerClassMethodStmt->args[0]->value, $this->testedClass)) { continue; } // remove it unset($node->stmts[$key]); } return $node; }
php
private function removeSelfTypeMethod(Class_ $node): Class_ { foreach ((array) $node->stmts as $key => $stmt) { if (! $stmt instanceof ClassMethod) { continue; } if (count((array) $stmt->stmts) !== 1) { continue; } $innerClassMethodStmt = $stmt->stmts[0] instanceof Expression ? $stmt->stmts[0]->expr : $stmt->stmts[0]; if (! $innerClassMethodStmt instanceof MethodCall) { continue; } if (! $this->isName($innerClassMethodStmt, 'shouldHaveType')) { continue; } // not the tested type if (! $this->isValue($innerClassMethodStmt->args[0]->value, $this->testedClass)) { continue; } // remove it unset($node->stmts[$key]); } return $node; }
[ "private", "function", "removeSelfTypeMethod", "(", "Class_", "$", "node", ")", ":", "Class_", "{", "foreach", "(", "(", "array", ")", "$", "node", "->", "stmts", "as", "$", "key", "=>", "$", "stmt", ")", "{", "if", "(", "!", "$", "stmt", "instanceof", "ClassMethod", ")", "{", "continue", ";", "}", "if", "(", "count", "(", "(", "array", ")", "$", "stmt", "->", "stmts", ")", "!==", "1", ")", "{", "continue", ";", "}", "$", "innerClassMethodStmt", "=", "$", "stmt", "->", "stmts", "[", "0", "]", "instanceof", "Expression", "?", "$", "stmt", "->", "stmts", "[", "0", "]", "->", "expr", ":", "$", "stmt", "->", "stmts", "[", "0", "]", ";", "if", "(", "!", "$", "innerClassMethodStmt", "instanceof", "MethodCall", ")", "{", "continue", ";", "}", "if", "(", "!", "$", "this", "->", "isName", "(", "$", "innerClassMethodStmt", ",", "'shouldHaveType'", ")", ")", "{", "continue", ";", "}", "// not the tested type", "if", "(", "!", "$", "this", "->", "isValue", "(", "$", "innerClassMethodStmt", "->", "args", "[", "0", "]", "->", "value", ",", "$", "this", "->", "testedClass", ")", ")", "{", "continue", ";", "}", "// remove it", "unset", "(", "$", "node", "->", "stmts", "[", "$", "key", "]", ")", ";", "}", "return", "$", "node", ";", "}" ]
This is already checked on construction of object
[ "This", "is", "already", "checked", "on", "construction", "of", "object" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/PhpSpecToPHPUnit/src/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php#L120-L151
train
rectorphp/rector
packages/CodeQuality/src/Rector/Identical/SimplifyConditionsRector.php
SimplifyConditionsRector.shouldSkip
private function shouldSkip(BinaryOp $binaryOp): bool { if ($binaryOp instanceof BooleanOr) { return true; } if ($binaryOp->left instanceof BinaryOp) { return true; } return $binaryOp->right instanceof BinaryOp; }
php
private function shouldSkip(BinaryOp $binaryOp): bool { if ($binaryOp instanceof BooleanOr) { return true; } if ($binaryOp->left instanceof BinaryOp) { return true; } return $binaryOp->right instanceof BinaryOp; }
[ "private", "function", "shouldSkip", "(", "BinaryOp", "$", "binaryOp", ")", ":", "bool", "{", "if", "(", "$", "binaryOp", "instanceof", "BooleanOr", ")", "{", "return", "true", ";", "}", "if", "(", "$", "binaryOp", "->", "left", "instanceof", "BinaryOp", ")", "{", "return", "true", ";", "}", "return", "$", "binaryOp", "->", "right", "instanceof", "BinaryOp", ";", "}" ]
Skip too nested binary || binary > binary combinations
[ "Skip", "too", "nested", "binary", "||", "binary", ">", "binary", "combinations" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/CodeQuality/src/Rector/Identical/SimplifyConditionsRector.php#L104-L114
train
rectorphp/rector
packages/NodeTypeResolver/src/Php/AbstractTypeInfo.php
AbstractTypeInfo.isTypehintAble
public function isTypehintAble(): bool { if ($this->hasRemovedTypes()) { return false; } $typeCount = count($this->types); if ($typeCount >= 2 && $this->isArraySubtype($this->types)) { return true; } return $typeCount === 1; }
php
public function isTypehintAble(): bool { if ($this->hasRemovedTypes()) { return false; } $typeCount = count($this->types); if ($typeCount >= 2 && $this->isArraySubtype($this->types)) { return true; } return $typeCount === 1; }
[ "public", "function", "isTypehintAble", "(", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "hasRemovedTypes", "(", ")", ")", "{", "return", "false", ";", "}", "$", "typeCount", "=", "count", "(", "$", "this", "->", "types", ")", ";", "if", "(", "$", "typeCount", ">=", "2", "&&", "$", "this", "->", "isArraySubtype", "(", "$", "this", "->", "types", ")", ")", "{", "return", "true", ";", "}", "return", "$", "typeCount", "===", "1", ";", "}" ]
Can be put as PHP typehint to code
[ "Can", "be", "put", "as", "PHP", "typehint", "to", "code" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/packages/NodeTypeResolver/src/Php/AbstractTypeInfo.php#L121-L134
train
rectorphp/rector
src/Rector/Namespace_/RenameNamespaceRector.php
RenameNamespaceRector.isClassFullyQualifiedName
private function isClassFullyQualifiedName(Node $node): bool { $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); if ($parentNode === null) { return false; } if (! $parentNode instanceof New_) { return false; } /** @var FullyQualified $fullyQualifiedNode */ $fullyQualifiedNode = $parentNode->class; $newClassName = $fullyQualifiedNode->toString(); return array_key_exists($newClassName, $this->oldToNewNamespaces); }
php
private function isClassFullyQualifiedName(Node $node): bool { $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); if ($parentNode === null) { return false; } if (! $parentNode instanceof New_) { return false; } /** @var FullyQualified $fullyQualifiedNode */ $fullyQualifiedNode = $parentNode->class; $newClassName = $fullyQualifiedNode->toString(); return array_key_exists($newClassName, $this->oldToNewNamespaces); }
[ "private", "function", "isClassFullyQualifiedName", "(", "Node", "$", "node", ")", ":", "bool", "{", "$", "parentNode", "=", "$", "node", "->", "getAttribute", "(", "AttributeKey", "::", "PARENT_NODE", ")", ";", "if", "(", "$", "parentNode", "===", "null", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "parentNode", "instanceof", "New_", ")", "{", "return", "false", ";", "}", "/** @var FullyQualified $fullyQualifiedNode */", "$", "fullyQualifiedNode", "=", "$", "parentNode", "->", "class", ";", "$", "newClassName", "=", "$", "fullyQualifiedNode", "->", "toString", "(", ")", ";", "return", "array_key_exists", "(", "$", "newClassName", ",", "$", "this", "->", "oldToNewNamespaces", ")", ";", "}" ]
Checks for "new \ClassNoNamespace;" This should be skipped, not a namespace.
[ "Checks", "for", "new", "\\", "ClassNoNamespace", ";", "This", "should", "be", "skipped", "not", "a", "namespace", "." ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/Rector/Namespace_/RenameNamespaceRector.php#L109-L126
train
rectorphp/rector
src/PhpParser/Node/Manipulator/VisibilityManipulator.php
VisibilityManipulator.removeOriginalVisibilityFromFlags
private function removeOriginalVisibilityFromFlags(Node $node): void { $this->ensureIsClassMethodOrProperty($node, __METHOD__); // no modifier if ($node->flags === 0) { return; } if ($node->isPublic()) { $node->flags -= Class_::MODIFIER_PUBLIC; } if ($node->isProtected()) { $node->flags -= Class_::MODIFIER_PROTECTED; } if ($node->isPrivate()) { $node->flags -= Class_::MODIFIER_PRIVATE; } }
php
private function removeOriginalVisibilityFromFlags(Node $node): void { $this->ensureIsClassMethodOrProperty($node, __METHOD__); // no modifier if ($node->flags === 0) { return; } if ($node->isPublic()) { $node->flags -= Class_::MODIFIER_PUBLIC; } if ($node->isProtected()) { $node->flags -= Class_::MODIFIER_PROTECTED; } if ($node->isPrivate()) { $node->flags -= Class_::MODIFIER_PRIVATE; } }
[ "private", "function", "removeOriginalVisibilityFromFlags", "(", "Node", "$", "node", ")", ":", "void", "{", "$", "this", "->", "ensureIsClassMethodOrProperty", "(", "$", "node", ",", "__METHOD__", ")", ";", "// no modifier", "if", "(", "$", "node", "->", "flags", "===", "0", ")", "{", "return", ";", "}", "if", "(", "$", "node", "->", "isPublic", "(", ")", ")", "{", "$", "node", "->", "flags", "-=", "Class_", "::", "MODIFIER_PUBLIC", ";", "}", "if", "(", "$", "node", "->", "isProtected", "(", ")", ")", "{", "$", "node", "->", "flags", "-=", "Class_", "::", "MODIFIER_PROTECTED", ";", "}", "if", "(", "$", "node", "->", "isPrivate", "(", ")", ")", "{", "$", "node", "->", "flags", "-=", "Class_", "::", "MODIFIER_PRIVATE", ";", "}", "}" ]
This way "abstract", "static", "final" are kept @param ClassMethod|Property|ClassConst $node
[ "This", "way", "abstract", "static", "final", "are", "kept" ]
82ad572707d684f4c608c85f0a4f6ce0ff481b12
https://github.com/rectorphp/rector/blob/82ad572707d684f4c608c85f0a4f6ce0ff481b12/src/PhpParser/Node/Manipulator/VisibilityManipulator.php#L46-L66
train
leocavalcante/siler
src/Monolog/Monolog.php
Loggers.getLogger
public static function getLogger(string $channel): Logger { if (empty(static::$loggers[$channel])) { static::$loggers[$channel] = new Logger($channel); } return static::$loggers[$channel]; }
php
public static function getLogger(string $channel): Logger { if (empty(static::$loggers[$channel])) { static::$loggers[$channel] = new Logger($channel); } return static::$loggers[$channel]; }
[ "public", "static", "function", "getLogger", "(", "string", "$", "channel", ")", ":", "Logger", "{", "if", "(", "empty", "(", "static", "::", "$", "loggers", "[", "$", "channel", "]", ")", ")", "{", "static", "::", "$", "loggers", "[", "$", "channel", "]", "=", "new", "Logger", "(", "$", "channel", ")", ";", "}", "return", "static", "::", "$", "loggers", "[", "$", "channel", "]", ";", "}" ]
Returns the Logger identified by the channel. @param string $channel The log channel. @return Logger
[ "Returns", "the", "Logger", "identified", "by", "the", "channel", "." ]
83bf76fc00e233f86c3234f0e427484caee5ebc6
https://github.com/leocavalcante/siler/blob/83bf76fc00e233f86c3234f0e427484caee5ebc6/src/Monolog/Monolog.php#L204-L211
train
dimsav/laravel-translatable
src/Translatable/Translatable.php
Translatable.scopeOrderByTranslation
public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc') { $translationTable = $this->getTranslationsTable(); $localeKey = $this->getLocaleKey(); $table = $this->getTable(); $keyName = $this->getKeyName(); return $query ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) { $join ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName) ->where($translationTable.'.'.$localeKey, $this->locale()); }) ->orderBy($translationTable.'.'.$key, $sortmethod) ->select($table.'.*') ->with('translations'); }
php
public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc') { $translationTable = $this->getTranslationsTable(); $localeKey = $this->getLocaleKey(); $table = $this->getTable(); $keyName = $this->getKeyName(); return $query ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) { $join ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName) ->where($translationTable.'.'.$localeKey, $this->locale()); }) ->orderBy($translationTable.'.'.$key, $sortmethod) ->select($table.'.*') ->with('translations'); }
[ "public", "function", "scopeOrderByTranslation", "(", "Builder", "$", "query", ",", "$", "key", ",", "$", "sortmethod", "=", "'asc'", ")", "{", "$", "translationTable", "=", "$", "this", "->", "getTranslationsTable", "(", ")", ";", "$", "localeKey", "=", "$", "this", "->", "getLocaleKey", "(", ")", ";", "$", "table", "=", "$", "this", "->", "getTable", "(", ")", ";", "$", "keyName", "=", "$", "this", "->", "getKeyName", "(", ")", ";", "return", "$", "query", "->", "join", "(", "$", "translationTable", ",", "function", "(", "JoinClause", "$", "join", ")", "use", "(", "$", "translationTable", ",", "$", "localeKey", ",", "$", "table", ",", "$", "keyName", ")", "{", "$", "join", "->", "on", "(", "$", "translationTable", ".", "'.'", ".", "$", "this", "->", "getRelationKey", "(", ")", ",", "'='", ",", "$", "table", ".", "'.'", ".", "$", "keyName", ")", "->", "where", "(", "$", "translationTable", ".", "'.'", ".", "$", "localeKey", ",", "$", "this", "->", "locale", "(", ")", ")", ";", "}", ")", "->", "orderBy", "(", "$", "translationTable", ".", "'.'", ".", "$", "key", ",", "$", "sortmethod", ")", "->", "select", "(", "$", "table", ".", "'.*'", ")", "->", "with", "(", "'translations'", ")", ";", "}" ]
This scope sorts results by the given translation field. @param \Illuminate\Database\Eloquent\Builder $query @param string $key @param string $sortmethod @return \Illuminate\Database\Eloquent\Builder|static
[ "This", "scope", "sorts", "results", "by", "the", "given", "translation", "field", "." ]
f1d5569b6c89da1e89dbe48b9bcbb9e54b0afa2c
https://github.com/dimsav/laravel-translatable/blob/f1d5569b6c89da1e89dbe48b9bcbb9e54b0afa2c/src/Translatable/Translatable.php#L711-L727
train
jenssegers/agent
src/Agent.php
Agent.getDetectionRulesExtended
public static function getDetectionRulesExtended() { static $rules; if (!$rules) { $rules = static::mergeRules( static::$desktopDevices, // NEW static::$phoneDevices, static::$tabletDevices, static::$operatingSystems, static::$additionalOperatingSystems, // NEW static::$browsers, static::$additionalBrowsers, // NEW static::$utilities ); } return $rules; }
php
public static function getDetectionRulesExtended() { static $rules; if (!$rules) { $rules = static::mergeRules( static::$desktopDevices, // NEW static::$phoneDevices, static::$tabletDevices, static::$operatingSystems, static::$additionalOperatingSystems, // NEW static::$browsers, static::$additionalBrowsers, // NEW static::$utilities ); } return $rules; }
[ "public", "static", "function", "getDetectionRulesExtended", "(", ")", "{", "static", "$", "rules", ";", "if", "(", "!", "$", "rules", ")", "{", "$", "rules", "=", "static", "::", "mergeRules", "(", "static", "::", "$", "desktopDevices", ",", "// NEW", "static", "::", "$", "phoneDevices", ",", "static", "::", "$", "tabletDevices", ",", "static", "::", "$", "operatingSystems", ",", "static", "::", "$", "additionalOperatingSystems", ",", "// NEW", "static", "::", "$", "browsers", ",", "static", "::", "$", "additionalBrowsers", ",", "// NEW", "static", "::", "$", "utilities", ")", ";", "}", "return", "$", "rules", ";", "}" ]
Get all detection rules. These rules include the additional platforms and browsers and utilities. @return array
[ "Get", "all", "detection", "rules", ".", "These", "rules", "include", "the", "additional", "platforms", "and", "browsers", "and", "utilities", "." ]
bcb895395e460478e101f41cdab139c48dc721ce
https://github.com/jenssegers/agent/blob/bcb895395e460478e101f41cdab139c48dc721ce/src/Agent.php#L86-L104
train
jenssegers/agent
src/Agent.php
Agent.languages
public function languages($acceptLanguage = null) { if ($acceptLanguage === null) { $acceptLanguage = $this->getHttpHeader('HTTP_ACCEPT_LANGUAGE'); } if (!$acceptLanguage) { return []; } $languages = []; // Parse accept language string. foreach (explode(',', $acceptLanguage) as $piece) { $parts = explode(';', $piece); $language = strtolower($parts[0]); $priority = empty($parts[1]) ? 1. : floatval(str_replace('q=', '', $parts[1])); $languages[$language] = $priority; } // Sort languages by priority. arsort($languages); return array_keys($languages); }
php
public function languages($acceptLanguage = null) { if ($acceptLanguage === null) { $acceptLanguage = $this->getHttpHeader('HTTP_ACCEPT_LANGUAGE'); } if (!$acceptLanguage) { return []; } $languages = []; // Parse accept language string. foreach (explode(',', $acceptLanguage) as $piece) { $parts = explode(';', $piece); $language = strtolower($parts[0]); $priority = empty($parts[1]) ? 1. : floatval(str_replace('q=', '', $parts[1])); $languages[$language] = $priority; } // Sort languages by priority. arsort($languages); return array_keys($languages); }
[ "public", "function", "languages", "(", "$", "acceptLanguage", "=", "null", ")", "{", "if", "(", "$", "acceptLanguage", "===", "null", ")", "{", "$", "acceptLanguage", "=", "$", "this", "->", "getHttpHeader", "(", "'HTTP_ACCEPT_LANGUAGE'", ")", ";", "}", "if", "(", "!", "$", "acceptLanguage", ")", "{", "return", "[", "]", ";", "}", "$", "languages", "=", "[", "]", ";", "// Parse accept language string.", "foreach", "(", "explode", "(", "','", ",", "$", "acceptLanguage", ")", "as", "$", "piece", ")", "{", "$", "parts", "=", "explode", "(", "';'", ",", "$", "piece", ")", ";", "$", "language", "=", "strtolower", "(", "$", "parts", "[", "0", "]", ")", ";", "$", "priority", "=", "empty", "(", "$", "parts", "[", "1", "]", ")", "?", "1.", ":", "floatval", "(", "str_replace", "(", "'q='", ",", "''", ",", "$", "parts", "[", "1", "]", ")", ")", ";", "$", "languages", "[", "$", "language", "]", "=", "$", "priority", ";", "}", "// Sort languages by priority.", "arsort", "(", "$", "languages", ")", ";", "return", "array_keys", "(", "$", "languages", ")", ";", "}" ]
Get accept languages. @param string $acceptLanguage @return array
[ "Get", "accept", "languages", "." ]
bcb895395e460478e101f41cdab139c48dc721ce
https://github.com/jenssegers/agent/blob/bcb895395e460478e101f41cdab139c48dc721ce/src/Agent.php#L169-L194
train
jenssegers/agent
src/Agent.php
Agent.findDetectionRulesAgainstUA
protected function findDetectionRulesAgainstUA(array $rules, $userAgent = null) { // Loop given rules foreach ($rules as $key => $regex) { if (empty($regex)) { continue; } // Check match if ($this->match($regex, $userAgent)) { return $key ?: reset($this->matchesArray); } } return false; }
php
protected function findDetectionRulesAgainstUA(array $rules, $userAgent = null) { // Loop given rules foreach ($rules as $key => $regex) { if (empty($regex)) { continue; } // Check match if ($this->match($regex, $userAgent)) { return $key ?: reset($this->matchesArray); } } return false; }
[ "protected", "function", "findDetectionRulesAgainstUA", "(", "array", "$", "rules", ",", "$", "userAgent", "=", "null", ")", "{", "// Loop given rules", "foreach", "(", "$", "rules", "as", "$", "key", "=>", "$", "regex", ")", "{", "if", "(", "empty", "(", "$", "regex", ")", ")", "{", "continue", ";", "}", "// Check match", "if", "(", "$", "this", "->", "match", "(", "$", "regex", ",", "$", "userAgent", ")", ")", "{", "return", "$", "key", "?", ":", "reset", "(", "$", "this", "->", "matchesArray", ")", ";", "}", "}", "return", "false", ";", "}" ]
Match a detection rule and return the matched key. @param array $rules @param string|null $userAgent @return string
[ "Match", "a", "detection", "rule", "and", "return", "the", "matched", "key", "." ]
bcb895395e460478e101f41cdab139c48dc721ce
https://github.com/jenssegers/agent/blob/bcb895395e460478e101f41cdab139c48dc721ce/src/Agent.php#L202-L217
train
jenssegers/agent
src/Agent.php
Agent.isDesktop
public function isDesktop($userAgent = null, $httpHeaders = null) { return !$this->isMobile($userAgent, $httpHeaders) && !$this->isTablet($userAgent, $httpHeaders) && !$this->isRobot($userAgent); }
php
public function isDesktop($userAgent = null, $httpHeaders = null) { return !$this->isMobile($userAgent, $httpHeaders) && !$this->isTablet($userAgent, $httpHeaders) && !$this->isRobot($userAgent); }
[ "public", "function", "isDesktop", "(", "$", "userAgent", "=", "null", ",", "$", "httpHeaders", "=", "null", ")", "{", "return", "!", "$", "this", "->", "isMobile", "(", "$", "userAgent", ",", "$", "httpHeaders", ")", "&&", "!", "$", "this", "->", "isTablet", "(", "$", "userAgent", ",", "$", "httpHeaders", ")", "&&", "!", "$", "this", "->", "isRobot", "(", "$", "userAgent", ")", ";", "}" ]
Check if the device is a desktop computer. @param string|null $userAgent deprecated @param array $httpHeaders deprecated @return bool
[ "Check", "if", "the", "device", "is", "a", "desktop", "computer", "." ]
bcb895395e460478e101f41cdab139c48dc721ce
https://github.com/jenssegers/agent/blob/bcb895395e460478e101f41cdab139c48dc721ce/src/Agent.php#L262-L265
train
jenssegers/agent
src/Agent.php
Agent.isPhone
public function isPhone($userAgent = null, $httpHeaders = null) { return $this->isMobile($userAgent, $httpHeaders) && !$this->isTablet($userAgent, $httpHeaders); }
php
public function isPhone($userAgent = null, $httpHeaders = null) { return $this->isMobile($userAgent, $httpHeaders) && !$this->isTablet($userAgent, $httpHeaders); }
[ "public", "function", "isPhone", "(", "$", "userAgent", "=", "null", ",", "$", "httpHeaders", "=", "null", ")", "{", "return", "$", "this", "->", "isMobile", "(", "$", "userAgent", ",", "$", "httpHeaders", ")", "&&", "!", "$", "this", "->", "isTablet", "(", "$", "userAgent", ",", "$", "httpHeaders", ")", ";", "}" ]
Check if the device is a mobile phone. @param string|null $userAgent deprecated @param array $httpHeaders deprecated @return bool
[ "Check", "if", "the", "device", "is", "a", "mobile", "phone", "." ]
bcb895395e460478e101f41cdab139c48dc721ce
https://github.com/jenssegers/agent/blob/bcb895395e460478e101f41cdab139c48dc721ce/src/Agent.php#L273-L276
train
silverstripe/silverstripe-framework
src/Forms/DefaultFormFactory.php
DefaultFormFactory.getFormFields
protected function getFormFields(RequestHandler $controller = null, $name, $context = []) { // Fall back to standard "getCMSFields" which itself uses the FormScaffolder as a fallback // @todo Deprecate or formalise support for getCMSFields() $fields = $context['Record']->getCMSFields(); $this->invokeWithExtensions('updateFormFields', $fields, $controller, $name, $context); return $fields; }
php
protected function getFormFields(RequestHandler $controller = null, $name, $context = []) { // Fall back to standard "getCMSFields" which itself uses the FormScaffolder as a fallback // @todo Deprecate or formalise support for getCMSFields() $fields = $context['Record']->getCMSFields(); $this->invokeWithExtensions('updateFormFields', $fields, $controller, $name, $context); return $fields; }
[ "protected", "function", "getFormFields", "(", "RequestHandler", "$", "controller", "=", "null", ",", "$", "name", ",", "$", "context", "=", "[", "]", ")", "{", "// Fall back to standard \"getCMSFields\" which itself uses the FormScaffolder as a fallback", "// @todo Deprecate or formalise support for getCMSFields()", "$", "fields", "=", "$", "context", "[", "'Record'", "]", "->", "getCMSFields", "(", ")", ";", "$", "this", "->", "invokeWithExtensions", "(", "'updateFormFields'", ",", "$", "fields", ",", "$", "controller", ",", "$", "name", ",", "$", "context", ")", ";", "return", "$", "fields", ";", "}" ]
Build field list for this form @param RequestHandler $controller @param string $name @param array $context @return FieldList
[ "Build", "field", "list", "for", "this", "form" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/DefaultFormFactory.php#L66-L73
train
silverstripe/silverstripe-framework
src/Forms/DefaultFormFactory.php
DefaultFormFactory.getFormActions
protected function getFormActions(RequestHandler $controller = null, $name, $context = []) { // @todo Deprecate or formalise support for getCMSActions() $actions = $context['Record']->getCMSActions(); $this->invokeWithExtensions('updateFormActions', $actions, $controller, $name, $context); return $actions; }
php
protected function getFormActions(RequestHandler $controller = null, $name, $context = []) { // @todo Deprecate or formalise support for getCMSActions() $actions = $context['Record']->getCMSActions(); $this->invokeWithExtensions('updateFormActions', $actions, $controller, $name, $context); return $actions; }
[ "protected", "function", "getFormActions", "(", "RequestHandler", "$", "controller", "=", "null", ",", "$", "name", ",", "$", "context", "=", "[", "]", ")", "{", "// @todo Deprecate or formalise support for getCMSActions()", "$", "actions", "=", "$", "context", "[", "'Record'", "]", "->", "getCMSActions", "(", ")", ";", "$", "this", "->", "invokeWithExtensions", "(", "'updateFormActions'", ",", "$", "actions", ",", "$", "controller", ",", "$", "name", ",", "$", "context", ")", ";", "return", "$", "actions", ";", "}" ]
Build list of actions for this form @param RequestHandler $controller @param string $name @param array $context @return FieldList
[ "Build", "list", "of", "actions", "for", "this", "form" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/DefaultFormFactory.php#L83-L89
train
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
RememberLoginHash.getNewHash
public function getNewHash(Member $member) { $generator = new RandomGenerator(); $this->setToken($generator->randomToken('sha1')); return $member->encryptWithUserSettings($this->token); }
php
public function getNewHash(Member $member) { $generator = new RandomGenerator(); $this->setToken($generator->randomToken('sha1')); return $member->encryptWithUserSettings($this->token); }
[ "public", "function", "getNewHash", "(", "Member", "$", "member", ")", "{", "$", "generator", "=", "new", "RandomGenerator", "(", ")", ";", "$", "this", "->", "setToken", "(", "$", "generator", "->", "randomToken", "(", "'sha1'", ")", ")", ";", "return", "$", "member", "->", "encryptWithUserSettings", "(", "$", "this", "->", "token", ")", ";", "}" ]
Creates a new random token and hashes it using the member information @param Member $member The logged in user @return string The hash to be stored in the database
[ "Creates", "a", "new", "random", "token", "and", "hashes", "it", "using", "the", "member", "information" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/RememberLoginHash.php#L113-L118
train
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
RememberLoginHash.generate
public static function generate(Member $member) { if (!$member->exists()) { return null; } if (static::config()->force_single_token) { RememberLoginHash::get()->filter('MemberID', $member->ID)->removeAll(); } /** @var RememberLoginHash $rememberLoginHash */ $rememberLoginHash = RememberLoginHash::create(); do { $deviceID = $rememberLoginHash->getNewDeviceID(); } while (RememberLoginHash::get()->filter('DeviceID', $deviceID)->count()); $rememberLoginHash->DeviceID = $deviceID; $rememberLoginHash->Hash = $rememberLoginHash->getNewHash($member); $rememberLoginHash->MemberID = $member->ID; $now = DBDatetime::now(); $expiryDate = new DateTime($now->Rfc2822()); $tokenExpiryDays = static::config()->token_expiry_days; $expiryDate->add(new DateInterval('P' . $tokenExpiryDays . 'D')); $rememberLoginHash->ExpiryDate = $expiryDate->format('Y-m-d H:i:s'); $rememberLoginHash->extend('onAfterGenerateToken'); $rememberLoginHash->write(); return $rememberLoginHash; }
php
public static function generate(Member $member) { if (!$member->exists()) { return null; } if (static::config()->force_single_token) { RememberLoginHash::get()->filter('MemberID', $member->ID)->removeAll(); } /** @var RememberLoginHash $rememberLoginHash */ $rememberLoginHash = RememberLoginHash::create(); do { $deviceID = $rememberLoginHash->getNewDeviceID(); } while (RememberLoginHash::get()->filter('DeviceID', $deviceID)->count()); $rememberLoginHash->DeviceID = $deviceID; $rememberLoginHash->Hash = $rememberLoginHash->getNewHash($member); $rememberLoginHash->MemberID = $member->ID; $now = DBDatetime::now(); $expiryDate = new DateTime($now->Rfc2822()); $tokenExpiryDays = static::config()->token_expiry_days; $expiryDate->add(new DateInterval('P' . $tokenExpiryDays . 'D')); $rememberLoginHash->ExpiryDate = $expiryDate->format('Y-m-d H:i:s'); $rememberLoginHash->extend('onAfterGenerateToken'); $rememberLoginHash->write(); return $rememberLoginHash; }
[ "public", "static", "function", "generate", "(", "Member", "$", "member", ")", "{", "if", "(", "!", "$", "member", "->", "exists", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "static", "::", "config", "(", ")", "->", "force_single_token", ")", "{", "RememberLoginHash", "::", "get", "(", ")", "->", "filter", "(", "'MemberID'", ",", "$", "member", "->", "ID", ")", "->", "removeAll", "(", ")", ";", "}", "/** @var RememberLoginHash $rememberLoginHash */", "$", "rememberLoginHash", "=", "RememberLoginHash", "::", "create", "(", ")", ";", "do", "{", "$", "deviceID", "=", "$", "rememberLoginHash", "->", "getNewDeviceID", "(", ")", ";", "}", "while", "(", "RememberLoginHash", "::", "get", "(", ")", "->", "filter", "(", "'DeviceID'", ",", "$", "deviceID", ")", "->", "count", "(", ")", ")", ";", "$", "rememberLoginHash", "->", "DeviceID", "=", "$", "deviceID", ";", "$", "rememberLoginHash", "->", "Hash", "=", "$", "rememberLoginHash", "->", "getNewHash", "(", "$", "member", ")", ";", "$", "rememberLoginHash", "->", "MemberID", "=", "$", "member", "->", "ID", ";", "$", "now", "=", "DBDatetime", "::", "now", "(", ")", ";", "$", "expiryDate", "=", "new", "DateTime", "(", "$", "now", "->", "Rfc2822", "(", ")", ")", ";", "$", "tokenExpiryDays", "=", "static", "::", "config", "(", ")", "->", "token_expiry_days", ";", "$", "expiryDate", "->", "add", "(", "new", "DateInterval", "(", "'P'", ".", "$", "tokenExpiryDays", ".", "'D'", ")", ")", ";", "$", "rememberLoginHash", "->", "ExpiryDate", "=", "$", "expiryDate", "->", "format", "(", "'Y-m-d H:i:s'", ")", ";", "$", "rememberLoginHash", "->", "extend", "(", "'onAfterGenerateToken'", ")", ";", "$", "rememberLoginHash", "->", "write", "(", ")", ";", "return", "$", "rememberLoginHash", ";", "}" ]
Generates a new login hash associated with a device The device is assigned a globally unique device ID The returned login hash stores the hashed token in the database, for this device and this member @param Member $member The logged in user @return RememberLoginHash The generated login hash
[ "Generates", "a", "new", "login", "hash", "associated", "with", "a", "device", "The", "device", "is", "assigned", "a", "globally", "unique", "device", "ID", "The", "returned", "login", "hash", "stores", "the", "hashed", "token", "in", "the", "database", "for", "this", "device", "and", "this", "member" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/RememberLoginHash.php#L128-L153
train
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
RememberLoginHash.renew
public function renew() { $hash = $this->getNewHash($this->Member()); $this->Hash = $hash; $this->extend('onAfterRenewToken'); $this->write(); return $this; }
php
public function renew() { $hash = $this->getNewHash($this->Member()); $this->Hash = $hash; $this->extend('onAfterRenewToken'); $this->write(); return $this; }
[ "public", "function", "renew", "(", ")", "{", "$", "hash", "=", "$", "this", "->", "getNewHash", "(", "$", "this", "->", "Member", "(", ")", ")", ";", "$", "this", "->", "Hash", "=", "$", "hash", ";", "$", "this", "->", "extend", "(", "'onAfterRenewToken'", ")", ";", "$", "this", "->", "write", "(", ")", ";", "return", "$", "this", ";", "}" ]
Generates a new hash for this member but keeps the device ID intact @return RememberLoginHash
[ "Generates", "a", "new", "hash", "for", "this", "member", "but", "keeps", "the", "device", "ID", "intact" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/RememberLoginHash.php#L160-L167
train
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
RememberLoginHash.clear
public static function clear(Member $member, $alcDevice = null) { if (!$member->exists()) { return; } $filter = array('MemberID'=>$member->ID); if (!static::config()->logout_across_devices && $alcDevice) { $filter['DeviceID'] = $alcDevice; } RememberLoginHash::get() ->filter($filter) ->removeAll(); }
php
public static function clear(Member $member, $alcDevice = null) { if (!$member->exists()) { return; } $filter = array('MemberID'=>$member->ID); if (!static::config()->logout_across_devices && $alcDevice) { $filter['DeviceID'] = $alcDevice; } RememberLoginHash::get() ->filter($filter) ->removeAll(); }
[ "public", "static", "function", "clear", "(", "Member", "$", "member", ",", "$", "alcDevice", "=", "null", ")", "{", "if", "(", "!", "$", "member", "->", "exists", "(", ")", ")", "{", "return", ";", "}", "$", "filter", "=", "array", "(", "'MemberID'", "=>", "$", "member", "->", "ID", ")", ";", "if", "(", "!", "static", "::", "config", "(", ")", "->", "logout_across_devices", "&&", "$", "alcDevice", ")", "{", "$", "filter", "[", "'DeviceID'", "]", "=", "$", "alcDevice", ";", "}", "RememberLoginHash", "::", "get", "(", ")", "->", "filter", "(", "$", "filter", ")", "->", "removeAll", "(", ")", ";", "}" ]
Deletes existing tokens for this member if logout_across_devices is true, all tokens are deleted, otherwise only the token for the provided device ID will be removed @param Member $member @param string $alcDevice
[ "Deletes", "existing", "tokens", "for", "this", "member", "if", "logout_across_devices", "is", "true", "all", "tokens", "are", "deleted", "otherwise", "only", "the", "token", "for", "the", "provided", "device", "ID", "will", "be", "removed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/RememberLoginHash.php#L177-L189
train
silverstripe/silverstripe-framework
src/Control/ContentNegotiator.php
ContentNegotiator.enabled_for
public static function enabled_for($response) { $contentType = $response->getHeader("Content-Type"); // Disable content negotiation for other content types if ($contentType && substr($contentType, 0, 9) != 'text/html' && substr($contentType, 0, 21) != 'application/xhtml+xml' ) { return false; } if (ContentNegotiator::getEnabled()) { return true; } else { return (substr($response->getBody(), 0, 5) == '<' . '?xml'); } }
php
public static function enabled_for($response) { $contentType = $response->getHeader("Content-Type"); // Disable content negotiation for other content types if ($contentType && substr($contentType, 0, 9) != 'text/html' && substr($contentType, 0, 21) != 'application/xhtml+xml' ) { return false; } if (ContentNegotiator::getEnabled()) { return true; } else { return (substr($response->getBody(), 0, 5) == '<' . '?xml'); } }
[ "public", "static", "function", "enabled_for", "(", "$", "response", ")", "{", "$", "contentType", "=", "$", "response", "->", "getHeader", "(", "\"Content-Type\"", ")", ";", "// Disable content negotiation for other content types", "if", "(", "$", "contentType", "&&", "substr", "(", "$", "contentType", ",", "0", ",", "9", ")", "!=", "'text/html'", "&&", "substr", "(", "$", "contentType", ",", "0", ",", "21", ")", "!=", "'application/xhtml+xml'", ")", "{", "return", "false", ";", "}", "if", "(", "ContentNegotiator", "::", "getEnabled", "(", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "(", "substr", "(", "$", "response", "->", "getBody", "(", ")", ",", "0", ",", "5", ")", "==", "'<'", ".", "'?xml'", ")", ";", "}", "}" ]
Returns true if negotiation is enabled for the given response. By default, negotiation is only enabled for pages that have the xml header. @param HTTPResponse $response @return bool
[ "Returns", "true", "if", "negotiation", "is", "enabled", "for", "the", "given", "response", ".", "By", "default", "negotiation", "is", "only", "enabled", "for", "pages", "that", "have", "the", "xml", "header", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/ContentNegotiator.php#L76-L93
train
silverstripe/silverstripe-framework
src/Dev/CsvBulkLoader.php
CsvBulkLoader.splitFile
protected function splitFile($path, $lines = null) { Deprecation::notice('5.0', 'splitFile is deprecated, please process files using a stream'); $previous = ini_get('auto_detect_line_endings'); ini_set('auto_detect_line_endings', true); if (!is_int($lines)) { $lines = $this->config()->get("lines"); } $new = $this->getNewSplitFileName(); $to = fopen($new, 'w+'); $from = fopen($path, 'r'); $header = null; if ($this->hasHeaderRow) { $header = fgets($from); fwrite($to, $header); } $files = array(); $files[] = $new; $count = 0; while (!feof($from)) { fwrite($to, fgets($from)); $count++; if ($count >= $lines) { fclose($to); // get a new temporary file name, to write the next lines to $new = $this->getNewSplitFileName(); $to = fopen($new, 'w+'); if ($this->hasHeaderRow) { // add the headers to the new file fwrite($to, $header); } $files[] = $new; $count = 0; } } fclose($to); ini_set('auto_detect_line_endings', $previous); return $files; }
php
protected function splitFile($path, $lines = null) { Deprecation::notice('5.0', 'splitFile is deprecated, please process files using a stream'); $previous = ini_get('auto_detect_line_endings'); ini_set('auto_detect_line_endings', true); if (!is_int($lines)) { $lines = $this->config()->get("lines"); } $new = $this->getNewSplitFileName(); $to = fopen($new, 'w+'); $from = fopen($path, 'r'); $header = null; if ($this->hasHeaderRow) { $header = fgets($from); fwrite($to, $header); } $files = array(); $files[] = $new; $count = 0; while (!feof($from)) { fwrite($to, fgets($from)); $count++; if ($count >= $lines) { fclose($to); // get a new temporary file name, to write the next lines to $new = $this->getNewSplitFileName(); $to = fopen($new, 'w+'); if ($this->hasHeaderRow) { // add the headers to the new file fwrite($to, $header); } $files[] = $new; $count = 0; } } fclose($to); ini_set('auto_detect_line_endings', $previous); return $files; }
[ "protected", "function", "splitFile", "(", "$", "path", ",", "$", "lines", "=", "null", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'splitFile is deprecated, please process files using a stream'", ")", ";", "$", "previous", "=", "ini_get", "(", "'auto_detect_line_endings'", ")", ";", "ini_set", "(", "'auto_detect_line_endings'", ",", "true", ")", ";", "if", "(", "!", "is_int", "(", "$", "lines", ")", ")", "{", "$", "lines", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "\"lines\"", ")", ";", "}", "$", "new", "=", "$", "this", "->", "getNewSplitFileName", "(", ")", ";", "$", "to", "=", "fopen", "(", "$", "new", ",", "'w+'", ")", ";", "$", "from", "=", "fopen", "(", "$", "path", ",", "'r'", ")", ";", "$", "header", "=", "null", ";", "if", "(", "$", "this", "->", "hasHeaderRow", ")", "{", "$", "header", "=", "fgets", "(", "$", "from", ")", ";", "fwrite", "(", "$", "to", ",", "$", "header", ")", ";", "}", "$", "files", "=", "array", "(", ")", ";", "$", "files", "[", "]", "=", "$", "new", ";", "$", "count", "=", "0", ";", "while", "(", "!", "feof", "(", "$", "from", ")", ")", "{", "fwrite", "(", "$", "to", ",", "fgets", "(", "$", "from", ")", ")", ";", "$", "count", "++", ";", "if", "(", "$", "count", ">=", "$", "lines", ")", "{", "fclose", "(", "$", "to", ")", ";", "// get a new temporary file name, to write the next lines to", "$", "new", "=", "$", "this", "->", "getNewSplitFileName", "(", ")", ";", "$", "to", "=", "fopen", "(", "$", "new", ",", "'w+'", ")", ";", "if", "(", "$", "this", "->", "hasHeaderRow", ")", "{", "// add the headers to the new file", "fwrite", "(", "$", "to", ",", "$", "header", ")", ";", "}", "$", "files", "[", "]", "=", "$", "new", ";", "$", "count", "=", "0", ";", "}", "}", "fclose", "(", "$", "to", ")", ";", "ini_set", "(", "'auto_detect_line_endings'", ",", "$", "previous", ")", ";", "return", "$", "files", ";", "}" ]
Splits a large file up into many smaller files. @param string $path Path to large file to split @param int $lines Number of lines per file @return array List of file paths
[ "Splits", "a", "large", "file", "up", "into", "many", "smaller", "files", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CsvBulkLoader.php#L157-L214
train
silverstripe/silverstripe-framework
src/Forms/Schema/FormSchema.php
FormSchema.getSchema
public function getSchema(Form $form) { $schema = [ 'name' => $form->getName(), 'id' => $form->FormName(), 'action' => $form->FormAction(), 'method' => $form->FormMethod(), 'attributes' => $form->getAttributes(), 'data' => [], 'fields' => [], 'actions' => [] ]; /** @var FormField $action */ foreach ($form->Actions() as $action) { $schema['actions'][] = $action->getSchemaData(); } /** @var FormField $field */ foreach ($form->Fields() as $field) { $schema['fields'][] = $field->getSchemaData(); } return $schema; }
php
public function getSchema(Form $form) { $schema = [ 'name' => $form->getName(), 'id' => $form->FormName(), 'action' => $form->FormAction(), 'method' => $form->FormMethod(), 'attributes' => $form->getAttributes(), 'data' => [], 'fields' => [], 'actions' => [] ]; /** @var FormField $action */ foreach ($form->Actions() as $action) { $schema['actions'][] = $action->getSchemaData(); } /** @var FormField $field */ foreach ($form->Fields() as $field) { $schema['fields'][] = $field->getSchemaData(); } return $schema; }
[ "public", "function", "getSchema", "(", "Form", "$", "form", ")", "{", "$", "schema", "=", "[", "'name'", "=>", "$", "form", "->", "getName", "(", ")", ",", "'id'", "=>", "$", "form", "->", "FormName", "(", ")", ",", "'action'", "=>", "$", "form", "->", "FormAction", "(", ")", ",", "'method'", "=>", "$", "form", "->", "FormMethod", "(", ")", ",", "'attributes'", "=>", "$", "form", "->", "getAttributes", "(", ")", ",", "'data'", "=>", "[", "]", ",", "'fields'", "=>", "[", "]", ",", "'actions'", "=>", "[", "]", "]", ";", "/** @var FormField $action */", "foreach", "(", "$", "form", "->", "Actions", "(", ")", "as", "$", "action", ")", "{", "$", "schema", "[", "'actions'", "]", "[", "]", "=", "$", "action", "->", "getSchemaData", "(", ")", ";", "}", "/** @var FormField $field */", "foreach", "(", "$", "form", "->", "Fields", "(", ")", "as", "$", "field", ")", "{", "$", "schema", "[", "'fields'", "]", "[", "]", "=", "$", "field", "->", "getSchemaData", "(", ")", ";", "}", "return", "$", "schema", ";", "}" ]
Gets the schema for this form as a nested array. @param Form $form @return array
[ "Gets", "the", "schema", "for", "this", "form", "as", "a", "nested", "array", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Schema/FormSchema.php#L92-L116
train
silverstripe/silverstripe-framework
src/Forms/Schema/FormSchema.php
FormSchema.getState
public function getState(Form $form) { $state = [ 'id' => $form->FormName(), 'fields' => [], 'messages' => [], 'notifyUnsavedChanges' => $form->getNotifyUnsavedChanges(), ]; // flattened nested fields are returned, rather than only top level fields. $state['fields'] = array_merge( $this->getFieldStates($form->Fields()), $this->getFieldStates($form->Actions()) ); if ($message = $form->getSchemaMessage()) { $state['messages'][] = $message; } return $state; }
php
public function getState(Form $form) { $state = [ 'id' => $form->FormName(), 'fields' => [], 'messages' => [], 'notifyUnsavedChanges' => $form->getNotifyUnsavedChanges(), ]; // flattened nested fields are returned, rather than only top level fields. $state['fields'] = array_merge( $this->getFieldStates($form->Fields()), $this->getFieldStates($form->Actions()) ); if ($message = $form->getSchemaMessage()) { $state['messages'][] = $message; } return $state; }
[ "public", "function", "getState", "(", "Form", "$", "form", ")", "{", "$", "state", "=", "[", "'id'", "=>", "$", "form", "->", "FormName", "(", ")", ",", "'fields'", "=>", "[", "]", ",", "'messages'", "=>", "[", "]", ",", "'notifyUnsavedChanges'", "=>", "$", "form", "->", "getNotifyUnsavedChanges", "(", ")", ",", "]", ";", "// flattened nested fields are returned, rather than only top level fields.", "$", "state", "[", "'fields'", "]", "=", "array_merge", "(", "$", "this", "->", "getFieldStates", "(", "$", "form", "->", "Fields", "(", ")", ")", ",", "$", "this", "->", "getFieldStates", "(", "$", "form", "->", "Actions", "(", ")", ")", ")", ";", "if", "(", "$", "message", "=", "$", "form", "->", "getSchemaMessage", "(", ")", ")", "{", "$", "state", "[", "'messages'", "]", "[", "]", "=", "$", "message", ";", "}", "return", "$", "state", ";", "}" ]
Gets the current state of this form as a nested array. @param Form $form @return array
[ "Gets", "the", "current", "state", "of", "this", "form", "as", "a", "nested", "array", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Schema/FormSchema.php#L124-L144
train
silverstripe/silverstripe-framework
src/Forms/Schema/FormSchema.php
FormSchema.getSchemaForMessage
protected function getSchemaForMessage($message) { // Form schema messages treat simple strings as plain text, so nest for html messages $value = $message['message']; if ($message['messageCast'] === ValidationResult::CAST_HTML) { $value = ['html' => $message]; } return [ 'value' => $value, 'type' => $message['messageType'], 'field' => empty($message['fieldName']) ? null : $message['fieldName'], ]; }
php
protected function getSchemaForMessage($message) { // Form schema messages treat simple strings as plain text, so nest for html messages $value = $message['message']; if ($message['messageCast'] === ValidationResult::CAST_HTML) { $value = ['html' => $message]; } return [ 'value' => $value, 'type' => $message['messageType'], 'field' => empty($message['fieldName']) ? null : $message['fieldName'], ]; }
[ "protected", "function", "getSchemaForMessage", "(", "$", "message", ")", "{", "// Form schema messages treat simple strings as plain text, so nest for html messages", "$", "value", "=", "$", "message", "[", "'message'", "]", ";", "if", "(", "$", "message", "[", "'messageCast'", "]", "===", "ValidationResult", "::", "CAST_HTML", ")", "{", "$", "value", "=", "[", "'html'", "=>", "$", "message", "]", ";", "}", "return", "[", "'value'", "=>", "$", "value", ",", "'type'", "=>", "$", "message", "[", "'messageType'", "]", ",", "'field'", "=>", "empty", "(", "$", "message", "[", "'fieldName'", "]", ")", "?", "null", ":", "$", "message", "[", "'fieldName'", "]", ",", "]", ";", "}" ]
Return form schema for encoded validation message @param array $message Internal ValidationResult format for this message @return array Form schema format for this message
[ "Return", "form", "schema", "for", "encoded", "validation", "message" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Schema/FormSchema.php#L165-L177
train
silverstripe/silverstripe-framework
src/Control/PjaxResponseNegotiator.php
PjaxResponseNegotiator.respond
public function respond(HTTPRequest $request, $extraCallbacks = array()) { // Prepare the default options and combine with the others $callbacks = array_merge($this->callbacks, $extraCallbacks); $response = $this->getResponse(); $responseParts = array(); if (isset($this->fragmentOverride)) { $fragments = $this->fragmentOverride; } elseif ($fragmentStr = $request->getHeader('X-Pjax')) { $fragments = explode(',', $fragmentStr); } else { if ($request->isAjax()) { throw new HTTPResponse_Exception("Ajax requests to this URL require an X-Pjax header.", 400); } elseif (empty($callbacks['default'])) { throw new HTTPResponse_Exception("Missing default response handler for this URL", 400); } $response->setBody(call_user_func($callbacks['default'])); return $response; } // Execute the fragment callbacks and build the response. foreach ($fragments as $fragment) { if (isset($callbacks[$fragment])) { $res = call_user_func($callbacks[$fragment]); $responseParts[$fragment] = $res ? (string) $res : $res; } else { throw new HTTPResponse_Exception("X-Pjax = '$fragment' not supported for this URL.", 400); } } $response->setBody(json_encode($responseParts)); $response->addHeader('Content-Type', 'application/json'); return $response; }
php
public function respond(HTTPRequest $request, $extraCallbacks = array()) { // Prepare the default options and combine with the others $callbacks = array_merge($this->callbacks, $extraCallbacks); $response = $this->getResponse(); $responseParts = array(); if (isset($this->fragmentOverride)) { $fragments = $this->fragmentOverride; } elseif ($fragmentStr = $request->getHeader('X-Pjax')) { $fragments = explode(',', $fragmentStr); } else { if ($request->isAjax()) { throw new HTTPResponse_Exception("Ajax requests to this URL require an X-Pjax header.", 400); } elseif (empty($callbacks['default'])) { throw new HTTPResponse_Exception("Missing default response handler for this URL", 400); } $response->setBody(call_user_func($callbacks['default'])); return $response; } // Execute the fragment callbacks and build the response. foreach ($fragments as $fragment) { if (isset($callbacks[$fragment])) { $res = call_user_func($callbacks[$fragment]); $responseParts[$fragment] = $res ? (string) $res : $res; } else { throw new HTTPResponse_Exception("X-Pjax = '$fragment' not supported for this URL.", 400); } } $response->setBody(json_encode($responseParts)); $response->addHeader('Content-Type', 'application/json'); return $response; }
[ "public", "function", "respond", "(", "HTTPRequest", "$", "request", ",", "$", "extraCallbacks", "=", "array", "(", ")", ")", "{", "// Prepare the default options and combine with the others", "$", "callbacks", "=", "array_merge", "(", "$", "this", "->", "callbacks", ",", "$", "extraCallbacks", ")", ";", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "$", "responseParts", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "fragmentOverride", ")", ")", "{", "$", "fragments", "=", "$", "this", "->", "fragmentOverride", ";", "}", "elseif", "(", "$", "fragmentStr", "=", "$", "request", "->", "getHeader", "(", "'X-Pjax'", ")", ")", "{", "$", "fragments", "=", "explode", "(", "','", ",", "$", "fragmentStr", ")", ";", "}", "else", "{", "if", "(", "$", "request", "->", "isAjax", "(", ")", ")", "{", "throw", "new", "HTTPResponse_Exception", "(", "\"Ajax requests to this URL require an X-Pjax header.\"", ",", "400", ")", ";", "}", "elseif", "(", "empty", "(", "$", "callbacks", "[", "'default'", "]", ")", ")", "{", "throw", "new", "HTTPResponse_Exception", "(", "\"Missing default response handler for this URL\"", ",", "400", ")", ";", "}", "$", "response", "->", "setBody", "(", "call_user_func", "(", "$", "callbacks", "[", "'default'", "]", ")", ")", ";", "return", "$", "response", ";", "}", "// Execute the fragment callbacks and build the response.", "foreach", "(", "$", "fragments", "as", "$", "fragment", ")", "{", "if", "(", "isset", "(", "$", "callbacks", "[", "$", "fragment", "]", ")", ")", "{", "$", "res", "=", "call_user_func", "(", "$", "callbacks", "[", "$", "fragment", "]", ")", ";", "$", "responseParts", "[", "$", "fragment", "]", "=", "$", "res", "?", "(", "string", ")", "$", "res", ":", "$", "res", ";", "}", "else", "{", "throw", "new", "HTTPResponse_Exception", "(", "\"X-Pjax = '$fragment' not supported for this URL.\"", ",", "400", ")", ";", "}", "}", "$", "response", "->", "setBody", "(", "json_encode", "(", "$", "responseParts", ")", ")", ";", "$", "response", "->", "addHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "return", "$", "response", ";", "}" ]
Out of the box, the handler "CurrentForm" value, which will return the rendered form. Non-Ajax calls will redirect back. @param HTTPRequest $request @param array $extraCallbacks List of anonymous functions or callables returning either a string or HTTPResponse, keyed by their fragment identifier. The 'default' key can be used as a fallback for non-ajax responses. @return HTTPResponse @throws HTTPResponse_Exception
[ "Out", "of", "the", "box", "the", "handler", "CurrentForm", "value", "which", "will", "return", "the", "rendered", "form", ".", "Non", "-", "Ajax", "calls", "will", "redirect", "back", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/PjaxResponseNegotiator.php#L74-L109
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldExportButton.php
GridFieldExportButton.getExportColumnsForGridField
protected function getExportColumnsForGridField(GridField $gridField) { if ($this->exportColumns) { return $this->exportColumns; } /** @var GridFieldDataColumns $dataCols */ $dataCols = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class); if ($dataCols) { return $dataCols->getDisplayFields($gridField); } return DataObject::singleton($gridField->getModelClass())->summaryFields(); }
php
protected function getExportColumnsForGridField(GridField $gridField) { if ($this->exportColumns) { return $this->exportColumns; } /** @var GridFieldDataColumns $dataCols */ $dataCols = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class); if ($dataCols) { return $dataCols->getDisplayFields($gridField); } return DataObject::singleton($gridField->getModelClass())->summaryFields(); }
[ "protected", "function", "getExportColumnsForGridField", "(", "GridField", "$", "gridField", ")", "{", "if", "(", "$", "this", "->", "exportColumns", ")", "{", "return", "$", "this", "->", "exportColumns", ";", "}", "/** @var GridFieldDataColumns $dataCols */", "$", "dataCols", "=", "$", "gridField", "->", "getConfig", "(", ")", "->", "getComponentByType", "(", "GridFieldDataColumns", "::", "class", ")", ";", "if", "(", "$", "dataCols", ")", "{", "return", "$", "dataCols", "->", "getDisplayFields", "(", "$", "gridField", ")", ";", "}", "return", "DataObject", "::", "singleton", "(", "$", "gridField", "->", "getModelClass", "(", ")", ")", "->", "summaryFields", "(", ")", ";", "}" ]
Return the columns to export @param GridField $gridField @return array
[ "Return", "the", "columns", "to", "export" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldExportButton.php#L144-L157
train
silverstripe/silverstripe-framework
src/Forms/ListboxField.php
ListboxField.Field
public function Field($properties = array()) { $properties = array_merge($properties, array( 'Options' => $this->getOptions(), )); return FormField::Field($properties); }
php
public function Field($properties = array()) { $properties = array_merge($properties, array( 'Options' => $this->getOptions(), )); return FormField::Field($properties); }
[ "public", "function", "Field", "(", "$", "properties", "=", "array", "(", ")", ")", "{", "$", "properties", "=", "array_merge", "(", "$", "properties", ",", "array", "(", "'Options'", "=>", "$", "this", "->", "getOptions", "(", ")", ",", ")", ")", ";", "return", "FormField", "::", "Field", "(", "$", "properties", ")", ";", "}" ]
Returns a select tag containing all the appropriate option tags @param array $properties @return string
[ "Returns", "a", "select", "tag", "containing", "all", "the", "appropriate", "option", "tags" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/ListboxField.php#L70-L77
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
CookieAuthenticationHandler.clearCookies
protected function clearCookies() { $secure = $this->getTokenCookieSecure(); Cookie::set($this->getTokenCookieName(), null, null, null, null, $secure); Cookie::set($this->getDeviceCookieName(), null, null, null, null, $secure); Cookie::force_expiry($this->getTokenCookieName(), null, null, null, null, $secure); Cookie::force_expiry($this->getDeviceCookieName(), null, null, null, null, $secure); }
php
protected function clearCookies() { $secure = $this->getTokenCookieSecure(); Cookie::set($this->getTokenCookieName(), null, null, null, null, $secure); Cookie::set($this->getDeviceCookieName(), null, null, null, null, $secure); Cookie::force_expiry($this->getTokenCookieName(), null, null, null, null, $secure); Cookie::force_expiry($this->getDeviceCookieName(), null, null, null, null, $secure); }
[ "protected", "function", "clearCookies", "(", ")", "{", "$", "secure", "=", "$", "this", "->", "getTokenCookieSecure", "(", ")", ";", "Cookie", "::", "set", "(", "$", "this", "->", "getTokenCookieName", "(", ")", ",", "null", ",", "null", ",", "null", ",", "null", ",", "$", "secure", ")", ";", "Cookie", "::", "set", "(", "$", "this", "->", "getDeviceCookieName", "(", ")", ",", "null", ",", "null", ",", "null", ",", "null", ",", "$", "secure", ")", ";", "Cookie", "::", "force_expiry", "(", "$", "this", "->", "getTokenCookieName", "(", ")", ",", "null", ",", "null", ",", "null", ",", "null", ",", "$", "secure", ")", ";", "Cookie", "::", "force_expiry", "(", "$", "this", "->", "getDeviceCookieName", "(", ")", ",", "null", ",", "null", ",", "null", ",", "null", ",", "$", "secure", ")", ";", "}" ]
Clear the cookies set for the user
[ "Clear", "the", "cookies", "set", "for", "the", "user" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php#L265-L272
train