repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
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); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2463-L2488
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; }
Check to see whether the object matching the parameters exists @param array $params Parameter array @param \PDO $db Database connection to use @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2498-L2512
andyburton/Sonic-Framework
src/Model.php
Model._getValues
public static function _getValues ($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 (); } // Return value return $db->getValues ($params); }
php
public static function _getValues ($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 (); } // Return value return $db->getValues ($params); }
Return all rows @param array $params Parameter array @param \PDO $db Database connection to use, default to slave resource @return mixed
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2599-L2627
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); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2638-L2663
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); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2673-L2677
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; }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2687-L2739
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); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2750-L2783
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); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2793-L2826
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; }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2837-L2884
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); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2896-L2924
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; }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2935-L3006
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; }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3020-L3091
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; }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3140-L3163
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; }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3177-L3246
andyburton/Sonic-Framework
src/Model.php
Model._getChildrenIndex
public static function _getChildrenIndex ($arr) { $return = array (); foreach ($arr as $child) { $return[] = $child->get ('id'); $return = array_merge ($return, self::_getChildrenIndex ($child->children)); } return $return; }
php
public static function _getChildrenIndex ($arr) { $return = array (); foreach ($arr as $child) { $return[] = $child->get ('id'); $return = array_merge ($return, self::_getChildrenIndex ($child->children)); } return $return; }
Return an array of child ids from an array of children returned from self::_getChildren @param array $arr Array of children @return array
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3255-L3268
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); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3278-L3343
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 ); }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3356-L3425
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); } }
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
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3435-L3451
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; }
Return random database resource object @param string $group Group name @return boolean|\Sonic\Model\PDO
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3460-L3518
andyburton/Sonic-Framework
src/Model.php
Model.&
public static function &_getDbMaster () { // Get the default master $obj =& self::_getResource ('db-master'); // Failing that try to get a random master if (!$obj) { $obj =& self::_getRandomDbResource ('db-master'); // Default to database resource if no valid master if (!$obj) { $obj =& self::_getResource ('db'); } } // Return database connection return $obj; }
php
public static function &_getDbMaster () { // Get the default master $obj =& self::_getResource ('db-master'); // Failing that try to get a random master if (!$obj) { $obj =& self::_getRandomDbResource ('db-master'); // Default to database resource if no valid master if (!$obj) { $obj =& self::_getResource ('db'); } } // Return database connection return $obj; }
Return database master @return \Sonic\Resource\Db
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3537-L3564
andyburton/Sonic-Framework
src/Model.php
Model.&
public static function &_getDbSlave () { // Get the default slave $obj =& self::_getResource ('db-slave'); // Failing that try to get a random slave if (!$obj) { $obj =& self::_getRandomDbResource ('db-slave'); // Default to database resource if no valid slave if (!$obj) { $obj =& self::_getResource ('db'); } } // Return database connection return $obj; }
php
public static function &_getDbSlave () { // Get the default slave $obj =& self::_getResource ('db-slave'); // Failing that try to get a random slave if (!$obj) { $obj =& self::_getRandomDbResource ('db-slave'); // Default to database resource if no valid slave if (!$obj) { $obj =& self::_getResource ('db'); } } // Return database connection return $obj; }
Return database slave @return \Sonic\Resource\Db
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3572-L3599
andyburton/Sonic-Framework
src/Model.php
Model.pre
public static function pre ($var, $mode = 0, $return = FALSE, $pre = TRUE) { Resource\Parser::pre ($var, $mode, $return, $pre); }
php
public static function pre ($var, $mode = 0, $return = FALSE, $pre = TRUE) { Resource\Parser::pre ($var, $mode, $return, $pre); }
Print a variable - very useful for debugging @param integer $mode Which display mode to use 0 - print_r, default 1 - var_dump @param boolean $return Return string rather than output @param boolean $pre Whether to wrap output in pre tags @return void|string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3612-L3615
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; }
Whether to write to the changelog @param string $type Change type (create, update, delete) @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L3624-L3652
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) . '>'; }
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
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L52-L57
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>'; }
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
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L69-L74
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; }
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
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L84-L113
frankfoerster/cakephp-asset
src/View/Helper/AssetHelper.php
AssetHelper._getBaseAssetPath
protected function _getBaseAssetPath($plugin = false) { if ($plugin !== false) { return $this->_getPluginPath($plugin) . 'src' . DS . 'Assets' . DS; } return ROOT . DS . 'src' . DS . 'Assets' . DS; }
php
protected function _getBaseAssetPath($plugin = false) { if ($plugin !== false) { return $this->_getPluginPath($plugin) . 'src' . DS . 'Assets' . DS; } return ROOT . DS . 'src' . DS . 'Assets' . DS; }
Get the path to /src/Assets either of the app or the provided $plugin. @param bool|string $plugin The name of a plugin or false. @return string
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L121-L128
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; }
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
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L136-L143
frankfoerster/cakephp-asset
src/View/Helper/AssetHelper.php
AssetHelper._getPluginPath
protected function _getPluginPath($plugin) { if (!Plugin::loaded($plugin)) { throw new MissingPluginException('Plugin ' . $plugin . ' is not loaded.'); } $pluginPath = Plugin::path($plugin); return $pluginPath; }
php
protected function _getPluginPath($plugin) { if (!Plugin::loaded($plugin)) { throw new MissingPluginException('Plugin ' . $plugin . ' is not loaded.'); } $pluginPath = Plugin::path($plugin); return $pluginPath; }
Get the absolute path to the given $plugin. @param string $plugin The name of the plugin. @return string
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L151-L159
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); }
Render attribute key value pairs as html attributes. @param array $attributes Key value pairs of html attributes. @return string
https://github.com/frankfoerster/cakephp-asset/blob/07b3646006d9bbf4f2d6fceeb319373392752b63/src/View/Helper/AssetHelper.php#L182-L194
Phauthentic/password-hashers
src/FallbackPasswordHasher.php
FallbackPasswordHasher.check
public function check(string $password, string $hashedPassword): bool { /* @var $hasher \Phauthentic\PasswordHasher\PasswordHasherInterface */ foreach ($this->hashers as $hasher) { if ($hasher->check($password, $hashedPassword)) { return true; } } return false; }
php
public function check(string $password, string $hashedPassword): bool { /* @var $hasher \Phauthentic\PasswordHasher\PasswordHasherInterface */ foreach ($this->hashers as $hasher) { if ($hasher->check($password, $hashedPassword)) { return true; } } return false; }
Verifies that the provided password corresponds to its hashed version This will iterate over all configured hashers until one of them returns true. @param string $password Plain text password to hash. @param string $hashedPassword Existing hashed password. @return bool True if hashes match else false.
https://github.com/Phauthentic/password-hashers/blob/c0679d51c941d8808ae143a20e63daab2d4388ec/src/FallbackPasswordHasher.php#L81-L91
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); } }
Initializes and renders the widget
https://github.com/Wonail/yii2-widget-nestable/blob/b9e4ccaab15d616e0791cb49a7a96597f4dc3d60/Nestable.php#L107-L121
Wonail/yii2-widget-nestable
Nestable.php
Nestable.registerPluginAssets
private function registerPluginAssets() { $view = $this->getView(); NestableAsset::register($view); $pluginOptions = Json::encode($this->pluginOptions); $name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->name; $js = <<<JS $('.dd').nestable({$pluginOptions}).on('change', function () { var obj = $(this).parents('.nestable-box'), nestable = new Array(); obj.find('.nestable-lists').each(function (index, element) { if ($(element).data('group')) { nestable[index] = new Object(); nestable[index]['group'] = $(element).data('group'); nestable[index]['title'] = $(element).data('title'); nestable[index]['items'] = $(element).find('.dd').nestable('serialize'); } }); $("[name=\"{$name}\"]").val(JSON.stringify(nestable)); }); JS; if ($this->collapsed) { $js .= "\n$('.dd').nestable('collapseAll')"; } $view->registerJs($js); }
php
private function registerPluginAssets() { $view = $this->getView(); NestableAsset::register($view); $pluginOptions = Json::encode($this->pluginOptions); $name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->name; $js = <<<JS $('.dd').nestable({$pluginOptions}).on('change', function () { var obj = $(this).parents('.nestable-box'), nestable = new Array(); obj.find('.nestable-lists').each(function (index, element) { if ($(element).data('group')) { nestable[index] = new Object(); nestable[index]['group'] = $(element).data('group'); nestable[index]['title'] = $(element).data('title'); nestable[index]['items'] = $(element).find('.dd').nestable('serialize'); } }); $("[name=\"{$name}\"]").val(JSON.stringify(nestable)); }); JS; if ($this->collapsed) { $js .= "\n$('.dd').nestable('collapseAll')"; } $view->registerJs($js); }
Register Asset manager
https://github.com/Wonail/yii2-widget-nestable/blob/b9e4ccaab15d616e0791cb49a7a96597f4dc3d60/Nestable.php#L217-L244
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(); }
Swoole Http Server
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L38-L66
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(); }
Swoole Tcp Server
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L71-L121
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(); }
Swoole UDP Server
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L126-L177
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(); }
Swoole Websocket Server
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L182-L230
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(); }
Swoole Mqtt Server
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L235-L280
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 ); }
Swoole UDP Client Demo
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L323-L356
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(); }
Websocket Client Demo
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/SwooleController.php#L361-L373
loevgaard/dandomain-api
src/Endpoint/Customer.php
Customer.getCustomerByEmail
public function getCustomerByEmail(string $email) : array { Assert::that($email)->email(); return (array)$this->master->doRequest( 'GET', sprintf('/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/GetCustomerByEmail?email=%s', rawurlencode($email)) ); }
php
public function getCustomerByEmail(string $email) : array { Assert::that($email)->email(); return (array)$this->master->doRequest( 'GET', sprintf('/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/GetCustomerByEmail?email=%s', rawurlencode($email)) ); }
@see https://shoppartner.dandomain.dk/dokumentation/api-documentation/customer/#GetCustomerByEmail_GET @param string $email @return array
https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Endpoint/Customer.php#L31-L39
loevgaard/dandomain-api
src/Endpoint/Customer.php
Customer.updateCustomer
public function updateCustomer(int $customerId, $customer) : array { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (array)$this->master->doRequest( 'PUT', sprintf('/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/%d', $customerId), $customer ); }
php
public function updateCustomer(int $customerId, $customer) : array { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (array)$this->master->doRequest( 'PUT', sprintf('/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/%d', $customerId), $customer ); }
@see https://shoppartner.dandomain.dk/dokumentation/api-documentation/customer/#UpdateCustomer_PUT @param int $customerId @param array|\stdClass $customer @return array
https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Endpoint/Customer.php#L73-L82
loevgaard/dandomain-api
src/Endpoint/Customer.php
Customer.deleteCustomer
public function deleteCustomer(int $customerId) : bool { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (bool)$this->master->doRequest( 'DELETE', sprintf( '/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/%d', $customerId ) ); }
php
public function deleteCustomer(int $customerId) : bool { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (bool)$this->master->doRequest( 'DELETE', sprintf( '/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/%d', $customerId ) ); }
@see https://shoppartner.dandomain.dk/dokumentation/api-documentation/customer/#DeleteCustomer_DELETE @param int $customerId @return boolean
https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Endpoint/Customer.php#L90-L101
loevgaard/dandomain-api
src/Endpoint/Customer.php
Customer.updateCustomerDiscount
public function updateCustomerDiscount(int $customerId, $customerDiscount) : array { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (array)$this->master->doRequest( 'POST', sprintf('/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/UpdateCustomerDiscount/%d', $customerId), $customerDiscount ); }
php
public function updateCustomerDiscount(int $customerId, $customerDiscount) : array { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (array)$this->master->doRequest( 'POST', sprintf('/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/UpdateCustomerDiscount/%d', $customerId), $customerDiscount ); }
@see https://shoppartner.dandomain.dk/dokumentation/api-documentation/customer/#UpdateCustomerDiscountPOST @param int $customerId @param array|\stdClass $customerDiscount @return array
https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Endpoint/Customer.php#L123-L132
loevgaard/dandomain-api
src/Endpoint/Customer.php
Customer.getCustomerDiscount
public function getCustomerDiscount(int $customerId) : array { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (array)$this->master->doRequest( 'GET', sprintf( '/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/GetCustomerDiscount/%d', $customerId ) ); }
php
public function getCustomerDiscount(int $customerId) : array { Assert::that($customerId)->greaterThan(0, 'The $customerId has to be positive'); return (array)$this->master->doRequest( 'GET', sprintf( '/admin/WEBAPI/Endpoints/v1_0/CustomerService/{KEY}/GetCustomerDiscount/%d', $customerId ) ); }
@see https://shoppartner.dandomain.dk/dokumentation/api-documentation/customer/#GetCustomerDiscountGET @param int $customerId @return array
https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Endpoint/Customer.php#L140-L151
PopSugar/php-yesmail-api
src/Yesmail/YesmailMasterRequiredTargetAttribute.php
YesmailMasterRequiredTargetAttribute.is_valid
public function is_valid() { $ret = false; if(is_null($this->name) === false && is_null($this->nullable) === false) { $ret = true; } return $ret; }
php
public function is_valid() { $ret = false; if(is_null($this->name) === false && is_null($this->nullable) === false) { $ret = true; } return $ret; }
Validates the target attribute @return bool True if the target attribute is valid, false otherwise @access public
https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/YesmailMasterRequiredTargetAttribute.php#L62-L70
PopSugar/php-yesmail-api
src/Yesmail/YesmailMasterRequiredTargetAttribute.php
YesmailMasterRequiredTargetAttribute.jsonSerialize
public function jsonSerialize() { $ret = new \stdClass(); $ret->name = $this->name; if(count($this->values) > 0) { $values = array(); $values['values'] = $this->values; $ret->values = $values; } $ret->nullable = $this->nullable; return $ret; }
php
public function jsonSerialize() { $ret = new \stdClass(); $ret->name = $this->name; if(count($this->values) > 0) { $values = array(); $values['values'] = $this->values; $ret->values = $values; } $ret->nullable = $this->nullable; return $ret; }
Return a json_encode able version of the object @return object A version of the object that is ready for json_encode @access public
https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/YesmailMasterRequiredTargetAttribute.php#L78-L91
acacha/forge-publish
src/Console/Commands/SaveEnvVariable.php
SaveEnvVariable.handle
public function handle() { $this->checkIfCommandHaveToBeSkipped(); $this->before(); $value = $this->argument($this->argKey()) ? $this->argument($this->argKey()) : $this->value() ; if (!$value) { $envVar = $this->envVar(); $this->error("Value could not be null for env var: $envVar"); die(); } $this->addValueToEnv($this->envVar(), $value); $this->info('The Acacha Forge ' . $this->argKey() . ' has been added to file .env with key ' . $this->envVar()); $this->after(); }
php
public function handle() { $this->checkIfCommandHaveToBeSkipped(); $this->before(); $value = $this->argument($this->argKey()) ? $this->argument($this->argKey()) : $this->value() ; if (!$value) { $envVar = $this->envVar(); $this->error("Value could not be null for env var: $envVar"); die(); } $this->addValueToEnv($this->envVar(), $value); $this->info('The Acacha Forge ' . $this->argKey() . ' has been added to file .env with key ' . $this->envVar()); $this->after(); }
Execute the console command.
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/SaveEnvVariable.php#L52-L69
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/FetchAlias.php
FetchAlias.initBySetting
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); $this->model = $model; if (is_array($setting)) { if (!isset($setting['remote_class_type'])) { throw new \Stack\Exception\MissingSetting('"remote_class_type" missing for the OneToMany relation.'); } if (!isset($setting['fetch_method'])) { throw new \Stack\Exception\MissingSetting('"fetch_method" missing for the FetchAlias relation.'); } $this->remoteModelType = $setting['remote_class_type']; $this->fetchMethod = $setting['fetch_method']; } }
php
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); $this->model = $model; if (is_array($setting)) { if (!isset($setting['remote_class_type'])) { throw new \Stack\Exception\MissingSetting('"remote_class_type" missing for the OneToMany relation.'); } if (!isset($setting['fetch_method'])) { throw new \Stack\Exception\MissingSetting('"fetch_method" missing for the FetchAlias relation.'); } $this->remoteModelType = $setting['remote_class_type']; $this->fetchMethod = $setting['fetch_method']; } }
/* CONSTRUCTOR ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/FetchAlias.php#L23-L37
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/FetchAlias.php
FetchAlias.reload
public function reload() { $entity = $this->getRemoteEntity(); $fetchMethod = $this->fetchMethod; $this->remoteModels = $entity->$fetchMethod($this->model); $this->initialized = true; }
php
public function reload() { $entity = $this->getRemoteEntity(); $fetchMethod = $this->fetchMethod; $this->remoteModels = $entity->$fetchMethod($this->model); $this->initialized = true; }
/* PUBLIC USER METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/FetchAlias.php#L42-L48
alphacomm/alpharpc
src/AlphaRPC/Manager/Protocol/WorkerStatusResponse.php
WorkerStatusResponse.fromMessage
public static function fromMessage(Message $msg) { $workerStatus = array(); while ($msg->peek() !== null) { $id = $msg->shift(); $actionCount = (int) $msg->shift(); $actionList = array(); for ($i = 0; $i < $actionCount; $i++) { $actionList[] = $msg->shift(); } $workerStatus[$id] = array( 'id' => $id, 'actionList' => $actionList, 'current' => $msg->shift(), 'ready' => (bool) $msg->shift(), 'valid' => (bool) $msg->shift(), ); } return new self($workerStatus); }
php
public static function fromMessage(Message $msg) { $workerStatus = array(); while ($msg->peek() !== null) { $id = $msg->shift(); $actionCount = (int) $msg->shift(); $actionList = array(); for ($i = 0; $i < $actionCount; $i++) { $actionList[] = $msg->shift(); } $workerStatus[$id] = array( 'id' => $id, 'actionList' => $actionList, 'current' => $msg->shift(), 'ready' => (bool) $msg->shift(), 'valid' => (bool) $msg->shift(), ); } return new self($workerStatus); }
Creates an instance from the Message. @param Message $msg @return WorkerStatusResponse
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/Protocol/WorkerStatusResponse.php#L61-L82
alphacomm/alpharpc
src/AlphaRPC/Manager/Protocol/WorkerStatusResponse.php
WorkerStatusResponse.toMessage
public function toMessage() { $m = new Message(); /* @var $w Worker */ foreach ($this->workerStatus as $w) { $m->push($w['id']); $m->push(count($w['actionList'])); $m->append($w['actionList']); $m->push($w['current']); $m->push($w['ready']); $m->push($w['valid']); } return $m; }
php
public function toMessage() { $m = new Message(); /* @var $w Worker */ foreach ($this->workerStatus as $w) { $m->push($w['id']); $m->push(count($w['actionList'])); $m->append($w['actionList']); $m->push($w['current']); $m->push($w['ready']); $m->push($w['valid']); } return $m; }
Create a new Message from this instance. @return Message
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/Protocol/WorkerStatusResponse.php#L89-L104
hal-platform/hal-core
src/Repository/EncryptedPropertyRepository.php
EncryptedPropertyRepository.getPropertiesForEnvironment
public function getPropertiesForEnvironment(Application $application, ?Environment $environment): array { $environmentCriteria = Criteria::expr()->isNull('environment'); if ($environment) { $specificEnvironment = Criteria::expr()->eq('environment', $environment); $environmentCriteria = Criteria::expr()->orX($specificEnvironment, $environmentCriteria); } $criteria = (new Criteria) ->where(Criteria::expr()->eq('application', $application)) ->andWhere($environmentCriteria) // null must be first! ->orderBy(['environment' => 'ASC']); $properties = $this ->matching($criteria) ->toArray(); $config = []; // We do this so that "global/no-env" properties are loaded first, and can be overwritten by environment-specific config. foreach ($properties as $property) { $config[$property->name()] = $property; } return $config; }
php
public function getPropertiesForEnvironment(Application $application, ?Environment $environment): array { $environmentCriteria = Criteria::expr()->isNull('environment'); if ($environment) { $specificEnvironment = Criteria::expr()->eq('environment', $environment); $environmentCriteria = Criteria::expr()->orX($specificEnvironment, $environmentCriteria); } $criteria = (new Criteria) ->where(Criteria::expr()->eq('application', $application)) ->andWhere($environmentCriteria) // null must be first! ->orderBy(['environment' => 'ASC']); $properties = $this ->matching($criteria) ->toArray(); $config = []; // We do this so that "global/no-env" properties are loaded first, and can be overwritten by environment-specific config. foreach ($properties as $property) { $config[$property->name()] = $property; } return $config; }
@param Application $application @param Environment|null $environment @return array
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/EncryptedPropertyRepository.php#L23-L52
courtney-miles/schnoop-schema
src/MySQL/DataType/SetType.php
SetType.cast
public function cast($value) { if (!empty($value)) { foreach ($value as $k => $v) { $value[$k] = parent::cast($v); } } return $value; }
php
public function cast($value) { if (!empty($value)) { foreach ($value as $k => $v) { $value[$k] = parent::cast($v); } } return $value; }
{@inheritdoc}
https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/DataType/SetType.php#L18-L27
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; }
2017-07-02 @override @see \Df\Config\Source::map() @used-by \Df\Config\Source::toOptionArray() @return array(string => string)
https://github.com/wartw98/core/blob/e1f44f6b4798a7b988f6a1cae639ff3745c9cd2a/Config/Source/API.php#L56-L64
xelax90/xelax-admin
src/XelaxAdmin/Router/ListRoute.php
ListRoute.match
public function match(RequestInterface $request, $pathOffset = null, array $options = array()) { $match = $this->match_part($request, $pathOffset, $options); if(!empty($match)){ $privilegeParts = explode('/', $match['params']['xelax_admin_privilege']); if(!isset($match['params']['action']) && array_pop($privilegeParts) != 'subroute'){ $match['params']['action'] = ''; } return new RouteMatch($match['params'], $match['length']); } return null; }
php
public function match(RequestInterface $request, $pathOffset = null, array $options = array()) { $match = $this->match_part($request, $pathOffset, $options); if(!empty($match)){ $privilegeParts = explode('/', $match['params']['xelax_admin_privilege']); if(!isset($match['params']['action']) && array_pop($privilegeParts) != 'subroute'){ $match['params']['action'] = ''; } return new RouteMatch($match['params'], $match['length']); } return null; }
match(): defined by RouteInterface interface. @see \Zend\Mvc\Router\RouteInterface::match() @param Request $request @param string|null $pathOffset @param array $options @return RouteMatch|null @throws Exception\RuntimeException
https://github.com/xelax90/xelax-admin/blob/eb8133384b74e18f6641689f290c6ba956641b6d/src/XelaxAdmin/Router/ListRoute.php#L89-L99
xelax90/xelax-admin
src/XelaxAdmin/Router/ListRoute.php
ListRoute.assemble
public function assemble(array $params = array(), array $options = array()) { $this->assembledParams = array(); return $this->buildRoute(array_merge($params, $this->defaults)); }
php
public function assemble(array $params = array(), array $options = array()) { $this->assembledParams = array(); return $this->buildRoute(array_merge($params, $this->defaults)); }
assemble(): Defined by RouteInterface interface. @see \Zend\Mvc\Router\RouteInterface::assemble() @param array $params @param array $options @return mixed
https://github.com/xelax90/xelax-admin/blob/eb8133384b74e18f6641689f290c6ba956641b6d/src/XelaxAdmin/Router/ListRoute.php#L360-L363
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; }
Fetches and returns the associated ListControllerOptions for this route @return ListControllerOptions @throws Exception\RuntimeException
https://github.com/xelax90/xelax-admin/blob/eb8133384b74e18f6641689f290c6ba956641b6d/src/XelaxAdmin/Router/ListRoute.php#L424-L447
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); }
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
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Criteria/ExtractionTrait.php#L36-L51
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); }
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
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Criteria/ExtractionTrait.php#L66-L89
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectTabIndention.php
HasCorrectTabIndention.apply
public function apply($testable, array $config = array()) { $followerCount = 0; $lines = $testable->lines(); $tabMessage = 'Incorrect tab indention {:actual} should be {:predicted}.'; $spaceMessage = 'Incorrect space indention {:actual} should be >= {:predicted}.'; foreach ($lines as $lineIndex => $line) { if (!$this->_shouldIgnoreLine($lineIndex, $testable)) { $actual = $this->_getIndent($line); $predicted = $this->_getPredictedIndent($lineIndex, $testable); if ($predicted['tab'] !== null && $actual['tab'] !== $predicted['tab']) { $this->addViolation(array( 'message' => String::insert($tabMessage, array( 'predicted' => $predicted['tab'], 'actual' => $actual['tab'], )), 'line' => $lineIndex + 1, )); } if ($predicted['minSpace'] !== null && $actual['space'] < $predicted['minSpace']) { $this->addViolation(array( 'message' => String::insert($spaceMessage, array( 'predicted' => $predicted['minSpace'], 'actual' => $actual['space'], )), 'line' => $lineIndex + 1, )); } } } }
php
public function apply($testable, array $config = array()) { $followerCount = 0; $lines = $testable->lines(); $tabMessage = 'Incorrect tab indention {:actual} should be {:predicted}.'; $spaceMessage = 'Incorrect space indention {:actual} should be >= {:predicted}.'; foreach ($lines as $lineIndex => $line) { if (!$this->_shouldIgnoreLine($lineIndex, $testable)) { $actual = $this->_getIndent($line); $predicted = $this->_getPredictedIndent($lineIndex, $testable); if ($predicted['tab'] !== null && $actual['tab'] !== $predicted['tab']) { $this->addViolation(array( 'message' => String::insert($tabMessage, array( 'predicted' => $predicted['tab'], 'actual' => $actual['tab'], )), 'line' => $lineIndex + 1, )); } if ($predicted['minSpace'] !== null && $actual['space'] < $predicted['minSpace']) { $this->addViolation(array( 'message' => String::insert($spaceMessage, array( 'predicted' => $predicted['minSpace'], 'actual' => $actual['space'], )), 'line' => $lineIndex + 1, )); } } } }
Will iterate the lines looking for $patterns while keeping track of how many tabs the current line should have. @param Testable $testable The testable object @return void
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectTabIndention.php#L44-L73
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectTabIndention.php
HasCorrectTabIndention._getPredictedIndent
protected function _getPredictedIndent($lineIndex, $testable) { $result = array('minSpace' => null,'tab' => null); $tokens = $testable->tokens(); $lines = $testable->lines(); $lineCache = $testable->lineCache(); $line = trim($lines[$lineIndex]); $lineLen = strlen($line); $prevLine = $lineIndex > 0 ? trim($lines[$lineIndex - 1]) : false; $prevLen = strlen($prevLine); $currentTokens = $lineCache[$testable->findTokensByLine($lineIndex + 1)]; $firstToken = $tokens[reset($currentTokens)]; if ($firstToken['id'] === T_WHITESPACE) { $firstToken = $tokens[next($currentTokens)]; } if (!isset($firstToken['level'])) { return $result; } $parentId = $firstToken['parent']; $parent = isset($tokens[$parentId]) ? $tokens[$parentId] : null; $expectedTab = $firstToken['nestLevel']; if ($expectedTab === null || ($firstToken['line'] !== $lineIndex + 1)) { return $result; } $breaked = false; foreach (array('&&', '||', 'and', 'or', 'xor', 'AND', 'OR', 'XOR', '.') as $op) { $op = preg_quote($op); if (preg_match("/\s+$op$/", $prevLine)) { $breaked = true; } } $minExpectedSpace = 0; $inArray = ($parent !== null && ( $parent['id'] === T_ARRAY_OPEN || $parent['id'] === T_SHORT_ARRAY_OPEN )); $inBrace = ($parent !== null && ( $parent['content'] === '(' || $parent['content'] === '[' )); if ($breaked) { if ($inArray) { $minExpectedSpace = $this->_getSpaceAlignmentInArray($lineIndex, $testable); } if (!$inBrace) { $expectedTab += 1; } } if (preg_match('/^->/', $line) && !$inBrace) { $expectedTab += 1; } if ($inArray) { $grandParent = $parent['parent'] > -1 ? $tokens[$parent['parent']] : null; if ($grandParent !== null) { $grandParentLine = trim($lines[$grandParent['line'] - 1]); if (preg_match('/^->/', $grandParentLine)) { $expectedTab += 1; } } } return array( 'minSpace' => $minExpectedSpace, 'tab' => $expectedTab ); }
php
protected function _getPredictedIndent($lineIndex, $testable) { $result = array('minSpace' => null,'tab' => null); $tokens = $testable->tokens(); $lines = $testable->lines(); $lineCache = $testable->lineCache(); $line = trim($lines[$lineIndex]); $lineLen = strlen($line); $prevLine = $lineIndex > 0 ? trim($lines[$lineIndex - 1]) : false; $prevLen = strlen($prevLine); $currentTokens = $lineCache[$testable->findTokensByLine($lineIndex + 1)]; $firstToken = $tokens[reset($currentTokens)]; if ($firstToken['id'] === T_WHITESPACE) { $firstToken = $tokens[next($currentTokens)]; } if (!isset($firstToken['level'])) { return $result; } $parentId = $firstToken['parent']; $parent = isset($tokens[$parentId]) ? $tokens[$parentId] : null; $expectedTab = $firstToken['nestLevel']; if ($expectedTab === null || ($firstToken['line'] !== $lineIndex + 1)) { return $result; } $breaked = false; foreach (array('&&', '||', 'and', 'or', 'xor', 'AND', 'OR', 'XOR', '.') as $op) { $op = preg_quote($op); if (preg_match("/\s+$op$/", $prevLine)) { $breaked = true; } } $minExpectedSpace = 0; $inArray = ($parent !== null && ( $parent['id'] === T_ARRAY_OPEN || $parent['id'] === T_SHORT_ARRAY_OPEN )); $inBrace = ($parent !== null && ( $parent['content'] === '(' || $parent['content'] === '[' )); if ($breaked) { if ($inArray) { $minExpectedSpace = $this->_getSpaceAlignmentInArray($lineIndex, $testable); } if (!$inBrace) { $expectedTab += 1; } } if (preg_match('/^->/', $line) && !$inBrace) { $expectedTab += 1; } if ($inArray) { $grandParent = $parent['parent'] > -1 ? $tokens[$parent['parent']] : null; if ($grandParent !== null) { $grandParentLine = trim($lines[$grandParent['line'] - 1]); if (preg_match('/^->/', $grandParentLine)) { $expectedTab += 1; } } } return array( 'minSpace' => $minExpectedSpace, 'tab' => $expectedTab ); }
Will determine how many tabs a current line should have. This makes use of an instance variable to track relative movements in tabs, calling this method out of order will have unexpected results. @param int $lineIndex The index the current line is on @param array $testable The testable object @return int
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectTabIndention.php#L84-L158
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; }
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
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectTabIndention.php#L167-L194
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 ); }
Will determine how many tabs are at the beginning of a line. @param string $line The current line is on @return bool
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectTabIndention.php#L202-L217
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectTabIndention.php
HasCorrectTabIndention._shouldIgnoreLine
protected function _shouldIgnoreLine($lineIndex, $testable) { $lines = $testable->lines(); $line = $lines[$lineIndex]; $plain = trim($line); if (empty($plain)) { return true; } $length = strlen($plain); if ($length > 1 && ($plain[0] . $plain[1] === "//")) { return true; } elseif ($length > 2 && ($plain[0] . $plain[1] . $plain[2] === "/**")) { return true; } elseif ($plain[0] === "#" || $plain[0] === "*") { return true; } $stringTokens = array(T_ENCAPSED_AND_WHITESPACE, T_END_HEREDOC); $tokens = $testable->tokens(); $start = $testable->findTokenByLine($lineIndex + 1); return in_array($tokens[$start]['id'], $stringTokens, true); }
php
protected function _shouldIgnoreLine($lineIndex, $testable) { $lines = $testable->lines(); $line = $lines[$lineIndex]; $plain = trim($line); if (empty($plain)) { return true; } $length = strlen($plain); if ($length > 1 && ($plain[0] . $plain[1] === "//")) { return true; } elseif ($length > 2 && ($plain[0] . $plain[1] . $plain[2] === "/**")) { return true; } elseif ($plain[0] === "#" || $plain[0] === "*") { return true; } $stringTokens = array(T_ENCAPSED_AND_WHITESPACE, T_END_HEREDOC); $tokens = $testable->tokens(); $start = $testable->findTokenByLine($lineIndex + 1); return in_array($tokens[$start]['id'], $stringTokens, true); }
Will determine if the line is ignoreable. Currently the line is ignoreable if: * Empty Line * In docblocks * In heredocs @param int $lineIndex The index the current line is on @param array $testable The testable object @return bool
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectTabIndention.php#L230-L252
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; }
Configures the pool builder. @param string $prefix @param string $resourceName @param array $options @return PoolBuilder
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L97-L104
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.build
public function build() { $this->createEntityClassParameter(); $this->createConfigurationDefinition(); $this->createMetadataDefinition(); $this->createManagerDefinition(); $this->createRepositoryDefinition(); $this->createOperatorDefinition(); // TODO search repository service $this->createControllerDefinition(); $this->createFormDefinition(); $this->createTableDefinition(); $this->configureTranslations(); return $this; }
php
public function build() { $this->createEntityClassParameter(); $this->createConfigurationDefinition(); $this->createMetadataDefinition(); $this->createManagerDefinition(); $this->createRepositoryDefinition(); $this->createOperatorDefinition(); // TODO search repository service $this->createControllerDefinition(); $this->createFormDefinition(); $this->createTableDefinition(); $this->configureTranslations(); return $this; }
Builds the container. @return PoolBuilder
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L111-L132
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.getOptionsResolver
private function getOptionsResolver() { if (null === self::$optionsResolver) { $classExists = function ($class) { if (!class_exists($class)) { throw new InvalidOptionsException(sprintf('Class %s does not exists.', $class)); } return true; }; $classExistsAndImplements = function($class, $interface) use ($classExists) { $classExists($class); if (!in_array($interface, class_implements($class))) { throw new InvalidOptionsException(sprintf('Class %s must implement %s.', $class, $interface)); } return true; }; $validOperator = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::OPERATOR_INTERFACE); }; $validController = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::CONTROLLER_INTERFACE); }; $validForm = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::FORM_INTERFACE); }; $validTable = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::TABLE_INTERFACE); }; $validEvent = function ($class) use ($classExistsAndImplements) { if (null === $class) { return true; } return $classExistsAndImplements($class, self::EVENT_INTERFACE); }; self::$optionsResolver = new OptionsResolver(); /** @noinspection PhpUnusedParameterInspection */ self::$optionsResolver ->setDefaults([ 'entity' => null, 'repository' => null, 'operator' => self::DEFAULT_OPERATOR, 'controller' => self::DEFAULT_CONTROLLER, 'templates' => null, 'form' => null, 'table' => null, 'event' => null, 'parent' => null, 'translation' => null, ]) ->setAllowedTypes('entity', 'string') ->setAllowedTypes('repository', ['null', 'string']) ->setAllowedTypes('operator', 'string') ->setAllowedTypes('controller', 'string') ->setAllowedTypes('templates', ['null', 'string', 'array']) ->setAllowedTypes('form', 'string') ->setAllowedTypes('table', 'string') ->setAllowedTypes('event', ['null', 'string']) ->setAllowedTypes('parent', ['null', 'string']) ->setAllowedTypes('translation', ['null', 'array']) ->setAllowedValues('entity', $classExists) ->setAllowedValues('operator', $validOperator) ->setAllowedValues('controller', $validController) ->setAllowedValues('form', $validForm) ->setAllowedValues('table', $validTable) ->setAllowedValues('event', $validEvent) ->setNormalizer('repository', function($options, $value) use ($classExistsAndImplements) { $translatable = is_array($options['translation']); $interface = $translatable ? self::TRANSLATABLE_REPOSITORY_INTERFACE : self::REPOSITORY_INTERFACE; if (null === $value) { if ($translatable) { $value = self::TRANSLATABLE_DEFAULT_REPOSITORY; } else { $value = self::DEFAULT_REPOSITORY; } } $classExistsAndImplements($value, $interface); return $value; }) ->setNormalizer('translation', function ($options, $value) use ($classExistsAndImplements) { if (is_array($value)) { if (!array_key_exists('entity', $value)) { throw new InvalidOptionsException('translation.entity must be defined.'); } if (!array_key_exists('fields', $value)) { throw new InvalidOptionsException('translation.fields must be defined.'); } if (!is_array($value['fields']) || empty($value['fields'])) { throw new InvalidOptionsException('translation.fields can\'t be empty.'); } if (!array_key_exists('repository', $value)) { $value['repository'] = self::DEFAULT_REPOSITORY; } $classExistsAndImplements($value['repository'], self::REPOSITORY_INTERFACE); } return $value; }) // TODO templates normalization ? ; } return self::$optionsResolver; }
php
private function getOptionsResolver() { if (null === self::$optionsResolver) { $classExists = function ($class) { if (!class_exists($class)) { throw new InvalidOptionsException(sprintf('Class %s does not exists.', $class)); } return true; }; $classExistsAndImplements = function($class, $interface) use ($classExists) { $classExists($class); if (!in_array($interface, class_implements($class))) { throw new InvalidOptionsException(sprintf('Class %s must implement %s.', $class, $interface)); } return true; }; $validOperator = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::OPERATOR_INTERFACE); }; $validController = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::CONTROLLER_INTERFACE); }; $validForm = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::FORM_INTERFACE); }; $validTable = function ($class) use ($classExistsAndImplements) { return $classExistsAndImplements($class, self::TABLE_INTERFACE); }; $validEvent = function ($class) use ($classExistsAndImplements) { if (null === $class) { return true; } return $classExistsAndImplements($class, self::EVENT_INTERFACE); }; self::$optionsResolver = new OptionsResolver(); /** @noinspection PhpUnusedParameterInspection */ self::$optionsResolver ->setDefaults([ 'entity' => null, 'repository' => null, 'operator' => self::DEFAULT_OPERATOR, 'controller' => self::DEFAULT_CONTROLLER, 'templates' => null, 'form' => null, 'table' => null, 'event' => null, 'parent' => null, 'translation' => null, ]) ->setAllowedTypes('entity', 'string') ->setAllowedTypes('repository', ['null', 'string']) ->setAllowedTypes('operator', 'string') ->setAllowedTypes('controller', 'string') ->setAllowedTypes('templates', ['null', 'string', 'array']) ->setAllowedTypes('form', 'string') ->setAllowedTypes('table', 'string') ->setAllowedTypes('event', ['null', 'string']) ->setAllowedTypes('parent', ['null', 'string']) ->setAllowedTypes('translation', ['null', 'array']) ->setAllowedValues('entity', $classExists) ->setAllowedValues('operator', $validOperator) ->setAllowedValues('controller', $validController) ->setAllowedValues('form', $validForm) ->setAllowedValues('table', $validTable) ->setAllowedValues('event', $validEvent) ->setNormalizer('repository', function($options, $value) use ($classExistsAndImplements) { $translatable = is_array($options['translation']); $interface = $translatable ? self::TRANSLATABLE_REPOSITORY_INTERFACE : self::REPOSITORY_INTERFACE; if (null === $value) { if ($translatable) { $value = self::TRANSLATABLE_DEFAULT_REPOSITORY; } else { $value = self::DEFAULT_REPOSITORY; } } $classExistsAndImplements($value, $interface); return $value; }) ->setNormalizer('translation', function ($options, $value) use ($classExistsAndImplements) { if (is_array($value)) { if (!array_key_exists('entity', $value)) { throw new InvalidOptionsException('translation.entity must be defined.'); } if (!array_key_exists('fields', $value)) { throw new InvalidOptionsException('translation.fields must be defined.'); } if (!is_array($value['fields']) || empty($value['fields'])) { throw new InvalidOptionsException('translation.fields can\'t be empty.'); } if (!array_key_exists('repository', $value)) { $value['repository'] = self::DEFAULT_REPOSITORY; } $classExistsAndImplements($value['repository'], self::REPOSITORY_INTERFACE); } return $value; }) // TODO templates normalization ? ; } return self::$optionsResolver; }
Returns the options resolver. @return OptionsResolver
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L139-L243
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'] ); }
Creates the entity class parameter.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L248-L260
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); } }
Creates the Configuration service definition.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L265-L288
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; }
Builds the templates list. @param mixed $templatesConfig @return array
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L296-L314
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createMetadataDefinition
private function createMetadataDefinition() { $id = $this->getServiceId('metadata'); if (!$this->container->has($id)) { $definition = new Definition(self::CLASS_METADATA); $definition ->setFactory([new Reference($this->getManagerServiceId()), 'getClassMetadata']) ->setArguments([ $this->container->getParameter($this->getServiceId('class')) ])//->setPublic(false) ; $this->container->setDefinition($id, $definition); } }
php
private function createMetadataDefinition() { $id = $this->getServiceId('metadata'); if (!$this->container->has($id)) { $definition = new Definition(self::CLASS_METADATA); $definition ->setFactory([new Reference($this->getManagerServiceId()), 'getClassMetadata']) ->setArguments([ $this->container->getParameter($this->getServiceId('class')) ])//->setPublic(false) ; $this->container->setDefinition($id, $definition); } }
Creates the Table service definition.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L319-L332
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())); } }
Creates the manager definition.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L337-L343
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); } }
Creates the Repository service definition.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L348-L365
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); } }
Creates the operator service definition. @TODO Swap with ResourceManager when ready.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L372-L385
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); } }
Creates the Controller service definition.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L390-L401
ekyna/AdminBundle
DependencyInjection/PoolBuilder.php
PoolBuilder.createTableDefinition
private function createTableDefinition() { $id = $this->getServiceId('table_type'); if (!$this->container->has($id)) { $definition = new Definition($this->getServiceClass('table')); $definition ->setArguments([$this->options['entity']]) ->addTag('table.type', [ 'alias' => sprintf('%s_%s', $this->prefix, $this->resourceName)] ) ; $this->container->setDefinition($id, $definition); } }
php
private function createTableDefinition() { $id = $this->getServiceId('table_type'); if (!$this->container->has($id)) { $definition = new Definition($this->getServiceClass('table')); $definition ->setArguments([$this->options['entity']]) ->addTag('table.type', [ 'alias' => sprintf('%s_%s', $this->prefix, $this->resourceName)] ) ; $this->container->setDefinition($id, $definition); } }
Creates the Table service definition.
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L424-L437
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']); } }
Configure the translation
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L442-L468
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); }
Configures mapping inheritance. @param string $id @param string $entity @param string $repository
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L477-L490
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; }
Returns the service class for the given name. @param string $name @throws \RuntimeException @return string|null
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/DependencyInjection/PoolBuilder.php#L533-L545
smartboxgroup/camel-config-bundle
ProcessorDefinitions/StopDefinition.php
StopDefinition.buildProcessor
public function buildProcessor($configNode, $id) { $def = parent::buildProcessor($configNode, $id); foreach ($configNode as $nodeName => $nodeValue) { switch ($nodeName) { case self::DESCRIPTION: $def->addMethodCall('setDescription', [(string) $nodeValue]); break; default: throw new InvalidConfigurationException('Unsupported stop processor node: "'.$nodeName.'"'); break; } } return $def; }
php
public function buildProcessor($configNode, $id) { $def = parent::buildProcessor($configNode, $id); foreach ($configNode as $nodeName => $nodeValue) { switch ($nodeName) { case self::DESCRIPTION: $def->addMethodCall('setDescription', [(string) $nodeValue]); break; default: throw new InvalidConfigurationException('Unsupported stop processor node: "'.$nodeName.'"'); break; } } return $def; }
{@inheritdoc}
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/ProcessorDefinitions/StopDefinition.php#L17-L33
randomstate/laravel-auth
src/AuthManager.php
AuthManager.register
public function register($name, AuthStrategy $strategy) { if($this->getOrNull($name)) { throw new StrategyAlreadyRegisteredException; }; $this->strategies[$name] = $strategy; return $this; }
php
public function register($name, AuthStrategy $strategy) { if($this->getOrNull($name)) { throw new StrategyAlreadyRegisteredException; }; $this->strategies[$name] = $strategy; return $this; }
@param $name @param AuthStrategy $strategy @return $this @throws StrategyAlreadyRegisteredException
https://github.com/randomstate/laravel-auth/blob/8054c6acd08c6b8e6e5ac362c42d968612ab9dc5/src/AuthManager.php#L36-L45
randomstate/laravel-auth
src/AuthManager.php
AuthManager.login
public function login($strategy, Request $request) { $strategy = $this->get($strategy); $user = $strategy->convert($strategy->attempt($request)); return $user; }
php
public function login($strategy, Request $request) { $strategy = $this->get($strategy); $user = $strategy->convert($strategy->attempt($request)); return $user; }
@param $strategy @param Request $request @return mixed @throws UnknownStrategyException
https://github.com/randomstate/laravel-auth/blob/8054c6acd08c6b8e6e5ac362c42d968612ab9dc5/src/AuthManager.php#L63-L69
randomstate/laravel-auth
src/AuthManager.php
AuthManager.get
public function get($strategy = null) { if(!$strategy) { return $this->defaultStrategy; } $strategy = $this->getOrNull($strategy); if(!$strategy) { throw new UnknownStrategyException; } return $strategy; }
php
public function get($strategy = null) { if(!$strategy) { return $this->defaultStrategy; } $strategy = $this->getOrNull($strategy); if(!$strategy) { throw new UnknownStrategyException; } return $strategy; }
@param $strategy @return bool|AuthStrategy @throws UnknownStrategyException
https://github.com/randomstate/laravel-auth/blob/8054c6acd08c6b8e6e5ac362c42d968612ab9dc5/src/AuthManager.php#L77-L90
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; }
Retrieves the user's description. @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L32-L35
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; }
Retrieves the user's name. @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L42-L45
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; }
Retrieves the user's location. @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L53-L56
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; }
Retrieves the user's twitter username. @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L63-L66
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; }
Retrievs the user's website. @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L73-L76
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; }
Retrieves the user's services. @return array
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L83-L86
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; }
Retrieves the user's qwerly username. @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L93-L96
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; }
Retrieves the user's facebook id. @return int
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Qwerly/User.php#L103-L106
internetofvoice/libvoice
src/Alexa/Request/Request/Intent/Intent.php
Intent.getSlotsAsArray
public function getSlotsAsArray() { $slots = []; if(!is_array($this->getSlots())) { return $slots; } foreach($this->getSlots() as $key => $slot) { $slots[$key] = $slot->getValue(); } return $slots; }
php
public function getSlotsAsArray() { $slots = []; if(!is_array($this->getSlots())) { return $slots; } foreach($this->getSlots() as $key => $slot) { $slots[$key] = $slot->getValue(); } return $slots; }
Get slots as [key1 => value1, key2 => value2, ...] @return array
https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Request/Request/Intent/Intent.php#L65-L76
internetofvoice/libvoice
src/Alexa/Request/Request/Intent/Intent.php
Intent.getSlot
public function getSlot($name) { return isset($this->slots[$name]) ? $this->slots[$name] : null; }
php
public function getSlot($name) { return isset($this->slots[$name]) ? $this->slots[$name] : null; }
@param string $name @return Slot
https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Request/Request/Intent/Intent.php#L83-L85
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; }
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;[email protected]> @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
https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/Helper/AlphaId.php#L107-L170
eloquent/endec
src/Base32/AbstractBase32EncodeTransform.php
AbstractBase32EncodeTransform.transform
public function transform($data, &$context, $isEnd = false) { $length = strlen($data); $consumed = intval($length / 5) * 5; $index = 0; $output = ''; while ($index < $consumed) { $output .= $this->map5( ord($data[$index++]), ord($data[$index++]), ord($data[$index++]), ord($data[$index++]), ord($data[$index++]) ); } if ($isEnd && $consumed !== $length) { $remaining = $length - $consumed; $consumed = $length; if (1 === $remaining) { $output .= $this->map1( ord($data[$index]) ); } elseif (2 === $remaining) { $output .= $this->map2( ord($data[$index++]), ord($data[$index]) ); } elseif (3 === $remaining) { $output .= $this->map3( ord($data[$index++]), ord($data[$index++]), ord($data[$index]) ); } elseif (4 === $remaining) { $output .= $this->map4( ord($data[$index++]), ord($data[$index++]), ord($data[$index++]), ord($data[$index]) ); } } return array($output, $consumed, null); }
php
public function transform($data, &$context, $isEnd = false) { $length = strlen($data); $consumed = intval($length / 5) * 5; $index = 0; $output = ''; while ($index < $consumed) { $output .= $this->map5( ord($data[$index++]), ord($data[$index++]), ord($data[$index++]), ord($data[$index++]), ord($data[$index++]) ); } if ($isEnd && $consumed !== $length) { $remaining = $length - $consumed; $consumed = $length; if (1 === $remaining) { $output .= $this->map1( ord($data[$index]) ); } elseif (2 === $remaining) { $output .= $this->map2( ord($data[$index++]), ord($data[$index]) ); } elseif (3 === $remaining) { $output .= $this->map3( ord($data[$index++]), ord($data[$index++]), ord($data[$index]) ); } elseif (4 === $remaining) { $output .= $this->map4( ord($data[$index++]), ord($data[$index++]), ord($data[$index++]), ord($data[$index]) ); } } return array($output, $consumed, null); }
Transform the supplied data. This method may transform only part of the supplied data. The return value includes information about how much data was actually consumed. The transform can be forced to consume all data by passing a boolean true as the $isEnd argument. The $context argument will initially be null, but any value assigned to this variable will persist until the stream transformation is complete. It can be used as a place to store state, such as a buffer. It is guaranteed that this method will be called with $isEnd = true once, and only once, at the end of the stream transformation. @param string $data The data to transform. @param mixed &$context An arbitrary context value. @param boolean $isEnd True if all supplied data must be transformed. @return tuple<string,integer,mixed> A 3-tuple of the transformed data, the number of bytes consumed, and any resulting error.
https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Base32/AbstractBase32EncodeTransform.php#L55-L102
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Cancel.php
EbayEnterprise_Order_Model_Cancel._checkTypes
protected function _checkTypes( Mage_Sales_Model_Order $order, EbayEnterprise_Order_Helper_Factory $factory, Radial_Core_Model_Config_Registry $orderCfg, Radial_Core_Helper_Data $coreHelper ) { return [$order, $factory, $orderCfg, $coreHelper]; }
php
protected function _checkTypes( Mage_Sales_Model_Order $order, EbayEnterprise_Order_Helper_Factory $factory, Radial_Core_Model_Config_Registry $orderCfg, Radial_Core_Helper_Data $coreHelper ) { return [$order, $factory, $orderCfg, $coreHelper]; }
Type hinting for self::__construct $initParams @param Mage_Sales_Model_Order @param EbayEnterprise_Order_Helper_Factory @param Radial_Core_Model_Config_Registry @param Radial_Core_Helper_Data @return array
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Cancel.php#L57-L64
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; }
Build order cancel payload. @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Cancel.php#L105-L111
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; }
Send order cancel payload. @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Cancel.php#L118-L124
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; }
Process order cancel response. @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Cancel.php#L131-L137