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_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
ClanCats/Hydrahon | src/Query/Sql/SelectJoin.php | SelectJoin.andOn | public function andOn($localKey, $operator, $referenceKey)
{
$this->on($localKey, $operator, $referenceKey, 'and'); return $this;
} | php | public function andOn($localKey, $operator, $referenceKey)
{
$this->on($localKey, $operator, $referenceKey, 'and'); return $this;
} | [
"public",
"function",
"andOn",
"(",
"$",
"localKey",
",",
"$",
"operator",
",",
"$",
"referenceKey",
")",
"{",
"$",
"this",
"->",
"on",
"(",
"$",
"localKey",
",",
"$",
"operator",
",",
"$",
"referenceKey",
",",
"'and'",
")",
";",
"return",
"$",
"this... | Add an and on condition to the join object
@param string $localKey
@param string $operator
@param string $referenceKey
@return self | [
"Add",
"an",
"and",
"on",
"condition",
"to",
"the",
"join",
"object"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/SelectJoin.php#L67-L70 |
ClanCats/Hydrahon | src/Query/Sql/Update.php | Update.set | public function set($param1, $param2 = null)
{
// do nothing if we get nothing
if (empty($param1))
{
return $this;
}
// when param 2 is not null we assume that only one set is passed
// like: set( 'name', 'Lu' ); instead of set( array( 'name' => 'Lu' ) );
if ( !is_null( $param2 ) )
{
$param1 = array( $param1 => $param2 );
}
// merge the new values with the existing ones.
$this->values = array_merge( $this->values, $param1 );
// return self so we can continue running the next function
return $this;
} | php | public function set($param1, $param2 = null)
{
// do nothing if we get nothing
if (empty($param1))
{
return $this;
}
// when param 2 is not null we assume that only one set is passed
// like: set( 'name', 'Lu' ); instead of set( array( 'name' => 'Lu' ) );
if ( !is_null( $param2 ) )
{
$param1 = array( $param1 => $param2 );
}
// merge the new values with the existing ones.
$this->values = array_merge( $this->values, $param1 );
// return self so we can continue running the next function
return $this;
} | [
"public",
"function",
"set",
"(",
"$",
"param1",
",",
"$",
"param2",
"=",
"null",
")",
"{",
"// do nothing if we get nothing",
"if",
"(",
"empty",
"(",
"$",
"param1",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"// when param 2 is not null we assume that o... | Add set values to the update query
->set('name', 'Luca')
@param string|array $param1
@param mixed $param2
@return self | [
"Add",
"set",
"values",
"to",
"the",
"update",
"query"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/Update.php#L28-L48 |
ClanCats/Hydrahon | src/Builder.php | Builder.extend | public static function extend($grammarKey, $queryBuilder, $queryTranslator)
{
if (isset(static::$grammar[$grammarKey]))
{
throw new Exception('Cannot overwrite Hydrahon grammar.');
}
static::$grammar[$grammarKey] = array($queryBuilder, $queryTranslator);
} | php | public static function extend($grammarKey, $queryBuilder, $queryTranslator)
{
if (isset(static::$grammar[$grammarKey]))
{
throw new Exception('Cannot overwrite Hydrahon grammar.');
}
static::$grammar[$grammarKey] = array($queryBuilder, $queryTranslator);
} | [
"public",
"static",
"function",
"extend",
"(",
"$",
"grammarKey",
",",
"$",
"queryBuilder",
",",
"$",
"queryTranslator",
")",
"{",
"if",
"(",
"isset",
"(",
"static",
"::",
"$",
"grammar",
"[",
"$",
"grammarKey",
"]",
")",
")",
"{",
"throw",
"new",
"Exc... | Extend the query builder by a new grammar
@throws ClanCats\Hydrahon\Exception
@param string $grammarKey
@param string $queryBuilder
@param string $queryTranslator
@return void | [
"Extend",
"the",
"query",
"builder",
"by",
"a",
"new",
"grammar"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Builder.php#L42-L50 |
ClanCats/Hydrahon | src/Builder.php | Builder.executeQuery | public function executeQuery(BaseQuery $query)
{
return call_user_func_array($this->executionCallback, array_merge(array($query), $this->translateQuery($query)));
} | php | public function executeQuery(BaseQuery $query)
{
return call_user_func_array($this->executionCallback, array_merge(array($query), $this->translateQuery($query)));
} | [
"public",
"function",
"executeQuery",
"(",
"BaseQuery",
"$",
"query",
")",
"{",
"return",
"call_user_func_array",
"(",
"$",
"this",
"->",
"executionCallback",
",",
"array_merge",
"(",
"array",
"(",
"$",
"query",
")",
",",
"$",
"this",
"->",
"translateQuery",
... | Translate a query and run the current execution callback
@param BaseQuery $query
@return mixed | [
"Translate",
"a",
"query",
"and",
"run",
"the",
"current",
"execution",
"callback"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Builder.php#L147-L150 |
ClanCats/Hydrahon | src/Query/Sql/Insert.php | Insert.values | public function values(array $values = array())
{
// do nothing if we get nothing
if (empty($values))
{
return $this;
}
// check if the the passed array is a collection.
// because we want to be able to insert bulk values.
if (!is_array(reset( $values )))
{
$values = array($values);
}
// because we could recive the arrays in diffrent order
// we have to sort them by their key.
foreach($values as $key => $value)
{
ksort( $value ); $values[$key] = $value;
}
// merge the new values with the existing ones.
$this->values = array_merge($this->values, $values);
// return self so we can continue running the next function
return $this;
} | php | public function values(array $values = array())
{
// do nothing if we get nothing
if (empty($values))
{
return $this;
}
// check if the the passed array is a collection.
// because we want to be able to insert bulk values.
if (!is_array(reset( $values )))
{
$values = array($values);
}
// because we could recive the arrays in diffrent order
// we have to sort them by their key.
foreach($values as $key => $value)
{
ksort( $value ); $values[$key] = $value;
}
// merge the new values with the existing ones.
$this->values = array_merge($this->values, $values);
// return self so we can continue running the next function
return $this;
} | [
"public",
"function",
"values",
"(",
"array",
"$",
"values",
"=",
"array",
"(",
")",
")",
"{",
"// do nothing if we get nothing",
"if",
"(",
"empty",
"(",
"$",
"values",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"// check if the the passed array is a col... | Add values to the insert
->values(['name' => 'Mario', 'age' => 42])
// you can also add multiple rows
->values([
['name' => 'Patrick', 'age' => 24],
['name' => 'Valentin', 'age' => 21]
])
@param array $values The data you want to insert.
@return self The current query builder. | [
"Add",
"values",
"to",
"the",
"insert"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/Insert.php#L55-L82 |
ClanCats/Hydrahon | src/Query/Sql.php | Sql.table | public function table($table = null, $alias = null)
{
$query = new Table($this); return $query->table($table, $alias);
} | php | public function table($table = null, $alias = null)
{
$query = new Table($this); return $query->table($table, $alias);
} | [
"public",
"function",
"table",
"(",
"$",
"table",
"=",
"null",
",",
"$",
"alias",
"=",
"null",
")",
"{",
"$",
"query",
"=",
"new",
"Table",
"(",
"$",
"this",
")",
";",
"return",
"$",
"query",
"->",
"table",
"(",
"$",
"table",
",",
"$",
"alias",
... | Create a new table instance
$h->table('users')
@param string|array $fields
@return Table | [
"Create",
"a",
"new",
"table",
"instance"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql.php#L30-L33 |
ClanCats/Hydrahon | src/Query/Sql.php | Sql.select | public function select($table = null, $fields = null)
{
return $this->table($table)->select($fields);
} | php | public function select($table = null, $fields = null)
{
return $this->table($table)->select($fields);
} | [
"public",
"function",
"select",
"(",
"$",
"table",
"=",
"null",
",",
"$",
"fields",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"table",
"(",
"$",
"table",
")",
"->",
"select",
"(",
"$",
"fields",
")",
";",
"}"
] | Create a new select query builder
$h->select('users', ['name', 'age'])
@param string|array $fields
@return Select | [
"Create",
"a",
"new",
"select",
"query",
"builder"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql.php#L43-L46 |
ClanCats/Hydrahon | src/BaseQuery.php | BaseQuery.inheritFromParent | protected function inheritFromParent(BaseQuery $parent)
{
$this->macros = $parent->macros;
$this->flags = $parent->flags;
$this->resultFetcher = $parent->resultFetcher;
} | php | protected function inheritFromParent(BaseQuery $parent)
{
$this->macros = $parent->macros;
$this->flags = $parent->flags;
$this->resultFetcher = $parent->resultFetcher;
} | [
"protected",
"function",
"inheritFromParent",
"(",
"BaseQuery",
"$",
"parent",
")",
"{",
"$",
"this",
"->",
"macros",
"=",
"$",
"parent",
"->",
"macros",
";",
"$",
"this",
"->",
"flags",
"=",
"$",
"parent",
"->",
"flags",
";",
"$",
"this",
"->",
"resul... | Inherit property values from parent query
@param BaseQuery $parent
@return void | [
"Inherit",
"property",
"values",
"from",
"parent",
"query"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/BaseQuery.php#L58-L63 |
ClanCats/Hydrahon | src/BaseQuery.php | BaseQuery.attributes | final public function attributes()
{
$excluded = array('resultFetcher', 'macros');
$attributes = get_object_vars($this);
foreach ($excluded as $key)
{
if (isset($attributes[$key])) { unset($attributes[$key]); }
}
return $attributes;
} | php | final public function attributes()
{
$excluded = array('resultFetcher', 'macros');
$attributes = get_object_vars($this);
foreach ($excluded as $key)
{
if (isset($attributes[$key])) { unset($attributes[$key]); }
}
return $attributes;
} | [
"final",
"public",
"function",
"attributes",
"(",
")",
"{",
"$",
"excluded",
"=",
"array",
"(",
"'resultFetcher'",
",",
"'macros'",
")",
";",
"$",
"attributes",
"=",
"get_object_vars",
"(",
"$",
"this",
")",
";",
"foreach",
"(",
"$",
"excluded",
"as",
"$... | Returns all avaialbe attribute data
The result fetcher callback is excluded
@return array | [
"Returns",
"all",
"avaialbe",
"attribute",
"data",
"The",
"result",
"fetcher",
"callback",
"is",
"excluded"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/BaseQuery.php#L168-L179 |
ClanCats/Hydrahon | src/BaseQuery.php | BaseQuery.overwriteAttributes | final public function overwriteAttributes($attributes)
{
foreach($attributes as $key => $attribute)
{
if (isset($this->{$key}))
{
$this->{$key} = $attribute;
}
}
return $attributes;
} | php | final public function overwriteAttributes($attributes)
{
foreach($attributes as $key => $attribute)
{
if (isset($this->{$key}))
{
$this->{$key} = $attribute;
}
}
return $attributes;
} | [
"final",
"public",
"function",
"overwriteAttributes",
"(",
"$",
"attributes",
")",
"{",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"key",
"=>",
"$",
"attribute",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"{",
"$",
"key",
"}",
")",
")",... | Overwrite the query attributes
Jesuz only use this if you really really know what your are doing
otherwise you might break stuff add sql injection and all other bad stuff..
@return array | [
"Overwrite",
"the",
"query",
"attributes"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/BaseQuery.php#L189-L200 |
ClanCats/Hydrahon | src/Query/Sql/SelectBase.php | SelectBase.where | public function where($column, $param1 = null, $param2 = null, $type = 'and')
{
// check if the where type is valid
if ($type !== 'and' && $type !== 'or' && $type !== 'where' )
{
throw new Exception('Invalid where type "'.$type.'"');
}
// if this is the first where element we are going to change
// the where type to 'where'
if (empty($this->wheres))
{
$type = 'where';
}
elseif($type === 'where')
{
$type = 'and';
}
// when column is an array we assume to make a bulk and where.
if (is_array($column))
{
$subquery = new SelectBase;
foreach ($column as $key => $val)
{
$subquery->where($key, $val, null, $type);
}
$this->wheres[] = array($type, $subquery); return $this;
}
// to make nested wheres possible you can pass an closure
// wich will create a new query where you can add your nested wheres
if (is_object($column) && ($column instanceof \Closure))
{
// create new query object
$subquery = new SelectBase;
// run the closure callback on the sub query
call_user_func_array($column, array( &$subquery ));
$this->wheres[] = array($type, $subquery); return $this;
}
// when param2 is null we replace param2 with param one as the
// value holder and make param1 to the = operator.
if (is_null($param2))
{
$param2 = $param1; $param1 = '=';
}
// if the param2 is an array we filter it. Im no more sure why
// but it's there since 4 years so i think i had a reason.
// edit: Found it out, when param2 is an array we probably
// have an "in" or "between" statement which has no need for dublicates.
if (is_array($param2))
{
$param2 = array_unique($param2);
}
$this->wheres[] = array($type, $column, $param1, $param2);
return $this;
} | php | public function where($column, $param1 = null, $param2 = null, $type = 'and')
{
// check if the where type is valid
if ($type !== 'and' && $type !== 'or' && $type !== 'where' )
{
throw new Exception('Invalid where type "'.$type.'"');
}
// if this is the first where element we are going to change
// the where type to 'where'
if (empty($this->wheres))
{
$type = 'where';
}
elseif($type === 'where')
{
$type = 'and';
}
// when column is an array we assume to make a bulk and where.
if (is_array($column))
{
$subquery = new SelectBase;
foreach ($column as $key => $val)
{
$subquery->where($key, $val, null, $type);
}
$this->wheres[] = array($type, $subquery); return $this;
}
// to make nested wheres possible you can pass an closure
// wich will create a new query where you can add your nested wheres
if (is_object($column) && ($column instanceof \Closure))
{
// create new query object
$subquery = new SelectBase;
// run the closure callback on the sub query
call_user_func_array($column, array( &$subquery ));
$this->wheres[] = array($type, $subquery); return $this;
}
// when param2 is null we replace param2 with param one as the
// value holder and make param1 to the = operator.
if (is_null($param2))
{
$param2 = $param1; $param1 = '=';
}
// if the param2 is an array we filter it. Im no more sure why
// but it's there since 4 years so i think i had a reason.
// edit: Found it out, when param2 is an array we probably
// have an "in" or "between" statement which has no need for dublicates.
if (is_array($param2))
{
$param2 = array_unique($param2);
}
$this->wheres[] = array($type, $column, $param1, $param2);
return $this;
} | [
"public",
"function",
"where",
"(",
"$",
"column",
",",
"$",
"param1",
"=",
"null",
",",
"$",
"param2",
"=",
"null",
",",
"$",
"type",
"=",
"'and'",
")",
"{",
"// check if the where type is valid",
"if",
"(",
"$",
"type",
"!==",
"'and'",
"&&",
"$",
"ty... | Create a where statement
->where('name', 'ladina')
->where('age', '>', 18)
->where('name', 'in', array('charles', 'john', 'jeffry'))
@param string $column The SQL column
@param mixed $param1 Operator or value depending if $param2 isset.
@param mixed $param2 The value if $param1 is an opartor.
@param string $type the where type ( and, or )
@return self The current query builder. | [
"Create",
"a",
"where",
"statement"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/SelectBase.php#L98-L161 |
ClanCats/Hydrahon | src/Query/Sql/SelectBase.php | SelectBase.andWhere | public function andWhere($column, $param1 = null, $param2 = null)
{
return $this->where($column, $param1, $param2, 'and');
} | php | public function andWhere($column, $param1 = null, $param2 = null)
{
return $this->where($column, $param1, $param2, 'and');
} | [
"public",
"function",
"andWhere",
"(",
"$",
"column",
",",
"$",
"param1",
"=",
"null",
",",
"$",
"param2",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"where",
"(",
"$",
"column",
",",
"$",
"param1",
",",
"$",
"param2",
",",
"'and'",
")",
... | Create an and where statement
This is the same as the normal where just with a fixed type
@param string $column The SQL column
@param mixed $param1
@param mixed $param2
@return self The current query builder. | [
"Create",
"an",
"and",
"where",
"statement"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/SelectBase.php#L190-L193 |
ClanCats/Hydrahon | src/Query/Sql/SelectBase.php | SelectBase.limit | public function limit($limit, $limit2 = null)
{
if (!is_null($limit2))
{
$this->offset = (int) $limit;
$this->limit = (int) $limit2;
} else {
$this->limit = (int) $limit;
}
return $this;
} | php | public function limit($limit, $limit2 = null)
{
if (!is_null($limit2))
{
$this->offset = (int) $limit;
$this->limit = (int) $limit2;
} else {
$this->limit = (int) $limit;
}
return $this;
} | [
"public",
"function",
"limit",
"(",
"$",
"limit",
",",
"$",
"limit2",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"limit2",
")",
")",
"{",
"$",
"this",
"->",
"offset",
"=",
"(",
"int",
")",
"$",
"limit",
";",
"$",
"this",
"->",
... | Set the query limit
// limit(<limit>)
->limit(20)
// limit(<offset>, <limit>)
->limit(60, 20)
@param int $limit
@param int $limit2
@return self The current query builder. | [
"Set",
"the",
"query",
"limit"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/SelectBase.php#L280-L291 |
ClanCats/Hydrahon | src/Query/Sql/SelectBase.php | SelectBase.page | public function page($page, $size = 25)
{
if (($page = (int) $page) < 0)
{
$page = 0;
}
$this->limit = (int) $size;
$this->offset = (int) $size * $page;
return $this;
} | php | public function page($page, $size = 25)
{
if (($page = (int) $page) < 0)
{
$page = 0;
}
$this->limit = (int) $size;
$this->offset = (int) $size * $page;
return $this;
} | [
"public",
"function",
"page",
"(",
"$",
"page",
",",
"$",
"size",
"=",
"25",
")",
"{",
"if",
"(",
"(",
"$",
"page",
"=",
"(",
"int",
")",
"$",
"page",
")",
"<",
"0",
")",
"{",
"$",
"page",
"=",
"0",
";",
"}",
"$",
"this",
"->",
"limit",
"... | Create an query limit based on a page and a page size
@param int $page
@param int $size
@return self The current query builder. | [
"Create",
"an",
"query",
"limit",
"based",
"on",
"a",
"page",
"and",
"a",
"page",
"size"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/SelectBase.php#L311-L322 |
ClanCats/Hydrahon | src/Query/Sql/Base.php | Base.inheritFromParent | protected function inheritFromParent(BaseQuery $parent)
{
parent::inheritFromParent($parent);
if (isset($parent->database)) {
$this->database = $parent->database;
}
if (isset($parent->table)) {
$this->table = $parent->table;
}
} | php | protected function inheritFromParent(BaseQuery $parent)
{
parent::inheritFromParent($parent);
if (isset($parent->database)) {
$this->database = $parent->database;
}
if (isset($parent->table)) {
$this->table = $parent->table;
}
} | [
"protected",
"function",
"inheritFromParent",
"(",
"BaseQuery",
"$",
"parent",
")",
"{",
"parent",
"::",
"inheritFromParent",
"(",
"$",
"parent",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"parent",
"->",
"database",
")",
")",
"{",
"$",
"this",
"->",
"datab... | Inherit property values from parent query
@param BaseQuery $parent
@return void | [
"Inherit",
"property",
"values",
"from",
"parent",
"query"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/Base.php#L34-L44 |
ClanCats/Hydrahon | src/Query/Sql/Base.php | Base.table | public function table($table, $alias = null)
{
$database = null;
// Check if the table is an object, this means
// we have an subselect inside the table
if (is_object($table) && ($table instanceof \Closure))
{
// we have to check if an alias isset
// otherwise throw an exception to prevent the
// "Every derived table must have its own alias" error
if (is_null($alias))
{
throw new Exception('You must define an alias when working with subselects.');
}
$table = array($alias => $table);
}
// Check if the $table is an array and the value is an closure
// that we can pass a new query object as subquery
if (is_array($table) && is_object(reset($table)) && (reset($table) instanceof \Closure))
{
$alias = key($table);
$table = reset($table);
// create new query object
$subquery = new Select;
// run the closure callback on the sub query
call_user_func_array($table, array(&$subquery));
// set the table
// IMPORTANT: Only if we have a closure as table
// we set the alias as key. This might cause some confusion
// but only this way we can keep the normal ['table' => 'alias'] syntax
$table = array($alias => $subquery);
}
// other wise normally try to split the table and database name
elseif (is_string($table) && strpos($table, '.') !== false)
{
$selection = explode('.', $table);
if (count($selection) !== 2)
{
throw new Exception( 'Invalid argument given. You can only define one seperator.' );
}
list($database, $table) = $selection;
}
// the table might include an alias we need to parse that one out
if (is_string($table) && strpos($table, ' as ') !== false)
{
$tableParts = explode(' as ', $table);
$table = array($tableParts[0] => $tableParts[1]);
}
// assing the result
$this->database = $database;
$this->table = $table;
// return self
return $this;
} | php | public function table($table, $alias = null)
{
$database = null;
// Check if the table is an object, this means
// we have an subselect inside the table
if (is_object($table) && ($table instanceof \Closure))
{
// we have to check if an alias isset
// otherwise throw an exception to prevent the
// "Every derived table must have its own alias" error
if (is_null($alias))
{
throw new Exception('You must define an alias when working with subselects.');
}
$table = array($alias => $table);
}
// Check if the $table is an array and the value is an closure
// that we can pass a new query object as subquery
if (is_array($table) && is_object(reset($table)) && (reset($table) instanceof \Closure))
{
$alias = key($table);
$table = reset($table);
// create new query object
$subquery = new Select;
// run the closure callback on the sub query
call_user_func_array($table, array(&$subquery));
// set the table
// IMPORTANT: Only if we have a closure as table
// we set the alias as key. This might cause some confusion
// but only this way we can keep the normal ['table' => 'alias'] syntax
$table = array($alias => $subquery);
}
// other wise normally try to split the table and database name
elseif (is_string($table) && strpos($table, '.') !== false)
{
$selection = explode('.', $table);
if (count($selection) !== 2)
{
throw new Exception( 'Invalid argument given. You can only define one seperator.' );
}
list($database, $table) = $selection;
}
// the table might include an alias we need to parse that one out
if (is_string($table) && strpos($table, ' as ') !== false)
{
$tableParts = explode(' as ', $table);
$table = array($tableParts[0] => $tableParts[1]);
}
// assing the result
$this->database = $database;
$this->table = $table;
// return self
return $this;
} | [
"public",
"function",
"table",
"(",
"$",
"table",
",",
"$",
"alias",
"=",
"null",
")",
"{",
"$",
"database",
"=",
"null",
";",
"// Check if the table is an object, this means",
"// we have an subselect inside the table",
"if",
"(",
"is_object",
"(",
"$",
"table",
... | Create a new select query builder
// selecting a table
$h->table('users')
// selecting table and database
$h->table('db_mydatabase.posts')
@param string $table
@return self | [
"Create",
"a",
"new",
"select",
"query",
"builder"
] | train | https://github.com/ClanCats/Hydrahon/blob/e2790279bfdb1faa9155504267db1f57d4dabe00/src/Query/Sql/Base.php#L58-L123 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.fromSqlBoolean | public function fromSqlBoolean($sqlBoolean, Provider $provider = null)
{
$this->setParameterProvider($provider);
return $provider->convertFromSqlBoolean($sqlBoolean);
} | php | public function fromSqlBoolean($sqlBoolean, Provider $provider = null)
{
$this->setParameterProvider($provider);
return $provider->convertFromSqlBoolean($sqlBoolean);
} | [
"public",
"function",
"fromSqlBoolean",
"(",
"$",
"sqlBoolean",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"provider",
")",
";",
"return",
"$",
"provider",
"->",
"convertFromSqlBoolean",
"(",
... | Converts an SQL boolean to a PHP boolean
@param mixed $sqlBoolean The boolean to convert
@param Provider $provider The provider to convert from
@return bool|null The PHP boolean if it was a boolean value, otherwise null | [
"Converts",
"an",
"SQL",
"boolean",
"to",
"a",
"PHP",
"boolean"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L45-L50 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.fromSqlDate | public function fromSqlDate($sqlDate, Provider $provider = null)
{
if ($sqlDate === null) {
return null;
}
$this->setParameterProvider($provider);
// The "!" zeroes out the hours, minutes, and seconds
$phpDate = DateTime::createFromFormat('!' . $provider->getDateFormat(), $sqlDate);
if ($phpDate === false) {
$phpDate = $this->parseUnknownDateTimeFormat($sqlDate);
}
return $phpDate;
} | php | public function fromSqlDate($sqlDate, Provider $provider = null)
{
if ($sqlDate === null) {
return null;
}
$this->setParameterProvider($provider);
// The "!" zeroes out the hours, minutes, and seconds
$phpDate = DateTime::createFromFormat('!' . $provider->getDateFormat(), $sqlDate);
if ($phpDate === false) {
$phpDate = $this->parseUnknownDateTimeFormat($sqlDate);
}
return $phpDate;
} | [
"public",
"function",
"fromSqlDate",
"(",
"$",
"sqlDate",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"sqlDate",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"pro... | Converts an SQL date to a PHP date time
@param string $sqlDate The date to convert
@param Provider $provider The provider to convert from
@return DateTime|null The PHP date
@throws InvalidArgumentException Thrown if the input date couldn't be cast to a PHP date | [
"Converts",
"an",
"SQL",
"date",
"to",
"a",
"PHP",
"date",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L60-L75 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.fromSqlJson | public function fromSqlJson($json, Provider $provider = null) : array
{
if ($json === null) {
return [];
}
return json_decode($json, true);
} | php | public function fromSqlJson($json, Provider $provider = null) : array
{
if ($json === null) {
return [];
}
return json_decode($json, true);
} | [
"public",
"function",
"fromSqlJson",
"(",
"$",
"json",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
":",
"array",
"{",
"if",
"(",
"$",
"json",
"===",
"null",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"json_decode",
"(",
"$",
"json",
... | Converts an SQL JSON string to a PHP array
@param string $json The JSON string to convert
@param Provider $provider The provider to convert from
@return array The PHP array | [
"Converts",
"an",
"SQL",
"JSON",
"string",
"to",
"a",
"PHP",
"array"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L84-L91 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.fromSqlTimeWithTimeZone | public function fromSqlTimeWithTimeZone($sqlTime, Provider $provider = null)
{
if ($sqlTime === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTime = DateTime::createFromFormat($provider->getTimeWithTimeZoneFormat(), $sqlTime);
if ($phpTime === false) {
$phpTime = $this->parseUnknownDateTimeFormat($sqlTime);
}
return $phpTime;
} | php | public function fromSqlTimeWithTimeZone($sqlTime, Provider $provider = null)
{
if ($sqlTime === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTime = DateTime::createFromFormat($provider->getTimeWithTimeZoneFormat(), $sqlTime);
if ($phpTime === false) {
$phpTime = $this->parseUnknownDateTimeFormat($sqlTime);
}
return $phpTime;
} | [
"public",
"function",
"fromSqlTimeWithTimeZone",
"(",
"$",
"sqlTime",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"sqlTime",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"setParameterProvider",
"(",
... | Converts an SQL time with time zone to a PHP date time
@param string $sqlTime The time to convert
@param Provider $provider The provider to convert from
@return DateTime|null The PHP time
@throws InvalidArgumentException Thrown if the input time couldn't be cast to a PHP time | [
"Converts",
"an",
"SQL",
"time",
"with",
"time",
"zone",
"to",
"a",
"PHP",
"date",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L101-L115 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.fromSqlTimeWithoutTimeZone | public function fromSqlTimeWithoutTimeZone($sqlTime, Provider $provider = null)
{
if ($sqlTime === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTime = DateTime::createFromFormat($provider->getTimeWithoutTimeZoneFormat(), $sqlTime);
if ($phpTime === false) {
$phpTime = $this->parseUnknownDateTimeFormat($sqlTime);
}
return $phpTime;
} | php | public function fromSqlTimeWithoutTimeZone($sqlTime, Provider $provider = null)
{
if ($sqlTime === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTime = DateTime::createFromFormat($provider->getTimeWithoutTimeZoneFormat(), $sqlTime);
if ($phpTime === false) {
$phpTime = $this->parseUnknownDateTimeFormat($sqlTime);
}
return $phpTime;
} | [
"public",
"function",
"fromSqlTimeWithoutTimeZone",
"(",
"$",
"sqlTime",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"sqlTime",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"setParameterProvider",
"("... | Converts an SQL time without time zone to a PHP date time
@param string $sqlTime The time to convert
@param Provider $provider The provider to convert from
@return DateTime|null The PHP time
@throws InvalidArgumentException Thrown if the input time couldn't be cast to a PHP time | [
"Converts",
"an",
"SQL",
"time",
"without",
"time",
"zone",
"to",
"a",
"PHP",
"date",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L125-L139 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.fromSqlTimestampWithTimeZone | public function fromSqlTimestampWithTimeZone($sqlTimestamp, Provider $provider = null)
{
if ($sqlTimestamp === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTimestamp = DateTime::createFromFormat($provider->getTimestampWithTimeZoneFormat(), $sqlTimestamp);
if ($phpTimestamp === false) {
$phpTimestamp = $this->parseUnknownDateTimeFormat($sqlTimestamp);
}
return $phpTimestamp;
} | php | public function fromSqlTimestampWithTimeZone($sqlTimestamp, Provider $provider = null)
{
if ($sqlTimestamp === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTimestamp = DateTime::createFromFormat($provider->getTimestampWithTimeZoneFormat(), $sqlTimestamp);
if ($phpTimestamp === false) {
$phpTimestamp = $this->parseUnknownDateTimeFormat($sqlTimestamp);
}
return $phpTimestamp;
} | [
"public",
"function",
"fromSqlTimestampWithTimeZone",
"(",
"$",
"sqlTimestamp",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"sqlTimestamp",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"setParameterProv... | Converts an SQL timestamp with time zone to a PHP date time
@param string $sqlTimestamp The timestamp with time zone to convert
@param Provider $provider The provider to convert from
@return DateTime|null The PHP date time
@throws InvalidArgumentException Thrown if the input timestamp couldn't be cast to a PHP timestamp | [
"Converts",
"an",
"SQL",
"timestamp",
"with",
"time",
"zone",
"to",
"a",
"PHP",
"date",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L149-L164 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.fromSqlTimestampWithoutTimeZone | public function fromSqlTimestampWithoutTimeZone($sqlTimestamp, Provider $provider = null)
{
if ($sqlTimestamp === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTimestamp = DateTime::createFromFormat($provider->getTimestampWithoutTimeZoneFormat(), $sqlTimestamp);
if ($phpTimestamp === false) {
$phpTimestamp = $this->parseUnknownDateTimeFormat($sqlTimestamp);
}
return $phpTimestamp;
} | php | public function fromSqlTimestampWithoutTimeZone($sqlTimestamp, Provider $provider = null)
{
if ($sqlTimestamp === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTimestamp = DateTime::createFromFormat($provider->getTimestampWithoutTimeZoneFormat(), $sqlTimestamp);
if ($phpTimestamp === false) {
$phpTimestamp = $this->parseUnknownDateTimeFormat($sqlTimestamp);
}
return $phpTimestamp;
} | [
"public",
"function",
"fromSqlTimestampWithoutTimeZone",
"(",
"$",
"sqlTimestamp",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"sqlTimestamp",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"setParameterP... | Converts an SQL timestamp without time zone to a PHP date time
@param string $sqlTimestamp The timestamp without time zone to convert
@param Provider $provider The provider to convert from
@return DateTime|null The PHP date time
@throws InvalidArgumentException Thrown if the input timestamp couldn't be cast to a PHP timestamp | [
"Converts",
"an",
"SQL",
"timestamp",
"without",
"time",
"zone",
"to",
"a",
"PHP",
"date",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L174-L188 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.toSqlBoolean | public function toSqlBoolean(bool $boolean, Provider $provider = null)
{
$this->setParameterProvider($provider);
return $provider->convertToSqlBoolean($boolean);
} | php | public function toSqlBoolean(bool $boolean, Provider $provider = null)
{
$this->setParameterProvider($provider);
return $provider->convertToSqlBoolean($boolean);
} | [
"public",
"function",
"toSqlBoolean",
"(",
"bool",
"$",
"boolean",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"provider",
")",
";",
"return",
"$",
"provider",
"->",
"convertToSqlBoolean",
"("... | Converts a PHP boolean to an SQL boolean
@param bool $boolean The boolean to convert
@param Provider $provider The provider to convert to
@return mixed The SQL boolean suitable for database storage | [
"Converts",
"a",
"PHP",
"boolean",
"to",
"an",
"SQL",
"boolean"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L197-L202 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.toSqlDate | public function toSqlDate(DateTimeInterface $date, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $date->format($provider->getDateFormat());
} | php | public function toSqlDate(DateTimeInterface $date, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $date->format($provider->getDateFormat());
} | [
"public",
"function",
"toSqlDate",
"(",
"DateTimeInterface",
"$",
"date",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
":",
"string",
"{",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"provider",
")",
";",
"return",
"$",
"date",
"->",
"forma... | Converts a PHP date time to an SQL date
@param DateTimeInterface $date The date time to convert
@param Provider $provider The provider to convert to
@return string The SQL date suitable for database storage | [
"Converts",
"a",
"PHP",
"date",
"time",
"to",
"an",
"SQL",
"date"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L211-L216 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.toSqlTimeWithTimeZone | public function toSqlTimeWithTimeZone(DateTimeInterface $time, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $time->format($provider->getTimeWithTimeZoneFormat());
} | php | public function toSqlTimeWithTimeZone(DateTimeInterface $time, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $time->format($provider->getTimeWithTimeZoneFormat());
} | [
"public",
"function",
"toSqlTimeWithTimeZone",
"(",
"DateTimeInterface",
"$",
"time",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
":",
"string",
"{",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"provider",
")",
";",
"return",
"$",
"time",
"-... | Converts a PHP date time with time zone to an SQL time
@param DateTimeInterface $time The date time to convert
@param Provider $provider The provider to convert to
@return string The SQL time suitable for database storage | [
"Converts",
"a",
"PHP",
"date",
"time",
"with",
"time",
"zone",
"to",
"an",
"SQL",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L237-L242 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.toSqlTimeWithoutTimeZone | public function toSqlTimeWithoutTimeZone(DateTimeInterface $time, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $time->format($provider->getTimeWithoutTimeZoneFormat());
} | php | public function toSqlTimeWithoutTimeZone(DateTimeInterface $time, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $time->format($provider->getTimeWithoutTimeZoneFormat());
} | [
"public",
"function",
"toSqlTimeWithoutTimeZone",
"(",
"DateTimeInterface",
"$",
"time",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
":",
"string",
"{",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"provider",
")",
";",
"return",
"$",
"time",
... | Converts a PHP date time without time zone to an SQL time
@param DateTimeInterface $time The date time to convert
@param Provider $provider The provider to convert to
@return string The SQL time suitable for database storage | [
"Converts",
"a",
"PHP",
"date",
"time",
"without",
"time",
"zone",
"to",
"an",
"SQL",
"time"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L251-L256 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.toSqlTimestampWithTimeZone | public function toSqlTimestampWithTimeZone(DateTimeInterface $timestamp, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $timestamp->format($provider->getTimestampWithTimeZoneFormat());
} | php | public function toSqlTimestampWithTimeZone(DateTimeInterface $timestamp, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $timestamp->format($provider->getTimestampWithTimeZoneFormat());
} | [
"public",
"function",
"toSqlTimestampWithTimeZone",
"(",
"DateTimeInterface",
"$",
"timestamp",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
":",
"string",
"{",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"provider",
")",
";",
"return",
"$",
"t... | Converts a PHP date time to an SQL timestamp with time zone
@param DateTimeInterface $timestamp The date time to convert
@param Provider $provider The provider to convert to
@return string The SQL timestamp with time zone suitable for database storage | [
"Converts",
"a",
"PHP",
"date",
"time",
"to",
"an",
"SQL",
"timestamp",
"with",
"time",
"zone"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L265-L270 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.toSqlTimestampWithoutTimeZone | public function toSqlTimestampWithoutTimeZone(DateTimeInterface $timestamp, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $timestamp->format($provider->getTimestampWithoutTimeZoneFormat());
} | php | public function toSqlTimestampWithoutTimeZone(DateTimeInterface $timestamp, Provider $provider = null) : string
{
$this->setParameterProvider($provider);
return $timestamp->format($provider->getTimestampWithoutTimeZoneFormat());
} | [
"public",
"function",
"toSqlTimestampWithoutTimeZone",
"(",
"DateTimeInterface",
"$",
"timestamp",
",",
"Provider",
"$",
"provider",
"=",
"null",
")",
":",
"string",
"{",
"$",
"this",
"->",
"setParameterProvider",
"(",
"$",
"provider",
")",
";",
"return",
"$",
... | Converts a PHP date time to an SQL timestamp without time zone
@param DateTimeInterface $timestamp The date time to convert
@param Provider $provider The provider to convert to
@return string The SQL timestamp without time zone suitable for database storage | [
"Converts",
"a",
"PHP",
"date",
"time",
"to",
"an",
"SQL",
"timestamp",
"without",
"time",
"zone"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L279-L284 |
opulencephp/Opulence | src/Opulence/Databases/Providers/Types/TypeMapper.php | TypeMapper.setParameterProvider | protected function setParameterProvider(Provider &$provider = null)
{
if ($provider === null) {
if ($this->provider === null) {
throw new RuntimeException('No provider specified');
}
$provider = $this->provider;
}
} | php | protected function setParameterProvider(Provider &$provider = null)
{
if ($provider === null) {
if ($this->provider === null) {
throw new RuntimeException('No provider specified');
}
$provider = $this->provider;
}
} | [
"protected",
"function",
"setParameterProvider",
"(",
"Provider",
"&",
"$",
"provider",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"provider",
"===",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"provider",
"===",
"null",
")",
"{",
"throw",
"new",
"Runt... | Checks to see that at least the object's provider is set or the input provider is set
If the input provider is not set, then it is set by reference to the object's provider
@param Provider $provider The provider to set
@throws RuntimeException Thrown if neither the input provider nor the object provider are specified | [
"Checks",
"to",
"see",
"that",
"at",
"least",
"the",
"object",
"s",
"provider",
"is",
"set",
"or",
"the",
"input",
"provider",
"is",
"set",
"If",
"the",
"input",
"provider",
"is",
"not",
"set",
"then",
"it",
"is",
"set",
"by",
"reference",
"to",
"the",... | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Providers/Types/TypeMapper.php#L309-L318 |
opulencephp/Opulence | src/Opulence/Console/Kernel.php | Kernel.handle | public function handle($input, IResponse $response = null) : int
{
if ($response === null) {
$response = new ConsoleResponse(new Compiler(new Lexer(), new Parser()));
}
try {
$request = $this->requestParser->parse($input);
if ($this->isInvokingHelpCommand($request)) {
// We are going to execute the help command
$compiledCommand = $this->getCompiledHelpCommand($request);
} elseif ($this->isInvokingVersionCommand($request)) {
// We are going to execute the version command
$compiledCommand = new VersionCommand($this->applicationVersion);
} elseif ($this->commandCollection->has($request->getCommandName())) {
// We are going to execute the command that was entered
$command = $this->commandCollection->get($request->getCommandName());
$compiledCommand = $this->commandCompiler->compile($command, $request);
} else {
// We are defaulting to the about command
$compiledCommand = new AboutCommand($this->commandCollection, new PaddingFormatter(),
$this->applicationVersion);
}
$statusCode = $compiledCommand->execute($response);
if ($statusCode === null) {
return StatusCodes::OK;
}
return $statusCode;
} catch (InvalidArgumentException $ex) {
$response->writeln("<error>{$ex->getMessage()}</error>");
return StatusCodes::ERROR;
} catch (Exception $ex) {
$response->writeln("<fatal>{$ex->getMessage()}</fatal>");
return StatusCodes::FATAL;
} catch (Throwable $ex) {
$response->writeln("<fatal>{$ex->getMessage()}</fatal>");
return StatusCodes::FATAL;
}
} | php | public function handle($input, IResponse $response = null) : int
{
if ($response === null) {
$response = new ConsoleResponse(new Compiler(new Lexer(), new Parser()));
}
try {
$request = $this->requestParser->parse($input);
if ($this->isInvokingHelpCommand($request)) {
// We are going to execute the help command
$compiledCommand = $this->getCompiledHelpCommand($request);
} elseif ($this->isInvokingVersionCommand($request)) {
// We are going to execute the version command
$compiledCommand = new VersionCommand($this->applicationVersion);
} elseif ($this->commandCollection->has($request->getCommandName())) {
// We are going to execute the command that was entered
$command = $this->commandCollection->get($request->getCommandName());
$compiledCommand = $this->commandCompiler->compile($command, $request);
} else {
// We are defaulting to the about command
$compiledCommand = new AboutCommand($this->commandCollection, new PaddingFormatter(),
$this->applicationVersion);
}
$statusCode = $compiledCommand->execute($response);
if ($statusCode === null) {
return StatusCodes::OK;
}
return $statusCode;
} catch (InvalidArgumentException $ex) {
$response->writeln("<error>{$ex->getMessage()}</error>");
return StatusCodes::ERROR;
} catch (Exception $ex) {
$response->writeln("<fatal>{$ex->getMessage()}</fatal>");
return StatusCodes::FATAL;
} catch (Throwable $ex) {
$response->writeln("<fatal>{$ex->getMessage()}</fatal>");
return StatusCodes::FATAL;
}
} | [
"public",
"function",
"handle",
"(",
"$",
"input",
",",
"IResponse",
"$",
"response",
"=",
"null",
")",
":",
"int",
"{",
"if",
"(",
"$",
"response",
"===",
"null",
")",
"{",
"$",
"response",
"=",
"new",
"ConsoleResponse",
"(",
"new",
"Compiler",
"(",
... | Handles a console command
@param mixed $input The raw input to parse
@param IResponse $response The response to write to
@return int The status code | [
"Handles",
"a",
"console",
"command"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Kernel.php#L72-L117 |
opulencephp/Opulence | src/Opulence/Console/Kernel.php | Kernel.getCompiledHelpCommand | private function getCompiledHelpCommand(IRequest $request) : ICommand
{
$helpCommand = new HelpCommand(new CommandFormatter(), new PaddingFormatter());
$commandName = null;
if ($request->getCommandName() === 'help') {
$compiledHelpCommand = $this->commandCompiler->compile($helpCommand, $request);
if ($compiledHelpCommand->argumentValueIsSet('command')) {
$commandName = $compiledHelpCommand->getArgumentValue('command');
}
} else {
$commandName = $request->getCommandName();
}
// Set the command only if it was passed as an argument to the help command
if ($commandName !== null && $commandName !== '') {
if (!$this->commandCollection->has($commandName)) {
throw new InvalidArgumentException("No command with name \"$commandName\" exists");
}
$command = $this->commandCollection->get($commandName);
$helpCommand->setCommand($command);
}
return $helpCommand;
} | php | private function getCompiledHelpCommand(IRequest $request) : ICommand
{
$helpCommand = new HelpCommand(new CommandFormatter(), new PaddingFormatter());
$commandName = null;
if ($request->getCommandName() === 'help') {
$compiledHelpCommand = $this->commandCompiler->compile($helpCommand, $request);
if ($compiledHelpCommand->argumentValueIsSet('command')) {
$commandName = $compiledHelpCommand->getArgumentValue('command');
}
} else {
$commandName = $request->getCommandName();
}
// Set the command only if it was passed as an argument to the help command
if ($commandName !== null && $commandName !== '') {
if (!$this->commandCollection->has($commandName)) {
throw new InvalidArgumentException("No command with name \"$commandName\" exists");
}
$command = $this->commandCollection->get($commandName);
$helpCommand->setCommand($command);
}
return $helpCommand;
} | [
"private",
"function",
"getCompiledHelpCommand",
"(",
"IRequest",
"$",
"request",
")",
":",
"ICommand",
"{",
"$",
"helpCommand",
"=",
"new",
"HelpCommand",
"(",
"new",
"CommandFormatter",
"(",
")",
",",
"new",
"PaddingFormatter",
"(",
")",
")",
";",
"$",
"co... | Gets the compiled help command
@param IRequest $request The parsed request
@return ICommand The compiled help command
@throws InvalidArgumentException Thrown if the command that is requesting help does not exist | [
"Gets",
"the",
"compiled",
"help",
"command"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Kernel.php#L126-L152 |
opulencephp/Opulence | src/Opulence/Console/Kernel.php | Kernel.isInvokingHelpCommand | private function isInvokingHelpCommand(IRequest $request) : bool
{
return $request->getCommandName() === 'help' || $request->optionIsSet('h') || $request->optionIsSet('help');
} | php | private function isInvokingHelpCommand(IRequest $request) : bool
{
return $request->getCommandName() === 'help' || $request->optionIsSet('h') || $request->optionIsSet('help');
} | [
"private",
"function",
"isInvokingHelpCommand",
"(",
"IRequest",
"$",
"request",
")",
":",
"bool",
"{",
"return",
"$",
"request",
"->",
"getCommandName",
"(",
")",
"===",
"'help'",
"||",
"$",
"request",
"->",
"optionIsSet",
"(",
"'h'",
")",
"||",
"$",
"req... | Gets whether or not the input is invoking the help command
@param IRequest $request The parsed request
@return bool True if it is invoking the help command, otherwise false | [
"Gets",
"whether",
"or",
"not",
"the",
"input",
"is",
"invoking",
"the",
"help",
"command"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Kernel.php#L160-L163 |
opulencephp/Opulence | src/Opulence/Orm/DataMappers/RedisDataMapper.php | RedisDataMapper.loadEntities | protected function loadEntities(array $entityIds)
{
if (count($entityIds) === 0) {
return null;
}
$entities = [];
// Create and store the entities associated with each Id
foreach ($entityIds as $entityId) {
$hash = $this->getEntityHashById($entityId);
if ($hash === null) {
return null;
}
$entities[] = $this->loadEntity($hash);
}
return $entities;
} | php | protected function loadEntities(array $entityIds)
{
if (count($entityIds) === 0) {
return null;
}
$entities = [];
// Create and store the entities associated with each Id
foreach ($entityIds as $entityId) {
$hash = $this->getEntityHashById($entityId);
if ($hash === null) {
return null;
}
$entities[] = $this->loadEntity($hash);
}
return $entities;
} | [
"protected",
"function",
"loadEntities",
"(",
"array",
"$",
"entityIds",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"entityIds",
")",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"$",
"entities",
"=",
"[",
"]",
";",
"// Create and store the entities asso... | Loads multiple entities from their Ids
@param array $entityIds The list of Ids of entities to load
@return array|null The list of entities if they were all found in cache, otherwise null | [
"Loads",
"multiple",
"entities",
"from",
"their",
"Ids"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/DataMappers/RedisDataMapper.php#L101-L121 |
opulencephp/Opulence | src/Opulence/Orm/DataMappers/RedisDataMapper.php | RedisDataMapper.read | protected function read(string $keyOfEntityIds, int $valueType)
{
switch ($valueType) {
case self::VALUE_TYPE_STRING:
$entityIds = $this->getValueFromRedis($keyOfEntityIds);
if ($entityIds === false) {
return null;
}
// To be compatible with the rest of this method, we'll convert the Id to an array containing that Id
$entityIds = [$entityIds];
break;
case self::VALUE_TYPE_SET:
$entityIds = $this->getSetMembersFromRedis($keyOfEntityIds);
if (count($entityIds) === 0) {
return null;
}
break;
case self::VALUE_TYPE_SORTED_SET:
$entityIds = $this->getSortedSetMembersFromRedis($keyOfEntityIds);
if (count($entityIds) === 0) {
return null;
}
break;
default:
return null;
}
$entities = $this->loadEntities($entityIds);
if ($valueType === self::VALUE_TYPE_STRING) {
return $entities[0];
}
return $entities;
} | php | protected function read(string $keyOfEntityIds, int $valueType)
{
switch ($valueType) {
case self::VALUE_TYPE_STRING:
$entityIds = $this->getValueFromRedis($keyOfEntityIds);
if ($entityIds === false) {
return null;
}
// To be compatible with the rest of this method, we'll convert the Id to an array containing that Id
$entityIds = [$entityIds];
break;
case self::VALUE_TYPE_SET:
$entityIds = $this->getSetMembersFromRedis($keyOfEntityIds);
if (count($entityIds) === 0) {
return null;
}
break;
case self::VALUE_TYPE_SORTED_SET:
$entityIds = $this->getSortedSetMembersFromRedis($keyOfEntityIds);
if (count($entityIds) === 0) {
return null;
}
break;
default:
return null;
}
$entities = $this->loadEntities($entityIds);
if ($valueType === self::VALUE_TYPE_STRING) {
return $entities[0];
}
return $entities;
} | [
"protected",
"function",
"read",
"(",
"string",
"$",
"keyOfEntityIds",
",",
"int",
"$",
"valueType",
")",
"{",
"switch",
"(",
"$",
"valueType",
")",
"{",
"case",
"self",
"::",
"VALUE_TYPE_STRING",
":",
"$",
"entityIds",
"=",
"$",
"this",
"->",
"getValueFro... | Performs the read query for entity(ies) and returns any results
This assumes that the Ids for all the entities are stored in a set, sorted set, or a string
@param string $keyOfEntityIds The key that contains the Id(s) of the entities we're searching for
@param int $valueType The constant indicating the type of value at the key
@return array|mixed|null The list of entities or an individual entity if successful, otherwise null | [
"Performs",
"the",
"read",
"query",
"for",
"entity",
"(",
"ies",
")",
"and",
"returns",
"any",
"results",
"This",
"assumes",
"that",
"the",
"Ids",
"for",
"all",
"the",
"entities",
"are",
"stored",
"in",
"a",
"set",
"sorted",
"set",
"or",
"a",
"string"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/DataMappers/RedisDataMapper.php#L131-L172 |
opulencephp/Opulence | src/Opulence/Routing/Routes/Compilers/Parsers/Parser.php | Parser.convertRawStringToRegex | private function convertRawStringToRegex(ParsedRoute $parsedRoute, string $rawString) : string
{
if (empty($rawString)) {
return '#^.*$#';
}
$this->variableNames = [];
$bracketDepth = 0;
$this->cursor = 0;
$rawStringLength = mb_strlen($rawString);
$regex = '';
while ($this->cursor < $rawStringLength) {
$char = $rawString[$this->cursor];
switch ($char) {
case ':':
$regex .= $this->getVarRegex($parsedRoute, mb_substr($rawString, $this->cursor));
break;
case '[':
$regex .= '(?:';
$bracketDepth++;
$this->cursor++;
break;
case ']':
$regex .= ')?';
$bracketDepth--;
$this->cursor++;
break;
default:
$regex .= preg_quote($char, '#');
$this->cursor++;
}
}
if ($bracketDepth != 0) {
throw new RouteException(
sprintf('Route has %s brackets', $bracketDepth > 0 ? 'unclosed' : 'unopened')
);
}
return sprintf('#^%s$#', $regex);
} | php | private function convertRawStringToRegex(ParsedRoute $parsedRoute, string $rawString) : string
{
if (empty($rawString)) {
return '#^.*$#';
}
$this->variableNames = [];
$bracketDepth = 0;
$this->cursor = 0;
$rawStringLength = mb_strlen($rawString);
$regex = '';
while ($this->cursor < $rawStringLength) {
$char = $rawString[$this->cursor];
switch ($char) {
case ':':
$regex .= $this->getVarRegex($parsedRoute, mb_substr($rawString, $this->cursor));
break;
case '[':
$regex .= '(?:';
$bracketDepth++;
$this->cursor++;
break;
case ']':
$regex .= ')?';
$bracketDepth--;
$this->cursor++;
break;
default:
$regex .= preg_quote($char, '#');
$this->cursor++;
}
}
if ($bracketDepth != 0) {
throw new RouteException(
sprintf('Route has %s brackets', $bracketDepth > 0 ? 'unclosed' : 'unopened')
);
}
return sprintf('#^%s$#', $regex);
} | [
"private",
"function",
"convertRawStringToRegex",
"(",
"ParsedRoute",
"$",
"parsedRoute",
",",
"string",
"$",
"rawString",
")",
":",
"string",
"{",
"if",
"(",
"empty",
"(",
"$",
"rawString",
")",
")",
"{",
"return",
"'#^.*$#'",
";",
"}",
"$",
"this",
"->",... | Converts a raw string with variables to a regex
@param ParsedRoute $parsedRoute The route whose string we're converting
@param string $rawString The raw string to convert
@return string The regex
@throws RouteException Thrown if the route variables are not correctly defined | [
"Converts",
"a",
"raw",
"string",
"with",
"variables",
"to",
"a",
"regex"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Routes/Compilers/Parsers/Parser.php#L56-L98 |
opulencephp/Opulence | src/Opulence/Routing/Routes/Compilers/Parsers/Parser.php | Parser.getVarRegex | private function getVarRegex(ParsedRoute $parsedRoute, string $segment) : string
{
if (preg_match(self::$variableMatchingRegex, $segment, $matches) !== 1) {
throw new RouteException("Variable name can't be empty");
}
$variableName = $matches[1];
$defaultValue = $matches[2] ?? '';
if (strlen($variableName) > self::VARIABLE_MAXIMUM_LENGTH) {
throw new RouteException(sprintf(
'Variable name "%s" cannot be longer than %d characters. Please use a shorter name.',
$variableName,
self::VARIABLE_MAXIMUM_LENGTH)
);
}
if (in_array($variableName, $this->variableNames)) {
throw new RouteException("Route uses multiple references to \"$variableName\"");
}
$this->variableNames[] = $variableName;
$parsedRoute->setDefaultValue($variableName, $defaultValue);
$variableRegex = $parsedRoute->getVarRegex($variableName);
if ($variableRegex === null) {
// Add a default regex
$variableRegex = "[^\/:]+";
}
$this->cursor += mb_strlen($matches[0]);
return sprintf('(?P<%s>%s)', $variableName, $variableRegex);
} | php | private function getVarRegex(ParsedRoute $parsedRoute, string $segment) : string
{
if (preg_match(self::$variableMatchingRegex, $segment, $matches) !== 1) {
throw new RouteException("Variable name can't be empty");
}
$variableName = $matches[1];
$defaultValue = $matches[2] ?? '';
if (strlen($variableName) > self::VARIABLE_MAXIMUM_LENGTH) {
throw new RouteException(sprintf(
'Variable name "%s" cannot be longer than %d characters. Please use a shorter name.',
$variableName,
self::VARIABLE_MAXIMUM_LENGTH)
);
}
if (in_array($variableName, $this->variableNames)) {
throw new RouteException("Route uses multiple references to \"$variableName\"");
}
$this->variableNames[] = $variableName;
$parsedRoute->setDefaultValue($variableName, $defaultValue);
$variableRegex = $parsedRoute->getVarRegex($variableName);
if ($variableRegex === null) {
// Add a default regex
$variableRegex = "[^\/:]+";
}
$this->cursor += mb_strlen($matches[0]);
return sprintf('(?P<%s>%s)', $variableName, $variableRegex);
} | [
"private",
"function",
"getVarRegex",
"(",
"ParsedRoute",
"$",
"parsedRoute",
",",
"string",
"$",
"segment",
")",
":",
"string",
"{",
"if",
"(",
"preg_match",
"(",
"self",
"::",
"$",
"variableMatchingRegex",
",",
"$",
"segment",
",",
"$",
"matches",
")",
"... | Parses a variable and returns the regex
@param ParsedRoute $parsedRoute The route being parsed
@param string $segment The segment being parsed
@return string The variable regex
@throws RouteException Thrown if the variable definition is invalid | [
"Parses",
"a",
"variable",
"and",
"returns",
"the",
"regex"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Routing/Routes/Compilers/Parsers/Parser.php#L108-L141 |
opulencephp/Opulence | src/Opulence/Framework/Authorization/Bootstrappers/AuthorizationBootstrapper.php | AuthorizationBootstrapper.getAuthority | protected function getAuthority(IContainer $container) : IAuthority
{
$permissionRegistry = $this->getPermissionRegistry($container);
$container->bindInstance(IPermissionRegistry::class, $permissionRegistry);
$container->bindInstance(IRoles::class, $this->getRoles($container));
return new Authority(-1, [], $permissionRegistry);
} | php | protected function getAuthority(IContainer $container) : IAuthority
{
$permissionRegistry = $this->getPermissionRegistry($container);
$container->bindInstance(IPermissionRegistry::class, $permissionRegistry);
$container->bindInstance(IRoles::class, $this->getRoles($container));
return new Authority(-1, [], $permissionRegistry);
} | [
"protected",
"function",
"getAuthority",
"(",
"IContainer",
"$",
"container",
")",
":",
"IAuthority",
"{",
"$",
"permissionRegistry",
"=",
"$",
"this",
"->",
"getPermissionRegistry",
"(",
"$",
"container",
")",
";",
"$",
"container",
"->",
"bindInstance",
"(",
... | Gets the authority
@param IContainer $container The IoC container
@return IAuthority The authority | [
"Gets",
"the",
"authority"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Authorization/Bootstrappers/AuthorizationBootstrapper.php#L74-L81 |
opulencephp/Opulence | src/Opulence/Framework/Authorization/Bootstrappers/AuthorizationBootstrapper.php | AuthorizationBootstrapper.getRoles | protected function getRoles(IContainer $container) : IRoles
{
$roleRepository = $this->getRoleRepository($container);
$roleMembershipRepository = $this->getRoleMembershipRepository($container);
$container->bindInstance(IRoleRepository::class, $roleRepository);
$container->bindInstance(IRoleMembershipRepository::class, $roleMembershipRepository);
return new Roles($roleRepository, $roleMembershipRepository);
} | php | protected function getRoles(IContainer $container) : IRoles
{
$roleRepository = $this->getRoleRepository($container);
$roleMembershipRepository = $this->getRoleMembershipRepository($container);
$container->bindInstance(IRoleRepository::class, $roleRepository);
$container->bindInstance(IRoleMembershipRepository::class, $roleMembershipRepository);
return new Roles($roleRepository, $roleMembershipRepository);
} | [
"protected",
"function",
"getRoles",
"(",
"IContainer",
"$",
"container",
")",
":",
"IRoles",
"{",
"$",
"roleRepository",
"=",
"$",
"this",
"->",
"getRoleRepository",
"(",
"$",
"container",
")",
";",
"$",
"roleMembershipRepository",
"=",
"$",
"this",
"->",
"... | Gets the roles
@param IContainer $container The IoC container
@return IRoles The roles | [
"Gets",
"the",
"roles"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Authorization/Bootstrappers/AuthorizationBootstrapper.php#L100-L108 |
opulencephp/Opulence | src/Opulence/Framework/Console/Commands/RenameAppCommand.php | RenameAppCommand.updateComposer | protected function updateComposer(string $currName, string $newName)
{
$rootPath = Config::get('paths', 'root');
$currComposerContents = $this->fileSystem->read("$rootPath/composer.json");
// Change the PSR-4 namespace
$updatedComposerContents = str_replace(
"$currName\\\\",
"$newName\\\\",
$currComposerContents
);
$this->fileSystem->write("$rootPath/composer.json", $updatedComposerContents);
} | php | protected function updateComposer(string $currName, string $newName)
{
$rootPath = Config::get('paths', 'root');
$currComposerContents = $this->fileSystem->read("$rootPath/composer.json");
// Change the PSR-4 namespace
$updatedComposerContents = str_replace(
"$currName\\\\",
"$newName\\\\",
$currComposerContents
);
$this->fileSystem->write("$rootPath/composer.json", $updatedComposerContents);
} | [
"protected",
"function",
"updateComposer",
"(",
"string",
"$",
"currName",
",",
"string",
"$",
"newName",
")",
"{",
"$",
"rootPath",
"=",
"Config",
"::",
"get",
"(",
"'paths'",
",",
"'root'",
")",
";",
"$",
"currComposerContents",
"=",
"$",
"this",
"->",
... | Updates the Composer config
@param string $currName The current application name
@param string $newName The new application name | [
"Updates",
"the",
"Composer",
"config"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Console/Commands/RenameAppCommand.php#L109-L120 |
opulencephp/Opulence | src/Opulence/Framework/Console/Commands/RenameAppCommand.php | RenameAppCommand.updateConfigs | protected function updateConfigs(string $currName, string $newName)
{
$configFiles = $this->fileSystem->getFiles(Config::get('paths', 'config'), true);
foreach ($configFiles as $file) {
$currentContents = $this->fileSystem->read($file);
$updatedContents = str_replace(
"$currName\\",
"$newName\\",
$currentContents
);
$this->fileSystem->write($file, $updatedContents);
}
} | php | protected function updateConfigs(string $currName, string $newName)
{
$configFiles = $this->fileSystem->getFiles(Config::get('paths', 'config'), true);
foreach ($configFiles as $file) {
$currentContents = $this->fileSystem->read($file);
$updatedContents = str_replace(
"$currName\\",
"$newName\\",
$currentContents
);
$this->fileSystem->write($file, $updatedContents);
}
} | [
"protected",
"function",
"updateConfigs",
"(",
"string",
"$",
"currName",
",",
"string",
"$",
"newName",
")",
"{",
"$",
"configFiles",
"=",
"$",
"this",
"->",
"fileSystem",
"->",
"getFiles",
"(",
"Config",
"::",
"get",
"(",
"'paths'",
",",
"'config'",
")",... | Updates any class names that appear in configs
@param string $currName The current application name
@param string $newName The new application name | [
"Updates",
"any",
"class",
"names",
"that",
"appear",
"in",
"configs"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Console/Commands/RenameAppCommand.php#L128-L141 |
opulencephp/Opulence | src/Opulence/Framework/Console/Commands/RenameAppCommand.php | RenameAppCommand.updateNamespaces | protected function updateNamespaces(string $currName, string $newName)
{
$paths = [Config::get('paths', 'src'), Config::get('paths', 'tests')];
foreach ($paths as $pathToUpdate) {
$files = $this->fileSystem->getFiles($pathToUpdate, true);
foreach ($files as $file) {
$currContents = $this->fileSystem->read($file);
// Change the "namespace" statements
$updatedContents = str_replace(
[
"namespace $currName;",
"namespace $currName\\"
],
[
"namespace $newName;",
"namespace $newName\\"
],
$currContents
);
// Change the "use" statements
$updatedContents = str_replace(
[
"use $currName;",
"use $currName\\"
],
[
"use $newName;",
"use $newName\\"
],
$updatedContents
);
$this->fileSystem->write($file, $updatedContents);
}
}
} | php | protected function updateNamespaces(string $currName, string $newName)
{
$paths = [Config::get('paths', 'src'), Config::get('paths', 'tests')];
foreach ($paths as $pathToUpdate) {
$files = $this->fileSystem->getFiles($pathToUpdate, true);
foreach ($files as $file) {
$currContents = $this->fileSystem->read($file);
// Change the "namespace" statements
$updatedContents = str_replace(
[
"namespace $currName;",
"namespace $currName\\"
],
[
"namespace $newName;",
"namespace $newName\\"
],
$currContents
);
// Change the "use" statements
$updatedContents = str_replace(
[
"use $currName;",
"use $currName\\"
],
[
"use $newName;",
"use $newName\\"
],
$updatedContents
);
$this->fileSystem->write($file, $updatedContents);
}
}
} | [
"protected",
"function",
"updateNamespaces",
"(",
"string",
"$",
"currName",
",",
"string",
"$",
"newName",
")",
"{",
"$",
"paths",
"=",
"[",
"Config",
"::",
"get",
"(",
"'paths'",
",",
"'src'",
")",
",",
"Config",
"::",
"get",
"(",
"'paths'",
",",
"'t... | Updates the namespaces
@param string $currName The current application name
@param string $newName The new application name | [
"Updates",
"the",
"namespaces"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Console/Commands/RenameAppCommand.php#L149-L185 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/ElementRegistrant.php | ElementRegistrant.registerElements | public function registerElements(ICompiler $compiler)
{
$compiler->registerElement('success', new Style(Colors::BLACK, Colors::GREEN));
$compiler->registerElement('info', new Style(Colors::GREEN));
$compiler->registerElement('error', new Style(Colors::BLACK, Colors::YELLOW));
$compiler->registerElement('fatal', new Style(Colors::WHITE, Colors::RED));
$compiler->registerElement('question', new Style(Colors::WHITE, Colors::BLUE));
$compiler->registerElement('comment', new Style(Colors::YELLOW));
$compiler->registerElement('b', new Style(null, null, [TextStyles::BOLD]));
$compiler->registerElement('u', new Style(null, null, [TextStyles::UNDERLINE]));
} | php | public function registerElements(ICompiler $compiler)
{
$compiler->registerElement('success', new Style(Colors::BLACK, Colors::GREEN));
$compiler->registerElement('info', new Style(Colors::GREEN));
$compiler->registerElement('error', new Style(Colors::BLACK, Colors::YELLOW));
$compiler->registerElement('fatal', new Style(Colors::WHITE, Colors::RED));
$compiler->registerElement('question', new Style(Colors::WHITE, Colors::BLUE));
$compiler->registerElement('comment', new Style(Colors::YELLOW));
$compiler->registerElement('b', new Style(null, null, [TextStyles::BOLD]));
$compiler->registerElement('u', new Style(null, null, [TextStyles::UNDERLINE]));
} | [
"public",
"function",
"registerElements",
"(",
"ICompiler",
"$",
"compiler",
")",
"{",
"$",
"compiler",
"->",
"registerElement",
"(",
"'success'",
",",
"new",
"Style",
"(",
"Colors",
"::",
"BLACK",
",",
"Colors",
"::",
"GREEN",
")",
")",
";",
"$",
"compile... | Registers the Apex elements
@param ICompiler $compiler The compiler to register to | [
"Registers",
"the",
"Apex",
"elements"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/ElementRegistrant.php#L27-L37 |
opulencephp/Opulence | src/Opulence/Validation/Rules/Errors/ErrorCollection.php | ErrorCollection.get | public function get(string $name, $default = null)
{
return $this->has($name) ? $this->errorsByField[$name] : $default;
} | php | public function get(string $name, $default = null)
{
return $this->has($name) ? $this->errorsByField[$name] : $default;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"has",
"(",
"$",
"name",
")",
"?",
"$",
"this",
"->",
"errorsByField",
"[",
"$",
"name",
"]",
":",
"$",
"default",
"... | Gets the input value
@param string $name The name of the value to get
@param mixed $default The default value
@return mixed The value of the value if it was found, otherwise the default value | [
"Gets",
"the",
"input",
"value"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Validation/Rules/Errors/ErrorCollection.php#L76-L79 |
opulencephp/Opulence | src/Opulence/Http/Collection.php | Collection.get | public function get(string $name, $default = null)
{
return $this->has($name) ? $this->values[$name] : $default;
} | php | public function get(string $name, $default = null)
{
return $this->has($name) ? $this->values[$name] : $default;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"has",
"(",
"$",
"name",
")",
"?",
"$",
"this",
"->",
"values",
"[",
"$",
"name",
"]",
":",
"$",
"default",
";",
"... | Gets the input value
@param string $name The name of the value to get
@param mixed $default The default value
@return mixed The value of the value if it was found, otherwise the default value | [
"Gets",
"the",
"input",
"value"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Collection.php#L76-L79 |
opulencephp/Opulence | src/Opulence/Databases/ConnectionPools/MasterSlaveConnectionPool.php | MasterSlaveConnectionPool.removeSlave | public function removeSlave(Server $slave)
{
$slaveHashId = spl_object_hash($slave);
if (isset($this->servers['slaves'][$slaveHashId])) {
unset($this->servers['slaves'][$slaveHashId]);
}
} | php | public function removeSlave(Server $slave)
{
$slaveHashId = spl_object_hash($slave);
if (isset($this->servers['slaves'][$slaveHashId])) {
unset($this->servers['slaves'][$slaveHashId]);
}
} | [
"public",
"function",
"removeSlave",
"(",
"Server",
"$",
"slave",
")",
"{",
"$",
"slaveHashId",
"=",
"spl_object_hash",
"(",
"$",
"slave",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"servers",
"[",
"'slaves'",
"]",
"[",
"$",
"slaveHashId",
"... | Removes the input slave if it is in the list of slaves
@param Server $slave The slave to remove | [
"Removes",
"the",
"input",
"slave",
"if",
"it",
"is",
"in",
"the",
"list",
"of",
"slaves"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/ConnectionPools/MasterSlaveConnectionPool.php#L93-L100 |
opulencephp/Opulence | src/Opulence/Http/Requests/UploadedFile.php | UploadedFile.move | public function move(string $targetDirectory, string $name = null)
{
if ($this->hasErrors()) {
throw new UploadException('Cannot move file with errors');
}
if (!is_dir($targetDirectory)) {
if (!mkdir($targetDirectory, 0777, true)) {
throw new UploadException('Could not create directory ' . $targetDirectory);
}
} elseif (!is_writable($targetDirectory)) {
throw new UploadException($targetDirectory . ' is not writable');
}
$name = $name ?: $this->getBasename();
$targetPath = rtrim($targetDirectory, '\\/') . '/' . $name;
if (!$this->doMove($this->getPathname(), $targetPath)) {
throw new UploadException('Could not move the uploaded file');
}
} | php | public function move(string $targetDirectory, string $name = null)
{
if ($this->hasErrors()) {
throw new UploadException('Cannot move file with errors');
}
if (!is_dir($targetDirectory)) {
if (!mkdir($targetDirectory, 0777, true)) {
throw new UploadException('Could not create directory ' . $targetDirectory);
}
} elseif (!is_writable($targetDirectory)) {
throw new UploadException($targetDirectory . ' is not writable');
}
$name = $name ?: $this->getBasename();
$targetPath = rtrim($targetDirectory, '\\/') . '/' . $name;
if (!$this->doMove($this->getPathname(), $targetPath)) {
throw new UploadException('Could not move the uploaded file');
}
} | [
"public",
"function",
"move",
"(",
"string",
"$",
"targetDirectory",
",",
"string",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasErrors",
"(",
")",
")",
"{",
"throw",
"new",
"UploadException",
"(",
"'Cannot move file with errors'",
... | Moves the file to the target path
@param string $targetDirectory The target directory
@param string|null $name The new name
@throws UploadException Thrown if the file could not be moved | [
"Moves",
"the",
"file",
"to",
"the",
"target",
"path"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/UploadedFile.php#L123-L143 |
opulencephp/Opulence | src/Opulence/Console/Responses/Formatters/PaddingFormatter.php | PaddingFormatter.format | public function format(array $rows, callable $callback) : string
{
foreach ($rows as &$row) {
$row = (array)$row;
}
$maxLengths = $this->normalizeColumns($rows);
$paddingType = $this->padAfter ? STR_PAD_RIGHT : STR_PAD_LEFT;
// Format the rows
foreach ($rows as &$row) {
foreach ($row as $index => &$item) {
$item = str_pad($item, $maxLengths[$index], $this->paddingString, $paddingType);
}
}
$formattedText = '';
foreach ($rows as &$row) {
$formattedText .= $callback($row) . $this->eolChar;
}
// Trim the excess separator
$formattedText = preg_replace('/' . preg_quote($this->eolChar, '/') . '$/', '', $formattedText);
return $formattedText;
} | php | public function format(array $rows, callable $callback) : string
{
foreach ($rows as &$row) {
$row = (array)$row;
}
$maxLengths = $this->normalizeColumns($rows);
$paddingType = $this->padAfter ? STR_PAD_RIGHT : STR_PAD_LEFT;
// Format the rows
foreach ($rows as &$row) {
foreach ($row as $index => &$item) {
$item = str_pad($item, $maxLengths[$index], $this->paddingString, $paddingType);
}
}
$formattedText = '';
foreach ($rows as &$row) {
$formattedText .= $callback($row) . $this->eolChar;
}
// Trim the excess separator
$formattedText = preg_replace('/' . preg_quote($this->eolChar, '/') . '$/', '', $formattedText);
return $formattedText;
} | [
"public",
"function",
"format",
"(",
"array",
"$",
"rows",
",",
"callable",
"$",
"callback",
")",
":",
"string",
"{",
"foreach",
"(",
"$",
"rows",
"as",
"&",
"$",
"row",
")",
"{",
"$",
"row",
"=",
"(",
"array",
")",
"$",
"row",
";",
"}",
"$",
"... | Formats rows of text so that each column is the same width
@param array $rows The rows to pad
@param callable $callback The callback that returns a formatted row of text
@return string A list of formatted rows | [
"Formats",
"rows",
"of",
"text",
"so",
"that",
"each",
"column",
"is",
"the",
"same",
"width"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Formatters/PaddingFormatter.php#L32-L58 |
opulencephp/Opulence | src/Opulence/Console/Responses/Formatters/PaddingFormatter.php | PaddingFormatter.normalizeColumns | public function normalizeColumns(array &$rows) : array
{
$maxNumColumns = 0;
// Find the max number of columns that appear in any given row
foreach ($rows as $row) {
$maxNumColumns = max($maxNumColumns, count($row));
}
$maxLengths = array_pad([], $maxNumColumns, 0);
// Normalize the number of columns in each row
foreach ($rows as &$row) {
$row = array_pad($row, $maxNumColumns, '');
}
// Get the length of the longest value in each column
foreach ($rows as &$row) {
foreach ($row as $column => &$value) {
$value = trim($value);
$maxLengths[$column] = max($maxLengths[$column], mb_strlen($value));
}
}
return $maxLengths;
} | php | public function normalizeColumns(array &$rows) : array
{
$maxNumColumns = 0;
// Find the max number of columns that appear in any given row
foreach ($rows as $row) {
$maxNumColumns = max($maxNumColumns, count($row));
}
$maxLengths = array_pad([], $maxNumColumns, 0);
// Normalize the number of columns in each row
foreach ($rows as &$row) {
$row = array_pad($row, $maxNumColumns, '');
}
// Get the length of the longest value in each column
foreach ($rows as &$row) {
foreach ($row as $column => &$value) {
$value = trim($value);
$maxLengths[$column] = max($maxLengths[$column], mb_strlen($value));
}
}
return $maxLengths;
} | [
"public",
"function",
"normalizeColumns",
"(",
"array",
"&",
"$",
"rows",
")",
":",
"array",
"{",
"$",
"maxNumColumns",
"=",
"0",
";",
"// Find the max number of columns that appear in any given row",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"row",
")",
"{",
"$",... | Normalizes the number of columns in each row
@param array $rows The rows to equalize
@return array The max length of each column | [
"Normalizes",
"the",
"number",
"of",
"columns",
"in",
"each",
"row"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Formatters/PaddingFormatter.php#L74-L99 |
opulencephp/Opulence | src/Opulence/Pipelines/Pipeline.php | Pipeline.createStageCallback | private function createStageCallback() : Closure
{
return function ($stages, $stage) {
return function ($input) use ($stages, $stage) {
if ($stage instanceof Closure) {
return $stage($input, $stages);
} else {
if ($this->methodToCall === null) {
throw new PipelineException('Method must not be null');
}
if (!method_exists($stage, $this->methodToCall)) {
throw new PipelineException(get_class($stage) . "::{$this->methodToCall} does not exist");
}
return $stage->{$this->methodToCall}($input, $stages);
}
};
};
} | php | private function createStageCallback() : Closure
{
return function ($stages, $stage) {
return function ($input) use ($stages, $stage) {
if ($stage instanceof Closure) {
return $stage($input, $stages);
} else {
if ($this->methodToCall === null) {
throw new PipelineException('Method must not be null');
}
if (!method_exists($stage, $this->methodToCall)) {
throw new PipelineException(get_class($stage) . "::{$this->methodToCall} does not exist");
}
return $stage->{$this->methodToCall}($input, $stages);
}
};
};
} | [
"private",
"function",
"createStageCallback",
"(",
")",
":",
"Closure",
"{",
"return",
"function",
"(",
"$",
"stages",
",",
"$",
"stage",
")",
"{",
"return",
"function",
"(",
"$",
"input",
")",
"use",
"(",
"$",
"stages",
",",
"$",
"stage",
")",
"{",
... | Creates a callback for an individual stage
@return Closure The callback
@throws PipelineException Thrown if there was a problem creating a stage | [
"Creates",
"a",
"callback",
"for",
"an",
"individual",
"stage"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Pipelines/Pipeline.php#L87-L106 |
opulencephp/Opulence | src/Opulence/Orm/Repositories/Repository.php | Repository.getFromDataMapper | protected function getFromDataMapper(string $functionName, array $args = [])
{
$entities = $this->dataMapper->$functionName(...$args);
if (is_array($entities)) {
// Passing by reference here is important because that reference may be updated in the unit of work
foreach ($entities as &$entity) {
if ($entity !== null) {
$this->unitOfWork->getEntityRegistry()->registerEntity($entity);
}
}
} elseif ($entities !== null) {
$this->unitOfWork->getEntityRegistry()->registerEntity($entities);
}
return $entities;
} | php | protected function getFromDataMapper(string $functionName, array $args = [])
{
$entities = $this->dataMapper->$functionName(...$args);
if (is_array($entities)) {
// Passing by reference here is important because that reference may be updated in the unit of work
foreach ($entities as &$entity) {
if ($entity !== null) {
$this->unitOfWork->getEntityRegistry()->registerEntity($entity);
}
}
} elseif ($entities !== null) {
$this->unitOfWork->getEntityRegistry()->registerEntity($entities);
}
return $entities;
} | [
"protected",
"function",
"getFromDataMapper",
"(",
"string",
"$",
"functionName",
",",
"array",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"$",
"entities",
"=",
"$",
"this",
"->",
"dataMapper",
"->",
"$",
"functionName",
"(",
"...",
"$",
"args",
")",
";",
"... | Performs a get query on the data mapper and adds any results as managed entities to the unit of work
@param string $functionName The name of the function to call in the data mapper
@param array $args The list of arguments to pass into the data mapper
@return object|object[] The entity or list of entities
@throws OrmException Thrown if there was an error getting the entity(ies) | [
"Performs",
"a",
"get",
"query",
"on",
"the",
"data",
"mapper",
"and",
"adds",
"any",
"results",
"as",
"managed",
"entities",
"to",
"the",
"unit",
"of",
"work"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Orm/Repositories/Repository.php#L88-L104 |
opulencephp/Opulence | src/Opulence/Console/Commands/HelpCommand.php | HelpCommand.getArgumentText | private function getArgumentText() : string
{
if (count($this->command->getArguments()) === 0) {
return ' No arguments';
}
$argumentTexts = [];
foreach ($this->command->getArguments() as $argument) {
$argumentTexts[] = [$argument->getName(), $argument->getDescription()];
}
return $this->paddingFormatter->format($argumentTexts, function ($row) {
return " <info>{$row[0]}</info> - {$row[1]}";
});
} | php | private function getArgumentText() : string
{
if (count($this->command->getArguments()) === 0) {
return ' No arguments';
}
$argumentTexts = [];
foreach ($this->command->getArguments() as $argument) {
$argumentTexts[] = [$argument->getName(), $argument->getDescription()];
}
return $this->paddingFormatter->format($argumentTexts, function ($row) {
return " <info>{$row[0]}</info> - {$row[1]}";
});
} | [
"private",
"function",
"getArgumentText",
"(",
")",
":",
"string",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"command",
"->",
"getArguments",
"(",
")",
")",
"===",
"0",
")",
"{",
"return",
"' No arguments'",
";",
"}",
"$",
"argumentTexts",
"=",
... | Converts the command arguments to text
@return string The arguments as text | [
"Converts",
"the",
"command",
"arguments",
"to",
"text"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/HelpCommand.php#L120-L135 |
opulencephp/Opulence | src/Opulence/Console/Commands/HelpCommand.php | HelpCommand.getOptionNames | private function getOptionNames(Option $option) : string
{
$optionNames = "--{$option->getName()}";
if ($option->getShortName() !== null) {
$optionNames .= "|-{$option->getShortName()}";
}
return $optionNames;
} | php | private function getOptionNames(Option $option) : string
{
$optionNames = "--{$option->getName()}";
if ($option->getShortName() !== null) {
$optionNames .= "|-{$option->getShortName()}";
}
return $optionNames;
} | [
"private",
"function",
"getOptionNames",
"(",
"Option",
"$",
"option",
")",
":",
"string",
"{",
"$",
"optionNames",
"=",
"\"--{$option->getName()}\"",
";",
"if",
"(",
"$",
"option",
"->",
"getShortName",
"(",
")",
"!==",
"null",
")",
"{",
"$",
"optionNames",... | Gets the option names as a formatted string
@param Option $option The option to convert to text
@return string The option names as text | [
"Gets",
"the",
"option",
"names",
"as",
"a",
"formatted",
"string"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/HelpCommand.php#L143-L152 |
opulencephp/Opulence | src/Opulence/Console/Commands/HelpCommand.php | HelpCommand.getOptionText | private function getOptionText() : string
{
if (count($this->command->getOptions()) === 0) {
return ' No options';
}
$optionTexts = [];
foreach ($this->command->getOptions() as $option) {
$optionTexts[] = [$this->getOptionNames($option), $option->getDescription()];
}
return $this->paddingFormatter->format($optionTexts, function ($row) {
return " <info>{$row[0]}</info> - {$row[1]}";
});
} | php | private function getOptionText() : string
{
if (count($this->command->getOptions()) === 0) {
return ' No options';
}
$optionTexts = [];
foreach ($this->command->getOptions() as $option) {
$optionTexts[] = [$this->getOptionNames($option), $option->getDescription()];
}
return $this->paddingFormatter->format($optionTexts, function ($row) {
return " <info>{$row[0]}</info> - {$row[1]}";
});
} | [
"private",
"function",
"getOptionText",
"(",
")",
":",
"string",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"command",
"->",
"getOptions",
"(",
")",
")",
"===",
"0",
")",
"{",
"return",
"' No options'",
";",
"}",
"$",
"optionTexts",
"=",
"[",
... | Gets the options as text
@return string The options as text | [
"Gets",
"the",
"options",
"as",
"text"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Commands/HelpCommand.php#L159-L174 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.flushExpressionBuffer | private function flushExpressionBuffer()
{
if ($this->expressionBuffer !== '') {
$this->tokens[] = new Token(TokenTypes::T_EXPRESSION, $this->expressionBuffer, $this->line);
// Account for all the new lines
$this->line += substr_count($this->expressionBuffer, "\n");
$this->expressionBuffer = '';
}
} | php | private function flushExpressionBuffer()
{
if ($this->expressionBuffer !== '') {
$this->tokens[] = new Token(TokenTypes::T_EXPRESSION, $this->expressionBuffer, $this->line);
// Account for all the new lines
$this->line += substr_count($this->expressionBuffer, "\n");
$this->expressionBuffer = '';
}
} | [
"private",
"function",
"flushExpressionBuffer",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"expressionBuffer",
"!==",
"''",
")",
"{",
"$",
"this",
"->",
"tokens",
"[",
"]",
"=",
"new",
"Token",
"(",
"TokenTypes",
"::",
"T_EXPRESSION",
",",
"$",
"this",... | Flushes the expression buffer | [
"Flushes",
"the",
"expression",
"buffer"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L68-L76 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.getStatementLexingMethods | private function getStatementLexingMethods() : array
{
$statements = [
$this->directiveDelimiters[0] => 'lexDirectiveStatement',
$this->sanitizedTagDelimiters[0] => 'lexSanitizedTagStatement',
$this->unsanitizedTagDelimiters[0] => 'lexUnsanitizedTagStatement',
$this->commentDelimiters[0] => 'lexCommentStatement',
'<?php' => 'lexPhpStatement',
'<?' => 'lexPhpStatement'
];
/**
* In case one delimiter is a substring of the other ("{{" and "{{!"), we want to sort the delimiters
* so that the longest delimiters come first
*/
uksort($statements, function ($a, $b) {
if (strlen($a) > strlen($b)) {
return -1;
} else {
return 1;
}
});
return $statements;
} | php | private function getStatementLexingMethods() : array
{
$statements = [
$this->directiveDelimiters[0] => 'lexDirectiveStatement',
$this->sanitizedTagDelimiters[0] => 'lexSanitizedTagStatement',
$this->unsanitizedTagDelimiters[0] => 'lexUnsanitizedTagStatement',
$this->commentDelimiters[0] => 'lexCommentStatement',
'<?php' => 'lexPhpStatement',
'<?' => 'lexPhpStatement'
];
/**
* In case one delimiter is a substring of the other ("{{" and "{{!"), we want to sort the delimiters
* so that the longest delimiters come first
*/
uksort($statements, function ($a, $b) {
if (strlen($a) > strlen($b)) {
return -1;
} else {
return 1;
}
});
return $statements;
} | [
"private",
"function",
"getStatementLexingMethods",
"(",
")",
":",
"array",
"{",
"$",
"statements",
"=",
"[",
"$",
"this",
"->",
"directiveDelimiters",
"[",
"0",
"]",
"=>",
"'lexDirectiveStatement'",
",",
"$",
"this",
"->",
"sanitizedTagDelimiters",
"[",
"0",
... | Gets a sorted mapping of opening statement delimiters to the lexing methods to call on a match
@return array The mapping of opening statement delimiters to the methods | [
"Gets",
"a",
"sorted",
"mapping",
"of",
"opening",
"statement",
"delimiters",
"to",
"the",
"lexing",
"methods",
"to",
"call",
"on",
"a",
"match"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L93-L117 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.getStream | private function getStream(int $cursor = null, int $length = null) : string
{
if ($cursor === null) {
$cursor = $this->cursor;
}
// If the cached length isn't the same or if the cursor has actually gone backwards, use the original input
if ($this->streamCache['length'] !== $length || $this->streamCache['cursor'] > $cursor) {
$this->streamCache['cursor'] = $cursor;
$this->streamCache['length'] = $length;
if ($length === null) {
$this->streamCache['stream'] = substr($this->input, $cursor);
} else {
$this->streamCache['stream'] = substr($this->input, $cursor, $length);
}
} elseif ($this->streamCache['length'] === $length && $this->streamCache['cursor'] !== $cursor) {
// Grab the substring from the cached stream
$cursorDifference = $cursor - $this->streamCache['cursor'];
if ($length === null) {
$this->streamCache['stream'] = substr($this->streamCache['stream'], $cursorDifference);
} else {
$this->streamCache['stream'] = substr($this->streamCache['stream'], $cursorDifference, $length);
}
$this->streamCache['cursor'] = $cursor;
}
return $this->streamCache['stream'];
} | php | private function getStream(int $cursor = null, int $length = null) : string
{
if ($cursor === null) {
$cursor = $this->cursor;
}
// If the cached length isn't the same or if the cursor has actually gone backwards, use the original input
if ($this->streamCache['length'] !== $length || $this->streamCache['cursor'] > $cursor) {
$this->streamCache['cursor'] = $cursor;
$this->streamCache['length'] = $length;
if ($length === null) {
$this->streamCache['stream'] = substr($this->input, $cursor);
} else {
$this->streamCache['stream'] = substr($this->input, $cursor, $length);
}
} elseif ($this->streamCache['length'] === $length && $this->streamCache['cursor'] !== $cursor) {
// Grab the substring from the cached stream
$cursorDifference = $cursor - $this->streamCache['cursor'];
if ($length === null) {
$this->streamCache['stream'] = substr($this->streamCache['stream'], $cursorDifference);
} else {
$this->streamCache['stream'] = substr($this->streamCache['stream'], $cursorDifference, $length);
}
$this->streamCache['cursor'] = $cursor;
}
return $this->streamCache['stream'];
} | [
"private",
"function",
"getStream",
"(",
"int",
"$",
"cursor",
"=",
"null",
",",
"int",
"$",
"length",
"=",
"null",
")",
":",
"string",
"{",
"if",
"(",
"$",
"cursor",
"===",
"null",
")",
"{",
"$",
"cursor",
"=",
"$",
"this",
"->",
"cursor",
";",
... | Gets the stream of input that has not yet been lexed
@param int|null $cursor The position of the cursor
@param int|null $length The length of input to return
@return string The stream of input | [
"Gets",
"the",
"stream",
"of",
"input",
"that",
"has",
"not",
"yet",
"been",
"lexed"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L126-L156 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.initializeVars | private function initializeVars(IView $view)
{
$this->directiveDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_DIRECTIVE);
$this->sanitizedTagDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_SANITIZED_TAG);
$this->unsanitizedTagDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_UNSANITIZED_TAG);
$this->commentDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_COMMENT);
// Normalize the line-endings
$this->input = str_replace(["\r\n", "\r"], "\n", $view->getContents());
$this->tokens = [];
$this->cursor = 0;
$this->line = 1;
$this->expressionBuffer = '';
} | php | private function initializeVars(IView $view)
{
$this->directiveDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_DIRECTIVE);
$this->sanitizedTagDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_SANITIZED_TAG);
$this->unsanitizedTagDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_UNSANITIZED_TAG);
$this->commentDelimiters = $view->getDelimiters(IView::DELIMITER_TYPE_COMMENT);
// Normalize the line-endings
$this->input = str_replace(["\r\n", "\r"], "\n", $view->getContents());
$this->tokens = [];
$this->cursor = 0;
$this->line = 1;
$this->expressionBuffer = '';
} | [
"private",
"function",
"initializeVars",
"(",
"IView",
"$",
"view",
")",
"{",
"$",
"this",
"->",
"directiveDelimiters",
"=",
"$",
"view",
"->",
"getDelimiters",
"(",
"IView",
"::",
"DELIMITER_TYPE_DIRECTIVE",
")",
";",
"$",
"this",
"->",
"sanitizedTagDelimiters"... | Initializes instance variables for lexing
@param IView $view The view that's being lexed | [
"Initializes",
"instance",
"variables",
"for",
"lexing"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L163-L175 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexCommentStatement | private function lexCommentStatement()
{
$this->lexDelimitedExpressionStatement(
TokenTypes::T_COMMENT_OPEN,
$this->commentDelimiters[0],
TokenTypes::T_COMMENT_CLOSE,
$this->commentDelimiters[1],
false
);
} | php | private function lexCommentStatement()
{
$this->lexDelimitedExpressionStatement(
TokenTypes::T_COMMENT_OPEN,
$this->commentDelimiters[0],
TokenTypes::T_COMMENT_CLOSE,
$this->commentDelimiters[1],
false
);
} | [
"private",
"function",
"lexCommentStatement",
"(",
")",
"{",
"$",
"this",
"->",
"lexDelimitedExpressionStatement",
"(",
"TokenTypes",
"::",
"T_COMMENT_OPEN",
",",
"$",
"this",
"->",
"commentDelimiters",
"[",
"0",
"]",
",",
"TokenTypes",
"::",
"T_COMMENT_CLOSE",
",... | Lexes a comment statement
@throws RuntimeException Thrown if the statement has an invalid token | [
"Lexes",
"a",
"comment",
"statement"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L182-L191 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexDelimitedExpression | private function lexDelimitedExpression(string $closeDelimiter)
{
$expressionBuffer = '';
$newLinesAfterExpression = 0;
while (!$this->matches($closeDelimiter, false) && !$this->atEof()) {
$currentChar = $this->getCurrentChar();
if ($currentChar === "\n") {
if (trim($expressionBuffer) === '') {
$this->line++;
} else {
$newLinesAfterExpression++;
}
}
$expressionBuffer .= $currentChar;
$this->cursor++;
}
$expressionBuffer = trim($expressionBuffer);
if ($expressionBuffer !== '') {
$this->tokens[] = new Token(
TokenTypes::T_EXPRESSION,
$this->replaceViewFunctionCalls($expressionBuffer),
$this->line
);
$this->line += $newLinesAfterExpression;
}
} | php | private function lexDelimitedExpression(string $closeDelimiter)
{
$expressionBuffer = '';
$newLinesAfterExpression = 0;
while (!$this->matches($closeDelimiter, false) && !$this->atEof()) {
$currentChar = $this->getCurrentChar();
if ($currentChar === "\n") {
if (trim($expressionBuffer) === '') {
$this->line++;
} else {
$newLinesAfterExpression++;
}
}
$expressionBuffer .= $currentChar;
$this->cursor++;
}
$expressionBuffer = trim($expressionBuffer);
if ($expressionBuffer !== '') {
$this->tokens[] = new Token(
TokenTypes::T_EXPRESSION,
$this->replaceViewFunctionCalls($expressionBuffer),
$this->line
);
$this->line += $newLinesAfterExpression;
}
} | [
"private",
"function",
"lexDelimitedExpression",
"(",
"string",
"$",
"closeDelimiter",
")",
"{",
"$",
"expressionBuffer",
"=",
"''",
";",
"$",
"newLinesAfterExpression",
"=",
"0",
";",
"while",
"(",
"!",
"$",
"this",
"->",
"matches",
"(",
"$",
"closeDelimiter"... | Lexes an expression that is delimited with tags
@param string $closeDelimiter The close delimiter | [
"Lexes",
"an",
"expression",
"that",
"is",
"delimited",
"with",
"tags"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L198-L228 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexDelimitedExpressionStatement | private function lexDelimitedExpressionStatement(
string $openTokenType,
string $openDelimiter,
string $closeTokenType,
string $closeDelimiter,
bool $closeDelimiterOptional
) {
$this->flushExpressionBuffer();
$this->tokens[] = new Token($openTokenType, $openDelimiter, $this->line);
$this->lexDelimitedExpression($closeDelimiter);
if (!$this->matches($closeDelimiter) && !$closeDelimiterOptional) {
throw new RuntimeException(
sprintf(
'Expected %s, found %s on line %d',
$closeDelimiter,
$this->getStream($this->cursor, strlen($closeDelimiter)),
$this->line
)
);
}
$this->tokens[] = new Token($closeTokenType, $closeDelimiter, $this->line);
} | php | private function lexDelimitedExpressionStatement(
string $openTokenType,
string $openDelimiter,
string $closeTokenType,
string $closeDelimiter,
bool $closeDelimiterOptional
) {
$this->flushExpressionBuffer();
$this->tokens[] = new Token($openTokenType, $openDelimiter, $this->line);
$this->lexDelimitedExpression($closeDelimiter);
if (!$this->matches($closeDelimiter) && !$closeDelimiterOptional) {
throw new RuntimeException(
sprintf(
'Expected %s, found %s on line %d',
$closeDelimiter,
$this->getStream($this->cursor, strlen($closeDelimiter)),
$this->line
)
);
}
$this->tokens[] = new Token($closeTokenType, $closeDelimiter, $this->line);
} | [
"private",
"function",
"lexDelimitedExpressionStatement",
"(",
"string",
"$",
"openTokenType",
",",
"string",
"$",
"openDelimiter",
",",
"string",
"$",
"closeTokenType",
",",
"string",
"$",
"closeDelimiter",
",",
"bool",
"$",
"closeDelimiterOptional",
")",
"{",
"$",... | Lexes a statement that is comprised of a delimited statement
@param string $openTokenType The open token type
@param string $openDelimiter The open delimiter
@param string $closeTokenType The close token type
@param string $closeDelimiter The close delimiter
@param bool $closeDelimiterOptional Whether or not the close delimiter is optional
@throws RuntimeException Thrown if the expression was not delimited correctly | [
"Lexes",
"a",
"statement",
"that",
"is",
"comprised",
"of",
"a",
"delimited",
"statement"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L240-L263 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexDirectiveExpression | private function lexDirectiveExpression()
{
$this->lexDirectiveName();
$parenthesisLevel = 0;
$newLinesAfterExpression = 0;
$expressionBuffer = '';
while (!$this->matches($this->directiveDelimiters[1], false) && !$this->atEof()) {
$currentChar = $this->getCurrentChar();
if ($currentChar === '(') {
$expressionBuffer .= $currentChar;
$parenthesisLevel++;
} elseif ($currentChar === ')') {
$parenthesisLevel--;
$expressionBuffer .= $currentChar;
} elseif ($currentChar === "\n") {
if (trim($expressionBuffer) === '') {
$this->line++;
} else {
$newLinesAfterExpression++;
}
} else {
$expressionBuffer .= $currentChar;
}
$this->cursor++;
}
if ($parenthesisLevel !== 0) {
throw new RuntimeException(
sprintf(
'Unmatched parenthesis on line %d',
$this->line
)
);
}
$expressionBuffer = trim($expressionBuffer);
$expressionBuffer = $this->replaceViewFunctionCalls($expressionBuffer);
if (!empty($expressionBuffer)) {
$this->tokens[] = new Token(TokenTypes::T_EXPRESSION, $expressionBuffer, $this->line);
}
$this->line += $newLinesAfterExpression;
} | php | private function lexDirectiveExpression()
{
$this->lexDirectiveName();
$parenthesisLevel = 0;
$newLinesAfterExpression = 0;
$expressionBuffer = '';
while (!$this->matches($this->directiveDelimiters[1], false) && !$this->atEof()) {
$currentChar = $this->getCurrentChar();
if ($currentChar === '(') {
$expressionBuffer .= $currentChar;
$parenthesisLevel++;
} elseif ($currentChar === ')') {
$parenthesisLevel--;
$expressionBuffer .= $currentChar;
} elseif ($currentChar === "\n") {
if (trim($expressionBuffer) === '') {
$this->line++;
} else {
$newLinesAfterExpression++;
}
} else {
$expressionBuffer .= $currentChar;
}
$this->cursor++;
}
if ($parenthesisLevel !== 0) {
throw new RuntimeException(
sprintf(
'Unmatched parenthesis on line %d',
$this->line
)
);
}
$expressionBuffer = trim($expressionBuffer);
$expressionBuffer = $this->replaceViewFunctionCalls($expressionBuffer);
if (!empty($expressionBuffer)) {
$this->tokens[] = new Token(TokenTypes::T_EXPRESSION, $expressionBuffer, $this->line);
}
$this->line += $newLinesAfterExpression;
} | [
"private",
"function",
"lexDirectiveExpression",
"(",
")",
"{",
"$",
"this",
"->",
"lexDirectiveName",
"(",
")",
";",
"$",
"parenthesisLevel",
"=",
"0",
";",
"$",
"newLinesAfterExpression",
"=",
"0",
";",
"$",
"expressionBuffer",
"=",
"''",
";",
"while",
"("... | Lexes a directive statement
@throws RuntimeException Thrown if there's an unmatched parenthesis | [
"Lexes",
"a",
"directive",
"statement"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L270-L317 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexDirectiveName | private function lexDirectiveName()
{
$name = '';
$newLinesAfterName = 0;
// Loop while there's still a directive name or until we encounter the first space after the name
do {
$currentChar = $this->getCurrentChar();
// Handle new line characters between directive delimiters
if ($currentChar === "\n") {
if (trim($name) === '') {
$this->line++;
} else {
$newLinesAfterName++;
}
}
$name .= $currentChar;
$this->cursor++;
} while (
preg_match("/^[a-zA-Z0-9_\s]$/", $this->getCurrentChar()) === 1 &&
($this->getCurrentChar() !== ' ' || trim($name) === '')
);
$name = trim($name);
if ($name === '') {
throw new RuntimeException(
sprintf(
'Expected %s on line %d, none found',
TokenTypes::T_DIRECTIVE_NAME,
$this->line
)
);
}
$this->tokens[] = new Token(TokenTypes::T_DIRECTIVE_NAME, $name, $this->line);
$this->line += $newLinesAfterName;
} | php | private function lexDirectiveName()
{
$name = '';
$newLinesAfterName = 0;
// Loop while there's still a directive name or until we encounter the first space after the name
do {
$currentChar = $this->getCurrentChar();
// Handle new line characters between directive delimiters
if ($currentChar === "\n") {
if (trim($name) === '') {
$this->line++;
} else {
$newLinesAfterName++;
}
}
$name .= $currentChar;
$this->cursor++;
} while (
preg_match("/^[a-zA-Z0-9_\s]$/", $this->getCurrentChar()) === 1 &&
($this->getCurrentChar() !== ' ' || trim($name) === '')
);
$name = trim($name);
if ($name === '') {
throw new RuntimeException(
sprintf(
'Expected %s on line %d, none found',
TokenTypes::T_DIRECTIVE_NAME,
$this->line
)
);
}
$this->tokens[] = new Token(TokenTypes::T_DIRECTIVE_NAME, $name, $this->line);
$this->line += $newLinesAfterName;
} | [
"private",
"function",
"lexDirectiveName",
"(",
")",
"{",
"$",
"name",
"=",
"''",
";",
"$",
"newLinesAfterName",
"=",
"0",
";",
"// Loop while there's still a directive name or until we encounter the first space after the name",
"do",
"{",
"$",
"currentChar",
"=",
"$",
... | Lexes a directive name
@throws RuntimeException Thrown if the directive did not have a name | [
"Lexes",
"a",
"directive",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L324-L363 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexDirectiveStatement | private function lexDirectiveStatement()
{
$this->flushExpressionBuffer();
$this->tokens[] = new Token(TokenTypes::T_DIRECTIVE_OPEN, $this->directiveDelimiters[0], $this->line);
$this->lexDirectiveExpression();
if (!$this->matches($this->directiveDelimiters[1])) {
throw new RuntimeException(
sprintf(
'Expected %s, found %s on line %d',
$this->directiveDelimiters[1],
$this->getStream($this->cursor, strlen($this->directiveDelimiters[1])),
$this->line
)
);
}
$this->tokens[] = new Token(TokenTypes::T_DIRECTIVE_CLOSE, $this->directiveDelimiters[1], $this->line);
} | php | private function lexDirectiveStatement()
{
$this->flushExpressionBuffer();
$this->tokens[] = new Token(TokenTypes::T_DIRECTIVE_OPEN, $this->directiveDelimiters[0], $this->line);
$this->lexDirectiveExpression();
if (!$this->matches($this->directiveDelimiters[1])) {
throw new RuntimeException(
sprintf(
'Expected %s, found %s on line %d',
$this->directiveDelimiters[1],
$this->getStream($this->cursor, strlen($this->directiveDelimiters[1])),
$this->line
)
);
}
$this->tokens[] = new Token(TokenTypes::T_DIRECTIVE_CLOSE, $this->directiveDelimiters[1], $this->line);
} | [
"private",
"function",
"lexDirectiveStatement",
"(",
")",
"{",
"$",
"this",
"->",
"flushExpressionBuffer",
"(",
")",
";",
"$",
"this",
"->",
"tokens",
"[",
"]",
"=",
"new",
"Token",
"(",
"TokenTypes",
"::",
"T_DIRECTIVE_OPEN",
",",
"$",
"this",
"->",
"dire... | Lexes a directive statement
@throws RuntimeException Thrown if the statement has an invalid token | [
"Lexes",
"a",
"directive",
"statement"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L370-L388 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexExpression | private function lexExpression()
{
$statementMethods = $this->getStatementLexingMethods();
while (!$this->atEof()) {
reset($statementMethods);
$matchedStatement = false;
// This is essentially a foreach loop that can be reset
while (list($statementOpenDelimiter, $methodName) = each($statementMethods)) {
if ($this->matches($statementOpenDelimiter)) {
// This is an unescaped statement
$matchedStatement = true;
$this->{$methodName}();
// Now that we've matched, we want to reset the loop so that longest delimiters are matched first
reset($statementMethods);
} elseif ($this->getCurrentChar() === '\\') {
// Now that we know we're on an escape character, spend the resources to check for a match
if ($this->matches("\\$statementOpenDelimiter")) {
// This is an escaped statement
$this->expressionBuffer .= $statementOpenDelimiter;
}
}
}
// Handle any text outside statements
if (!$matchedStatement && !$this->atEof()) {
$currentChar = $this->getCurrentChar();
$this->expressionBuffer .= $currentChar;
$this->cursor++;
// Keep on going if we're seeing alphanumeric text
while (ctype_alnum($this->getCurrentChar())) {
$currentChar = $this->getCurrentChar();
$this->expressionBuffer .= $currentChar;
$this->cursor++;
}
} else {
$this->flushExpressionBuffer();
}
}
// Flush anything left over in the buffer
$this->flushExpressionBuffer();
} | php | private function lexExpression()
{
$statementMethods = $this->getStatementLexingMethods();
while (!$this->atEof()) {
reset($statementMethods);
$matchedStatement = false;
// This is essentially a foreach loop that can be reset
while (list($statementOpenDelimiter, $methodName) = each($statementMethods)) {
if ($this->matches($statementOpenDelimiter)) {
// This is an unescaped statement
$matchedStatement = true;
$this->{$methodName}();
// Now that we've matched, we want to reset the loop so that longest delimiters are matched first
reset($statementMethods);
} elseif ($this->getCurrentChar() === '\\') {
// Now that we know we're on an escape character, spend the resources to check for a match
if ($this->matches("\\$statementOpenDelimiter")) {
// This is an escaped statement
$this->expressionBuffer .= $statementOpenDelimiter;
}
}
}
// Handle any text outside statements
if (!$matchedStatement && !$this->atEof()) {
$currentChar = $this->getCurrentChar();
$this->expressionBuffer .= $currentChar;
$this->cursor++;
// Keep on going if we're seeing alphanumeric text
while (ctype_alnum($this->getCurrentChar())) {
$currentChar = $this->getCurrentChar();
$this->expressionBuffer .= $currentChar;
$this->cursor++;
}
} else {
$this->flushExpressionBuffer();
}
}
// Flush anything left over in the buffer
$this->flushExpressionBuffer();
} | [
"private",
"function",
"lexExpression",
"(",
")",
"{",
"$",
"statementMethods",
"=",
"$",
"this",
"->",
"getStatementLexingMethods",
"(",
")",
";",
"while",
"(",
"!",
"$",
"this",
"->",
"atEof",
"(",
")",
")",
"{",
"reset",
"(",
"$",
"statementMethods",
... | Lexes an expression
@throws RuntimeException Thrown if there was an invalid token | [
"Lexes",
"an",
"expression"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L395-L440 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexSanitizedTagStatement | private function lexSanitizedTagStatement()
{
$this->lexDelimitedExpressionStatement(
TokenTypes::T_SANITIZED_TAG_OPEN,
$this->sanitizedTagDelimiters[0],
TokenTypes::T_SANITIZED_TAG_CLOSE,
$this->sanitizedTagDelimiters[1],
false
);
} | php | private function lexSanitizedTagStatement()
{
$this->lexDelimitedExpressionStatement(
TokenTypes::T_SANITIZED_TAG_OPEN,
$this->sanitizedTagDelimiters[0],
TokenTypes::T_SANITIZED_TAG_CLOSE,
$this->sanitizedTagDelimiters[1],
false
);
} | [
"private",
"function",
"lexSanitizedTagStatement",
"(",
")",
"{",
"$",
"this",
"->",
"lexDelimitedExpressionStatement",
"(",
"TokenTypes",
"::",
"T_SANITIZED_TAG_OPEN",
",",
"$",
"this",
"->",
"sanitizedTagDelimiters",
"[",
"0",
"]",
",",
"TokenTypes",
"::",
"T_SANI... | Lexes a sanitized tag statement
@throws RuntimeException Thrown if the statement has an invalid token | [
"Lexes",
"a",
"sanitized",
"tag",
"statement"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L463-L472 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.lexUnsanitizedTagStatement | private function lexUnsanitizedTagStatement()
{
$this->lexDelimitedExpressionStatement(
TokenTypes::T_UNSANITIZED_TAG_OPEN,
$this->unsanitizedTagDelimiters[0],
TokenTypes::T_UNSANITIZED_TAG_CLOSE,
$this->unsanitizedTagDelimiters[1],
false
);
} | php | private function lexUnsanitizedTagStatement()
{
$this->lexDelimitedExpressionStatement(
TokenTypes::T_UNSANITIZED_TAG_OPEN,
$this->unsanitizedTagDelimiters[0],
TokenTypes::T_UNSANITIZED_TAG_CLOSE,
$this->unsanitizedTagDelimiters[1],
false
);
} | [
"private",
"function",
"lexUnsanitizedTagStatement",
"(",
")",
"{",
"$",
"this",
"->",
"lexDelimitedExpressionStatement",
"(",
"TokenTypes",
"::",
"T_UNSANITIZED_TAG_OPEN",
",",
"$",
"this",
"->",
"unsanitizedTagDelimiters",
"[",
"0",
"]",
",",
"TokenTypes",
"::",
"... | Lexes an unsanitized tag statement
@throws RuntimeException Thrown if the statement has an invalid token | [
"Lexes",
"an",
"unsanitized",
"tag",
"statement"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L479-L488 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.matches | private function matches(string $expected, bool $shouldConsume = true, int $cursor = null) : bool
{
$stream = $this->getStream($cursor);
$expectedLength = strlen($expected);
if (substr($stream, 0, $expectedLength) == $expected) {
if ($shouldConsume) {
$this->cursor += $expectedLength;
}
return true;
}
return false;
} | php | private function matches(string $expected, bool $shouldConsume = true, int $cursor = null) : bool
{
$stream = $this->getStream($cursor);
$expectedLength = strlen($expected);
if (substr($stream, 0, $expectedLength) == $expected) {
if ($shouldConsume) {
$this->cursor += $expectedLength;
}
return true;
}
return false;
} | [
"private",
"function",
"matches",
"(",
"string",
"$",
"expected",
",",
"bool",
"$",
"shouldConsume",
"=",
"true",
",",
"int",
"$",
"cursor",
"=",
"null",
")",
":",
"bool",
"{",
"$",
"stream",
"=",
"$",
"this",
"->",
"getStream",
"(",
"$",
"cursor",
"... | Gets whether or not the input at the cursor matches an expected value
@param string $expected The expected string
@param bool $shouldConsume Whether or not to consume the expected value on a match
@param int|null $cursor The cursor position to match at
@return bool True if the input at the cursor matches the expected value, otherwise false | [
"Gets",
"whether",
"or",
"not",
"the",
"input",
"at",
"the",
"cursor",
"matches",
"an",
"expected",
"value"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L498-L512 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php | Lexer.replaceViewFunctionCalls | private function replaceViewFunctionCalls(string $expression) : string
{
$phpTokens = token_get_all('<?php ' . $expression . ' ?>');
$opulenceTokens = [];
// This is essentially a foreach loop that can be fast-forwarded
while (list($index, $token) = each($phpTokens)) {
if (is_string($token)) {
// Convert the simple token to an array for uniformity
$opulenceTokens[] = [T_STRING, $token, 0];
continue;
}
switch ($token[0]) {
case T_STRING:
// If this is a function
if (count($phpTokens) > $index && $phpTokens[$index + 1] === '(') {
$prevToken = $index > 0 ? $phpTokens[$index - 1] : null;
// If this is a native PHP function or is really a method call, don't convert it
if (
(
($prevToken[0] === T_OBJECT_OPERATOR || $prevToken[0] === T_DOUBLE_COLON) &&
is_array($prevToken)
) ||
function_exists($token[1])
) {
$opulenceTokens[] = $token;
} else {
// This is a view function
// Add $__opulenceFortuneTranspiler
$opulenceTokens[] = [T_VARIABLE, '$__opulenceFortuneTranspiler', $token[2]];
// Add ->
$opulenceTokens[] = [T_OBJECT_OPERATOR, '->', $token[2]];
// Add callViewFunction("FUNCTION_NAME")
$opulenceTokens[] = [T_STRING, 'callViewFunction("' . $token[1] . '")', $token[2]];
}
} else {
$opulenceTokens[] = $token;
}
break;
default:
$opulenceTokens[] = $token;
break;
}
}
// Remove php open/close PHP tags
array_shift($opulenceTokens);
array_pop($opulenceTokens);
// Rejoin the tokens
$joinedTokens = implode('', array_column($opulenceTokens, 1));
$replacementCount = 0;
$callback = function (array $matches) {
if ($matches[2] === ')') {
// There were no parameters
return $matches[1] . ')';
} else {
// There were parameters
return $matches[1] . ', ' . $matches[2];
}
};
/**
* View functions are left in a broken state
* For example, 'foo()' will currently look like '...->callViewFunction("foo")()'
* This should be converted to '...->callViewFunction("foo")'
* Similarly, 'foo("bar")' will currently look like '...->callViewFunction("foo")("bar")'
* This should be converted to '...->callViewFunction("foo", "bar")'
*/
do {
$joinedTokens = preg_replace_callback(
'/(\$__opulenceFortuneTranspiler->callViewFunction\([^\)]+)\)\((.)/',
$callback,
$joinedTokens,
-1,
$replacementCount
);
} while ($replacementCount > 0);
return trim($joinedTokens);
} | php | private function replaceViewFunctionCalls(string $expression) : string
{
$phpTokens = token_get_all('<?php ' . $expression . ' ?>');
$opulenceTokens = [];
// This is essentially a foreach loop that can be fast-forwarded
while (list($index, $token) = each($phpTokens)) {
if (is_string($token)) {
// Convert the simple token to an array for uniformity
$opulenceTokens[] = [T_STRING, $token, 0];
continue;
}
switch ($token[0]) {
case T_STRING:
// If this is a function
if (count($phpTokens) > $index && $phpTokens[$index + 1] === '(') {
$prevToken = $index > 0 ? $phpTokens[$index - 1] : null;
// If this is a native PHP function or is really a method call, don't convert it
if (
(
($prevToken[0] === T_OBJECT_OPERATOR || $prevToken[0] === T_DOUBLE_COLON) &&
is_array($prevToken)
) ||
function_exists($token[1])
) {
$opulenceTokens[] = $token;
} else {
// This is a view function
// Add $__opulenceFortuneTranspiler
$opulenceTokens[] = [T_VARIABLE, '$__opulenceFortuneTranspiler', $token[2]];
// Add ->
$opulenceTokens[] = [T_OBJECT_OPERATOR, '->', $token[2]];
// Add callViewFunction("FUNCTION_NAME")
$opulenceTokens[] = [T_STRING, 'callViewFunction("' . $token[1] . '")', $token[2]];
}
} else {
$opulenceTokens[] = $token;
}
break;
default:
$opulenceTokens[] = $token;
break;
}
}
// Remove php open/close PHP tags
array_shift($opulenceTokens);
array_pop($opulenceTokens);
// Rejoin the tokens
$joinedTokens = implode('', array_column($opulenceTokens, 1));
$replacementCount = 0;
$callback = function (array $matches) {
if ($matches[2] === ')') {
// There were no parameters
return $matches[1] . ')';
} else {
// There were parameters
return $matches[1] . ', ' . $matches[2];
}
};
/**
* View functions are left in a broken state
* For example, 'foo()' will currently look like '...->callViewFunction("foo")()'
* This should be converted to '...->callViewFunction("foo")'
* Similarly, 'foo("bar")' will currently look like '...->callViewFunction("foo")("bar")'
* This should be converted to '...->callViewFunction("foo", "bar")'
*/
do {
$joinedTokens = preg_replace_callback(
'/(\$__opulenceFortuneTranspiler->callViewFunction\([^\)]+)\)\((.)/',
$callback,
$joinedTokens,
-1,
$replacementCount
);
} while ($replacementCount > 0);
return trim($joinedTokens);
} | [
"private",
"function",
"replaceViewFunctionCalls",
"(",
"string",
"$",
"expression",
")",
":",
"string",
"{",
"$",
"phpTokens",
"=",
"token_get_all",
"(",
"'<?php '",
".",
"$",
"expression",
".",
"' ?>'",
")",
";",
"$",
"opulenceTokens",
"=",
"[",
"]",
";",
... | Replaces view function calls with valid PHP calls
@param string $expression The expression to replace calls in
@return string The expression with replaced calls | [
"Replaces",
"view",
"function",
"calls",
"with",
"valid",
"PHP",
"calls"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/Lexers/Lexer.php#L520-L606 |
opulencephp/Opulence | src/Opulence/Http/Responses/Response.php | Response.sendHeaders | public function sendHeaders()
{
if (!$this->headersAreSent()) {
header(
sprintf(
'HTTP/%s %s %s',
$this->httpVersion,
$this->statusCode,
$this->statusText
),
true,
$this->statusCode
);
// Send the headers
foreach ($this->headers->getAll() as $name => $values) {
// Headers are allowed to have multiple values
foreach ($values as $value) {
header("$name:$value", false, $this->statusCode);
}
}
// Send the cookies
/** @var Cookie $cookie */
foreach ($this->headers->getCookies(true) as $cookie) {
setcookie(
$cookie->getName(),
$cookie->getValue(),
$cookie->getExpiration(),
$cookie->getPath(),
$cookie->getDomain(),
$cookie->isSecure(),
$cookie->isHttpOnly()
);
}
}
} | php | public function sendHeaders()
{
if (!$this->headersAreSent()) {
header(
sprintf(
'HTTP/%s %s %s',
$this->httpVersion,
$this->statusCode,
$this->statusText
),
true,
$this->statusCode
);
// Send the headers
foreach ($this->headers->getAll() as $name => $values) {
// Headers are allowed to have multiple values
foreach ($values as $value) {
header("$name:$value", false, $this->statusCode);
}
}
// Send the cookies
/** @var Cookie $cookie */
foreach ($this->headers->getCookies(true) as $cookie) {
setcookie(
$cookie->getName(),
$cookie->getValue(),
$cookie->getExpiration(),
$cookie->getPath(),
$cookie->getDomain(),
$cookie->isSecure(),
$cookie->isHttpOnly()
);
}
}
} | [
"public",
"function",
"sendHeaders",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"headersAreSent",
"(",
")",
")",
"{",
"header",
"(",
"sprintf",
"(",
"'HTTP/%s %s %s'",
",",
"$",
"this",
"->",
"httpVersion",
",",
"$",
"this",
"->",
"statusCode",
... | Sends the headers if they haven't already been sent | [
"Sends",
"the",
"headers",
"if",
"they",
"haven",
"t",
"already",
"been",
"sent"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Responses/Response.php#L111-L147 |
opulencephp/Opulence | src/Opulence/Http/Responses/Response.php | Response.setStatusCode | public function setStatusCode(int $statusCode, string $statusText = null)
{
$this->statusCode = $statusCode;
if ($statusText === null && isset(ResponseHeaders::$statusTexts[$statusCode])) {
$this->statusText = ResponseHeaders::$statusTexts[$statusCode];
} else {
$this->statusText = $statusText;
}
} | php | public function setStatusCode(int $statusCode, string $statusText = null)
{
$this->statusCode = $statusCode;
if ($statusText === null && isset(ResponseHeaders::$statusTexts[$statusCode])) {
$this->statusText = ResponseHeaders::$statusTexts[$statusCode];
} else {
$this->statusText = $statusText;
}
} | [
"public",
"function",
"setStatusCode",
"(",
"int",
"$",
"statusCode",
",",
"string",
"$",
"statusText",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"statusCode",
"=",
"$",
"statusCode",
";",
"if",
"(",
"$",
"statusText",
"===",
"null",
"&&",
"isset",
"(",
... | Sets the status code
@param int $statusCode The HTTP status code
@param string|null $statusText The status text
If null, the default text is used for the input code | [
"Sets",
"the",
"status",
"code"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Responses/Response.php#L182-L191 |
opulencephp/Opulence | src/Opulence/Http/Responses/ResponseHeaders.php | ResponseHeaders.deleteCookie | public function deleteCookie(
string $name,
string $path = '/',
string $domain = '',
bool $isSecure = false,
bool $isHttpOnly = true
) {
// Remove the cookie from the response
$this->setCookie(new Cookie($name, '', 0, $path, $domain, $isSecure, $isHttpOnly));
} | php | public function deleteCookie(
string $name,
string $path = '/',
string $domain = '',
bool $isSecure = false,
bool $isHttpOnly = true
) {
// Remove the cookie from the response
$this->setCookie(new Cookie($name, '', 0, $path, $domain, $isSecure, $isHttpOnly));
} | [
"public",
"function",
"deleteCookie",
"(",
"string",
"$",
"name",
",",
"string",
"$",
"path",
"=",
"'/'",
",",
"string",
"$",
"domain",
"=",
"''",
",",
"bool",
"$",
"isSecure",
"=",
"false",
",",
"bool",
"$",
"isHttpOnly",
"=",
"true",
")",
"{",
"// ... | Deletes a cookie in the response header
@param string $name The name of the cookie to delete
@param string $path The path the cookie is valid on
@param string $domain The domain the cookie is valid on
@param bool $isSecure Whether or not the cookie was secure
@param bool $isHttpOnly Whether or not the cookie was HTTP-only | [
"Deletes",
"a",
"cookie",
"in",
"the",
"response",
"header"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Responses/ResponseHeaders.php#L183-L192 |
opulencephp/Opulence | src/Opulence/Http/Responses/ResponseHeaders.php | ResponseHeaders.getCookies | public function getCookies(bool $includeDeletedCookies = false) : array
{
$cookies = [];
foreach ($this->cookies as $domain => $cookiesByDomain) {
foreach ($cookiesByDomain as $path => $cookiesByPath) {
/**
* @var string $name
* @var Cookie $cookie
*/
foreach ($cookiesByPath as $name => $cookie) {
// Only include active cookies
if ($includeDeletedCookies || $cookie->getExpiration() >= time()) {
$cookies[] = $cookie;
}
}
}
}
return $cookies;
} | php | public function getCookies(bool $includeDeletedCookies = false) : array
{
$cookies = [];
foreach ($this->cookies as $domain => $cookiesByDomain) {
foreach ($cookiesByDomain as $path => $cookiesByPath) {
/**
* @var string $name
* @var Cookie $cookie
*/
foreach ($cookiesByPath as $name => $cookie) {
// Only include active cookies
if ($includeDeletedCookies || $cookie->getExpiration() >= time()) {
$cookies[] = $cookie;
}
}
}
}
return $cookies;
} | [
"public",
"function",
"getCookies",
"(",
"bool",
"$",
"includeDeletedCookies",
"=",
"false",
")",
":",
"array",
"{",
"$",
"cookies",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"cookies",
"as",
"$",
"domain",
"=>",
"$",
"cookiesByDomain",
")",... | Gets a list of all the active cookies
@param bool $includeDeletedCookies Whether or not to include deleted cookies
@return Cookie[] The list of all the set cookies | [
"Gets",
"a",
"list",
"of",
"all",
"the",
"active",
"cookies"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Responses/ResponseHeaders.php#L200-L220 |
opulencephp/Opulence | src/Opulence/Http/Responses/ResponseHeaders.php | ResponseHeaders.setCookie | public function setCookie(Cookie $cookie)
{
$this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
} | php | public function setCookie(Cookie $cookie)
{
$this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
} | [
"public",
"function",
"setCookie",
"(",
"Cookie",
"$",
"cookie",
")",
"{",
"$",
"this",
"->",
"cookies",
"[",
"$",
"cookie",
"->",
"getDomain",
"(",
")",
"]",
"[",
"$",
"cookie",
"->",
"getPath",
"(",
")",
"]",
"[",
"$",
"cookie",
"->",
"getName",
... | Sets a cookie
@param Cookie $cookie The cookie to set | [
"Sets",
"a",
"cookie"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Responses/ResponseHeaders.php#L227-L230 |
opulencephp/Opulence | src/Opulence/Framework/Configuration/Config.php | Config.get | public static function get(string $category, string $setting, $default = null)
{
if (!isset(self::$settings[$category][$setting])) {
return $default;
}
return self::$settings[$category][$setting];
} | php | public static function get(string $category, string $setting, $default = null)
{
if (!isset(self::$settings[$category][$setting])) {
return $default;
}
return self::$settings[$category][$setting];
} | [
"public",
"static",
"function",
"get",
"(",
"string",
"$",
"category",
",",
"string",
"$",
"setting",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"settings",
"[",
"$",
"category",
"]",
"[",
"$",
"set... | Gets a setting
@param string $category The category of setting to get
@param string $setting The name of the setting to get
@param null $default The default value if one does not exist
@return mixed The value of the setting | [
"Gets",
"a",
"setting"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Configuration/Config.php#L29-L36 |
opulencephp/Opulence | src/Opulence/Framework/Configuration/Config.php | Config.has | public static function has(string $category, string $setting) : bool
{
return isset(self::$settings[$category]) && isset(self::$settings[$category][$setting]);
} | php | public static function has(string $category, string $setting) : bool
{
return isset(self::$settings[$category]) && isset(self::$settings[$category][$setting]);
} | [
"public",
"static",
"function",
"has",
"(",
"string",
"$",
"category",
",",
"string",
"$",
"setting",
")",
":",
"bool",
"{",
"return",
"isset",
"(",
"self",
"::",
"$",
"settings",
"[",
"$",
"category",
"]",
")",
"&&",
"isset",
"(",
"self",
"::",
"$",... | Gets whether or not a setting has a value
@param string $category The category whose setting we're checking
@param string $setting The setting to check for
@return bool True if the setting exists, otherwise false | [
"Gets",
"whether",
"or",
"not",
"a",
"setting",
"has",
"a",
"value"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Configuration/Config.php#L45-L48 |
opulencephp/Opulence | src/Opulence/Framework/Configuration/Config.php | Config.set | public static function set(string $category, string $setting, $value)
{
if (!isset(self::$settings[$category])) {
self::$settings[$category] = [];
}
self::$settings[$category][$setting] = $value;
} | php | public static function set(string $category, string $setting, $value)
{
if (!isset(self::$settings[$category])) {
self::$settings[$category] = [];
}
self::$settings[$category][$setting] = $value;
} | [
"public",
"static",
"function",
"set",
"(",
"string",
"$",
"category",
",",
"string",
"$",
"setting",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"settings",
"[",
"$",
"category",
"]",
")",
")",
"{",
"self",
"::",
... | Sets a setting
@param string $category The category whose setting we're changing
@param string $setting The name of the setting to set
@param mixed $value The value of the setting | [
"Sets",
"a",
"setting"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Framework/Configuration/Config.php#L57-L64 |
opulencephp/Opulence | src/Opulence/Authentication/Tokens/Signatures/Factories/SignerFactory.php | SignerFactory.createSigner | public function createSigner(string $algorithm, $publicKey, $privateKey = null) : ISigner
{
if (!is_string($publicKey) && !is_resource($publicKey)) {
throw new InvalidArgumentException('Public key must either be a string or a resource');
}
if ($this->algorithmIsSymmetric($algorithm)) {
return new HmacSigner($algorithm, $publicKey);
} else {
if (!is_string($privateKey) && !is_resource($privateKey)) {
throw new InvalidArgumentException('Must specify private key for asymmetric algorithms');
}
return new RsaSsaPkcsSigner($algorithm, $publicKey, $privateKey);
}
} | php | public function createSigner(string $algorithm, $publicKey, $privateKey = null) : ISigner
{
if (!is_string($publicKey) && !is_resource($publicKey)) {
throw new InvalidArgumentException('Public key must either be a string or a resource');
}
if ($this->algorithmIsSymmetric($algorithm)) {
return new HmacSigner($algorithm, $publicKey);
} else {
if (!is_string($privateKey) && !is_resource($privateKey)) {
throw new InvalidArgumentException('Must specify private key for asymmetric algorithms');
}
return new RsaSsaPkcsSigner($algorithm, $publicKey, $privateKey);
}
} | [
"public",
"function",
"createSigner",
"(",
"string",
"$",
"algorithm",
",",
"$",
"publicKey",
",",
"$",
"privateKey",
"=",
"null",
")",
":",
"ISigner",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"publicKey",
")",
"&&",
"!",
"is_resource",
"(",
"$",
"p... | Creates a signer with the input algorithm
@param string $algorithm The algorithm to use (one of the Algorithms constants)
@param string|resource $publicKey The public key to sign data with
@param string|resource|null $privateKey The private key to sign data with (required for asymmetric algorithms)
@return ISigner The signer
@throws InvalidArgumentException Thrown if the keys are not in a valid format | [
"Creates",
"a",
"signer",
"with",
"the",
"input",
"algorithm"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Tokens/Signatures/Factories/SignerFactory.php#L33-L48 |
opulencephp/Opulence | src/Opulence/Authentication/Tokens/Signatures/Factories/SignerFactory.php | SignerFactory.algorithmIsSymmetric | private function algorithmIsSymmetric(string $algorithm) : bool
{
return in_array($algorithm, [Algorithms::SHA256, Algorithms::SHA384, Algorithms::SHA512]);
} | php | private function algorithmIsSymmetric(string $algorithm) : bool
{
return in_array($algorithm, [Algorithms::SHA256, Algorithms::SHA384, Algorithms::SHA512]);
} | [
"private",
"function",
"algorithmIsSymmetric",
"(",
"string",
"$",
"algorithm",
")",
":",
"bool",
"{",
"return",
"in_array",
"(",
"$",
"algorithm",
",",
"[",
"Algorithms",
"::",
"SHA256",
",",
"Algorithms",
"::",
"SHA384",
",",
"Algorithms",
"::",
"SHA512",
... | Gets whether or not an algorithm is symmetric
@param string $algorithm The algorithm to check
@return bool True if the algorithm is symmetric, otherwise false | [
"Gets",
"whether",
"or",
"not",
"an",
"algorithm",
"is",
"symmetric"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Tokens/Signatures/Factories/SignerFactory.php#L56-L59 |
opulencephp/Opulence | src/Opulence/Views/Compilers/CompilerRegistry.php | CompilerRegistry.getExtension | protected function getExtension(IView $view) : string
{
// Find a registered extension that the view's path ends with
foreach (array_keys($this->compilers) as $extension) {
$lengthDifference = strlen($view->getPath()) - strlen($extension);
if ($lengthDifference >= 0 && strpos($view->getPath(), $extension, $lengthDifference) !== false) {
return $extension;
}
}
throw new InvalidArgumentException("No extension registered for path \"{$view->getPath()}\"");
} | php | protected function getExtension(IView $view) : string
{
// Find a registered extension that the view's path ends with
foreach (array_keys($this->compilers) as $extension) {
$lengthDifference = strlen($view->getPath()) - strlen($extension);
if ($lengthDifference >= 0 && strpos($view->getPath(), $extension, $lengthDifference) !== false) {
return $extension;
}
}
throw new InvalidArgumentException("No extension registered for path \"{$view->getPath()}\"");
} | [
"protected",
"function",
"getExtension",
"(",
"IView",
"$",
"view",
")",
":",
"string",
"{",
"// Find a registered extension that the view's path ends with",
"foreach",
"(",
"array_keys",
"(",
"$",
"this",
"->",
"compilers",
")",
"as",
"$",
"extension",
")",
"{",
... | Gets the extension for a view
@param IView $view The view whose extension we're getting
@return string The view's extension
@throws InvalidArgumentException Thrown if no extension was found | [
"Gets",
"the",
"extension",
"for",
"a",
"view"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/CompilerRegistry.php#L53-L65 |
opulencephp/Opulence | src/Opulence/Authentication/Tokens/JsonWebTokens/JwtPayload.php | JwtPayload.add | public function add(string $name, $value)
{
if (in_array($name, ['exp', 'nbf', 'iat']) && is_int($value)) {
$value = DateTimeImmutable::createFromFormat('U', $value);
}
$this->claims[$name] = $value;
} | php | public function add(string $name, $value)
{
if (in_array($name, ['exp', 'nbf', 'iat']) && is_int($value)) {
$value = DateTimeImmutable::createFromFormat('U', $value);
}
$this->claims[$name] = $value;
} | [
"public",
"function",
"add",
"(",
"string",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"[",
"'exp'",
",",
"'nbf'",
",",
"'iat'",
"]",
")",
"&&",
"is_int",
"(",
"$",
"value",
")",
")",
"{",
"$",
"valu... | Adds an extra claim
@param string $name The name of the claim to add
@param mixed $value The value to add | [
"Adds",
"an",
"extra",
"claim"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Tokens/JsonWebTokens/JwtPayload.php#L57-L64 |
opulencephp/Opulence | src/Opulence/Authentication/Tokens/JsonWebTokens/JwtPayload.php | JwtPayload.get | public function get(string $name)
{
$claims = $this->getAll();
if (!array_key_exists($name, $claims)) {
return null;
}
return $claims[$name];
} | php | public function get(string $name)
{
$claims = $this->getAll();
if (!array_key_exists($name, $claims)) {
return null;
}
return $claims[$name];
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
")",
"{",
"$",
"claims",
"=",
"$",
"this",
"->",
"getAll",
"(",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"claims",
")",
")",
"{",
"return",
"null",
";",
"}"... | Gets the value for a claim
@param string $name The name of the claim to get
@return mixed|null The value of the claim if it exists, otherwise null | [
"Gets",
"the",
"value",
"for",
"a",
"claim"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Tokens/JsonWebTokens/JwtPayload.php#L82-L91 |
opulencephp/Opulence | src/Opulence/Authentication/Tokens/JsonWebTokens/JwtPayload.php | JwtPayload.getAll | public function getAll() : array
{
$convertedClaims = [];
$timeFields = ['exp', 'nbf', 'iat'];
// Convert date times to timestamps
foreach ($this->claims as $name => $value) {
if ($value !== null && in_array($name, $timeFields)) {
/** @var DateTimeImmutable $value */
$value = $value->getTimestamp();
}
$convertedClaims[$name] = $value;
}
if (!isset($this->claims['jti'])) {
$convertedClaims['jti'] = $this->getId();
}
return $convertedClaims;
} | php | public function getAll() : array
{
$convertedClaims = [];
$timeFields = ['exp', 'nbf', 'iat'];
// Convert date times to timestamps
foreach ($this->claims as $name => $value) {
if ($value !== null && in_array($name, $timeFields)) {
/** @var DateTimeImmutable $value */
$value = $value->getTimestamp();
}
$convertedClaims[$name] = $value;
}
if (!isset($this->claims['jti'])) {
$convertedClaims['jti'] = $this->getId();
}
return $convertedClaims;
} | [
"public",
"function",
"getAll",
"(",
")",
":",
"array",
"{",
"$",
"convertedClaims",
"=",
"[",
"]",
";",
"$",
"timeFields",
"=",
"[",
"'exp'",
",",
"'nbf'",
",",
"'iat'",
"]",
";",
"// Convert date times to timestamps",
"foreach",
"(",
"$",
"this",
"->",
... | Gets the value for all the claims
@return array The mapping of set claims to their values | [
"Gets",
"the",
"value",
"for",
"all",
"the",
"claims"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Tokens/JsonWebTokens/JwtPayload.php#L98-L118 |
opulencephp/Opulence | src/Opulence/Http/Requests/RequestHeaders.php | RequestHeaders.normalizeName | protected function normalizeName(string $name) : string
{
$name = parent::normalizeName($name);
if (strpos($name, 'http-') === 0) {
$name = substr($name, 5);
}
return $name;
} | php | protected function normalizeName(string $name) : string
{
$name = parent::normalizeName($name);
if (strpos($name, 'http-') === 0) {
$name = substr($name, 5);
}
return $name;
} | [
"protected",
"function",
"normalizeName",
"(",
"string",
"$",
"name",
")",
":",
"string",
"{",
"$",
"name",
"=",
"parent",
"::",
"normalizeName",
"(",
"$",
"name",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"name",
",",
"'http-'",
")",
"===",
"0",
")",... | Removes the "http-" from the name
@param string $name The name to normalize
@return string The normalized name | [
"Removes",
"the",
"http",
"-",
"from",
"the",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Http/Requests/RequestHeaders.php#L64-L73 |
opulencephp/Opulence | src/Opulence/Console/Prompts/Questions/MultipleChoice.php | MultipleChoice.getSelectedAssociativeChoices | private function getSelectedAssociativeChoices(array $answers) : array
{
$selectedChoices = [];
foreach ($answers as $answer) {
if (array_key_exists($answer, $this->choices)) {
$selectedChoices[] = $this->choices[$answer];
}
}
return $selectedChoices;
} | php | private function getSelectedAssociativeChoices(array $answers) : array
{
$selectedChoices = [];
foreach ($answers as $answer) {
if (array_key_exists($answer, $this->choices)) {
$selectedChoices[] = $this->choices[$answer];
}
}
return $selectedChoices;
} | [
"private",
"function",
"getSelectedAssociativeChoices",
"(",
"array",
"$",
"answers",
")",
":",
"array",
"{",
"$",
"selectedChoices",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"answers",
"as",
"$",
"answer",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$"... | Gets the list of selected associative choices from a list of answers
@param array $answers The list of answers
@return array The list of selected choices | [
"Gets",
"the",
"list",
"of",
"selected",
"associative",
"choices",
"from",
"a",
"list",
"of",
"answers"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Prompts/Questions/MultipleChoice.php#L132-L143 |
opulencephp/Opulence | src/Opulence/Console/Prompts/Questions/MultipleChoice.php | MultipleChoice.getSelectedIndexChoices | private function getSelectedIndexChoices(array $answers) : array
{
$selectedChoices = [];
foreach ($answers as $answer) {
if (!ctype_digit($answer)) {
throw new InvalidArgumentException('Answer is not an integer');
}
$answer = (int)$answer;
if ($answer < 1 || $answer > count($this->choices)) {
throw new InvalidArgumentException('Choice must be between 1 and ' . count($this->choices));
}
// Answers are 1-indexed
$selectedChoices[] = $this->choices[$answer - 1];
}
return $selectedChoices;
} | php | private function getSelectedIndexChoices(array $answers) : array
{
$selectedChoices = [];
foreach ($answers as $answer) {
if (!ctype_digit($answer)) {
throw new InvalidArgumentException('Answer is not an integer');
}
$answer = (int)$answer;
if ($answer < 1 || $answer > count($this->choices)) {
throw new InvalidArgumentException('Choice must be between 1 and ' . count($this->choices));
}
// Answers are 1-indexed
$selectedChoices[] = $this->choices[$answer - 1];
}
return $selectedChoices;
} | [
"private",
"function",
"getSelectedIndexChoices",
"(",
"array",
"$",
"answers",
")",
":",
"array",
"{",
"$",
"selectedChoices",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"answers",
"as",
"$",
"answer",
")",
"{",
"if",
"(",
"!",
"ctype_digit",
"(",
"$",
... | Gets the list of selected indexed choices from a list of answers
@param array $answers The list of answers
@return array The list of selected choices
@throws InvalidArgumentException Thrown if the answers are not of the correct type | [
"Gets",
"the",
"list",
"of",
"selected",
"indexed",
"choices",
"from",
"a",
"list",
"of",
"answers"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Prompts/Questions/MultipleChoice.php#L152-L172 |
opulencephp/Opulence | src/Opulence/Views/Compilers/Fortune/ViewFunctionRegistrant.php | ViewFunctionRegistrant.registerViewFunctions | public function registerViewFunctions(ITranspiler $transpiler)
{
// Register the charset function
$transpiler->registerViewFunction('charset', function ($charset) {
return '<meta charset="' . $charset . '">';
});
// Register the CSS function
$transpiler->registerViewFunction('css', function ($paths) {
$callback = function ($path) {
return '<link href="' . $path . '" rel="stylesheet">';
};
return implode("\n", array_map($callback, (array)$paths));
});
// Register the favicon function
$transpiler->registerViewFunction('favicon', function ($path) {
return '<link href="' . $path . '" rel="shortcut icon">';
});
// Register the HTTP-equiv function
$transpiler->registerViewFunction('httpEquiv', function ($name, $value) {
return '<meta http-equiv="' . htmlentities($name) . '" content="' . htmlentities($value) . '">';
});
// Registers the HTTP method hidden input
$transpiler->registerViewFunction('httpMethodInput', function ($httpMethod) {
return sprintf(
'<input type="hidden" name="_method" value="%s">',
$httpMethod
);
});
// Register the meta description function
$transpiler->registerViewFunction('metaDescription', function ($metaDescription) {
return '<meta name="description" content="' . htmlentities($metaDescription) . '">';
});
// Register the meta keywords function
$transpiler->registerViewFunction('metaKeywords', function (array $metaKeywords) {
return '<meta name="keywords" content="' . implode(',', array_map('htmlentities', $metaKeywords)) . '">';
});
// Register the page title function
$transpiler->registerViewFunction('pageTitle', function ($title) {
return '<title>' . htmlentities($title) . '</title>';
});
// Register the script function
$transpiler->registerViewFunction('script', function ($paths, $type = 'text/javascript') {
$callback = function ($path) use ($type) {
return '<script type="' . $type . '" src="' . $path . '"></script>';
};
return implode(PHP_EOL, array_map($callback, (array)$paths));
});
} | php | public function registerViewFunctions(ITranspiler $transpiler)
{
// Register the charset function
$transpiler->registerViewFunction('charset', function ($charset) {
return '<meta charset="' . $charset . '">';
});
// Register the CSS function
$transpiler->registerViewFunction('css', function ($paths) {
$callback = function ($path) {
return '<link href="' . $path . '" rel="stylesheet">';
};
return implode("\n", array_map($callback, (array)$paths));
});
// Register the favicon function
$transpiler->registerViewFunction('favicon', function ($path) {
return '<link href="' . $path . '" rel="shortcut icon">';
});
// Register the HTTP-equiv function
$transpiler->registerViewFunction('httpEquiv', function ($name, $value) {
return '<meta http-equiv="' . htmlentities($name) . '" content="' . htmlentities($value) . '">';
});
// Registers the HTTP method hidden input
$transpiler->registerViewFunction('httpMethodInput', function ($httpMethod) {
return sprintf(
'<input type="hidden" name="_method" value="%s">',
$httpMethod
);
});
// Register the meta description function
$transpiler->registerViewFunction('metaDescription', function ($metaDescription) {
return '<meta name="description" content="' . htmlentities($metaDescription) . '">';
});
// Register the meta keywords function
$transpiler->registerViewFunction('metaKeywords', function (array $metaKeywords) {
return '<meta name="keywords" content="' . implode(',', array_map('htmlentities', $metaKeywords)) . '">';
});
// Register the page title function
$transpiler->registerViewFunction('pageTitle', function ($title) {
return '<title>' . htmlentities($title) . '</title>';
});
// Register the script function
$transpiler->registerViewFunction('script', function ($paths, $type = 'text/javascript') {
$callback = function ($path) use ($type) {
return '<script type="' . $type . '" src="' . $path . '"></script>';
};
return implode(PHP_EOL, array_map($callback, (array)$paths));
});
} | [
"public",
"function",
"registerViewFunctions",
"(",
"ITranspiler",
"$",
"transpiler",
")",
"{",
"// Register the charset function",
"$",
"transpiler",
"->",
"registerViewFunction",
"(",
"'charset'",
",",
"function",
"(",
"$",
"charset",
")",
"{",
"return",
"'<meta cha... | Registers the built-in view functions
@param ITranspiler $transpiler The transpiler to register to | [
"Registers",
"the",
"built",
"-",
"in",
"view",
"functions"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Compilers/Fortune/ViewFunctionRegistrant.php#L23-L72 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Lexers/Lexer.php | Lexer.getSurroundingText | private function getSurroundingText(array $charArray, int $position) : string
{
if (count($charArray) <= 3) {
return implode('', $charArray);
}
if ($position <= 3) {
return implode('', array_slice($charArray, 0, 4));
}
return implode('', array_slice($charArray, $position - 3, 4));
} | php | private function getSurroundingText(array $charArray, int $position) : string
{
if (count($charArray) <= 3) {
return implode('', $charArray);
}
if ($position <= 3) {
return implode('', array_slice($charArray, 0, 4));
}
return implode('', array_slice($charArray, $position - 3, 4));
} | [
"private",
"function",
"getSurroundingText",
"(",
"array",
"$",
"charArray",
",",
"int",
"$",
"position",
")",
":",
"string",
"{",
"if",
"(",
"count",
"(",
"$",
"charArray",
")",
"<=",
"3",
")",
"{",
"return",
"implode",
"(",
"''",
",",
"$",
"charArray... | Gets text around a certain position for use in exceptions
@param array $charArray The char array
@param int $position The numerical position to grab text around
@return string The surrounding text | [
"Gets",
"text",
"around",
"a",
"certain",
"position",
"for",
"use",
"in",
"exceptions"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Lexers/Lexer.php#L135-L146 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Lexers/Lexer.php | Lexer.lookBehind | private function lookBehind(array $charArray, int $currPosition)
{
if ($currPosition === 0 || count($charArray) === 0) {
return null;
}
return $charArray[$currPosition - 1];
} | php | private function lookBehind(array $charArray, int $currPosition)
{
if ($currPosition === 0 || count($charArray) === 0) {
return null;
}
return $charArray[$currPosition - 1];
} | [
"private",
"function",
"lookBehind",
"(",
"array",
"$",
"charArray",
",",
"int",
"$",
"currPosition",
")",
"{",
"if",
"(",
"$",
"currPosition",
"===",
"0",
"||",
"count",
"(",
"$",
"charArray",
")",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"... | Looks back at the previous character in the string
@param array $charArray The char array
@param int $currPosition The current position
@return string|null The previous character if there is one, otherwise null | [
"Looks",
"back",
"at",
"the",
"previous",
"character",
"in",
"the",
"string"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Lexers/Lexer.php#L155-L162 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Lexers/Lexer.php | Lexer.peek | private function peek(array $charArray, int $currPosition)
{
$charArrayLength = count($charArray);
if ($charArrayLength === 0 || $charArrayLength === $currPosition + 1) {
return null;
}
return $charArray[$currPosition + 1];
} | php | private function peek(array $charArray, int $currPosition)
{
$charArrayLength = count($charArray);
if ($charArrayLength === 0 || $charArrayLength === $currPosition + 1) {
return null;
}
return $charArray[$currPosition + 1];
} | [
"private",
"function",
"peek",
"(",
"array",
"$",
"charArray",
",",
"int",
"$",
"currPosition",
")",
"{",
"$",
"charArrayLength",
"=",
"count",
"(",
"$",
"charArray",
")",
";",
"if",
"(",
"$",
"charArrayLength",
"===",
"0",
"||",
"$",
"charArrayLength",
... | Peeks at the next character in the string
@param array $charArray The char array
@param int $currPosition The current position
@return string|null The next character if there is one, otherwise null | [
"Peeks",
"at",
"the",
"next",
"character",
"in",
"the",
"string"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Lexers/Lexer.php#L171-L180 |
opulencephp/Opulence | src/Opulence/Redis/Redis.php | Redis.deleteKeyPatterns | public function deleteKeyPatterns($keyPatterns) : bool
{
if (is_string($keyPatterns)) {
$keyPatterns = [$keyPatterns];
}
// Loops through our key patterns, gets all keys that match them, then deletes each of them
$lua = "local keyPatterns = {'" . implode("','", $keyPatterns) . "'}
for i, keyPattern in ipairs(keyPatterns) do
for j, key in ipairs(redis.call('keys', keyPattern)) do
redis.call('del', key)
end
end";
$this->eval($lua);
return $this->getLastError() === null;
} | php | public function deleteKeyPatterns($keyPatterns) : bool
{
if (is_string($keyPatterns)) {
$keyPatterns = [$keyPatterns];
}
// Loops through our key patterns, gets all keys that match them, then deletes each of them
$lua = "local keyPatterns = {'" . implode("','", $keyPatterns) . "'}
for i, keyPattern in ipairs(keyPatterns) do
for j, key in ipairs(redis.call('keys', keyPattern)) do
redis.call('del', key)
end
end";
$this->eval($lua);
return $this->getLastError() === null;
} | [
"public",
"function",
"deleteKeyPatterns",
"(",
"$",
"keyPatterns",
")",
":",
"bool",
"{",
"if",
"(",
"is_string",
"(",
"$",
"keyPatterns",
")",
")",
"{",
"$",
"keyPatterns",
"=",
"[",
"$",
"keyPatterns",
"]",
";",
"}",
"// Loops through our key patterns, gets... | Deletes all the keys that match the input patterns
If you know the specific key(s) to delete, call Redis' delete command instead because this is relatively slow
@param array|string The key pattern or list of key patterns to delete
@return bool True if successful, otherwise false | [
"Deletes",
"all",
"the",
"keys",
"that",
"match",
"the",
"input",
"patterns",
"If",
"you",
"know",
"the",
"specific",
"key",
"(",
"s",
")",
"to",
"delete",
"call",
"Redis",
"delete",
"command",
"instead",
"because",
"this",
"is",
"relatively",
"slow"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Redis/Redis.php#L59-L75 |
opulencephp/Opulence | src/Opulence/Redis/Redis.php | Redis.getClient | public function getClient(string $name = 'default')
{
if (!isset($this->clients[$name])) {
throw new InvalidArgumentException("No client with name \"$name\"");
}
return $this->clients[$name];
} | php | public function getClient(string $name = 'default')
{
if (!isset($this->clients[$name])) {
throw new InvalidArgumentException("No client with name \"$name\"");
}
return $this->clients[$name];
} | [
"public",
"function",
"getClient",
"(",
"string",
"$",
"name",
"=",
"'default'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"clients",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"No client wit... | Gets the client with the input name
@param string $name The name of the client to get
@return mixed The client
@throws InvalidArgumentException Thrown if no client with the input name exists | [
"Gets",
"the",
"client",
"with",
"the",
"input",
"name"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Redis/Redis.php#L84-L91 |
opulencephp/Opulence | src/Opulence/Authentication/Tokens/JsonWebTokens/Verification/JwtVerifier.php | JwtVerifier.verify | public function verify(SignedJwt $jwt, VerificationContext $verificationContext, array &$errors) : bool
{
$verifiers = [
new SignatureVerifier($verificationContext->getSigner()),
new AudienceVerifier($verificationContext->getAudience()),
new ExpirationVerifier(),
new NotBeforeVerifier(),
new IssuerVerifier($verificationContext->getIssuer()),
new SubjectVerifier($verificationContext->getSubject())
];
$isVerified = true;
/** @var IVerifier $verifier */
foreach ($verifiers as $verifier) {
$error = '';
if (!$verifier->verify($jwt, $error)) {
$isVerified = false;
$errors[] = $error;
}
}
return $isVerified;
} | php | public function verify(SignedJwt $jwt, VerificationContext $verificationContext, array &$errors) : bool
{
$verifiers = [
new SignatureVerifier($verificationContext->getSigner()),
new AudienceVerifier($verificationContext->getAudience()),
new ExpirationVerifier(),
new NotBeforeVerifier(),
new IssuerVerifier($verificationContext->getIssuer()),
new SubjectVerifier($verificationContext->getSubject())
];
$isVerified = true;
/** @var IVerifier $verifier */
foreach ($verifiers as $verifier) {
$error = '';
if (!$verifier->verify($jwt, $error)) {
$isVerified = false;
$errors[] = $error;
}
}
return $isVerified;
} | [
"public",
"function",
"verify",
"(",
"SignedJwt",
"$",
"jwt",
",",
"VerificationContext",
"$",
"verificationContext",
",",
"array",
"&",
"$",
"errors",
")",
":",
"bool",
"{",
"$",
"verifiers",
"=",
"[",
"new",
"SignatureVerifier",
"(",
"$",
"verificationContex... | Verifies a token
@param SignedJwt $jwt The token to verify
@param VerificationContext $verificationContext The context to verify against
@param array $errors The list of errors, if there are any
@return bool True if the token is valid | [
"Verifies",
"a",
"token"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Authentication/Tokens/JsonWebTokens/Verification/JwtVerifier.php#L28-L51 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Compiler.php | Compiler.compileNode | private function compileNode(Node $node) : string
{
if ($node->isLeaf()) {
// Don't compile a leaf that is a tag because that means it doesn't have any content
if ($node->isTag()) {
return '';
}
return $node->getValue() ?: '';
} else {
$output = '';
foreach ($node->getChildren() as $childNode) {
if ($node->isTag()) {
if (!isset($this->elements[$node->getValue()])) {
throw new InvalidArgumentException("No style registered for element \"{$node->getValue()}\"");
}
$style = $this->elements[$node->getValue()];
$output .= $style->format($this->compileNode($childNode));
} else {
$output .= $this->compileNode($childNode);
}
}
return $output;
}
} | php | private function compileNode(Node $node) : string
{
if ($node->isLeaf()) {
// Don't compile a leaf that is a tag because that means it doesn't have any content
if ($node->isTag()) {
return '';
}
return $node->getValue() ?: '';
} else {
$output = '';
foreach ($node->getChildren() as $childNode) {
if ($node->isTag()) {
if (!isset($this->elements[$node->getValue()])) {
throw new InvalidArgumentException("No style registered for element \"{$node->getValue()}\"");
}
$style = $this->elements[$node->getValue()];
$output .= $style->format($this->compileNode($childNode));
} else {
$output .= $this->compileNode($childNode);
}
}
return $output;
}
} | [
"private",
"function",
"compileNode",
"(",
"Node",
"$",
"node",
")",
":",
"string",
"{",
"if",
"(",
"$",
"node",
"->",
"isLeaf",
"(",
")",
")",
"{",
"// Don't compile a leaf that is a tag because that means it doesn't have any content",
"if",
"(",
"$",
"node",
"->... | Recursively compiles a node and its children
@param Node $node The node to compile
@return string The compiled node
@throws RuntimeException Thrown if there was an error compiling the node
@throws InvalidArgumentException Thrown if there is no matching element for a particular tag | [
"Recursively",
"compiles",
"a",
"node",
"and",
"its",
"children"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Compiler.php#L89-L116 |
opulencephp/Opulence | src/Opulence/Databases/Migrations/Migrator.php | Migrator.executeRollBacks | private function executeRollBacks(array $migrations) : void
{
$this->connection->beginTransaction();
foreach ($migrations as $migration) {
$migration->down();
$this->executedMigrations->delete(get_class($migration));
}
$this->connection->commit();
} | php | private function executeRollBacks(array $migrations) : void
{
$this->connection->beginTransaction();
foreach ($migrations as $migration) {
$migration->down();
$this->executedMigrations->delete(get_class($migration));
}
$this->connection->commit();
} | [
"private",
"function",
"executeRollBacks",
"(",
"array",
"$",
"migrations",
")",
":",
"void",
"{",
"$",
"this",
"->",
"connection",
"->",
"beginTransaction",
"(",
")",
";",
"foreach",
"(",
"$",
"migrations",
"as",
"$",
"migration",
")",
"{",
"$",
"migratio... | Executes the roll backs on a list of migrations
@param IMigration[] $migrations The migrations to execute the down method on | [
"Executes",
"the",
"roll",
"backs",
"on",
"a",
"list",
"of",
"migrations"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Migrations/Migrator.php#L99-L109 |
opulencephp/Opulence | src/Opulence/Databases/Migrations/Migrator.php | Migrator.resolveManyMigrations | private function resolveManyMigrations(array $migrationClasses) : array
{
$migrations = [];
foreach ($migrationClasses as $migrationClass) {
$migrations[] = $this->migrationResolver->resolve($migrationClass);
}
return $migrations;
} | php | private function resolveManyMigrations(array $migrationClasses) : array
{
$migrations = [];
foreach ($migrationClasses as $migrationClass) {
$migrations[] = $this->migrationResolver->resolve($migrationClass);
}
return $migrations;
} | [
"private",
"function",
"resolveManyMigrations",
"(",
"array",
"$",
"migrationClasses",
")",
":",
"array",
"{",
"$",
"migrations",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"migrationClasses",
"as",
"$",
"migrationClass",
")",
"{",
"$",
"migrations",
"[",
"]",... | Resolves many migrations at once
@param string[] $migrationClasses The list of migration classes to resolve
@return IMigration[] The list of resolved migrations | [
"Resolves",
"many",
"migrations",
"at",
"once"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Databases/Migrations/Migrator.php#L117-L126 |
opulencephp/Opulence | src/Opulence/Console/Prompts/Prompt.php | Prompt.ask | public function ask(IQuestion $question, IResponse $response)
{
$response->write("<question>{$question->getText()}</question>");
if ($question instanceof MultipleChoice) {
/** @var MultipleChoice $question */
$response->writeln('');
$choicesAreAssociative = $question->choicesAreAssociative();
$choiceTexts = [];
foreach ($question->getChoices() as $key => $choice) {
if (!$choicesAreAssociative) {
// Make the choice 1-indexed
++$key;
}
$choiceTexts[] = [$key . ')', $choice];
}
$response->writeln($this->paddingFormatter->format($choiceTexts, function ($row) {
return " {$row[0]} {$row[1]}";
}));
$response->write($question->getAnswerLineString());
}
$answer = fgets($this->inputStream, 4096);
if ($answer === false) {
throw new RuntimeException('Failed to get answer');
}
$answer = trim($answer);
if ($answer === '') {
$answer = $question->getDefaultAnswer();
}
return $question->formatAnswer($answer);
} | php | public function ask(IQuestion $question, IResponse $response)
{
$response->write("<question>{$question->getText()}</question>");
if ($question instanceof MultipleChoice) {
/** @var MultipleChoice $question */
$response->writeln('');
$choicesAreAssociative = $question->choicesAreAssociative();
$choiceTexts = [];
foreach ($question->getChoices() as $key => $choice) {
if (!$choicesAreAssociative) {
// Make the choice 1-indexed
++$key;
}
$choiceTexts[] = [$key . ')', $choice];
}
$response->writeln($this->paddingFormatter->format($choiceTexts, function ($row) {
return " {$row[0]} {$row[1]}";
}));
$response->write($question->getAnswerLineString());
}
$answer = fgets($this->inputStream, 4096);
if ($answer === false) {
throw new RuntimeException('Failed to get answer');
}
$answer = trim($answer);
if ($answer === '') {
$answer = $question->getDefaultAnswer();
}
return $question->formatAnswer($answer);
} | [
"public",
"function",
"ask",
"(",
"IQuestion",
"$",
"question",
",",
"IResponse",
"$",
"response",
")",
"{",
"$",
"response",
"->",
"write",
"(",
"\"<question>{$question->getText()}</question>\"",
")",
";",
"if",
"(",
"$",
"question",
"instanceof",
"MultipleChoice... | Prompts the user to answer a question
@param IQuestion $question The question to ask
@param IResponse $response The response to write output to
@return mixed The user's answer to the question
@throws RuntimeException Thrown if we failed to get the user's answer | [
"Prompts",
"the",
"user",
"to",
"answer",
"a",
"question"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Prompts/Prompt.php#L53-L91 |
opulencephp/Opulence | src/Opulence/Views/Caching/ArrayCache.php | ArrayCache.getViewKey | private function getViewKey(IView $view, bool $checkVars) : string
{
$data = ['u' => $view->getContents()];
if ($checkVars) {
$data['v'] = $view->getVars();
}
return md5(http_build_query($data));
} | php | private function getViewKey(IView $view, bool $checkVars) : string
{
$data = ['u' => $view->getContents()];
if ($checkVars) {
$data['v'] = $view->getVars();
}
return md5(http_build_query($data));
} | [
"private",
"function",
"getViewKey",
"(",
"IView",
"$",
"view",
",",
"bool",
"$",
"checkVars",
")",
":",
"string",
"{",
"$",
"data",
"=",
"[",
"'u'",
"=>",
"$",
"view",
"->",
"getContents",
"(",
")",
"]",
";",
"if",
"(",
"$",
"checkVars",
")",
"{",... | Gets key for the cached view
@param IView $view The view whose cached file path we want
@param bool $checkVars Whether or not we want to also check for variable value equivalence when looking up cached views
@return string The key for the cached view | [
"Gets",
"key",
"for",
"the",
"cached",
"view"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Views/Caching/ArrayCache.php#L82-L91 |
opulencephp/Opulence | src/Opulence/Cryptography/Encryption/Keys/Pbkdf2KeyDeriver.php | Pbkdf2KeyDeriver.validateSaltLength | private function validateSaltLength(string $salt)
{
if (\mb_strlen($salt, '8bit') !== self::KEY_SALT_BYTE_LENGTH) {
throw new InvalidArgumentException('Salt must be ' . self::KEY_SALT_BYTE_LENGTH . ' bytes long');
}
} | php | private function validateSaltLength(string $salt)
{
if (\mb_strlen($salt, '8bit') !== self::KEY_SALT_BYTE_LENGTH) {
throw new InvalidArgumentException('Salt must be ' . self::KEY_SALT_BYTE_LENGTH . ' bytes long');
}
} | [
"private",
"function",
"validateSaltLength",
"(",
"string",
"$",
"salt",
")",
"{",
"if",
"(",
"\\",
"mb_strlen",
"(",
"$",
"salt",
",",
"'8bit'",
")",
"!==",
"self",
"::",
"KEY_SALT_BYTE_LENGTH",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'S... | Verifies the salt length
@param string $salt The salt to validate
@throws InvalidArgumentException Thrown if the salt is not the correct length | [
"Verifies",
"the",
"salt",
"length"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Cryptography/Encryption/Keys/Pbkdf2KeyDeriver.php#L67-L72 |
opulencephp/Opulence | src/Opulence/Console/Responses/Compilers/Parsers/Nodes/Node.php | Node.addChild | public function addChild(Node $node) : self
{
$node->setParent($this);
$this->children[] = $node;
return $this;
} | php | public function addChild(Node $node) : self
{
$node->setParent($this);
$this->children[] = $node;
return $this;
} | [
"public",
"function",
"addChild",
"(",
"Node",
"$",
"node",
")",
":",
"self",
"{",
"$",
"node",
"->",
"setParent",
"(",
"$",
"this",
")",
";",
"$",
"this",
"->",
"children",
"[",
"]",
"=",
"$",
"node",
";",
"return",
"$",
"this",
";",
"}"
] | Adds a child to this node
@param Node $node The child to add
@return self Returns this for chaining | [
"Adds",
"a",
"child",
"to",
"this",
"node"
] | train | https://github.com/opulencephp/Opulence/blob/27c86747f893a78ab0bc9b8a90aae3cad6e7afb5/src/Opulence/Console/Responses/Compilers/Parsers/Nodes/Node.php#L46-L52 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.