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
irfantoor/database
src/Database/Model.php
Model.getSchema
function getSchema() { # Database structure $schema = 'CREATE TABLE IF NOT EXISTS ' . $this->table . ' ('; $sep = PHP_EOL; foreach($this->schema as $fld) { $schema .= $sep . $fld; $sep = ', ' . PHP_EOL; } $schema .= PHP_EOL . ');' . PHP_EOL; # Indecies foreach($this->indecies as $index) { foreach($index as $type=>$field) { $type = strtolower($type); switch ($type) { case 'u': case 'unique': $schema .= 'CREATE UNIQUE INDEX '; break; case 'i': case 'index': default: $schema .= 'CREATE INDEX '; } $schema .= "{$this->table}_{$field}_{$type}" . ' ON ' . $this->table . '(' . $field . ');' . PHP_EOL; } } return $schema; }
php
function getSchema() { # Database structure $schema = 'CREATE TABLE IF NOT EXISTS ' . $this->table . ' ('; $sep = PHP_EOL; foreach($this->schema as $fld) { $schema .= $sep . $fld; $sep = ', ' . PHP_EOL; } $schema .= PHP_EOL . ');' . PHP_EOL; # Indecies foreach($this->indecies as $index) { foreach($index as $type=>$field) { $type = strtolower($type); switch ($type) { case 'u': case 'unique': $schema .= 'CREATE UNIQUE INDEX '; break; case 'i': case 'index': default: $schema .= 'CREATE INDEX '; } $schema .= "{$this->table}_{$field}_{$type}" . ' ON ' . $this->table . '(' . $field . ');' . PHP_EOL; } } return $schema; }
[ "function", "getSchema", "(", ")", "{", "# Database structure", "$", "schema", "=", "'CREATE TABLE IF NOT EXISTS '", ".", "$", "this", "->", "table", ".", "' ('", ";", "$", "sep", "=", "PHP_EOL", ";", "foreach", "(", "$", "this", "->", "schema", "as", "$", "fld", ")", "{", "$", "schema", ".=", "$", "sep", ".", "$", "fld", ";", "$", "sep", "=", "', '", ".", "PHP_EOL", ";", "}", "$", "schema", ".=", "PHP_EOL", ".", "');'", ".", "PHP_EOL", ";", "# Indecies", "foreach", "(", "$", "this", "->", "indecies", "as", "$", "index", ")", "{", "foreach", "(", "$", "index", "as", "$", "type", "=>", "$", "field", ")", "{", "$", "type", "=", "strtolower", "(", "$", "type", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'u'", ":", "case", "'unique'", ":", "$", "schema", ".=", "'CREATE UNIQUE INDEX '", ";", "break", ";", "case", "'i'", ":", "case", "'index'", ":", "default", ":", "$", "schema", ".=", "'CREATE INDEX '", ";", "}", "$", "schema", ".=", "\"{$this->table}_{$field}_{$type}\"", ".", "' ON '", ".", "$", "this", "->", "table", ".", "'('", ".", "$", "field", ".", "');'", ".", "PHP_EOL", ";", "}", "}", "return", "$", "schema", ";", "}" ]
Creates the schema of the DB according to the defined
[ "Creates", "the", "schema", "of", "the", "DB", "according", "to", "the", "defined" ]
0e01e2f265b95f17b1a888137c4364714c367128
https://github.com/irfantoor/database/blob/0e01e2f265b95f17b1a888137c4364714c367128/src/Database/Model.php#L95-L129
train
irfantoor/database
src/Database/Model.php
Model.getFirst
public function getFirst($q = [], $data = []) { $q['limit'] = 1; $list = $this->get($q, $data); return (count($list)) ? $list[0] : null; }
php
public function getFirst($q = [], $data = []) { $q['limit'] = 1; $list = $this->get($q, $data); return (count($list)) ? $list[0] : null; }
[ "public", "function", "getFirst", "(", "$", "q", "=", "[", "]", ",", "$", "data", "=", "[", "]", ")", "{", "$", "q", "[", "'limit'", "]", "=", "1", ";", "$", "list", "=", "$", "this", "->", "get", "(", "$", "q", ",", "$", "data", ")", ";", "return", "(", "count", "(", "$", "list", ")", ")", "?", "$", "list", "[", "0", "]", ":", "null", ";", "}" ]
Gets the first item as predfined by any previous functional operators @param array $q different elements of sql @param array $data elements used for binding @return array|null the first matching record as associated array or null
[ "Gets", "the", "first", "item", "as", "predfined", "by", "any", "previous", "functional", "operators" ]
0e01e2f265b95f17b1a888137c4364714c367128
https://github.com/irfantoor/database/blob/0e01e2f265b95f17b1a888137c4364714c367128/src/Database/Model.php#L193-L199
train
nicodevs/laito
src/Laito/Model.php
Model.where
public function where($column, $value, $operator = '=', $table = null) { $table = $table? $table : $this->table; $this->db()->where($column, $value, $operator, $table); return $this; }
php
public function where($column, $value, $operator = '=', $table = null) { $table = $table? $table : $this->table; $this->db()->where($column, $value, $operator, $table); return $this; }
[ "public", "function", "where", "(", "$", "column", ",", "$", "value", ",", "$", "operator", "=", "'='", ",", "$", "table", "=", "null", ")", "{", "$", "table", "=", "$", "table", "?", "$", "table", ":", "$", "this", "->", "table", ";", "$", "this", "->", "db", "(", ")", "->", "where", "(", "$", "column", ",", "$", "value", ",", "$", "operator", ",", "$", "table", ")", ";", "return", "$", "this", ";", "}" ]
Sets a where condition @param string $column Column name @param string $value Value to match @param string $operator Operator to compare with @return object Database instance
[ "Sets", "a", "where", "condition" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L189-L194
train
nicodevs/laito
src/Laito/Model.php
Model.whereIn
public function whereIn($column, $values, $table = null) { $this->db()->whereIn($column, $values, $table); return $this; }
php
public function whereIn($column, $values, $table = null) { $this->db()->whereIn($column, $values, $table); return $this; }
[ "public", "function", "whereIn", "(", "$", "column", ",", "$", "values", ",", "$", "table", "=", "null", ")", "{", "$", "this", "->", "db", "(", ")", "->", "whereIn", "(", "$", "column", ",", "$", "values", ",", "$", "table", ")", ";", "return", "$", "this", ";", "}" ]
Sets a where in condition @param string $column Column name @param string $values Values to match @return object Database instance
[ "Sets", "a", "where", "in", "condition" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L203-L207
train
nicodevs/laito
src/Laito/Model.php
Model.search
public function search($filters = []) { // Set resolved $resolved = []; // Check the filters if (!isset($filters) || !is_array($filters)) { throw new \InvalidArgumentException('Undefined search filters', 400); } // Set limit, offset and order if (isset($filters['limit'])) { $this->limit($filters['limit']); } if (isset($filters['offset'])) { $this->offset($filters['offset']); } if (isset($filters['order'])) { $this->orderBy($filters['order']); } // Remove invalid filters $filters = array_intersect_key($filters, array_flip(array_keys($this->filters))); // Set where in conditions foreach ($filters as $key => $value) { // Get filter data $current = $this->filters[$key]; $filterName = $current[0]; // Add condition if (isset($this->relationships['belongsToMany']) && is_array($this->relationships['belongsToMany']) && count($this->relationships['belongsToMany'])) { foreach ($this->relationships['belongsToMany'] as $join) { if ($filterName === $join['alias']) { $this->whereIn($join['pivot'] . '.' . $join['foreignKey'], (array) $value, $join['pivot']); $resolved[] = $key; } } } } // Set where conditions foreach ($filters as $key => $value) { if (!in_array($key, $resolved)) { // Get filter data $current = $this->filters[$key]; $column = $current[0]; $operator = isset($current[1])? $current[1] : '='; if ($operator === 'LIKE') { $value = '%' . $value . '%'; } if ($operator === 'IS_NOT_EMPTY') { $operator = '<>'; $value = ''; } // Add condition $table = isset($current[2])? $current[2] : $this->table; $this->where($column, $value, $operator, $table); } } // Return model instance return $this; }
php
public function search($filters = []) { // Set resolved $resolved = []; // Check the filters if (!isset($filters) || !is_array($filters)) { throw new \InvalidArgumentException('Undefined search filters', 400); } // Set limit, offset and order if (isset($filters['limit'])) { $this->limit($filters['limit']); } if (isset($filters['offset'])) { $this->offset($filters['offset']); } if (isset($filters['order'])) { $this->orderBy($filters['order']); } // Remove invalid filters $filters = array_intersect_key($filters, array_flip(array_keys($this->filters))); // Set where in conditions foreach ($filters as $key => $value) { // Get filter data $current = $this->filters[$key]; $filterName = $current[0]; // Add condition if (isset($this->relationships['belongsToMany']) && is_array($this->relationships['belongsToMany']) && count($this->relationships['belongsToMany'])) { foreach ($this->relationships['belongsToMany'] as $join) { if ($filterName === $join['alias']) { $this->whereIn($join['pivot'] . '.' . $join['foreignKey'], (array) $value, $join['pivot']); $resolved[] = $key; } } } } // Set where conditions foreach ($filters as $key => $value) { if (!in_array($key, $resolved)) { // Get filter data $current = $this->filters[$key]; $column = $current[0]; $operator = isset($current[1])? $current[1] : '='; if ($operator === 'LIKE') { $value = '%' . $value . '%'; } if ($operator === 'IS_NOT_EMPTY') { $operator = '<>'; $value = ''; } // Add condition $table = isset($current[2])? $current[2] : $this->table; $this->where($column, $value, $operator, $table); } } // Return model instance return $this; }
[ "public", "function", "search", "(", "$", "filters", "=", "[", "]", ")", "{", "// Set resolved", "$", "resolved", "=", "[", "]", ";", "// Check the filters", "if", "(", "!", "isset", "(", "$", "filters", ")", "||", "!", "is_array", "(", "$", "filters", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Undefined search filters'", ",", "400", ")", ";", "}", "// Set limit, offset and order", "if", "(", "isset", "(", "$", "filters", "[", "'limit'", "]", ")", ")", "{", "$", "this", "->", "limit", "(", "$", "filters", "[", "'limit'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "filters", "[", "'offset'", "]", ")", ")", "{", "$", "this", "->", "offset", "(", "$", "filters", "[", "'offset'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "filters", "[", "'order'", "]", ")", ")", "{", "$", "this", "->", "orderBy", "(", "$", "filters", "[", "'order'", "]", ")", ";", "}", "// Remove invalid filters", "$", "filters", "=", "array_intersect_key", "(", "$", "filters", ",", "array_flip", "(", "array_keys", "(", "$", "this", "->", "filters", ")", ")", ")", ";", "// Set where in conditions", "foreach", "(", "$", "filters", "as", "$", "key", "=>", "$", "value", ")", "{", "// Get filter data", "$", "current", "=", "$", "this", "->", "filters", "[", "$", "key", "]", ";", "$", "filterName", "=", "$", "current", "[", "0", "]", ";", "// Add condition", "if", "(", "isset", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", "&&", "is_array", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", "&&", "count", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", "as", "$", "join", ")", "{", "if", "(", "$", "filterName", "===", "$", "join", "[", "'alias'", "]", ")", "{", "$", "this", "->", "whereIn", "(", "$", "join", "[", "'pivot'", "]", ".", "'.'", ".", "$", "join", "[", "'foreignKey'", "]", ",", "(", "array", ")", "$", "value", ",", "$", "join", "[", "'pivot'", "]", ")", ";", "$", "resolved", "[", "]", "=", "$", "key", ";", "}", "}", "}", "}", "// Set where conditions", "foreach", "(", "$", "filters", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "resolved", ")", ")", "{", "// Get filter data", "$", "current", "=", "$", "this", "->", "filters", "[", "$", "key", "]", ";", "$", "column", "=", "$", "current", "[", "0", "]", ";", "$", "operator", "=", "isset", "(", "$", "current", "[", "1", "]", ")", "?", "$", "current", "[", "1", "]", ":", "'='", ";", "if", "(", "$", "operator", "===", "'LIKE'", ")", "{", "$", "value", "=", "'%'", ".", "$", "value", ".", "'%'", ";", "}", "if", "(", "$", "operator", "===", "'IS_NOT_EMPTY'", ")", "{", "$", "operator", "=", "'<>'", ";", "$", "value", "=", "''", ";", "}", "// Add condition", "$", "table", "=", "isset", "(", "$", "current", "[", "2", "]", ")", "?", "$", "current", "[", "2", "]", ":", "$", "this", "->", "table", ";", "$", "this", "->", "where", "(", "$", "column", ",", "$", "value", ",", "$", "operator", ",", "$", "table", ")", ";", "}", "}", "// Return model instance", "return", "$", "this", ";", "}" ]
Sets an array of filters as where conditions @param array $params Search parameters @return bool|array Array of results, or false
[ "Sets", "an", "array", "of", "filters", "as", "where", "conditions" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L235-L301
train
nicodevs/laito
src/Laito/Model.php
Model.get
public function get() { // Perform before hook $this->beforeGet(); // Set basic query $this->db()->table($this->table)->select($this->columns)->limit($this->limit)->offset($this->offset)->orderBy($this->orderBy); // Resolve relationships $this->hasOne()->belongsToMany(); // Get results $this->records = $this->db()->get(); // Add has many relationships $this->hasMany(); // Format relationships $this->formatBelongsToMany()->formatHasOne(); // Perform after hook $this->afterGet(); // Return query results return $this->records; }
php
public function get() { // Perform before hook $this->beforeGet(); // Set basic query $this->db()->table($this->table)->select($this->columns)->limit($this->limit)->offset($this->offset)->orderBy($this->orderBy); // Resolve relationships $this->hasOne()->belongsToMany(); // Get results $this->records = $this->db()->get(); // Add has many relationships $this->hasMany(); // Format relationships $this->formatBelongsToMany()->formatHasOne(); // Perform after hook $this->afterGet(); // Return query results return $this->records; }
[ "public", "function", "get", "(", ")", "{", "// Perform before hook", "$", "this", "->", "beforeGet", "(", ")", ";", "// Set basic query", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "this", "->", "table", ")", "->", "select", "(", "$", "this", "->", "columns", ")", "->", "limit", "(", "$", "this", "->", "limit", ")", "->", "offset", "(", "$", "this", "->", "offset", ")", "->", "orderBy", "(", "$", "this", "->", "orderBy", ")", ";", "// Resolve relationships", "$", "this", "->", "hasOne", "(", ")", "->", "belongsToMany", "(", ")", ";", "// Get results", "$", "this", "->", "records", "=", "$", "this", "->", "db", "(", ")", "->", "get", "(", ")", ";", "// Add has many relationships", "$", "this", "->", "hasMany", "(", ")", ";", "// Format relationships", "$", "this", "->", "formatBelongsToMany", "(", ")", "->", "formatHasOne", "(", ")", ";", "// Perform after hook", "$", "this", "->", "afterGet", "(", ")", ";", "// Return query results", "return", "$", "this", "->", "records", ";", "}" ]
Returns an array of models @return bool|array Array of models, or false
[ "Returns", "an", "array", "of", "models" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L308-L333
train
nicodevs/laito
src/Laito/Model.php
Model.count
public function count() { $this->db()->table($this->table)->groupBy($this->table . '.' . $this->primaryKey); $this->hasOne()->belongsToMany(); $count = $this->db()->count($this->primaryKey); return $count; }
php
public function count() { $this->db()->table($this->table)->groupBy($this->table . '.' . $this->primaryKey); $this->hasOne()->belongsToMany(); $count = $this->db()->count($this->primaryKey); return $count; }
[ "public", "function", "count", "(", ")", "{", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "this", "->", "table", ")", "->", "groupBy", "(", "$", "this", "->", "table", ".", "'.'", ".", "$", "this", "->", "primaryKey", ")", ";", "$", "this", "->", "hasOne", "(", ")", "->", "belongsToMany", "(", ")", ";", "$", "count", "=", "$", "this", "->", "db", "(", ")", "->", "count", "(", "$", "this", "->", "primaryKey", ")", ";", "return", "$", "count", ";", "}" ]
Returns the total number of models @param string $column Column to count by @return int Total number of models
[ "Returns", "the", "total", "number", "of", "models" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L341-L347
train
nicodevs/laito
src/Laito/Model.php
Model.find
public function find($id = null) { // ID has to be defined if (!isset($id)) { throw new \InvalidArgumentException('Undefined ID to find', 400); } // Return the first found record using the primary key for the where $result = $this->where($this->primaryKey, $id, '=', $this->table)->limit(1)->first(); // Return the first matching record return $result; }
php
public function find($id = null) { // ID has to be defined if (!isset($id)) { throw new \InvalidArgumentException('Undefined ID to find', 400); } // Return the first found record using the primary key for the where $result = $this->where($this->primaryKey, $id, '=', $this->table)->limit(1)->first(); // Return the first matching record return $result; }
[ "public", "function", "find", "(", "$", "id", "=", "null", ")", "{", "// ID has to be defined", "if", "(", "!", "isset", "(", "$", "id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Undefined ID to find'", ",", "400", ")", ";", "}", "// Return the first found record using the primary key for the where", "$", "result", "=", "$", "this", "->", "where", "(", "$", "this", "->", "primaryKey", ",", "$", "id", ",", "'='", ",", "$", "this", "->", "table", ")", "->", "limit", "(", "1", ")", "->", "first", "(", ")", ";", "// Return the first matching record", "return", "$", "result", ";", "}" ]
Returns a single model by primary key @param string $id Primary key value @return bool|array Model attributes, or false
[ "Returns", "a", "single", "model", "by", "primary", "key" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L355-L367
train
nicodevs/laito
src/Laito/Model.php
Model.first
public function first() { // Perform query $result = $this->get(); // Abort if no models where found if (!$result || !is_array($result) || empty($result)) { return false; } // Return the first matching model return reset($result); }
php
public function first() { // Perform query $result = $this->get(); // Abort if no models where found if (!$result || !is_array($result) || empty($result)) { return false; } // Return the first matching model return reset($result); }
[ "public", "function", "first", "(", ")", "{", "// Perform query", "$", "result", "=", "$", "this", "->", "get", "(", ")", ";", "// Abort if no models where found", "if", "(", "!", "$", "result", "||", "!", "is_array", "(", "$", "result", ")", "||", "empty", "(", "$", "result", ")", ")", "{", "return", "false", ";", "}", "// Return the first matching model", "return", "reset", "(", "$", "result", ")", ";", "}" ]
Returns the first model found @return bool|array Model attributes, or false
[ "Returns", "the", "first", "model", "found" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L374-L386
train
nicodevs/laito
src/Laito/Model.php
Model.create
public function create($attributes = []) { // Attributes have to be array if (!(isset($attributes)) || !is_array($attributes)) { throw new \InvalidArgumentException('Undefined attributes', 400); } // Perform before hook $attributes = $this->beforeCreate($attributes); // Remove non fillable attributes $fields = array_intersect_key($attributes, array_flip($this->fillable)); // Validate attributes $this->setValidationRules(); $errors = $this->validationErrors($fields); if ($errors) { throw new Exceptions\ValidationException('Invalid attributes', 400, $errors); } // Create the model and return its ID $result = $this->db()->table($this->table)->insertGetId($fields); // Return false if create fails if (!$result) { throw new \Exception('Could not create the model', 500); } // Sync many to many relationships $this->sync($result, $attributes); // Upsert has many relationships $this->updateHasMany($result, $attributes); // Get the created model $model = $this->find($result); // Run after hook $model = $this->afterCreate($result, $attributes, $model); // Return the created model return $model; }
php
public function create($attributes = []) { // Attributes have to be array if (!(isset($attributes)) || !is_array($attributes)) { throw new \InvalidArgumentException('Undefined attributes', 400); } // Perform before hook $attributes = $this->beforeCreate($attributes); // Remove non fillable attributes $fields = array_intersect_key($attributes, array_flip($this->fillable)); // Validate attributes $this->setValidationRules(); $errors = $this->validationErrors($fields); if ($errors) { throw new Exceptions\ValidationException('Invalid attributes', 400, $errors); } // Create the model and return its ID $result = $this->db()->table($this->table)->insertGetId($fields); // Return false if create fails if (!$result) { throw new \Exception('Could not create the model', 500); } // Sync many to many relationships $this->sync($result, $attributes); // Upsert has many relationships $this->updateHasMany($result, $attributes); // Get the created model $model = $this->find($result); // Run after hook $model = $this->afterCreate($result, $attributes, $model); // Return the created model return $model; }
[ "public", "function", "create", "(", "$", "attributes", "=", "[", "]", ")", "{", "// Attributes have to be array", "if", "(", "!", "(", "isset", "(", "$", "attributes", ")", ")", "||", "!", "is_array", "(", "$", "attributes", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Undefined attributes'", ",", "400", ")", ";", "}", "// Perform before hook", "$", "attributes", "=", "$", "this", "->", "beforeCreate", "(", "$", "attributes", ")", ";", "// Remove non fillable attributes", "$", "fields", "=", "array_intersect_key", "(", "$", "attributes", ",", "array_flip", "(", "$", "this", "->", "fillable", ")", ")", ";", "// Validate attributes", "$", "this", "->", "setValidationRules", "(", ")", ";", "$", "errors", "=", "$", "this", "->", "validationErrors", "(", "$", "fields", ")", ";", "if", "(", "$", "errors", ")", "{", "throw", "new", "Exceptions", "\\", "ValidationException", "(", "'Invalid attributes'", ",", "400", ",", "$", "errors", ")", ";", "}", "// Create the model and return its ID", "$", "result", "=", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "this", "->", "table", ")", "->", "insertGetId", "(", "$", "fields", ")", ";", "// Return false if create fails", "if", "(", "!", "$", "result", ")", "{", "throw", "new", "\\", "Exception", "(", "'Could not create the model'", ",", "500", ")", ";", "}", "// Sync many to many relationships", "$", "this", "->", "sync", "(", "$", "result", ",", "$", "attributes", ")", ";", "// Upsert has many relationships", "$", "this", "->", "updateHasMany", "(", "$", "result", ",", "$", "attributes", ")", ";", "// Get the created model", "$", "model", "=", "$", "this", "->", "find", "(", "$", "result", ")", ";", "// Run after hook", "$", "model", "=", "$", "this", "->", "afterCreate", "(", "$", "result", ",", "$", "attributes", ",", "$", "model", ")", ";", "// Return the created model", "return", "$", "model", ";", "}" ]
Creates a new model @param $attributes Model attributes @return bool|array Created model ID, or false
[ "Creates", "a", "new", "model" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L394-L436
train
nicodevs/laito
src/Laito/Model.php
Model.update
public function update($id = null, $attributes = []) { // ID has to be defined if (!isset($id)) { throw new \InvalidArgumentException('Undefined ID to update', 400); } // Attributes have to be array if (!(isset($attributes)) || !is_array($attributes)) { throw new \InvalidArgumentException('Undefined attributes', 400); } // Perform before hook $attributes = $this->beforeUpdate($id, $attributes); // Remove non fillable attributes $fields = array_intersect_key($attributes, array_flip($this->fillable)); // Validate attributes $this->setValidationRules(); $errors = $this->validationErrors($fields); if ($errors) { throw new Exceptions\ValidationException('Invalid attributes', 400, $errors); } // Update the model if ($fields && count($fields)) { $result = $this->db()->table($this->table)->where($this->primaryKey, $id, '=', $this->table)->update($fields); // Return false if the update failed if (!$result) { throw new \Exception('Could not update the model', 500); } } // Sync many to many relationships $this->sync($id, $attributes); // Upsert has many relationships $this->updateHasMany($id, $attributes); // Get the created model $model = $this->find($id); // Run after hook $model = $this->afterUpdate($id, $attributes, $model); // Return the created model return $model; }
php
public function update($id = null, $attributes = []) { // ID has to be defined if (!isset($id)) { throw new \InvalidArgumentException('Undefined ID to update', 400); } // Attributes have to be array if (!(isset($attributes)) || !is_array($attributes)) { throw new \InvalidArgumentException('Undefined attributes', 400); } // Perform before hook $attributes = $this->beforeUpdate($id, $attributes); // Remove non fillable attributes $fields = array_intersect_key($attributes, array_flip($this->fillable)); // Validate attributes $this->setValidationRules(); $errors = $this->validationErrors($fields); if ($errors) { throw new Exceptions\ValidationException('Invalid attributes', 400, $errors); } // Update the model if ($fields && count($fields)) { $result = $this->db()->table($this->table)->where($this->primaryKey, $id, '=', $this->table)->update($fields); // Return false if the update failed if (!$result) { throw new \Exception('Could not update the model', 500); } } // Sync many to many relationships $this->sync($id, $attributes); // Upsert has many relationships $this->updateHasMany($id, $attributes); // Get the created model $model = $this->find($id); // Run after hook $model = $this->afterUpdate($id, $attributes, $model); // Return the created model return $model; }
[ "public", "function", "update", "(", "$", "id", "=", "null", ",", "$", "attributes", "=", "[", "]", ")", "{", "// ID has to be defined", "if", "(", "!", "isset", "(", "$", "id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Undefined ID to update'", ",", "400", ")", ";", "}", "// Attributes have to be array", "if", "(", "!", "(", "isset", "(", "$", "attributes", ")", ")", "||", "!", "is_array", "(", "$", "attributes", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Undefined attributes'", ",", "400", ")", ";", "}", "// Perform before hook", "$", "attributes", "=", "$", "this", "->", "beforeUpdate", "(", "$", "id", ",", "$", "attributes", ")", ";", "// Remove non fillable attributes", "$", "fields", "=", "array_intersect_key", "(", "$", "attributes", ",", "array_flip", "(", "$", "this", "->", "fillable", ")", ")", ";", "// Validate attributes", "$", "this", "->", "setValidationRules", "(", ")", ";", "$", "errors", "=", "$", "this", "->", "validationErrors", "(", "$", "fields", ")", ";", "if", "(", "$", "errors", ")", "{", "throw", "new", "Exceptions", "\\", "ValidationException", "(", "'Invalid attributes'", ",", "400", ",", "$", "errors", ")", ";", "}", "// Update the model", "if", "(", "$", "fields", "&&", "count", "(", "$", "fields", ")", ")", "{", "$", "result", "=", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "this", "->", "table", ")", "->", "where", "(", "$", "this", "->", "primaryKey", ",", "$", "id", ",", "'='", ",", "$", "this", "->", "table", ")", "->", "update", "(", "$", "fields", ")", ";", "// Return false if the update failed", "if", "(", "!", "$", "result", ")", "{", "throw", "new", "\\", "Exception", "(", "'Could not update the model'", ",", "500", ")", ";", "}", "}", "// Sync many to many relationships", "$", "this", "->", "sync", "(", "$", "id", ",", "$", "attributes", ")", ";", "// Upsert has many relationships", "$", "this", "->", "updateHasMany", "(", "$", "id", ",", "$", "attributes", ")", ";", "// Get the created model", "$", "model", "=", "$", "this", "->", "find", "(", "$", "id", ")", ";", "// Run after hook", "$", "model", "=", "$", "this", "->", "afterUpdate", "(", "$", "id", ",", "$", "attributes", ",", "$", "model", ")", ";", "// Return the created model", "return", "$", "model", ";", "}" ]
Updates a model @param $id Model primary key @param $attributes Model attributes @return bool|array Updated model, or false
[ "Updates", "a", "model" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L445-L494
train
nicodevs/laito
src/Laito/Model.php
Model.destroy
public function destroy($id = null) { // ID has to be defined if (!isset($id)) { throw new \InvalidArgumentException('Undefined ID to destroy', 400); } // Perform before hook $this->beforeDestroy($id); // Update the model $result = $this->db()->table($this->table)->where($this->primaryKey, $id)->limit(1)->delete(); // Return false on failures if (!$result) { throw new \Exception('Could not destroy the model', 500); } // Perform after hook $this->afterDestroy($id); // Return the destroyed model ID, or false on fail return $id; }
php
public function destroy($id = null) { // ID has to be defined if (!isset($id)) { throw new \InvalidArgumentException('Undefined ID to destroy', 400); } // Perform before hook $this->beforeDestroy($id); // Update the model $result = $this->db()->table($this->table)->where($this->primaryKey, $id)->limit(1)->delete(); // Return false on failures if (!$result) { throw new \Exception('Could not destroy the model', 500); } // Perform after hook $this->afterDestroy($id); // Return the destroyed model ID, or false on fail return $id; }
[ "public", "function", "destroy", "(", "$", "id", "=", "null", ")", "{", "// ID has to be defined", "if", "(", "!", "isset", "(", "$", "id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Undefined ID to destroy'", ",", "400", ")", ";", "}", "// Perform before hook", "$", "this", "->", "beforeDestroy", "(", "$", "id", ")", ";", "// Update the model", "$", "result", "=", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "this", "->", "table", ")", "->", "where", "(", "$", "this", "->", "primaryKey", ",", "$", "id", ")", "->", "limit", "(", "1", ")", "->", "delete", "(", ")", ";", "// Return false on failures", "if", "(", "!", "$", "result", ")", "{", "throw", "new", "\\", "Exception", "(", "'Could not destroy the model'", ",", "500", ")", ";", "}", "// Perform after hook", "$", "this", "->", "afterDestroy", "(", "$", "id", ")", ";", "// Return the destroyed model ID, or false on fail", "return", "$", "id", ";", "}" ]
Destroys a model @return bool|array Deleted model ID, or false
[ "Destroys", "a", "model" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L501-L524
train
nicodevs/laito
src/Laito/Model.php
Model.hasOne
private function hasOne() { // Return if there are no relationships of that type if (!isset($this->relationships['hasOne']) || empty($this->relationships['hasOne'])) { return $this; } // Iterate relationships foreach ($this->relationships['hasOne'] as $join) { // Perform join $this->db()->join($join['table'], $join['localKey'], '=', $join['foreignKey']); // Add related columns to select foreach ($join['columns'] as $column) { $column = $join['table'] . '.' . $column . ' as _' . $join['alias'] . '_' . $column; $this->db()->addSelect($column); } } // Return model instance return $this; }
php
private function hasOne() { // Return if there are no relationships of that type if (!isset($this->relationships['hasOne']) || empty($this->relationships['hasOne'])) { return $this; } // Iterate relationships foreach ($this->relationships['hasOne'] as $join) { // Perform join $this->db()->join($join['table'], $join['localKey'], '=', $join['foreignKey']); // Add related columns to select foreach ($join['columns'] as $column) { $column = $join['table'] . '.' . $column . ' as _' . $join['alias'] . '_' . $column; $this->db()->addSelect($column); } } // Return model instance return $this; }
[ "private", "function", "hasOne", "(", ")", "{", "// Return if there are no relationships of that type", "if", "(", "!", "isset", "(", "$", "this", "->", "relationships", "[", "'hasOne'", "]", ")", "||", "empty", "(", "$", "this", "->", "relationships", "[", "'hasOne'", "]", ")", ")", "{", "return", "$", "this", ";", "}", "// Iterate relationships", "foreach", "(", "$", "this", "->", "relationships", "[", "'hasOne'", "]", "as", "$", "join", ")", "{", "// Perform join", "$", "this", "->", "db", "(", ")", "->", "join", "(", "$", "join", "[", "'table'", "]", ",", "$", "join", "[", "'localKey'", "]", ",", "'='", ",", "$", "join", "[", "'foreignKey'", "]", ")", ";", "// Add related columns to select", "foreach", "(", "$", "join", "[", "'columns'", "]", "as", "$", "column", ")", "{", "$", "column", "=", "$", "join", "[", "'table'", "]", ".", "'.'", ".", "$", "column", ".", "' as _'", ".", "$", "join", "[", "'alias'", "]", ".", "'_'", ".", "$", "column", ";", "$", "this", "->", "db", "(", ")", "->", "addSelect", "(", "$", "column", ")", ";", "}", "}", "// Return model instance", "return", "$", "this", ";", "}" ]
Resolves one to one relationships @return object Model instance
[ "Resolves", "one", "to", "one", "relationships" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L632-L654
train
nicodevs/laito
src/Laito/Model.php
Model.hasMany
private function hasMany() { // Return if there are no relationships of that type if (!isset($this->relationships['hasMany']) || empty($this->relationships['hasMany'])) { return $this; } // Get current records IDs $ids = array_column($this->records, 'id'); // Return if no records where found if (empty($ids)) { return $this; } // Make a associative array from current records $records = array_combine($ids, $this->records); // Iterate relationships foreach ($this->relationships['hasMany'] as $join) { // Get relationship results trought the model if (isset($join['model'])) { if (isset($this->models) && isset($this->models[$join['model']])) { $instance = $this->models[$join['model']]; } else { $instance = new $join['model']; } $childs = $instance->whereIn($join['foreignKey'], $ids)->limit($join['limit'])->orderBy($join['orderBy'])->get(); } // Or get relationship results by database if (!isset($join['model'])) { $join['orderBy'] = isset($join['orderBy'])? $join['orderBy'] : 'id'; $childs = $this->db()->table($join['table'])->select(array_merge([$join['foreignKey']], $join['columns']))->whereIn($join['foreignKey'], $ids)->limit($join['limit'])->orderBy($join['orderBy'])->get(); } // Group them by foreign key if ($childs) { foreach ($childs as $child) { $key = $join['foreignKey']; $id = $child[$key]; // If the ID was not required as a column to show, leave it out if (!in_array($key, $join['columns'])) { unset($child[$key]); } // Save the result $join['results'][$id][] = $child; } } // Add relationship results to the main collection foreach ($records as $key => $value) { $id = $value[$join['localKey']]; $records[$id][$join['alias']] = (isset($join['results'][$id]))? $join['results'][$value[$join['localKey']]] : []; } } // Save the records with the resolved relationships $this->records = array_values($records); // Return model instance return $this; }
php
private function hasMany() { // Return if there are no relationships of that type if (!isset($this->relationships['hasMany']) || empty($this->relationships['hasMany'])) { return $this; } // Get current records IDs $ids = array_column($this->records, 'id'); // Return if no records where found if (empty($ids)) { return $this; } // Make a associative array from current records $records = array_combine($ids, $this->records); // Iterate relationships foreach ($this->relationships['hasMany'] as $join) { // Get relationship results trought the model if (isset($join['model'])) { if (isset($this->models) && isset($this->models[$join['model']])) { $instance = $this->models[$join['model']]; } else { $instance = new $join['model']; } $childs = $instance->whereIn($join['foreignKey'], $ids)->limit($join['limit'])->orderBy($join['orderBy'])->get(); } // Or get relationship results by database if (!isset($join['model'])) { $join['orderBy'] = isset($join['orderBy'])? $join['orderBy'] : 'id'; $childs = $this->db()->table($join['table'])->select(array_merge([$join['foreignKey']], $join['columns']))->whereIn($join['foreignKey'], $ids)->limit($join['limit'])->orderBy($join['orderBy'])->get(); } // Group them by foreign key if ($childs) { foreach ($childs as $child) { $key = $join['foreignKey']; $id = $child[$key]; // If the ID was not required as a column to show, leave it out if (!in_array($key, $join['columns'])) { unset($child[$key]); } // Save the result $join['results'][$id][] = $child; } } // Add relationship results to the main collection foreach ($records as $key => $value) { $id = $value[$join['localKey']]; $records[$id][$join['alias']] = (isset($join['results'][$id]))? $join['results'][$value[$join['localKey']]] : []; } } // Save the records with the resolved relationships $this->records = array_values($records); // Return model instance return $this; }
[ "private", "function", "hasMany", "(", ")", "{", "// Return if there are no relationships of that type", "if", "(", "!", "isset", "(", "$", "this", "->", "relationships", "[", "'hasMany'", "]", ")", "||", "empty", "(", "$", "this", "->", "relationships", "[", "'hasMany'", "]", ")", ")", "{", "return", "$", "this", ";", "}", "// Get current records IDs", "$", "ids", "=", "array_column", "(", "$", "this", "->", "records", ",", "'id'", ")", ";", "// Return if no records where found", "if", "(", "empty", "(", "$", "ids", ")", ")", "{", "return", "$", "this", ";", "}", "// Make a associative array from current records", "$", "records", "=", "array_combine", "(", "$", "ids", ",", "$", "this", "->", "records", ")", ";", "// Iterate relationships", "foreach", "(", "$", "this", "->", "relationships", "[", "'hasMany'", "]", "as", "$", "join", ")", "{", "// Get relationship results trought the model", "if", "(", "isset", "(", "$", "join", "[", "'model'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "models", ")", "&&", "isset", "(", "$", "this", "->", "models", "[", "$", "join", "[", "'model'", "]", "]", ")", ")", "{", "$", "instance", "=", "$", "this", "->", "models", "[", "$", "join", "[", "'model'", "]", "]", ";", "}", "else", "{", "$", "instance", "=", "new", "$", "join", "[", "'model'", "]", ";", "}", "$", "childs", "=", "$", "instance", "->", "whereIn", "(", "$", "join", "[", "'foreignKey'", "]", ",", "$", "ids", ")", "->", "limit", "(", "$", "join", "[", "'limit'", "]", ")", "->", "orderBy", "(", "$", "join", "[", "'orderBy'", "]", ")", "->", "get", "(", ")", ";", "}", "// Or get relationship results by database", "if", "(", "!", "isset", "(", "$", "join", "[", "'model'", "]", ")", ")", "{", "$", "join", "[", "'orderBy'", "]", "=", "isset", "(", "$", "join", "[", "'orderBy'", "]", ")", "?", "$", "join", "[", "'orderBy'", "]", ":", "'id'", ";", "$", "childs", "=", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "join", "[", "'table'", "]", ")", "->", "select", "(", "array_merge", "(", "[", "$", "join", "[", "'foreignKey'", "]", "]", ",", "$", "join", "[", "'columns'", "]", ")", ")", "->", "whereIn", "(", "$", "join", "[", "'foreignKey'", "]", ",", "$", "ids", ")", "->", "limit", "(", "$", "join", "[", "'limit'", "]", ")", "->", "orderBy", "(", "$", "join", "[", "'orderBy'", "]", ")", "->", "get", "(", ")", ";", "}", "// Group them by foreign key", "if", "(", "$", "childs", ")", "{", "foreach", "(", "$", "childs", "as", "$", "child", ")", "{", "$", "key", "=", "$", "join", "[", "'foreignKey'", "]", ";", "$", "id", "=", "$", "child", "[", "$", "key", "]", ";", "// If the ID was not required as a column to show, leave it out", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "join", "[", "'columns'", "]", ")", ")", "{", "unset", "(", "$", "child", "[", "$", "key", "]", ")", ";", "}", "// Save the result", "$", "join", "[", "'results'", "]", "[", "$", "id", "]", "[", "]", "=", "$", "child", ";", "}", "}", "// Add relationship results to the main collection", "foreach", "(", "$", "records", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "id", "=", "$", "value", "[", "$", "join", "[", "'localKey'", "]", "]", ";", "$", "records", "[", "$", "id", "]", "[", "$", "join", "[", "'alias'", "]", "]", "=", "(", "isset", "(", "$", "join", "[", "'results'", "]", "[", "$", "id", "]", ")", ")", "?", "$", "join", "[", "'results'", "]", "[", "$", "value", "[", "$", "join", "[", "'localKey'", "]", "]", "]", ":", "[", "]", ";", "}", "}", "// Save the records with the resolved relationships", "$", "this", "->", "records", "=", "array_values", "(", "$", "records", ")", ";", "// Return model instance", "return", "$", "this", ";", "}" ]
Resolves one to many relationships @return object Model instance
[ "Resolves", "one", "to", "many", "relationships" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L661-L726
train
nicodevs/laito
src/Laito/Model.php
Model.belongsToMany
private function belongsToMany() { // Return if there are no relationships of that type if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) { return $this; } // Group by primary key $this->db()->groupBy($this->table . '.' . $this->primaryKey); // Iterate relationships foreach ($this->relationships['belongsToMany'] as $join) { // Perform join $this->db()->join($join['pivot'], $this->primaryKey, '=', $join['localKey']); // Add related columns to select $column = 'GROUP_CONCAT(' . $join['pivot'] . '.' . $join['foreignKey'] . ') as concat_' . $join['alias']; $this->db()->addSelect($column); } // Return model instance return $this; }
php
private function belongsToMany() { // Return if there are no relationships of that type if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) { return $this; } // Group by primary key $this->db()->groupBy($this->table . '.' . $this->primaryKey); // Iterate relationships foreach ($this->relationships['belongsToMany'] as $join) { // Perform join $this->db()->join($join['pivot'], $this->primaryKey, '=', $join['localKey']); // Add related columns to select $column = 'GROUP_CONCAT(' . $join['pivot'] . '.' . $join['foreignKey'] . ') as concat_' . $join['alias']; $this->db()->addSelect($column); } // Return model instance return $this; }
[ "private", "function", "belongsToMany", "(", ")", "{", "// Return if there are no relationships of that type", "if", "(", "!", "isset", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", "||", "empty", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", ")", "{", "return", "$", "this", ";", "}", "// Group by primary key", "$", "this", "->", "db", "(", ")", "->", "groupBy", "(", "$", "this", "->", "table", ".", "'.'", ".", "$", "this", "->", "primaryKey", ")", ";", "// Iterate relationships", "foreach", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", "as", "$", "join", ")", "{", "// Perform join", "$", "this", "->", "db", "(", ")", "->", "join", "(", "$", "join", "[", "'pivot'", "]", ",", "$", "this", "->", "primaryKey", ",", "'='", ",", "$", "join", "[", "'localKey'", "]", ")", ";", "// Add related columns to select", "$", "column", "=", "'GROUP_CONCAT('", ".", "$", "join", "[", "'pivot'", "]", ".", "'.'", ".", "$", "join", "[", "'foreignKey'", "]", ".", "') as concat_'", ".", "$", "join", "[", "'alias'", "]", ";", "$", "this", "->", "db", "(", ")", "->", "addSelect", "(", "$", "column", ")", ";", "}", "// Return model instance", "return", "$", "this", ";", "}" ]
Resolves many to many relationships @return object Model instance
[ "Resolves", "many", "to", "many", "relationships" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L733-L756
train
nicodevs/laito
src/Laito/Model.php
Model.sync
private function sync($id, $attributes) { // Return if the ID is invalid, or attributes is not an array if (!isset($id) || !isset($attributes) || empty($attributes)) { return $this; } // Return if there are no relationships of that type if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) { return $this; } // Sync each relationship foreach ($this->relationships['belongsToMany'] as $join) { // The sync option has to be true, the related attribute an array if (isset($join['sync']) && $join['sync'] && isset($attributes[$join['alias']]) && is_array($attributes[$join['alias']])) { // Delete old values $delete = $this->db()->table($join['pivot'])->where($join['localKey'], $id, '=')->delete(); // Insert new values foreach ($attributes[$join['alias']] as $value) { $this->db()->table($join['pivot'])->insert([$join['localKey'] => $id, $join['foreignKey'] => $value]); } } } // Return model instance return $this; }
php
private function sync($id, $attributes) { // Return if the ID is invalid, or attributes is not an array if (!isset($id) || !isset($attributes) || empty($attributes)) { return $this; } // Return if there are no relationships of that type if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) { return $this; } // Sync each relationship foreach ($this->relationships['belongsToMany'] as $join) { // The sync option has to be true, the related attribute an array if (isset($join['sync']) && $join['sync'] && isset($attributes[$join['alias']]) && is_array($attributes[$join['alias']])) { // Delete old values $delete = $this->db()->table($join['pivot'])->where($join['localKey'], $id, '=')->delete(); // Insert new values foreach ($attributes[$join['alias']] as $value) { $this->db()->table($join['pivot'])->insert([$join['localKey'] => $id, $join['foreignKey'] => $value]); } } } // Return model instance return $this; }
[ "private", "function", "sync", "(", "$", "id", ",", "$", "attributes", ")", "{", "// Return if the ID is invalid, or attributes is not an array", "if", "(", "!", "isset", "(", "$", "id", ")", "||", "!", "isset", "(", "$", "attributes", ")", "||", "empty", "(", "$", "attributes", ")", ")", "{", "return", "$", "this", ";", "}", "// Return if there are no relationships of that type", "if", "(", "!", "isset", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", "||", "empty", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", ")", "{", "return", "$", "this", ";", "}", "// Sync each relationship", "foreach", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", "as", "$", "join", ")", "{", "// The sync option has to be true, the related attribute an array", "if", "(", "isset", "(", "$", "join", "[", "'sync'", "]", ")", "&&", "$", "join", "[", "'sync'", "]", "&&", "isset", "(", "$", "attributes", "[", "$", "join", "[", "'alias'", "]", "]", ")", "&&", "is_array", "(", "$", "attributes", "[", "$", "join", "[", "'alias'", "]", "]", ")", ")", "{", "// Delete old values", "$", "delete", "=", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "join", "[", "'pivot'", "]", ")", "->", "where", "(", "$", "join", "[", "'localKey'", "]", ",", "$", "id", ",", "'='", ")", "->", "delete", "(", ")", ";", "// Insert new values", "foreach", "(", "$", "attributes", "[", "$", "join", "[", "'alias'", "]", "]", "as", "$", "value", ")", "{", "$", "this", "->", "db", "(", ")", "->", "table", "(", "$", "join", "[", "'pivot'", "]", ")", "->", "insert", "(", "[", "$", "join", "[", "'localKey'", "]", "=>", "$", "id", ",", "$", "join", "[", "'foreignKey'", "]", "=>", "$", "value", "]", ")", ";", "}", "}", "}", "// Return model instance", "return", "$", "this", ";", "}" ]
Syncs many to many relationships @param $attributes Model attributes @return object Model instance
[ "Syncs", "many", "to", "many", "relationships" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L764-L794
train
nicodevs/laito
src/Laito/Model.php
Model.formatBelongsToMany
private function formatBelongsToMany() { // Return if there are no relationships of that type if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) { return $this; } // Iterate relationships foreach ($this->relationships['belongsToMany'] as $join) { $this->records = array_map(function ($record) use ($join) { foreach ($record as $key => $value) { if ($key === 'concat_' . $join['alias']) { $record[$join['alias']] = ($value)? explode(',', $value) : []; unset($record[$key]); } } return $record; }, $this->records); } // Return model instance return $this; }
php
private function formatBelongsToMany() { // Return if there are no relationships of that type if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) { return $this; } // Iterate relationships foreach ($this->relationships['belongsToMany'] as $join) { $this->records = array_map(function ($record) use ($join) { foreach ($record as $key => $value) { if ($key === 'concat_' . $join['alias']) { $record[$join['alias']] = ($value)? explode(',', $value) : []; unset($record[$key]); } } return $record; }, $this->records); } // Return model instance return $this; }
[ "private", "function", "formatBelongsToMany", "(", ")", "{", "// Return if there are no relationships of that type", "if", "(", "!", "isset", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", "||", "empty", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", ")", ")", "{", "return", "$", "this", ";", "}", "// Iterate relationships", "foreach", "(", "$", "this", "->", "relationships", "[", "'belongsToMany'", "]", "as", "$", "join", ")", "{", "$", "this", "->", "records", "=", "array_map", "(", "function", "(", "$", "record", ")", "use", "(", "$", "join", ")", "{", "foreach", "(", "$", "record", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "key", "===", "'concat_'", ".", "$", "join", "[", "'alias'", "]", ")", "{", "$", "record", "[", "$", "join", "[", "'alias'", "]", "]", "=", "(", "$", "value", ")", "?", "explode", "(", "','", ",", "$", "value", ")", ":", "[", "]", ";", "unset", "(", "$", "record", "[", "$", "key", "]", ")", ";", "}", "}", "return", "$", "record", ";", "}", ",", "$", "this", "->", "records", ")", ";", "}", "// Return model instance", "return", "$", "this", ";", "}" ]
Format many to many relationships results @return object Model instance
[ "Format", "many", "to", "many", "relationships", "results" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L915-L937
train
nicodevs/laito
src/Laito/Model.php
Model.formatHasOne
private function formatHasOne() { // Return if there are no relationships of that type if (!isset($this->relationships['hasOne']) || empty($this->relationships['hasOne'])) { return $this; } // Iterate relationships foreach ($this->relationships['hasOne'] as $join) { $this->records = array_map(function ($record) use ($join) { foreach ($record as $key => $value) { $prefix = '_' . $join['alias'] . '_'; if (preg_match('/^' . $prefix . '[\w]+/', $key)) { $record[$join['alias']][str_replace($prefix, '', $key)] = $value; unset($record[$key]); } } return $record; }, $this->records); } // Return model instance return $this; }
php
private function formatHasOne() { // Return if there are no relationships of that type if (!isset($this->relationships['hasOne']) || empty($this->relationships['hasOne'])) { return $this; } // Iterate relationships foreach ($this->relationships['hasOne'] as $join) { $this->records = array_map(function ($record) use ($join) { foreach ($record as $key => $value) { $prefix = '_' . $join['alias'] . '_'; if (preg_match('/^' . $prefix . '[\w]+/', $key)) { $record[$join['alias']][str_replace($prefix, '', $key)] = $value; unset($record[$key]); } } return $record; }, $this->records); } // Return model instance return $this; }
[ "private", "function", "formatHasOne", "(", ")", "{", "// Return if there are no relationships of that type", "if", "(", "!", "isset", "(", "$", "this", "->", "relationships", "[", "'hasOne'", "]", ")", "||", "empty", "(", "$", "this", "->", "relationships", "[", "'hasOne'", "]", ")", ")", "{", "return", "$", "this", ";", "}", "// Iterate relationships", "foreach", "(", "$", "this", "->", "relationships", "[", "'hasOne'", "]", "as", "$", "join", ")", "{", "$", "this", "->", "records", "=", "array_map", "(", "function", "(", "$", "record", ")", "use", "(", "$", "join", ")", "{", "foreach", "(", "$", "record", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "prefix", "=", "'_'", ".", "$", "join", "[", "'alias'", "]", ".", "'_'", ";", "if", "(", "preg_match", "(", "'/^'", ".", "$", "prefix", ".", "'[\\w]+/'", ",", "$", "key", ")", ")", "{", "$", "record", "[", "$", "join", "[", "'alias'", "]", "]", "[", "str_replace", "(", "$", "prefix", ",", "''", ",", "$", "key", ")", "]", "=", "$", "value", ";", "unset", "(", "$", "record", "[", "$", "key", "]", ")", ";", "}", "}", "return", "$", "record", ";", "}", ",", "$", "this", "->", "records", ")", ";", "}", "// Return model instance", "return", "$", "this", ";", "}" ]
Format has many relationships results @return object Model instance
[ "Format", "has", "many", "relationships", "results" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L944-L967
train
nicodevs/laito
src/Laito/Model.php
Model.validationErrors
public function validationErrors($attributes, $rules = null) { // Rules container $this->rules = $this->setValidationRules(); // Ruleset $ruleSet = isset($rules)? $rules : $this->validate; // Errors collector $errors = []; // Leave only the validable attributes $attributes = array_intersect_key($attributes, array_flip(array_keys($ruleSet))); // Check for required attributes foreach ($ruleSet as $key => $rules) { if (in_array('required', $rules) && (!isset($attributes[$key]) || trim($attributes[$key]) === '')) { $errors[$key] = 'required'; } $ruleSet[$key] = array_diff($rules, ['required']); } // Check for format errors foreach ($attributes as $key => $value) { foreach ($ruleSet[$key] as $name => $rule) { if (!preg_match($this->rules[$rule], $value)) { $errors[$key] = $rule; } } } // Return errors or false return count($errors)? $errors : false; }
php
public function validationErrors($attributes, $rules = null) { // Rules container $this->rules = $this->setValidationRules(); // Ruleset $ruleSet = isset($rules)? $rules : $this->validate; // Errors collector $errors = []; // Leave only the validable attributes $attributes = array_intersect_key($attributes, array_flip(array_keys($ruleSet))); // Check for required attributes foreach ($ruleSet as $key => $rules) { if (in_array('required', $rules) && (!isset($attributes[$key]) || trim($attributes[$key]) === '')) { $errors[$key] = 'required'; } $ruleSet[$key] = array_diff($rules, ['required']); } // Check for format errors foreach ($attributes as $key => $value) { foreach ($ruleSet[$key] as $name => $rule) { if (!preg_match($this->rules[$rule], $value)) { $errors[$key] = $rule; } } } // Return errors or false return count($errors)? $errors : false; }
[ "public", "function", "validationErrors", "(", "$", "attributes", ",", "$", "rules", "=", "null", ")", "{", "// Rules container", "$", "this", "->", "rules", "=", "$", "this", "->", "setValidationRules", "(", ")", ";", "// Ruleset", "$", "ruleSet", "=", "isset", "(", "$", "rules", ")", "?", "$", "rules", ":", "$", "this", "->", "validate", ";", "// Errors collector", "$", "errors", "=", "[", "]", ";", "// Leave only the validable attributes", "$", "attributes", "=", "array_intersect_key", "(", "$", "attributes", ",", "array_flip", "(", "array_keys", "(", "$", "ruleSet", ")", ")", ")", ";", "// Check for required attributes", "foreach", "(", "$", "ruleSet", "as", "$", "key", "=>", "$", "rules", ")", "{", "if", "(", "in_array", "(", "'required'", ",", "$", "rules", ")", "&&", "(", "!", "isset", "(", "$", "attributes", "[", "$", "key", "]", ")", "||", "trim", "(", "$", "attributes", "[", "$", "key", "]", ")", "===", "''", ")", ")", "{", "$", "errors", "[", "$", "key", "]", "=", "'required'", ";", "}", "$", "ruleSet", "[", "$", "key", "]", "=", "array_diff", "(", "$", "rules", ",", "[", "'required'", "]", ")", ";", "}", "// Check for format errors", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "foreach", "(", "$", "ruleSet", "[", "$", "key", "]", "as", "$", "name", "=>", "$", "rule", ")", "{", "if", "(", "!", "preg_match", "(", "$", "this", "->", "rules", "[", "$", "rule", "]", ",", "$", "value", ")", ")", "{", "$", "errors", "[", "$", "key", "]", "=", "$", "rule", ";", "}", "}", "}", "// Return errors or false", "return", "count", "(", "$", "errors", ")", "?", "$", "errors", ":", "false", ";", "}" ]
Validates a model @param $attributes Attributes to validate @param $rules Rules to validate @return array|bool Array of errors, or false if the model is valid
[ "Validates", "a", "model" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Model.php#L986-L1020
train
XetaIO/Xetaravel-IpTraceable
src/Listeners/Subscribers/IpTraceableSubscriber.php
IpTraceableSubscriber.onLogin
public function onLogin(Login $event) { $ip = $this->request->getClientIp(); $this->updateFields($this->auth, $ip); }
php
public function onLogin(Login $event) { $ip = $this->request->getClientIp(); $this->updateFields($this->auth, $ip); }
[ "public", "function", "onLogin", "(", "Login", "$", "event", ")", "{", "$", "ip", "=", "$", "this", "->", "request", "->", "getClientIp", "(", ")", ";", "$", "this", "->", "updateFields", "(", "$", "this", "->", "auth", ",", "$", "ip", ")", ";", "}" ]
Listener for the login event. @param \Illuminate\Auth\Events\Login $event The event that was fired. @return bool
[ "Listener", "for", "the", "login", "event", "." ]
e1c57592d45f240c55e827fd6b756e5143c892b5
https://github.com/XetaIO/Xetaravel-IpTraceable/blob/e1c57592d45f240c55e827fd6b756e5143c892b5/src/Listeners/Subscribers/IpTraceableSubscriber.php#L58-L63
train
romm/configuration_object
Classes/Core/Core.php
Core.classExists
public function classExists($className) { if (!$className) { return false; } if (false === isset($this->existingClassList[$className])) { $this->existingClassList[$className] = class_exists($className) || interface_exists($className); } return $this->existingClassList[$className]; }
php
public function classExists($className) { if (!$className) { return false; } if (false === isset($this->existingClassList[$className])) { $this->existingClassList[$className] = class_exists($className) || interface_exists($className); } return $this->existingClassList[$className]; }
[ "public", "function", "classExists", "(", "$", "className", ")", "{", "if", "(", "!", "$", "className", ")", "{", "return", "false", ";", "}", "if", "(", "false", "===", "isset", "(", "$", "this", "->", "existingClassList", "[", "$", "className", "]", ")", ")", "{", "$", "this", "->", "existingClassList", "[", "$", "className", "]", "=", "class_exists", "(", "$", "className", ")", "||", "interface_exists", "(", "$", "className", ")", ";", "}", "return", "$", "this", "->", "existingClassList", "[", "$", "className", "]", ";", "}" ]
Internal function which will check if the given class exists. This is useful because of the calls to undefined class, which can lead to a lack of performance due to the auto-loader called if the name of the class is not registered yet. This function will store the already checked class name in local cache. @param string $className @return bool
[ "Internal", "function", "which", "will", "check", "if", "the", "given", "class", "exists", ".", "This", "is", "useful", "because", "of", "the", "calls", "to", "undefined", "class", "which", "can", "lead", "to", "a", "lack", "of", "performance", "due", "to", "the", "auto", "-", "loader", "called", "if", "the", "name", "of", "the", "class", "is", "not", "registered", "yet", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Core/Core.php#L114-L125
train
romm/configuration_object
Classes/Core/Core.php
Core.getGettablePropertiesOfObject
public function getGettablePropertiesOfObject($object) { $className = get_class($object); if (false === isset($this->gettablePropertiesOfObjects[$className])) { $this->gettablePropertiesOfObjects[$className] = []; $properties = $this->getReflectionService()->getClassPropertyNames($className); foreach ($properties as $propertyName) { if (true === $this->isPropertyGettable($object, $propertyName)) { $this->gettablePropertiesOfObjects[$className][] = $propertyName; } } } return $this->gettablePropertiesOfObjects[$className]; }
php
public function getGettablePropertiesOfObject($object) { $className = get_class($object); if (false === isset($this->gettablePropertiesOfObjects[$className])) { $this->gettablePropertiesOfObjects[$className] = []; $properties = $this->getReflectionService()->getClassPropertyNames($className); foreach ($properties as $propertyName) { if (true === $this->isPropertyGettable($object, $propertyName)) { $this->gettablePropertiesOfObjects[$className][] = $propertyName; } } } return $this->gettablePropertiesOfObjects[$className]; }
[ "public", "function", "getGettablePropertiesOfObject", "(", "$", "object", ")", "{", "$", "className", "=", "get_class", "(", "$", "object", ")", ";", "if", "(", "false", "===", "isset", "(", "$", "this", "->", "gettablePropertiesOfObjects", "[", "$", "className", "]", ")", ")", "{", "$", "this", "->", "gettablePropertiesOfObjects", "[", "$", "className", "]", "=", "[", "]", ";", "$", "properties", "=", "$", "this", "->", "getReflectionService", "(", ")", "->", "getClassPropertyNames", "(", "$", "className", ")", ";", "foreach", "(", "$", "properties", "as", "$", "propertyName", ")", "{", "if", "(", "true", "===", "$", "this", "->", "isPropertyGettable", "(", "$", "object", ",", "$", "propertyName", ")", ")", "{", "$", "this", "->", "gettablePropertiesOfObjects", "[", "$", "className", "]", "[", "]", "=", "$", "propertyName", ";", "}", "}", "}", "return", "$", "this", "->", "gettablePropertiesOfObjects", "[", "$", "className", "]", ";", "}" ]
Returns the list of properties which are accessible for this given object. Properties are stored in local cache to improve performance. @param object $object @return array
[ "Returns", "the", "list", "of", "properties", "which", "are", "accessible", "for", "this", "given", "object", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Core/Core.php#L136-L152
train
carno-php/rpc
src/Chips/DInstances.php
DInstances.preparing
public function preparing(Promised $started, Promised $stopping) : Promised { $starts = []; foreach ($this->dr()->servers() as $api) { foreach ($this->dr()->services($api) as $service => $route) { // set global instance of service DI::set($class = $route[1], $server = DI::object($class)); // lifecycle hooks if ($server instanceof Lifecycle) { $starts[] = $started->then([$server, 'started']); $stopping->then([$server, 'stopped']); } } } return all(...$starts); }
php
public function preparing(Promised $started, Promised $stopping) : Promised { $starts = []; foreach ($this->dr()->servers() as $api) { foreach ($this->dr()->services($api) as $service => $route) { // set global instance of service DI::set($class = $route[1], $server = DI::object($class)); // lifecycle hooks if ($server instanceof Lifecycle) { $starts[] = $started->then([$server, 'started']); $stopping->then([$server, 'stopped']); } } } return all(...$starts); }
[ "public", "function", "preparing", "(", "Promised", "$", "started", ",", "Promised", "$", "stopping", ")", ":", "Promised", "{", "$", "starts", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "dr", "(", ")", "->", "servers", "(", ")", "as", "$", "api", ")", "{", "foreach", "(", "$", "this", "->", "dr", "(", ")", "->", "services", "(", "$", "api", ")", "as", "$", "service", "=>", "$", "route", ")", "{", "// set global instance of service", "DI", "::", "set", "(", "$", "class", "=", "$", "route", "[", "1", "]", ",", "$", "server", "=", "DI", "::", "object", "(", "$", "class", ")", ")", ";", "// lifecycle hooks", "if", "(", "$", "server", "instanceof", "Lifecycle", ")", "{", "$", "starts", "[", "]", "=", "$", "started", "->", "then", "(", "[", "$", "server", ",", "'started'", "]", ")", ";", "$", "stopping", "->", "then", "(", "[", "$", "server", ",", "'stopped'", "]", ")", ";", "}", "}", "}", "return", "all", "(", "...", "$", "starts", ")", ";", "}" ]
bind service implementer @param Promised $started @param Promised $stopping @return Promised
[ "bind", "service", "implementer" ]
0f1b310ac44a7f61271ba2a95ca265ed98f322ce
https://github.com/carno-php/rpc/blob/0f1b310ac44a7f61271ba2a95ca265ed98f322ce/src/Chips/DInstances.php#L33-L50
train
Wedeto/HTTP
src/Nonce.php
Nonce.getNonce
public static function getNonce(string $action, Session $session, array $context = [], int $timestamp = null) { // When nonce are not allowed to be stored, the nonce is not actually // used only once since it needs to be reproducable to be verifiable. // Therefore, it sent timestamped to the client. $timestamp = $timestamp ?? time(); $hashable = $action . $timestamp . $session->getSessionSalt(); foreach ($context as $key => $value) { if ($value === null) $value = "NULL"; if (!is_scalar($value)) throw new InvalidArgumentException("Context variables must be scalar"); $hashable .= '&' . $key . '=' . $value; } $nonce = sha1($hashable) . '$' . $timestamp; return $nonce; }
php
public static function getNonce(string $action, Session $session, array $context = [], int $timestamp = null) { // When nonce are not allowed to be stored, the nonce is not actually // used only once since it needs to be reproducable to be verifiable. // Therefore, it sent timestamped to the client. $timestamp = $timestamp ?? time(); $hashable = $action . $timestamp . $session->getSessionSalt(); foreach ($context as $key => $value) { if ($value === null) $value = "NULL"; if (!is_scalar($value)) throw new InvalidArgumentException("Context variables must be scalar"); $hashable .= '&' . $key . '=' . $value; } $nonce = sha1($hashable) . '$' . $timestamp; return $nonce; }
[ "public", "static", "function", "getNonce", "(", "string", "$", "action", ",", "Session", "$", "session", ",", "array", "$", "context", "=", "[", "]", ",", "int", "$", "timestamp", "=", "null", ")", "{", "// When nonce are not allowed to be stored, the nonce is not actually ", "// used only once since it needs to be reproducable to be verifiable.", "// Therefore, it sent timestamped to the client.", "$", "timestamp", "=", "$", "timestamp", "??", "time", "(", ")", ";", "$", "hashable", "=", "$", "action", ".", "$", "timestamp", ".", "$", "session", "->", "getSessionSalt", "(", ")", ";", "foreach", "(", "$", "context", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "===", "null", ")", "$", "value", "=", "\"NULL\"", ";", "if", "(", "!", "is_scalar", "(", "$", "value", ")", ")", "throw", "new", "InvalidArgumentException", "(", "\"Context variables must be scalar\"", ")", ";", "$", "hashable", ".=", "'&'", ".", "$", "key", ".", "'='", ".", "$", "value", ";", "}", "$", "nonce", "=", "sha1", "(", "$", "hashable", ")", ".", "'$'", ".", "$", "timestamp", ";", "return", "$", "nonce", ";", "}" ]
Get a nonce for the specified action optionally including context @param string $action The action to tie the nonce to @param Session $session The session to get the session salt from @param array $context The context required for the nonce to be validated @return string The nonce that should be submitted as parameter nonce
[ "Get", "a", "nonce", "for", "the", "specified", "action", "optionally", "including", "context" ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Nonce.php#L79-L97
train
Wedeto/HTTP
src/Nonce.php
Nonce.validateNonce
public static function validateNonce(string $action, Session $session, Dictionary $arguments, array $context = []) { // Check if a nonce was posted at all if (!$arguments->has(self::$nonce_parameter, Type::STRING)) { // No nonce submitted, indeterminate outcome return null; } $context_values = []; foreach ($context as $key => $value) { if (is_int($key)) { $key = $value; $value = $arguments->get($key); } $context_values[$key] = $value; } $nonce = $arguments->getString(self::$nonce_parameter); $parts = explode('$', $nonce); if (count($parts) !== 2) return false; list($hash, $timestamp) = $parts; // Check that the nonce has not expired yet $now = time(); if ($timestamp > $now || $now - $timestamp > self::$nonce_timeout) return false; // Generate the expected nonce $expected_nonce = self::getNonce($action, $session, $context_values, $timestamp); // Compare the generated nonce with the submitted nonce return $expected_nonce === $nonce; }
php
public static function validateNonce(string $action, Session $session, Dictionary $arguments, array $context = []) { // Check if a nonce was posted at all if (!$arguments->has(self::$nonce_parameter, Type::STRING)) { // No nonce submitted, indeterminate outcome return null; } $context_values = []; foreach ($context as $key => $value) { if (is_int($key)) { $key = $value; $value = $arguments->get($key); } $context_values[$key] = $value; } $nonce = $arguments->getString(self::$nonce_parameter); $parts = explode('$', $nonce); if (count($parts) !== 2) return false; list($hash, $timestamp) = $parts; // Check that the nonce has not expired yet $now = time(); if ($timestamp > $now || $now - $timestamp > self::$nonce_timeout) return false; // Generate the expected nonce $expected_nonce = self::getNonce($action, $session, $context_values, $timestamp); // Compare the generated nonce with the submitted nonce return $expected_nonce === $nonce; }
[ "public", "static", "function", "validateNonce", "(", "string", "$", "action", ",", "Session", "$", "session", ",", "Dictionary", "$", "arguments", ",", "array", "$", "context", "=", "[", "]", ")", "{", "// Check if a nonce was posted at all", "if", "(", "!", "$", "arguments", "->", "has", "(", "self", "::", "$", "nonce_parameter", ",", "Type", "::", "STRING", ")", ")", "{", "// No nonce submitted, indeterminate outcome", "return", "null", ";", "}", "$", "context_values", "=", "[", "]", ";", "foreach", "(", "$", "context", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "key", "=", "$", "value", ";", "$", "value", "=", "$", "arguments", "->", "get", "(", "$", "key", ")", ";", "}", "$", "context_values", "[", "$", "key", "]", "=", "$", "value", ";", "}", "$", "nonce", "=", "$", "arguments", "->", "getString", "(", "self", "::", "$", "nonce_parameter", ")", ";", "$", "parts", "=", "explode", "(", "'$'", ",", "$", "nonce", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "!==", "2", ")", "return", "false", ";", "list", "(", "$", "hash", ",", "$", "timestamp", ")", "=", "$", "parts", ";", "// Check that the nonce has not expired yet", "$", "now", "=", "time", "(", ")", ";", "if", "(", "$", "timestamp", ">", "$", "now", "||", "$", "now", "-", "$", "timestamp", ">", "self", "::", "$", "nonce_timeout", ")", "return", "false", ";", "// Generate the expected nonce", "$", "expected_nonce", "=", "self", "::", "getNonce", "(", "$", "action", ",", "$", "session", ",", "$", "context_values", ",", "$", "timestamp", ")", ";", "// Compare the generated nonce with the submitted nonce", "return", "$", "expected_nonce", "===", "$", "nonce", ";", "}" ]
Check if a nonce was posted and if it matches the data @param Dictionary $arguments The POST arguments. @param Session $session The session where the nonce data was stored @return bool True when a nonce was posted and validated, false if a nonce was posted and rejected, null when no nonce was posted.
[ "Check", "if", "a", "nonce", "was", "posted", "and", "if", "it", "matches", "the", "data" ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Nonce.php#L106-L144
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.required
public function required(string $alias, string $type): EntityDefinitionOptions { return $this->required[$alias] = new EntityDefinitionOptions($alias, $type); }
php
public function required(string $alias, string $type): EntityDefinitionOptions { return $this->required[$alias] = new EntityDefinitionOptions($alias, $type); }
[ "public", "function", "required", "(", "string", "$", "alias", ",", "string", "$", "type", ")", ":", "EntityDefinitionOptions", "{", "return", "$", "this", "->", "required", "[", "$", "alias", "]", "=", "new", "EntityDefinitionOptions", "(", "$", "alias", ",", "$", "type", ")", ";", "}" ]
Adds a required column @param string $alias The name of the column (does not have to match the database) @param string $type A value object class name @return EntityDefinitionOptions Options for the column
[ "Adds", "a", "required", "column" ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L112-L114
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.optional
public function optional(string $alias, string $type): EntityDefinitionOptions { return $this->optional[$alias] = new EntityDefinitionOptions($alias, $type); }
php
public function optional(string $alias, string $type): EntityDefinitionOptions { return $this->optional[$alias] = new EntityDefinitionOptions($alias, $type); }
[ "public", "function", "optional", "(", "string", "$", "alias", ",", "string", "$", "type", ")", ":", "EntityDefinitionOptions", "{", "return", "$", "this", "->", "optional", "[", "$", "alias", "]", "=", "new", "EntityDefinitionOptions", "(", "$", "alias", ",", "$", "type", ")", ";", "}" ]
Adds an optional column @param string $alias The name of the column (does not have to match the database) @param string $type A value object class name @return EntityDefinitionOptions Options for the column
[ "Adds", "an", "optional", "column" ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L124-L126
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.timestamps
public function timestamps(): void { $this->optional('created_at', Timestamp::class)->readOnly(); $this->optional('updated_at', Timestamp::class)->readOnly(); }
php
public function timestamps(): void { $this->optional('created_at', Timestamp::class)->readOnly(); $this->optional('updated_at', Timestamp::class)->readOnly(); }
[ "public", "function", "timestamps", "(", ")", ":", "void", "{", "$", "this", "->", "optional", "(", "'created_at'", ",", "Timestamp", "::", "class", ")", "->", "readOnly", "(", ")", ";", "$", "this", "->", "optional", "(", "'updated_at'", ",", "Timestamp", "::", "class", ")", "->", "readOnly", "(", ")", ";", "}" ]
Adds `created_at` and `updated_at` timestamps @return void
[ "Adds", "created_at", "and", "updated_at", "timestamps" ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L133-L136
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.hasMany
public function hasMany(string $alias, string $entity): Relation { return $this->has_many[$entity] = new Relation($alias, $this->full_name, $entity); }
php
public function hasMany(string $alias, string $entity): Relation { return $this->has_many[$entity] = new Relation($alias, $this->full_name, $entity); }
[ "public", "function", "hasMany", "(", "string", "$", "alias", ",", "string", "$", "entity", ")", ":", "Relation", "{", "return", "$", "this", "->", "has_many", "[", "$", "entity", "]", "=", "new", "Relation", "(", "$", "alias", ",", "$", "this", "->", "full_name", ",", "$", "entity", ")", ";", "}" ]
Add a `has many` relationship @param string $alias The name of the local column @param string $entity The fully-qualified class name of the related `Entity` @return Relation Options for the relation
[ "Add", "a", "has", "many", "relationship" ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L146-L148
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.hasManyThrough
public function hasManyThrough(string $alias, string $entity_join, string $entity_foreign): HasManyThrough { return $this->has_many_through[] = new HasManyThrough($alias, $entity_join, $entity_foreign); }
php
public function hasManyThrough(string $alias, string $entity_join, string $entity_foreign): HasManyThrough { return $this->has_many_through[] = new HasManyThrough($alias, $entity_join, $entity_foreign); }
[ "public", "function", "hasManyThrough", "(", "string", "$", "alias", ",", "string", "$", "entity_join", ",", "string", "$", "entity_foreign", ")", ":", "HasManyThrough", "{", "return", "$", "this", "->", "has_many_through", "[", "]", "=", "new", "HasManyThrough", "(", "$", "alias", ",", "$", "entity_join", ",", "$", "entity_foreign", ")", ";", "}" ]
Add a `has many through` relationship @param string $alias The name of the local column @param string $entity_join The fully-qualified class name of the intermediate `Entity` @param string $entity_foreign The fully-qualified class name of the foreign `Entity` @return HasManyThrough Options for the relation
[ "Add", "a", "has", "many", "through", "relationship" ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L159-L161
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.belongsTo
public function belongsTo(string $alias, string $entity): Relation { return $this->belongs_to[$entity] = new Relation($alias, $this->full_name, $entity); }
php
public function belongsTo(string $alias, string $entity): Relation { return $this->belongs_to[$entity] = new Relation($alias, $this->full_name, $entity); }
[ "public", "function", "belongsTo", "(", "string", "$", "alias", ",", "string", "$", "entity", ")", ":", "Relation", "{", "return", "$", "this", "->", "belongs_to", "[", "$", "entity", "]", "=", "new", "Relation", "(", "$", "alias", ",", "$", "this", "->", "full_name", ",", "$", "entity", ")", ";", "}" ]
Add a `belongs to` relationship @param string $alias The name of the local column @param string $entity The fully-qualified class name of the related `Entity` @return Relation Options for the relation
[ "Add", "a", "belongs", "to", "relationship" ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L171-L173
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.associates
public function associates(string $alias_join, string $alias_left, string $entity_left, string $alias_right, string $entity_right): ManyToMany { return $this->many_to_many[] = new ManyToMany($alias_join, $alias_left, $this->full_name, $entity_left, $alias_right, $entity_right); }
php
public function associates(string $alias_join, string $alias_left, string $entity_left, string $alias_right, string $entity_right): ManyToMany { return $this->many_to_many[] = new ManyToMany($alias_join, $alias_left, $this->full_name, $entity_left, $alias_right, $entity_right); }
[ "public", "function", "associates", "(", "string", "$", "alias_join", ",", "string", "$", "alias_left", ",", "string", "$", "entity_left", ",", "string", "$", "alias_right", ",", "string", "$", "entity_right", ")", ":", "ManyToMany", "{", "return", "$", "this", "->", "many_to_many", "[", "]", "=", "new", "ManyToMany", "(", "$", "alias_join", ",", "$", "alias_left", ",", "$", "this", "->", "full_name", ",", "$", "entity_left", ",", "$", "alias_right", ",", "$", "entity_right", ")", ";", "}" ]
Adds a `has many through` relationship to the left and right `Entity`s through this `Entity` @param string $alias_join The name of the join column @param string $alias_left The name of the left column @param string $entity_left The fully-qualified class name of the left `Entity` @param string $alias_right The name of the right column @param string $entity_right The fully-qualified class name of the right `Entity` @return ManyToMany Options for the relation
[ "Adds", "a", "has", "many", "through", "relationship", "to", "the", "left", "and", "right", "Entity", "s", "through", "this", "Entity" ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L186-L188
train
BapCat/Remodel
src/EntityDefinition.php
EntityDefinition.virtual
public function virtual(string $name, string $type, callable $callback): void { $this->virtuals[$name] = new VirtualField($name, $type, $callback); }
php
public function virtual(string $name, string $type, callable $callback): void { $this->virtuals[$name] = new VirtualField($name, $type, $callback); }
[ "public", "function", "virtual", "(", "string", "$", "name", ",", "string", "$", "type", ",", "callable", "$", "callback", ")", ":", "void", "{", "$", "this", "->", "virtuals", "[", "$", "name", "]", "=", "new", "VirtualField", "(", "$", "name", ",", "$", "type", ",", "$", "callback", ")", ";", "}" ]
Adds a virtual field to the `Entity`. The `callable` will be executed whenever the virtual field is accessed, and passed the `Entity`. @param string $name @param string $type @param callable $callback
[ "Adds", "a", "virtual", "field", "to", "the", "Entity", ".", "The", "callable", "will", "be", "executed", "whenever", "the", "virtual", "field", "is", "accessed", "and", "passed", "the", "Entity", "." ]
80fcdec8bca22b88c5af9a0a93622c796cf3e7b1
https://github.com/BapCat/Remodel/blob/80fcdec8bca22b88c5af9a0a93622c796cf3e7b1/src/EntityDefinition.php#L212-L214
train
flipbox/spark
src/models/traits/UserAttribute.php
UserTrait.setUserId
public function setUserId(int $id) { // Has the id changed? if ($id !== $this->userId) { // Invalidate existing user if ($this->user !== null && $this->user->getId() !== $id) { $this->user = null; }; $this->userId = $id; } return $this; }
php
public function setUserId(int $id) { // Has the id changed? if ($id !== $this->userId) { // Invalidate existing user if ($this->user !== null && $this->user->getId() !== $id) { $this->user = null; }; $this->userId = $id; } return $this; }
[ "public", "function", "setUserId", "(", "int", "$", "id", ")", "{", "// Has the id changed?", "if", "(", "$", "id", "!==", "$", "this", "->", "userId", ")", "{", "// Invalidate existing user", "if", "(", "$", "this", "->", "user", "!==", "null", "&&", "$", "this", "->", "user", "->", "getId", "(", ")", "!==", "$", "id", ")", "{", "$", "this", "->", "user", "=", "null", ";", "}", ";", "$", "this", "->", "userId", "=", "$", "id", ";", "}", "return", "$", "this", ";", "}" ]
Set associated userId @param $id @return $this
[ "Set", "associated", "userId" ]
9d75fd3d95744b9c9187921c4f3b9eea42c035d4
https://github.com/flipbox/spark/blob/9d75fd3d95744b9c9187921c4f3b9eea42c035d4/src/models/traits/UserAttribute.php#L38-L52
train
Dhii/placeholder-template-abstract
src/ReplaceTokensCapableTrait.php
ReplaceTokensCapableTrait._replaceTokens
protected function _replaceTokens($input, $source, $tokenStart, $tokenEnd, $default = null) { $input = $this->_normalizeString($input); $default = $default === null ? '' : $this->_normalizeString($default); $regexDelimiter = '/'; $tokenStart = $this->_quoteRegex($tokenStart, $regexDelimiter); $tokenEnd = $this->_quoteRegex($tokenEnd, $regexDelimiter); $regex = $regexDelimiter . $tokenStart . '(.*?)' . $tokenEnd . $regexDelimiter; $matches = $this->_getAllMatchesRegex($regex, $input); foreach ($matches[0] as $i => $token) { $key = $matches[1][$i]; $key = $this->_normalizeTokenKey($key); try { $value = $this->_containerGet($source, $key); } catch (NotFoundExceptionInterface $e) { $value = $default; } catch (RootException $e) { $this->_createRuntimeException($this->__('Could not access reference value for key "%1$s"', [$key]), null, $e); } try { $input = $this->_stringableReplace($token, $value, $input); } catch (RootException $e) { $this->_createRuntimeException($this->__('Could not replace token with key "%1$s"', [$key]), null, $e); } } return $input; }
php
protected function _replaceTokens($input, $source, $tokenStart, $tokenEnd, $default = null) { $input = $this->_normalizeString($input); $default = $default === null ? '' : $this->_normalizeString($default); $regexDelimiter = '/'; $tokenStart = $this->_quoteRegex($tokenStart, $regexDelimiter); $tokenEnd = $this->_quoteRegex($tokenEnd, $regexDelimiter); $regex = $regexDelimiter . $tokenStart . '(.*?)' . $tokenEnd . $regexDelimiter; $matches = $this->_getAllMatchesRegex($regex, $input); foreach ($matches[0] as $i => $token) { $key = $matches[1][$i]; $key = $this->_normalizeTokenKey($key); try { $value = $this->_containerGet($source, $key); } catch (NotFoundExceptionInterface $e) { $value = $default; } catch (RootException $e) { $this->_createRuntimeException($this->__('Could not access reference value for key "%1$s"', [$key]), null, $e); } try { $input = $this->_stringableReplace($token, $value, $input); } catch (RootException $e) { $this->_createRuntimeException($this->__('Could not replace token with key "%1$s"', [$key]), null, $e); } } return $input; }
[ "protected", "function", "_replaceTokens", "(", "$", "input", ",", "$", "source", ",", "$", "tokenStart", ",", "$", "tokenEnd", ",", "$", "default", "=", "null", ")", "{", "$", "input", "=", "$", "this", "->", "_normalizeString", "(", "$", "input", ")", ";", "$", "default", "=", "$", "default", "===", "null", "?", "''", ":", "$", "this", "->", "_normalizeString", "(", "$", "default", ")", ";", "$", "regexDelimiter", "=", "'/'", ";", "$", "tokenStart", "=", "$", "this", "->", "_quoteRegex", "(", "$", "tokenStart", ",", "$", "regexDelimiter", ")", ";", "$", "tokenEnd", "=", "$", "this", "->", "_quoteRegex", "(", "$", "tokenEnd", ",", "$", "regexDelimiter", ")", ";", "$", "regex", "=", "$", "regexDelimiter", ".", "$", "tokenStart", ".", "'(.*?)'", ".", "$", "tokenEnd", ".", "$", "regexDelimiter", ";", "$", "matches", "=", "$", "this", "->", "_getAllMatchesRegex", "(", "$", "regex", ",", "$", "input", ")", ";", "foreach", "(", "$", "matches", "[", "0", "]", "as", "$", "i", "=>", "$", "token", ")", "{", "$", "key", "=", "$", "matches", "[", "1", "]", "[", "$", "i", "]", ";", "$", "key", "=", "$", "this", "->", "_normalizeTokenKey", "(", "$", "key", ")", ";", "try", "{", "$", "value", "=", "$", "this", "->", "_containerGet", "(", "$", "source", ",", "$", "key", ")", ";", "}", "catch", "(", "NotFoundExceptionInterface", "$", "e", ")", "{", "$", "value", "=", "$", "default", ";", "}", "catch", "(", "RootException", "$", "e", ")", "{", "$", "this", "->", "_createRuntimeException", "(", "$", "this", "->", "__", "(", "'Could not access reference value for key \"%1$s\"'", ",", "[", "$", "key", "]", ")", ",", "null", ",", "$", "e", ")", ";", "}", "try", "{", "$", "input", "=", "$", "this", "->", "_stringableReplace", "(", "$", "token", ",", "$", "value", ",", "$", "input", ")", ";", "}", "catch", "(", "RootException", "$", "e", ")", "{", "$", "this", "->", "_createRuntimeException", "(", "$", "this", "->", "__", "(", "'Could not replace token with key \"%1$s\"'", ",", "[", "$", "key", "]", ")", ",", "null", ",", "$", "e", ")", ";", "}", "}", "return", "$", "input", ";", "}" ]
Replaces all tokens in a string with corresponding values. Use {@see _normalizeTokenKey()} to convert token keys into a format used in the container. @since [*next-version*] @param string|Stringable $input The string that may contain tokens. @param BaseContainerInterface|array|ArrayAccess|stdClass $source The source of values for replacement. @param string|Stringable $tokenStart Starting delimiter of token. @param string|Stringable $tokenEnd Ending delimiter of token. @param string|Stringable|null $default Default replacement value. Used if a token does not correspond to known value. @throws InvalidArgumentException If input, source, token start or end, or the default value are invalid. @throws RuntimeException If problem replacing tokens. @return string The resulting string.
[ "Replaces", "all", "tokens", "in", "a", "string", "with", "corresponding", "values", "." ]
bfa7cea3b1e078b19bcf59d9a3da63b8c12ed03b
https://github.com/Dhii/placeholder-template-abstract/blob/bfa7cea3b1e078b19bcf59d9a3da63b8c12ed03b/src/ReplaceTokensCapableTrait.php#L40-L72
train
Tom-Millard/php-class-gen
src/Generator.php
Generator.createClass
public function createClass(string $name, string $location, string $extends = "") : bool { $namespace = trim($this->getNameSpace($name)); $name = trim($this->getClassName($name)); $className = $name; if ($extends !== "") { $className .= " extends {$extends}"; } if ($namespace != "") { $namespace = "namespace ".$namespace; } $class = file_get_contents($this->templates["class.template"]); $class = str_replace(["[namespace]","[name]"], [$namespace, $className], $class); if (is_dir($location)) { file_put_contents($location."/".$name.".php", $class); return true; } return false; }
php
public function createClass(string $name, string $location, string $extends = "") : bool { $namespace = trim($this->getNameSpace($name)); $name = trim($this->getClassName($name)); $className = $name; if ($extends !== "") { $className .= " extends {$extends}"; } if ($namespace != "") { $namespace = "namespace ".$namespace; } $class = file_get_contents($this->templates["class.template"]); $class = str_replace(["[namespace]","[name]"], [$namespace, $className], $class); if (is_dir($location)) { file_put_contents($location."/".$name.".php", $class); return true; } return false; }
[ "public", "function", "createClass", "(", "string", "$", "name", ",", "string", "$", "location", ",", "string", "$", "extends", "=", "\"\"", ")", ":", "bool", "{", "$", "namespace", "=", "trim", "(", "$", "this", "->", "getNameSpace", "(", "$", "name", ")", ")", ";", "$", "name", "=", "trim", "(", "$", "this", "->", "getClassName", "(", "$", "name", ")", ")", ";", "$", "className", "=", "$", "name", ";", "if", "(", "$", "extends", "!==", "\"\"", ")", "{", "$", "className", ".=", "\" extends {$extends}\"", ";", "}", "if", "(", "$", "namespace", "!=", "\"\"", ")", "{", "$", "namespace", "=", "\"namespace \"", ".", "$", "namespace", ";", "}", "$", "class", "=", "file_get_contents", "(", "$", "this", "->", "templates", "[", "\"class.template\"", "]", ")", ";", "$", "class", "=", "str_replace", "(", "[", "\"[namespace]\"", ",", "\"[name]\"", "]", ",", "[", "$", "namespace", ",", "$", "className", "]", ",", "$", "class", ")", ";", "if", "(", "is_dir", "(", "$", "location", ")", ")", "{", "file_put_contents", "(", "$", "location", ".", "\"/\"", ".", "$", "name", ".", "\".php\"", ",", "$", "class", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Create a class @param string $name @param string $location @param string $extends @return boolean
[ "Create", "a", "class" ]
a4c06620589a63a98b3b64c9f64b9a85d754810e
https://github.com/Tom-Millard/php-class-gen/blob/a4c06620589a63a98b3b64c9f64b9a85d754810e/src/Generator.php#L32-L55
train
Tom-Millard/php-class-gen
src/Generator.php
Generator.getNameSpace
public function getNameSpace(string $name) : string { $segs = []; $name = str_replace("/", "\\", $name); $namespace = explode("\\", $name); array_pop($namespace); array_walk($namespace, function (&$value) { $value = $this->removeNoneAlpherNumeric($value); }); return implode("\\", $namespace); }
php
public function getNameSpace(string $name) : string { $segs = []; $name = str_replace("/", "\\", $name); $namespace = explode("\\", $name); array_pop($namespace); array_walk($namespace, function (&$value) { $value = $this->removeNoneAlpherNumeric($value); }); return implode("\\", $namespace); }
[ "public", "function", "getNameSpace", "(", "string", "$", "name", ")", ":", "string", "{", "$", "segs", "=", "[", "]", ";", "$", "name", "=", "str_replace", "(", "\"/\"", ",", "\"\\\\\"", ",", "$", "name", ")", ";", "$", "namespace", "=", "explode", "(", "\"\\\\\"", ",", "$", "name", ")", ";", "array_pop", "(", "$", "namespace", ")", ";", "array_walk", "(", "$", "namespace", ",", "function", "(", "&", "$", "value", ")", "{", "$", "value", "=", "$", "this", "->", "removeNoneAlpherNumeric", "(", "$", "value", ")", ";", "}", ")", ";", "return", "implode", "(", "\"\\\\\"", ",", "$", "namespace", ")", ";", "}" ]
Work out name space of the class @param string $name @return string
[ "Work", "out", "name", "space", "of", "the", "class" ]
a4c06620589a63a98b3b64c9f64b9a85d754810e
https://github.com/Tom-Millard/php-class-gen/blob/a4c06620589a63a98b3b64c9f64b9a85d754810e/src/Generator.php#L121-L133
train
Tom-Millard/php-class-gen
src/Generator.php
Generator.getClassName
public function getClassName(string $name) : string { $name = str_replace("/", "\\", $name); $name = explode("\\", $name); $name = array_pop($name); $name = $this->removeNoneAlpherNumeric($name); return $name; }
php
public function getClassName(string $name) : string { $name = str_replace("/", "\\", $name); $name = explode("\\", $name); $name = array_pop($name); $name = $this->removeNoneAlpherNumeric($name); return $name; }
[ "public", "function", "getClassName", "(", "string", "$", "name", ")", ":", "string", "{", "$", "name", "=", "str_replace", "(", "\"/\"", ",", "\"\\\\\"", ",", "$", "name", ")", ";", "$", "name", "=", "explode", "(", "\"\\\\\"", ",", "$", "name", ")", ";", "$", "name", "=", "array_pop", "(", "$", "name", ")", ";", "$", "name", "=", "$", "this", "->", "removeNoneAlpherNumeric", "(", "$", "name", ")", ";", "return", "$", "name", ";", "}" ]
Work out the class name from a namespace string @param string $name @return string
[ "Work", "out", "the", "class", "name", "from", "a", "namespace", "string" ]
a4c06620589a63a98b3b64c9f64b9a85d754810e
https://github.com/Tom-Millard/php-class-gen/blob/a4c06620589a63a98b3b64c9f64b9a85d754810e/src/Generator.php#L141-L148
train
agentmedia/phine-builtin
src/BuiltIn/Logic/Tree/NavigationTreeProvider.php
NavigationTreeProvider.Equals
public function Equals($item1, $item2) { if ($item1 === null && $item2 !== null) { return false; } else if ($item1 !== null && $item2 === null) { return false; } else if ($item1 === null && $item2 === null) { return true; } return $item1->Equals($item2); }
php
public function Equals($item1, $item2) { if ($item1 === null && $item2 !== null) { return false; } else if ($item1 !== null && $item2 === null) { return false; } else if ($item1 === null && $item2 === null) { return true; } return $item1->Equals($item2); }
[ "public", "function", "Equals", "(", "$", "item1", ",", "$", "item2", ")", "{", "if", "(", "$", "item1", "===", "null", "&&", "$", "item2", "!==", "null", ")", "{", "return", "false", ";", "}", "else", "if", "(", "$", "item1", "!==", "null", "&&", "$", "item2", "===", "null", ")", "{", "return", "false", ";", "}", "else", "if", "(", "$", "item1", "===", "null", "&&", "$", "item2", "===", "null", ")", "{", "return", "true", ";", "}", "return", "$", "item1", "->", "Equals", "(", "$", "item2", ")", ";", "}" ]
Compares the items @param NavigationItem $item1 @param NavigationItem $item2
[ "Compares", "the", "items" ]
4dd05bc406a71e997bd4eaa16b12e23dbe62a456
https://github.com/agentmedia/phine-builtin/blob/4dd05bc406a71e997bd4eaa16b12e23dbe62a456/src/BuiltIn/Logic/Tree/NavigationTreeProvider.php#L40-L55
train
praxigento/mobi_mod_downline
Service/Customer/Get/ById.php
ById.convertDbToApi
private function convertDbToApi($db) { $result = new AResponse(); if ($db) { /* extract DB data */ $custId = $db[QBGetCustomer::A_ID]; $email = $db[QBGetCustomer::A_EMAIL]; $nameFirst = $db[QBGetCustomer::A_NAME_FIRST]; $nameLast = $db[QBGetCustomer::A_NAME_LAST]; $mlmId = $db[QBGetCustomer::A_MLM_ID]; $path = $db[QBGetCustomer::A_PATH]; $country = $db[QBGetCustomer::A_COUNTRY]; /* prepare response data */ $pathFull = $path . $custId . Cfg::DTPS; /* compose response data */ $result->setId($custId); $result->setEmail($email); $result->setNameFirst($nameFirst); $result->setNameLast($nameLast); $result->setMlmId($mlmId); $result->setCountry($country); $result->setPathFull($pathFull); } return $result; }
php
private function convertDbToApi($db) { $result = new AResponse(); if ($db) { /* extract DB data */ $custId = $db[QBGetCustomer::A_ID]; $email = $db[QBGetCustomer::A_EMAIL]; $nameFirst = $db[QBGetCustomer::A_NAME_FIRST]; $nameLast = $db[QBGetCustomer::A_NAME_LAST]; $mlmId = $db[QBGetCustomer::A_MLM_ID]; $path = $db[QBGetCustomer::A_PATH]; $country = $db[QBGetCustomer::A_COUNTRY]; /* prepare response data */ $pathFull = $path . $custId . Cfg::DTPS; /* compose response data */ $result->setId($custId); $result->setEmail($email); $result->setNameFirst($nameFirst); $result->setNameLast($nameLast); $result->setMlmId($mlmId); $result->setCountry($country); $result->setPathFull($pathFull); } return $result; }
[ "private", "function", "convertDbToApi", "(", "$", "db", ")", "{", "$", "result", "=", "new", "AResponse", "(", ")", ";", "if", "(", "$", "db", ")", "{", "/* extract DB data */", "$", "custId", "=", "$", "db", "[", "QBGetCustomer", "::", "A_ID", "]", ";", "$", "email", "=", "$", "db", "[", "QBGetCustomer", "::", "A_EMAIL", "]", ";", "$", "nameFirst", "=", "$", "db", "[", "QBGetCustomer", "::", "A_NAME_FIRST", "]", ";", "$", "nameLast", "=", "$", "db", "[", "QBGetCustomer", "::", "A_NAME_LAST", "]", ";", "$", "mlmId", "=", "$", "db", "[", "QBGetCustomer", "::", "A_MLM_ID", "]", ";", "$", "path", "=", "$", "db", "[", "QBGetCustomer", "::", "A_PATH", "]", ";", "$", "country", "=", "$", "db", "[", "QBGetCustomer", "::", "A_COUNTRY", "]", ";", "/* prepare response data */", "$", "pathFull", "=", "$", "path", ".", "$", "custId", ".", "Cfg", "::", "DTPS", ";", "/* compose response data */", "$", "result", "->", "setId", "(", "$", "custId", ")", ";", "$", "result", "->", "setEmail", "(", "$", "email", ")", ";", "$", "result", "->", "setNameFirst", "(", "$", "nameFirst", ")", ";", "$", "result", "->", "setNameLast", "(", "$", "nameLast", ")", ";", "$", "result", "->", "setMlmId", "(", "$", "mlmId", ")", ";", "$", "result", "->", "setCountry", "(", "$", "country", ")", ";", "$", "result", "->", "setPathFull", "(", "$", "pathFull", ")", ";", "}", "return", "$", "result", ";", "}" ]
Convert database query result set to response object. @param array $db @return \Praxigento\Downline\Api\Service\Customer\Get\ById\Response @throws \Exception
[ "Convert", "database", "query", "result", "set", "to", "response", "object", "." ]
0f3c276dfff1aa029f9fd205ccfc56f207a2e75b
https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Service/Customer/Get/ById.php#L42-L68
train
juliangut/mapping
src/Driver/Locator/FileLocator.php
FileLocator.getMappingFiles
public function getMappingFiles(): array { $mappingPaths = []; foreach ($this->paths as $mappingPath) { if (\is_dir($mappingPath)) { $mappingPaths[] = $this->getFilesFromDirectory($mappingPath); } elseif (\is_file($mappingPath)) { $mappingPaths[] = [$mappingPath]; } else { throw new DriverException(\sprintf('Path "%s" does not exist', $mappingPath)); } } return \count($mappingPaths) > 0 ? \array_merge(...$mappingPaths) : []; }
php
public function getMappingFiles(): array { $mappingPaths = []; foreach ($this->paths as $mappingPath) { if (\is_dir($mappingPath)) { $mappingPaths[] = $this->getFilesFromDirectory($mappingPath); } elseif (\is_file($mappingPath)) { $mappingPaths[] = [$mappingPath]; } else { throw new DriverException(\sprintf('Path "%s" does not exist', $mappingPath)); } } return \count($mappingPaths) > 0 ? \array_merge(...$mappingPaths) : []; }
[ "public", "function", "getMappingFiles", "(", ")", ":", "array", "{", "$", "mappingPaths", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "paths", "as", "$", "mappingPath", ")", "{", "if", "(", "\\", "is_dir", "(", "$", "mappingPath", ")", ")", "{", "$", "mappingPaths", "[", "]", "=", "$", "this", "->", "getFilesFromDirectory", "(", "$", "mappingPath", ")", ";", "}", "elseif", "(", "\\", "is_file", "(", "$", "mappingPath", ")", ")", "{", "$", "mappingPaths", "[", "]", "=", "[", "$", "mappingPath", "]", ";", "}", "else", "{", "throw", "new", "DriverException", "(", "\\", "sprintf", "(", "'Path \"%s\" does not exist'", ",", "$", "mappingPath", ")", ")", ";", "}", "}", "return", "\\", "count", "(", "$", "mappingPaths", ")", ">", "0", "?", "\\", "array_merge", "(", "...", "$", "mappingPaths", ")", ":", "[", "]", ";", "}" ]
Get mapping files. @throws DriverException
[ "Get", "mapping", "files", "." ]
1830ff84c054d8e3759df170a5664a97f7070be9
https://github.com/juliangut/mapping/blob/1830ff84c054d8e3759df170a5664a97f7070be9/src/Driver/Locator/FileLocator.php#L74-L89
train
juliangut/mapping
src/Driver/Locator/FileLocator.php
FileLocator.getFilesFromDirectory
protected function getFilesFromDirectory(string $mappingDirectory): array { $mappingPaths = []; $filePattern = \sprintf('/^.+\.(%s)$/i', \implode('|', $this->extensions)); $recursiveIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($mappingDirectory)); $regexIterator = new \RegexIterator($recursiveIterator, $filePattern, \RecursiveRegexIterator::GET_MATCH); foreach ($regexIterator as $mappingFile) { $mappingPaths[] = $mappingFile[0]; } \sort($mappingPaths); return $mappingPaths; }
php
protected function getFilesFromDirectory(string $mappingDirectory): array { $mappingPaths = []; $filePattern = \sprintf('/^.+\.(%s)$/i', \implode('|', $this->extensions)); $recursiveIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($mappingDirectory)); $regexIterator = new \RegexIterator($recursiveIterator, $filePattern, \RecursiveRegexIterator::GET_MATCH); foreach ($regexIterator as $mappingFile) { $mappingPaths[] = $mappingFile[0]; } \sort($mappingPaths); return $mappingPaths; }
[ "protected", "function", "getFilesFromDirectory", "(", "string", "$", "mappingDirectory", ")", ":", "array", "{", "$", "mappingPaths", "=", "[", "]", ";", "$", "filePattern", "=", "\\", "sprintf", "(", "'/^.+\\.(%s)$/i'", ",", "\\", "implode", "(", "'|'", ",", "$", "this", "->", "extensions", ")", ")", ";", "$", "recursiveIterator", "=", "new", "\\", "RecursiveIteratorIterator", "(", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "mappingDirectory", ")", ")", ";", "$", "regexIterator", "=", "new", "\\", "RegexIterator", "(", "$", "recursiveIterator", ",", "$", "filePattern", ",", "\\", "RecursiveRegexIterator", "::", "GET_MATCH", ")", ";", "foreach", "(", "$", "regexIterator", "as", "$", "mappingFile", ")", "{", "$", "mappingPaths", "[", "]", "=", "$", "mappingFile", "[", "0", "]", ";", "}", "\\", "sort", "(", "$", "mappingPaths", ")", ";", "return", "$", "mappingPaths", ";", "}" ]
Get mapping files from directory. @param string $mappingDirectory @return array
[ "Get", "mapping", "files", "from", "directory", "." ]
1830ff84c054d8e3759df170a5664a97f7070be9
https://github.com/juliangut/mapping/blob/1830ff84c054d8e3759df170a5664a97f7070be9/src/Driver/Locator/FileLocator.php#L98-L113
train
g4code/storage
src/StorageFactory.php
StorageFactory.createInstance
public static function createInstance($driver, $options) { if(!in_array($driver, self::$_validDrivers)) { throw new \Exception("Driver '{$driver}' not implemented"); } $class = __NAMESPACE__ . '\\Driver\\' . $driver; $driver = new $class; $driver->setOptions($options); return new Storage($driver); }
php
public static function createInstance($driver, $options) { if(!in_array($driver, self::$_validDrivers)) { throw new \Exception("Driver '{$driver}' not implemented"); } $class = __NAMESPACE__ . '\\Driver\\' . $driver; $driver = new $class; $driver->setOptions($options); return new Storage($driver); }
[ "public", "static", "function", "createInstance", "(", "$", "driver", ",", "$", "options", ")", "{", "if", "(", "!", "in_array", "(", "$", "driver", ",", "self", "::", "$", "_validDrivers", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Driver '{$driver}' not implemented\"", ")", ";", "}", "$", "class", "=", "__NAMESPACE__", ".", "'\\\\Driver\\\\'", ".", "$", "driver", ";", "$", "driver", "=", "new", "$", "class", ";", "$", "driver", "->", "setOptions", "(", "$", "options", ")", ";", "return", "new", "Storage", "(", "$", "driver", ")", ";", "}" ]
Create new instance of G4\Storage\Storage @param string $driver @param array $options @throws \Exception @return \G4\Storage\Storage
[ "Create", "new", "instance", "of", "G4", "\\", "Storage", "\\", "Storage" ]
05b3976d5b855c2855979ff9fd9db1090473541d
https://github.com/g4code/storage/blob/05b3976d5b855c2855979ff9fd9db1090473541d/src/StorageFactory.php#L24-L36
train
rollerworks-graveyard/metadata
src/DefaultClassMetadata.php
DefaultClassMetadata.merge
public function merge(ClassMetadata $object) { $properties = $this->properties; $methods = $this->methods; foreach ($object->getProperties() as $property) { $properties[$property->getName()] = $property; } foreach ($object->getMethods() as $method) { $methods[$method->getName()] = $method; } $createdAt = $this->createdAt; if (($otherCreatedAt = $object->getCreatedAt()) > $createdAt) { $createdAt = $otherCreatedAt; } return new static($this->className, $properties, $methods, $createdAt); }
php
public function merge(ClassMetadata $object) { $properties = $this->properties; $methods = $this->methods; foreach ($object->getProperties() as $property) { $properties[$property->getName()] = $property; } foreach ($object->getMethods() as $method) { $methods[$method->getName()] = $method; } $createdAt = $this->createdAt; if (($otherCreatedAt = $object->getCreatedAt()) > $createdAt) { $createdAt = $otherCreatedAt; } return new static($this->className, $properties, $methods, $createdAt); }
[ "public", "function", "merge", "(", "ClassMetadata", "$", "object", ")", "{", "$", "properties", "=", "$", "this", "->", "properties", ";", "$", "methods", "=", "$", "this", "->", "methods", ";", "foreach", "(", "$", "object", "->", "getProperties", "(", ")", "as", "$", "property", ")", "{", "$", "properties", "[", "$", "property", "->", "getName", "(", ")", "]", "=", "$", "property", ";", "}", "foreach", "(", "$", "object", "->", "getMethods", "(", ")", "as", "$", "method", ")", "{", "$", "methods", "[", "$", "method", "->", "getName", "(", ")", "]", "=", "$", "method", ";", "}", "$", "createdAt", "=", "$", "this", "->", "createdAt", ";", "if", "(", "(", "$", "otherCreatedAt", "=", "$", "object", "->", "getCreatedAt", "(", ")", ")", ">", "$", "createdAt", ")", "{", "$", "createdAt", "=", "$", "otherCreatedAt", ";", "}", "return", "new", "static", "(", "$", "this", "->", "className", ",", "$", "properties", ",", "$", "methods", ",", "$", "createdAt", ")", ";", "}" ]
Merge the ClassMetadata of the object with the current ClassMetadata into a new object. Note: instead of modifying the current ClassMetadata you should instead return a new object. @param ClassMetadata $object Another MergeableClassMetadata object. @return self New ClassMetadata instance with the merged class metadata.
[ "Merge", "the", "ClassMetadata", "of", "the", "object", "with", "the", "current", "ClassMetadata", "into", "a", "new", "object", "." ]
5b07f564aad87709ca0d0b3e140e4dc4edf9d375
https://github.com/rollerworks-graveyard/metadata/blob/5b07f564aad87709ca0d0b3e140e4dc4edf9d375/src/DefaultClassMetadata.php#L180-L200
train
theopera/framework
src/Component/WebApplication/WebApplication.php
WebApplication.mapQueryToActionParameters
private function mapQueryToActionParameters(RouteEndpoint $route, RequestInterface $request) : array { $reflection = new ReflectionClass($route->getFullyQualifiedName()); $method = $reflection->getMethod($route->getAction(true)); $query = $request->getQuery(); $mapper = []; foreach ($method->getParameters() as $parameter) { $defaultValue = null; if ($parameter->isDefaultValueAvailable()) { $defaultValue = $parameter->getDefaultValue(); } $value = $query->get($parameter->getName(), $defaultValue); // We are missing a required parameter, so this is a bad request if ($value === null && !$parameter->allowsNull()) { throw HttpException::badRequest(); } $mapper[$parameter->getName()] = $value; } return $mapper; }
php
private function mapQueryToActionParameters(RouteEndpoint $route, RequestInterface $request) : array { $reflection = new ReflectionClass($route->getFullyQualifiedName()); $method = $reflection->getMethod($route->getAction(true)); $query = $request->getQuery(); $mapper = []; foreach ($method->getParameters() as $parameter) { $defaultValue = null; if ($parameter->isDefaultValueAvailable()) { $defaultValue = $parameter->getDefaultValue(); } $value = $query->get($parameter->getName(), $defaultValue); // We are missing a required parameter, so this is a bad request if ($value === null && !$parameter->allowsNull()) { throw HttpException::badRequest(); } $mapper[$parameter->getName()] = $value; } return $mapper; }
[ "private", "function", "mapQueryToActionParameters", "(", "RouteEndpoint", "$", "route", ",", "RequestInterface", "$", "request", ")", ":", "array", "{", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "route", "->", "getFullyQualifiedName", "(", ")", ")", ";", "$", "method", "=", "$", "reflection", "->", "getMethod", "(", "$", "route", "->", "getAction", "(", "true", ")", ")", ";", "$", "query", "=", "$", "request", "->", "getQuery", "(", ")", ";", "$", "mapper", "=", "[", "]", ";", "foreach", "(", "$", "method", "->", "getParameters", "(", ")", "as", "$", "parameter", ")", "{", "$", "defaultValue", "=", "null", ";", "if", "(", "$", "parameter", "->", "isDefaultValueAvailable", "(", ")", ")", "{", "$", "defaultValue", "=", "$", "parameter", "->", "getDefaultValue", "(", ")", ";", "}", "$", "value", "=", "$", "query", "->", "get", "(", "$", "parameter", "->", "getName", "(", ")", ",", "$", "defaultValue", ")", ";", "// We are missing a required parameter, so this is a bad request", "if", "(", "$", "value", "===", "null", "&&", "!", "$", "parameter", "->", "allowsNull", "(", ")", ")", "{", "throw", "HttpException", "::", "badRequest", "(", ")", ";", "}", "$", "mapper", "[", "$", "parameter", "->", "getName", "(", ")", "]", "=", "$", "value", ";", "}", "return", "$", "mapper", ";", "}" ]
Maps all the query parameters to the controller action parameters @param RouteEndpoint $route @return string[] @throws HttpException @throws ReflectionException
[ "Maps", "all", "the", "query", "parameters", "to", "the", "controller", "action", "parameters" ]
fa6165d3891a310faa580c81dee49a63c150c711
https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/WebApplication/WebApplication.php#L160-L184
train
kaiohken1982/Cropper
src/Cropper/Filter/File/ImageCrop.php
ImageCrop.setThumbnailer
protected function setThumbnailer(Thumbnailer $thumbnailer) { if(!$thumbnailer instanceof Thumbnailer) { throw new \Exception('The thumbnailer service given is not instance of Thumbnailer\Thumbnailer\Thumbnailer'); } $this->options['thumbnailer'] = $thumbnailer; return $this; }
php
protected function setThumbnailer(Thumbnailer $thumbnailer) { if(!$thumbnailer instanceof Thumbnailer) { throw new \Exception('The thumbnailer service given is not instance of Thumbnailer\Thumbnailer\Thumbnailer'); } $this->options['thumbnailer'] = $thumbnailer; return $this; }
[ "protected", "function", "setThumbnailer", "(", "Thumbnailer", "$", "thumbnailer", ")", "{", "if", "(", "!", "$", "thumbnailer", "instanceof", "Thumbnailer", ")", "{", "throw", "new", "\\", "Exception", "(", "'The thumbnailer service given is not instance of Thumbnailer\\Thumbnailer\\Thumbnailer'", ")", ";", "}", "$", "this", "->", "options", "[", "'thumbnailer'", "]", "=", "$", "thumbnailer", ";", "return", "$", "this", ";", "}" ]
Set the thumbnailer given with the options @throws \Exception @return Cropper\Filter\File\ImageCrop
[ "Set", "the", "thumbnailer", "given", "with", "the", "options" ]
5ec42136d085fdd4162ecca82c467fe9f7e6bdb0
https://github.com/kaiohken1982/Cropper/blob/5ec42136d085fdd4162ecca82c467fe9f7e6bdb0/src/Cropper/Filter/File/ImageCrop.php#L27-L35
train
native5/native5-sdk-client-php
src/Native5/Sessions/WebContext.php
WebContext.get
public function get($key) { if (array_key_exists($key, $this->_map)) { return $this->_map[$key]; } return null; }
php
public function get($key) { if (array_key_exists($key, $this->_map)) { return $this->_map[$key]; } return null; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "_map", ")", ")", "{", "return", "$", "this", "->", "_map", "[", "$", "key", "]", ";", "}", "return", "null", ";", "}" ]
Get attribute from web context. @param mixed $key The key to search for in the map. @access public @return void
[ "Get", "attribute", "from", "web", "context", "." ]
e1f598cf27654d81bb5facace1990b737242a2f9
https://github.com/native5/native5-sdk-client-php/blob/e1f598cf27654d81bb5facace1990b737242a2f9/src/Native5/Sessions/WebContext.php#L83-L91
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.query
public function query($name, $val = null) { return isset($this->_queries[$name]) ? $this->_queries[$name] : $val; }
php
public function query($name, $val = null) { return isset($this->_queries[$name]) ? $this->_queries[$name] : $val; }
[ "public", "function", "query", "(", "$", "name", ",", "$", "val", "=", "null", ")", "{", "return", "isset", "(", "$", "this", "->", "_queries", "[", "$", "name", "]", ")", "?", "$", "this", "->", "_queries", "[", "$", "name", "]", ":", "$", "val", ";", "}" ]
Get query string from url @access public @param string $name Input name @param string $val Default value if query doesn't exists @return mixed
[ "Get", "query", "string", "from", "url" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L126-L130
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.queries
public function queries(array $names, $default = null) { $var = []; foreach ($names as $in) { $var[$in] = isset($this->_queries[$in]) ? $this->_queries[$in] : $default; } return $var; }
php
public function queries(array $names, $default = null) { $var = []; foreach ($names as $in) { $var[$in] = isset($this->_queries[$in]) ? $this->_queries[$in] : $default; } return $var; }
[ "public", "function", "queries", "(", "array", "$", "names", ",", "$", "default", "=", "null", ")", "{", "$", "var", "=", "[", "]", ";", "foreach", "(", "$", "names", "as", "$", "in", ")", "{", "$", "var", "[", "$", "in", "]", "=", "isset", "(", "$", "this", "->", "_queries", "[", "$", "in", "]", ")", "?", "$", "this", "->", "_queries", "[", "$", "in", "]", ":", "$", "default", ";", "}", "return", "$", "var", ";", "}" ]
Getting querie from url parameters @access public @param array $name Query names @param mixed $default Default value @return array
[ "Getting", "querie", "from", "url", "parameters" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L141-L151
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.only
public function only(array $names, $default = null) { $var = []; foreach ($names as $in) { $var[$in] = isset($this->_requests[$in]) ? $this->_requests[$in] : $default; } return $var; }
php
public function only(array $names, $default = null) { $var = []; foreach ($names as $in) { $var[$in] = isset($this->_requests[$in]) ? $this->_requests[$in] : $default; } return $var; }
[ "public", "function", "only", "(", "array", "$", "names", ",", "$", "default", "=", "null", ")", "{", "$", "var", "=", "[", "]", ";", "foreach", "(", "$", "names", "as", "$", "in", ")", "{", "$", "var", "[", "$", "in", "]", "=", "isset", "(", "$", "this", "->", "_requests", "[", "$", "in", "]", ")", "?", "$", "this", "->", "_requests", "[", "$", "in", "]", ":", "$", "default", ";", "}", "return", "$", "var", ";", "}" ]
Getting segments of inputs @access public @param array $names Input names @param mixed $default Default value (null) @return array
[ "Getting", "segments", "of", "inputs" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L162-L172
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.except
public function except(array $name) { $var = []; foreach ($this->_requests as $k => $v) { if (!in_array($k, $name)) { $var[$k] = $v; } } return $var; }
php
public function except(array $name) { $var = []; foreach ($this->_requests as $k => $v) { if (!in_array($k, $name)) { $var[$k] = $v; } } return $var; }
[ "public", "function", "except", "(", "array", "$", "name", ")", "{", "$", "var", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "_requests", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "!", "in_array", "(", "$", "k", ",", "$", "name", ")", ")", "{", "$", "var", "[", "$", "k", "]", "=", "$", "v", ";", "}", "}", "return", "$", "var", ";", "}" ]
Get data input except some @access public @param array $name Input names @return array
[ "Get", "data", "input", "except", "some" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L182-L192
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.hasInputs
public function hasInputs(array $names) { foreach ($names as $name) { if (!$this->has($name)) return false; } return true; }
php
public function hasInputs(array $names) { foreach ($names as $name) { if (!$this->has($name)) return false; } return true; }
[ "public", "function", "hasInputs", "(", "array", "$", "names", ")", "{", "foreach", "(", "$", "names", "as", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "name", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if inputs are received @access public @param array $names Input names @return bool
[ "Check", "if", "inputs", "are", "received" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L226-L233
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.hasQueries
public function hasQueries(array $names) { foreach ($names as $name) { if (!$this->hasQuery($name)) return false; } return true; }
php
public function hasQueries(array $names) { foreach ($names as $name) { if (!$this->hasQuery($name)) return false; } return true; }
[ "public", "function", "hasQueries", "(", "array", "$", "names", ")", "{", "foreach", "(", "$", "names", "as", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "hasQuery", "(", "$", "name", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if queries exists @access public @param array $names Query names @return bool
[ "Check", "if", "queries", "exists" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L255-L262
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.url
public function url($component = -1) { $active_url = URL::here(); if ($component > -1) { return parse_url($active_url, $component); } return $active_url; }
php
public function url($component = -1) { $active_url = URL::here(); if ($component > -1) { return parse_url($active_url, $component); } return $active_url; }
[ "public", "function", "url", "(", "$", "component", "=", "-", "1", ")", "{", "$", "active_url", "=", "URL", "::", "here", "(", ")", ";", "if", "(", "$", "component", ">", "-", "1", ")", "{", "return", "parse_url", "(", "$", "active_url", ",", "$", "component", ")", ";", "}", "return", "$", "active_url", ";", "}" ]
Get request URL @access public @param int $component URL parse_url component @return string
[ "Get", "request", "URL" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L294-L301
train
jabernardo/lollipop-php
Library/HTTP/Request.php
Request.header
public function header($header) { foreach($this->_headers as $k => $v) { if (!strcasecmp($k, $header)) { return $v; } } return null; }
php
public function header($header) { foreach($this->_headers as $k => $v) { if (!strcasecmp($k, $header)) { return $v; } } return null; }
[ "public", "function", "header", "(", "$", "header", ")", "{", "foreach", "(", "$", "this", "->", "_headers", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "!", "strcasecmp", "(", "$", "k", ",", "$", "header", ")", ")", "{", "return", "$", "v", ";", "}", "}", "return", "null", ";", "}" ]
Get request header value @access public @param string $header Request header @return mixed `null` if header is not set
[ "Get", "request", "header", "value" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Request.php#L322-L330
train
AmaraLiving/php-onehydra
src/Amara/OneHydra/Api.php
Api.getPageResult
public function getPageResult($url, $attributes = []) { $request = new Request(); $request->setService(self::SERVICE_PAGE); $request->setParam('url', $url); $request->setAttributes($attributes); return $this->execute($request); }
php
public function getPageResult($url, $attributes = []) { $request = new Request(); $request->setService(self::SERVICE_PAGE); $request->setParam('url', $url); $request->setAttributes($attributes); return $this->execute($request); }
[ "public", "function", "getPageResult", "(", "$", "url", ",", "$", "attributes", "=", "[", "]", ")", "{", "$", "request", "=", "new", "Request", "(", ")", ";", "$", "request", "->", "setService", "(", "self", "::", "SERVICE_PAGE", ")", ";", "$", "request", "->", "setParam", "(", "'url'", ",", "$", "url", ")", ";", "$", "request", "->", "setAttributes", "(", "$", "attributes", ")", ";", "return", "$", "this", "->", "execute", "(", "$", "request", ")", ";", "}" ]
Get details for a page @param string $url @param array $attributes @return PageResult
[ "Get", "details", "for", "a", "page" ]
f2c3155c42c8c0bec8c0246feb2a5959a15b2406
https://github.com/AmaraLiving/php-onehydra/blob/f2c3155c42c8c0bec8c0246feb2a5959a15b2406/src/Amara/OneHydra/Api.php#L103-L112
train
AmaraLiving/php-onehydra
src/Amara/OneHydra/Api.php
Api.execute
public function execute(RequestInterface $request) { $httpRequest = $this->httpRequestBuilder->build($request); $httpResponse = $this->transport->execute($httpRequest); return $this->resultBuilderEngine->build($request, $httpResponse); }
php
public function execute(RequestInterface $request) { $httpRequest = $this->httpRequestBuilder->build($request); $httpResponse = $this->transport->execute($httpRequest); return $this->resultBuilderEngine->build($request, $httpResponse); }
[ "public", "function", "execute", "(", "RequestInterface", "$", "request", ")", "{", "$", "httpRequest", "=", "$", "this", "->", "httpRequestBuilder", "->", "build", "(", "$", "request", ")", ";", "$", "httpResponse", "=", "$", "this", "->", "transport", "->", "execute", "(", "$", "httpRequest", ")", ";", "return", "$", "this", "->", "resultBuilderEngine", "->", "build", "(", "$", "request", ",", "$", "httpResponse", ")", ";", "}" ]
Execute a OneHydra request and return the result @param RequestInterface $request @return ResultInterface @throws HttpTransportException
[ "Execute", "a", "OneHydra", "request", "and", "return", "the", "result" ]
f2c3155c42c8c0bec8c0246feb2a5959a15b2406
https://github.com/AmaraLiving/php-onehydra/blob/f2c3155c42c8c0bec8c0246feb2a5959a15b2406/src/Amara/OneHydra/Api.php#L121-L128
train
Aviogram/Common
src/ArrayUtils.php
ArrayUtils.targetGet
public static function targetGet($needle, array $haystack, $default = null) { if ($needle === null) { return $haystack; } $parts = preg_split('/(?<!\\\\)\./', $needle); foreach ($parts as $part) { $key = str_replace('\\.', '.', $part); if ( is_array($haystack) === false || array_key_exists($key, $haystack) === false ) { return $default; } $haystack = $haystack[$part]; } return $haystack; }
php
public static function targetGet($needle, array $haystack, $default = null) { if ($needle === null) { return $haystack; } $parts = preg_split('/(?<!\\\\)\./', $needle); foreach ($parts as $part) { $key = str_replace('\\.', '.', $part); if ( is_array($haystack) === false || array_key_exists($key, $haystack) === false ) { return $default; } $haystack = $haystack[$part]; } return $haystack; }
[ "public", "static", "function", "targetGet", "(", "$", "needle", ",", "array", "$", "haystack", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "needle", "===", "null", ")", "{", "return", "$", "haystack", ";", "}", "$", "parts", "=", "preg_split", "(", "'/(?<!\\\\\\\\)\\./'", ",", "$", "needle", ")", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "$", "key", "=", "str_replace", "(", "'\\\\.'", ",", "'.'", ",", "$", "part", ")", ";", "if", "(", "is_array", "(", "$", "haystack", ")", "===", "false", "||", "array_key_exists", "(", "$", "key", ",", "$", "haystack", ")", "===", "false", ")", "{", "return", "$", "default", ";", "}", "$", "haystack", "=", "$", "haystack", "[", "$", "part", "]", ";", "}", "return", "$", "haystack", ";", "}" ]
Get an value from an array via a dotted notation @param string $needle (my.scope.notation) Use \. to escape . characters @param array $haystack @param mixed $default @return mixed
[ "Get", "an", "value", "from", "an", "array", "via", "a", "dotted", "notation" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/ArrayUtils.php#L15-L37
train
Aviogram/Common
src/ArrayUtils.php
ArrayUtils.targetSet
public static function targetSet($needle, $value, array $haystack = array()) { $keys = explode('.', $needle); $loop = &$haystack; foreach ($keys as $key) { if (is_array($loop) === false) { $loop = array(); } if (array_key_exists($key, $loop) === false) { $loop[$key] = array(); } $loop = &$loop[$key]; } $loop = $value; return $haystack; }
php
public static function targetSet($needle, $value, array $haystack = array()) { $keys = explode('.', $needle); $loop = &$haystack; foreach ($keys as $key) { if (is_array($loop) === false) { $loop = array(); } if (array_key_exists($key, $loop) === false) { $loop[$key] = array(); } $loop = &$loop[$key]; } $loop = $value; return $haystack; }
[ "public", "static", "function", "targetSet", "(", "$", "needle", ",", "$", "value", ",", "array", "$", "haystack", "=", "array", "(", ")", ")", "{", "$", "keys", "=", "explode", "(", "'.'", ",", "$", "needle", ")", ";", "$", "loop", "=", "&", "$", "haystack", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "is_array", "(", "$", "loop", ")", "===", "false", ")", "{", "$", "loop", "=", "array", "(", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "loop", ")", "===", "false", ")", "{", "$", "loop", "[", "$", "key", "]", "=", "array", "(", ")", ";", "}", "$", "loop", "=", "&", "$", "loop", "[", "$", "key", "]", ";", "}", "$", "loop", "=", "$", "value", ";", "return", "$", "haystack", ";", "}" ]
Set an value on a multi dimensional array via a dotted string notation @param string $needle @param string $value @param array $haystack @return array
[ "Set", "an", "value", "on", "a", "multi", "dimensional", "array", "via", "a", "dotted", "string", "notation" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/ArrayUtils.php#L48-L68
train
covex-nn/JooS
src/JooS/Helper/Broker.php
Broker.__isset
public function __isset($helper) { if (isset($this->_helpers[$helper])) { $isset = true; } else { $isset = !is_null($this->_getHelper($helper)); } return $isset; }
php
public function __isset($helper) { if (isset($this->_helpers[$helper])) { $isset = true; } else { $isset = !is_null($this->_getHelper($helper)); } return $isset; }
[ "public", "function", "__isset", "(", "$", "helper", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_helpers", "[", "$", "helper", "]", ")", ")", "{", "$", "isset", "=", "true", ";", "}", "else", "{", "$", "isset", "=", "!", "is_null", "(", "$", "this", "->", "_getHelper", "(", "$", "helper", ")", ")", ";", "}", "return", "$", "isset", ";", "}" ]
Is helper presents ? @param string $helper Name @return boolean
[ "Is", "helper", "presents", "?" ]
8dfb94edccecaf307787d4091ba7f20a674b7792
https://github.com/covex-nn/JooS/blob/8dfb94edccecaf307787d4091ba7f20a674b7792/src/JooS/Helper/Broker.php#L87-L95
train
covex-nn/JooS
src/JooS/Helper/Broker.php
Broker._getHelper
private function _getHelper($helper) { $instance = null; foreach ($this->_prefixes as $prefix) { $className = $prefix . "\\" . $helper; if (Loader::loadClass($className)) { if (is_subclass_of($className, __NAMESPACE__ . "\\Helper_Interface")) { $instance = new $className(); /* @var $instance Helper_Interface */ $instance->setSubject($this->_subject); } break; } } return $instance; }
php
private function _getHelper($helper) { $instance = null; foreach ($this->_prefixes as $prefix) { $className = $prefix . "\\" . $helper; if (Loader::loadClass($className)) { if (is_subclass_of($className, __NAMESPACE__ . "\\Helper_Interface")) { $instance = new $className(); /* @var $instance Helper_Interface */ $instance->setSubject($this->_subject); } break; } } return $instance; }
[ "private", "function", "_getHelper", "(", "$", "helper", ")", "{", "$", "instance", "=", "null", ";", "foreach", "(", "$", "this", "->", "_prefixes", "as", "$", "prefix", ")", "{", "$", "className", "=", "$", "prefix", ".", "\"\\\\\"", ".", "$", "helper", ";", "if", "(", "Loader", "::", "loadClass", "(", "$", "className", ")", ")", "{", "if", "(", "is_subclass_of", "(", "$", "className", ",", "__NAMESPACE__", ".", "\"\\\\Helper_Interface\"", ")", ")", "{", "$", "instance", "=", "new", "$", "className", "(", ")", ";", "/* @var $instance Helper_Interface */", "$", "instance", "->", "setSubject", "(", "$", "this", "->", "_subject", ")", ";", "}", "break", ";", "}", "}", "return", "$", "instance", ";", "}" ]
Creates a new helper's instance @param string $helper Name @return Helper_Interface
[ "Creates", "a", "new", "helper", "s", "instance" ]
8dfb94edccecaf307787d4091ba7f20a674b7792
https://github.com/covex-nn/JooS/blob/8dfb94edccecaf307787d4091ba7f20a674b7792/src/JooS/Helper/Broker.php#L104-L119
train
covex-nn/JooS
src/JooS/Helper/Broker.php
Broker.prependPrefix
public function prependPrefix($prefix) { $this->deletePrefix($prefix); $prepend = array($prefix => $prefix); $this->_prefixes = array_merge($prepend, $this->_prefixes); }
php
public function prependPrefix($prefix) { $this->deletePrefix($prefix); $prepend = array($prefix => $prefix); $this->_prefixes = array_merge($prepend, $this->_prefixes); }
[ "public", "function", "prependPrefix", "(", "$", "prefix", ")", "{", "$", "this", "->", "deletePrefix", "(", "$", "prefix", ")", ";", "$", "prepend", "=", "array", "(", "$", "prefix", "=>", "$", "prefix", ")", ";", "$", "this", "->", "_prefixes", "=", "array_merge", "(", "$", "prepend", ",", "$", "this", "->", "_prefixes", ")", ";", "}" ]
Prepend namespace-prefix @param string $prefix Prefix @return null
[ "Prepend", "namespace", "-", "prefix" ]
8dfb94edccecaf307787d4091ba7f20a674b7792
https://github.com/covex-nn/JooS/blob/8dfb94edccecaf307787d4091ba7f20a674b7792/src/JooS/Helper/Broker.php#L156-L162
train
bseddon/XPath20
Value/HexBinaryValue.php
HexBinaryValue.fromString
public static function fromString( $string ) { // Make sure the string does not contain non-hex characters $matched = preg_match( "/[^0-9a-fA-F]+/", $string, $matches ); if ( $matched || strlen( $string ) % 2 != 0 ) { throw XPath2Exception::withErrorCodeAndParams( "FORG0001", Resources::InvalidFormat, array( $string, "xs:hexBinary" ) ); } $binary = hex2bin( $string ); return new HexBinaryValue( $binary ); }
php
public static function fromString( $string ) { // Make sure the string does not contain non-hex characters $matched = preg_match( "/[^0-9a-fA-F]+/", $string, $matches ); if ( $matched || strlen( $string ) % 2 != 0 ) { throw XPath2Exception::withErrorCodeAndParams( "FORG0001", Resources::InvalidFormat, array( $string, "xs:hexBinary" ) ); } $binary = hex2bin( $string ); return new HexBinaryValue( $binary ); }
[ "public", "static", "function", "fromString", "(", "$", "string", ")", "{", "// Make sure the string does not contain non-hex characters\r", "$", "matched", "=", "preg_match", "(", "\"/[^0-9a-fA-F]+/\"", ",", "$", "string", ",", "$", "matches", ")", ";", "if", "(", "$", "matched", "||", "strlen", "(", "$", "string", ")", "%", "2", "!=", "0", ")", "{", "throw", "XPath2Exception", "::", "withErrorCodeAndParams", "(", "\"FORG0001\"", ",", "Resources", "::", "InvalidFormat", ",", "array", "(", "$", "string", ",", "\"xs:hexBinary\"", ")", ")", ";", "}", "$", "binary", "=", "hex2bin", "(", "$", "string", ")", ";", "return", "new", "HexBinaryValue", "(", "$", "binary", ")", ";", "}" ]
Convert a string representation of a hex value to is binary version and create a HexBinaryValue instance @param unknown $string
[ "Convert", "a", "string", "representation", "of", "a", "hex", "value", "to", "is", "binary", "version", "and", "create", "a", "HexBinaryValue", "instance" ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/HexBinaryValue.php#L65-L76
train
romm/configuration_object
Classes/Service/Items/Parents/ParentsUtility.php
ParentsUtility.classUsesParentsTrait
public function classUsesParentsTrait($className) { if (is_object($className)) { $className = get_class($className); } if (false === isset($this->classUsingParentsTrait[$className])) { $this->classUsingParentsTrait[$className] = $this->checkClassUsesParentsTrait($className); } return $this->classUsingParentsTrait[$className]; }
php
public function classUsesParentsTrait($className) { if (is_object($className)) { $className = get_class($className); } if (false === isset($this->classUsingParentsTrait[$className])) { $this->classUsingParentsTrait[$className] = $this->checkClassUsesParentsTrait($className); } return $this->classUsingParentsTrait[$className]; }
[ "public", "function", "classUsesParentsTrait", "(", "$", "className", ")", "{", "if", "(", "is_object", "(", "$", "className", ")", ")", "{", "$", "className", "=", "get_class", "(", "$", "className", ")", ";", "}", "if", "(", "false", "===", "isset", "(", "$", "this", "->", "classUsingParentsTrait", "[", "$", "className", "]", ")", ")", "{", "$", "this", "->", "classUsingParentsTrait", "[", "$", "className", "]", "=", "$", "this", "->", "checkClassUsesParentsTrait", "(", "$", "className", ")", ";", "}", "return", "$", "this", "->", "classUsingParentsTrait", "[", "$", "className", "]", ";", "}" ]
Will check and store the class names which use the trait `ParentsTrait`. @param string|object $className @return bool
[ "Will", "check", "and", "store", "the", "class", "names", "which", "use", "the", "trait", "ParentsTrait", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Service/Items/Parents/ParentsUtility.php#L35-L46
train
romm/configuration_object
Classes/Service/Items/Parents/ParentsUtility.php
ParentsUtility.checkClassUsesParentsTrait
protected function checkClassUsesParentsTrait($className) { $flag = false; $classes = array_merge([$className], class_parents($className)); foreach ($classes as $class) { $traits = class_uses($class); $flag = $flag || (true === isset($traits[ParentsTrait::class])); } return $flag; }
php
protected function checkClassUsesParentsTrait($className) { $flag = false; $classes = array_merge([$className], class_parents($className)); foreach ($classes as $class) { $traits = class_uses($class); $flag = $flag || (true === isset($traits[ParentsTrait::class])); } return $flag; }
[ "protected", "function", "checkClassUsesParentsTrait", "(", "$", "className", ")", "{", "$", "flag", "=", "false", ";", "$", "classes", "=", "array_merge", "(", "[", "$", "className", "]", ",", "class_parents", "(", "$", "className", ")", ")", ";", "foreach", "(", "$", "classes", "as", "$", "class", ")", "{", "$", "traits", "=", "class_uses", "(", "$", "class", ")", ";", "$", "flag", "=", "$", "flag", "||", "(", "true", "===", "isset", "(", "$", "traits", "[", "ParentsTrait", "::", "class", "]", ")", ")", ";", "}", "return", "$", "flag", ";", "}" ]
Will check if the given class name uses the trait `ParentsTrait`. @param string $className @return bool
[ "Will", "check", "if", "the", "given", "class", "name", "uses", "the", "trait", "ParentsTrait", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Service/Items/Parents/ParentsUtility.php#L54-L65
train
freialib/hlin.archetype
src/Trait/CLI.php
CLITrait.ask
function ask($question, array $answers) { // question loop $optstr = implode("|", $answers); do { $this->printf("$question [$optstr] "); $answer = $this->fgets(); } while ( ! in_array($answer, $answers)); return $answer; }
php
function ask($question, array $answers) { // question loop $optstr = implode("|", $answers); do { $this->printf("$question [$optstr] "); $answer = $this->fgets(); } while ( ! in_array($answer, $answers)); return $answer; }
[ "function", "ask", "(", "$", "question", ",", "array", "$", "answers", ")", "{", "// question loop", "$", "optstr", "=", "implode", "(", "\"|\"", ",", "$", "answers", ")", ";", "do", "{", "$", "this", "->", "printf", "(", "\"$question [$optstr] \"", ")", ";", "$", "answer", "=", "$", "this", "->", "fgets", "(", ")", ";", "}", "while", "(", "!", "in_array", "(", "$", "answer", ",", "$", "answers", ")", ")", ";", "return", "$", "answer", ";", "}" ]
Shorthand for retrieving confirmation from console. Common console task for input. @return string answer
[ "Shorthand", "for", "retrieving", "confirmation", "from", "console", ".", "Common", "console", "task", "for", "input", "." ]
d8750a9bf4b7efb8063899969e3f39c1915c423a
https://github.com/freialib/hlin.archetype/blob/d8750a9bf4b7efb8063899969e3f39c1915c423a/src/Trait/CLI.php#L85-L95
train
AlexyaFramework/Tools
Alexya/Tools/Inflector.php
Inflector.plural
public static function plural(string $word) : string { // Check that `$word` is countable. if(in_array($word, Inflector::$_uncontable)) { return $word; } // Now check that `$word` is regular. if(isset(Inflector::$_plural["irregular"][$word])) { return Inflector::$_plural["irregular"][$word]; } // Now check that `$word` can be pluralize. foreach(Inflector::$_plural["uninflected"] as $rule) { if(preg_match("/^". $rule ."$/", $word)) { return $word; } } // Now the word follows a rule, so apply it foreach(Inflector::$_plural["rules"] as $key => $value) { if(preg_match($key, $word)) { return preg_replace($key, $value, $word); } } // Well, right now the word couldn't be pluralized // so return it as it was (or throw an exception?) return $word; }
php
public static function plural(string $word) : string { // Check that `$word` is countable. if(in_array($word, Inflector::$_uncontable)) { return $word; } // Now check that `$word` is regular. if(isset(Inflector::$_plural["irregular"][$word])) { return Inflector::$_plural["irregular"][$word]; } // Now check that `$word` can be pluralize. foreach(Inflector::$_plural["uninflected"] as $rule) { if(preg_match("/^". $rule ."$/", $word)) { return $word; } } // Now the word follows a rule, so apply it foreach(Inflector::$_plural["rules"] as $key => $value) { if(preg_match($key, $word)) { return preg_replace($key, $value, $word); } } // Well, right now the word couldn't be pluralized // so return it as it was (or throw an exception?) return $word; }
[ "public", "static", "function", "plural", "(", "string", "$", "word", ")", ":", "string", "{", "// Check that `$word` is countable.", "if", "(", "in_array", "(", "$", "word", ",", "Inflector", "::", "$", "_uncontable", ")", ")", "{", "return", "$", "word", ";", "}", "// Now check that `$word` is regular.", "if", "(", "isset", "(", "Inflector", "::", "$", "_plural", "[", "\"irregular\"", "]", "[", "$", "word", "]", ")", ")", "{", "return", "Inflector", "::", "$", "_plural", "[", "\"irregular\"", "]", "[", "$", "word", "]", ";", "}", "// Now check that `$word` can be pluralize.", "foreach", "(", "Inflector", "::", "$", "_plural", "[", "\"uninflected\"", "]", "as", "$", "rule", ")", "{", "if", "(", "preg_match", "(", "\"/^\"", ".", "$", "rule", ".", "\"$/\"", ",", "$", "word", ")", ")", "{", "return", "$", "word", ";", "}", "}", "// Now the word follows a rule, so apply it", "foreach", "(", "Inflector", "::", "$", "_plural", "[", "\"rules\"", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "preg_match", "(", "$", "key", ",", "$", "word", ")", ")", "{", "return", "preg_replace", "(", "$", "key", ",", "$", "value", ",", "$", "word", ")", ";", "}", "}", "// Well, right now the word couldn't be pluralized", "// so return it as it was (or throw an exception?)", "return", "$", "word", ";", "}" ]
Returns the plural form of the word. @param string $word Word to pluralize. @return string The plural form of `$word`.
[ "Returns", "the", "plural", "form", "of", "the", "word", "." ]
2ae7c91cde0517579b926dd872eaf7ea324fd1e4
https://github.com/AlexyaFramework/Tools/blob/2ae7c91cde0517579b926dd872eaf7ea324fd1e4/Alexya/Tools/Inflector.php#L307-L336
train
AlexyaFramework/Tools
Alexya/Tools/Inflector.php
Inflector.singular
public static function singular(string $word) : string { // Check that `$word` is countable. if(in_array($word, Inflector::$_uncontable)) { return $word; } // Now check that `$word` is regular. if(isset(Inflector::$_singular["irregular"][$word])) { return Inflector::$_singular["irregular"][$word]; } // Now check that `$word` can be singularize. foreach(Inflector::$_singular["uninflected"] as $rule) { if(preg_match("/^". $rule ."$/", $word)) { return $word; } } // Now the word follows a rule, so apply it foreach(Inflector::$_singular["rules"] as $key => $value) { if(preg_match($key, $word)) { return preg_replace($key, $value, $word); } } // Well, right now the word couldn't be singularized // so return it as it was (or throw an exception?) return $word; }
php
public static function singular(string $word) : string { // Check that `$word` is countable. if(in_array($word, Inflector::$_uncontable)) { return $word; } // Now check that `$word` is regular. if(isset(Inflector::$_singular["irregular"][$word])) { return Inflector::$_singular["irregular"][$word]; } // Now check that `$word` can be singularize. foreach(Inflector::$_singular["uninflected"] as $rule) { if(preg_match("/^". $rule ."$/", $word)) { return $word; } } // Now the word follows a rule, so apply it foreach(Inflector::$_singular["rules"] as $key => $value) { if(preg_match($key, $word)) { return preg_replace($key, $value, $word); } } // Well, right now the word couldn't be singularized // so return it as it was (or throw an exception?) return $word; }
[ "public", "static", "function", "singular", "(", "string", "$", "word", ")", ":", "string", "{", "// Check that `$word` is countable.", "if", "(", "in_array", "(", "$", "word", ",", "Inflector", "::", "$", "_uncontable", ")", ")", "{", "return", "$", "word", ";", "}", "// Now check that `$word` is regular.", "if", "(", "isset", "(", "Inflector", "::", "$", "_singular", "[", "\"irregular\"", "]", "[", "$", "word", "]", ")", ")", "{", "return", "Inflector", "::", "$", "_singular", "[", "\"irregular\"", "]", "[", "$", "word", "]", ";", "}", "// Now check that `$word` can be singularize.", "foreach", "(", "Inflector", "::", "$", "_singular", "[", "\"uninflected\"", "]", "as", "$", "rule", ")", "{", "if", "(", "preg_match", "(", "\"/^\"", ".", "$", "rule", ".", "\"$/\"", ",", "$", "word", ")", ")", "{", "return", "$", "word", ";", "}", "}", "// Now the word follows a rule, so apply it", "foreach", "(", "Inflector", "::", "$", "_singular", "[", "\"rules\"", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "preg_match", "(", "$", "key", ",", "$", "word", ")", ")", "{", "return", "preg_replace", "(", "$", "key", ",", "$", "value", ",", "$", "word", ")", ";", "}", "}", "// Well, right now the word couldn't be singularized", "// so return it as it was (or throw an exception?)", "return", "$", "word", ";", "}" ]
Returns the singular form of the word. @param string $word Word to singularize. @return string The singular form of `$word`.
[ "Returns", "the", "singular", "form", "of", "the", "word", "." ]
2ae7c91cde0517579b926dd872eaf7ea324fd1e4
https://github.com/AlexyaFramework/Tools/blob/2ae7c91cde0517579b926dd872eaf7ea324fd1e4/Alexya/Tools/Inflector.php#L345-L374
train
Wedeto/Auth
src/PasswordGenerator.php
PasswordGenerator.addCharacters
public function addCharacters($chars) { if (WF::is_array_like($chars)) { foreach ($chars as $char) { if (!is_string($char)) throw new InvalidArgumentException("Invalid type: " . WF::str($chars)); $this->characters[$char] = true; } } elseif (is_string($chars)) { for ($i = 0; $i < mb_strlen($chars); ++$i) $this->characters[mb_substr($chars, $i, 1)] = true; } else { throw new InvalidArgumentException("Invalid type: " . WF::str($chars)); } return $this; }
php
public function addCharacters($chars) { if (WF::is_array_like($chars)) { foreach ($chars as $char) { if (!is_string($char)) throw new InvalidArgumentException("Invalid type: " . WF::str($chars)); $this->characters[$char] = true; } } elseif (is_string($chars)) { for ($i = 0; $i < mb_strlen($chars); ++$i) $this->characters[mb_substr($chars, $i, 1)] = true; } else { throw new InvalidArgumentException("Invalid type: " . WF::str($chars)); } return $this; }
[ "public", "function", "addCharacters", "(", "$", "chars", ")", "{", "if", "(", "WF", "::", "is_array_like", "(", "$", "chars", ")", ")", "{", "foreach", "(", "$", "chars", "as", "$", "char", ")", "{", "if", "(", "!", "is_string", "(", "$", "char", ")", ")", "throw", "new", "InvalidArgumentException", "(", "\"Invalid type: \"", ".", "WF", "::", "str", "(", "$", "chars", ")", ")", ";", "$", "this", "->", "characters", "[", "$", "char", "]", "=", "true", ";", "}", "}", "elseif", "(", "is_string", "(", "$", "chars", ")", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "mb_strlen", "(", "$", "chars", ")", ";", "++", "$", "i", ")", "$", "this", "->", "characters", "[", "mb_substr", "(", "$", "chars", ",", "$", "i", ",", "1", ")", "]", "=", "true", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid type: \"", ".", "WF", "::", "str", "(", "$", "chars", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Add one or more characters to the list of eligible characters @param string|array $chars The characters to add @return Wedeto\Auth\PasswordGenerator Provides fluent interface
[ "Add", "one", "or", "more", "characters", "to", "the", "list", "of", "eligible", "characters" ]
d53777d860a9e67154b84b425e29da5d4dcd28e0
https://github.com/Wedeto/Auth/blob/d53777d860a9e67154b84b425e29da5d4dcd28e0/src/PasswordGenerator.php#L51-L72
train
Wedeto/Auth
src/PasswordGenerator.php
PasswordGenerator.generatePassword
public function generatePassword(int $length = 8) { if ($length <= 0) throw new DomainException("Cannot generate zero-length passwords"); if (empty($this->characters)) throw new UnderflowException("First add characters used to generate the password"); $chars = implode('', array_keys($this->characters)); $max_val = mb_strlen($chars) - 1; $pwd = ""; for ($i = 0; $i < $length; ++$i) { $pos = random_int(0, $max_val); $pwd .= mb_substr($chars, $pos, 1); } return $pwd; }
php
public function generatePassword(int $length = 8) { if ($length <= 0) throw new DomainException("Cannot generate zero-length passwords"); if (empty($this->characters)) throw new UnderflowException("First add characters used to generate the password"); $chars = implode('', array_keys($this->characters)); $max_val = mb_strlen($chars) - 1; $pwd = ""; for ($i = 0; $i < $length; ++$i) { $pos = random_int(0, $max_val); $pwd .= mb_substr($chars, $pos, 1); } return $pwd; }
[ "public", "function", "generatePassword", "(", "int", "$", "length", "=", "8", ")", "{", "if", "(", "$", "length", "<=", "0", ")", "throw", "new", "DomainException", "(", "\"Cannot generate zero-length passwords\"", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "characters", ")", ")", "throw", "new", "UnderflowException", "(", "\"First add characters used to generate the password\"", ")", ";", "$", "chars", "=", "implode", "(", "''", ",", "array_keys", "(", "$", "this", "->", "characters", ")", ")", ";", "$", "max_val", "=", "mb_strlen", "(", "$", "chars", ")", "-", "1", ";", "$", "pwd", "=", "\"\"", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "++", "$", "i", ")", "{", "$", "pos", "=", "random_int", "(", "0", ",", "$", "max_val", ")", ";", "$", "pwd", ".=", "mb_substr", "(", "$", "chars", ",", "$", "pos", ",", "1", ")", ";", "}", "return", "$", "pwd", ";", "}" ]
Generate a password of the specified length
[ "Generate", "a", "password", "of", "the", "specified", "length" ]
d53777d860a9e67154b84b425e29da5d4dcd28e0
https://github.com/Wedeto/Auth/blob/d53777d860a9e67154b84b425e29da5d4dcd28e0/src/PasswordGenerator.php#L104-L121
train
Wedeto/Auth
src/PasswordGenerator.php
PasswordGenerator.loadDictionary
public function loadDictionary(string $filename, $append = false, $regexp = "/^[a-z]{4,6}$/") { if (!file_exists($filename) || !is_readable($filename)) { $orig = $filename; $filename = "/usr/share/dict/" . $filename; if (!file_exists($filename)) throw new IOException("Cannot open file $orig and dictionary $filename does not exist"); } $cnt = mime_content_type($filename); if (substr($cnt, 0, 4) !== "text") throw new IOException("$filename does not appear to contain text"); $contents = file_get_contents($filename); $lines = explode("\n", $contents); if (!$append) $this->dictionary = array(); $nwords = 0; $wrapper = new ErrorInterceptor('preg_match'); $wrapper->registerError(E_WARNING, 'preg_match'); foreach ($lines as $line) { if (empty($regexp) || $wrapper->execute($regexp, $line)) { $this->dictionary[] = $line; ++$nwords; } if (count($wrapper->getInterceptedErrors())) throw new InvalidArgumentException("Invalid regexp: $regexp"); } if ($nwords === 0) throw new InvalidArgumentException("File $filename contains no words that match $regexp"); return $this; }
php
public function loadDictionary(string $filename, $append = false, $regexp = "/^[a-z]{4,6}$/") { if (!file_exists($filename) || !is_readable($filename)) { $orig = $filename; $filename = "/usr/share/dict/" . $filename; if (!file_exists($filename)) throw new IOException("Cannot open file $orig and dictionary $filename does not exist"); } $cnt = mime_content_type($filename); if (substr($cnt, 0, 4) !== "text") throw new IOException("$filename does not appear to contain text"); $contents = file_get_contents($filename); $lines = explode("\n", $contents); if (!$append) $this->dictionary = array(); $nwords = 0; $wrapper = new ErrorInterceptor('preg_match'); $wrapper->registerError(E_WARNING, 'preg_match'); foreach ($lines as $line) { if (empty($regexp) || $wrapper->execute($regexp, $line)) { $this->dictionary[] = $line; ++$nwords; } if (count($wrapper->getInterceptedErrors())) throw new InvalidArgumentException("Invalid regexp: $regexp"); } if ($nwords === 0) throw new InvalidArgumentException("File $filename contains no words that match $regexp"); return $this; }
[ "public", "function", "loadDictionary", "(", "string", "$", "filename", ",", "$", "append", "=", "false", ",", "$", "regexp", "=", "\"/^[a-z]{4,6}$/\"", ")", "{", "if", "(", "!", "file_exists", "(", "$", "filename", ")", "||", "!", "is_readable", "(", "$", "filename", ")", ")", "{", "$", "orig", "=", "$", "filename", ";", "$", "filename", "=", "\"/usr/share/dict/\"", ".", "$", "filename", ";", "if", "(", "!", "file_exists", "(", "$", "filename", ")", ")", "throw", "new", "IOException", "(", "\"Cannot open file $orig and dictionary $filename does not exist\"", ")", ";", "}", "$", "cnt", "=", "mime_content_type", "(", "$", "filename", ")", ";", "if", "(", "substr", "(", "$", "cnt", ",", "0", ",", "4", ")", "!==", "\"text\"", ")", "throw", "new", "IOException", "(", "\"$filename does not appear to contain text\"", ")", ";", "$", "contents", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "$", "contents", ")", ";", "if", "(", "!", "$", "append", ")", "$", "this", "->", "dictionary", "=", "array", "(", ")", ";", "$", "nwords", "=", "0", ";", "$", "wrapper", "=", "new", "ErrorInterceptor", "(", "'preg_match'", ")", ";", "$", "wrapper", "->", "registerError", "(", "E_WARNING", ",", "'preg_match'", ")", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "if", "(", "empty", "(", "$", "regexp", ")", "||", "$", "wrapper", "->", "execute", "(", "$", "regexp", ",", "$", "line", ")", ")", "{", "$", "this", "->", "dictionary", "[", "]", "=", "$", "line", ";", "++", "$", "nwords", ";", "}", "if", "(", "count", "(", "$", "wrapper", "->", "getInterceptedErrors", "(", ")", ")", ")", "throw", "new", "InvalidArgumentException", "(", "\"Invalid regexp: $regexp\"", ")", ";", "}", "if", "(", "$", "nwords", "===", "0", ")", "throw", "new", "InvalidArgumentException", "(", "\"File $filename contains no words that match $regexp\"", ")", ";", "return", "$", "this", ";", "}" ]
Load a dictionary file for passphrase generation @param string $filename The file to read. Can be a full path or a name of a dictionary in /usr/share/dict @param bool $append True to add to the list of words, false to replace it. Defauls to false @param string $regexp A regular expression to match each word to. Can be empty. Defaults to allowing on lowercase latin alphabet. @return Wedeto\Auth\PasswordGenerator Provides fluent interface @throws InvalidArgumentException When an invalid regular expression is given or no words match it. @throws Wedeto\IOException When the file is not readable
[ "Load", "a", "dictionary", "file", "for", "passphrase", "generation" ]
d53777d860a9e67154b84b425e29da5d4dcd28e0
https://github.com/Wedeto/Auth/blob/d53777d860a9e67154b84b425e29da5d4dcd28e0/src/PasswordGenerator.php#L136-L176
train
Wedeto/Auth
src/PasswordGenerator.php
PasswordGenerator.generatePassphrase
public function generatePassphrase($num_words = 4) { if (count($this->dictionary) < $num_words) { throw new UnderflowException( "Not enough words loaded to generate a passphrase of $num_words words" ); } $words = array(); $attempt = 0; while (count($words) < $num_words) { ++$attempt; $s = random_int(0, count($this->dictionary) - 1); $word = $this->dictionary[$s]; if (!in_array($word, $words) || $attempt > 4 * $num_words) $words[] = $word; } return implode(" ", $words); }
php
public function generatePassphrase($num_words = 4) { if (count($this->dictionary) < $num_words) { throw new UnderflowException( "Not enough words loaded to generate a passphrase of $num_words words" ); } $words = array(); $attempt = 0; while (count($words) < $num_words) { ++$attempt; $s = random_int(0, count($this->dictionary) - 1); $word = $this->dictionary[$s]; if (!in_array($word, $words) || $attempt > 4 * $num_words) $words[] = $word; } return implode(" ", $words); }
[ "public", "function", "generatePassphrase", "(", "$", "num_words", "=", "4", ")", "{", "if", "(", "count", "(", "$", "this", "->", "dictionary", ")", "<", "$", "num_words", ")", "{", "throw", "new", "UnderflowException", "(", "\"Not enough words loaded to generate a passphrase of $num_words words\"", ")", ";", "}", "$", "words", "=", "array", "(", ")", ";", "$", "attempt", "=", "0", ";", "while", "(", "count", "(", "$", "words", ")", "<", "$", "num_words", ")", "{", "++", "$", "attempt", ";", "$", "s", "=", "random_int", "(", "0", ",", "count", "(", "$", "this", "->", "dictionary", ")", "-", "1", ")", ";", "$", "word", "=", "$", "this", "->", "dictionary", "[", "$", "s", "]", ";", "if", "(", "!", "in_array", "(", "$", "word", ",", "$", "words", ")", "||", "$", "attempt", ">", "4", "*", "$", "num_words", ")", "$", "words", "[", "]", "=", "$", "word", ";", "}", "return", "implode", "(", "\" \"", ",", "$", "words", ")", ";", "}" ]
Generate a passphrase of the specified amount of words @param int $num_words The number of words in the passphase @retuern string The generated passprase @throws UnderflowException If no or not enough words have been loaded
[ "Generate", "a", "passphrase", "of", "the", "specified", "amount", "of", "words" ]
d53777d860a9e67154b84b425e29da5d4dcd28e0
https://github.com/Wedeto/Auth/blob/d53777d860a9e67154b84b425e29da5d4dcd28e0/src/PasswordGenerator.php#L184-L204
train
juliangut/mapping
src/Metadata/MetadataResolver.php
MetadataResolver.normalizeMappingSources
protected function normalizeMappingSources(array $mappingSources): array { return \array_map( function ($mappingSource): array { if (!\is_array($mappingSource)) { $mappingSource = [ 'type' => DriverFactoryInterface::DRIVER_ANNOTATION, 'path' => $mappingSource, ]; } return $mappingSource; }, $mappingSources ); }
php
protected function normalizeMappingSources(array $mappingSources): array { return \array_map( function ($mappingSource): array { if (!\is_array($mappingSource)) { $mappingSource = [ 'type' => DriverFactoryInterface::DRIVER_ANNOTATION, 'path' => $mappingSource, ]; } return $mappingSource; }, $mappingSources ); }
[ "protected", "function", "normalizeMappingSources", "(", "array", "$", "mappingSources", ")", ":", "array", "{", "return", "\\", "array_map", "(", "function", "(", "$", "mappingSource", ")", ":", "array", "{", "if", "(", "!", "\\", "is_array", "(", "$", "mappingSource", ")", ")", "{", "$", "mappingSource", "=", "[", "'type'", "=>", "DriverFactoryInterface", "::", "DRIVER_ANNOTATION", ",", "'path'", "=>", "$", "mappingSource", ",", "]", ";", "}", "return", "$", "mappingSource", ";", "}", ",", "$", "mappingSources", ")", ";", "}" ]
Normalize mapping sources format. @param mixed[] $mappingSources @return string[][]
[ "Normalize", "mapping", "sources", "format", "." ]
1830ff84c054d8e3759df170a5664a97f7070be9
https://github.com/juliangut/mapping/blob/1830ff84c054d8e3759df170a5664a97f7070be9/src/Metadata/MetadataResolver.php#L113-L128
train
agentmedia/phine-core
src/Core/Snippets/FormParts/PageUrlSelector.php
PageUrlSelector.RenderScript
function RenderScript() { $templateFile = Path::RemoveExtension($this->TemplateFile()); $scriptFile = Path::AddExtension($templateFile, 'Script'); ob_start(); require Path::AddExtension($scriptFile, 'phtml'); return ob_get_clean(); }
php
function RenderScript() { $templateFile = Path::RemoveExtension($this->TemplateFile()); $scriptFile = Path::AddExtension($templateFile, 'Script'); ob_start(); require Path::AddExtension($scriptFile, 'phtml'); return ob_get_clean(); }
[ "function", "RenderScript", "(", ")", "{", "$", "templateFile", "=", "Path", "::", "RemoveExtension", "(", "$", "this", "->", "TemplateFile", "(", ")", ")", ";", "$", "scriptFile", "=", "Path", "::", "AddExtension", "(", "$", "templateFile", ",", "'Script'", ")", ";", "ob_start", "(", ")", ";", "require", "Path", "::", "AddExtension", "(", "$", "scriptFile", ",", "'phtml'", ")", ";", "return", "ob_get_clean", "(", ")", ";", "}" ]
Renderst necessary javascript @return string Returns javascript for html output
[ "Renderst", "necessary", "javascript" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/FormParts/PageUrlSelector.php#L168-L175
train
agentmedia/phine-core
src/Core/Snippets/FormParts/PageUrlSelector.php
PageUrlSelector.Check
public function Check($data) { $value = $data[$this->prefix . 'Page']; return $this->pageField->Check($value); }
php
public function Check($data) { $value = $data[$this->prefix . 'Page']; return $this->pageField->Check($value); }
[ "public", "function", "Check", "(", "$", "data", ")", "{", "$", "value", "=", "$", "data", "[", "$", "this", "->", "prefix", ".", "'Page'", "]", ";", "return", "$", "this", "->", "pageField", "->", "Check", "(", "$", "value", ")", ";", "}" ]
Check the selector @param array $data
[ "Check", "the", "selector" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/FormParts/PageUrlSelector.php#L203-L207
train
agentmedia/phine-core
src/Core/Snippets/FormParts/PageUrlSelector.php
PageUrlSelector.Save
public function Save(PageUrl $pageUrl = null) { $exists = $pageUrl && $pageUrl->Exists(); $page = $this->Value('Page') ? Page::Schema()->ByID($this->Value('Page')) : null; if (!$page) { if ($exists) { $pageUrl->Delete(); } return null; } if (!$exists) { $pageUrl = new PageUrl(); } $pageUrl->SetPage($page); $pageUrl->SetFragment($this->Value('Fragment')); $pageUrl->Save(); $this->SaveParams($pageUrl); return $pageUrl; }
php
public function Save(PageUrl $pageUrl = null) { $exists = $pageUrl && $pageUrl->Exists(); $page = $this->Value('Page') ? Page::Schema()->ByID($this->Value('Page')) : null; if (!$page) { if ($exists) { $pageUrl->Delete(); } return null; } if (!$exists) { $pageUrl = new PageUrl(); } $pageUrl->SetPage($page); $pageUrl->SetFragment($this->Value('Fragment')); $pageUrl->Save(); $this->SaveParams($pageUrl); return $pageUrl; }
[ "public", "function", "Save", "(", "PageUrl", "$", "pageUrl", "=", "null", ")", "{", "$", "exists", "=", "$", "pageUrl", "&&", "$", "pageUrl", "->", "Exists", "(", ")", ";", "$", "page", "=", "$", "this", "->", "Value", "(", "'Page'", ")", "?", "Page", "::", "Schema", "(", ")", "->", "ByID", "(", "$", "this", "->", "Value", "(", "'Page'", ")", ")", ":", "null", ";", "if", "(", "!", "$", "page", ")", "{", "if", "(", "$", "exists", ")", "{", "$", "pageUrl", "->", "Delete", "(", ")", ";", "}", "return", "null", ";", "}", "if", "(", "!", "$", "exists", ")", "{", "$", "pageUrl", "=", "new", "PageUrl", "(", ")", ";", "}", "$", "pageUrl", "->", "SetPage", "(", "$", "page", ")", ";", "$", "pageUrl", "->", "SetFragment", "(", "$", "this", "->", "Value", "(", "'Fragment'", ")", ")", ";", "$", "pageUrl", "->", "Save", "(", ")", ";", "$", "this", "->", "SaveParams", "(", "$", "pageUrl", ")", ";", "return", "$", "pageUrl", ";", "}" ]
Saves the page url and returns it @param PageUrl $pageUrl The page url @return PageUrl Returns the page url with properties attached
[ "Saves", "the", "page", "url", "and", "returns", "it" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/FormParts/PageUrlSelector.php#L240-L258
train
agentmedia/phine-core
src/Core/Snippets/FormParts/PageUrlSelector.php
PageUrlSelector.SaveParams
private function SaveParams(PageUrl $pageUrl) { $this->ClearParams($pageUrl); $params = $this->serializer->LinesToArray($this->Value('Params')); $prev = null; foreach ($params as $name => $value) { $param = new PageUrlParameter(); $param->SetPageUrl($pageUrl); $param->SetPrevious($prev); $param->SetName($name); $param->SetValue($value); $param->Save(); $prev = $param; } }
php
private function SaveParams(PageUrl $pageUrl) { $this->ClearParams($pageUrl); $params = $this->serializer->LinesToArray($this->Value('Params')); $prev = null; foreach ($params as $name => $value) { $param = new PageUrlParameter(); $param->SetPageUrl($pageUrl); $param->SetPrevious($prev); $param->SetName($name); $param->SetValue($value); $param->Save(); $prev = $param; } }
[ "private", "function", "SaveParams", "(", "PageUrl", "$", "pageUrl", ")", "{", "$", "this", "->", "ClearParams", "(", "$", "pageUrl", ")", ";", "$", "params", "=", "$", "this", "->", "serializer", "->", "LinesToArray", "(", "$", "this", "->", "Value", "(", "'Params'", ")", ")", ";", "$", "prev", "=", "null", ";", "foreach", "(", "$", "params", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "param", "=", "new", "PageUrlParameter", "(", ")", ";", "$", "param", "->", "SetPageUrl", "(", "$", "pageUrl", ")", ";", "$", "param", "->", "SetPrevious", "(", "$", "prev", ")", ";", "$", "param", "->", "SetName", "(", "$", "name", ")", ";", "$", "param", "->", "SetValue", "(", "$", "value", ")", ";", "$", "param", "->", "Save", "(", ")", ";", "$", "prev", "=", "$", "param", ";", "}", "}" ]
Saves the page paramters after the page url is saved @param PageUrl $pageUrl The page url
[ "Saves", "the", "page", "paramters", "after", "the", "page", "url", "is", "saved" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/FormParts/PageUrlSelector.php#L264-L278
train
agentmedia/phine-core
src/Core/Snippets/FormParts/PageUrlSelector.php
PageUrlSelector.Value
private function Value($name) { $value = Request::PostData($this->prefix . $name); return Str::Trim($value); }
php
private function Value($name) { $value = Request::PostData($this->prefix . $name); return Str::Trim($value); }
[ "private", "function", "Value", "(", "$", "name", ")", "{", "$", "value", "=", "Request", "::", "PostData", "(", "$", "this", "->", "prefix", ".", "$", "name", ")", ";", "return", "Str", "::", "Trim", "(", "$", "value", ")", ";", "}" ]
Gets the value by pure name @param string $name The name without prefix @return string Returns the value
[ "Gets", "the", "value", "by", "pure", "name" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/FormParts/PageUrlSelector.php#L285-L289
train
agentmedia/phine-core
src/Core/Snippets/FormParts/PageUrlSelector.php
PageUrlSelector.ClearParams
private function ClearParams(PageUrl $pageUrl) { $sql = Access::SqlBuilder(); $tblParams = PageUrlParameter::Schema()->Table(); $where = $sql->Equals($tblParams->Field('PageUrl'), $sql->Value($pageUrl->GetID())); PageUrlParameter::Schema()->Delete($where); }
php
private function ClearParams(PageUrl $pageUrl) { $sql = Access::SqlBuilder(); $tblParams = PageUrlParameter::Schema()->Table(); $where = $sql->Equals($tblParams->Field('PageUrl'), $sql->Value($pageUrl->GetID())); PageUrlParameter::Schema()->Delete($where); }
[ "private", "function", "ClearParams", "(", "PageUrl", "$", "pageUrl", ")", "{", "$", "sql", "=", "Access", "::", "SqlBuilder", "(", ")", ";", "$", "tblParams", "=", "PageUrlParameter", "::", "Schema", "(", ")", "->", "Table", "(", ")", ";", "$", "where", "=", "$", "sql", "->", "Equals", "(", "$", "tblParams", "->", "Field", "(", "'PageUrl'", ")", ",", "$", "sql", "->", "Value", "(", "$", "pageUrl", "->", "GetID", "(", ")", ")", ")", ";", "PageUrlParameter", "::", "Schema", "(", ")", "->", "Delete", "(", "$", "where", ")", ";", "}" ]
Clears the parameters of the page url @param PageUrl $pageUrl The page url
[ "Clears", "the", "parameters", "of", "the", "page", "url" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Snippets/FormParts/PageUrlSelector.php#L295-L301
train
myerscode/utilities-strings
src/Utility.php
Utility.append
public function append(string $postfix): Utility { return new static($this->string . new static($postfix, $this->encoding), $this->encoding); }
php
public function append(string $postfix): Utility { return new static($this->string . new static($postfix, $this->encoding), $this->encoding); }
[ "public", "function", "append", "(", "string", "$", "postfix", ")", ":", "Utility", "{", "return", "new", "static", "(", "$", "this", "->", "string", ".", "new", "static", "(", "$", "postfix", ",", "$", "this", "->", "encoding", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Append the string with a given value @param string $postfix Value to append to the string @return $this
[ "Append", "the", "string", "with", "a", "given", "value" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L68-L71
train
myerscode/utilities-strings
src/Utility.php
Utility.at
public function at(int $position): Utility { if ($position < 0) { return new static('', $this->encoding); } return $this->substring($position, 1); }
php
public function at(int $position): Utility { if ($position < 0) { return new static('', $this->encoding); } return $this->substring($position, 1); }
[ "public", "function", "at", "(", "int", "$", "position", ")", ":", "Utility", "{", "if", "(", "$", "position", "<", "0", ")", "{", "return", "new", "static", "(", "''", ",", "$", "this", "->", "encoding", ")", ";", "}", "return", "$", "this", "->", "substring", "(", "$", "position", ",", "1", ")", ";", "}" ]
Get the character at a specific index @param int $position @return Utility
[ "Get", "the", "character", "at", "a", "specific", "index" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L110-L117
train
myerscode/utilities-strings
src/Utility.php
Utility.clean
public function clean(string $allowedTags = null): Utility { $string = strip_tags(trim($this->string), $allowedTags); return new static($string, $this->encoding); }
php
public function clean(string $allowedTags = null): Utility { $string = strip_tags(trim($this->string), $allowedTags); return new static($string, $this->encoding); }
[ "public", "function", "clean", "(", "string", "$", "allowedTags", "=", "null", ")", ":", "Utility", "{", "$", "string", "=", "strip_tags", "(", "trim", "(", "$", "this", "->", "string", ")", ",", "$", "allowedTags", ")", ";", "return", "new", "static", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Remove tags and trim the string @param null|string $allowedTags [optional] Tags to keep when passing through strip_tags @return $this
[ "Remove", "tags", "and", "trim", "the", "string" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L159-L164
train
myerscode/utilities-strings
src/Utility.php
Utility.containsAll
public function containsAll($contains, int $offset = 0): bool { if (empty($contains)) { return false; } $parameters = $this->parameters($contains); if ($offset > $this->length()) { return false; } foreach ($parameters as $needle) { if (strpos($this->string, $needle->value(), $offset) === false) { return false; } } return true; }
php
public function containsAll($contains, int $offset = 0): bool { if (empty($contains)) { return false; } $parameters = $this->parameters($contains); if ($offset > $this->length()) { return false; } foreach ($parameters as $needle) { if (strpos($this->string, $needle->value(), $offset) === false) { return false; } } return true; }
[ "public", "function", "containsAll", "(", "$", "contains", ",", "int", "$", "offset", "=", "0", ")", ":", "bool", "{", "if", "(", "empty", "(", "$", "contains", ")", ")", "{", "return", "false", ";", "}", "$", "parameters", "=", "$", "this", "->", "parameters", "(", "$", "contains", ")", ";", "if", "(", "$", "offset", ">", "$", "this", "->", "length", "(", ")", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "parameters", "as", "$", "needle", ")", "{", "if", "(", "strpos", "(", "$", "this", "->", "string", ",", "$", "needle", "->", "value", "(", ")", ",", "$", "offset", ")", "===", "false", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if a string contains all of the given values @param string|array $contains Values to look for in the string @param int $offset [optional] Search will start this number of characters from the beginning of the string. @return bool
[ "Check", "if", "a", "string", "contains", "all", "of", "the", "given", "values" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L174-L194
train
myerscode/utilities-strings
src/Utility.php
Utility.explode
public function explode($delimiter, $limit = PHP_INT_MAX): array { return array_slice(array_map('trim', array_filter(explode($delimiter, $this->string, $limit))), 0); }
php
public function explode($delimiter, $limit = PHP_INT_MAX): array { return array_slice(array_map('trim', array_filter(explode($delimiter, $this->string, $limit))), 0); }
[ "public", "function", "explode", "(", "$", "delimiter", ",", "$", "limit", "=", "PHP_INT_MAX", ")", ":", "array", "{", "return", "array_slice", "(", "array_map", "(", "'trim'", ",", "array_filter", "(", "explode", "(", "$", "delimiter", ",", "$", "this", "->", "string", ",", "$", "limit", ")", ")", ")", ",", "0", ")", ";", "}" ]
Explode the string on a given @param $delimiter @param $limit @return array
[ "Explode", "the", "string", "on", "a", "given" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L319-L322
train
myerscode/utilities-strings
src/Utility.php
Utility.first
public function first(int $count): Utility { if ($count < 0) { return new static('', $this->encoding); } return $this->substring(0, $count); }
php
public function first(int $count): Utility { if ($count < 0) { return new static('', $this->encoding); } return $this->substring(0, $count); }
[ "public", "function", "first", "(", "int", "$", "count", ")", ":", "Utility", "{", "if", "(", "$", "count", "<", "0", ")", "{", "return", "new", "static", "(", "''", ",", "$", "this", "->", "encoding", ")", ";", "}", "return", "$", "this", "->", "substring", "(", "0", ",", "$", "count", ")", ";", "}" ]
Get the first x characters from the string @param int $count @return Utility
[ "Get", "the", "first", "x", "characters", "from", "the", "string" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L330-L337
train
myerscode/utilities-strings
src/Utility.php
Utility.format
public function format(...$replacements): Utility { $string = $this->string; foreach ($replacements as $index => $value) { if (!is_scalar($value) || (is_object($value) && !method_exists($value, '__toString'))) { $type = is_object($value) ? get_class($value) : gettype($value); throw new InvalidFormatArgumentException( sprintf('Placeholder %s could not convert type %s to a string', $index, $type) ); } $string = str_replace('{' . $index . '}', $value, $string); } return new static($string, $this->encoding); }
php
public function format(...$replacements): Utility { $string = $this->string; foreach ($replacements as $index => $value) { if (!is_scalar($value) || (is_object($value) && !method_exists($value, '__toString'))) { $type = is_object($value) ? get_class($value) : gettype($value); throw new InvalidFormatArgumentException( sprintf('Placeholder %s could not convert type %s to a string', $index, $type) ); } $string = str_replace('{' . $index . '}', $value, $string); } return new static($string, $this->encoding); }
[ "public", "function", "format", "(", "...", "$", "replacements", ")", ":", "Utility", "{", "$", "string", "=", "$", "this", "->", "string", ";", "foreach", "(", "$", "replacements", "as", "$", "index", "=>", "$", "value", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "value", ")", "||", "(", "is_object", "(", "$", "value", ")", "&&", "!", "method_exists", "(", "$", "value", ",", "'__toString'", ")", ")", ")", "{", "$", "type", "=", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "gettype", "(", "$", "value", ")", ";", "throw", "new", "InvalidFormatArgumentException", "(", "sprintf", "(", "'Placeholder %s could not convert type %s to a string'", ",", "$", "index", ",", "$", "type", ")", ")", ";", "}", "$", "string", "=", "str_replace", "(", "'{'", ".", "$", "index", ".", "'}'", ",", "$", "value", ",", "$", "string", ")", ";", "}", "return", "new", "static", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Inserts the given values into the chronological placeholders @param array ...$replacements Collection of items to insert into the string @return $this
[ "Inserts", "the", "given", "values", "into", "the", "chronological", "placeholders" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L346-L362
train
myerscode/utilities-strings
src/Utility.php
Utility.isFalse
public function isFalse(): bool { return ( in_array($this->string, ['']) || (false === filter_var($this->string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) ); }
php
public function isFalse(): bool { return ( in_array($this->string, ['']) || (false === filter_var($this->string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) ); }
[ "public", "function", "isFalse", "(", ")", ":", "bool", "{", "return", "(", "in_array", "(", "$", "this", "->", "string", ",", "[", "''", "]", ")", "||", "(", "false", "===", "filter_var", "(", "$", "this", "->", "string", ",", "FILTER_VALIDATE_BOOLEAN", ",", "FILTER_NULL_ON_FAILURE", ")", ")", ")", ";", "}" ]
Check if a given value can be perceived as false. Will only return false if the value "looks false-y" by being a value of "false", "0", "no", "off", "" @return bool
[ "Check", "if", "a", "given", "value", "can", "be", "perceived", "as", "false", ".", "Will", "only", "return", "false", "if", "the", "value", "looks", "false", "-", "y", "by", "being", "a", "value", "of", "false", "0", "no", "off" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L400-L406
train
myerscode/utilities-strings
src/Utility.php
Utility.isTrue
public function isTrue(): bool { return ( in_array($this->string, ['ok']) || (true === filter_var($this->string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) ); }
php
public function isTrue(): bool { return ( in_array($this->string, ['ok']) || (true === filter_var($this->string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) ); }
[ "public", "function", "isTrue", "(", ")", ":", "bool", "{", "return", "(", "in_array", "(", "$", "this", "->", "string", ",", "[", "'ok'", "]", ")", "||", "(", "true", "===", "filter_var", "(", "$", "this", "->", "string", ",", "FILTER_VALIDATE_BOOLEAN", ",", "FILTER_NULL_ON_FAILURE", ")", ")", ")", ";", "}" ]
Check if a given value can be perceived as true Will on return true if the value "looks true-y" "true", "1", "yes", "on", "ok" @return bool
[ "Check", "if", "a", "given", "value", "can", "be", "perceived", "as", "true", "Will", "on", "return", "true", "if", "the", "value", "looks", "true", "-", "y", "true", "1", "yes", "on", "ok" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L427-L433
train
myerscode/utilities-strings
src/Utility.php
Utility.limit
public function limit(int $length) { $string = $this->string; if ($this->length() > $length) { $string = substr($string, 0, $length); } return new static($string, $this->encoding); }
php
public function limit(int $length) { $string = $this->string; if ($this->length() > $length) { $string = substr($string, 0, $length); } return new static($string, $this->encoding); }
[ "public", "function", "limit", "(", "int", "$", "length", ")", "{", "$", "string", "=", "$", "this", "->", "string", ";", "if", "(", "$", "this", "->", "length", "(", ")", ">", "$", "length", ")", "{", "$", "string", "=", "substr", "(", "$", "string", ",", "0", ",", "$", "length", ")", ";", "}", "return", "new", "static", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Limit the length of the string to a given value @param int $length Desired length the string should be @return $this
[ "Limit", "the", "length", "of", "the", "string", "to", "a", "given", "value" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L452-L461
train
myerscode/utilities-strings
src/Utility.php
Utility.minimise
public function minimise(): Utility { // remove redundant (white-space) characters $replace = [ // remove tabs before and after HTML tags '/\>[^\S ]+/s' => '>', '/[^\S ]+\</s' => '<', // shorten multiple whitespace sequences; keep new-line characters because they matter in JS!!! '/([\t ])+/s' => ' ', // remove leading and trailing spaces '/^([\t ])+/m' => '', '/([\t ])+$/m' => '', // remove JS line comments (simple only); // do NOT remove lines containing URL (e.g. 'src="http://server.com/"')!!! '~//[a-zA-Z0-9 ]+$~m' => '', // remove empty lines (sequence of line-end and white-space characters) '/[\r\n]+([\t ]?[\r\n]+)+/s' => "\n", // remove empty lines (between HTML tags); // cannot remove just any line-end characters because in inline JS they can matter! '/\>[\r\n\t ]+\</s' => '><', // remove "empty" lines containing only JS's block end character; // join with next line (e.g. "}\n}\n</script>" --> "}}</script>" '/}[\r\n\t ]+/s' => '}', '/}[\r\n\t ]+,[\r\n\t ]+/s' => '},', // remove new-line after JS's function or condition start; join with next line '/\)[\r\n\t ]?{[\r\n\t ]+/s' => '){', '/,[\r\n\t ]?{[\r\n\t ]+/s' => ',{', // remove new-line after JS's line end (only most obvious and safe cases) '/\),[\r\n\t ]+/s' => '),', // remove quotes from HTML attributes that does not contain spaces; keep quotes around URLs! '~([\r\n\t ])?([a-zA-Z0-9]+)="([a-zA-Z0-9_/\\-]+)"([\r\n\t ])?~s' => '$1$2=$3$4', // $1 and $4 insert first white-space character found before/after attribute '!/\*[^*]*\*+([^/][^*]*\*+)*/!' => '', // Remove comments ]; $string = preg_replace(array_keys($replace), array_values($replace), $this->string); $remove = ['</option>', '</li>', '</dt>', '</dd>', '</tr>', '</th>', '</td>']; // remove optional ending tags (see http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission ) $string = str_ireplace($remove, '', $string); // remove tabs $string = str_replace("\t", ' ', $string); // remove new lines $string = str_replace("\n", ' ', $string); // remove carriage returns $string = str_replace("\r", ' ', $string); $string = trim(preg_replace('/[\s\t\n\r\s]+/', ' ', $string)); return new static($string, $this->encoding); }
php
public function minimise(): Utility { // remove redundant (white-space) characters $replace = [ // remove tabs before and after HTML tags '/\>[^\S ]+/s' => '>', '/[^\S ]+\</s' => '<', // shorten multiple whitespace sequences; keep new-line characters because they matter in JS!!! '/([\t ])+/s' => ' ', // remove leading and trailing spaces '/^([\t ])+/m' => '', '/([\t ])+$/m' => '', // remove JS line comments (simple only); // do NOT remove lines containing URL (e.g. 'src="http://server.com/"')!!! '~//[a-zA-Z0-9 ]+$~m' => '', // remove empty lines (sequence of line-end and white-space characters) '/[\r\n]+([\t ]?[\r\n]+)+/s' => "\n", // remove empty lines (between HTML tags); // cannot remove just any line-end characters because in inline JS they can matter! '/\>[\r\n\t ]+\</s' => '><', // remove "empty" lines containing only JS's block end character; // join with next line (e.g. "}\n}\n</script>" --> "}}</script>" '/}[\r\n\t ]+/s' => '}', '/}[\r\n\t ]+,[\r\n\t ]+/s' => '},', // remove new-line after JS's function or condition start; join with next line '/\)[\r\n\t ]?{[\r\n\t ]+/s' => '){', '/,[\r\n\t ]?{[\r\n\t ]+/s' => ',{', // remove new-line after JS's line end (only most obvious and safe cases) '/\),[\r\n\t ]+/s' => '),', // remove quotes from HTML attributes that does not contain spaces; keep quotes around URLs! '~([\r\n\t ])?([a-zA-Z0-9]+)="([a-zA-Z0-9_/\\-]+)"([\r\n\t ])?~s' => '$1$2=$3$4', // $1 and $4 insert first white-space character found before/after attribute '!/\*[^*]*\*+([^/][^*]*\*+)*/!' => '', // Remove comments ]; $string = preg_replace(array_keys($replace), array_values($replace), $this->string); $remove = ['</option>', '</li>', '</dt>', '</dd>', '</tr>', '</th>', '</td>']; // remove optional ending tags (see http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission ) $string = str_ireplace($remove, '', $string); // remove tabs $string = str_replace("\t", ' ', $string); // remove new lines $string = str_replace("\n", ' ', $string); // remove carriage returns $string = str_replace("\r", ' ', $string); $string = trim(preg_replace('/[\s\t\n\r\s]+/', ' ', $string)); return new static($string, $this->encoding); }
[ "public", "function", "minimise", "(", ")", ":", "Utility", "{", "// remove redundant (white-space) characters", "$", "replace", "=", "[", "// remove tabs before and after HTML tags", "'/\\>[^\\S ]+/s'", "=>", "'>'", ",", "'/[^\\S ]+\\</s'", "=>", "'<'", ",", "// shorten multiple whitespace sequences; keep new-line characters because they matter in JS!!!", "'/([\\t ])+/s'", "=>", "' '", ",", "// remove leading and trailing spaces", "'/^([\\t ])+/m'", "=>", "''", ",", "'/([\\t ])+$/m'", "=>", "''", ",", "// remove JS line comments (simple only);", "// do NOT remove lines containing URL (e.g. 'src=\"http://server.com/\"')!!!", "'~//[a-zA-Z0-9 ]+$~m'", "=>", "''", ",", "// remove empty lines (sequence of line-end and white-space characters)", "'/[\\r\\n]+([\\t ]?[\\r\\n]+)+/s'", "=>", "\"\\n\"", ",", "// remove empty lines (between HTML tags);", "// cannot remove just any line-end characters because in inline JS they can matter!", "'/\\>[\\r\\n\\t ]+\\</s'", "=>", "'><'", ",", "// remove \"empty\" lines containing only JS's block end character;", "// join with next line (e.g. \"}\\n}\\n</script>\" --> \"}}</script>\"", "'/}[\\r\\n\\t ]+/s'", "=>", "'}'", ",", "'/}[\\r\\n\\t ]+,[\\r\\n\\t ]+/s'", "=>", "'},'", ",", "// remove new-line after JS's function or condition start; join with next line", "'/\\)[\\r\\n\\t ]?{[\\r\\n\\t ]+/s'", "=>", "'){'", ",", "'/,[\\r\\n\\t ]?{[\\r\\n\\t ]+/s'", "=>", "',{'", ",", "// remove new-line after JS's line end (only most obvious and safe cases)", "'/\\),[\\r\\n\\t ]+/s'", "=>", "'),'", ",", "// remove quotes from HTML attributes that does not contain spaces; keep quotes around URLs!", "'~([\\r\\n\\t ])?([a-zA-Z0-9]+)=\"([a-zA-Z0-9_/\\\\-]+)\"([\\r\\n\\t ])?~s'", "=>", "'$1$2=$3$4'", ",", "// $1 and $4 insert first white-space character found before/after attribute", "'!/\\*[^*]*\\*+([^/][^*]*\\*+)*/!'", "=>", "''", ",", "// Remove comments", "]", ";", "$", "string", "=", "preg_replace", "(", "array_keys", "(", "$", "replace", ")", ",", "array_values", "(", "$", "replace", ")", ",", "$", "this", "->", "string", ")", ";", "$", "remove", "=", "[", "'</option>'", ",", "'</li>'", ",", "'</dt>'", ",", "'</dd>'", ",", "'</tr>'", ",", "'</th>'", ",", "'</td>'", "]", ";", "// remove optional ending tags (see http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission )", "$", "string", "=", "str_ireplace", "(", "$", "remove", ",", "''", ",", "$", "string", ")", ";", "// remove tabs", "$", "string", "=", "str_replace", "(", "\"\\t\"", ",", "' '", ",", "$", "string", ")", ";", "// remove new lines", "$", "string", "=", "str_replace", "(", "\"\\n\"", ",", "' '", ",", "$", "string", ")", ";", "// remove carriage returns", "$", "string", "=", "str_replace", "(", "\"\\r\"", ",", "' '", ",", "$", "string", ")", ";", "$", "string", "=", "trim", "(", "preg_replace", "(", "'/[\\s\\t\\n\\r\\s]+/'", ",", "' '", ",", "$", "string", ")", ")", ";", "return", "new", "static", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Minimise string, removing all extra spaces, new lines and any unneeded html content @return $this
[ "Minimise", "string", "removing", "all", "extra", "spaces", "new", "lines", "and", "any", "unneeded", "html", "content" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L481-L533
train
myerscode/utilities-strings
src/Utility.php
Utility.occurrences
public function occurrences(string $needle): array { $offset = 0; $allPositions = []; while (($position = strpos($this->string, $needle, $offset)) !== false) { $offset = $position + 1; $allPositions[] = $position; } return $allPositions; }
php
public function occurrences(string $needle): array { $offset = 0; $allPositions = []; while (($position = strpos($this->string, $needle, $offset)) !== false) { $offset = $position + 1; $allPositions[] = $position; } return $allPositions; }
[ "public", "function", "occurrences", "(", "string", "$", "needle", ")", ":", "array", "{", "$", "offset", "=", "0", ";", "$", "allPositions", "=", "[", "]", ";", "while", "(", "(", "$", "position", "=", "strpos", "(", "$", "this", "->", "string", ",", "$", "needle", ",", "$", "offset", ")", ")", "!==", "false", ")", "{", "$", "offset", "=", "$", "position", "+", "1", ";", "$", "allPositions", "[", "]", "=", "$", "position", ";", "}", "return", "$", "allPositions", ";", "}" ]
Find all the positions of occurrences of the given needle in the string @param string $needle The value to find in the string @return array
[ "Find", "all", "the", "positions", "of", "occurrences", "of", "the", "given", "needle", "in", "the", "string" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L542-L553
train
myerscode/utilities-strings
src/Utility.php
Utility.pad
public function pad(int $length, string $padding = ' '): Utility { $padLength = $length - $this->length(); return $this->applyPadding(floor($padLength / 2), ceil($padLength / 2), $padding); }
php
public function pad(int $length, string $padding = ' '): Utility { $padLength = $length - $this->length(); return $this->applyPadding(floor($padLength / 2), ceil($padLength / 2), $padding); }
[ "public", "function", "pad", "(", "int", "$", "length", ",", "string", "$", "padding", "=", "' '", ")", ":", "Utility", "{", "$", "padLength", "=", "$", "length", "-", "$", "this", "->", "length", "(", ")", ";", "return", "$", "this", "->", "applyPadding", "(", "floor", "(", "$", "padLength", "/", "2", ")", ",", "ceil", "(", "$", "padLength", "/", "2", ")", ",", "$", "padding", ")", ";", "}" ]
Pad the string with a value until it is the given length @param int $length Desired string length after padding @param string $padding Value to pad the string with @return $this
[ "Pad", "the", "string", "with", "a", "value", "until", "it", "is", "the", "given", "length" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L563-L568
train
myerscode/utilities-strings
src/Utility.php
Utility.padLeft
public function padLeft($length, $padding = ' '): Utility { return $this->applyPadding($length - $this->length(), 0, $padding); }
php
public function padLeft($length, $padding = ' '): Utility { return $this->applyPadding($length - $this->length(), 0, $padding); }
[ "public", "function", "padLeft", "(", "$", "length", ",", "$", "padding", "=", "' '", ")", ":", "Utility", "{", "return", "$", "this", "->", "applyPadding", "(", "$", "length", "-", "$", "this", "->", "length", "(", ")", ",", "0", ",", "$", "padding", ")", ";", "}" ]
Pad the left the string with a value until it is the given length @param int $length Desired string length after padding @param string $padding Value to pad the string with @return $this
[ "Pad", "the", "left", "the", "string", "with", "a", "value", "until", "it", "is", "the", "given", "length" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L578-L581
train
myerscode/utilities-strings
src/Utility.php
Utility.padRight
public function padRight($length, $padding = ' '): Utility { return $this->applyPadding(0, $length - $this->length(), $padding); }
php
public function padRight($length, $padding = ' '): Utility { return $this->applyPadding(0, $length - $this->length(), $padding); }
[ "public", "function", "padRight", "(", "$", "length", ",", "$", "padding", "=", "' '", ")", ":", "Utility", "{", "return", "$", "this", "->", "applyPadding", "(", "0", ",", "$", "length", "-", "$", "this", "->", "length", "(", ")", ",", "$", "padding", ")", ";", "}" ]
Pad the right the string with a value until it is the given length @param int $length Desired string length after padding @param string $padding Value to pad the string with @return $this
[ "Pad", "the", "right", "the", "string", "with", "a", "value", "until", "it", "is", "the", "given", "length" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L591-L594
train
myerscode/utilities-strings
src/Utility.php
Utility.parameters
private function parameters($parameters): array { $values = (!is_array($parameters)) ? [$parameters] : $parameters; $strings = []; foreach ($values as $value) { $strings[] = self::make($value, $this->encoding); } return $strings; }
php
private function parameters($parameters): array { $values = (!is_array($parameters)) ? [$parameters] : $parameters; $strings = []; foreach ($values as $value) { $strings[] = self::make($value, $this->encoding); } return $strings; }
[ "private", "function", "parameters", "(", "$", "parameters", ")", ":", "array", "{", "$", "values", "=", "(", "!", "is_array", "(", "$", "parameters", ")", ")", "?", "[", "$", "parameters", "]", ":", "$", "parameters", ";", "$", "strings", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "$", "strings", "[", "]", "=", "self", "::", "make", "(", "$", "value", ",", "$", "this", "->", "encoding", ")", ";", "}", "return", "$", "strings", ";", "}" ]
Transform user input into a collection of Utility @param string|array $parameters @return Utility[]
[ "Transform", "user", "input", "into", "a", "collection", "of", "Utility" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L603-L614
train
myerscode/utilities-strings
src/Utility.php
Utility.prepareForCasing
private function prepareForCasing($string): array { $string = str_replace(['.', '_', '-'], ' ', $string); // split on capital letters $string = implode(' ', preg_split('/(?<=\\w)(?=[A-Z])/', $string)); // explode on numbers $parts = preg_split('/(,?\s+)|((?<=[a-z])(?=\d))|((?<=\d)(?=[a-z]))/i', $string); // return only words return array_values(array_filter($parts, function ($value) { return !empty($value); })); }
php
private function prepareForCasing($string): array { $string = str_replace(['.', '_', '-'], ' ', $string); // split on capital letters $string = implode(' ', preg_split('/(?<=\\w)(?=[A-Z])/', $string)); // explode on numbers $parts = preg_split('/(,?\s+)|((?<=[a-z])(?=\d))|((?<=\d)(?=[a-z]))/i', $string); // return only words return array_values(array_filter($parts, function ($value) { return !empty($value); })); }
[ "private", "function", "prepareForCasing", "(", "$", "string", ")", ":", "array", "{", "$", "string", "=", "str_replace", "(", "[", "'.'", ",", "'_'", ",", "'-'", "]", ",", "' '", ",", "$", "string", ")", ";", "// split on capital letters", "$", "string", "=", "implode", "(", "' '", ",", "preg_split", "(", "'/(?<=\\\\w)(?=[A-Z])/'", ",", "$", "string", ")", ")", ";", "// explode on numbers", "$", "parts", "=", "preg_split", "(", "'/(,?\\s+)|((?<=[a-z])(?=\\d))|((?<=\\d)(?=[a-z]))/i'", ",", "$", "string", ")", ";", "// return only words", "return", "array_values", "(", "array_filter", "(", "$", "parts", ",", "function", "(", "$", "value", ")", "{", "return", "!", "empty", "(", "$", "value", ")", ";", "}", ")", ")", ";", "}" ]
Clean up and chunk a string ready for use in casing the string value @param string $string @return array
[ "Clean", "up", "and", "chunk", "a", "string", "ready", "for", "use", "in", "casing", "the", "string", "value" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L623-L637
train
myerscode/utilities-strings
src/Utility.php
Utility.prepend
public function prepend($prefix): Utility { return new static(new static($prefix, $this->encoding) . $this->string, $this->encoding); }
php
public function prepend($prefix): Utility { return new static(new static($prefix, $this->encoding) . $this->string, $this->encoding); }
[ "public", "function", "prepend", "(", "$", "prefix", ")", ":", "Utility", "{", "return", "new", "static", "(", "new", "static", "(", "$", "prefix", ",", "$", "this", "->", "encoding", ")", ".", "$", "this", "->", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Prepend the string with a given value @param string $prefix @return $this
[ "Prepend", "the", "string", "with", "a", "given", "value" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L646-L649
train
myerscode/utilities-strings
src/Utility.php
Utility.removeRepeating
public function removeRepeating(string $repeatingValue = ' '): Utility { $string = preg_replace('{(' . preg_quote($repeatingValue) . ')\1+}', $repeatingValue, $this->string); return new static($string, $this->encoding); }
php
public function removeRepeating(string $repeatingValue = ' '): Utility { $string = preg_replace('{(' . preg_quote($repeatingValue) . ')\1+}', $repeatingValue, $this->string); return new static($string, $this->encoding); }
[ "public", "function", "removeRepeating", "(", "string", "$", "repeatingValue", "=", "' '", ")", ":", "Utility", "{", "$", "string", "=", "preg_replace", "(", "'{('", ".", "preg_quote", "(", "$", "repeatingValue", ")", ".", "')\\1+}'", ",", "$", "repeatingValue", ",", "$", "this", "->", "string", ")", ";", "return", "new", "static", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Remove repeating characters from the value @param string $repeatingValue Value to remove @return $this
[ "Remove", "repeating", "characters", "from", "the", "value" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L682-L687
train
myerscode/utilities-strings
src/Utility.php
Utility.removeSpace
public function removeSpace(): Utility { $string = preg_replace('~[[:cntrl:][:space:]]~', '', trim($this->string)); return new static($string, $this->encoding); }
php
public function removeSpace(): Utility { $string = preg_replace('~[[:cntrl:][:space:]]~', '', trim($this->string)); return new static($string, $this->encoding); }
[ "public", "function", "removeSpace", "(", ")", ":", "Utility", "{", "$", "string", "=", "preg_replace", "(", "'~[[:cntrl:][:space:]]~'", ",", "''", ",", "trim", "(", "$", "this", "->", "string", ")", ")", ";", "return", "new", "static", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Remove all spaces and white space from the string @return $this
[ "Remove", "all", "spaces", "and", "white", "space", "from", "the", "string" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L694-L699
train
myerscode/utilities-strings
src/Utility.php
Utility.repeat
public function repeat(int $multiplier): Utility { $string = str_repeat($this->string, $multiplier); return new static($string, $this->encoding); }
php
public function repeat(int $multiplier): Utility { $string = str_repeat($this->string, $multiplier); return new static($string, $this->encoding); }
[ "public", "function", "repeat", "(", "int", "$", "multiplier", ")", ":", "Utility", "{", "$", "string", "=", "str_repeat", "(", "$", "this", "->", "string", ",", "$", "multiplier", ")", ";", "return", "new", "static", "(", "$", "string", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Repeat the string by the amount of the multiplier @param int $multiplier The number of times to repeat the string @return $this
[ "Repeat", "the", "string", "by", "the", "amount", "of", "the", "multiplier" ]
e7adb907a57de060295a7f3886d43230f66f6b76
https://github.com/myerscode/utilities-strings/blob/e7adb907a57de060295a7f3886d43230f66f6b76/src/Utility.php#L708-L713
train