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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
andyburton/Sonic-Framework
src/Model.php
Model.resetPK
public function resetPK ($val = FALSE) { if ($val === FALSE) { $this->reset (static::$pk); } else { $this->attributeValues[static::$pk] = $val; } }
php
public function resetPK ($val = FALSE) { if ($val === FALSE) { $this->reset (static::$pk); } else { $this->attributeValues[static::$pk] = $val; } }
[ "public", "function", "resetPK", "(", "$", "val", "=", "FALSE", ")", "{", "if", "(", "$", "val", "===", "FALSE", ")", "{", "$", "this", "->", "reset", "(", "static", "::", "$", "pk", ")", ";", "}", "else", "{", "$", "this", "->", "attributeValues", "[", "static", "::", "$", "pk", "]", "=", "$", "val", ";", "}", "}" ]
Reset the primary key to default or set to a specific value @param mixed $val Value
[ "Reset", "the", "primary", "key", "to", "default", "or", "set", "to", "a", "specific", "value" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L561-L573
train
andyburton/Sonic-Framework
src/Model.php
Model.cast
public function cast ($name, $val) { // Ignore if value is null if (is_null ($val)) { return $val; } // Cast value based upon attribute datatype switch (@static::$attributes[$name]['type']) { case self::TYPE_INT: $val = (int)$val; break; case self::TYPE_STRING: $val = (string)$val; break; case self::TYPE_BOOL: $val = (bool)$val; break; case self::TYPE_DECIMAL: $val = (float)$val; break; case self::TYPE_BINARY: $val = (binary)$val; break; } // Return casted value return $val; }
php
public function cast ($name, $val) { // Ignore if value is null if (is_null ($val)) { return $val; } // Cast value based upon attribute datatype switch (@static::$attributes[$name]['type']) { case self::TYPE_INT: $val = (int)$val; break; case self::TYPE_STRING: $val = (string)$val; break; case self::TYPE_BOOL: $val = (bool)$val; break; case self::TYPE_DECIMAL: $val = (float)$val; break; case self::TYPE_BINARY: $val = (binary)$val; break; } // Return casted value return $val; }
[ "public", "function", "cast", "(", "$", "name", ",", "$", "val", ")", "{", "// Ignore if value is null", "if", "(", "is_null", "(", "$", "val", ")", ")", "{", "return", "$", "val", ";", "}", "// Cast value based upon attribute datatype", "switch", "(", "@", "static", "::", "$", "attributes", "[", "$", "name", "]", "[", "'type'", "]", ")", "{", "case", "self", "::", "TYPE_INT", ":", "$", "val", "=", "(", "int", ")", "$", "val", ";", "break", ";", "case", "self", "::", "TYPE_STRING", ":", "$", "val", "=", "(", "string", ")", "$", "val", ";", "break", ";", "case", "self", "::", "TYPE_BOOL", ":", "$", "val", "=", "(", "bool", ")", "$", "val", ";", "break", ";", "case", "self", "::", "TYPE_DECIMAL", ":", "$", "val", "=", "(", "float", ")", "$", "val", ";", "break", ";", "case", "self", "::", "TYPE_BINARY", ":", "$", "val", "=", "(", "binary", ")", "$", "val", ";", "break", ";", "}", "// Return casted value", "return", "$", "val", ";", "}" ]
Cast a value for an attribute datatype @param string $name Attribute name @param mixed $val Value to cast @return mixed
[ "Cast", "a", "value", "for", "an", "attribute", "datatype" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L583-L624
train
andyburton/Sonic-Framework
src/Model.php
Model.create
public function create ($exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') '); // Bind attributes $this->bindAttributes ($query, $exclude); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // Changelog if ($this->changelog ('create')) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('create', static::_Read ($this->iget (static::$pk), $db)); } // return TRUE return TRUE; }
php
public function create ($exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') '); // Bind attributes $this->bindAttributes ($query, $exclude); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // Changelog if ($this->changelog ('create')) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('create', static::_Read ($this->iget (static::$pk), $db)); } // return TRUE return TRUE; }
[ "public", "function", "create", "(", "$", "exclude", "=", "array", "(", ")", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Get columns and values", "$", "create", "=", "$", "this", "->", "createColumnsAndValues", "(", "$", "exclude", ")", ";", "// Get database master for write", "if", "(", "$", "db", "===", "FALSE", ")", "{", "$", "db", "=", "&", "$", "this", "->", "getDbMaster", "(", ")", ";", "}", "// Prepare query", "$", "query", "=", "$", "db", "->", "prepare", "(", "'\n\t\tINSERT INTO `'", ".", "static", "::", "$", "dbTable", ".", "'` ('", ".", "$", "create", "[", "'columns'", "]", ".", "')\n\t\tVALUES ( '", ".", "$", "create", "[", "'values'", "]", ".", "')\n\t\t'", ")", ";", "// Bind attributes", "$", "this", "->", "bindAttributes", "(", "$", "query", ",", "$", "exclude", ")", ";", "// Execute", "if", "(", "!", "$", "this", "->", "executeCreateUpdateQuery", "(", "$", "query", ")", ")", "{", "return", "FALSE", ";", "}", "// Set the pk", "if", "(", "!", "$", "this", "->", "attributeHasValue", "(", "static", "::", "$", "pk", ")", "||", "!", "$", "this", "->", "iget", "(", "static", "::", "$", "pk", ")", ")", "{", "$", "this", "->", "iset", "(", "static", "::", "$", "pk", ",", "$", "db", "->", "lastInsertID", "(", ")", ")", ";", "}", "// Changelog", "if", "(", "$", "this", "->", "changelog", "(", "'create'", ")", ")", "{", "$", "log", "=", "&", "$", "this", "->", "getResource", "(", "'changelog'", ")", ";", "$", "log", "->", "hookTransactions", "(", "$", "db", ")", ";", "$", "log", "::", "_Log", "(", "'create'", ",", "static", "::", "_Read", "(", "$", "this", "->", "iget", "(", "static", "::", "$", "pk", ")", ",", "$", "db", ")", ")", ";", "}", "// return TRUE", "return", "TRUE", ";", "}" ]
Create object in the database @param array $exclude Attributes not to set @param \PDO $db Database connection to use, default to master resource @return boolean
[ "Create", "object", "in", "the", "database" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L634-L686
train
andyburton/Sonic-Framework
src/Model.php
Model.createOrUpdate
public function createOrUpdate ($update, $exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Generate update values $updateVals = NULL; foreach ($update as $column => $value) { // Add column $updateVals .= ', `' . $column . '` = '; // If the updated value is an array treat first item // as literal query insert and the second a params to bind $updateVals .= is_array ($value)? $value[0] : $value; } // Trim the first character (,) from the update $updateVals = substr ($updateVals, 2); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(' . static::$pk . '), ' . $updateVals . ' '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind update parameters foreach ($update as $value) { if (is_array ($value) && isset ($value[1]) && is_array ($value[1])) { foreach ($value[1] as $column => $newVal) { $query->bindValue ($column, $newVal); } } } // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // return TRUE return TRUE; }
php
public function createOrUpdate ($update, $exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Generate update values $updateVals = NULL; foreach ($update as $column => $value) { // Add column $updateVals .= ', `' . $column . '` = '; // If the updated value is an array treat first item // as literal query insert and the second a params to bind $updateVals .= is_array ($value)? $value[0] : $value; } // Trim the first character (,) from the update $updateVals = substr ($updateVals, 2); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(' . static::$pk . '), ' . $updateVals . ' '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind update parameters foreach ($update as $value) { if (is_array ($value) && isset ($value[1]) && is_array ($value[1])) { foreach ($value[1] as $column => $newVal) { $query->bindValue ($column, $newVal); } } } // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // return TRUE return TRUE; }
[ "public", "function", "createOrUpdate", "(", "$", "update", ",", "$", "exclude", "=", "array", "(", ")", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Get columns and values", "$", "create", "=", "$", "this", "->", "createColumnsAndValues", "(", "$", "exclude", ")", ";", "// Generate update values", "$", "updateVals", "=", "NULL", ";", "foreach", "(", "$", "update", "as", "$", "column", "=>", "$", "value", ")", "{", "// Add column", "$", "updateVals", ".=", "', `'", ".", "$", "column", ".", "'` = '", ";", "// If the updated value is an array treat first item", "// as literal query insert and the second a params to bind", "$", "updateVals", ".=", "is_array", "(", "$", "value", ")", "?", "$", "value", "[", "0", "]", ":", "$", "value", ";", "}", "// Trim the first character (,) from the update", "$", "updateVals", "=", "substr", "(", "$", "updateVals", ",", "2", ")", ";", "// Get database master for write", "if", "(", "$", "db", "===", "FALSE", ")", "{", "$", "db", "=", "&", "$", "this", "->", "getDbMaster", "(", ")", ";", "}", "// Prepare query", "$", "query", "=", "$", "db", "->", "prepare", "(", "'\n\t\tINSERT INTO `'", ".", "static", "::", "$", "dbTable", ".", "'` ('", ".", "$", "create", "[", "'columns'", "]", ".", "')\n\t\tVALUES ( '", ".", "$", "create", "[", "'values'", "]", ".", "') \n\t\tON DUPLICATE KEY UPDATE id = LAST_INSERT_ID('", ".", "static", "::", "$", "pk", ".", "'), '", ".", "$", "updateVals", ".", "'\n\t\t'", ")", ";", "// Bind attributes", "$", "this", "->", "bindAttributes", "(", "$", "query", ",", "$", "exclude", ")", ";", "// Bind update parameters", "foreach", "(", "$", "update", "as", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "isset", "(", "$", "value", "[", "1", "]", ")", "&&", "is_array", "(", "$", "value", "[", "1", "]", ")", ")", "{", "foreach", "(", "$", "value", "[", "1", "]", "as", "$", "column", "=>", "$", "newVal", ")", "{", "$", "query", "->", "bindValue", "(", "$", "column", ",", "$", "newVal", ")", ";", "}", "}", "}", "// Execute", "if", "(", "!", "$", "this", "->", "executeCreateUpdateQuery", "(", "$", "query", ")", ")", "{", "return", "FALSE", ";", "}", "// Set the pk", "if", "(", "!", "$", "this", "->", "attributeHasValue", "(", "static", "::", "$", "pk", ")", "||", "!", "$", "this", "->", "iget", "(", "static", "::", "$", "pk", ")", ")", "{", "$", "this", "->", "iset", "(", "static", "::", "$", "pk", ",", "$", "db", "->", "lastInsertID", "(", ")", ")", ";", "}", "// return TRUE", "return", "TRUE", ";", "}" ]
Create or update an object in the database if it already exists @param array $update Values to update @param array $exclude Attributes not to set in create @param \PDO $db Database connection to use, default to master resource @return boolean
[ "Create", "or", "update", "an", "object", "in", "the", "database", "if", "it", "already", "exists" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L697-L776
train
andyburton/Sonic-Framework
src/Model.php
Model.createColumnsAndValues
private function createColumnsAndValues (&$exclude) { // If there is no primary key value exclude it (i.e assume auto increment) if (!$this->attributeHasValue (static::$pk)) { $exclude[] = static::$pk; } // Set column and value variables $columns = NULL; $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute is not set if (!$this->attributeIsset ($name)) { // If there is a default set it if (array_key_exists ('default', $attribute)) { $this->iset ($name, $attribute['default'], FALSE); } // Else if the attribute can be set to NULL then do so else if (isset ($attribute['null']) && $attribute['null']) { $this->iset ($name, NULL, FALSE); } // Else set a blank value else { $this->iset ($name, '', FALSE); } } // Add the column and values $columns .= ', `' . $name . '`'; $values .= ', ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the column and values $columns = substr ($columns, 2); $values = substr ($values, 2); // Return columns and values return array ( 'columns' => $columns, 'values' => $values ); }
php
private function createColumnsAndValues (&$exclude) { // If there is no primary key value exclude it (i.e assume auto increment) if (!$this->attributeHasValue (static::$pk)) { $exclude[] = static::$pk; } // Set column and value variables $columns = NULL; $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute is not set if (!$this->attributeIsset ($name)) { // If there is a default set it if (array_key_exists ('default', $attribute)) { $this->iset ($name, $attribute['default'], FALSE); } // Else if the attribute can be set to NULL then do so else if (isset ($attribute['null']) && $attribute['null']) { $this->iset ($name, NULL, FALSE); } // Else set a blank value else { $this->iset ($name, '', FALSE); } } // Add the column and values $columns .= ', `' . $name . '`'; $values .= ', ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the column and values $columns = substr ($columns, 2); $values = substr ($values, 2); // Return columns and values return array ( 'columns' => $columns, 'values' => $values ); }
[ "private", "function", "createColumnsAndValues", "(", "&", "$", "exclude", ")", "{", "// If there is no primary key value exclude it (i.e assume auto increment)", "if", "(", "!", "$", "this", "->", "attributeHasValue", "(", "static", "::", "$", "pk", ")", ")", "{", "$", "exclude", "[", "]", "=", "static", "::", "$", "pk", ";", "}", "// Set column and value variables", "$", "columns", "=", "NULL", ";", "$", "values", "=", "NULL", ";", "// Loop through attributes", "foreach", "(", "static", "::", "$", "attributes", "as", "$", "name", "=>", "$", "attribute", ")", "{", "// If we're excluding the attribute then move on", "if", "(", "in_array", "(", "$", "name", ",", "$", "exclude", ")", ")", "{", "continue", ";", "}", "// If the attribute is not set", "if", "(", "!", "$", "this", "->", "attributeIsset", "(", "$", "name", ")", ")", "{", "// If there is a default set it", "if", "(", "array_key_exists", "(", "'default'", ",", "$", "attribute", ")", ")", "{", "$", "this", "->", "iset", "(", "$", "name", ",", "$", "attribute", "[", "'default'", "]", ",", "FALSE", ")", ";", "}", "// Else if the attribute can be set to NULL then do so", "else", "if", "(", "isset", "(", "$", "attribute", "[", "'null'", "]", ")", "&&", "$", "attribute", "[", "'null'", "]", ")", "{", "$", "this", "->", "iset", "(", "$", "name", ",", "NULL", ",", "FALSE", ")", ";", "}", "// Else set a blank value", "else", "{", "$", "this", "->", "iset", "(", "$", "name", ",", "''", ",", "FALSE", ")", ";", "}", "}", "// Add the column and values", "$", "columns", ".=", "', `'", ".", "$", "name", ".", "'`'", ";", "$", "values", ".=", "', '", ".", "$", "this", "->", "transformValue", "(", "$", "name", ",", "$", "attribute", ",", "$", "exclude", ")", ";", "}", "// Trim the first character (,) from the column and values", "$", "columns", "=", "substr", "(", "$", "columns", ",", "2", ")", ";", "$", "values", "=", "substr", "(", "$", "values", ",", "2", ")", ";", "// Return columns and values", "return", "array", "(", "'columns'", "=>", "$", "columns", ",", "'values'", "=>", "$", "values", ")", ";", "}" ]
Generate create query columns and values @param array $exclude Attribute exclusion array @return array ('columns', 'values')
[ "Generate", "create", "query", "columns", "and", "values" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L785-L859
train
andyburton/Sonic-Framework
src/Model.php
Model.transformValue
private function transformValue ($name, $attribute, &$exclude) { // If an attribute can accept NULL and it's value is '' then NULL will be set $value = $this->iget ($name); if (is_null ($value) || (isset ($attribute['null']) && $attribute['null'] && $value === '')) { $this->iset ($name, NULL); $value = 'NULL'; $exclude[] = $name; } else { // Switch special values switch ((string)$value) { case "CURRENT_TIMESTAMP": $value = 'CURRENT_TIMESTAMP'; $exclude[] = $name; break; case 'CURRENT_UTC_DATE': $value = "'" . $this->parser->utcDate () . "'"; $exclude[] = $name; break; default: $value = ':' . $name; break; } } // Return transformed value return $value; }
php
private function transformValue ($name, $attribute, &$exclude) { // If an attribute can accept NULL and it's value is '' then NULL will be set $value = $this->iget ($name); if (is_null ($value) || (isset ($attribute['null']) && $attribute['null'] && $value === '')) { $this->iset ($name, NULL); $value = 'NULL'; $exclude[] = $name; } else { // Switch special values switch ((string)$value) { case "CURRENT_TIMESTAMP": $value = 'CURRENT_TIMESTAMP'; $exclude[] = $name; break; case 'CURRENT_UTC_DATE': $value = "'" . $this->parser->utcDate () . "'"; $exclude[] = $name; break; default: $value = ':' . $name; break; } } // Return transformed value return $value; }
[ "private", "function", "transformValue", "(", "$", "name", ",", "$", "attribute", ",", "&", "$", "exclude", ")", "{", "// If an attribute can accept NULL and it's value is '' then NULL will be set", "$", "value", "=", "$", "this", "->", "iget", "(", "$", "name", ")", ";", "if", "(", "is_null", "(", "$", "value", ")", "||", "(", "isset", "(", "$", "attribute", "[", "'null'", "]", ")", "&&", "$", "attribute", "[", "'null'", "]", "&&", "$", "value", "===", "''", ")", ")", "{", "$", "this", "->", "iset", "(", "$", "name", ",", "NULL", ")", ";", "$", "value", "=", "'NULL'", ";", "$", "exclude", "[", "]", "=", "$", "name", ";", "}", "else", "{", "// Switch special values", "switch", "(", "(", "string", ")", "$", "value", ")", "{", "case", "\"CURRENT_TIMESTAMP\"", ":", "$", "value", "=", "'CURRENT_TIMESTAMP'", ";", "$", "exclude", "[", "]", "=", "$", "name", ";", "break", ";", "case", "'CURRENT_UTC_DATE'", ":", "$", "value", "=", "\"'\"", ".", "$", "this", "->", "parser", "->", "utcDate", "(", ")", ".", "\"'\"", ";", "$", "exclude", "[", "]", "=", "$", "name", ";", "break", ";", "default", ":", "$", "value", "=", "':'", ".", "$", "name", ";", "break", ";", "}", "}", "// Return transformed value", "return", "$", "value", ";", "}" ]
Apply any attribute value transformations for SQL query @param string $name Attribute name @param array $attribute Attribute property array @param array $exclude Attribute exclusion array @return mixed
[ "Apply", "any", "attribute", "value", "transformations", "for", "SQL", "query" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L870-L916
train
andyburton/Sonic-Framework
src/Model.php
Model.bindAttributes
private function bindAttributes (&$query, $exclude = array ()) { // Loop through attributes foreach (array_keys (static::$attributes) as $name) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // Bind paramater $query->bindValue (':' . $name, $this->iget ($name)); } }
php
private function bindAttributes (&$query, $exclude = array ()) { // Loop through attributes foreach (array_keys (static::$attributes) as $name) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // Bind paramater $query->bindValue (':' . $name, $this->iget ($name)); } }
[ "private", "function", "bindAttributes", "(", "&", "$", "query", ",", "$", "exclude", "=", "array", "(", ")", ")", "{", "// Loop through attributes", "foreach", "(", "array_keys", "(", "static", "::", "$", "attributes", ")", "as", "$", "name", ")", "{", "// If we're excluding the attribute then move on", "if", "(", "in_array", "(", "$", "name", ",", "$", "exclude", ")", ")", "{", "continue", ";", "}", "// Bind paramater", "$", "query", "->", "bindValue", "(", "':'", ".", "$", "name", ",", "$", "this", "->", "iget", "(", "$", "name", ")", ")", ";", "}", "}" ]
Bind object attribute values to the query @param \PDOStatement $query Query object to bind values to @param array $exclude Attributes to exclude @return void
[ "Bind", "object", "attribute", "values", "to", "the", "query" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L926-L947
train
andyburton/Sonic-Framework
src/Model.php
Model.executeCreateUpdateQuery
private function executeCreateUpdateQuery (&$query) { // Execute try { $query->execute (); return TRUE; } catch (\PDOException $e) { // Catch some errors switch ($e->getCode ()) { // Duplicate Key case 23000: // Get attribute name and set error if (preg_match ('/Duplicate entry \'(.*?)\' for key \'(.*?)\'/', $e->getMessage (), $match)) { $name = $this->attributeExists ($match[2]) && isset (static::$attributes[$match[2]]['name'])? static::$attributes[$match[2]]['name'] : $match[2]; new Message ('error', 'Please choose another ' . ucwords ($name) . ' `' . $match[1] . '` already exists!'); return FALSE; } // Else unrecognised message so throw the error again else { throw $e; } break; // Throw error by default default: throw $e; } } }
php
private function executeCreateUpdateQuery (&$query) { // Execute try { $query->execute (); return TRUE; } catch (\PDOException $e) { // Catch some errors switch ($e->getCode ()) { // Duplicate Key case 23000: // Get attribute name and set error if (preg_match ('/Duplicate entry \'(.*?)\' for key \'(.*?)\'/', $e->getMessage (), $match)) { $name = $this->attributeExists ($match[2]) && isset (static::$attributes[$match[2]]['name'])? static::$attributes[$match[2]]['name'] : $match[2]; new Message ('error', 'Please choose another ' . ucwords ($name) . ' `' . $match[1] . '` already exists!'); return FALSE; } // Else unrecognised message so throw the error again else { throw $e; } break; // Throw error by default default: throw $e; } } }
[ "private", "function", "executeCreateUpdateQuery", "(", "&", "$", "query", ")", "{", "// Execute", "try", "{", "$", "query", "->", "execute", "(", ")", ";", "return", "TRUE", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "// Catch some errors", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "// Duplicate Key", "case", "23000", ":", "// Get attribute name and set error", "if", "(", "preg_match", "(", "'/Duplicate entry \\'(.*?)\\' for key \\'(.*?)\\'/'", ",", "$", "e", "->", "getMessage", "(", ")", ",", "$", "match", ")", ")", "{", "$", "name", "=", "$", "this", "->", "attributeExists", "(", "$", "match", "[", "2", "]", ")", "&&", "isset", "(", "static", "::", "$", "attributes", "[", "$", "match", "[", "2", "]", "]", "[", "'name'", "]", ")", "?", "static", "::", "$", "attributes", "[", "$", "match", "[", "2", "]", "]", "[", "'name'", "]", ":", "$", "match", "[", "2", "]", ";", "new", "Message", "(", "'error'", ",", "'Please choose another '", ".", "ucwords", "(", "$", "name", ")", ".", "' `'", ".", "$", "match", "[", "1", "]", ".", "'` already exists!'", ")", ";", "return", "FALSE", ";", "}", "// Else unrecognised message so throw the error again", "else", "{", "throw", "$", "e", ";", "}", "break", ";", "// Throw error by default", "default", ":", "throw", "$", "e", ";", "}", "}", "}" ]
Execute create or update query and cope with an exception @param \PDOStatement $query Query object to bind values to @return boolean @throws PDOException
[ "Execute", "create", "or", "update", "query", "and", "cope", "with", "an", "exception" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L957-L1007
train
andyburton/Sonic-Framework
src/Model.php
Model.read
public function read ($pkValue = FALSE, &$db = FALSE) { try { // If there is a key value passed set it if ($pkValue !== FALSE) { $this->iset (static::$pk, $pkValue); } // Get database slave for read if ($db === FALSE) { $db =& $this->getDbSlave (); } // Prepare query $query = $db->prepare (' SELECT * FROM `' . static::$dbTable . '` WHERE ' . static::$pk . ' = :pk '); // Bind paramater $query->bindValue (':pk', $this->iget (static::$pk)); // Execute $query->execute (); // Set row $row = $query->fetch (\PDO::FETCH_ASSOC); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($this->attributeExists ($name)) { $this->iset ($name, $val, FALSE, TRUE); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); return FALSE; } // Return TRUE return TRUE; }
php
public function read ($pkValue = FALSE, &$db = FALSE) { try { // If there is a key value passed set it if ($pkValue !== FALSE) { $this->iset (static::$pk, $pkValue); } // Get database slave for read if ($db === FALSE) { $db =& $this->getDbSlave (); } // Prepare query $query = $db->prepare (' SELECT * FROM `' . static::$dbTable . '` WHERE ' . static::$pk . ' = :pk '); // Bind paramater $query->bindValue (':pk', $this->iget (static::$pk)); // Execute $query->execute (); // Set row $row = $query->fetch (\PDO::FETCH_ASSOC); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($this->attributeExists ($name)) { $this->iset ($name, $val, FALSE, TRUE); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); return FALSE; } // Return TRUE return TRUE; }
[ "public", "function", "read", "(", "$", "pkValue", "=", "FALSE", ",", "&", "$", "db", "=", "FALSE", ")", "{", "try", "{", "// If there is a key value passed set it", "if", "(", "$", "pkValue", "!==", "FALSE", ")", "{", "$", "this", "->", "iset", "(", "static", "::", "$", "pk", ",", "$", "pkValue", ")", ";", "}", "// Get database slave for read", "if", "(", "$", "db", "===", "FALSE", ")", "{", "$", "db", "=", "&", "$", "this", "->", "getDbSlave", "(", ")", ";", "}", "// Prepare query", "$", "query", "=", "$", "db", "->", "prepare", "(", "'\n\t\t\tSELECT * FROM `'", ".", "static", "::", "$", "dbTable", ".", "'`\n\t\t\tWHERE '", ".", "static", "::", "$", "pk", ".", "' = :pk\n\t\t\t'", ")", ";", "// Bind paramater", "$", "query", "->", "bindValue", "(", "':pk'", ",", "$", "this", "->", "iget", "(", "static", "::", "$", "pk", ")", ")", ";", "// Execute", "$", "query", "->", "execute", "(", ")", ";", "// Set row", "$", "row", "=", "$", "query", "->", "fetch", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "// If no data was returned return FALSE", "if", "(", "!", "$", "row", ")", "{", "return", "FALSE", ";", "}", "// Set each attribute value", "foreach", "(", "$", "row", "as", "$", "name", "=>", "$", "val", ")", "{", "if", "(", "$", "this", "->", "attributeExists", "(", "$", "name", ")", ")", "{", "$", "this", "->", "iset", "(", "$", "name", ",", "$", "val", ",", "FALSE", ",", "TRUE", ")", ";", "}", "}", "}", "// Set errors as framework messages", "catch", "(", "Resource", "\\", "Parser", "\\", "Exception", "$", "e", ")", "{", "new", "Message", "(", "'error'", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "return", "FALSE", ";", "}", "// Return TRUE", "return", "TRUE", ";", "}" ]
Read an object from the database, populating the object attributes @param mixed $pkValue Primary key value @param \PDO $db Database connection to use, default to slave resource @return boolean
[ "Read", "an", "object", "from", "the", "database", "populating", "the", "object", "attributes" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1017-L1089
train
andyburton/Sonic-Framework
src/Model.php
Model.readAttribute
public function readAttribute ($name) { $this->iset ($name, $this->getValue (array ( 'select' => $name, 'where' => array (array (static::$pk, $this->iget (static::$pk))) ))); }
php
public function readAttribute ($name) { $this->iset ($name, $this->getValue (array ( 'select' => $name, 'where' => array (array (static::$pk, $this->iget (static::$pk))) ))); }
[ "public", "function", "readAttribute", "(", "$", "name", ")", "{", "$", "this", "->", "iset", "(", "$", "name", ",", "$", "this", "->", "getValue", "(", "array", "(", "'select'", "=>", "$", "name", ",", "'where'", "=>", "array", "(", "array", "(", "static", "::", "$", "pk", ",", "$", "this", "->", "iget", "(", "static", "::", "$", "pk", ")", ")", ")", ")", ")", ")", ";", "}" ]
Read and set a single object attribute from the database @param string $name Attribute name @return void
[ "Read", "and", "set", "a", "single", "object", "attribute", "from", "the", "database" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1098-L1104
train
andyburton/Sonic-Framework
src/Model.php
Model.update
public function update ($exclude = array (), &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Changelog $old = FALSE; if ($this->changelog ('update')) { $old = static::_Read ($this->get (static::$pk), $db); } // Exclude the primary key $exclude[] = static::$pk; // Set value variable $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute has derefresh enabled the refresh value to default for the update if (isset ($attribute['deupdate']) && $attribute['deupdate']) { $this->reset ($name); } // Else if the attribute is not set or is creation only else if (!$this->attributeIsset ($name) || (isset ($attribute['creation']) && $attribute['creation'])) { // Exclude it and move on $exclude[] = $name; continue; } // Add the value $values .= ',`' . $name . '` = ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the values $values = substr ($values, 1); // Prepare query $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $values . ' WHERE ' . static::$pk . ' = :pk '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind pk $query->bindValue (':pk', $this->iget (static::$pk)); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Changelog if ($old) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('update', $old, $this); } // return TRUE return TRUE; }
php
public function update ($exclude = array (), &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Changelog $old = FALSE; if ($this->changelog ('update')) { $old = static::_Read ($this->get (static::$pk), $db); } // Exclude the primary key $exclude[] = static::$pk; // Set value variable $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute has derefresh enabled the refresh value to default for the update if (isset ($attribute['deupdate']) && $attribute['deupdate']) { $this->reset ($name); } // Else if the attribute is not set or is creation only else if (!$this->attributeIsset ($name) || (isset ($attribute['creation']) && $attribute['creation'])) { // Exclude it and move on $exclude[] = $name; continue; } // Add the value $values .= ',`' . $name . '` = ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the values $values = substr ($values, 1); // Prepare query $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $values . ' WHERE ' . static::$pk . ' = :pk '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind pk $query->bindValue (':pk', $this->iget (static::$pk)); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Changelog if ($old) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('update', $old, $this); } // return TRUE return TRUE; }
[ "public", "function", "update", "(", "$", "exclude", "=", "array", "(", ")", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Get database master for write", "if", "(", "$", "db", "===", "FALSE", ")", "{", "$", "db", "=", "&", "$", "this", "->", "getDbMaster", "(", ")", ";", "}", "// Changelog", "$", "old", "=", "FALSE", ";", "if", "(", "$", "this", "->", "changelog", "(", "'update'", ")", ")", "{", "$", "old", "=", "static", "::", "_Read", "(", "$", "this", "->", "get", "(", "static", "::", "$", "pk", ")", ",", "$", "db", ")", ";", "}", "// Exclude the primary key", "$", "exclude", "[", "]", "=", "static", "::", "$", "pk", ";", "// Set value variable", "$", "values", "=", "NULL", ";", "// Loop through attributes", "foreach", "(", "static", "::", "$", "attributes", "as", "$", "name", "=>", "$", "attribute", ")", "{", "// If we're excluding the attribute then move on", "if", "(", "in_array", "(", "$", "name", ",", "$", "exclude", ")", ")", "{", "continue", ";", "}", "// If the attribute has derefresh enabled the refresh value to default for the update", "if", "(", "isset", "(", "$", "attribute", "[", "'deupdate'", "]", ")", "&&", "$", "attribute", "[", "'deupdate'", "]", ")", "{", "$", "this", "->", "reset", "(", "$", "name", ")", ";", "}", "// Else if the attribute is not set or is creation only", "else", "if", "(", "!", "$", "this", "->", "attributeIsset", "(", "$", "name", ")", "||", "(", "isset", "(", "$", "attribute", "[", "'creation'", "]", ")", "&&", "$", "attribute", "[", "'creation'", "]", ")", ")", "{", "// Exclude it and move on", "$", "exclude", "[", "]", "=", "$", "name", ";", "continue", ";", "}", "// Add the value", "$", "values", ".=", "',`'", ".", "$", "name", ".", "'` = '", ".", "$", "this", "->", "transformValue", "(", "$", "name", ",", "$", "attribute", ",", "$", "exclude", ")", ";", "}", "// Trim the first character (,) from the values", "$", "values", "=", "substr", "(", "$", "values", ",", "1", ")", ";", "// Prepare query", "$", "query", "=", "$", "db", "->", "prepare", "(", "'\n\t\tUPDATE `'", ".", "static", "::", "$", "dbTable", ".", "'`\n\t\tSET '", ".", "$", "values", ".", "'\n\t\tWHERE '", ".", "static", "::", "$", "pk", ".", "' = :pk\n\t\t'", ")", ";", "// Bind attributes", "$", "this", "->", "bindAttributes", "(", "$", "query", ",", "$", "exclude", ")", ";", "// Bind pk", "$", "query", "->", "bindValue", "(", "':pk'", ",", "$", "this", "->", "iget", "(", "static", "::", "$", "pk", ")", ")", ";", "// Execute", "if", "(", "!", "$", "this", "->", "executeCreateUpdateQuery", "(", "$", "query", ")", ")", "{", "return", "FALSE", ";", "}", "// Changelog", "if", "(", "$", "old", ")", "{", "$", "log", "=", "&", "$", "this", "->", "getResource", "(", "'changelog'", ")", ";", "$", "log", "->", "hookTransactions", "(", "$", "db", ")", ";", "$", "log", "::", "_Log", "(", "'update'", ",", "$", "old", ",", "$", "this", ")", ";", "}", "// return TRUE", "return", "TRUE", ";", "}" ]
Update an object in the database @param array $exclude Attributes not to update @param \PDO $db Database connection to use, default to master resource @return boolean
[ "Update", "an", "object", "in", "the", "database" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1114-L1219
train
andyburton/Sonic-Framework
src/Model.php
Model.hookTransactions
public function hookTransactions (Resource\Db &$parent, Resource\Db &$child = NULL) { // Use default object database resource if none is specified if (!$child) { $child =& $this->getResource ('db'); } /** * We only want to create the hook and begin a transaction on the database * if a transaction has already begun on the database we're hooking onto. */ if ($parent->getTransactionCount () > 0 && $parent->addTransactionHook ($child)) { $child->beginTransaction (); } }
php
public function hookTransactions (Resource\Db &$parent, Resource\Db &$child = NULL) { // Use default object database resource if none is specified if (!$child) { $child =& $this->getResource ('db'); } /** * We only want to create the hook and begin a transaction on the database * if a transaction has already begun on the database we're hooking onto. */ if ($parent->getTransactionCount () > 0 && $parent->addTransactionHook ($child)) { $child->beginTransaction (); } }
[ "public", "function", "hookTransactions", "(", "Resource", "\\", "Db", "&", "$", "parent", ",", "Resource", "\\", "Db", "&", "$", "child", "=", "NULL", ")", "{", "// Use default object database resource if none is specified", "if", "(", "!", "$", "child", ")", "{", "$", "child", "=", "&", "$", "this", "->", "getResource", "(", "'db'", ")", ";", "}", "/**\n\t\t * We only want to create the hook and begin a transaction on the database\n\t\t * if a transaction has already begun on the database we're hooking onto.\n\t\t */", "if", "(", "$", "parent", "->", "getTransactionCount", "(", ")", ">", "0", "&&", "$", "parent", "->", "addTransactionHook", "(", "$", "child", ")", ")", "{", "$", "child", "->", "beginTransaction", "(", ")", ";", "}", "}" ]
Hook any database queries into another database transaction so that the queries are commited and rolled back at the same point @param \Sonic\Resource\Db $parent Parent database This is the database resource that is hooked and passes transaction state to the child database @param \Sonic\Resource\Db $child Child database This is the datababase resource that hooks onto the parent and has its transaction state copied from the parent Defaults to object 'db' connection resource
[ "Hook", "any", "database", "queries", "into", "another", "database", "transaction", "so", "that", "the", "queries", "are", "commited", "and", "rolled", "back", "at", "the", "same", "point" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1449-L1469
train
andyburton/Sonic-Framework
src/Model.php
Model.toXML
public function toXML ($attributes = FALSE) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); // Create DOMDocument $doc = new \DOMDocument ('1.0', 'UTF-8'); // Create root node $node = $doc->createElement ($class); $doc->appendChild ($node); // Get array $arr = $this->toArray ($attributes); // Set each attribute foreach ($arr as $name => $val) { $node->appendChild ($doc->createElement (strtolower ($name), htmlentities ($val))); } // Return doc return $doc; }
php
public function toXML ($attributes = FALSE) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); // Create DOMDocument $doc = new \DOMDocument ('1.0', 'UTF-8'); // Create root node $node = $doc->createElement ($class); $doc->appendChild ($node); // Get array $arr = $this->toArray ($attributes); // Set each attribute foreach ($arr as $name => $val) { $node->appendChild ($doc->createElement (strtolower ($name), htmlentities ($val))); } // Return doc return $doc; }
[ "public", "function", "toXML", "(", "$", "attributes", "=", "FALSE", ")", "{", "// Set class name for the elements", "// Remove the Sonic\\Model prefix and convert namespace \\ to _", "$", "class", "=", "str_replace", "(", "'\\\\'", ",", "'_'", ",", "str_replace", "(", "'sonic\\\\model\\\\'", ",", "''", ",", "strtolower", "(", "get_called_class", "(", ")", ")", ")", ")", ";", "// Create DOMDocument", "$", "doc", "=", "new", "\\", "DOMDocument", "(", "'1.0'", ",", "'UTF-8'", ")", ";", "// Create root node", "$", "node", "=", "$", "doc", "->", "createElement", "(", "$", "class", ")", ";", "$", "doc", "->", "appendChild", "(", "$", "node", ")", ";", "// Get array", "$", "arr", "=", "$", "this", "->", "toArray", "(", "$", "attributes", ")", ";", "// Set each attribute", "foreach", "(", "$", "arr", "as", "$", "name", "=>", "$", "val", ")", "{", "$", "node", "->", "appendChild", "(", "$", "doc", "->", "createElement", "(", "strtolower", "(", "$", "name", ")", ",", "htmlentities", "(", "$", "val", ")", ")", ")", ";", "}", "// Return doc", "return", "$", "doc", ";", "}" ]
Return a DOM tree with object attributes @param array|boolean $attributes Attributes to include, default to false i.e all attributes @return \DOMDocument|boolean
[ "Return", "a", "DOM", "tree", "with", "object", "attributes" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1478-L1510
train
andyburton/Sonic-Framework
src/Model.php
Model.toJSON
public function toJSON ($attributes = FALSE, $addClass = FALSE) { // Get array $arr = $this->toArray ($attributes); // Add the class name if required if ($addClass) { $arr['class'] = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); } // Return json encoded return json_encode ($arr); }
php
public function toJSON ($attributes = FALSE, $addClass = FALSE) { // Get array $arr = $this->toArray ($attributes); // Add the class name if required if ($addClass) { $arr['class'] = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); } // Return json encoded return json_encode ($arr); }
[ "public", "function", "toJSON", "(", "$", "attributes", "=", "FALSE", ",", "$", "addClass", "=", "FALSE", ")", "{", "// Get array", "$", "arr", "=", "$", "this", "->", "toArray", "(", "$", "attributes", ")", ";", "// Add the class name if required", "if", "(", "$", "addClass", ")", "{", "$", "arr", "[", "'class'", "]", "=", "str_replace", "(", "'\\\\'", ",", "'_'", ",", "str_replace", "(", "'sonic\\\\model\\\\'", ",", "''", ",", "strtolower", "(", "get_called_class", "(", ")", ")", ")", ")", ";", "}", "// Return json encoded", "return", "json_encode", "(", "$", "arr", ")", ";", "}" ]
Return a JSON encoded string with object attributes @param array|boolean $attributes Attributes to include, default to false i.e all attributes @param boolean $addClass Whether to add the class name to each exported object @return object|boolean
[ "Return", "a", "JSON", "encoded", "string", "with", "object", "attributes" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1520-L1538
train
andyburton/Sonic-Framework
src/Model.php
Model.fromArray
public function fromArray ($attributes, $removeClass = FALSE, $validate = TRUE, $required = array (), $valid = array ()) { // Remove class prefix if ($removeClass) { // Set attributes to set $arr = array (); // Get class name $class = strtolower ($this->getClass ()); // Loop through attributes and add any that exist with the class name foreach (array_keys (static::$attributes) as $name) { if (isset ($attributes[$class . '_' . strtolower ($name)])) { $arr[$name] = $attributes[$class . '_' . $name]; } } // Set attributes $attributes = $arr; } // If we have an array of valid attributes to set // Remove any that arent valid if ($valid) { foreach (array_keys ($attributes) as $name) { if (!in_array ($name, $valid, TRUE)) { unset ($attributes[$name]); } } } // Set each attribute try { foreach ($attributes as $name => $val) { if ($this->attributeExists ($name) && $this->attributeSet ($name)) { $this->set ($name, $val, $validate); } if (($key = array_search ($name, $required, TRUE)) !== FALSE) { unset ($required[$key]); } } // Error if there are required fields that have not been set if (count ($required) > 0) { foreach ($required as $name) { if ($this->attributeExists ($name) && isset (static::$attributes[$name]['name'])) { $name = static::$attributes[$name]['name']; } $word = in_array (strtoupper ($name[0]), array ('A', 'E', 'I', 'O'))? 'an' : 'a'; new Message ('error', 'You have not entered ' . $word . ' ' . ucwords ($name)); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); } }
php
public function fromArray ($attributes, $removeClass = FALSE, $validate = TRUE, $required = array (), $valid = array ()) { // Remove class prefix if ($removeClass) { // Set attributes to set $arr = array (); // Get class name $class = strtolower ($this->getClass ()); // Loop through attributes and add any that exist with the class name foreach (array_keys (static::$attributes) as $name) { if (isset ($attributes[$class . '_' . strtolower ($name)])) { $arr[$name] = $attributes[$class . '_' . $name]; } } // Set attributes $attributes = $arr; } // If we have an array of valid attributes to set // Remove any that arent valid if ($valid) { foreach (array_keys ($attributes) as $name) { if (!in_array ($name, $valid, TRUE)) { unset ($attributes[$name]); } } } // Set each attribute try { foreach ($attributes as $name => $val) { if ($this->attributeExists ($name) && $this->attributeSet ($name)) { $this->set ($name, $val, $validate); } if (($key = array_search ($name, $required, TRUE)) !== FALSE) { unset ($required[$key]); } } // Error if there are required fields that have not been set if (count ($required) > 0) { foreach ($required as $name) { if ($this->attributeExists ($name) && isset (static::$attributes[$name]['name'])) { $name = static::$attributes[$name]['name']; } $word = in_array (strtoupper ($name[0]), array ('A', 'E', 'I', 'O'))? 'an' : 'a'; new Message ('error', 'You have not entered ' . $word . ' ' . ucwords ($name)); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); } }
[ "public", "function", "fromArray", "(", "$", "attributes", ",", "$", "removeClass", "=", "FALSE", ",", "$", "validate", "=", "TRUE", ",", "$", "required", "=", "array", "(", ")", ",", "$", "valid", "=", "array", "(", ")", ")", "{", "// Remove class prefix", "if", "(", "$", "removeClass", ")", "{", "// Set attributes to set", "$", "arr", "=", "array", "(", ")", ";", "// Get class name", "$", "class", "=", "strtolower", "(", "$", "this", "->", "getClass", "(", ")", ")", ";", "// Loop through attributes and add any that exist with the class name", "foreach", "(", "array_keys", "(", "static", "::", "$", "attributes", ")", "as", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "attributes", "[", "$", "class", ".", "'_'", ".", "strtolower", "(", "$", "name", ")", "]", ")", ")", "{", "$", "arr", "[", "$", "name", "]", "=", "$", "attributes", "[", "$", "class", ".", "'_'", ".", "$", "name", "]", ";", "}", "}", "// Set attributes", "$", "attributes", "=", "$", "arr", ";", "}", "// If we have an array of valid attributes to set", "// Remove any that arent valid", "if", "(", "$", "valid", ")", "{", "foreach", "(", "array_keys", "(", "$", "attributes", ")", "as", "$", "name", ")", "{", "if", "(", "!", "in_array", "(", "$", "name", ",", "$", "valid", ",", "TRUE", ")", ")", "{", "unset", "(", "$", "attributes", "[", "$", "name", "]", ")", ";", "}", "}", "}", "// Set each attribute", "try", "{", "foreach", "(", "$", "attributes", "as", "$", "name", "=>", "$", "val", ")", "{", "if", "(", "$", "this", "->", "attributeExists", "(", "$", "name", ")", "&&", "$", "this", "->", "attributeSet", "(", "$", "name", ")", ")", "{", "$", "this", "->", "set", "(", "$", "name", ",", "$", "val", ",", "$", "validate", ")", ";", "}", "if", "(", "(", "$", "key", "=", "array_search", "(", "$", "name", ",", "$", "required", ",", "TRUE", ")", ")", "!==", "FALSE", ")", "{", "unset", "(", "$", "required", "[", "$", "key", "]", ")", ";", "}", "}", "// Error if there are required fields that have not been set", "if", "(", "count", "(", "$", "required", ")", ">", "0", ")", "{", "foreach", "(", "$", "required", "as", "$", "name", ")", "{", "if", "(", "$", "this", "->", "attributeExists", "(", "$", "name", ")", "&&", "isset", "(", "static", "::", "$", "attributes", "[", "$", "name", "]", "[", "'name'", "]", ")", ")", "{", "$", "name", "=", "static", "::", "$", "attributes", "[", "$", "name", "]", "[", "'name'", "]", ";", "}", "$", "word", "=", "in_array", "(", "strtoupper", "(", "$", "name", "[", "0", "]", ")", ",", "array", "(", "'A'", ",", "'E'", ",", "'I'", ",", "'O'", ")", ")", "?", "'an'", ":", "'a'", ";", "new", "Message", "(", "'error'", ",", "'You have not entered '", ".", "$", "word", ".", "' '", ".", "ucwords", "(", "$", "name", ")", ")", ";", "}", "}", "}", "// Set errors as framework messages", "catch", "(", "Resource", "\\", "Parser", "\\", "Exception", "$", "e", ")", "{", "new", "Message", "(", "'error'", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Populate object attributes from an array @param array $attributes Attributes array @param boolean $removeClass Remove class prefix from the attribute name @param boolean $validate Validate attributes during set @param array $required Required attributes @param array $valid Valid attributes to set @return void
[ "Populate", "object", "attributes", "from", "an", "array" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1738-L1840
train
andyburton/Sonic-Framework
src/Model.php
Model.getChildren
public function getChildren ($class, $recursive = FALSE, $index = FALSE, $key = FALSE, $params = array ()) { // Get children $children = self::_getChildren ($class, $this->iget (self::$pk), $recursive, $key, $params); // If we want the indexes if ($index) { $children = static::_getChildrenIndex ($children); } return $children; }
php
public function getChildren ($class, $recursive = FALSE, $index = FALSE, $key = FALSE, $params = array ()) { // Get children $children = self::_getChildren ($class, $this->iget (self::$pk), $recursive, $key, $params); // If we want the indexes if ($index) { $children = static::_getChildrenIndex ($children); } return $children; }
[ "public", "function", "getChildren", "(", "$", "class", ",", "$", "recursive", "=", "FALSE", ",", "$", "index", "=", "FALSE", ",", "$", "key", "=", "FALSE", ",", "$", "params", "=", "array", "(", ")", ")", "{", "// Get children", "$", "children", "=", "self", "::", "_getChildren", "(", "$", "class", ",", "$", "this", "->", "iget", "(", "self", "::", "$", "pk", ")", ",", "$", "recursive", ",", "$", "key", ",", "$", "params", ")", ";", "// If we want the indexes", "if", "(", "$", "index", ")", "{", "$", "children", "=", "static", "::", "_getChildrenIndex", "(", "$", "children", ")", ";", "}", "return", "$", "children", ";", "}" ]
Return child objects matching class type @param string $class Child class type @param boolean $recursive Whether to load childrens children. This will create an object attribute called 'children' on all objects @param boolean $index Return indexed child array rather than object array @param string $key Attribute to use as array key @param array $params Query parameter array @return array|boolean
[ "Return", "child", "objects", "matching", "class", "type" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1893-L1909
train
andyburton/Sonic-Framework
src/Model.php
Model.getValue
public function getValue ($params, $fetchMode = \PDO::FETCH_ASSOC, &$db = FALSE) { // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } // Set table $params['from'] = '`' . static::$dbTable . '`'; // Return value return $db->getValue ($params, $fetchMode); }
php
public function getValue ($params, $fetchMode = \PDO::FETCH_ASSOC, &$db = FALSE) { // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } // Set table $params['from'] = '`' . static::$dbTable . '`'; // Return value return $db->getValue ($params, $fetchMode); }
[ "public", "function", "getValue", "(", "$", "params", ",", "$", "fetchMode", "=", "\\", "PDO", "::", "FETCH_ASSOC", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Get database slave for read", "if", "(", "$", "db", "===", "FALSE", ")", "{", "$", "db", "=", "&", "self", "::", "_getDbSlave", "(", ")", ";", "}", "// Set table", "$", "params", "[", "'from'", "]", "=", "'`'", ".", "static", "::", "$", "dbTable", ".", "'`'", ";", "// Return value", "return", "$", "db", "->", "getValue", "(", "$", "params", ",", "$", "fetchMode", ")", ";", "}" ]
Return a single row @param array $params Parameter array @param int $fetchMode PDO fetch mode, default to assoc @param \PDO $db Database connection to use, default to slave resource @return mixed
[ "Return", "a", "single", "row" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1920-L1938
train
andyburton/Sonic-Framework
src/Model.php
Model.&
public function &getResource ($name) { // If the resource is not set if (!isset ($this->resources[$name])) { // Return FALSE $bln = FALSE; return $bln; } // Return resource reference return $this->resources[$name]; }
php
public function &getResource ($name) { // If the resource is not set if (!isset ($this->resources[$name])) { // Return FALSE $bln = FALSE; return $bln; } // Return resource reference return $this->resources[$name]; }
[ "public", "function", "&", "getResource", "(", "$", "name", ")", "{", "// If the resource is not set", "if", "(", "!", "isset", "(", "$", "this", "->", "resources", "[", "$", "name", "]", ")", ")", "{", "// Return FALSE", "$", "bln", "=", "FALSE", ";", "return", "$", "bln", ";", "}", "// Return resource reference", "return", "$", "this", "->", "resources", "[", "$", "name", "]", ";", "}" ]
Return a class resource reference @param string $name Resource name @return object|boolean
[ "Return", "a", "class", "resource", "reference" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2053-L2072
train
andyburton/Sonic-Framework
src/Model.php
Model.setResource
public function setResource ($name, $resource) { // Get the resource $obj =& Sonic::getResource ($resource); if (!$obj) { return FALSE; } // Set resource object $this->setResourceObj ($name, $obj); // Return return TRUE; }
php
public function setResource ($name, $resource) { // Get the resource $obj =& Sonic::getResource ($resource); if (!$obj) { return FALSE; } // Set resource object $this->setResourceObj ($name, $obj); // Return return TRUE; }
[ "public", "function", "setResource", "(", "$", "name", ",", "$", "resource", ")", "{", "// Get the resource", "$", "obj", "=", "&", "Sonic", "::", "getResource", "(", "$", "resource", ")", ";", "if", "(", "!", "$", "obj", ")", "{", "return", "FALSE", ";", "}", "// Set resource object", "$", "this", "->", "setResourceObj", "(", "$", "name", ",", "$", "obj", ")", ";", "// Return", "return", "TRUE", ";", "}" ]
Set an internal resource from a framework resource @param string $name Resource name @param string|array $resource Framework resource referece @return boolean
[ "Set", "an", "internal", "resource", "from", "a", "framework", "resource" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2082-L2102
train
andyburton/Sonic-Framework
src/Model.php
Model.setResourceObj
public function setResourceObj ($name, &$resource) { // Set the resource $this->resources[$name] =& $resource; // If the object variable exists if (isset ($this->$name)) { // Assign to object variable $this->$name =& $this->resources[$name]; } }
php
public function setResourceObj ($name, &$resource) { // Set the resource $this->resources[$name] =& $resource; // If the object variable exists if (isset ($this->$name)) { // Assign to object variable $this->$name =& $this->resources[$name]; } }
[ "public", "function", "setResourceObj", "(", "$", "name", ",", "&", "$", "resource", ")", "{", "// Set the resource", "$", "this", "->", "resources", "[", "$", "name", "]", "=", "&", "$", "resource", ";", "// If the object variable exists ", "if", "(", "isset", "(", "$", "this", "->", "$", "name", ")", ")", "{", "// Assign to object variable", "$", "this", "->", "$", "name", "=", "&", "$", "this", "->", "resources", "[", "$", "name", "]", ";", "}", "}" ]
Set a class resource from the resource object @param string $name Resource name @param object $resource Resource object @return void
[ "Set", "a", "class", "resource", "from", "the", "resource", "object" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2112-L2130
train
andyburton/Sonic-Framework
src/Model.php
Model.removeResource
public function removeResource ($name) { if (isset ($this->resources[$name])) { unset ($this->resources[$name]); if (isset ($this->$name)) { unset ($this->$name); } } }
php
public function removeResource ($name) { if (isset ($this->resources[$name])) { unset ($this->resources[$name]); if (isset ($this->$name)) { unset ($this->$name); } } }
[ "public", "function", "removeResource", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "resources", "[", "$", "name", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "resources", "[", "$", "name", "]", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "$", "name", ")", ")", "{", "unset", "(", "$", "this", "->", "$", "name", ")", ";", "}", "}", "}" ]
Remove a class resource @param string $name Resource name @return void
[ "Remove", "a", "class", "resource" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2139-L2154
train
andyburton/Sonic-Framework
src/Model.php
Model.removeResources
public function removeResources () { foreach (array_keys ($this->resources) as $name) { if (isset ($this->$name)) { unset ($this->$name); } } unset ($this->resources); }
php
public function removeResources () { foreach (array_keys ($this->resources) as $name) { if (isset ($this->$name)) { unset ($this->$name); } } unset ($this->resources); }
[ "public", "function", "removeResources", "(", ")", "{", "foreach", "(", "array_keys", "(", "$", "this", "->", "resources", ")", "as", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "$", "name", ")", ")", "{", "unset", "(", "$", "this", "->", "$", "name", ")", ";", "}", "}", "unset", "(", "$", "this", "->", "resources", ")", ";", "}" ]
Remove all class resources @return void
[ "Remove", "all", "class", "resources" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2162-L2175
train
andyburton/Sonic-Framework
src/Model.php
Model._attributeProperties
public static function _attributeProperties ($name, $property = FALSE) { // If the attribute exists if (isset (static::$attributes[$name])) { // If a property is specified if ($property) { // If the property doesnt exist if (!isset (static::$attributes[$name][$property])) { return FALSE; } // Return property return static::$attributes[$name][$property]; } // Return attribute return static::$attributes[$name]; } // Return FALSE return FALSE; }
php
public static function _attributeProperties ($name, $property = FALSE) { // If the attribute exists if (isset (static::$attributes[$name])) { // If a property is specified if ($property) { // If the property doesnt exist if (!isset (static::$attributes[$name][$property])) { return FALSE; } // Return property return static::$attributes[$name][$property]; } // Return attribute return static::$attributes[$name]; } // Return FALSE return FALSE; }
[ "public", "static", "function", "_attributeProperties", "(", "$", "name", ",", "$", "property", "=", "FALSE", ")", "{", "// If the attribute exists", "if", "(", "isset", "(", "static", "::", "$", "attributes", "[", "$", "name", "]", ")", ")", "{", "// If a property is specified", "if", "(", "$", "property", ")", "{", "// If the property doesnt exist", "if", "(", "!", "isset", "(", "static", "::", "$", "attributes", "[", "$", "name", "]", "[", "$", "property", "]", ")", ")", "{", "return", "FALSE", ";", "}", "// Return property", "return", "static", "::", "$", "attributes", "[", "$", "name", "]", "[", "$", "property", "]", ";", "}", "// Return attribute", "return", "static", "::", "$", "attributes", "[", "$", "name", "]", ";", "}", "// Return FALSE", "return", "FALSE", ";", "}" ]
Return an attribute parameters array or FALSE if it doesnt exist Also pass option property array to return a single attribute property @param string $name Attribute name @param string $property Attribute property @return boolean
[ "Return", "an", "attribute", "parameters", "array", "or", "FALSE", "if", "it", "doesnt", "exist", "Also", "pass", "option", "property", "array", "to", "return", "a", "single", "attribute", "property" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2258-L2294
train
andyburton/Sonic-Framework
src/Model.php
Model._read
public static function _read ($params, &$db = FALSE) { // Create the object $obj = new static; // If the params are an array if (is_array ($params)) { // Select all $params['select'] = '*'; // Get data $row = static::_getValue ($params, \PDO::FETCH_ASSOC, $db); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($obj->attributeExists ($name)) { $obj->iset ($name, $val); } } } // Else the params are not an array, so assume pk else { // Read the object if (!$obj->read ($params, $db)) { return FALSE; } } // Return the object return $obj; }
php
public static function _read ($params, &$db = FALSE) { // Create the object $obj = new static; // If the params are an array if (is_array ($params)) { // Select all $params['select'] = '*'; // Get data $row = static::_getValue ($params, \PDO::FETCH_ASSOC, $db); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($obj->attributeExists ($name)) { $obj->iset ($name, $val); } } } // Else the params are not an array, so assume pk else { // Read the object if (!$obj->read ($params, $db)) { return FALSE; } } // Return the object return $obj; }
[ "public", "static", "function", "_read", "(", "$", "params", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Create the object", "$", "obj", "=", "new", "static", ";", "// If the params are an array", "if", "(", "is_array", "(", "$", "params", ")", ")", "{", "// Select all", "$", "params", "[", "'select'", "]", "=", "'*'", ";", "// Get data", "$", "row", "=", "static", "::", "_getValue", "(", "$", "params", ",", "\\", "PDO", "::", "FETCH_ASSOC", ",", "$", "db", ")", ";", "// If no data was returned return FALSE", "if", "(", "!", "$", "row", ")", "{", "return", "FALSE", ";", "}", "// Set each attribute value", "foreach", "(", "$", "row", "as", "$", "name", "=>", "$", "val", ")", "{", "if", "(", "$", "obj", "->", "attributeExists", "(", "$", "name", ")", ")", "{", "$", "obj", "->", "iset", "(", "$", "name", ",", "$", "val", ")", ";", "}", "}", "}", "// Else the params are not an array, so assume pk", "else", "{", "// Read the object", "if", "(", "!", "$", "obj", "->", "read", "(", "$", "params", ",", "$", "db", ")", ")", "{", "return", "FALSE", ";", "}", "}", "// Return the object", "return", "$", "obj", ";", "}" ]
Create a new object instance and read it from the database, populating the object attributes @param mixed $params Object to read. This can be an instance ID or a parameter array. @param \PDO $db Database connection to use @return \Sonic\Model
[ "Create", "a", "new", "object", "instance", "and", "read", "it", "from", "the", "database", "populating", "the", "object", "attributes" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2373-L2432
train
andyburton/Sonic-Framework
src/Model.php
Model._count
public static function _count ($params = array (), &$db = FALSE) { // Remove order if (isset ($params['orderby'])) { unset ($params['orderby']); } // Remove limit if (isset ($params['limit'])) { unset ($params['limit']); } // Select count $params['select'] = 'COUNT(*)'; // Return return static::_getValue ($params, \PDO::FETCH_ASSOC, $db); }
php
public static function _count ($params = array (), &$db = FALSE) { // Remove order if (isset ($params['orderby'])) { unset ($params['orderby']); } // Remove limit if (isset ($params['limit'])) { unset ($params['limit']); } // Select count $params['select'] = 'COUNT(*)'; // Return return static::_getValue ($params, \PDO::FETCH_ASSOC, $db); }
[ "public", "static", "function", "_count", "(", "$", "params", "=", "array", "(", ")", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Remove order", "if", "(", "isset", "(", "$", "params", "[", "'orderby'", "]", ")", ")", "{", "unset", "(", "$", "params", "[", "'orderby'", "]", ")", ";", "}", "// Remove limit", "if", "(", "isset", "(", "$", "params", "[", "'limit'", "]", ")", ")", "{", "unset", "(", "$", "params", "[", "'limit'", "]", ")", ";", "}", "// Select count", "$", "params", "[", "'select'", "]", "=", "'COUNT(*)'", ";", "// Return", "return", "static", "::", "_getValue", "(", "$", "params", ",", "\\", "PDO", "::", "FETCH_ASSOC", ",", "$", "db", ")", ";", "}" ]
Return the number of objects in the database matching the parameters @param array $params Parameter array @param \PDO $db Database connection to use @return integer|boolean
[ "Return", "the", "number", "of", "objects", "in", "the", "database", "matching", "the", "parameters" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2463-L2488
train
andyburton/Sonic-Framework
src/Model.php
Model._exists
public static function _exists ($params, &$db = FALSE) { if (!is_array ($params)) { $params = array ( 'where' => array ( array (static::$pk, $params) ) ); } return self::_count ($params, $db) > 0; }
php
public static function _exists ($params, &$db = FALSE) { if (!is_array ($params)) { $params = array ( 'where' => array ( array (static::$pk, $params) ) ); } return self::_count ($params, $db) > 0; }
[ "public", "static", "function", "_exists", "(", "$", "params", ",", "&", "$", "db", "=", "FALSE", ")", "{", "if", "(", "!", "is_array", "(", "$", "params", ")", ")", "{", "$", "params", "=", "array", "(", "'where'", "=>", "array", "(", "array", "(", "static", "::", "$", "pk", ",", "$", "params", ")", ")", ")", ";", "}", "return", "self", "::", "_count", "(", "$", "params", ",", "$", "db", ")", ">", "0", ";", "}" ]
Check to see whether the object matching the parameters exists @param array $params Parameter array @param \PDO $db Database connection to use @return boolean
[ "Check", "to", "see", "whether", "the", "object", "matching", "the", "parameters", "exists" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2498-L2512
train
andyburton/Sonic-Framework
src/Model.php
Model._getObjects
public static function _getObjects ($params = array (), $key = FALSE, &$db = FALSE) { // Select all attributes if none are set if (!isset ($params['select'])) { $params['select'] = '*'; } // Get data $rows = static::_getValues ($params, $db); // If no data was returned return FALSE if ($rows === FALSE) { return FALSE; } // Return objects return self::_arrayToObjects ($rows, $key); }
php
public static function _getObjects ($params = array (), $key = FALSE, &$db = FALSE) { // Select all attributes if none are set if (!isset ($params['select'])) { $params['select'] = '*'; } // Get data $rows = static::_getValues ($params, $db); // If no data was returned return FALSE if ($rows === FALSE) { return FALSE; } // Return objects return self::_arrayToObjects ($rows, $key); }
[ "public", "static", "function", "_getObjects", "(", "$", "params", "=", "array", "(", ")", ",", "$", "key", "=", "FALSE", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Select all attributes if none are set", "if", "(", "!", "isset", "(", "$", "params", "[", "'select'", "]", ")", ")", "{", "$", "params", "[", "'select'", "]", "=", "'*'", ";", "}", "// Get data", "$", "rows", "=", "static", "::", "_getValues", "(", "$", "params", ",", "$", "db", ")", ";", "// If no data was returned return FALSE", "if", "(", "$", "rows", "===", "FALSE", ")", "{", "return", "FALSE", ";", "}", "// Return objects", "return", "self", "::", "_arrayToObjects", "(", "$", "rows", ",", "$", "key", ")", ";", "}" ]
Create and return an array of objects for query parameters @param array $params Parameter array @param string $key Attribute value to use as the array index, default to 0-indexed @param \PDO $db Database connection to use @return \Sonic\Resource\Model\Collection
[ "Create", "and", "return", "an", "array", "of", "objects", "for", "query", "parameters" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2638-L2663
train
andyburton/Sonic-Framework
src/Model.php
Model._queryToObjects
public static function _queryToObjects ($query, $key = FALSE) { $query->execute (); return static::_arrayToObjects ($query->fetchAll (\PDO::FETCH_ASSOC), $key); }
php
public static function _queryToObjects ($query, $key = FALSE) { $query->execute (); return static::_arrayToObjects ($query->fetchAll (\PDO::FETCH_ASSOC), $key); }
[ "public", "static", "function", "_queryToObjects", "(", "$", "query", ",", "$", "key", "=", "FALSE", ")", "{", "$", "query", "->", "execute", "(", ")", ";", "return", "static", "::", "_arrayToObjects", "(", "$", "query", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ",", "$", "key", ")", ";", "}" ]
Execute a PDOStatement query and convert the results into objects @param \PDOStatement Query to execute @param string $key Attribute value to use as the array index, default to 0-indexed @return Resource\Model\Collection
[ "Execute", "a", "PDOStatement", "query", "and", "convert", "the", "results", "into", "objects" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2673-L2677
train
andyburton/Sonic-Framework
src/Model.php
Model._arrayToObjects
public static function _arrayToObjects ($arr, $key = FALSE) { // Set object array $objs = new Resource\Model\Collection; // If no data if (!$arr) { return $objs; } // For each row foreach ($arr as $row) { // Create the object $obj = new static; // Set each attribute value foreach ($row as $name => $val) { if ($obj->attributeExists ($name)) { $obj->iset ($name, $val, FALSE, TRUE); } } // Add to the array if ($key && isset ($row[$key])) { $objs[$row[$key]] = $obj; } else { $objs[] = $obj; } } // Return the objects return $objs; }
php
public static function _arrayToObjects ($arr, $key = FALSE) { // Set object array $objs = new Resource\Model\Collection; // If no data if (!$arr) { return $objs; } // For each row foreach ($arr as $row) { // Create the object $obj = new static; // Set each attribute value foreach ($row as $name => $val) { if ($obj->attributeExists ($name)) { $obj->iset ($name, $val, FALSE, TRUE); } } // Add to the array if ($key && isset ($row[$key])) { $objs[$row[$key]] = $obj; } else { $objs[] = $obj; } } // Return the objects return $objs; }
[ "public", "static", "function", "_arrayToObjects", "(", "$", "arr", ",", "$", "key", "=", "FALSE", ")", "{", "// Set object array", "$", "objs", "=", "new", "Resource", "\\", "Model", "\\", "Collection", ";", "// If no data", "if", "(", "!", "$", "arr", ")", "{", "return", "$", "objs", ";", "}", "// For each row", "foreach", "(", "$", "arr", "as", "$", "row", ")", "{", "// Create the object", "$", "obj", "=", "new", "static", ";", "// Set each attribute value", "foreach", "(", "$", "row", "as", "$", "name", "=>", "$", "val", ")", "{", "if", "(", "$", "obj", "->", "attributeExists", "(", "$", "name", ")", ")", "{", "$", "obj", "->", "iset", "(", "$", "name", ",", "$", "val", ",", "FALSE", ",", "TRUE", ")", ";", "}", "}", "// Add to the array", "if", "(", "$", "key", "&&", "isset", "(", "$", "row", "[", "$", "key", "]", ")", ")", "{", "$", "objs", "[", "$", "row", "[", "$", "key", "]", "]", "=", "$", "obj", ";", "}", "else", "{", "$", "objs", "[", "]", "=", "$", "obj", ";", "}", "}", "// Return the objects", "return", "$", "objs", ";", "}" ]
Convert an array into objects @param array $arr Array to convert @param string $key Attribute value to use as the array index, default to 0-indexed @return Resource\Model\Collection
[ "Convert", "an", "array", "into", "objects" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2687-L2739
train
andyburton/Sonic-Framework
src/Model.php
Model._genQuery
public static function _genQuery ($params, &$db = FALSE) { // Set select if (!isset ($params['select'])) { $params['select'] = '*'; } // Set from if (!isset ($params['from'])) { $params['from'] = '`' . static::$dbTable . '`'; } // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } if (!($db instanceof \PDO)) { throw new Exception ('Invalid or no database resource set'); } // Return value return $db->genQuery ($params); }
php
public static function _genQuery ($params, &$db = FALSE) { // Set select if (!isset ($params['select'])) { $params['select'] = '*'; } // Set from if (!isset ($params['from'])) { $params['from'] = '`' . static::$dbTable . '`'; } // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } if (!($db instanceof \PDO)) { throw new Exception ('Invalid or no database resource set'); } // Return value return $db->genQuery ($params); }
[ "public", "static", "function", "_genQuery", "(", "$", "params", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Set select", "if", "(", "!", "isset", "(", "$", "params", "[", "'select'", "]", ")", ")", "{", "$", "params", "[", "'select'", "]", "=", "'*'", ";", "}", "// Set from", "if", "(", "!", "isset", "(", "$", "params", "[", "'from'", "]", ")", ")", "{", "$", "params", "[", "'from'", "]", "=", "'`'", ".", "static", "::", "$", "dbTable", ".", "'`'", ";", "}", "// Get database slave for read", "if", "(", "$", "db", "===", "FALSE", ")", "{", "$", "db", "=", "&", "self", "::", "_getDbSlave", "(", ")", ";", "}", "if", "(", "!", "(", "$", "db", "instanceof", "\\", "PDO", ")", ")", "{", "throw", "new", "Exception", "(", "'Invalid or no database resource set'", ")", ";", "}", "// Return value", "return", "$", "db", "->", "genQuery", "(", "$", "params", ")", ";", "}" ]
Generate a query and return the PDOStatement object @param array $params Query parameters @param \Sonic\Resource\Db $db Database resource, default to class slave @return \PDOStatement @throws Exception
[ "Generate", "a", "query", "and", "return", "the", "PDOStatement", "object" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2750-L2783
train
andyburton/Sonic-Framework
src/Model.php
Model._genSQL
public static function _genSQL ($params = array (), &$db = FALSE) { // Set select if (!isset ($params['select'])) { $params['select'] = '*'; } // Set from if (!isset ($params['from'])) { $params['from'] = '`' . static::$dbTable . '`'; } // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } if (!($db instanceof \PDO)) { throw new Exception ('Invalid or no database resource set'); } // Return value return $db->genSQL ($params); }
php
public static function _genSQL ($params = array (), &$db = FALSE) { // Set select if (!isset ($params['select'])) { $params['select'] = '*'; } // Set from if (!isset ($params['from'])) { $params['from'] = '`' . static::$dbTable . '`'; } // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } if (!($db instanceof \PDO)) { throw new Exception ('Invalid or no database resource set'); } // Return value return $db->genSQL ($params); }
[ "public", "static", "function", "_genSQL", "(", "$", "params", "=", "array", "(", ")", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Set select", "if", "(", "!", "isset", "(", "$", "params", "[", "'select'", "]", ")", ")", "{", "$", "params", "[", "'select'", "]", "=", "'*'", ";", "}", "// Set from", "if", "(", "!", "isset", "(", "$", "params", "[", "'from'", "]", ")", ")", "{", "$", "params", "[", "'from'", "]", "=", "'`'", ".", "static", "::", "$", "dbTable", ".", "'`'", ";", "}", "// Get database slave for read", "if", "(", "$", "db", "===", "FALSE", ")", "{", "$", "db", "=", "&", "self", "::", "_getDbSlave", "(", ")", ";", "}", "if", "(", "!", "(", "$", "db", "instanceof", "\\", "PDO", ")", ")", "{", "throw", "new", "Exception", "(", "'Invalid or no database resource set'", ")", ";", "}", "// Return value", "return", "$", "db", "->", "genSQL", "(", "$", "params", ")", ";", "}" ]
Generate the SQL for a query on the model @param array $params Parameter array @param \PDO $db Database connection to use, default db @return string
[ "Generate", "the", "SQL", "for", "a", "query", "on", "the", "model" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2793-L2826
train
andyburton/Sonic-Framework
src/Model.php
Model._toXML
public static function _toXML ($params = array (), $attributes = FALSE, &$db = FALSE) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); // Create DOMDocument $doc = new \DOMDocument ('1.0', 'UTF-8'); // Create root node $xml = $doc->createElement ('elements'); $doc->appendChild ($xml); // Get objects $rows = static::_toArray ($params, $attributes, $db); // For each row foreach ($rows as $row) { // Create the node $node = $doc->createElement ($class); // Set each attribute foreach ($row as $name => $val) { $node->appendChild ($doc->createElement (strtolower ($name), htmlentities ($val))); } // Add node $xml->appendChild ($node); } // Return doc return $doc; }
php
public static function _toXML ($params = array (), $attributes = FALSE, &$db = FALSE) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); // Create DOMDocument $doc = new \DOMDocument ('1.0', 'UTF-8'); // Create root node $xml = $doc->createElement ('elements'); $doc->appendChild ($xml); // Get objects $rows = static::_toArray ($params, $attributes, $db); // For each row foreach ($rows as $row) { // Create the node $node = $doc->createElement ($class); // Set each attribute foreach ($row as $name => $val) { $node->appendChild ($doc->createElement (strtolower ($name), htmlentities ($val))); } // Add node $xml->appendChild ($node); } // Return doc return $doc; }
[ "public", "static", "function", "_toXML", "(", "$", "params", "=", "array", "(", ")", ",", "$", "attributes", "=", "FALSE", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Set class name for the elements", "// Remove the Sonic\\Model prefix and convert namespace \\ to _", "$", "class", "=", "str_replace", "(", "'\\\\'", ",", "'_'", ",", "str_replace", "(", "'sonic\\\\model\\\\'", ",", "''", ",", "strtolower", "(", "get_called_class", "(", ")", ")", ")", ")", ";", "// Create DOMDocument", "$", "doc", "=", "new", "\\", "DOMDocument", "(", "'1.0'", ",", "'UTF-8'", ")", ";", "// Create root node", "$", "xml", "=", "$", "doc", "->", "createElement", "(", "'elements'", ")", ";", "$", "doc", "->", "appendChild", "(", "$", "xml", ")", ";", "// Get objects", "$", "rows", "=", "static", "::", "_toArray", "(", "$", "params", ",", "$", "attributes", ",", "$", "db", ")", ";", "// For each row", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "// Create the node", "$", "node", "=", "$", "doc", "->", "createElement", "(", "$", "class", ")", ";", "// Set each attribute", "foreach", "(", "$", "row", "as", "$", "name", "=>", "$", "val", ")", "{", "$", "node", "->", "appendChild", "(", "$", "doc", "->", "createElement", "(", "strtolower", "(", "$", "name", ")", ",", "htmlentities", "(", "$", "val", ")", ")", ")", ";", "}", "// Add node", "$", "xml", "->", "appendChild", "(", "$", "node", ")", ";", "}", "// Return doc", "return", "$", "doc", ";", "}" ]
Return a DOM tree with objects for given query parameters @param array $params Parameter array @param array|boolean $attributes Attributes to include, default to false i.e all attributes @param \PDO $db Database connection to use @return \DOMDocument|boolean
[ "Return", "a", "DOM", "tree", "with", "objects", "for", "given", "query", "parameters" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2837-L2884
train
andyburton/Sonic-Framework
src/Model.php
Model._toJSON
public static function _toJSON ($params = array (), $attributes = FALSE, $addClass = FALSE, &$db = FALSE) { // Get objects $rows = static::_toArray ($params, $attributes, $db); // Add the class name if required if ($addClass) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); foreach ($rows as &$row) { $row['class'] = $class; } } // Return json encoded return json_encode ($rows); }
php
public static function _toJSON ($params = array (), $attributes = FALSE, $addClass = FALSE, &$db = FALSE) { // Get objects $rows = static::_toArray ($params, $attributes, $db); // Add the class name if required if ($addClass) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); foreach ($rows as &$row) { $row['class'] = $class; } } // Return json encoded return json_encode ($rows); }
[ "public", "static", "function", "_toJSON", "(", "$", "params", "=", "array", "(", ")", ",", "$", "attributes", "=", "FALSE", ",", "$", "addClass", "=", "FALSE", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// Get objects", "$", "rows", "=", "static", "::", "_toArray", "(", "$", "params", ",", "$", "attributes", ",", "$", "db", ")", ";", "// Add the class name if required", "if", "(", "$", "addClass", ")", "{", "// Set class name for the elements", "// Remove the Sonic\\Model prefix and convert namespace \\ to _", "$", "class", "=", "str_replace", "(", "'\\\\'", ",", "'_'", ",", "str_replace", "(", "'sonic\\\\model\\\\'", ",", "''", ",", "strtolower", "(", "get_called_class", "(", ")", ")", ")", ")", ";", "foreach", "(", "$", "rows", "as", "&", "$", "row", ")", "{", "$", "row", "[", "'class'", "]", "=", "$", "class", ";", "}", "}", "// Return json encoded", "return", "json_encode", "(", "$", "rows", ")", ";", "}" ]
Return a JSON encoded string with objects for given query parameters @param array $params Parameter array @param array|boolean $attributes Attributes to include, default to false i.e all attributes @param boolean $addClass Whether to add the class name to each exported object @param \PDO $db Database connection to use @return object|boolean
[ "Return", "a", "JSON", "encoded", "string", "with", "objects", "for", "given", "query", "parameters" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2896-L2924
train
andyburton/Sonic-Framework
src/Model.php
Model._toArray
public static function _toArray ($params = array (), $attributes = FALSE, &$db = FALSE) { // If no attributes are set to display, get all class attributes with get allowed if ($attributes === FALSE) { $attributes = array (); $obj = new static; foreach (array_keys (static::$attributes) as $name) { if ($obj->attributeGet ($name)) { $attributes[] = $name; } } } // Select all attributes from the database if none are set if (!isset ($params['select'])) { $params['select'] = '*'; } // Get data $rows = static::_getValues ($params, $db); // If no data was returned return FALSE if ($rows === FALSE) { return FALSE; } // Set array $arr = array (); // For each row foreach ($rows as $row) { // Create the sub array $obj = array (); // Set each attribute foreach ($attributes as $name) { $obj[$name] = isset ($row[$name])? $row[$name] : NULL; } // Add to main array $arr[] = $obj; } // Return array return $arr; }
php
public static function _toArray ($params = array (), $attributes = FALSE, &$db = FALSE) { // If no attributes are set to display, get all class attributes with get allowed if ($attributes === FALSE) { $attributes = array (); $obj = new static; foreach (array_keys (static::$attributes) as $name) { if ($obj->attributeGet ($name)) { $attributes[] = $name; } } } // Select all attributes from the database if none are set if (!isset ($params['select'])) { $params['select'] = '*'; } // Get data $rows = static::_getValues ($params, $db); // If no data was returned return FALSE if ($rows === FALSE) { return FALSE; } // Set array $arr = array (); // For each row foreach ($rows as $row) { // Create the sub array $obj = array (); // Set each attribute foreach ($attributes as $name) { $obj[$name] = isset ($row[$name])? $row[$name] : NULL; } // Add to main array $arr[] = $obj; } // Return array return $arr; }
[ "public", "static", "function", "_toArray", "(", "$", "params", "=", "array", "(", ")", ",", "$", "attributes", "=", "FALSE", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// If no attributes are set to display, get all class attributes with get allowed", "if", "(", "$", "attributes", "===", "FALSE", ")", "{", "$", "attributes", "=", "array", "(", ")", ";", "$", "obj", "=", "new", "static", ";", "foreach", "(", "array_keys", "(", "static", "::", "$", "attributes", ")", "as", "$", "name", ")", "{", "if", "(", "$", "obj", "->", "attributeGet", "(", "$", "name", ")", ")", "{", "$", "attributes", "[", "]", "=", "$", "name", ";", "}", "}", "}", "// Select all attributes from the database if none are set", "if", "(", "!", "isset", "(", "$", "params", "[", "'select'", "]", ")", ")", "{", "$", "params", "[", "'select'", "]", "=", "'*'", ";", "}", "// Get data", "$", "rows", "=", "static", "::", "_getValues", "(", "$", "params", ",", "$", "db", ")", ";", "// If no data was returned return FALSE", "if", "(", "$", "rows", "===", "FALSE", ")", "{", "return", "FALSE", ";", "}", "// Set array", "$", "arr", "=", "array", "(", ")", ";", "// For each row", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "// Create the sub array", "$", "obj", "=", "array", "(", ")", ";", "// Set each attribute", "foreach", "(", "$", "attributes", "as", "$", "name", ")", "{", "$", "obj", "[", "$", "name", "]", "=", "isset", "(", "$", "row", "[", "$", "name", "]", ")", "?", "$", "row", "[", "$", "name", "]", ":", "NULL", ";", "}", "// Add to main array", "$", "arr", "[", "]", "=", "$", "obj", ";", "}", "// Return array", "return", "$", "arr", ";", "}" ]
Return an array with object attributes for given query parameters @param array $params Parameter array @param array|boolean $attributes Attributes to include, default to false i.e all attributes @param \PDO $db Database connection to use @return object|boolean
[ "Return", "an", "array", "with", "object", "attributes", "for", "given", "query", "parameters" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2935-L3006
train
andyburton/Sonic-Framework
src/Model.php
Model._getRelationPaths
public static function _getRelationPaths ($endClass, $fork = array (), $paths = array (), $processed = array (), $depth = 0) { // Remove first \ from end class if ($endClass[0] == '\\') { $endClass = substr ($endClass, 1); } // Make sure fork is an array if ($fork === FALSE) { $fork = array (); } // Set variables $class = get_called_class (); $processed[] = strtolower ($class); $parent = $paths; $depth++; // Find paths to the end class // Loop through attributes foreach (static::$attributes as $name => $attribute) { // No attribute relation or class for the relation if (!isset ($attribute['relation']) || !class_exists ($attribute['relation']) || (isset ($fork[$class]) && $fork[$class] != $name)) { continue; } // Attribute relation matches the end class so add to paths else if ($attribute['relation'] == $endClass) { $paths[$name] = $depth; continue; } // The attribute relation has already been processed else if (in_array (strtolower ($attribute['relation']), $processed)) { continue; } // Recursively look at relation attributes else { $subPaths = $attribute['relation']::_getRelationPaths ($endClass, $fork, $parent, $processed, $depth); if ($subPaths) { $paths[$name] = $subPaths; } } } return $paths; }
php
public static function _getRelationPaths ($endClass, $fork = array (), $paths = array (), $processed = array (), $depth = 0) { // Remove first \ from end class if ($endClass[0] == '\\') { $endClass = substr ($endClass, 1); } // Make sure fork is an array if ($fork === FALSE) { $fork = array (); } // Set variables $class = get_called_class (); $processed[] = strtolower ($class); $parent = $paths; $depth++; // Find paths to the end class // Loop through attributes foreach (static::$attributes as $name => $attribute) { // No attribute relation or class for the relation if (!isset ($attribute['relation']) || !class_exists ($attribute['relation']) || (isset ($fork[$class]) && $fork[$class] != $name)) { continue; } // Attribute relation matches the end class so add to paths else if ($attribute['relation'] == $endClass) { $paths[$name] = $depth; continue; } // The attribute relation has already been processed else if (in_array (strtolower ($attribute['relation']), $processed)) { continue; } // Recursively look at relation attributes else { $subPaths = $attribute['relation']::_getRelationPaths ($endClass, $fork, $parent, $processed, $depth); if ($subPaths) { $paths[$name] = $subPaths; } } } return $paths; }
[ "public", "static", "function", "_getRelationPaths", "(", "$", "endClass", ",", "$", "fork", "=", "array", "(", ")", ",", "$", "paths", "=", "array", "(", ")", ",", "$", "processed", "=", "array", "(", ")", ",", "$", "depth", "=", "0", ")", "{", "// Remove first \\ from end class", "if", "(", "$", "endClass", "[", "0", "]", "==", "'\\\\'", ")", "{", "$", "endClass", "=", "substr", "(", "$", "endClass", ",", "1", ")", ";", "}", "// Make sure fork is an array", "if", "(", "$", "fork", "===", "FALSE", ")", "{", "$", "fork", "=", "array", "(", ")", ";", "}", "// Set variables", "$", "class", "=", "get_called_class", "(", ")", ";", "$", "processed", "[", "]", "=", "strtolower", "(", "$", "class", ")", ";", "$", "parent", "=", "$", "paths", ";", "$", "depth", "++", ";", "// Find paths to the end class", "// Loop through attributes", "foreach", "(", "static", "::", "$", "attributes", "as", "$", "name", "=>", "$", "attribute", ")", "{", "// No attribute relation or class for the relation", "if", "(", "!", "isset", "(", "$", "attribute", "[", "'relation'", "]", ")", "||", "!", "class_exists", "(", "$", "attribute", "[", "'relation'", "]", ")", "||", "(", "isset", "(", "$", "fork", "[", "$", "class", "]", ")", "&&", "$", "fork", "[", "$", "class", "]", "!=", "$", "name", ")", ")", "{", "continue", ";", "}", "// Attribute relation matches the end class so add to paths", "else", "if", "(", "$", "attribute", "[", "'relation'", "]", "==", "$", "endClass", ")", "{", "$", "paths", "[", "$", "name", "]", "=", "$", "depth", ";", "continue", ";", "}", "// The attribute relation has already been processed", "else", "if", "(", "in_array", "(", "strtolower", "(", "$", "attribute", "[", "'relation'", "]", ")", ",", "$", "processed", ")", ")", "{", "continue", ";", "}", "// Recursively look at relation attributes", "else", "{", "$", "subPaths", "=", "$", "attribute", "[", "'relation'", "]", "::", "_getRelationPaths", "(", "$", "endClass", ",", "$", "fork", ",", "$", "parent", ",", "$", "processed", ",", "$", "depth", ")", ";", "if", "(", "$", "subPaths", ")", "{", "$", "paths", "[", "$", "name", "]", "=", "$", "subPaths", ";", "}", "}", "}", "return", "$", "paths", ";", "}" ]
Return an array of available paths to a related class @param string $class Destination class @param array $fork Used to determine which fork to use when there are multiple attributes related to the same class (see getRelated comments) @param array $paths Available paths, set recursively @param array $processed Already processed classes, set recursively @param integer $depth Path depth, set recursively @return array
[ "Return", "an", "array", "of", "available", "paths", "to", "a", "related", "class" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3020-L3091
train
andyburton/Sonic-Framework
src/Model.php
Model._getRelation
public static function _getRelation ($obj, $path, $params = array ()) { foreach ($path as $class => $name) { $class = get_class ($obj); $childClass = $class::$attributes[$name]['relation']; if ($obj->iget ($name)) { $params['where'][] = array ($childClass::$pk, $obj->iget ($name)); $obj = $childClass::_Read ($params); } else { return FALSE; } } return $obj; }
php
public static function _getRelation ($obj, $path, $params = array ()) { foreach ($path as $class => $name) { $class = get_class ($obj); $childClass = $class::$attributes[$name]['relation']; if ($obj->iget ($name)) { $params['where'][] = array ($childClass::$pk, $obj->iget ($name)); $obj = $childClass::_Read ($params); } else { return FALSE; } } return $obj; }
[ "public", "static", "function", "_getRelation", "(", "$", "obj", ",", "$", "path", ",", "$", "params", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "path", "as", "$", "class", "=>", "$", "name", ")", "{", "$", "class", "=", "get_class", "(", "$", "obj", ")", ";", "$", "childClass", "=", "$", "class", "::", "$", "attributes", "[", "$", "name", "]", "[", "'relation'", "]", ";", "if", "(", "$", "obj", "->", "iget", "(", "$", "name", ")", ")", "{", "$", "params", "[", "'where'", "]", "[", "]", "=", "array", "(", "$", "childClass", "::", "$", "pk", ",", "$", "obj", "->", "iget", "(", "$", "name", ")", ")", ";", "$", "obj", "=", "$", "childClass", "::", "_Read", "(", "$", "params", ")", ";", "}", "else", "{", "return", "FALSE", ";", "}", "}", "return", "$", "obj", ";", "}" ]
Return a related object for a given object and path @param Model $obj Starting object @param array $path Path to the end object @param array $params Query parameter array @return \Sonic\Model|boolean
[ "Return", "a", "related", "object", "for", "a", "given", "object", "and", "path" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3140-L3163
train
andyburton/Sonic-Framework
src/Model.php
Model._getChildren
public static function _getChildren ($class, $id, $recursive = FALSE, $key = FALSE, $params = array ()) { // Remove first \ from class if ($class[0] == '\\') { $class = substr ($class, 1); } // Get current (parent) class $parent = get_called_class (); // Find the child variable pointing to the parent $var = FALSE; foreach ($class::$attributes as $name => $attribute) { if (isset ($attribute['relation']) && class_exists ($attribute['relation']) && $attribute['relation'] == $parent) { $var = $name; break; } } // If no argument if ($var === FALSE) { return array (); } // Get children $qParams = $params; if (is_null ($id)) { $qParams['where'][] = array ($var, 'NULL', 'IS'); } else { $qParams['where'][] = array ($var, $id); } $children = $class::_getObjects ($qParams, $key); // Get recursively if ($recursive) { foreach ($children as &$child) { $child->children = $child->getChildren ($class, $recursive, FALSE, $key, $params); } } // Return children return $children; }
php
public static function _getChildren ($class, $id, $recursive = FALSE, $key = FALSE, $params = array ()) { // Remove first \ from class if ($class[0] == '\\') { $class = substr ($class, 1); } // Get current (parent) class $parent = get_called_class (); // Find the child variable pointing to the parent $var = FALSE; foreach ($class::$attributes as $name => $attribute) { if (isset ($attribute['relation']) && class_exists ($attribute['relation']) && $attribute['relation'] == $parent) { $var = $name; break; } } // If no argument if ($var === FALSE) { return array (); } // Get children $qParams = $params; if (is_null ($id)) { $qParams['where'][] = array ($var, 'NULL', 'IS'); } else { $qParams['where'][] = array ($var, $id); } $children = $class::_getObjects ($qParams, $key); // Get recursively if ($recursive) { foreach ($children as &$child) { $child->children = $child->getChildren ($class, $recursive, FALSE, $key, $params); } } // Return children return $children; }
[ "public", "static", "function", "_getChildren", "(", "$", "class", ",", "$", "id", ",", "$", "recursive", "=", "FALSE", ",", "$", "key", "=", "FALSE", ",", "$", "params", "=", "array", "(", ")", ")", "{", "// Remove first \\ from class", "if", "(", "$", "class", "[", "0", "]", "==", "'\\\\'", ")", "{", "$", "class", "=", "substr", "(", "$", "class", ",", "1", ")", ";", "}", "// Get current (parent) class", "$", "parent", "=", "get_called_class", "(", ")", ";", "// Find the child variable pointing to the parent", "$", "var", "=", "FALSE", ";", "foreach", "(", "$", "class", "::", "$", "attributes", "as", "$", "name", "=>", "$", "attribute", ")", "{", "if", "(", "isset", "(", "$", "attribute", "[", "'relation'", "]", ")", "&&", "class_exists", "(", "$", "attribute", "[", "'relation'", "]", ")", "&&", "$", "attribute", "[", "'relation'", "]", "==", "$", "parent", ")", "{", "$", "var", "=", "$", "name", ";", "break", ";", "}", "}", "// If no argument", "if", "(", "$", "var", "===", "FALSE", ")", "{", "return", "array", "(", ")", ";", "}", "// Get children", "$", "qParams", "=", "$", "params", ";", "if", "(", "is_null", "(", "$", "id", ")", ")", "{", "$", "qParams", "[", "'where'", "]", "[", "]", "=", "array", "(", "$", "var", ",", "'NULL'", ",", "'IS'", ")", ";", "}", "else", "{", "$", "qParams", "[", "'where'", "]", "[", "]", "=", "array", "(", "$", "var", ",", "$", "id", ")", ";", "}", "$", "children", "=", "$", "class", "::", "_getObjects", "(", "$", "qParams", ",", "$", "key", ")", ";", "// Get recursively", "if", "(", "$", "recursive", ")", "{", "foreach", "(", "$", "children", "as", "&", "$", "child", ")", "{", "$", "child", "->", "children", "=", "$", "child", "->", "getChildren", "(", "$", "class", ",", "$", "recursive", ",", "FALSE", ",", "$", "key", ",", "$", "params", ")", ";", "}", "}", "// Return children", "return", "$", "children", ";", "}" ]
Return child objects with an attribute matching the current class and specified ID @param string $class Child class @param integer $id Parent ID @param boolean $recursive Whether to load childrens children. This will create an object attribute called 'children' on all objects @param string $key Attribute to use as array key @param array $params Query parameter array @return array|boolean
[ "Return", "child", "objects", "with", "an", "attribute", "matching", "the", "current", "class", "and", "specified", "ID" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3177-L3246
train
andyburton/Sonic-Framework
src/Model.php
Model.getFromPivot
public function getFromPivot (\Sonic\Model $target, \Sonic\Model $pivot, $key = FALSE, $params = []) { // Find the pivot attribute pointing to the source $sourceClass = get_called_class (); $sourceRef = FALSE; foreach ($pivot::$attributes as $name => $attribute) { if (isset ($attribute['relation']) && $attribute['relation'] == $sourceClass) { $sourceRef = $name; break; } } if (!$sourceRef) { return FALSE; } // Find the pivot attribute pointing to the target $targetClass = get_class ($target); $targetRef = FALSE; foreach ($pivot::$attributes as $name => $attribute) { if (isset ($attribute['relation']) && $attribute['relation'] == $targetClass) { $targetRef = $name; break; } } if (!$targetRef) { return FALSE; } // Query parameters if (!isset ($params['select'])) { $params['select'] = 'DISTINCT t.*'; } if (isset ($params['from']) && !is_array ($params['from'])) { $params['from'] = [$params['from']]; } $params['from'][] = $target::$dbTable . ' as t'; $params['from'][] = $pivot::$dbTable . ' as p'; $params['where'][] = ['p.' . $sourceRef, $this->getPK ()]; $params['where'][] = 'p.' . $targetRef . ' = t.' . $target::$pk; // Get related objects return $target::_getObjects ($params, $key); }
php
public function getFromPivot (\Sonic\Model $target, \Sonic\Model $pivot, $key = FALSE, $params = []) { // Find the pivot attribute pointing to the source $sourceClass = get_called_class (); $sourceRef = FALSE; foreach ($pivot::$attributes as $name => $attribute) { if (isset ($attribute['relation']) && $attribute['relation'] == $sourceClass) { $sourceRef = $name; break; } } if (!$sourceRef) { return FALSE; } // Find the pivot attribute pointing to the target $targetClass = get_class ($target); $targetRef = FALSE; foreach ($pivot::$attributes as $name => $attribute) { if (isset ($attribute['relation']) && $attribute['relation'] == $targetClass) { $targetRef = $name; break; } } if (!$targetRef) { return FALSE; } // Query parameters if (!isset ($params['select'])) { $params['select'] = 'DISTINCT t.*'; } if (isset ($params['from']) && !is_array ($params['from'])) { $params['from'] = [$params['from']]; } $params['from'][] = $target::$dbTable . ' as t'; $params['from'][] = $pivot::$dbTable . ' as p'; $params['where'][] = ['p.' . $sourceRef, $this->getPK ()]; $params['where'][] = 'p.' . $targetRef . ' = t.' . $target::$pk; // Get related objects return $target::_getObjects ($params, $key); }
[ "public", "function", "getFromPivot", "(", "\\", "Sonic", "\\", "Model", "$", "target", ",", "\\", "Sonic", "\\", "Model", "$", "pivot", ",", "$", "key", "=", "FALSE", ",", "$", "params", "=", "[", "]", ")", "{", "// Find the pivot attribute pointing to the source", "$", "sourceClass", "=", "get_called_class", "(", ")", ";", "$", "sourceRef", "=", "FALSE", ";", "foreach", "(", "$", "pivot", "::", "$", "attributes", "as", "$", "name", "=>", "$", "attribute", ")", "{", "if", "(", "isset", "(", "$", "attribute", "[", "'relation'", "]", ")", "&&", "$", "attribute", "[", "'relation'", "]", "==", "$", "sourceClass", ")", "{", "$", "sourceRef", "=", "$", "name", ";", "break", ";", "}", "}", "if", "(", "!", "$", "sourceRef", ")", "{", "return", "FALSE", ";", "}", "// Find the pivot attribute pointing to the target", "$", "targetClass", "=", "get_class", "(", "$", "target", ")", ";", "$", "targetRef", "=", "FALSE", ";", "foreach", "(", "$", "pivot", "::", "$", "attributes", "as", "$", "name", "=>", "$", "attribute", ")", "{", "if", "(", "isset", "(", "$", "attribute", "[", "'relation'", "]", ")", "&&", "$", "attribute", "[", "'relation'", "]", "==", "$", "targetClass", ")", "{", "$", "targetRef", "=", "$", "name", ";", "break", ";", "}", "}", "if", "(", "!", "$", "targetRef", ")", "{", "return", "FALSE", ";", "}", "// Query parameters", "if", "(", "!", "isset", "(", "$", "params", "[", "'select'", "]", ")", ")", "{", "$", "params", "[", "'select'", "]", "=", "'DISTINCT t.*'", ";", "}", "if", "(", "isset", "(", "$", "params", "[", "'from'", "]", ")", "&&", "!", "is_array", "(", "$", "params", "[", "'from'", "]", ")", ")", "{", "$", "params", "[", "'from'", "]", "=", "[", "$", "params", "[", "'from'", "]", "]", ";", "}", "$", "params", "[", "'from'", "]", "[", "]", "=", "$", "target", "::", "$", "dbTable", ".", "' as t'", ";", "$", "params", "[", "'from'", "]", "[", "]", "=", "$", "pivot", "::", "$", "dbTable", ".", "' as p'", ";", "$", "params", "[", "'where'", "]", "[", "]", "=", "[", "'p.'", ".", "$", "sourceRef", ",", "$", "this", "->", "getPK", "(", ")", "]", ";", "$", "params", "[", "'where'", "]", "[", "]", "=", "'p.'", ".", "$", "targetRef", ".", "' = t.'", ".", "$", "target", "::", "$", "pk", ";", "// Get related objects", "return", "$", "target", "::", "_getObjects", "(", "$", "params", ",", "$", "key", ")", ";", "}" ]
Return related objects from a many-to-many pivot table @param \Sonic\Model $target Target objects to return @param \Sonic\Model $pivot Pivot object @return boolean|Model\Collection
[ "Return", "related", "objects", "from", "a", "many", "-", "to", "-", "many", "pivot", "table" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3278-L3343
train
andyburton/Sonic-Framework
src/Model.php
Model._getGrid
public static function _getGrid ($params = array (), $relations = array (), &$db = FALSE) { // If no limit has been set if (!$params || !isset ($params['limit'])) { // Set default query limit $params['limit'] = array (0, 50); } // Get data if ($relations) { $objs = static::_getObjects ($params, $db); $data = array (); foreach ($objs as $obj) { $attributes = is_array ($params['select'])? $params['select'] : explode (',', $params['select']); foreach ($attributes as &$val) { $val = trim ($val); } $data[] = $obj->toArray ($attributes, $relations); } } else { $data = static::_getValues ($params, $db); } // Get count $count = self::_count ($params, $db); // If there was a problem return FALSE if ($count === FALSE || $data === FALSE) { return FALSE; } // Add class (for API XML response) $class = self::_getClass (); foreach ($data as &$row) { $row['class'] = $class; } // Return grid return array ( 'total' => $count, 'rows' => $data ); }
php
public static function _getGrid ($params = array (), $relations = array (), &$db = FALSE) { // If no limit has been set if (!$params || !isset ($params['limit'])) { // Set default query limit $params['limit'] = array (0, 50); } // Get data if ($relations) { $objs = static::_getObjects ($params, $db); $data = array (); foreach ($objs as $obj) { $attributes = is_array ($params['select'])? $params['select'] : explode (',', $params['select']); foreach ($attributes as &$val) { $val = trim ($val); } $data[] = $obj->toArray ($attributes, $relations); } } else { $data = static::_getValues ($params, $db); } // Get count $count = self::_count ($params, $db); // If there was a problem return FALSE if ($count === FALSE || $data === FALSE) { return FALSE; } // Add class (for API XML response) $class = self::_getClass (); foreach ($data as &$row) { $row['class'] = $class; } // Return grid return array ( 'total' => $count, 'rows' => $data ); }
[ "public", "static", "function", "_getGrid", "(", "$", "params", "=", "array", "(", ")", ",", "$", "relations", "=", "array", "(", ")", ",", "&", "$", "db", "=", "FALSE", ")", "{", "// If no limit has been set", "if", "(", "!", "$", "params", "||", "!", "isset", "(", "$", "params", "[", "'limit'", "]", ")", ")", "{", "// Set default query limit", "$", "params", "[", "'limit'", "]", "=", "array", "(", "0", ",", "50", ")", ";", "}", "// Get data", "if", "(", "$", "relations", ")", "{", "$", "objs", "=", "static", "::", "_getObjects", "(", "$", "params", ",", "$", "db", ")", ";", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "objs", "as", "$", "obj", ")", "{", "$", "attributes", "=", "is_array", "(", "$", "params", "[", "'select'", "]", ")", "?", "$", "params", "[", "'select'", "]", ":", "explode", "(", "','", ",", "$", "params", "[", "'select'", "]", ")", ";", "foreach", "(", "$", "attributes", "as", "&", "$", "val", ")", "{", "$", "val", "=", "trim", "(", "$", "val", ")", ";", "}", "$", "data", "[", "]", "=", "$", "obj", "->", "toArray", "(", "$", "attributes", ",", "$", "relations", ")", ";", "}", "}", "else", "{", "$", "data", "=", "static", "::", "_getValues", "(", "$", "params", ",", "$", "db", ")", ";", "}", "// Get count", "$", "count", "=", "self", "::", "_count", "(", "$", "params", ",", "$", "db", ")", ";", "// If there was a problem return FALSE", "if", "(", "$", "count", "===", "FALSE", "||", "$", "data", "===", "FALSE", ")", "{", "return", "FALSE", ";", "}", "// Add class (for API XML response)", "$", "class", "=", "self", "::", "_getClass", "(", ")", ";", "foreach", "(", "$", "data", "as", "&", "$", "row", ")", "{", "$", "row", "[", "'class'", "]", "=", "$", "class", ";", "}", "// Return grid", "return", "array", "(", "'total'", "=>", "$", "count", ",", "'rows'", "=>", "$", "data", ")", ";", "}" ]
Return an array of items with total result count @param array $params Array of query parameters - MUST BE ESCAPED! @param array $relations Array of related object attributes or tranformed method attributes to return e.g. related value - 'query_name' => array ('\Sonic\Model\User\Group', 'name') e.g. tranformed value - 'permission_value' => array ('$this', 'getStringValue') @param \PDO $db Database connection to use @return array|boolean
[ "Return", "an", "array", "of", "items", "with", "total", "result", "count" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3356-L3425
train
andyburton/Sonic-Framework
src/Model.php
Model.&
public static function &_getResource ($name) { if (is_array ($name)) { return Sonic::getResource ($name); } else if (isset (static::$defaultResources[$name])) { return Sonic::getResource (static::$defaultResources[$name]); } else { return Sonic::getSelectedResource ($name); } }
php
public static function &_getResource ($name) { if (is_array ($name)) { return Sonic::getResource ($name); } else if (isset (static::$defaultResources[$name])) { return Sonic::getResource (static::$defaultResources[$name]); } else { return Sonic::getSelectedResource ($name); } }
[ "public", "static", "function", "&", "_getResource", "(", "$", "name", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "return", "Sonic", "::", "getResource", "(", "$", "name", ")", ";", "}", "else", "if", "(", "isset", "(", "static", "::", "$", "defaultResources", "[", "$", "name", "]", ")", ")", "{", "return", "Sonic", "::", "getResource", "(", "static", "::", "$", "defaultResources", "[", "$", "name", "]", ")", ";", "}", "else", "{", "return", "Sonic", "::", "getSelectedResource", "(", "$", "name", ")", ";", "}", "}" ]
Return a class resource This will either be the default as defined for the class or the global framework resource @param string|array $name Resource name @return object|boolean
[ "Return", "a", "class", "resource", "This", "will", "either", "be", "the", "default", "as", "defined", "for", "the", "class", "or", "the", "global", "framework", "resource" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3435-L3451
train
andyburton/Sonic-Framework
src/Model.php
Model.&
public static function &_getRandomDbResource ($group) { $obj = FALSE; while (Sonic::countResourceGroup ($group) > 0) { $name = Sonic::selectRandomResource ($group); $obj =& Sonic::getResource (array ($group, $name)); // If a PDO object if ($obj instanceof \PDO) { // Attempt to connect to the resource // This will throw an exception if it fails or break the loop if it succeeds if ($obj instanceof Resource\Db) { try { $obj->Connect (); // Set as default group object for persistence Sonic::setSelectedResource ($group, $name); break; } catch (\PDOException $e) { // Do nothing } } // Else not a framework database objects so break the loop to use it else { break; } } // Remove resource from the framework as its not valid // then continue to the next object Sonic::removeResource ($group, $name); $obj = FALSE; } return $obj; }
php
public static function &_getRandomDbResource ($group) { $obj = FALSE; while (Sonic::countResourceGroup ($group) > 0) { $name = Sonic::selectRandomResource ($group); $obj =& Sonic::getResource (array ($group, $name)); // If a PDO object if ($obj instanceof \PDO) { // Attempt to connect to the resource // This will throw an exception if it fails or break the loop if it succeeds if ($obj instanceof Resource\Db) { try { $obj->Connect (); // Set as default group object for persistence Sonic::setSelectedResource ($group, $name); break; } catch (\PDOException $e) { // Do nothing } } // Else not a framework database objects so break the loop to use it else { break; } } // Remove resource from the framework as its not valid // then continue to the next object Sonic::removeResource ($group, $name); $obj = FALSE; } return $obj; }
[ "public", "static", "function", "&", "_getRandomDbResource", "(", "$", "group", ")", "{", "$", "obj", "=", "FALSE", ";", "while", "(", "Sonic", "::", "countResourceGroup", "(", "$", "group", ")", ">", "0", ")", "{", "$", "name", "=", "Sonic", "::", "selectRandomResource", "(", "$", "group", ")", ";", "$", "obj", "=", "&", "Sonic", "::", "getResource", "(", "array", "(", "$", "group", ",", "$", "name", ")", ")", ";", "// If a PDO object", "if", "(", "$", "obj", "instanceof", "\\", "PDO", ")", "{", "// Attempt to connect to the resource", "// This will throw an exception if it fails or break the loop if it succeeds", "if", "(", "$", "obj", "instanceof", "Resource", "\\", "Db", ")", "{", "try", "{", "$", "obj", "->", "Connect", "(", ")", ";", "// Set as default group object for persistence", "Sonic", "::", "setSelectedResource", "(", "$", "group", ",", "$", "name", ")", ";", "break", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "// Do nothing", "}", "}", "// Else not a framework database objects so break the loop to use it", "else", "{", "break", ";", "}", "}", "// Remove resource from the framework as its not valid", "// then continue to the next object", "Sonic", "::", "removeResource", "(", "$", "group", ",", "$", "name", ")", ";", "$", "obj", "=", "FALSE", ";", "}", "return", "$", "obj", ";", "}" ]
Return random database resource object @param string $group Group name @return boolean|\Sonic\Model\PDO
[ "Return", "random", "database", "resource", "object" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3460-L3518
train
andyburton/Sonic-Framework
src/Model.php
Model.changelog
private function changelog ($type) { // If changelog or type is disabled for the class return FALSE if (isset (static::$changelogIgnore)) { if (static::$changelogIgnore === TRUE || is_array (static::$changelogIgnore) && in_array ($type, static::$changelogIgnore)) { return FALSE; } } // If there is no changelog resource defined or we're dealing with a changelog object return FALSE if (!($this->getResource ('changelog') instanceof Resource\Change\Log) || $this instanceof Resource\Change\Log || $this instanceof Resource\Change\Log\Column) { return FALSE; } // Default return TRUE return TRUE; }
php
private function changelog ($type) { // If changelog or type is disabled for the class return FALSE if (isset (static::$changelogIgnore)) { if (static::$changelogIgnore === TRUE || is_array (static::$changelogIgnore) && in_array ($type, static::$changelogIgnore)) { return FALSE; } } // If there is no changelog resource defined or we're dealing with a changelog object return FALSE if (!($this->getResource ('changelog') instanceof Resource\Change\Log) || $this instanceof Resource\Change\Log || $this instanceof Resource\Change\Log\Column) { return FALSE; } // Default return TRUE return TRUE; }
[ "private", "function", "changelog", "(", "$", "type", ")", "{", "// If changelog or type is disabled for the class return FALSE", "if", "(", "isset", "(", "static", "::", "$", "changelogIgnore", ")", ")", "{", "if", "(", "static", "::", "$", "changelogIgnore", "===", "TRUE", "||", "is_array", "(", "static", "::", "$", "changelogIgnore", ")", "&&", "in_array", "(", "$", "type", ",", "static", "::", "$", "changelogIgnore", ")", ")", "{", "return", "FALSE", ";", "}", "}", "// If there is no changelog resource defined or we're dealing with a changelog object return FALSE", "if", "(", "!", "(", "$", "this", "->", "getResource", "(", "'changelog'", ")", "instanceof", "Resource", "\\", "Change", "\\", "Log", ")", "||", "$", "this", "instanceof", "Resource", "\\", "Change", "\\", "Log", "||", "$", "this", "instanceof", "Resource", "\\", "Change", "\\", "Log", "\\", "Column", ")", "{", "return", "FALSE", ";", "}", "// Default return TRUE", "return", "TRUE", ";", "}" ]
Whether to write to the changelog @param string $type Change type (create, update, delete) @return boolean
[ "Whether", "to", "write", "to", "the", "changelog" ]
a5999448a0abab4d542413002a780ede391e7374
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3624-L3652
train
frankfoerster/cakephp-asset
src/View/Helper/AssetHelper.php
AssetHelper.css
public function css($path, $plugin = false, $appendTime = true, array $attributes = []) { $href = $this->getUrl($path, $plugin, $appendTime); return '<link rel="stylesheet" type="text/css" href="' . $href . '"' . $this->_renderAttributes($attributes) . '>'; }
php
public function css($path, $plugin = false, $appendTime = true, array $attributes = []) { $href = $this->getUrl($path, $plugin, $appendTime); return '<link rel="stylesheet" type="text/css" href="' . $href . '"' . $this->_renderAttributes($attributes) . '>'; }
[ "public", "function", "css", "(", "$", "path", ",", "$", "plugin", "=", "false", ",", "$", "appendTime", "=", "true", ",", "array", "$", "attributes", "=", "[", "]", ")", "{", "$", "href", "=", "$", "this", "->", "getUrl", "(", "$", "path", ",", "$", "plugin", ",", "$", "appendTime", ")", ";", "return", "'<link rel=\"stylesheet\" type=\"text/css\" href=\"'", ".", "$", "href", ".", "'\"'", ".", "$", "this", "->", "_renderAttributes", "(", "$", "attributes", ")", ".", "'>'", ";", "}" ]
Output a link stylesheet tag for a specific css file and optionally append a last modified timestamp to clear the browser cache. @param string $path The path to the css file relative to WEBROOT @param bool $plugin Either false or the name of a plugin. @param bool $appendTime Whether to append a last modified timestamp to the url. @param array $attributes Additional html attributes to render on the link tag. @return string
[ "Output", "a", "link", "stylesheet", "tag", "for", "a", "specific", "css", "file", "and", "optionally", "append", "a", "last", "modified", "timestamp", "to", "clear", "the", "browser", "cache", "." ]
07b3646006d9bbf4f2d6fceeb319373392752b63
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L52-L57
train
frankfoerster/cakephp-asset
src/View/Helper/AssetHelper.php
AssetHelper.js
public function js($path, $plugin = false, $appendTime = true, array $attributes = []) { $src = $this->getUrl($path, $plugin, $appendTime); return '<script type="text/javascript" src="' . $src . '"' . $this->_renderAttributes($attributes) . '></script>'; }
php
public function js($path, $plugin = false, $appendTime = true, array $attributes = []) { $src = $this->getUrl($path, $plugin, $appendTime); return '<script type="text/javascript" src="' . $src . '"' . $this->_renderAttributes($attributes) . '></script>'; }
[ "public", "function", "js", "(", "$", "path", ",", "$", "plugin", "=", "false", ",", "$", "appendTime", "=", "true", ",", "array", "$", "attributes", "=", "[", "]", ")", "{", "$", "src", "=", "$", "this", "->", "getUrl", "(", "$", "path", ",", "$", "plugin", ",", "$", "appendTime", ")", ";", "return", "'<script type=\"text/javascript\" src=\"'", ".", "$", "src", ".", "'\"'", ".", "$", "this", "->", "_renderAttributes", "(", "$", "attributes", ")", ".", "'></script>'", ";", "}" ]
Output a script tag for a specific js file and optionally append a last modified timestamp to clear the browser cache. @param string $path The path to the css file relative to the app or plugin webroot. @param bool|string $plugin Either false or the name of a plugin. @param bool $appendTime Whether to append a last modified timestamp to the url. @param array $attributes Additional html attributes to render on the script tag. @return string
[ "Output", "a", "script", "tag", "for", "a", "specific", "js", "file", "and", "optionally", "append", "a", "last", "modified", "timestamp", "to", "clear", "the", "browser", "cache", "." ]
07b3646006d9bbf4f2d6fceeb319373392752b63
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L69-L74
train
frankfoerster/cakephp-asset
src/View/Helper/AssetHelper.php
AssetHelper.getUrl
public function getUrl($path, $plugin, $appendTime = true) { $pathParts = explode('/', $path); $isAssetPath = ($pathParts[0] === 'ASSETS'); if ($isAssetPath) { $absPath = $this->_getBaseAssetPath($plugin) . join('/', array_slice($pathParts, 1)); } else { $absPath = $this->_getBasePath($plugin) . $path; } $time = $appendTime ? $this->_getModifiedTime($absPath) : ''; $pathPrefix = ''; if ($plugin !== false) { $pluginParts = explode('/', $plugin); foreach ($pluginParts as $key => $part) { $pluginParts[$key] = Inflector::underscore($part); } $pathPrefix .= join('/', $pluginParts) . '/'; } else { $pathPrefix = ''; } $path = $pathPrefix . $path; $options = [ 'fullBase' => (bool)$this->getConfig('fullBase', false) ]; return $this->Url->assetUrl($path, $options) . $time; }
php
public function getUrl($path, $plugin, $appendTime = true) { $pathParts = explode('/', $path); $isAssetPath = ($pathParts[0] === 'ASSETS'); if ($isAssetPath) { $absPath = $this->_getBaseAssetPath($plugin) . join('/', array_slice($pathParts, 1)); } else { $absPath = $this->_getBasePath($plugin) . $path; } $time = $appendTime ? $this->_getModifiedTime($absPath) : ''; $pathPrefix = ''; if ($plugin !== false) { $pluginParts = explode('/', $plugin); foreach ($pluginParts as $key => $part) { $pluginParts[$key] = Inflector::underscore($part); } $pathPrefix .= join('/', $pluginParts) . '/'; } else { $pathPrefix = ''; } $path = $pathPrefix . $path; $options = [ 'fullBase' => (bool)$this->getConfig('fullBase', false) ]; return $this->Url->assetUrl($path, $options) . $time; }
[ "public", "function", "getUrl", "(", "$", "path", ",", "$", "plugin", ",", "$", "appendTime", "=", "true", ")", "{", "$", "pathParts", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "$", "isAssetPath", "=", "(", "$", "pathParts", "[", "0", "]", "===", "'ASSETS'", ")", ";", "if", "(", "$", "isAssetPath", ")", "{", "$", "absPath", "=", "$", "this", "->", "_getBaseAssetPath", "(", "$", "plugin", ")", ".", "join", "(", "'/'", ",", "array_slice", "(", "$", "pathParts", ",", "1", ")", ")", ";", "}", "else", "{", "$", "absPath", "=", "$", "this", "->", "_getBasePath", "(", "$", "plugin", ")", ".", "$", "path", ";", "}", "$", "time", "=", "$", "appendTime", "?", "$", "this", "->", "_getModifiedTime", "(", "$", "absPath", ")", ":", "''", ";", "$", "pathPrefix", "=", "''", ";", "if", "(", "$", "plugin", "!==", "false", ")", "{", "$", "pluginParts", "=", "explode", "(", "'/'", ",", "$", "plugin", ")", ";", "foreach", "(", "$", "pluginParts", "as", "$", "key", "=>", "$", "part", ")", "{", "$", "pluginParts", "[", "$", "key", "]", "=", "Inflector", "::", "underscore", "(", "$", "part", ")", ";", "}", "$", "pathPrefix", ".=", "join", "(", "'/'", ",", "$", "pluginParts", ")", ".", "'/'", ";", "}", "else", "{", "$", "pathPrefix", "=", "''", ";", "}", "$", "path", "=", "$", "pathPrefix", ".", "$", "path", ";", "$", "options", "=", "[", "'fullBase'", "=>", "(", "bool", ")", "$", "this", "->", "getConfig", "(", "'fullBase'", ",", "false", ")", "]", ";", "return", "$", "this", "->", "Url", "->", "assetUrl", "(", "$", "path", ",", "$", "options", ")", ".", "$", "time", ";", "}" ]
Get the asset url for a specific file. @param string $path The path to the css file relative to the app or plugin webroot. @param bool|string $plugin Either false or the name of a plugin. @param bool $appendTime Whether to append a last modified timestamp to the url. @return string
[ "Get", "the", "asset", "url", "for", "a", "specific", "file", "." ]
07b3646006d9bbf4f2d6fceeb319373392752b63
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L84-L113
train
frankfoerster/cakephp-asset
src/View/Helper/AssetHelper.php
AssetHelper._getBasePath
protected function _getBasePath($plugin = false) { if ($plugin !== false) { return $this->_getPluginPath($plugin) . 'webroot' . DS; } return WWW_ROOT; }
php
protected function _getBasePath($plugin = false) { if ($plugin !== false) { return $this->_getPluginPath($plugin) . 'webroot' . DS; } return WWW_ROOT; }
[ "protected", "function", "_getBasePath", "(", "$", "plugin", "=", "false", ")", "{", "if", "(", "$", "plugin", "!==", "false", ")", "{", "return", "$", "this", "->", "_getPluginPath", "(", "$", "plugin", ")", ".", "'webroot'", ".", "DS", ";", "}", "return", "WWW_ROOT", ";", "}" ]
Get the base path to the app webroot or a plugin webroot. @param bool|string $plugin Either false or the name of a plugin. @return string
[ "Get", "the", "base", "path", "to", "the", "app", "webroot", "or", "a", "plugin", "webroot", "." ]
07b3646006d9bbf4f2d6fceeb319373392752b63
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L136-L143
train
frankfoerster/cakephp-asset
src/View/Helper/AssetHelper.php
AssetHelper._renderAttributes
protected function _renderAttributes(array $attributes = []) { $attributeStrings = []; foreach ($attributes as $attribute => $value) { $attributeStrings[] = $attribute . '="' . htmlentities($value) . '"'; } if (empty($attributeStrings)) { return ''; } return ' ' . join(' ', $attributeStrings); }
php
protected function _renderAttributes(array $attributes = []) { $attributeStrings = []; foreach ($attributes as $attribute => $value) { $attributeStrings[] = $attribute . '="' . htmlentities($value) . '"'; } if (empty($attributeStrings)) { return ''; } return ' ' . join(' ', $attributeStrings); }
[ "protected", "function", "_renderAttributes", "(", "array", "$", "attributes", "=", "[", "]", ")", "{", "$", "attributeStrings", "=", "[", "]", ";", "foreach", "(", "$", "attributes", "as", "$", "attribute", "=>", "$", "value", ")", "{", "$", "attributeStrings", "[", "]", "=", "$", "attribute", ".", "'=\"'", ".", "htmlentities", "(", "$", "value", ")", ".", "'\"'", ";", "}", "if", "(", "empty", "(", "$", "attributeStrings", ")", ")", "{", "return", "''", ";", "}", "return", "' '", ".", "join", "(", "' '", ",", "$", "attributeStrings", ")", ";", "}" ]
Render attribute key value pairs as html attributes. @param array $attributes Key value pairs of html attributes. @return string
[ "Render", "attribute", "key", "value", "pairs", "as", "html", "attributes", "." ]
07b3646006d9bbf4f2d6fceeb319373392752b63
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L182-L194
train
Wonail/yii2-widget-nestable
Nestable.php
Nestable.renderWidget
public function renderWidget() { // BEGIN:nestable-box echo Html::beginTag('div', ['class' => 'nestable-box']); foreach ($this->items as $item) { $this->renderGroup($item); } // END:nestable-box echo Html::endTag('div'); if ($this->hasModel()) { echo Html::activeHiddenInput($this->model, $this->attribute); } else { echo Html::hiddenInput($this->name); } }
php
public function renderWidget() { // BEGIN:nestable-box echo Html::beginTag('div', ['class' => 'nestable-box']); foreach ($this->items as $item) { $this->renderGroup($item); } // END:nestable-box echo Html::endTag('div'); if ($this->hasModel()) { echo Html::activeHiddenInput($this->model, $this->attribute); } else { echo Html::hiddenInput($this->name); } }
[ "public", "function", "renderWidget", "(", ")", "{", "// BEGIN:nestable-box", "echo", "Html", "::", "beginTag", "(", "'div'", ",", "[", "'class'", "=>", "'nestable-box'", "]", ")", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "$", "this", "->", "renderGroup", "(", "$", "item", ")", ";", "}", "// END:nestable-box", "echo", "Html", "::", "endTag", "(", "'div'", ")", ";", "if", "(", "$", "this", "->", "hasModel", "(", ")", ")", "{", "echo", "Html", "::", "activeHiddenInput", "(", "$", "this", "->", "model", ",", "$", "this", "->", "attribute", ")", ";", "}", "else", "{", "echo", "Html", "::", "hiddenInput", "(", "$", "this", "->", "name", ")", ";", "}", "}" ]
Initializes and renders the widget
[ "Initializes", "and", "renders", "the", "widget" ]
b9e4ccaab15d616e0791cb49a7a96597f4dc3d60
https://github.com/Wonail/yii2-widget-nestable/blob/b9e4ccaab15d616e0791cb49a7a96597f4dc3d60/Nestable.php#L107-L121
train
luoxiaojun1992/lb_framework
controllers/console/SwooleController.php
SwooleController.http
public function http() { $this->writeln('Starting swoole http server...'); $server = new HttpServer( $this->swooleConfig['http']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['http']['port'] ?? self::DEFAULT_SWOOLE_PORT ); $server->on( 'Request', function ($request, $response) { $swooleRequest = (new SwooleRequest())->setSwooleRequest($request); $swooleResponse = (new SwooleResponse())->setSwooleResponse($response); $sessionId = $swooleRequest->getCookie('swoole_session_id'); if (!$sessionId) { $sessionId = IdGenerator::component()->generate(); $swooleResponse->setCookie('swoole_session_id', $sessionId); } $swooleRequest->setSessionId($sessionId); $swooleResponse->setSessionId($sessionId); (new App($swooleRequest, $swooleResponse))->run(); } ); $server->start(); }
php
public function http() { $this->writeln('Starting swoole http server...'); $server = new HttpServer( $this->swooleConfig['http']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['http']['port'] ?? self::DEFAULT_SWOOLE_PORT ); $server->on( 'Request', function ($request, $response) { $swooleRequest = (new SwooleRequest())->setSwooleRequest($request); $swooleResponse = (new SwooleResponse())->setSwooleResponse($response); $sessionId = $swooleRequest->getCookie('swoole_session_id'); if (!$sessionId) { $sessionId = IdGenerator::component()->generate(); $swooleResponse->setCookie('swoole_session_id', $sessionId); } $swooleRequest->setSessionId($sessionId); $swooleResponse->setSessionId($sessionId); (new App($swooleRequest, $swooleResponse))->run(); } ); $server->start(); }
[ "public", "function", "http", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting swoole http server...'", ")", ";", "$", "server", "=", "new", "HttpServer", "(", "$", "this", "->", "swooleConfig", "[", "'http'", "]", "[", "'host'", "]", "??", "self", "::", "DEFAULT_SWOOLE_HOST", ",", "$", "this", "->", "swooleConfig", "[", "'http'", "]", "[", "'port'", "]", "??", "self", "::", "DEFAULT_SWOOLE_PORT", ")", ";", "$", "server", "->", "on", "(", "'Request'", ",", "function", "(", "$", "request", ",", "$", "response", ")", "{", "$", "swooleRequest", "=", "(", "new", "SwooleRequest", "(", ")", ")", "->", "setSwooleRequest", "(", "$", "request", ")", ";", "$", "swooleResponse", "=", "(", "new", "SwooleResponse", "(", ")", ")", "->", "setSwooleResponse", "(", "$", "response", ")", ";", "$", "sessionId", "=", "$", "swooleRequest", "->", "getCookie", "(", "'swoole_session_id'", ")", ";", "if", "(", "!", "$", "sessionId", ")", "{", "$", "sessionId", "=", "IdGenerator", "::", "component", "(", ")", "->", "generate", "(", ")", ";", "$", "swooleResponse", "->", "setCookie", "(", "'swoole_session_id'", ",", "$", "sessionId", ")", ";", "}", "$", "swooleRequest", "->", "setSessionId", "(", "$", "sessionId", ")", ";", "$", "swooleResponse", "->", "setSessionId", "(", "$", "sessionId", ")", ";", "(", "new", "App", "(", "$", "swooleRequest", ",", "$", "swooleResponse", ")", ")", "->", "run", "(", ")", ";", "}", ")", ";", "$", "server", "->", "start", "(", ")", ";", "}" ]
Swoole Http Server
[ "Swoole", "Http", "Server" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L38-L66
train
luoxiaojun1992/lb_framework
controllers/console/SwooleController.php
SwooleController.tcp
public function tcp() { $this->writeln('Starting swoole tcp server...'); $server = new TcpServer( $this->swooleConfig['tcp']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['tcp']['port'] ?? self::DEFAULT_SWOOLE_PORT ); //防止粘包 $server->set( [ 'open_eof_split' => true, 'package_eof' => self::EOF, ] ); $server->on( 'connect', function ($serv, $fd) { $this->writeln('Client:Connect.'); } ); $server->on( 'receive', function ($serv, $fd, $from_id, $data) { $jsonData = JsonHelper::decode(str_replace(self::EOF, '', $data)); if (isset($jsonData['handler'])) { $jsonData['swoole_from_id'] = $from_id; $handlerClass = $jsonData['handler']; try { $serv->send( $fd, Lb::app()->dispatchJob($handlerClass, $jsonData) ); } catch (\Throwable $e) { $serv->send($fd, 'Exception:' . $e->getTraceAsString()); } } else { $serv->send($fd, 'Handler not exists'); } } ); $server->on( 'close', function ($serv, $fd) { $this->writeln('Client: Close.'); } ); $server->start(); }
php
public function tcp() { $this->writeln('Starting swoole tcp server...'); $server = new TcpServer( $this->swooleConfig['tcp']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['tcp']['port'] ?? self::DEFAULT_SWOOLE_PORT ); //防止粘包 $server->set( [ 'open_eof_split' => true, 'package_eof' => self::EOF, ] ); $server->on( 'connect', function ($serv, $fd) { $this->writeln('Client:Connect.'); } ); $server->on( 'receive', function ($serv, $fd, $from_id, $data) { $jsonData = JsonHelper::decode(str_replace(self::EOF, '', $data)); if (isset($jsonData['handler'])) { $jsonData['swoole_from_id'] = $from_id; $handlerClass = $jsonData['handler']; try { $serv->send( $fd, Lb::app()->dispatchJob($handlerClass, $jsonData) ); } catch (\Throwable $e) { $serv->send($fd, 'Exception:' . $e->getTraceAsString()); } } else { $serv->send($fd, 'Handler not exists'); } } ); $server->on( 'close', function ($serv, $fd) { $this->writeln('Client: Close.'); } ); $server->start(); }
[ "public", "function", "tcp", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting swoole tcp server...'", ")", ";", "$", "server", "=", "new", "TcpServer", "(", "$", "this", "->", "swooleConfig", "[", "'tcp'", "]", "[", "'host'", "]", "??", "self", "::", "DEFAULT_SWOOLE_HOST", ",", "$", "this", "->", "swooleConfig", "[", "'tcp'", "]", "[", "'port'", "]", "??", "self", "::", "DEFAULT_SWOOLE_PORT", ")", ";", "//防止粘包", "$", "server", "->", "set", "(", "[", "'open_eof_split'", "=>", "true", ",", "'package_eof'", "=>", "self", "::", "EOF", ",", "]", ")", ";", "$", "server", "->", "on", "(", "'connect'", ",", "function", "(", "$", "serv", ",", "$", "fd", ")", "{", "$", "this", "->", "writeln", "(", "'Client:Connect.'", ")", ";", "}", ")", ";", "$", "server", "->", "on", "(", "'receive'", ",", "function", "(", "$", "serv", ",", "$", "fd", ",", "$", "from_id", ",", "$", "data", ")", "{", "$", "jsonData", "=", "JsonHelper", "::", "decode", "(", "str_replace", "(", "self", "::", "EOF", ",", "''", ",", "$", "data", ")", ")", ";", "if", "(", "isset", "(", "$", "jsonData", "[", "'handler'", "]", ")", ")", "{", "$", "jsonData", "[", "'swoole_from_id'", "]", "=", "$", "from_id", ";", "$", "handlerClass", "=", "$", "jsonData", "[", "'handler'", "]", ";", "try", "{", "$", "serv", "->", "send", "(", "$", "fd", ",", "Lb", "::", "app", "(", ")", "->", "dispatchJob", "(", "$", "handlerClass", ",", "$", "jsonData", ")", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "$", "serv", "->", "send", "(", "$", "fd", ",", "'Exception:'", ".", "$", "e", "->", "getTraceAsString", "(", ")", ")", ";", "}", "}", "else", "{", "$", "serv", "->", "send", "(", "$", "fd", ",", "'Handler not exists'", ")", ";", "}", "}", ")", ";", "$", "server", "->", "on", "(", "'close'", ",", "function", "(", "$", "serv", ",", "$", "fd", ")", "{", "$", "this", "->", "writeln", "(", "'Client: Close.'", ")", ";", "}", ")", ";", "$", "server", "->", "start", "(", ")", ";", "}" ]
Swoole Tcp Server
[ "Swoole", "Tcp", "Server" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L71-L121
train
luoxiaojun1992/lb_framework
controllers/console/SwooleController.php
SwooleController.udp
public function udp() { $this->writeln('Starting swoole udp server...'); $udpServer = new TcpServer( $this->swooleConfig['upd']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['upd']['port'] ?? self::DEFAULT_SWOOLE_PORT, SWOOLE_PROCESS, SWOOLE_SOCK_UDP ); //防止粘包 $udpServer->set( [ 'open_eof_split' => true, 'package_eof' => self::EOF, ] ); $udpServer->on( 'Packet', function ($serv, $data, $clientInfo) { $clientAddress = $clientInfo['address']; $clientPort = $clientInfo['port']; $jsonData = JsonHelper::decode(str_replace(self::EOF, '', $data)); if (isset($jsonData['handler'])) { $jsonData['swoole_client_info'] = $clientInfo; $handlerClass = $jsonData['handler']; try { $serv->sendto( $clientAddress, $clientPort, Lb::app()->dispatchJob($handlerClass, $jsonData) ); } catch (\Throwable $e) { $serv->sendto( $clientAddress, $clientPort, 'Exception:' . $e->getTraceAsString() ); } } else { $serv->sendto( $clientAddress, $clientPort, 'Handler not exists' ); } } ); $udpServer->start(); }
php
public function udp() { $this->writeln('Starting swoole udp server...'); $udpServer = new TcpServer( $this->swooleConfig['upd']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['upd']['port'] ?? self::DEFAULT_SWOOLE_PORT, SWOOLE_PROCESS, SWOOLE_SOCK_UDP ); //防止粘包 $udpServer->set( [ 'open_eof_split' => true, 'package_eof' => self::EOF, ] ); $udpServer->on( 'Packet', function ($serv, $data, $clientInfo) { $clientAddress = $clientInfo['address']; $clientPort = $clientInfo['port']; $jsonData = JsonHelper::decode(str_replace(self::EOF, '', $data)); if (isset($jsonData['handler'])) { $jsonData['swoole_client_info'] = $clientInfo; $handlerClass = $jsonData['handler']; try { $serv->sendto( $clientAddress, $clientPort, Lb::app()->dispatchJob($handlerClass, $jsonData) ); } catch (\Throwable $e) { $serv->sendto( $clientAddress, $clientPort, 'Exception:' . $e->getTraceAsString() ); } } else { $serv->sendto( $clientAddress, $clientPort, 'Handler not exists' ); } } ); $udpServer->start(); }
[ "public", "function", "udp", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting swoole udp server...'", ")", ";", "$", "udpServer", "=", "new", "TcpServer", "(", "$", "this", "->", "swooleConfig", "[", "'upd'", "]", "[", "'host'", "]", "??", "self", "::", "DEFAULT_SWOOLE_HOST", ",", "$", "this", "->", "swooleConfig", "[", "'upd'", "]", "[", "'port'", "]", "??", "self", "::", "DEFAULT_SWOOLE_PORT", ",", "SWOOLE_PROCESS", ",", "SWOOLE_SOCK_UDP", ")", ";", "//防止粘包", "$", "udpServer", "->", "set", "(", "[", "'open_eof_split'", "=>", "true", ",", "'package_eof'", "=>", "self", "::", "EOF", ",", "]", ")", ";", "$", "udpServer", "->", "on", "(", "'Packet'", ",", "function", "(", "$", "serv", ",", "$", "data", ",", "$", "clientInfo", ")", "{", "$", "clientAddress", "=", "$", "clientInfo", "[", "'address'", "]", ";", "$", "clientPort", "=", "$", "clientInfo", "[", "'port'", "]", ";", "$", "jsonData", "=", "JsonHelper", "::", "decode", "(", "str_replace", "(", "self", "::", "EOF", ",", "''", ",", "$", "data", ")", ")", ";", "if", "(", "isset", "(", "$", "jsonData", "[", "'handler'", "]", ")", ")", "{", "$", "jsonData", "[", "'swoole_client_info'", "]", "=", "$", "clientInfo", ";", "$", "handlerClass", "=", "$", "jsonData", "[", "'handler'", "]", ";", "try", "{", "$", "serv", "->", "sendto", "(", "$", "clientAddress", ",", "$", "clientPort", ",", "Lb", "::", "app", "(", ")", "->", "dispatchJob", "(", "$", "handlerClass", ",", "$", "jsonData", ")", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "$", "serv", "->", "sendto", "(", "$", "clientAddress", ",", "$", "clientPort", ",", "'Exception:'", ".", "$", "e", "->", "getTraceAsString", "(", ")", ")", ";", "}", "}", "else", "{", "$", "serv", "->", "sendto", "(", "$", "clientAddress", ",", "$", "clientPort", ",", "'Handler not exists'", ")", ";", "}", "}", ")", ";", "$", "udpServer", "->", "start", "(", ")", ";", "}" ]
Swoole UDP Server
[ "Swoole", "UDP", "Server" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L126-L177
train
luoxiaojun1992/lb_framework
controllers/console/SwooleController.php
SwooleController.websocket
public function websocket() { $this->writeln('Starting swoole websocket server...'); $ws = new WebsocketServer( $this->swooleConfig['ws']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['ws']['port'] ?? self::DEFAULT_SWOOLE_PORT ); $ws->on( 'open', function ($ws, $request) { $this->writeln('client-Connect.'); } ); $ws->on( 'message', function ($ws, $frame) { $jsonData = JsonHelper::decode($frame->data); if (isset($jsonData['handler'])) { $jsonData['swoole_frame'] = $frame; $handlerClass = $jsonData['handler']; try { $ws->push( $frame->fd, Lb::app()->dispatchJob($handlerClass, $jsonData) ); } catch (\Throwable $e) { $ws->push( $frame->fd, 'Exception:' . $e->getTraceAsString() ); } } else { $ws->push( $frame->fd, 'Handler not exists' ); } } ); $ws->on( 'close', function ($ws, $fd) { $this->writeln('client-closed'); } ); $ws->start(); }
php
public function websocket() { $this->writeln('Starting swoole websocket server...'); $ws = new WebsocketServer( $this->swooleConfig['ws']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['ws']['port'] ?? self::DEFAULT_SWOOLE_PORT ); $ws->on( 'open', function ($ws, $request) { $this->writeln('client-Connect.'); } ); $ws->on( 'message', function ($ws, $frame) { $jsonData = JsonHelper::decode($frame->data); if (isset($jsonData['handler'])) { $jsonData['swoole_frame'] = $frame; $handlerClass = $jsonData['handler']; try { $ws->push( $frame->fd, Lb::app()->dispatchJob($handlerClass, $jsonData) ); } catch (\Throwable $e) { $ws->push( $frame->fd, 'Exception:' . $e->getTraceAsString() ); } } else { $ws->push( $frame->fd, 'Handler not exists' ); } } ); $ws->on( 'close', function ($ws, $fd) { $this->writeln('client-closed'); } ); $ws->start(); }
[ "public", "function", "websocket", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting swoole websocket server...'", ")", ";", "$", "ws", "=", "new", "WebsocketServer", "(", "$", "this", "->", "swooleConfig", "[", "'ws'", "]", "[", "'host'", "]", "??", "self", "::", "DEFAULT_SWOOLE_HOST", ",", "$", "this", "->", "swooleConfig", "[", "'ws'", "]", "[", "'port'", "]", "??", "self", "::", "DEFAULT_SWOOLE_PORT", ")", ";", "$", "ws", "->", "on", "(", "'open'", ",", "function", "(", "$", "ws", ",", "$", "request", ")", "{", "$", "this", "->", "writeln", "(", "'client-Connect.'", ")", ";", "}", ")", ";", "$", "ws", "->", "on", "(", "'message'", ",", "function", "(", "$", "ws", ",", "$", "frame", ")", "{", "$", "jsonData", "=", "JsonHelper", "::", "decode", "(", "$", "frame", "->", "data", ")", ";", "if", "(", "isset", "(", "$", "jsonData", "[", "'handler'", "]", ")", ")", "{", "$", "jsonData", "[", "'swoole_frame'", "]", "=", "$", "frame", ";", "$", "handlerClass", "=", "$", "jsonData", "[", "'handler'", "]", ";", "try", "{", "$", "ws", "->", "push", "(", "$", "frame", "->", "fd", ",", "Lb", "::", "app", "(", ")", "->", "dispatchJob", "(", "$", "handlerClass", ",", "$", "jsonData", ")", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "$", "ws", "->", "push", "(", "$", "frame", "->", "fd", ",", "'Exception:'", ".", "$", "e", "->", "getTraceAsString", "(", ")", ")", ";", "}", "}", "else", "{", "$", "ws", "->", "push", "(", "$", "frame", "->", "fd", ",", "'Handler not exists'", ")", ";", "}", "}", ")", ";", "$", "ws", "->", "on", "(", "'close'", ",", "function", "(", "$", "ws", ",", "$", "fd", ")", "{", "$", "this", "->", "writeln", "(", "'client-closed'", ")", ";", "}", ")", ";", "$", "ws", "->", "start", "(", ")", ";", "}" ]
Swoole Websocket Server
[ "Swoole", "Websocket", "Server" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L182-L230
train
luoxiaojun1992/lb_framework
controllers/console/SwooleController.php
SwooleController.mqtt
public function mqtt() { $this->writeln('Starting swoole mqtt server...'); $serv = new TcpServer( $this->swooleConfig['tcp']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['tcp']['port'] ?? self::DEFAULT_SWOOLE_PORT, SWOOLE_BASE ); $serv->set( array( 'open_mqtt_protocol' => 1, 'worker_num' => 1, ) ); $serv->on( 'connect', function ($serv, $fd) { echo "Client:Connect.\n"; } ); $serv->on( 'receive', function ($serv, $fd, $from_id, $data) { $header = Mqtt::mqtt_get_header($data); var_dump($header); if ($header['type'] == 1) { $resp = chr(32) . chr(2) . chr(0) . chr(0);//转换为二进制返回应该使用chr Mqtt::event_connect(substr($data, 2)); $serv->send($fd, $resp); } elseif ($header['type'] == 3) { $offset = 2; $topic = Mqtt::decodeString(substr($data, $offset)); $offset += strlen($topic) + 2; $msg = substr($data, $offset); echo "client msg: $topic\n---------------------------------\n$msg\n"; //file_put_contents(__DIR__.'/data.log', $data); } echo "received length=".strlen($data)."\n"; } ); $serv->on( 'close', function ($serv, $fd) { echo "Client: Close.\n"; } ); $serv->start(); }
php
public function mqtt() { $this->writeln('Starting swoole mqtt server...'); $serv = new TcpServer( $this->swooleConfig['tcp']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['tcp']['port'] ?? self::DEFAULT_SWOOLE_PORT, SWOOLE_BASE ); $serv->set( array( 'open_mqtt_protocol' => 1, 'worker_num' => 1, ) ); $serv->on( 'connect', function ($serv, $fd) { echo "Client:Connect.\n"; } ); $serv->on( 'receive', function ($serv, $fd, $from_id, $data) { $header = Mqtt::mqtt_get_header($data); var_dump($header); if ($header['type'] == 1) { $resp = chr(32) . chr(2) . chr(0) . chr(0);//转换为二进制返回应该使用chr Mqtt::event_connect(substr($data, 2)); $serv->send($fd, $resp); } elseif ($header['type'] == 3) { $offset = 2; $topic = Mqtt::decodeString(substr($data, $offset)); $offset += strlen($topic) + 2; $msg = substr($data, $offset); echo "client msg: $topic\n---------------------------------\n$msg\n"; //file_put_contents(__DIR__.'/data.log', $data); } echo "received length=".strlen($data)."\n"; } ); $serv->on( 'close', function ($serv, $fd) { echo "Client: Close.\n"; } ); $serv->start(); }
[ "public", "function", "mqtt", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting swoole mqtt server...'", ")", ";", "$", "serv", "=", "new", "TcpServer", "(", "$", "this", "->", "swooleConfig", "[", "'tcp'", "]", "[", "'host'", "]", "??", "self", "::", "DEFAULT_SWOOLE_HOST", ",", "$", "this", "->", "swooleConfig", "[", "'tcp'", "]", "[", "'port'", "]", "??", "self", "::", "DEFAULT_SWOOLE_PORT", ",", "SWOOLE_BASE", ")", ";", "$", "serv", "->", "set", "(", "array", "(", "'open_mqtt_protocol'", "=>", "1", ",", "'worker_num'", "=>", "1", ",", ")", ")", ";", "$", "serv", "->", "on", "(", "'connect'", ",", "function", "(", "$", "serv", ",", "$", "fd", ")", "{", "echo", "\"Client:Connect.\\n\"", ";", "}", ")", ";", "$", "serv", "->", "on", "(", "'receive'", ",", "function", "(", "$", "serv", ",", "$", "fd", ",", "$", "from_id", ",", "$", "data", ")", "{", "$", "header", "=", "Mqtt", "::", "mqtt_get_header", "(", "$", "data", ")", ";", "var_dump", "(", "$", "header", ")", ";", "if", "(", "$", "header", "[", "'type'", "]", "==", "1", ")", "{", "$", "resp", "=", "chr", "(", "32", ")", ".", "chr", "(", "2", ")", ".", "chr", "(", "0", ")", ".", "chr", "(", "0", ")", ";", "//转换为二进制返回应该使用chr", "Mqtt", "::", "event_connect", "(", "substr", "(", "$", "data", ",", "2", ")", ")", ";", "$", "serv", "->", "send", "(", "$", "fd", ",", "$", "resp", ")", ";", "}", "elseif", "(", "$", "header", "[", "'type'", "]", "==", "3", ")", "{", "$", "offset", "=", "2", ";", "$", "topic", "=", "Mqtt", "::", "decodeString", "(", "substr", "(", "$", "data", ",", "$", "offset", ")", ")", ";", "$", "offset", "+=", "strlen", "(", "$", "topic", ")", "+", "2", ";", "$", "msg", "=", "substr", "(", "$", "data", ",", "$", "offset", ")", ";", "echo", "\"client msg: $topic\\n---------------------------------\\n$msg\\n\"", ";", "//file_put_contents(__DIR__.'/data.log', $data);", "}", "echo", "\"received length=\"", ".", "strlen", "(", "$", "data", ")", ".", "\"\\n\"", ";", "}", ")", ";", "$", "serv", "->", "on", "(", "'close'", ",", "function", "(", "$", "serv", ",", "$", "fd", ")", "{", "echo", "\"Client: Close.\\n\"", ";", "}", ")", ";", "$", "serv", "->", "start", "(", ")", ";", "}" ]
Swoole Mqtt Server
[ "Swoole", "Mqtt", "Server" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L235-L280
train
luoxiaojun1992/lb_framework
controllers/console/SwooleController.php
SwooleController.udpClient
public function udpClient() { $this->writeln('Starting demo swoole udp client...'); $client = new TcpClient(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC); $client->on( 'connect', function ($cli) { //发送数据中不能包含'\r\n\r\n' $cli->send(JsonHelper::encode(['handler' => SwooleTcpJob::class]) . self::EOF); } ); $client->on( 'receive', function ($cli, $data) { $this->writeln('Received: '.$data); } ); $client->on( 'error', function ($cli) { $this->writeln('Connect failed'); } ); $client->on( "close", function ($cli) { $this->writeln('Connection close'); } ); $client->connect( $this->swooleConfig['udp']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['udp']['port'] ?? self::DEFAULT_SWOOLE_PORT, $this->swooleConfig['udp']['timeout'] ?? self::DEFAULT_SWOOLE_TIMEOUT ); }
php
public function udpClient() { $this->writeln('Starting demo swoole udp client...'); $client = new TcpClient(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC); $client->on( 'connect', function ($cli) { //发送数据中不能包含'\r\n\r\n' $cli->send(JsonHelper::encode(['handler' => SwooleTcpJob::class]) . self::EOF); } ); $client->on( 'receive', function ($cli, $data) { $this->writeln('Received: '.$data); } ); $client->on( 'error', function ($cli) { $this->writeln('Connect failed'); } ); $client->on( "close", function ($cli) { $this->writeln('Connection close'); } ); $client->connect( $this->swooleConfig['udp']['host'] ?? self::DEFAULT_SWOOLE_HOST, $this->swooleConfig['udp']['port'] ?? self::DEFAULT_SWOOLE_PORT, $this->swooleConfig['udp']['timeout'] ?? self::DEFAULT_SWOOLE_TIMEOUT ); }
[ "public", "function", "udpClient", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting demo swoole udp client...'", ")", ";", "$", "client", "=", "new", "TcpClient", "(", "SWOOLE_SOCK_UDP", ",", "SWOOLE_SOCK_ASYNC", ")", ";", "$", "client", "->", "on", "(", "'connect'", ",", "function", "(", "$", "cli", ")", "{", "//发送数据中不能包含'\\r\\n\\r\\n'", "$", "cli", "->", "send", "(", "JsonHelper", "::", "encode", "(", "[", "'handler'", "=>", "SwooleTcpJob", "::", "class", "]", ")", ".", "self", "::", "EOF", ")", ";", "}", ")", ";", "$", "client", "->", "on", "(", "'receive'", ",", "function", "(", "$", "cli", ",", "$", "data", ")", "{", "$", "this", "->", "writeln", "(", "'Received: '", ".", "$", "data", ")", ";", "}", ")", ";", "$", "client", "->", "on", "(", "'error'", ",", "function", "(", "$", "cli", ")", "{", "$", "this", "->", "writeln", "(", "'Connect failed'", ")", ";", "}", ")", ";", "$", "client", "->", "on", "(", "\"close\"", ",", "function", "(", "$", "cli", ")", "{", "$", "this", "->", "writeln", "(", "'Connection close'", ")", ";", "}", ")", ";", "$", "client", "->", "connect", "(", "$", "this", "->", "swooleConfig", "[", "'udp'", "]", "[", "'host'", "]", "??", "self", "::", "DEFAULT_SWOOLE_HOST", ",", "$", "this", "->", "swooleConfig", "[", "'udp'", "]", "[", "'port'", "]", "??", "self", "::", "DEFAULT_SWOOLE_PORT", ",", "$", "this", "->", "swooleConfig", "[", "'udp'", "]", "[", "'timeout'", "]", "??", "self", "::", "DEFAULT_SWOOLE_TIMEOUT", ")", ";", "}" ]
Swoole UDP Client Demo
[ "Swoole", "UDP", "Client", "Demo" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L323-L356
train
luoxiaojun1992/lb_framework
controllers/console/SwooleController.php
SwooleController.websocketClient
public function websocketClient() { $this->writeln('Starting demo websocket client...'); $client = new Client( 'ws://' . ($this->swooleConfig['ws']['host'] ?? self::DEFAULT_SWOOLE_HOST) . ':' . ($this->swooleConfig['ws']['port'] ?? self::DEFAULT_SWOOLE_PORT) ); $client->send(JsonHelper::encode(['handler' => SwooleTcpJob::class])); $this->writeln($client->receive()); $client->close(); }
php
public function websocketClient() { $this->writeln('Starting demo websocket client...'); $client = new Client( 'ws://' . ($this->swooleConfig['ws']['host'] ?? self::DEFAULT_SWOOLE_HOST) . ':' . ($this->swooleConfig['ws']['port'] ?? self::DEFAULT_SWOOLE_PORT) ); $client->send(JsonHelper::encode(['handler' => SwooleTcpJob::class])); $this->writeln($client->receive()); $client->close(); }
[ "public", "function", "websocketClient", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting demo websocket client...'", ")", ";", "$", "client", "=", "new", "Client", "(", "'ws://'", ".", "(", "$", "this", "->", "swooleConfig", "[", "'ws'", "]", "[", "'host'", "]", "??", "self", "::", "DEFAULT_SWOOLE_HOST", ")", ".", "':'", ".", "(", "$", "this", "->", "swooleConfig", "[", "'ws'", "]", "[", "'port'", "]", "??", "self", "::", "DEFAULT_SWOOLE_PORT", ")", ")", ";", "$", "client", "->", "send", "(", "JsonHelper", "::", "encode", "(", "[", "'handler'", "=>", "SwooleTcpJob", "::", "class", "]", ")", ")", ";", "$", "this", "->", "writeln", "(", "$", "client", "->", "receive", "(", ")", ")", ";", "$", "client", "->", "close", "(", ")", ";", "}" ]
Websocket Client Demo
[ "Websocket", "Client", "Demo" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L361-L373
train
wartw98/core
Config/Source/API.php
API.map
final protected function map() { /** @var array(string => string) $result */ /** @var bool $met */ $result = df_map_0([], $met = $this->isRequirementMet() ? null : $this->requirement()); if ($met) { try {$result += $this->fetch();} catch (\Exception $e) {$result = $this->exception($e);} } return $result; }
php
final protected function map() { /** @var array(string => string) $result */ /** @var bool $met */ $result = df_map_0([], $met = $this->isRequirementMet() ? null : $this->requirement()); if ($met) { try {$result += $this->fetch();} catch (\Exception $e) {$result = $this->exception($e);} } return $result; }
[ "final", "protected", "function", "map", "(", ")", "{", "/** @var array(string => string) $result */", "/** @var bool $met */", "$", "result", "=", "df_map_0", "(", "[", "]", ",", "$", "met", "=", "$", "this", "->", "isRequirementMet", "(", ")", "?", "null", ":", "$", "this", "->", "requirement", "(", ")", ")", ";", "if", "(", "$", "met", ")", "{", "try", "{", "$", "result", "+=", "$", "this", "->", "fetch", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "result", "=", "$", "this", "->", "exception", "(", "$", "e", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
2017-07-02 @override @see \Df\Config\Source::map() @used-by \Df\Config\Source::toOptionArray() @return array(string => string)
[ "2017", "-", "07", "-", "02" ]
e1f44f6b4798a7b988f6a1cae639ff3745c9cd2a
https://github.com/wartw98/core/blob/e1f44f6b4798a7b988f6a1cae639ff3745c9cd2a/Config/Source/API.php#L56-L64
train
xelax90/xelax-admin
src/XelaxAdmin/Router/ListRoute.php
ListRoute.getControllerOptions
public function getControllerOptions(){ if(empty($this->controllerOptions)){ $routePluginManager = $this->getServiceLocator(); if(empty($routePluginManager)){ throw new Exception\RuntimeException('ServiceLocator not set'); } /* @var $sl ServiceLocatorInterface */ $sl = $routePluginManager->getServiceLocator(); if(empty($sl)){ throw new Exception\RuntimeException('Plugin manager ServiceLocator not set'); } $config = $sl->get('XelaxAdmin\ListControllerOptions'); if(empty($config[$this->controllerOptionName])){ throw new Exception\RuntimeException('Controller options not found'); } $this->controllerOptions = $config[$this->controllerOptionName]; } return $this->controllerOptions; }
php
public function getControllerOptions(){ if(empty($this->controllerOptions)){ $routePluginManager = $this->getServiceLocator(); if(empty($routePluginManager)){ throw new Exception\RuntimeException('ServiceLocator not set'); } /* @var $sl ServiceLocatorInterface */ $sl = $routePluginManager->getServiceLocator(); if(empty($sl)){ throw new Exception\RuntimeException('Plugin manager ServiceLocator not set'); } $config = $sl->get('XelaxAdmin\ListControllerOptions'); if(empty($config[$this->controllerOptionName])){ throw new Exception\RuntimeException('Controller options not found'); } $this->controllerOptions = $config[$this->controllerOptionName]; } return $this->controllerOptions; }
[ "public", "function", "getControllerOptions", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "controllerOptions", ")", ")", "{", "$", "routePluginManager", "=", "$", "this", "->", "getServiceLocator", "(", ")", ";", "if", "(", "empty", "(", "$", "routePluginManager", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'ServiceLocator not set'", ")", ";", "}", "/* @var $sl ServiceLocatorInterface */", "$", "sl", "=", "$", "routePluginManager", "->", "getServiceLocator", "(", ")", ";", "if", "(", "empty", "(", "$", "sl", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'Plugin manager ServiceLocator not set'", ")", ";", "}", "$", "config", "=", "$", "sl", "->", "get", "(", "'XelaxAdmin\\ListControllerOptions'", ")", ";", "if", "(", "empty", "(", "$", "config", "[", "$", "this", "->", "controllerOptionName", "]", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'Controller options not found'", ")", ";", "}", "$", "this", "->", "controllerOptions", "=", "$", "config", "[", "$", "this", "->", "controllerOptionName", "]", ";", "}", "return", "$", "this", "->", "controllerOptions", ";", "}" ]
Fetches and returns the associated ListControllerOptions for this route @return ListControllerOptions @throws Exception\RuntimeException
[ "Fetches", "and", "returns", "the", "associated", "ListControllerOptions", "for", "this", "route" ]
eb8133384b74e18f6641689f290c6ba956641b6d
https://github.com/xelax90/xelax-admin/blob/eb8133384b74e18f6641689f290c6ba956641b6d/src/XelaxAdmin/Router/ListRoute.php#L424-L447
train
matryoshka-model/matryoshka
library/Criteria/ExtractionTrait.php
ExtractionTrait.extractValue
protected function extractValue(ModelStubInterface $model, $name, $value, $extractName = true) { $modelHydrator = $model->getHydrator(); if (!$modelHydrator || !method_exists($modelHydrator, 'extractValue')) { throw new Exception\RuntimeException( 'Model hydrator must be set and must have extractValue() method ' . 'in order extract a single value' ); } if ($extractName) { $name = $this->extractName($model, $name); } return $modelHydrator->extractValue($name, $value); }
php
protected function extractValue(ModelStubInterface $model, $name, $value, $extractName = true) { $modelHydrator = $model->getHydrator(); if (!$modelHydrator || !method_exists($modelHydrator, 'extractValue')) { throw new Exception\RuntimeException( 'Model hydrator must be set and must have extractValue() method ' . 'in order extract a single value' ); } if ($extractName) { $name = $this->extractName($model, $name); } return $modelHydrator->extractValue($name, $value); }
[ "protected", "function", "extractValue", "(", "ModelStubInterface", "$", "model", ",", "$", "name", ",", "$", "value", ",", "$", "extractName", "=", "true", ")", "{", "$", "modelHydrator", "=", "$", "model", "->", "getHydrator", "(", ")", ";", "if", "(", "!", "$", "modelHydrator", "||", "!", "method_exists", "(", "$", "modelHydrator", ",", "'extractValue'", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'Model hydrator must be set and must have extractValue() method '", ".", "'in order extract a single value'", ")", ";", "}", "if", "(", "$", "extractName", ")", "{", "$", "name", "=", "$", "this", "->", "extractName", "(", "$", "model", ",", "$", "name", ")", ";", "}", "return", "$", "modelHydrator", "->", "extractValue", "(", "$", "name", ",", "$", "value", ")", ";", "}" ]
Extract a value in order to be used within datagateway context If $extractName is false, $name must be in the datagateway context, otherwise $name will be converted using extractName(). @param ModelStubInterface $model @param string $name @param string $value @param bool $extractName @throws Exception\RuntimeException
[ "Extract", "a", "value", "in", "order", "to", "be", "used", "within", "datagateway", "context" ]
51792df00d9897f556d5a3c53193eed0974ff09d
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Criteria/ExtractionTrait.php#L36-L51
train
matryoshka-model/matryoshka
library/Criteria/ExtractionTrait.php
ExtractionTrait.extractName
protected function extractName(ModelStubInterface $model, $name) { if ($model->getObjectPrototype() instanceof HydratorAwareInterface) { $objectHydrator = $model->getObjectPrototype()->getHydrator(); if (!$objectHydrator || !method_exists($objectHydrator, 'hydrateName')) { throw new Exception\RuntimeException( 'Object hydrator must be set and must have hydrateName() ' . 'in order to convert a single field' ); } $name = $objectHydrator->hydrateName($name); } $modelHydrator = $model->getHydrator(); if (!$modelHydrator || !method_exists($modelHydrator, 'extractName')) { throw new Exception\RuntimeException( 'Model hydrator must be set and must have extractName() method ' . 'in order to convert a single field' ); } return $modelHydrator->extractName($name); }
php
protected function extractName(ModelStubInterface $model, $name) { if ($model->getObjectPrototype() instanceof HydratorAwareInterface) { $objectHydrator = $model->getObjectPrototype()->getHydrator(); if (!$objectHydrator || !method_exists($objectHydrator, 'hydrateName')) { throw new Exception\RuntimeException( 'Object hydrator must be set and must have hydrateName() ' . 'in order to convert a single field' ); } $name = $objectHydrator->hydrateName($name); } $modelHydrator = $model->getHydrator(); if (!$modelHydrator || !method_exists($modelHydrator, 'extractName')) { throw new Exception\RuntimeException( 'Model hydrator must be set and must have extractName() method ' . 'in order to convert a single field' ); } return $modelHydrator->extractName($name); }
[ "protected", "function", "extractName", "(", "ModelStubInterface", "$", "model", ",", "$", "name", ")", "{", "if", "(", "$", "model", "->", "getObjectPrototype", "(", ")", "instanceof", "HydratorAwareInterface", ")", "{", "$", "objectHydrator", "=", "$", "model", "->", "getObjectPrototype", "(", ")", "->", "getHydrator", "(", ")", ";", "if", "(", "!", "$", "objectHydrator", "||", "!", "method_exists", "(", "$", "objectHydrator", ",", "'hydrateName'", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'Object hydrator must be set and must have hydrateName() '", ".", "'in order to convert a single field'", ")", ";", "}", "$", "name", "=", "$", "objectHydrator", "->", "hydrateName", "(", "$", "name", ")", ";", "}", "$", "modelHydrator", "=", "$", "model", "->", "getHydrator", "(", ")", ";", "if", "(", "!", "$", "modelHydrator", "||", "!", "method_exists", "(", "$", "modelHydrator", ",", "'extractName'", ")", ")", "{", "throw", "new", "Exception", "\\", "RuntimeException", "(", "'Model hydrator must be set and must have extractName() method '", ".", "'in order to convert a single field'", ")", ";", "}", "return", "$", "modelHydrator", "->", "extractName", "(", "$", "name", ")", ";", "}" ]
Extract a name in order to be used within datagateway context If an object's hydrator is avaliable, then $name will be converted to a model name using the object's hydrator naming strategy. Finally, $name will be extracted using the model's hydrator naming strategy. @param ModelStubInterface $model @param string $name @throws Exception\RuntimeException @return string
[ "Extract", "a", "name", "in", "order", "to", "be", "used", "within", "datagateway", "context" ]
51792df00d9897f556d5a3c53193eed0974ff09d
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Criteria/ExtractionTrait.php#L66-L89
train
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectTabIndention.php
HasCorrectTabIndention._getSpaceAlignmentInArray
protected function _getSpaceAlignmentInArray($lineIndex, $testable) { if (!$lineIndex) { return; } $tokens = $testable->tokens(); $lines = $testable->lines(); $lineCache = $testable->lineCache(); $prevLine = $lines[$lineIndex - 1]; $previousTokens = $lineCache[$testable->findTokensByLine($lineIndex)]; $alignTo = 0; $len = 0; foreach ($previousTokens as $tokenId) { $len += strlen($tokens[$tokenId]['content']); if ($tokens[$tokenId]['content'] === '=>') { $max = strlen($prevLine); while ($len + 1 < $max) { if ($prevLine[$len + 1] !== ' ') { break; } $len++; } $alignTo = $len; } } return $alignTo === null ? $alignTo = 0 : $alignTo; }
php
protected function _getSpaceAlignmentInArray($lineIndex, $testable) { if (!$lineIndex) { return; } $tokens = $testable->tokens(); $lines = $testable->lines(); $lineCache = $testable->lineCache(); $prevLine = $lines[$lineIndex - 1]; $previousTokens = $lineCache[$testable->findTokensByLine($lineIndex)]; $alignTo = 0; $len = 0; foreach ($previousTokens as $tokenId) { $len += strlen($tokens[$tokenId]['content']); if ($tokens[$tokenId]['content'] === '=>') { $max = strlen($prevLine); while ($len + 1 < $max) { if ($prevLine[$len + 1] !== ' ') { break; } $len++; } $alignTo = $len; } } return $alignTo === null ? $alignTo = 0 : $alignTo; }
[ "protected", "function", "_getSpaceAlignmentInArray", "(", "$", "lineIndex", ",", "$", "testable", ")", "{", "if", "(", "!", "$", "lineIndex", ")", "{", "return", ";", "}", "$", "tokens", "=", "$", "testable", "->", "tokens", "(", ")", ";", "$", "lines", "=", "$", "testable", "->", "lines", "(", ")", ";", "$", "lineCache", "=", "$", "testable", "->", "lineCache", "(", ")", ";", "$", "prevLine", "=", "$", "lines", "[", "$", "lineIndex", "-", "1", "]", ";", "$", "previousTokens", "=", "$", "lineCache", "[", "$", "testable", "->", "findTokensByLine", "(", "$", "lineIndex", ")", "]", ";", "$", "alignTo", "=", "0", ";", "$", "len", "=", "0", ";", "foreach", "(", "$", "previousTokens", "as", "$", "tokenId", ")", "{", "$", "len", "+=", "strlen", "(", "$", "tokens", "[", "$", "tokenId", "]", "[", "'content'", "]", ")", ";", "if", "(", "$", "tokens", "[", "$", "tokenId", "]", "[", "'content'", "]", "===", "'=>'", ")", "{", "$", "max", "=", "strlen", "(", "$", "prevLine", ")", ";", "while", "(", "$", "len", "+", "1", "<", "$", "max", ")", "{", "if", "(", "$", "prevLine", "[", "$", "len", "+", "1", "]", "!==", "' '", ")", "{", "break", ";", "}", "$", "len", "++", ";", "}", "$", "alignTo", "=", "$", "len", ";", "}", "}", "return", "$", "alignTo", "===", "null", "?", "$", "alignTo", "=", "0", ":", "$", "alignTo", ";", "}" ]
Return the minimal space required for a multilined expression in an array definition. @param int $lineIndex The index the current line is on @param array $testable The testable object @return int
[ "Return", "the", "minimal", "space", "required", "for", "a", "multilined", "expression", "in", "an", "array", "definition", "." ]
acb72a43ae835e6d200bc0eba1a61aee610e36bf
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectTabIndention.php#L167-L194
train
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectTabIndention.php
HasCorrectTabIndention._getIndent
protected function _getIndent($line) { $count = $space = $tab = 0; $end = strlen($line); while (($count < $end) && ($line[$count] === "\t")) { $tab++; $count++; } while (($count < $end) && ($line[$count] === ' ')) { $space++; $count++; } return array( 'space' => $space, 'tab' => $tab ); }
php
protected function _getIndent($line) { $count = $space = $tab = 0; $end = strlen($line); while (($count < $end) && ($line[$count] === "\t")) { $tab++; $count++; } while (($count < $end) && ($line[$count] === ' ')) { $space++; $count++; } return array( 'space' => $space, 'tab' => $tab ); }
[ "protected", "function", "_getIndent", "(", "$", "line", ")", "{", "$", "count", "=", "$", "space", "=", "$", "tab", "=", "0", ";", "$", "end", "=", "strlen", "(", "$", "line", ")", ";", "while", "(", "(", "$", "count", "<", "$", "end", ")", "&&", "(", "$", "line", "[", "$", "count", "]", "===", "\"\\t\"", ")", ")", "{", "$", "tab", "++", ";", "$", "count", "++", ";", "}", "while", "(", "(", "$", "count", "<", "$", "end", ")", "&&", "(", "$", "line", "[", "$", "count", "]", "===", "' '", ")", ")", "{", "$", "space", "++", ";", "$", "count", "++", ";", "}", "return", "array", "(", "'space'", "=>", "$", "space", ",", "'tab'", "=>", "$", "tab", ")", ";", "}" ]
Will determine how many tabs are at the beginning of a line. @param string $line The current line is on @return bool
[ "Will", "determine", "how", "many", "tabs", "are", "at", "the", "beginning", "of", "a", "line", "." ]
acb72a43ae835e6d200bc0eba1a61aee610e36bf
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectTabIndention.php#L202-L217
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.configure
public function configure($prefix, $resourceName, array $options) { $this->prefix = $prefix; $this->resourceName = $resourceName; $this->options = $this->getOptionsResolver()->resolve($options); return $this; }
php
public function configure($prefix, $resourceName, array $options) { $this->prefix = $prefix; $this->resourceName = $resourceName; $this->options = $this->getOptionsResolver()->resolve($options); return $this; }
[ "public", "function", "configure", "(", "$", "prefix", ",", "$", "resourceName", ",", "array", "$", "options", ")", "{", "$", "this", "->", "prefix", "=", "$", "prefix", ";", "$", "this", "->", "resourceName", "=", "$", "resourceName", ";", "$", "this", "->", "options", "=", "$", "this", "->", "getOptionsResolver", "(", ")", "->", "resolve", "(", "$", "options", ")", ";", "return", "$", "this", ";", "}" ]
Configures the pool builder. @param string $prefix @param string $resourceName @param array $options @return PoolBuilder
[ "Configures", "the", "pool", "builder", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L97-L104
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createEntityClassParameter
private function createEntityClassParameter() { $id = $this->getServiceId('class'); if (!$this->container->hasParameter($id)) { $this->container->setParameter($id, $this->options['entity']); } $this->configureInheritanceMapping( $this->prefix.'.'.$this->resourceName, $this->options['entity'], $this->options['repository'] ); }
php
private function createEntityClassParameter() { $id = $this->getServiceId('class'); if (!$this->container->hasParameter($id)) { $this->container->setParameter($id, $this->options['entity']); } $this->configureInheritanceMapping( $this->prefix.'.'.$this->resourceName, $this->options['entity'], $this->options['repository'] ); }
[ "private", "function", "createEntityClassParameter", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getServiceId", "(", "'class'", ")", ";", "if", "(", "!", "$", "this", "->", "container", "->", "hasParameter", "(", "$", "id", ")", ")", "{", "$", "this", "->", "container", "->", "setParameter", "(", "$", "id", ",", "$", "this", "->", "options", "[", "'entity'", "]", ")", ";", "}", "$", "this", "->", "configureInheritanceMapping", "(", "$", "this", "->", "prefix", ".", "'.'", ".", "$", "this", "->", "resourceName", ",", "$", "this", "->", "options", "[", "'entity'", "]", ",", "$", "this", "->", "options", "[", "'repository'", "]", ")", ";", "}" ]
Creates the entity class parameter.
[ "Creates", "the", "entity", "class", "parameter", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L248-L260
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createConfigurationDefinition
private function createConfigurationDefinition() { $id = $this->getServiceId('configuration'); if (!$this->container->has($id)) { $definition = new Definition(self::CONFIGURATION); $definition ->setFactory([new Reference('ekyna_admin.pool_factory'), 'createConfiguration']) // ->setFactoryService('ekyna_admin.pool_factory') // ->setFactoryMethod('createConfiguration') ->setArguments([ $this->prefix, $this->resourceName, $this->options['entity'], $this->buildTemplateList($this->options['templates']), $this->options['event'], $this->options['parent'] ]) ->addTag('ekyna_admin.configuration', [ 'alias' => sprintf('%s_%s', $this->prefix, $this->resourceName)] ) ; $this->container->setDefinition($id, $definition); } }
php
private function createConfigurationDefinition() { $id = $this->getServiceId('configuration'); if (!$this->container->has($id)) { $definition = new Definition(self::CONFIGURATION); $definition ->setFactory([new Reference('ekyna_admin.pool_factory'), 'createConfiguration']) // ->setFactoryService('ekyna_admin.pool_factory') // ->setFactoryMethod('createConfiguration') ->setArguments([ $this->prefix, $this->resourceName, $this->options['entity'], $this->buildTemplateList($this->options['templates']), $this->options['event'], $this->options['parent'] ]) ->addTag('ekyna_admin.configuration', [ 'alias' => sprintf('%s_%s', $this->prefix, $this->resourceName)] ) ; $this->container->setDefinition($id, $definition); } }
[ "private", "function", "createConfigurationDefinition", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getServiceId", "(", "'configuration'", ")", ";", "if", "(", "!", "$", "this", "->", "container", "->", "has", "(", "$", "id", ")", ")", "{", "$", "definition", "=", "new", "Definition", "(", "self", "::", "CONFIGURATION", ")", ";", "$", "definition", "->", "setFactory", "(", "[", "new", "Reference", "(", "'ekyna_admin.pool_factory'", ")", ",", "'createConfiguration'", "]", ")", "// ->setFactoryService('ekyna_admin.pool_factory')", "// ->setFactoryMethod('createConfiguration')", "->", "setArguments", "(", "[", "$", "this", "->", "prefix", ",", "$", "this", "->", "resourceName", ",", "$", "this", "->", "options", "[", "'entity'", "]", ",", "$", "this", "->", "buildTemplateList", "(", "$", "this", "->", "options", "[", "'templates'", "]", ")", ",", "$", "this", "->", "options", "[", "'event'", "]", ",", "$", "this", "->", "options", "[", "'parent'", "]", "]", ")", "->", "addTag", "(", "'ekyna_admin.configuration'", ",", "[", "'alias'", "=>", "sprintf", "(", "'%s_%s'", ",", "$", "this", "->", "prefix", ",", "$", "this", "->", "resourceName", ")", "]", ")", ";", "$", "this", "->", "container", "->", "setDefinition", "(", "$", "id", ",", "$", "definition", ")", ";", "}", "}" ]
Creates the Configuration service definition.
[ "Creates", "the", "Configuration", "service", "definition", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L265-L288
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.buildTemplateList
private function buildTemplateList($templatesConfig) { $templateNamespace = self::DEFAULT_TEMPLATES; if (is_string($templatesConfig)) { $templateNamespace = $templatesConfig; } $templatesList = []; foreach (self::$templates as $name => $extensions) { foreach ($extensions as $extension) { $file = $name.'.'.$extension; $templatesList[$file] = $templateNamespace.':'.$file; } } // TODO add resources controller traits templates ? (like new_child.html) if (is_array($templatesConfig)) { $templatesList = array_merge($templatesList, $templatesConfig); } return $templatesList; }
php
private function buildTemplateList($templatesConfig) { $templateNamespace = self::DEFAULT_TEMPLATES; if (is_string($templatesConfig)) { $templateNamespace = $templatesConfig; } $templatesList = []; foreach (self::$templates as $name => $extensions) { foreach ($extensions as $extension) { $file = $name.'.'.$extension; $templatesList[$file] = $templateNamespace.':'.$file; } } // TODO add resources controller traits templates ? (like new_child.html) if (is_array($templatesConfig)) { $templatesList = array_merge($templatesList, $templatesConfig); } return $templatesList; }
[ "private", "function", "buildTemplateList", "(", "$", "templatesConfig", ")", "{", "$", "templateNamespace", "=", "self", "::", "DEFAULT_TEMPLATES", ";", "if", "(", "is_string", "(", "$", "templatesConfig", ")", ")", "{", "$", "templateNamespace", "=", "$", "templatesConfig", ";", "}", "$", "templatesList", "=", "[", "]", ";", "foreach", "(", "self", "::", "$", "templates", "as", "$", "name", "=>", "$", "extensions", ")", "{", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "$", "file", "=", "$", "name", ".", "'.'", ".", "$", "extension", ";", "$", "templatesList", "[", "$", "file", "]", "=", "$", "templateNamespace", ".", "':'", ".", "$", "file", ";", "}", "}", "// TODO add resources controller traits templates ? (like new_child.html)", "if", "(", "is_array", "(", "$", "templatesConfig", ")", ")", "{", "$", "templatesList", "=", "array_merge", "(", "$", "templatesList", ",", "$", "templatesConfig", ")", ";", "}", "return", "$", "templatesList", ";", "}" ]
Builds the templates list. @param mixed $templatesConfig @return array
[ "Builds", "the", "templates", "list", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L296-L314
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createManagerDefinition
private function createManagerDefinition() { $id = $this->getServiceId('manager'); if (!$this->container->has($id)) { $this->container->setAlias($id, new Alias($this->getManagerServiceId())); } }
php
private function createManagerDefinition() { $id = $this->getServiceId('manager'); if (!$this->container->has($id)) { $this->container->setAlias($id, new Alias($this->getManagerServiceId())); } }
[ "private", "function", "createManagerDefinition", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getServiceId", "(", "'manager'", ")", ";", "if", "(", "!", "$", "this", "->", "container", "->", "has", "(", "$", "id", ")", ")", "{", "$", "this", "->", "container", "->", "setAlias", "(", "$", "id", ",", "new", "Alias", "(", "$", "this", "->", "getManagerServiceId", "(", ")", ")", ")", ";", "}", "}" ]
Creates the manager definition.
[ "Creates", "the", "manager", "definition", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L337-L343
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createRepositoryDefinition
private function createRepositoryDefinition() { $id = $this->getServiceId('repository'); if (!$this->container->has($id)) { $definition = new Definition($class = $this->getServiceClass('repository')); $definition->setArguments([ new Reference($this->getServiceId('manager')), new Reference($this->getServiceId('metadata')) ]); if (is_array($this->options['translation'])) { $definition ->addMethodCall('setLocaleProvider', [new Reference('ekyna_core.locale_provider.request')]) // TODO alias / configurable ? ->addMethodCall('setTranslatableFields', [$this->options['translation']['fields']]) ; } $this->container->setDefinition($id, $definition); } }
php
private function createRepositoryDefinition() { $id = $this->getServiceId('repository'); if (!$this->container->has($id)) { $definition = new Definition($class = $this->getServiceClass('repository')); $definition->setArguments([ new Reference($this->getServiceId('manager')), new Reference($this->getServiceId('metadata')) ]); if (is_array($this->options['translation'])) { $definition ->addMethodCall('setLocaleProvider', [new Reference('ekyna_core.locale_provider.request')]) // TODO alias / configurable ? ->addMethodCall('setTranslatableFields', [$this->options['translation']['fields']]) ; } $this->container->setDefinition($id, $definition); } }
[ "private", "function", "createRepositoryDefinition", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getServiceId", "(", "'repository'", ")", ";", "if", "(", "!", "$", "this", "->", "container", "->", "has", "(", "$", "id", ")", ")", "{", "$", "definition", "=", "new", "Definition", "(", "$", "class", "=", "$", "this", "->", "getServiceClass", "(", "'repository'", ")", ")", ";", "$", "definition", "->", "setArguments", "(", "[", "new", "Reference", "(", "$", "this", "->", "getServiceId", "(", "'manager'", ")", ")", ",", "new", "Reference", "(", "$", "this", "->", "getServiceId", "(", "'metadata'", ")", ")", "]", ")", ";", "if", "(", "is_array", "(", "$", "this", "->", "options", "[", "'translation'", "]", ")", ")", "{", "$", "definition", "->", "addMethodCall", "(", "'setLocaleProvider'", ",", "[", "new", "Reference", "(", "'ekyna_core.locale_provider.request'", ")", "]", ")", "// TODO alias / configurable ?", "->", "addMethodCall", "(", "'setTranslatableFields'", ",", "[", "$", "this", "->", "options", "[", "'translation'", "]", "[", "'fields'", "]", "]", ")", ";", "}", "$", "this", "->", "container", "->", "setDefinition", "(", "$", "id", ",", "$", "definition", ")", ";", "}", "}" ]
Creates the Repository service definition.
[ "Creates", "the", "Repository", "service", "definition", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L348-L365
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createOperatorDefinition
private function createOperatorDefinition() { $id = $this->getServiceId('operator'); if (!$this->container->has($id)) { $definition = new Definition($this->getServiceClass('operator')); $definition->setArguments([ new Reference($this->getManagerServiceId()), new Reference($this->getEventDispatcherServiceId()), new Reference($this->getServiceId('configuration')), $this->container->getParameter('kernel.debug') ]); $this->container->setDefinition($id, $definition); } }
php
private function createOperatorDefinition() { $id = $this->getServiceId('operator'); if (!$this->container->has($id)) { $definition = new Definition($this->getServiceClass('operator')); $definition->setArguments([ new Reference($this->getManagerServiceId()), new Reference($this->getEventDispatcherServiceId()), new Reference($this->getServiceId('configuration')), $this->container->getParameter('kernel.debug') ]); $this->container->setDefinition($id, $definition); } }
[ "private", "function", "createOperatorDefinition", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getServiceId", "(", "'operator'", ")", ";", "if", "(", "!", "$", "this", "->", "container", "->", "has", "(", "$", "id", ")", ")", "{", "$", "definition", "=", "new", "Definition", "(", "$", "this", "->", "getServiceClass", "(", "'operator'", ")", ")", ";", "$", "definition", "->", "setArguments", "(", "[", "new", "Reference", "(", "$", "this", "->", "getManagerServiceId", "(", ")", ")", ",", "new", "Reference", "(", "$", "this", "->", "getEventDispatcherServiceId", "(", ")", ")", ",", "new", "Reference", "(", "$", "this", "->", "getServiceId", "(", "'configuration'", ")", ")", ",", "$", "this", "->", "container", "->", "getParameter", "(", "'kernel.debug'", ")", "]", ")", ";", "$", "this", "->", "container", "->", "setDefinition", "(", "$", "id", ",", "$", "definition", ")", ";", "}", "}" ]
Creates the operator service definition. @TODO Swap with ResourceManager when ready.
[ "Creates", "the", "operator", "service", "definition", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L372-L385
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createControllerDefinition
private function createControllerDefinition() { $id = $this->getServiceId('controller'); if (!$this->container->has($id)) { $definition = new Definition($this->getServiceClass('controller')); $definition ->addMethodCall('setConfiguration', [new Reference($this->getServiceId('configuration'))]) ->addMethodCall('setContainer', [new Reference('service_container')]) ; $this->container->setDefinition($id, $definition); } }
php
private function createControllerDefinition() { $id = $this->getServiceId('controller'); if (!$this->container->has($id)) { $definition = new Definition($this->getServiceClass('controller')); $definition ->addMethodCall('setConfiguration', [new Reference($this->getServiceId('configuration'))]) ->addMethodCall('setContainer', [new Reference('service_container')]) ; $this->container->setDefinition($id, $definition); } }
[ "private", "function", "createControllerDefinition", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getServiceId", "(", "'controller'", ")", ";", "if", "(", "!", "$", "this", "->", "container", "->", "has", "(", "$", "id", ")", ")", "{", "$", "definition", "=", "new", "Definition", "(", "$", "this", "->", "getServiceClass", "(", "'controller'", ")", ")", ";", "$", "definition", "->", "addMethodCall", "(", "'setConfiguration'", ",", "[", "new", "Reference", "(", "$", "this", "->", "getServiceId", "(", "'configuration'", ")", ")", "]", ")", "->", "addMethodCall", "(", "'setContainer'", ",", "[", "new", "Reference", "(", "'service_container'", ")", "]", ")", ";", "$", "this", "->", "container", "->", "setDefinition", "(", "$", "id", ",", "$", "definition", ")", ";", "}", "}" ]
Creates the Controller service definition.
[ "Creates", "the", "Controller", "service", "definition", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L390-L401
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.configureTranslations
private function configureTranslations() { if (null !== array_key_exists('translation', $this->options) && is_array($this->options['translation'])) { $translatable = $this->options['entity']; $translation = $this->options['translation']['entity']; $id = sprintf('%s.%s_translation', $this->prefix, $this->resourceName); // Load metadata event mapping $mapping = [ $translatable => $translation, $translation => $translatable, ]; if ($this->container->hasParameter('ekyna_admin.translation_mapping')) { $mapping = array_merge($this->container->getParameter('ekyna_admin.translation_mapping'), $mapping); } $this->container->setParameter('ekyna_admin.translation_mapping', $mapping); // Translation class parameter if (!$this->container->hasParameter($id.'.class')) { $this->container->setParameter($id.'.class', $translation); } // Inheritance mapping $this->configureInheritanceMapping($id, $translation, $this->options['translation']['repository']); } }
php
private function configureTranslations() { if (null !== array_key_exists('translation', $this->options) && is_array($this->options['translation'])) { $translatable = $this->options['entity']; $translation = $this->options['translation']['entity']; $id = sprintf('%s.%s_translation', $this->prefix, $this->resourceName); // Load metadata event mapping $mapping = [ $translatable => $translation, $translation => $translatable, ]; if ($this->container->hasParameter('ekyna_admin.translation_mapping')) { $mapping = array_merge($this->container->getParameter('ekyna_admin.translation_mapping'), $mapping); } $this->container->setParameter('ekyna_admin.translation_mapping', $mapping); // Translation class parameter if (!$this->container->hasParameter($id.'.class')) { $this->container->setParameter($id.'.class', $translation); } // Inheritance mapping $this->configureInheritanceMapping($id, $translation, $this->options['translation']['repository']); } }
[ "private", "function", "configureTranslations", "(", ")", "{", "if", "(", "null", "!==", "array_key_exists", "(", "'translation'", ",", "$", "this", "->", "options", ")", "&&", "is_array", "(", "$", "this", "->", "options", "[", "'translation'", "]", ")", ")", "{", "$", "translatable", "=", "$", "this", "->", "options", "[", "'entity'", "]", ";", "$", "translation", "=", "$", "this", "->", "options", "[", "'translation'", "]", "[", "'entity'", "]", ";", "$", "id", "=", "sprintf", "(", "'%s.%s_translation'", ",", "$", "this", "->", "prefix", ",", "$", "this", "->", "resourceName", ")", ";", "// Load metadata event mapping", "$", "mapping", "=", "[", "$", "translatable", "=>", "$", "translation", ",", "$", "translation", "=>", "$", "translatable", ",", "]", ";", "if", "(", "$", "this", "->", "container", "->", "hasParameter", "(", "'ekyna_admin.translation_mapping'", ")", ")", "{", "$", "mapping", "=", "array_merge", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'ekyna_admin.translation_mapping'", ")", ",", "$", "mapping", ")", ";", "}", "$", "this", "->", "container", "->", "setParameter", "(", "'ekyna_admin.translation_mapping'", ",", "$", "mapping", ")", ";", "// Translation class parameter", "if", "(", "!", "$", "this", "->", "container", "->", "hasParameter", "(", "$", "id", ".", "'.class'", ")", ")", "{", "$", "this", "->", "container", "->", "setParameter", "(", "$", "id", ".", "'.class'", ",", "$", "translation", ")", ";", "}", "// Inheritance mapping", "$", "this", "->", "configureInheritanceMapping", "(", "$", "id", ",", "$", "translation", ",", "$", "this", "->", "options", "[", "'translation'", "]", "[", "'repository'", "]", ")", ";", "}", "}" ]
Configure the translation
[ "Configure", "the", "translation" ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L442-L468
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.configureInheritanceMapping
private function configureInheritanceMapping($id, $entity, $repository) { $entities = [ $id => [ 'class' => $entity, 'repository' => $repository, ], ]; if ($this->container->hasParameter('ekyna_core.entities')) { $entities = array_merge($this->container->getParameter('ekyna_core.entities'), $entities); } $this->container->setParameter('ekyna_core.entities', $entities); }
php
private function configureInheritanceMapping($id, $entity, $repository) { $entities = [ $id => [ 'class' => $entity, 'repository' => $repository, ], ]; if ($this->container->hasParameter('ekyna_core.entities')) { $entities = array_merge($this->container->getParameter('ekyna_core.entities'), $entities); } $this->container->setParameter('ekyna_core.entities', $entities); }
[ "private", "function", "configureInheritanceMapping", "(", "$", "id", ",", "$", "entity", ",", "$", "repository", ")", "{", "$", "entities", "=", "[", "$", "id", "=>", "[", "'class'", "=>", "$", "entity", ",", "'repository'", "=>", "$", "repository", ",", "]", ",", "]", ";", "if", "(", "$", "this", "->", "container", "->", "hasParameter", "(", "'ekyna_core.entities'", ")", ")", "{", "$", "entities", "=", "array_merge", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'ekyna_core.entities'", ")", ",", "$", "entities", ")", ";", "}", "$", "this", "->", "container", "->", "setParameter", "(", "'ekyna_core.entities'", ",", "$", "entities", ")", ";", "}" ]
Configures mapping inheritance. @param string $id @param string $entity @param string $repository
[ "Configures", "mapping", "inheritance", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L477-L490
train
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.getServiceClass
private function getServiceClass($name) { $serviceId = $this->getServiceId($name); $parameterId = $serviceId.'.class'; if ($this->container->hasParameter($parameterId)) { $class = $this->container->getParameter($parameterId); } elseif (array_key_exists($name, $this->options)) { $class = $this->options[$name]; } else { throw new \RuntimeException(sprintf('Undefined "%s" service class.', $name)); } return $class; }
php
private function getServiceClass($name) { $serviceId = $this->getServiceId($name); $parameterId = $serviceId.'.class'; if ($this->container->hasParameter($parameterId)) { $class = $this->container->getParameter($parameterId); } elseif (array_key_exists($name, $this->options)) { $class = $this->options[$name]; } else { throw new \RuntimeException(sprintf('Undefined "%s" service class.', $name)); } return $class; }
[ "private", "function", "getServiceClass", "(", "$", "name", ")", "{", "$", "serviceId", "=", "$", "this", "->", "getServiceId", "(", "$", "name", ")", ";", "$", "parameterId", "=", "$", "serviceId", ".", "'.class'", ";", "if", "(", "$", "this", "->", "container", "->", "hasParameter", "(", "$", "parameterId", ")", ")", "{", "$", "class", "=", "$", "this", "->", "container", "->", "getParameter", "(", "$", "parameterId", ")", ";", "}", "elseif", "(", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "options", ")", ")", "{", "$", "class", "=", "$", "this", "->", "options", "[", "$", "name", "]", ";", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Undefined \"%s\" service class.'", ",", "$", "name", ")", ")", ";", "}", "return", "$", "class", ";", "}" ]
Returns the service class for the given name. @param string $name @throws \RuntimeException @return string|null
[ "Returns", "the", "service", "class", "for", "the", "given", "name", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L533-L545
train
schpill/thin
src/Html/Qwerly/User.php
User.getDescription
public function getDescription() { return isset($this->_data[self::PROFILE][self::DESCRIPTION]) ? $this->_data[self::PROFILE][self::DESCRIPTION] : null; }
php
public function getDescription() { return isset($this->_data[self::PROFILE][self::DESCRIPTION]) ? $this->_data[self::PROFILE][self::DESCRIPTION] : null; }
[ "public", "function", "getDescription", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "DESCRIPTION", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "DESCRIPTION", "]", ":", "null", ";", "}" ]
Retrieves the user's description. @return string
[ "Retrieves", "the", "user", "s", "description", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L32-L35
train
schpill/thin
src/Html/Qwerly/User.php
User.getName
public function getName() { return isset($this->_data[self::PROFILE][self::NAME]) ? $this->_data[self::PROFILE][self::NAME] : null; }
php
public function getName() { return isset($this->_data[self::PROFILE][self::NAME]) ? $this->_data[self::PROFILE][self::NAME] : null; }
[ "public", "function", "getName", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "NAME", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "NAME", "]", ":", "null", ";", "}" ]
Retrieves the user's name. @return string
[ "Retrieves", "the", "user", "s", "name", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L42-L45
train
schpill/thin
src/Html/Qwerly/User.php
User.getLocation
public function getLocation() { return isset($this->_data[self::PROFILE][self::LOCATION]) ? $this->_data[self::PROFILE][self::LOCATION] : null; }
php
public function getLocation() { return isset($this->_data[self::PROFILE][self::LOCATION]) ? $this->_data[self::PROFILE][self::LOCATION] : null; }
[ "public", "function", "getLocation", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "LOCATION", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "LOCATION", "]", ":", "null", ";", "}" ]
Retrieves the user's location. @return string
[ "Retrieves", "the", "user", "s", "location", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L53-L56
train
schpill/thin
src/Html/Qwerly/User.php
User.getTwitter
public function getTwitter() { return isset($this->_data[self::PROFILE][self::TWITTER_USERNAME]) ? $this->_data[self::PROFILE][self::TWITTER_USERNAME] : null; }
php
public function getTwitter() { return isset($this->_data[self::PROFILE][self::TWITTER_USERNAME]) ? $this->_data[self::PROFILE][self::TWITTER_USERNAME] : null; }
[ "public", "function", "getTwitter", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "TWITTER_USERNAME", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "TWITTER_USERNAME", "]", ":", "null", ";", "}" ]
Retrieves the user's twitter username. @return string
[ "Retrieves", "the", "user", "s", "twitter", "username", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L63-L66
train
schpill/thin
src/Html/Qwerly/User.php
User.getWebsite
public function getWebsite() { return isset($this->_data[self::PROFILE][self::WEBSITE]) ? $this->_data[self::PROFILE][self::WEBSITE] : null; }
php
public function getWebsite() { return isset($this->_data[self::PROFILE][self::WEBSITE]) ? $this->_data[self::PROFILE][self::WEBSITE] : null; }
[ "public", "function", "getWebsite", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "WEBSITE", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "WEBSITE", "]", ":", "null", ";", "}" ]
Retrievs the user's website. @return string
[ "Retrievs", "the", "user", "s", "website", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L73-L76
train
schpill/thin
src/Html/Qwerly/User.php
User.getServices
public function getServices() { return isset($this->_data[self::PROFILE][self::SERVICES]) ? $this->_data[self::PROFILE][self::SERVICES] : null; }
php
public function getServices() { return isset($this->_data[self::PROFILE][self::SERVICES]) ? $this->_data[self::PROFILE][self::SERVICES] : null; }
[ "public", "function", "getServices", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "SERVICES", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "SERVICES", "]", ":", "null", ";", "}" ]
Retrieves the user's services. @return array
[ "Retrieves", "the", "user", "s", "services", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L83-L86
train
schpill/thin
src/Html/Qwerly/User.php
User.getQwerly
public function getQwerly() { return isset($this->_data[self::PROFILE][self::QWERLY]) ? $this->_data[self::PROFILE][self::QWERLY] : null; }
php
public function getQwerly() { return isset($this->_data[self::PROFILE][self::QWERLY]) ? $this->_data[self::PROFILE][self::QWERLY] : null; }
[ "public", "function", "getQwerly", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "QWERLY", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "QWERLY", "]", ":", "null", ";", "}" ]
Retrieves the user's qwerly username. @return string
[ "Retrieves", "the", "user", "s", "qwerly", "username", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L93-L96
train
schpill/thin
src/Html/Qwerly/User.php
User.getFacebook
public function getFacebook() { return isset($this->_data[self::PROFILE][self::FACEBOOK_ID]) ? $this->_data[self::PROFILE][self::FACEBOOK_ID] : null; }
php
public function getFacebook() { return isset($this->_data[self::PROFILE][self::FACEBOOK_ID]) ? $this->_data[self::PROFILE][self::FACEBOOK_ID] : null; }
[ "public", "function", "getFacebook", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "FACEBOOK_ID", "]", ")", "?", "$", "this", "->", "_data", "[", "self", "::", "PROFILE", "]", "[", "self", "::", "FACEBOOK_ID", "]", ":", "null", ";", "}" ]
Retrieves the user's facebook id. @return int
[ "Retrieves", "the", "user", "s", "facebook", "id", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L103-L106
train
oliwierptak/Everon1
src/Everon/Helper/AlphaId.php
AlphaId.alphaId
function alphaId($in, $to_num = false, $pad_up = false, $pass_key = null) { $out = ''; $index = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $base = strlen($index); if ($pass_key !== null) { // Although this function's purpose is to just make the // ID short - and not so much secure, // with this patch by Simon Franz (http://blog.snaky.org/) // you can optionally supply a password to make it harder // to calculate the corresponding numeric ID for ($n = 0; $n < strlen($index); $n++) { $i[] = substr($index, $n, 1); } $pass_hash = hash('sha256',$pass_key); $pass_hash = (strlen($pass_hash) < strlen($index) ? hash('sha512', $pass_key) : $pass_hash); for ($n = 0; $n < strlen($index); $n++) { $p[] = substr($pass_hash, $n, 1); } array_multisort($p, SORT_DESC, $i); $index = implode($i); } if ($to_num) { // Digital number <<-- alphabet letter code $len = strlen($in) - 1; for ($t = $len; $t >= 0; $t--) { $bcp = bcpow($base, $len - $t); $out = $out + strpos($index, substr($in, $t, 1)) * $bcp; } if (is_numeric($pad_up)) { $pad_up--; if ($pad_up > 0) { $out -= pow($base, $pad_up); } } } else { // Digital number -->> alphabet letter code if (is_numeric($pad_up)) { $pad_up--; if ($pad_up > 0) { $in += pow($base, $pad_up); } } for ($t = ($in != 0 ? floor(log($in, $base)) : 0); $t >= 0; $t--) { $bcp = bcpow($base, $t); $a = floor($in / $bcp) % $base; $out = $out . substr($index, $a, 1); $in = $in - ($a * $bcp); } } return $out; }
php
function alphaId($in, $to_num = false, $pad_up = false, $pass_key = null) { $out = ''; $index = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $base = strlen($index); if ($pass_key !== null) { // Although this function's purpose is to just make the // ID short - and not so much secure, // with this patch by Simon Franz (http://blog.snaky.org/) // you can optionally supply a password to make it harder // to calculate the corresponding numeric ID for ($n = 0; $n < strlen($index); $n++) { $i[] = substr($index, $n, 1); } $pass_hash = hash('sha256',$pass_key); $pass_hash = (strlen($pass_hash) < strlen($index) ? hash('sha512', $pass_key) : $pass_hash); for ($n = 0; $n < strlen($index); $n++) { $p[] = substr($pass_hash, $n, 1); } array_multisort($p, SORT_DESC, $i); $index = implode($i); } if ($to_num) { // Digital number <<-- alphabet letter code $len = strlen($in) - 1; for ($t = $len; $t >= 0; $t--) { $bcp = bcpow($base, $len - $t); $out = $out + strpos($index, substr($in, $t, 1)) * $bcp; } if (is_numeric($pad_up)) { $pad_up--; if ($pad_up > 0) { $out -= pow($base, $pad_up); } } } else { // Digital number -->> alphabet letter code if (is_numeric($pad_up)) { $pad_up--; if ($pad_up > 0) { $in += pow($base, $pad_up); } } for ($t = ($in != 0 ? floor(log($in, $base)) : 0); $t >= 0; $t--) { $bcp = bcpow($base, $t); $a = floor($in / $bcp) % $base; $out = $out . substr($index, $a, 1); $in = $in - ($a * $bcp); } } return $out; }
[ "function", "alphaId", "(", "$", "in", ",", "$", "to_num", "=", "false", ",", "$", "pad_up", "=", "false", ",", "$", "pass_key", "=", "null", ")", "{", "$", "out", "=", "''", ";", "$", "index", "=", "'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'", ";", "$", "base", "=", "strlen", "(", "$", "index", ")", ";", "if", "(", "$", "pass_key", "!==", "null", ")", "{", "// Although this function's purpose is to just make the", "// ID short - and not so much secure,", "// with this patch by Simon Franz (http://blog.snaky.org/)", "// you can optionally supply a password to make it harder", "// to calculate the corresponding numeric ID", "for", "(", "$", "n", "=", "0", ";", "$", "n", "<", "strlen", "(", "$", "index", ")", ";", "$", "n", "++", ")", "{", "$", "i", "[", "]", "=", "substr", "(", "$", "index", ",", "$", "n", ",", "1", ")", ";", "}", "$", "pass_hash", "=", "hash", "(", "'sha256'", ",", "$", "pass_key", ")", ";", "$", "pass_hash", "=", "(", "strlen", "(", "$", "pass_hash", ")", "<", "strlen", "(", "$", "index", ")", "?", "hash", "(", "'sha512'", ",", "$", "pass_key", ")", ":", "$", "pass_hash", ")", ";", "for", "(", "$", "n", "=", "0", ";", "$", "n", "<", "strlen", "(", "$", "index", ")", ";", "$", "n", "++", ")", "{", "$", "p", "[", "]", "=", "substr", "(", "$", "pass_hash", ",", "$", "n", ",", "1", ")", ";", "}", "array_multisort", "(", "$", "p", ",", "SORT_DESC", ",", "$", "i", ")", ";", "$", "index", "=", "implode", "(", "$", "i", ")", ";", "}", "if", "(", "$", "to_num", ")", "{", "// Digital number <<-- alphabet letter code", "$", "len", "=", "strlen", "(", "$", "in", ")", "-", "1", ";", "for", "(", "$", "t", "=", "$", "len", ";", "$", "t", ">=", "0", ";", "$", "t", "--", ")", "{", "$", "bcp", "=", "bcpow", "(", "$", "base", ",", "$", "len", "-", "$", "t", ")", ";", "$", "out", "=", "$", "out", "+", "strpos", "(", "$", "index", ",", "substr", "(", "$", "in", ",", "$", "t", ",", "1", ")", ")", "*", "$", "bcp", ";", "}", "if", "(", "is_numeric", "(", "$", "pad_up", ")", ")", "{", "$", "pad_up", "--", ";", "if", "(", "$", "pad_up", ">", "0", ")", "{", "$", "out", "-=", "pow", "(", "$", "base", ",", "$", "pad_up", ")", ";", "}", "}", "}", "else", "{", "// Digital number -->> alphabet letter code", "if", "(", "is_numeric", "(", "$", "pad_up", ")", ")", "{", "$", "pad_up", "--", ";", "if", "(", "$", "pad_up", ">", "0", ")", "{", "$", "in", "+=", "pow", "(", "$", "base", ",", "$", "pad_up", ")", ";", "}", "}", "for", "(", "$", "t", "=", "(", "$", "in", "!=", "0", "?", "floor", "(", "log", "(", "$", "in", ",", "$", "base", ")", ")", ":", "0", ")", ";", "$", "t", ">=", "0", ";", "$", "t", "--", ")", "{", "$", "bcp", "=", "bcpow", "(", "$", "base", ",", "$", "t", ")", ";", "$", "a", "=", "floor", "(", "$", "in", "/", "$", "bcp", ")", "%", "$", "base", ";", "$", "out", "=", "$", "out", ".", "substr", "(", "$", "index", ",", "$", "a", ",", "1", ")", ";", "$", "in", "=", "$", "in", "-", "(", "$", "a", "*", "$", "bcp", ")", ";", "}", "}", "return", "$", "out", ";", "}" ]
Translates a number to a short alhanumeric version Translated any number up to 9007199254740992 to a shorter version in letters e.g.: 9007199254740989 --> PpQXn7COf specifiying the second argument true, it will translate back e.g.: PpQXn7COf --> 9007199254740989 this function is based on any2dec && dec2any by fragmer[at]mail[dot]ru see: http://nl3.php.net/manual/en/function.base-convert.php#52450 If you want the alphaID to be at least 3 letter long, use the $pad_up = 3 argument In most cases this is better than totally random ID generators because this can easily avoid duplicate ID's. For example if you correlate the alpha ID to an auto incrementing ID in your database, you're done. The reverse is done because it makes it slightly more cryptic, but it also makes it easier to spread lots of IDs in different directories on your filesystem. Example: $part1 = substr($alpha_id,0,1); $part2 = substr($alpha_id,1,1); $part3 = substr($alpha_id,2,strlen($alpha_id)); $destindir = "/".$part1."/".$part2."/".$part3; // by reversing, directories are more evenly spread out. The // first 26 directories already occupy 26 main levels more info on limitation: - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/165372 if you really need this for bigger numbers you probably have to look at things like: http://theserverpages.com/php/manual/en/ref.bc.php or: http://theserverpages.com/php/manual/en/ref.gmp.php but I haven't really dugg into this. If you have more info on those matters feel free to leave a comment. The following code block can be utilized by PEAR's Testing_DocTest <code> // Input // $number_in = 2188847690240; $alpha_in = "SpQXn7Cb"; // Execute // $alpha_out = alphaID($number_in, false, 8); $number_out = alphaID($alpha_in, true, 8); if ($number_in != $number_out) { echo "Conversion failure, ".$alpha_in." returns ".$number_out." instead of the "; echo "desired: ".$number_in."\n"; } if ($alpha_in != $alpha_out) { echo "Conversion failure, ".$number_in." returns ".$alpha_out." instead of the "; echo "desired: ".$alpha_in."\n"; } // Show // echo $number_out." => ".$alpha_out."\n"; echo $alpha_in." => ".$number_out."\n"; echo alphaID(238328, false)." => ".alphaID(alphaID(238328, false), true)."\n"; // expects: // 2188847690240 => SpQXn7Cb // SpQXn7Cb => 2188847690240 // aaab => 238328 </code> @author Kevin van Zonneveld &lt;kevin@vanzonneveld.net> @author Simon Franz @author Deadfish @author SK83RJOSH @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net) @license http://www.opensource.org/licenses/bsd-license.php New BSD Licence @version SVN: Release: $Id: alphaID.inc.php 344 2009-06-10 17:43:59Z kevin $ @link http://kevin.vanzonneveld.net/ @param mixed $in String or long input to translate @param boolean $to_num Reverses translation when true @param mixed $pad_up Number or boolean padds the result up to a specified length @param string $pass_key Supplying a password makes it harder to calculate the original ID @return mixed string or long
[ "Translates", "a", "number", "to", "a", "short", "alhanumeric", "version" ]
ac93793d1fa517a8394db5f00062f1925dc218a3
https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/Helper/AlphaId.php#L107-L170
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Cancel.php
EbayEnterprise_Order_Model_Cancel._buildRequest
protected function _buildRequest() { $this->_request = $this->_factory ->getNewCancelBuildRequest($this->_api, $this->_order) ->build(); return $this; }
php
protected function _buildRequest() { $this->_request = $this->_factory ->getNewCancelBuildRequest($this->_api, $this->_order) ->build(); return $this; }
[ "protected", "function", "_buildRequest", "(", ")", "{", "$", "this", "->", "_request", "=", "$", "this", "->", "_factory", "->", "getNewCancelBuildRequest", "(", "$", "this", "->", "_api", ",", "$", "this", "->", "_order", ")", "->", "build", "(", ")", ";", "return", "$", "this", ";", "}" ]
Build order cancel payload. @return self
[ "Build", "order", "cancel", "payload", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Cancel.php#L105-L111
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Cancel.php
EbayEnterprise_Order_Model_Cancel._sendRequest
protected function _sendRequest() { $this->_response = $this->_factory ->getNewCancelSendRequest($this->_api, $this->_request) ->send(); return $this; }
php
protected function _sendRequest() { $this->_response = $this->_factory ->getNewCancelSendRequest($this->_api, $this->_request) ->send(); return $this; }
[ "protected", "function", "_sendRequest", "(", ")", "{", "$", "this", "->", "_response", "=", "$", "this", "->", "_factory", "->", "getNewCancelSendRequest", "(", "$", "this", "->", "_api", ",", "$", "this", "->", "_request", ")", "->", "send", "(", ")", ";", "return", "$", "this", ";", "}" ]
Send order cancel payload. @return self
[ "Send", "order", "cancel", "payload", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Cancel.php#L118-L124
train
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Cancel.php
EbayEnterprise_Order_Model_Cancel._processResponse
protected function _processResponse() { $this->_factory ->getNewCancelProcessResponse($this->_response, $this->_order) ->process(); return $this; }
php
protected function _processResponse() { $this->_factory ->getNewCancelProcessResponse($this->_response, $this->_order) ->process(); return $this; }
[ "protected", "function", "_processResponse", "(", ")", "{", "$", "this", "->", "_factory", "->", "getNewCancelProcessResponse", "(", "$", "this", "->", "_response", ",", "$", "this", "->", "_order", ")", "->", "process", "(", ")", ";", "return", "$", "this", ";", "}" ]
Process order cancel response. @return self
[ "Process", "order", "cancel", "response", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Cancel.php#L131-L137
train
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.create
public static function create($code, $value = 0) { $cd = strtoupper($code); list($symbol, $precision, $name) = self::getDefinition($cd); $crcy = new Currency($value, $cd, $symbol, $precision, $name); $crcy->setLocale(self::getLocale()); return $crcy; }
php
public static function create($code, $value = 0) { $cd = strtoupper($code); list($symbol, $precision, $name) = self::getDefinition($cd); $crcy = new Currency($value, $cd, $symbol, $precision, $name); $crcy->setLocale(self::getLocale()); return $crcy; }
[ "public", "static", "function", "create", "(", "$", "code", ",", "$", "value", "=", "0", ")", "{", "$", "cd", "=", "strtoupper", "(", "$", "code", ")", ";", "list", "(", "$", "symbol", ",", "$", "precision", ",", "$", "name", ")", "=", "self", "::", "getDefinition", "(", "$", "cd", ")", ";", "$", "crcy", "=", "new", "Currency", "(", "$", "value", ",", "$", "cd", ",", "$", "symbol", ",", "$", "precision", ",", "$", "name", ")", ";", "$", "crcy", "->", "setLocale", "(", "self", "::", "getLocale", "(", ")", ")", ";", "return", "$", "crcy", ";", "}" ]
Create a currency @param string $code Currency 3 letter ISO4217 code @param int $value initial value for currency @return Currency @throws \ErrorException
[ "Create", "a", "currency" ]
d2c6a3da2d1443818b98206ec2cb8f34c2a3be84
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L41-L49
train
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.getDefinition
protected static function getDefinition($code) { $currencies = self::getDefinitions(); $nodes = $currencies->xpath("//currency[@code='{$code}']"); if (empty($nodes)) { throw new \InvalidArgumentException("Unknown currency: {$code}"); } $cNode = $nodes[0]; $def = array( self::createSymbol($cNode->symbol, $code), intval($cNode->exponent), self::createName($cNode), ); return $def; }
php
protected static function getDefinition($code) { $currencies = self::getDefinitions(); $nodes = $currencies->xpath("//currency[@code='{$code}']"); if (empty($nodes)) { throw new \InvalidArgumentException("Unknown currency: {$code}"); } $cNode = $nodes[0]; $def = array( self::createSymbol($cNode->symbol, $code), intval($cNode->exponent), self::createName($cNode), ); return $def; }
[ "protected", "static", "function", "getDefinition", "(", "$", "code", ")", "{", "$", "currencies", "=", "self", "::", "getDefinitions", "(", ")", ";", "$", "nodes", "=", "$", "currencies", "->", "xpath", "(", "\"//currency[@code='{$code}']\"", ")", ";", "if", "(", "empty", "(", "$", "nodes", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Unknown currency: {$code}\"", ")", ";", "}", "$", "cNode", "=", "$", "nodes", "[", "0", "]", ";", "$", "def", "=", "array", "(", "self", "::", "createSymbol", "(", "$", "cNode", "->", "symbol", ",", "$", "code", ")", ",", "intval", "(", "$", "cNode", "->", "exponent", ")", ",", "self", "::", "createName", "(", "$", "cNode", ")", ",", ")", ";", "return", "$", "def", ";", "}" ]
Get a currency definition @param string $code ISO4217 currency code @return array ['symbol','precision', 'name'] @throws \ErrorException
[ "Get", "a", "currency", "definition" ]
d2c6a3da2d1443818b98206ec2cb8f34c2a3be84
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L84-L101
train
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.getDefinitions
protected static function getDefinitions() { if (empty(self::$definitions)) { self::$definitions = \simplexml_load_file(__DIR__ . '/currencies.xml'); } return self::$definitions; }
php
protected static function getDefinitions() { if (empty(self::$definitions)) { self::$definitions = \simplexml_load_file(__DIR__ . '/currencies.xml'); } return self::$definitions; }
[ "protected", "static", "function", "getDefinitions", "(", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "definitions", ")", ")", "{", "self", "::", "$", "definitions", "=", "\\", "simplexml_load_file", "(", "__DIR__", ".", "'/currencies.xml'", ")", ";", "}", "return", "self", "::", "$", "definitions", ";", "}" ]
Load currency definitions @return \SimpleXMLElement
[ "Load", "currency", "definitions" ]
d2c6a3da2d1443818b98206ec2cb8f34c2a3be84
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L108-L115
train
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.createSymbol
protected static function createSymbol(\SimpleXMLElement $sNode, $code) { switch((string) $sNode['type']) { case 'UCS': $symbol = (string) $sNode['UTF-8']; break; case null: //no symbol - use code default: $symbol = $code; break; } return $symbol; }
php
protected static function createSymbol(\SimpleXMLElement $sNode, $code) { switch((string) $sNode['type']) { case 'UCS': $symbol = (string) $sNode['UTF-8']; break; case null: //no symbol - use code default: $symbol = $code; break; } return $symbol; }
[ "protected", "static", "function", "createSymbol", "(", "\\", "SimpleXMLElement", "$", "sNode", ",", "$", "code", ")", "{", "switch", "(", "(", "string", ")", "$", "sNode", "[", "'type'", "]", ")", "{", "case", "'UCS'", ":", "$", "symbol", "=", "(", "string", ")", "$", "sNode", "[", "'UTF-8'", "]", ";", "break", ";", "case", "null", ":", "//no symbol - use code", "default", ":", "$", "symbol", "=", "$", "code", ";", "break", ";", "}", "return", "$", "symbol", ";", "}" ]
Create currency symbol from the symbol node @param \SimpleXMLElement $sNode @param string $code currency code @return string
[ "Create", "currency", "symbol", "from", "the", "symbol", "node" ]
d2c6a3da2d1443818b98206ec2cb8f34c2a3be84
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L125-L138
train
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.createName
protected static function createName(\SimpleXMLElement $currency) { $locale = self::getLocale(); //first - see if we have an exact locale match $nodes = $currency->xpath("name[@lang='{$locale}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //next, see if we have a name for the language part of the locale $lang = \locale_get_primary_language($locale()); $nodes = $currency->xpath("name[@lang='{$lang}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //else default to using 'en' $nodes = $currency->xpath("name[@lang='en']"); return (string) $nodes[0]; }
php
protected static function createName(\SimpleXMLElement $currency) { $locale = self::getLocale(); //first - see if we have an exact locale match $nodes = $currency->xpath("name[@lang='{$locale}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //next, see if we have a name for the language part of the locale $lang = \locale_get_primary_language($locale()); $nodes = $currency->xpath("name[@lang='{$lang}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //else default to using 'en' $nodes = $currency->xpath("name[@lang='en']"); return (string) $nodes[0]; }
[ "protected", "static", "function", "createName", "(", "\\", "SimpleXMLElement", "$", "currency", ")", "{", "$", "locale", "=", "self", "::", "getLocale", "(", ")", ";", "//first - see if we have an exact locale match", "$", "nodes", "=", "$", "currency", "->", "xpath", "(", "\"name[@lang='{$locale}']\"", ")", ";", "if", "(", "count", "(", "$", "nodes", ")", ">", "0", ")", "{", "return", "(", "string", ")", "$", "nodes", "[", "0", "]", ";", "}", "//next, see if we have a name for the language part of the locale", "$", "lang", "=", "\\", "locale_get_primary_language", "(", "$", "locale", "(", ")", ")", ";", "$", "nodes", "=", "$", "currency", "->", "xpath", "(", "\"name[@lang='{$lang}']\"", ")", ";", "if", "(", "count", "(", "$", "nodes", ")", ">", "0", ")", "{", "return", "(", "string", ")", "$", "nodes", "[", "0", "]", ";", "}", "//else default to using 'en'", "$", "nodes", "=", "$", "currency", "->", "xpath", "(", "\"name[@lang='en']\"", ")", ";", "return", "(", "string", ")", "$", "nodes", "[", "0", "]", ";", "}" ]
Find closest matching name for a currency based on currently set locale. Default to 'en' entry if none more suitable found @param \SimpleXMLElement $currency @return string
[ "Find", "closest", "matching", "name", "for", "a", "currency", "based", "on", "currently", "set", "locale", ".", "Default", "to", "en", "entry", "if", "none", "more", "suitable", "found" ]
d2c6a3da2d1443818b98206ec2cb8f34c2a3be84
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L148-L167
train
gplcart/file_manager
handlers/commands/Command.php
Command.getTotal
protected function getTotal($directory, array $options = array()) { $options['count'] = true; return (int) $this->scanner->scan($directory, $options); }
php
protected function getTotal($directory, array $options = array()) { $options['count'] = true; return (int) $this->scanner->scan($directory, $options); }
[ "protected", "function", "getTotal", "(", "$", "directory", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "options", "[", "'count'", "]", "=", "true", ";", "return", "(", "int", ")", "$", "this", "->", "scanner", "->", "scan", "(", "$", "directory", ",", "$", "options", ")", ";", "}" ]
Returns a total number of scanned files @param string $directory @param array $options @return integer
[ "Returns", "a", "total", "number", "of", "scanned", "files" ]
45424e93eafea75d31af6410ac9cf110f08e500a
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L59-L63
train
gplcart/file_manager
handlers/commands/Command.php
Command.getRelativePath
protected function getRelativePath($path = null) { if (!isset($path)) { $path = $this->scanner->getInitialPath(true); } return gplcart_path_normalize(gplcart_path_relative($path)); }
php
protected function getRelativePath($path = null) { if (!isset($path)) { $path = $this->scanner->getInitialPath(true); } return gplcart_path_normalize(gplcart_path_relative($path)); }
[ "protected", "function", "getRelativePath", "(", "$", "path", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "path", ")", ")", "{", "$", "path", "=", "$", "this", "->", "scanner", "->", "getInitialPath", "(", "true", ")", ";", "}", "return", "gplcart_path_normalize", "(", "gplcart_path_relative", "(", "$", "path", ")", ")", ";", "}" ]
Returns a relative file path or initial directory @param null|string $path @return string
[ "Returns", "a", "relative", "file", "path", "or", "initial", "directory" ]
45424e93eafea75d31af6410ac9cf110f08e500a
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L91-L98
train
gplcart/file_manager
handlers/commands/Command.php
Command.move
protected function move($src, $dest, &$errors = 0, &$success = 0) { $this->copy($src, $dest, $errors, $success); if (empty($errors)) { gplcart_file_delete_recursive($src, $errors); } return empty($errors); }
php
protected function move($src, $dest, &$errors = 0, &$success = 0) { $this->copy($src, $dest, $errors, $success); if (empty($errors)) { gplcart_file_delete_recursive($src, $errors); } return empty($errors); }
[ "protected", "function", "move", "(", "$", "src", ",", "$", "dest", ",", "&", "$", "errors", "=", "0", ",", "&", "$", "success", "=", "0", ")", "{", "$", "this", "->", "copy", "(", "$", "src", ",", "$", "dest", ",", "$", "errors", ",", "$", "success", ")", ";", "if", "(", "empty", "(", "$", "errors", ")", ")", "{", "gplcart_file_delete_recursive", "(", "$", "src", ",", "$", "errors", ")", ";", "}", "return", "empty", "(", "$", "errors", ")", ";", "}" ]
Moves a file to a new destination @param string $src @param string $dest @param int $errors @param int $success @return bool
[ "Moves", "a", "file", "to", "a", "new", "destination" ]
45424e93eafea75d31af6410ac9cf110f08e500a
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L118-L127
train
gplcart/file_manager
handlers/commands/Command.php
Command.isInitialPath
protected function isInitialPath($file) { $current_path = gplcart_path_normalize($file->getRealPath()); $initial_path = gplcart_path_normalize($this->scanner->getInitialPath(true)); return $current_path === $initial_path; }
php
protected function isInitialPath($file) { $current_path = gplcart_path_normalize($file->getRealPath()); $initial_path = gplcart_path_normalize($this->scanner->getInitialPath(true)); return $current_path === $initial_path; }
[ "protected", "function", "isInitialPath", "(", "$", "file", ")", "{", "$", "current_path", "=", "gplcart_path_normalize", "(", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "$", "initial_path", "=", "gplcart_path_normalize", "(", "$", "this", "->", "scanner", "->", "getInitialPath", "(", "true", ")", ")", ";", "return", "$", "current_path", "===", "$", "initial_path", ";", "}" ]
Whether the current file is the initial file manager path @param \SplFileInfo $file @return bool
[ "Whether", "the", "current", "file", "is", "the", "initial", "file", "manager", "path" ]
45424e93eafea75d31af6410ac9cf110f08e500a
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L184-L190
train
heliopsis/ezforms-bundle
Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php
MultiplexerHandler.setLocation
public function setLocation( Location $location ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof LocationAwareHandlerInterface ) { $handler->setLocation( $location ); } } }
php
public function setLocation( Location $location ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof LocationAwareHandlerInterface ) { $handler->setLocation( $location ); } } }
[ "public", "function", "setLocation", "(", "Location", "$", "location", ")", "{", "foreach", "(", "$", "this", "->", "handlers", "as", "$", "handler", ")", "{", "if", "(", "$", "handler", "instanceof", "LocationAwareHandlerInterface", ")", "{", "$", "handler", "->", "setLocation", "(", "$", "location", ")", ";", "}", "}", "}" ]
Passes location to location aware handlers @param \eZ\Publish\API\Repository\Values\Content\Location $location
[ "Passes", "location", "to", "location", "aware", "handlers" ]
ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4
https://github.com/heliopsis/ezforms-bundle/blob/ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4/Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php#L62-L71
train
heliopsis/ezforms-bundle
Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php
MultiplexerHandler.setContent
public function setContent( Content $content ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof ContentAwareHandlerInterface ) { $handler->setContent( $content ); } } }
php
public function setContent( Content $content ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof ContentAwareHandlerInterface ) { $handler->setContent( $content ); } } }
[ "public", "function", "setContent", "(", "Content", "$", "content", ")", "{", "foreach", "(", "$", "this", "->", "handlers", "as", "$", "handler", ")", "{", "if", "(", "$", "handler", "instanceof", "ContentAwareHandlerInterface", ")", "{", "$", "handler", "->", "setContent", "(", "$", "content", ")", ";", "}", "}", "}" ]
Passes content to content aware handlers @param \eZ\Publish\API\Repository\Values\Content\Content $content
[ "Passes", "content", "to", "content", "aware", "handlers" ]
ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4
https://github.com/heliopsis/ezforms-bundle/blob/ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4/Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php#L77-L86
train
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.httpAction
public function httpAction() { $status = self::STATUS_SUCCESS; $responses = array(); $exception = null; $data = null; $debug = $this->getRouteParam('debug', false); try { $service = $this->fetchService(); $operation = $service ? $this->fetchOperation() : false; if(!$service){ throw new ServiceNotFoundException("Route doesn't contain service information"); } elseif (!$operation) { throw new OperationNotFoundException("Route doesn't contain operation information"); } try { $params = $this->fetchParams(); } catch(\Exception $e) { $status = self::STATUS_MALFORMED_REQUEST; $exception = $e; } if ($status === self::STATUS_SUCCESS) { if (isset($params[self::HEADER_FORCE_CONTENT_HTML])) { if ($params[self::HEADER_FORCE_CONTENT_HTML]) { $this->getRequest()->getHeaders()->addHeaders([ self::HEADER_FORCE_CONTENT_HTML => true ]); } unset($params[self::HEADER_FORCE_CONTENT_HTML]); } $data = $this->exec( $service, $operation, $params, Command::CONTEXT_HTTP); } } catch (PermissionDeniedException $exception) { $status = self::STATUS_PERMISSION_DENIED; } catch (NotFoundException $exception) { $status = self::STATUS_NOT_FOUND; } catch (ServiceException $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } catch (\Exception $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } // Log error if ($exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); if ($debug) { throw $exception; } } return $this->prepareHttpResponse( $data, $status, $exception); }
php
public function httpAction() { $status = self::STATUS_SUCCESS; $responses = array(); $exception = null; $data = null; $debug = $this->getRouteParam('debug', false); try { $service = $this->fetchService(); $operation = $service ? $this->fetchOperation() : false; if(!$service){ throw new ServiceNotFoundException("Route doesn't contain service information"); } elseif (!$operation) { throw new OperationNotFoundException("Route doesn't contain operation information"); } try { $params = $this->fetchParams(); } catch(\Exception $e) { $status = self::STATUS_MALFORMED_REQUEST; $exception = $e; } if ($status === self::STATUS_SUCCESS) { if (isset($params[self::HEADER_FORCE_CONTENT_HTML])) { if ($params[self::HEADER_FORCE_CONTENT_HTML]) { $this->getRequest()->getHeaders()->addHeaders([ self::HEADER_FORCE_CONTENT_HTML => true ]); } unset($params[self::HEADER_FORCE_CONTENT_HTML]); } $data = $this->exec( $service, $operation, $params, Command::CONTEXT_HTTP); } } catch (PermissionDeniedException $exception) { $status = self::STATUS_PERMISSION_DENIED; } catch (NotFoundException $exception) { $status = self::STATUS_NOT_FOUND; } catch (ServiceException $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } catch (\Exception $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } // Log error if ($exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); if ($debug) { throw $exception; } } return $this->prepareHttpResponse( $data, $status, $exception); }
[ "public", "function", "httpAction", "(", ")", "{", "$", "status", "=", "self", "::", "STATUS_SUCCESS", ";", "$", "responses", "=", "array", "(", ")", ";", "$", "exception", "=", "null", ";", "$", "data", "=", "null", ";", "$", "debug", "=", "$", "this", "->", "getRouteParam", "(", "'debug'", ",", "false", ")", ";", "try", "{", "$", "service", "=", "$", "this", "->", "fetchService", "(", ")", ";", "$", "operation", "=", "$", "service", "?", "$", "this", "->", "fetchOperation", "(", ")", ":", "false", ";", "if", "(", "!", "$", "service", ")", "{", "throw", "new", "ServiceNotFoundException", "(", "\"Route doesn't contain service information\"", ")", ";", "}", "elseif", "(", "!", "$", "operation", ")", "{", "throw", "new", "OperationNotFoundException", "(", "\"Route doesn't contain operation information\"", ")", ";", "}", "try", "{", "$", "params", "=", "$", "this", "->", "fetchParams", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "status", "=", "self", "::", "STATUS_MALFORMED_REQUEST", ";", "$", "exception", "=", "$", "e", ";", "}", "if", "(", "$", "status", "===", "self", "::", "STATUS_SUCCESS", ")", "{", "if", "(", "isset", "(", "$", "params", "[", "self", "::", "HEADER_FORCE_CONTENT_HTML", "]", ")", ")", "{", "if", "(", "$", "params", "[", "self", "::", "HEADER_FORCE_CONTENT_HTML", "]", ")", "{", "$", "this", "->", "getRequest", "(", ")", "->", "getHeaders", "(", ")", "->", "addHeaders", "(", "[", "self", "::", "HEADER_FORCE_CONTENT_HTML", "=>", "true", "]", ")", ";", "}", "unset", "(", "$", "params", "[", "self", "::", "HEADER_FORCE_CONTENT_HTML", "]", ")", ";", "}", "$", "data", "=", "$", "this", "->", "exec", "(", "$", "service", ",", "$", "operation", ",", "$", "params", ",", "Command", "::", "CONTEXT_HTTP", ")", ";", "}", "}", "catch", "(", "PermissionDeniedException", "$", "exception", ")", "{", "$", "status", "=", "self", "::", "STATUS_PERMISSION_DENIED", ";", "}", "catch", "(", "NotFoundException", "$", "exception", ")", "{", "$", "status", "=", "self", "::", "STATUS_NOT_FOUND", ";", "}", "catch", "(", "ServiceException", "$", "exception", ")", "{", "$", "status", "=", "self", "::", "STATUS_UNKNOWN_EXCEPTION", ";", "}", "catch", "(", "\\", "Exception", "$", "exception", ")", "{", "$", "status", "=", "self", "::", "STATUS_UNKNOWN_EXCEPTION", ";", "}", "// Log error", "if", "(", "$", "exception", ")", "{", "error_log", "(", "$", "exception", "->", "getMessage", "(", ")", ".", "' ('", ".", "$", "exception", "->", "getFile", "(", ")", ".", "':'", ".", "$", "exception", "->", "getLine", "(", ")", ".", "')'", ")", ";", "if", "(", "$", "debug", ")", "{", "throw", "$", "exception", ";", "}", "}", "return", "$", "this", "->", "prepareHttpResponse", "(", "$", "data", ",", "$", "status", ",", "$", "exception", ")", ";", "}" ]
Performs service operation matched by HTTP router @throws \Exception @return Response
[ "Performs", "service", "operation", "matched", "by", "HTTP", "router" ]
c96bed0f6bd21551822334fe6cfe913a7436dd17
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L184-L250
train
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.consoleAction
public function consoleAction() { $request = $this->getRequest(); $service = $this->fetchService(); $operation = $this->fetchOperation(); $query = $this->fetchConsoleQuery(); if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('You can only use this action from a console!'); } // Check flags $verbose = $request->getParam('verbose') || $request->getParam('v'); $silent = $request->getParam('silent') || $request->getParam('s'); $params = Json::decode( $query, Json::TYPE_ARRAY ); try { $data = $this->exec($service, $operation, $params, Command::CONTEXT_CLI); return $this->prepareConsoleResponse($data, null, $verbose, $silent); } catch (\Exception $exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); return $this->prepareConsoleResponse(null, $exception, $verbose, $silent); } }
php
public function consoleAction() { $request = $this->getRequest(); $service = $this->fetchService(); $operation = $this->fetchOperation(); $query = $this->fetchConsoleQuery(); if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('You can only use this action from a console!'); } // Check flags $verbose = $request->getParam('verbose') || $request->getParam('v'); $silent = $request->getParam('silent') || $request->getParam('s'); $params = Json::decode( $query, Json::TYPE_ARRAY ); try { $data = $this->exec($service, $operation, $params, Command::CONTEXT_CLI); return $this->prepareConsoleResponse($data, null, $verbose, $silent); } catch (\Exception $exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); return $this->prepareConsoleResponse(null, $exception, $verbose, $silent); } }
[ "public", "function", "consoleAction", "(", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "service", "=", "$", "this", "->", "fetchService", "(", ")", ";", "$", "operation", "=", "$", "this", "->", "fetchOperation", "(", ")", ";", "$", "query", "=", "$", "this", "->", "fetchConsoleQuery", "(", ")", ";", "if", "(", "!", "$", "request", "instanceof", "ConsoleRequest", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'You can only use this action from a console!'", ")", ";", "}", "// Check flags", "$", "verbose", "=", "$", "request", "->", "getParam", "(", "'verbose'", ")", "||", "$", "request", "->", "getParam", "(", "'v'", ")", ";", "$", "silent", "=", "$", "request", "->", "getParam", "(", "'silent'", ")", "||", "$", "request", "->", "getParam", "(", "'s'", ")", ";", "$", "params", "=", "Json", "::", "decode", "(", "$", "query", ",", "Json", "::", "TYPE_ARRAY", ")", ";", "try", "{", "$", "data", "=", "$", "this", "->", "exec", "(", "$", "service", ",", "$", "operation", ",", "$", "params", ",", "Command", "::", "CONTEXT_CLI", ")", ";", "return", "$", "this", "->", "prepareConsoleResponse", "(", "$", "data", ",", "null", ",", "$", "verbose", ",", "$", "silent", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "exception", ")", "{", "error_log", "(", "$", "exception", "->", "getMessage", "(", ")", ".", "' ('", ".", "$", "exception", "->", "getFile", "(", ")", ".", "':'", ".", "$", "exception", "->", "getLine", "(", ")", ".", "')'", ")", ";", "return", "$", "this", "->", "prepareConsoleResponse", "(", "null", ",", "$", "exception", ",", "$", "verbose", ",", "$", "silent", ")", ";", "}", "}" ]
Performs service operation routed by console router
[ "Performs", "service", "operation", "routed", "by", "console", "router" ]
c96bed0f6bd21551822334fe6cfe913a7436dd17
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L255-L283
train
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.prepareHttpResponse
protected function prepareHttpResponse($data, $status, $exception = null) { $error = $this->getRequest()->getHeader( self::HEADER_ERRORS, self::HEADER_ERRORS_DEFAULT); $forceHtmlContentType = $this->getRequest()->getHeader( self::HEADER_FORCE_CONTENT_HTML, false); if ($error instanceof HeaderInterface) { $error = $error->getFieldValue(); } $response = $this->getResponse(); $headers = array( 'Cache-Control' => 'no-cache, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => '2000-01-01 00:00:00', 'Content-Type' => 'application/json', ); if ($forceHtmlContentType) { $headers['Content-Type'] = 'text/html'; } $response->getHeaders()->addHeaders($headers); // update response status code $response->setStatusCode( $status ); // update reason phrase if($exception){ if ($exception instanceof ServiceException) { $message = $exception->getMessage(); } else { $message = 'Unknown exception'; } $response->setReasonPhrase( $message ); } if ($data instanceof \Zend\Http\Response) { // Attach custom stream response sender listener // to send the stream to output buffer in chunks if ($data instanceof Stream) { $sendReponseListener = $this->getServiceLocator()->get('SendResponseListener'); $sendReponseListener->getEventManager()->attach( SendResponseEvent::EVENT_SEND_RESPONSE, new StreamResponseSender(), 10000); } return $data; } else { $responseModel = array( 'd' => $data ); // Append exception data if ($exception) { if ($error == self::HEADER_ERRORS_VERBOSE && $exception instanceof ServiceException) { $responseModel['e'] = array( 'm' => $exception->getRawMessage(), 'c' => $exception->getCode(), 'a' => $exception->getVars() ); } else { $responseModel['e'] = array( 'm' => $response->getReasonPhrase(), 'c' => $exception->getCode(), ); } } try { $response->setContent(JsonEncoder::encode($responseModel, true)); } catch (Exception $e) { if ($e instanceof RecursionException) { $message = self::CYCLIC_DATA_ERROR; } else { $message = $e->getMessage(); } $response->setReasonPhrase( $message ); $response->setStatusCode( self::STATUS_UNKNOWN_EXCEPTION ); $response->setContent(JsonEncoder::encode([ 'd' => null, 'e' => [ 'm' => $message, 'c' => $e->getCode() ] ], true)); } return $response; } }
php
protected function prepareHttpResponse($data, $status, $exception = null) { $error = $this->getRequest()->getHeader( self::HEADER_ERRORS, self::HEADER_ERRORS_DEFAULT); $forceHtmlContentType = $this->getRequest()->getHeader( self::HEADER_FORCE_CONTENT_HTML, false); if ($error instanceof HeaderInterface) { $error = $error->getFieldValue(); } $response = $this->getResponse(); $headers = array( 'Cache-Control' => 'no-cache, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => '2000-01-01 00:00:00', 'Content-Type' => 'application/json', ); if ($forceHtmlContentType) { $headers['Content-Type'] = 'text/html'; } $response->getHeaders()->addHeaders($headers); // update response status code $response->setStatusCode( $status ); // update reason phrase if($exception){ if ($exception instanceof ServiceException) { $message = $exception->getMessage(); } else { $message = 'Unknown exception'; } $response->setReasonPhrase( $message ); } if ($data instanceof \Zend\Http\Response) { // Attach custom stream response sender listener // to send the stream to output buffer in chunks if ($data instanceof Stream) { $sendReponseListener = $this->getServiceLocator()->get('SendResponseListener'); $sendReponseListener->getEventManager()->attach( SendResponseEvent::EVENT_SEND_RESPONSE, new StreamResponseSender(), 10000); } return $data; } else { $responseModel = array( 'd' => $data ); // Append exception data if ($exception) { if ($error == self::HEADER_ERRORS_VERBOSE && $exception instanceof ServiceException) { $responseModel['e'] = array( 'm' => $exception->getRawMessage(), 'c' => $exception->getCode(), 'a' => $exception->getVars() ); } else { $responseModel['e'] = array( 'm' => $response->getReasonPhrase(), 'c' => $exception->getCode(), ); } } try { $response->setContent(JsonEncoder::encode($responseModel, true)); } catch (Exception $e) { if ($e instanceof RecursionException) { $message = self::CYCLIC_DATA_ERROR; } else { $message = $e->getMessage(); } $response->setReasonPhrase( $message ); $response->setStatusCode( self::STATUS_UNKNOWN_EXCEPTION ); $response->setContent(JsonEncoder::encode([ 'd' => null, 'e' => [ 'm' => $message, 'c' => $e->getCode() ] ], true)); } return $response; } }
[ "protected", "function", "prepareHttpResponse", "(", "$", "data", ",", "$", "status", ",", "$", "exception", "=", "null", ")", "{", "$", "error", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getHeader", "(", "self", "::", "HEADER_ERRORS", ",", "self", "::", "HEADER_ERRORS_DEFAULT", ")", ";", "$", "forceHtmlContentType", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getHeader", "(", "self", "::", "HEADER_FORCE_CONTENT_HTML", ",", "false", ")", ";", "if", "(", "$", "error", "instanceof", "HeaderInterface", ")", "{", "$", "error", "=", "$", "error", "->", "getFieldValue", "(", ")", ";", "}", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "$", "headers", "=", "array", "(", "'Cache-Control'", "=>", "'no-cache, must-revalidate'", ",", "'Pragma'", "=>", "'no-cache'", ",", "'Expires'", "=>", "'2000-01-01 00:00:00'", ",", "'Content-Type'", "=>", "'application/json'", ",", ")", ";", "if", "(", "$", "forceHtmlContentType", ")", "{", "$", "headers", "[", "'Content-Type'", "]", "=", "'text/html'", ";", "}", "$", "response", "->", "getHeaders", "(", ")", "->", "addHeaders", "(", "$", "headers", ")", ";", "// update response status code", "$", "response", "->", "setStatusCode", "(", "$", "status", ")", ";", "// update reason phrase", "if", "(", "$", "exception", ")", "{", "if", "(", "$", "exception", "instanceof", "ServiceException", ")", "{", "$", "message", "=", "$", "exception", "->", "getMessage", "(", ")", ";", "}", "else", "{", "$", "message", "=", "'Unknown exception'", ";", "}", "$", "response", "->", "setReasonPhrase", "(", "$", "message", ")", ";", "}", "if", "(", "$", "data", "instanceof", "\\", "Zend", "\\", "Http", "\\", "Response", ")", "{", "// Attach custom stream response sender listener", "// to send the stream to output buffer in chunks", "if", "(", "$", "data", "instanceof", "Stream", ")", "{", "$", "sendReponseListener", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "'SendResponseListener'", ")", ";", "$", "sendReponseListener", "->", "getEventManager", "(", ")", "->", "attach", "(", "SendResponseEvent", "::", "EVENT_SEND_RESPONSE", ",", "new", "StreamResponseSender", "(", ")", ",", "10000", ")", ";", "}", "return", "$", "data", ";", "}", "else", "{", "$", "responseModel", "=", "array", "(", "'d'", "=>", "$", "data", ")", ";", "// Append exception data", "if", "(", "$", "exception", ")", "{", "if", "(", "$", "error", "==", "self", "::", "HEADER_ERRORS_VERBOSE", "&&", "$", "exception", "instanceof", "ServiceException", ")", "{", "$", "responseModel", "[", "'e'", "]", "=", "array", "(", "'m'", "=>", "$", "exception", "->", "getRawMessage", "(", ")", ",", "'c'", "=>", "$", "exception", "->", "getCode", "(", ")", ",", "'a'", "=>", "$", "exception", "->", "getVars", "(", ")", ")", ";", "}", "else", "{", "$", "responseModel", "[", "'e'", "]", "=", "array", "(", "'m'", "=>", "$", "response", "->", "getReasonPhrase", "(", ")", ",", "'c'", "=>", "$", "exception", "->", "getCode", "(", ")", ",", ")", ";", "}", "}", "try", "{", "$", "response", "->", "setContent", "(", "JsonEncoder", "::", "encode", "(", "$", "responseModel", ",", "true", ")", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "if", "(", "$", "e", "instanceof", "RecursionException", ")", "{", "$", "message", "=", "self", "::", "CYCLIC_DATA_ERROR", ";", "}", "else", "{", "$", "message", "=", "$", "e", "->", "getMessage", "(", ")", ";", "}", "$", "response", "->", "setReasonPhrase", "(", "$", "message", ")", ";", "$", "response", "->", "setStatusCode", "(", "self", "::", "STATUS_UNKNOWN_EXCEPTION", ")", ";", "$", "response", "->", "setContent", "(", "JsonEncoder", "::", "encode", "(", "[", "'d'", "=>", "null", ",", "'e'", "=>", "[", "'m'", "=>", "$", "message", ",", "'c'", "=>", "$", "e", "->", "getCode", "(", ")", "]", "]", ",", "true", ")", ")", ";", "}", "return", "$", "response", ";", "}", "}" ]
Prepares HTTP response @param mixed $data @param int $status @param \Exception|null $exception @return Response
[ "Prepares", "HTTP", "response" ]
c96bed0f6bd21551822334fe6cfe913a7436dd17
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L312-L427
train
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.prepareConsoleResponse
protected function prepareConsoleResponse($data, \Exception $exception = null, $verbose = false, $silent = false) { $response = new ConsoleResponse(); try { if (is_array($data) || is_object($data)) { $json = JsonEncoder::encode($data, true); $data = Json::prettyPrint($json) . "\n"; } else if (is_scalar($data)) { $data = (string)$data."\n"; } } catch (Exception $e) { $exception = $e; $data = null; } if ($exception) { if ($verbose) { $msg = $exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine() . ')'; } else { $msg = $exception->getMessage(); } if (!$silent) { $response->setContent("Error: " . $msg . "\n"); } $response->setErrorLevel($exception->getCode()); } if (!$silent) { $response->setContent($data); } return $response; }
php
protected function prepareConsoleResponse($data, \Exception $exception = null, $verbose = false, $silent = false) { $response = new ConsoleResponse(); try { if (is_array($data) || is_object($data)) { $json = JsonEncoder::encode($data, true); $data = Json::prettyPrint($json) . "\n"; } else if (is_scalar($data)) { $data = (string)$data."\n"; } } catch (Exception $e) { $exception = $e; $data = null; } if ($exception) { if ($verbose) { $msg = $exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine() . ')'; } else { $msg = $exception->getMessage(); } if (!$silent) { $response->setContent("Error: " . $msg . "\n"); } $response->setErrorLevel($exception->getCode()); } if (!$silent) { $response->setContent($data); } return $response; }
[ "protected", "function", "prepareConsoleResponse", "(", "$", "data", ",", "\\", "Exception", "$", "exception", "=", "null", ",", "$", "verbose", "=", "false", ",", "$", "silent", "=", "false", ")", "{", "$", "response", "=", "new", "ConsoleResponse", "(", ")", ";", "try", "{", "if", "(", "is_array", "(", "$", "data", ")", "||", "is_object", "(", "$", "data", ")", ")", "{", "$", "json", "=", "JsonEncoder", "::", "encode", "(", "$", "data", ",", "true", ")", ";", "$", "data", "=", "Json", "::", "prettyPrint", "(", "$", "json", ")", ".", "\"\\n\"", ";", "}", "else", "if", "(", "is_scalar", "(", "$", "data", ")", ")", "{", "$", "data", "=", "(", "string", ")", "$", "data", ".", "\"\\n\"", ";", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "exception", "=", "$", "e", ";", "$", "data", "=", "null", ";", "}", "if", "(", "$", "exception", ")", "{", "if", "(", "$", "verbose", ")", "{", "$", "msg", "=", "$", "exception", "->", "getMessage", "(", ")", ".", "' ('", ".", "$", "exception", "->", "getFile", "(", ")", ".", "':'", ".", "$", "exception", "->", "getLine", "(", ")", ".", "')'", ";", "}", "else", "{", "$", "msg", "=", "$", "exception", "->", "getMessage", "(", ")", ";", "}", "if", "(", "!", "$", "silent", ")", "{", "$", "response", "->", "setContent", "(", "\"Error: \"", ".", "$", "msg", ".", "\"\\n\"", ")", ";", "}", "$", "response", "->", "setErrorLevel", "(", "$", "exception", "->", "getCode", "(", ")", ")", ";", "}", "if", "(", "!", "$", "silent", ")", "{", "$", "response", "->", "setContent", "(", "$", "data", ")", ";", "}", "return", "$", "response", ";", "}" ]
Prepares console response @param mixed $data @param \Exception|null $exception @param boolean $verbose @param boolean $silent @return ConsoleResponse
[ "Prepares", "console", "response" ]
c96bed0f6bd21551822334fe6cfe913a7436dd17
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L438-L474
train
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.fetchService
protected function fetchService() { $service = $this->getRouteParam('service'); $service = $this->parseCanonicalName($service, true); if (preg_match($this->servicePattern, $service)) { return $service; } else { return false; } }
php
protected function fetchService() { $service = $this->getRouteParam('service'); $service = $this->parseCanonicalName($service, true); if (preg_match($this->servicePattern, $service)) { return $service; } else { return false; } }
[ "protected", "function", "fetchService", "(", ")", "{", "$", "service", "=", "$", "this", "->", "getRouteParam", "(", "'service'", ")", ";", "$", "service", "=", "$", "this", "->", "parseCanonicalName", "(", "$", "service", ",", "true", ")", ";", "if", "(", "preg_match", "(", "$", "this", "->", "servicePattern", ",", "$", "service", ")", ")", "{", "return", "$", "service", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Parse service name from request @return string|boolean
[ "Parse", "service", "name", "from", "request" ]
c96bed0f6bd21551822334fe6cfe913a7436dd17
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L481-L491
train