repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
list | docstring
stringlengths 3
47.2k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
silverstripe/silverstripe-framework | src/ORM/Connect/MySQLiConnector.php | MySQLiConnector.parsePreparedParameters | public function parsePreparedParameters($parameters, &$blobs)
{
$types = '';
$values = array();
$blobs = array();
$parametersCount = count($parameters);
for ($index = 0; $index < $parametersCount; $index++) {
$value = $parameters[$index];
$phpType = gettype($value);
// Allow overriding of parameter type using an associative array
if ($phpType === 'array') {
$phpType = $value['type'];
$value = $value['value'];
}
// Convert php variable type to one that makes mysqli_stmt_bind_param happy
// @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php
switch ($phpType) {
case 'boolean':
case 'integer':
$types .= 'i';
break;
case 'float': // Not actually returnable from gettype
case 'double':
$types .= 'd';
break;
case 'object': // Allowed if the object or resource has a __toString method
case 'resource':
case 'string':
case 'NULL': // Take care that a where clause should use "where XX is null" not "where XX = null"
$types .= 's';
break;
case 'blob':
$types .= 'b';
// Blobs must be sent via send_long_data and set to null here
$blobs[] = array(
'index' => $index,
'value' => $value
);
$value = null;
break;
case 'array':
case 'unknown type':
default:
user_error(
"Cannot bind parameter \"$value\" as it is an unsupported type ($phpType)",
E_USER_ERROR
);
break;
}
$values[] = $value;
}
return array_merge(array($types), $values);
} | php | public function parsePreparedParameters($parameters, &$blobs)
{
$types = '';
$values = array();
$blobs = array();
$parametersCount = count($parameters);
for ($index = 0; $index < $parametersCount; $index++) {
$value = $parameters[$index];
$phpType = gettype($value);
// Allow overriding of parameter type using an associative array
if ($phpType === 'array') {
$phpType = $value['type'];
$value = $value['value'];
}
// Convert php variable type to one that makes mysqli_stmt_bind_param happy
// @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php
switch ($phpType) {
case 'boolean':
case 'integer':
$types .= 'i';
break;
case 'float': // Not actually returnable from gettype
case 'double':
$types .= 'd';
break;
case 'object': // Allowed if the object or resource has a __toString method
case 'resource':
case 'string':
case 'NULL': // Take care that a where clause should use "where XX is null" not "where XX = null"
$types .= 's';
break;
case 'blob':
$types .= 'b';
// Blobs must be sent via send_long_data and set to null here
$blobs[] = array(
'index' => $index,
'value' => $value
);
$value = null;
break;
case 'array':
case 'unknown type':
default:
user_error(
"Cannot bind parameter \"$value\" as it is an unsupported type ($phpType)",
E_USER_ERROR
);
break;
}
$values[] = $value;
}
return array_merge(array($types), $values);
} | [
"public",
"function",
"parsePreparedParameters",
"(",
"$",
"parameters",
",",
"&",
"$",
"blobs",
")",
"{",
"$",
"types",
"=",
"''",
";",
"$",
"values",
"=",
"array",
"(",
")",
";",
"$",
"blobs",
"=",
"array",
"(",
")",
";",
"$",
"parametersCount",
"=",
"count",
"(",
"$",
"parameters",
")",
";",
"for",
"(",
"$",
"index",
"=",
"0",
";",
"$",
"index",
"<",
"$",
"parametersCount",
";",
"$",
"index",
"++",
")",
"{",
"$",
"value",
"=",
"$",
"parameters",
"[",
"$",
"index",
"]",
";",
"$",
"phpType",
"=",
"gettype",
"(",
"$",
"value",
")",
";",
"// Allow overriding of parameter type using an associative array",
"if",
"(",
"$",
"phpType",
"===",
"'array'",
")",
"{",
"$",
"phpType",
"=",
"$",
"value",
"[",
"'type'",
"]",
";",
"$",
"value",
"=",
"$",
"value",
"[",
"'value'",
"]",
";",
"}",
"// Convert php variable type to one that makes mysqli_stmt_bind_param happy",
"// @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php",
"switch",
"(",
"$",
"phpType",
")",
"{",
"case",
"'boolean'",
":",
"case",
"'integer'",
":",
"$",
"types",
".=",
"'i'",
";",
"break",
";",
"case",
"'float'",
":",
"// Not actually returnable from gettype",
"case",
"'double'",
":",
"$",
"types",
".=",
"'d'",
";",
"break",
";",
"case",
"'object'",
":",
"// Allowed if the object or resource has a __toString method",
"case",
"'resource'",
":",
"case",
"'string'",
":",
"case",
"'NULL'",
":",
"// Take care that a where clause should use \"where XX is null\" not \"where XX = null\"",
"$",
"types",
".=",
"'s'",
";",
"break",
";",
"case",
"'blob'",
":",
"$",
"types",
".=",
"'b'",
";",
"// Blobs must be sent via send_long_data and set to null here",
"$",
"blobs",
"[",
"]",
"=",
"array",
"(",
"'index'",
"=>",
"$",
"index",
",",
"'value'",
"=>",
"$",
"value",
")",
";",
"$",
"value",
"=",
"null",
";",
"break",
";",
"case",
"'array'",
":",
"case",
"'unknown type'",
":",
"default",
":",
"user_error",
"(",
"\"Cannot bind parameter \\\"$value\\\" as it is an unsupported type ($phpType)\"",
",",
"E_USER_ERROR",
")",
";",
"break",
";",
"}",
"$",
"values",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"array_merge",
"(",
"array",
"(",
"$",
"types",
")",
",",
"$",
"values",
")",
";",
"}"
]
| Prepares the list of parameters in preparation for passing to mysqli_stmt_bind_param
@param array $parameters List of parameters
@param array &$blobs Out parameter for list of blobs to bind separately
@return array List of parameters appropriate for mysqli_stmt_bind_param function | [
"Prepares",
"the",
"list",
"of",
"parameters",
"in",
"preparation",
"for",
"passing",
"to",
"mysqli_stmt_bind_param"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLiConnector.php#L196-L250 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/MySQLiConnector.php | MySQLiConnector.bindParameters | public function bindParameters(mysqli_stmt $statement, array $parameters)
{
// Because mysqli_stmt::bind_param arguments must be passed by reference
// we need to do a bit of hackery
$boundNames = [];
$parametersCount = count($parameters);
for ($i = 0; $i < $parametersCount; $i++) {
$boundName = "param$i";
$$boundName = $parameters[$i];
$boundNames[] = &$$boundName;
}
$statement->bind_param(...$boundNames);
} | php | public function bindParameters(mysqli_stmt $statement, array $parameters)
{
// Because mysqli_stmt::bind_param arguments must be passed by reference
// we need to do a bit of hackery
$boundNames = [];
$parametersCount = count($parameters);
for ($i = 0; $i < $parametersCount; $i++) {
$boundName = "param$i";
$$boundName = $parameters[$i];
$boundNames[] = &$$boundName;
}
$statement->bind_param(...$boundNames);
} | [
"public",
"function",
"bindParameters",
"(",
"mysqli_stmt",
"$",
"statement",
",",
"array",
"$",
"parameters",
")",
"{",
"// Because mysqli_stmt::bind_param arguments must be passed by reference",
"// we need to do a bit of hackery",
"$",
"boundNames",
"=",
"[",
"]",
";",
"$",
"parametersCount",
"=",
"count",
"(",
"$",
"parameters",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"parametersCount",
";",
"$",
"i",
"++",
")",
"{",
"$",
"boundName",
"=",
"\"param$i\"",
";",
"$",
"$",
"boundName",
"=",
"$",
"parameters",
"[",
"$",
"i",
"]",
";",
"$",
"boundNames",
"[",
"]",
"=",
"&",
"$",
"$",
"boundName",
";",
"}",
"$",
"statement",
"->",
"bind_param",
"(",
"...",
"$",
"boundNames",
")",
";",
"}"
]
| Binds a list of parameters to a statement
@param mysqli_stmt $statement MySQLi statement
@param array $parameters List of parameters to pass to bind_param | [
"Binds",
"a",
"list",
"of",
"parameters",
"to",
"a",
"statement"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLiConnector.php#L258-L270 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBTime.php | DBTime.Short | public function Short()
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter(IntlDateFormatter::SHORT);
return $formatter->format($this->getTimestamp());
} | php | public function Short()
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter(IntlDateFormatter::SHORT);
return $formatter->format($this->getTimestamp());
} | [
"public",
"function",
"Short",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"value",
")",
"{",
"return",
"null",
";",
"}",
"$",
"formatter",
"=",
"$",
"this",
"->",
"getFormatter",
"(",
"IntlDateFormatter",
"::",
"SHORT",
")",
";",
"return",
"$",
"formatter",
"->",
"format",
"(",
"$",
"this",
"->",
"getTimestamp",
"(",
")",
")",
";",
"}"
]
| Returns the date in the localised short format
@return string | [
"Returns",
"the",
"date",
"in",
"the",
"localised",
"short",
"format"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBTime.php#L90-L97 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBTime.php | DBTime.Format | public function Format($format)
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter();
$formatter->setPattern($format);
return $formatter->format($this->getTimestamp());
} | php | public function Format($format)
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter();
$formatter->setPattern($format);
return $formatter->format($this->getTimestamp());
} | [
"public",
"function",
"Format",
"(",
"$",
"format",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"value",
")",
"{",
"return",
"null",
";",
"}",
"$",
"formatter",
"=",
"$",
"this",
"->",
"getFormatter",
"(",
")",
";",
"$",
"formatter",
"->",
"setPattern",
"(",
"$",
"format",
")",
";",
"return",
"$",
"formatter",
"->",
"format",
"(",
"$",
"this",
"->",
"getTimestamp",
"(",
")",
")",
";",
"}"
]
| Return the time using a particular formatting string.
@param string $format Format code string. See http://userguide.icu-project.org/formatparse/datetime
@return string The time in the requested format | [
"Return",
"the",
"time",
"using",
"a",
"particular",
"formatting",
"string",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBTime.php#L120-L128 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBTime.php | DBTime.FormatFromSettings | public function FormatFromSettings($member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
// Fall back to nice
if (!$member) {
return $this->Nice();
}
// Get user format
$format = $member->getTimeFormat();
return $this->Format($format);
} | php | public function FormatFromSettings($member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
// Fall back to nice
if (!$member) {
return $this->Nice();
}
// Get user format
$format = $member->getTimeFormat();
return $this->Format($format);
} | [
"public",
"function",
"FormatFromSettings",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"member",
")",
"{",
"$",
"member",
"=",
"Security",
"::",
"getCurrentUser",
"(",
")",
";",
"}",
"// Fall back to nice",
"if",
"(",
"!",
"$",
"member",
")",
"{",
"return",
"$",
"this",
"->",
"Nice",
"(",
")",
";",
"}",
"// Get user format",
"$",
"format",
"=",
"$",
"member",
"->",
"getTimeFormat",
"(",
")",
";",
"return",
"$",
"this",
"->",
"Format",
"(",
"$",
"format",
")",
";",
"}"
]
| Return a time formatted as per a CMS user's settings.
@param Member $member
@return string A time formatted as per user-defined settings. | [
"Return",
"a",
"time",
"formatted",
"as",
"per",
"a",
"CMS",
"user",
"s",
"settings",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBTime.php#L154-L168 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.get_conn | public static function get_conn($name = 'default')
{
if (isset(self::$connections[$name])) {
return self::$connections[$name];
}
// lazy connect
$config = static::getConfig($name);
if ($config) {
return static::connect($config, $name);
}
return null;
} | php | public static function get_conn($name = 'default')
{
if (isset(self::$connections[$name])) {
return self::$connections[$name];
}
// lazy connect
$config = static::getConfig($name);
if ($config) {
return static::connect($config, $name);
}
return null;
} | [
"public",
"static",
"function",
"get_conn",
"(",
"$",
"name",
"=",
"'default'",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"connections",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"connections",
"[",
"$",
"name",
"]",
";",
"}",
"// lazy connect",
"$",
"config",
"=",
"static",
"::",
"getConfig",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"config",
")",
"{",
"return",
"static",
"::",
"connect",
"(",
"$",
"config",
",",
"$",
"name",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Get the global database connection.
@param string $name An optional name given to a connection in the DB::setConn() call. If omitted,
the default connection is returned.
@return Database | [
"Get",
"the",
"global",
"database",
"connection",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L99-L112 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.get_schema | public static function get_schema($name = 'default')
{
$connection = self::get_conn($name);
if ($connection) {
return $connection->getSchemaManager();
}
return null;
} | php | public static function get_schema($name = 'default')
{
$connection = self::get_conn($name);
if ($connection) {
return $connection->getSchemaManager();
}
return null;
} | [
"public",
"static",
"function",
"get_schema",
"(",
"$",
"name",
"=",
"'default'",
")",
"{",
"$",
"connection",
"=",
"self",
"::",
"get_conn",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"connection",
")",
"{",
"return",
"$",
"connection",
"->",
"getSchemaManager",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Retrieves the schema manager for the current database
@param string $name An optional name given to a connection in the DB::setConn() call. If omitted,
the default connection is returned.
@return DBSchemaManager | [
"Retrieves",
"the",
"schema",
"manager",
"for",
"the",
"current",
"database"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L131-L138 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.get_connector | public static function get_connector($name = 'default')
{
$connection = self::get_conn($name);
if ($connection) {
return $connection->getConnector();
}
return null;
} | php | public static function get_connector($name = 'default')
{
$connection = self::get_conn($name);
if ($connection) {
return $connection->getConnector();
}
return null;
} | [
"public",
"static",
"function",
"get_connector",
"(",
"$",
"name",
"=",
"'default'",
")",
"{",
"$",
"connection",
"=",
"self",
"::",
"get_conn",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"connection",
")",
"{",
"return",
"$",
"connection",
"->",
"getConnector",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Retrieves the connector object for the current database
@param string $name An optional name given to a connection in the DB::setConn() call. If omitted,
the default connection is returned.
@return DBConnector | [
"Retrieves",
"the",
"connector",
"object",
"for",
"the",
"current",
"database"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L167-L174 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.set_alternative_database_name | public static function set_alternative_database_name($name = null)
{
// Ignore if disabled
if (!Config::inst()->get(static::class, 'alternative_database_enabled')) {
return;
}
// Skip if CLI
if (Director::is_cli()) {
return;
}
// Validate name
if ($name && !self::valid_alternative_database_name($name)) {
throw new InvalidArgumentException(sprintf(
'Invalid alternative database name: "%s"',
$name
));
}
// Set against session
if (!Injector::inst()->has(HTTPRequest::class)) {
return;
}
/** @var HTTPRequest $request */
$request = Injector::inst()->get(HTTPRequest::class);
if ($name) {
$request->getSession()->set(self::ALT_DB_KEY, $name);
} else {
$request->getSession()->clear(self::ALT_DB_KEY);
}
} | php | public static function set_alternative_database_name($name = null)
{
// Ignore if disabled
if (!Config::inst()->get(static::class, 'alternative_database_enabled')) {
return;
}
// Skip if CLI
if (Director::is_cli()) {
return;
}
// Validate name
if ($name && !self::valid_alternative_database_name($name)) {
throw new InvalidArgumentException(sprintf(
'Invalid alternative database name: "%s"',
$name
));
}
// Set against session
if (!Injector::inst()->has(HTTPRequest::class)) {
return;
}
/** @var HTTPRequest $request */
$request = Injector::inst()->get(HTTPRequest::class);
if ($name) {
$request->getSession()->set(self::ALT_DB_KEY, $name);
} else {
$request->getSession()->clear(self::ALT_DB_KEY);
}
} | [
"public",
"static",
"function",
"set_alternative_database_name",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"// Ignore if disabled",
"if",
"(",
"!",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"static",
"::",
"class",
",",
"'alternative_database_enabled'",
")",
")",
"{",
"return",
";",
"}",
"// Skip if CLI",
"if",
"(",
"Director",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Validate name",
"if",
"(",
"$",
"name",
"&&",
"!",
"self",
"::",
"valid_alternative_database_name",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Invalid alternative database name: \"%s\"'",
",",
"$",
"name",
")",
")",
";",
"}",
"// Set against session",
"if",
"(",
"!",
"Injector",
"::",
"inst",
"(",
")",
"->",
"has",
"(",
"HTTPRequest",
"::",
"class",
")",
")",
"{",
"return",
";",
"}",
"/** @var HTTPRequest $request */",
"$",
"request",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"HTTPRequest",
"::",
"class",
")",
";",
"if",
"(",
"$",
"name",
")",
"{",
"$",
"request",
"->",
"getSession",
"(",
")",
"->",
"set",
"(",
"self",
"::",
"ALT_DB_KEY",
",",
"$",
"name",
")",
";",
"}",
"else",
"{",
"$",
"request",
"->",
"getSession",
"(",
")",
"->",
"clear",
"(",
"self",
"::",
"ALT_DB_KEY",
")",
";",
"}",
"}"
]
| Set an alternative database in a browser cookie,
with the cookie lifetime set to the browser session.
This is useful for integration testing on temporary databases.
There is a strict naming convention for temporary databases to avoid abuse:
<prefix> (default: 'ss_') + tmpdb + <7 digits>
As an additional security measure, temporary databases will
be ignored in "live" mode.
Note that the database will be set on the next request.
Set it to null to revert to the main database.
@param string $name | [
"Set",
"an",
"alternative",
"database",
"in",
"a",
"browser",
"cookie",
"with",
"the",
"cookie",
"lifetime",
"set",
"to",
"the",
"browser",
"session",
".",
"This",
"is",
"useful",
"for",
"integration",
"testing",
"on",
"temporary",
"databases",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L191-L220 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.get_alternative_database_name | public static function get_alternative_database_name()
{
// Ignore if disabled
if (!Config::inst()->get(static::class, 'alternative_database_enabled')) {
return false;
}
// Skip if CLI
if (Director::is_cli()) {
return false;
}
// Skip if there's no request object yet
if (!Injector::inst()->has(HTTPRequest::class)) {
return null;
}
/** @var HTTPRequest $request */
$request = Injector::inst()->get(HTTPRequest::class);
// Skip if the session hasn't been started
if (!$request->getSession()->isStarted()) {
return null;
}
$name = $request->getSession()->get(self::ALT_DB_KEY);
if (self::valid_alternative_database_name($name)) {
return $name;
}
return false;
} | php | public static function get_alternative_database_name()
{
// Ignore if disabled
if (!Config::inst()->get(static::class, 'alternative_database_enabled')) {
return false;
}
// Skip if CLI
if (Director::is_cli()) {
return false;
}
// Skip if there's no request object yet
if (!Injector::inst()->has(HTTPRequest::class)) {
return null;
}
/** @var HTTPRequest $request */
$request = Injector::inst()->get(HTTPRequest::class);
// Skip if the session hasn't been started
if (!$request->getSession()->isStarted()) {
return null;
}
$name = $request->getSession()->get(self::ALT_DB_KEY);
if (self::valid_alternative_database_name($name)) {
return $name;
}
return false;
} | [
"public",
"static",
"function",
"get_alternative_database_name",
"(",
")",
"{",
"// Ignore if disabled",
"if",
"(",
"!",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"static",
"::",
"class",
",",
"'alternative_database_enabled'",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Skip if CLI",
"if",
"(",
"Director",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Skip if there's no request object yet",
"if",
"(",
"!",
"Injector",
"::",
"inst",
"(",
")",
"->",
"has",
"(",
"HTTPRequest",
"::",
"class",
")",
")",
"{",
"return",
"null",
";",
"}",
"/** @var HTTPRequest $request */",
"$",
"request",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"HTTPRequest",
"::",
"class",
")",
";",
"// Skip if the session hasn't been started",
"if",
"(",
"!",
"$",
"request",
"->",
"getSession",
"(",
")",
"->",
"isStarted",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"name",
"=",
"$",
"request",
"->",
"getSession",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"ALT_DB_KEY",
")",
";",
"if",
"(",
"self",
"::",
"valid_alternative_database_name",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"name",
";",
"}",
"return",
"false",
";",
"}"
]
| Get the name of the database in use
@return string|false Name of temp database, or false if not set | [
"Get",
"the",
"name",
"of",
"the",
"database",
"in",
"use"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L227-L254 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.valid_alternative_database_name | public static function valid_alternative_database_name($name)
{
if (Director::isLive() || empty($name)) {
return false;
}
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
$pattern = strtolower(sprintf('/^%stmpdb\d{7}$/', $prefix));
return (bool)preg_match($pattern, $name);
} | php | public static function valid_alternative_database_name($name)
{
if (Director::isLive() || empty($name)) {
return false;
}
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
$pattern = strtolower(sprintf('/^%stmpdb\d{7}$/', $prefix));
return (bool)preg_match($pattern, $name);
} | [
"public",
"static",
"function",
"valid_alternative_database_name",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"Director",
"::",
"isLive",
"(",
")",
"||",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"prefix",
"=",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_PREFIX'",
")",
"?",
":",
"'ss_'",
";",
"$",
"pattern",
"=",
"strtolower",
"(",
"sprintf",
"(",
"'/^%stmpdb\\d{7}$/'",
",",
"$",
"prefix",
")",
")",
";",
"return",
"(",
"bool",
")",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"name",
")",
";",
"}"
]
| Determines if the name is valid, as a security
measure against setting arbitrary databases.
@param string $name
@return bool | [
"Determines",
"if",
"the",
"name",
"is",
"valid",
"as",
"a",
"security",
"measure",
"against",
"setting",
"arbitrary",
"databases",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L263-L272 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.connect | public static function connect($databaseConfig, $label = 'default')
{
// This is used by the "testsession" module to test up a test session using an alternative name
if ($name = self::get_alternative_database_name()) {
$databaseConfig['database'] = $name;
}
if (!isset($databaseConfig['type']) || empty($databaseConfig['type'])) {
throw new InvalidArgumentException("DB::connect: Not passed a valid database config");
}
self::$connection_attempted = true;
$dbClass = $databaseConfig['type'];
// Using Injector->create allows us to use registered configurations
// which may or may not map to explicit objects
$conn = Injector::inst()->create($dbClass);
self::set_conn($conn, $label);
$conn->connect($databaseConfig);
return $conn;
} | php | public static function connect($databaseConfig, $label = 'default')
{
// This is used by the "testsession" module to test up a test session using an alternative name
if ($name = self::get_alternative_database_name()) {
$databaseConfig['database'] = $name;
}
if (!isset($databaseConfig['type']) || empty($databaseConfig['type'])) {
throw new InvalidArgumentException("DB::connect: Not passed a valid database config");
}
self::$connection_attempted = true;
$dbClass = $databaseConfig['type'];
// Using Injector->create allows us to use registered configurations
// which may or may not map to explicit objects
$conn = Injector::inst()->create($dbClass);
self::set_conn($conn, $label);
$conn->connect($databaseConfig);
return $conn;
} | [
"public",
"static",
"function",
"connect",
"(",
"$",
"databaseConfig",
",",
"$",
"label",
"=",
"'default'",
")",
"{",
"// This is used by the \"testsession\" module to test up a test session using an alternative name",
"if",
"(",
"$",
"name",
"=",
"self",
"::",
"get_alternative_database_name",
"(",
")",
")",
"{",
"$",
"databaseConfig",
"[",
"'database'",
"]",
"=",
"$",
"name",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"databaseConfig",
"[",
"'type'",
"]",
")",
"||",
"empty",
"(",
"$",
"databaseConfig",
"[",
"'type'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"DB::connect: Not passed a valid database config\"",
")",
";",
"}",
"self",
"::",
"$",
"connection_attempted",
"=",
"true",
";",
"$",
"dbClass",
"=",
"$",
"databaseConfig",
"[",
"'type'",
"]",
";",
"// Using Injector->create allows us to use registered configurations",
"// which may or may not map to explicit objects",
"$",
"conn",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"dbClass",
")",
";",
"self",
"::",
"set_conn",
"(",
"$",
"conn",
",",
"$",
"label",
")",
";",
"$",
"conn",
"->",
"connect",
"(",
"$",
"databaseConfig",
")",
";",
"return",
"$",
"conn",
";",
"}"
]
| Specify connection to a database
Given the database configuration, this method will create the correct
subclass of {@link SS_Database}.
@param array $databaseConfig A map of options. The 'type' is the name of the
subclass of SS_Database to use. For the rest of the options, see the specific class.
@param string $label identifier for the connection
@return Database | [
"Specify",
"connection",
"to",
"a",
"database"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L285-L307 | train |
silverstripe/silverstripe-framework | src/ORM/DB.php | DB.create_field | public static function create_field($table, $field, $spec)
{
return self::get_schema()->createField($table, $field, $spec);
} | php | public static function create_field($table, $field, $spec)
{
return self::get_schema()->createField($table, $field, $spec);
} | [
"public",
"static",
"function",
"create_field",
"(",
"$",
"table",
",",
"$",
"field",
",",
"$",
"spec",
")",
"{",
"return",
"self",
"::",
"get_schema",
"(",
")",
"->",
"createField",
"(",
"$",
"table",
",",
"$",
"field",
",",
"$",
"spec",
")",
";",
"}"
]
| Create a new field on a table.
@param string $table Name of the table.
@param string $field Name of the field to add.
@param string $spec The field specification, eg 'INTEGER NOT NULL' | [
"Create",
"a",
"new",
"field",
"on",
"a",
"table",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DB.php#L559-L562 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Query.php | Query.column | public function column($column = null)
{
$result = array();
while ($record = $this->next()) {
if ($column) {
$result[] = $record[$column];
} else {
$result[] = $record[key($record)];
}
}
return $result;
} | php | public function column($column = null)
{
$result = array();
while ($record = $this->next()) {
if ($column) {
$result[] = $record[$column];
} else {
$result[] = $record[key($record)];
}
}
return $result;
} | [
"public",
"function",
"column",
"(",
"$",
"column",
"=",
"null",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"while",
"(",
"$",
"record",
"=",
"$",
"this",
"->",
"next",
"(",
")",
")",
"{",
"if",
"(",
"$",
"column",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"record",
"[",
"$",
"column",
"]",
";",
"}",
"else",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"record",
"[",
"key",
"(",
"$",
"record",
")",
"]",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
]
| Return an array containing all the values from a specific column. If no column is set, then the first will be
returned
@param string $column
@return array | [
"Return",
"an",
"array",
"containing",
"all",
"the",
"values",
"from",
"a",
"specific",
"column",
".",
"If",
"no",
"column",
"is",
"set",
"then",
"the",
"first",
"will",
"be",
"returned"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Query.php#L61-L74 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Query.php | Query.keyedColumn | public function keyedColumn()
{
$column = array();
foreach ($this as $record) {
$val = $record[key($record)];
$column[$val] = $val;
}
return $column;
} | php | public function keyedColumn()
{
$column = array();
foreach ($this as $record) {
$val = $record[key($record)];
$column[$val] = $val;
}
return $column;
} | [
"public",
"function",
"keyedColumn",
"(",
")",
"{",
"$",
"column",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"record",
")",
"{",
"$",
"val",
"=",
"$",
"record",
"[",
"key",
"(",
"$",
"record",
")",
"]",
";",
"$",
"column",
"[",
"$",
"val",
"]",
"=",
"$",
"val",
";",
"}",
"return",
"$",
"column",
";",
"}"
]
| Return an array containing all values in the leftmost column, where the keys are the
same as the values.
@return array | [
"Return",
"an",
"array",
"containing",
"all",
"values",
"in",
"the",
"leftmost",
"column",
"where",
"the",
"keys",
"are",
"the",
"same",
"as",
"the",
"values",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Query.php#L82-L90 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Query.php | Query.map | public function map()
{
$column = array();
foreach ($this as $record) {
$key = reset($record);
$val = next($record);
$column[$key] = $val;
}
return $column;
} | php | public function map()
{
$column = array();
foreach ($this as $record) {
$key = reset($record);
$val = next($record);
$column[$key] = $val;
}
return $column;
} | [
"public",
"function",
"map",
"(",
")",
"{",
"$",
"column",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"record",
")",
"{",
"$",
"key",
"=",
"reset",
"(",
"$",
"record",
")",
";",
"$",
"val",
"=",
"next",
"(",
"$",
"record",
")",
";",
"$",
"column",
"[",
"$",
"key",
"]",
"=",
"$",
"val",
";",
"}",
"return",
"$",
"column",
";",
"}"
]
| Return a map from the first column to the second column.
@return array | [
"Return",
"a",
"map",
"from",
"the",
"first",
"column",
"to",
"the",
"second",
"column",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Query.php#L97-L106 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Query.php | Query.table | public function table()
{
$first = true;
$result = "<table>\n";
foreach ($this as $record) {
if ($first) {
$result .= "<tr>";
foreach ($record as $k => $v) {
$result .= "<th>" . Convert::raw2xml($k) . "</th> ";
}
$result .= "</tr> \n";
}
$result .= "<tr>";
foreach ($record as $k => $v) {
$result .= "<td>" . Convert::raw2xml($v) . "</td> ";
}
$result .= "</tr> \n";
$first = false;
}
$result .= "</table>\n";
if ($first) {
return "No records found";
}
return $result;
} | php | public function table()
{
$first = true;
$result = "<table>\n";
foreach ($this as $record) {
if ($first) {
$result .= "<tr>";
foreach ($record as $k => $v) {
$result .= "<th>" . Convert::raw2xml($k) . "</th> ";
}
$result .= "</tr> \n";
}
$result .= "<tr>";
foreach ($record as $k => $v) {
$result .= "<td>" . Convert::raw2xml($v) . "</td> ";
}
$result .= "</tr> \n";
$first = false;
}
$result .= "</table>\n";
if ($first) {
return "No records found";
}
return $result;
} | [
"public",
"function",
"table",
"(",
")",
"{",
"$",
"first",
"=",
"true",
";",
"$",
"result",
"=",
"\"<table>\\n\"",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"record",
")",
"{",
"if",
"(",
"$",
"first",
")",
"{",
"$",
"result",
".=",
"\"<tr>\"",
";",
"foreach",
"(",
"$",
"record",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"result",
".=",
"\"<th>\"",
".",
"Convert",
"::",
"raw2xml",
"(",
"$",
"k",
")",
".",
"\"</th> \"",
";",
"}",
"$",
"result",
".=",
"\"</tr> \\n\"",
";",
"}",
"$",
"result",
".=",
"\"<tr>\"",
";",
"foreach",
"(",
"$",
"record",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"result",
".=",
"\"<td>\"",
".",
"Convert",
"::",
"raw2xml",
"(",
"$",
"v",
")",
".",
"\"</td> \"",
";",
"}",
"$",
"result",
".=",
"\"</tr> \\n\"",
";",
"$",
"first",
"=",
"false",
";",
"}",
"$",
"result",
".=",
"\"</table>\\n\"",
";",
"if",
"(",
"$",
"first",
")",
"{",
"return",
"\"No records found\"",
";",
"}",
"return",
"$",
"result",
";",
"}"
]
| Return an HTML table containing the full result-set
@return string | [
"Return",
"an",
"HTML",
"table",
"containing",
"the",
"full",
"result",
"-",
"set"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Query.php#L137-L165 | train |
silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | InheritedPermissions.flushMemberCache | public function flushMemberCache($memberIDs = null)
{
if (!$this->cacheService) {
return;
}
// Hard flush, e.g. flush=1
if (!$memberIDs) {
$this->cacheService->clear();
}
if ($memberIDs && is_array($memberIDs)) {
foreach ([self::VIEW, self::EDIT, self::DELETE] as $type) {
foreach ($memberIDs as $memberID) {
$key = $this->generateCacheKey($type, $memberID);
$this->cacheService->delete($key);
}
}
}
} | php | public function flushMemberCache($memberIDs = null)
{
if (!$this->cacheService) {
return;
}
// Hard flush, e.g. flush=1
if (!$memberIDs) {
$this->cacheService->clear();
}
if ($memberIDs && is_array($memberIDs)) {
foreach ([self::VIEW, self::EDIT, self::DELETE] as $type) {
foreach ($memberIDs as $memberID) {
$key = $this->generateCacheKey($type, $memberID);
$this->cacheService->delete($key);
}
}
}
} | [
"public",
"function",
"flushMemberCache",
"(",
"$",
"memberIDs",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cacheService",
")",
"{",
"return",
";",
"}",
"// Hard flush, e.g. flush=1",
"if",
"(",
"!",
"$",
"memberIDs",
")",
"{",
"$",
"this",
"->",
"cacheService",
"->",
"clear",
"(",
")",
";",
"}",
"if",
"(",
"$",
"memberIDs",
"&&",
"is_array",
"(",
"$",
"memberIDs",
")",
")",
"{",
"foreach",
"(",
"[",
"self",
"::",
"VIEW",
",",
"self",
"::",
"EDIT",
",",
"self",
"::",
"DELETE",
"]",
"as",
"$",
"type",
")",
"{",
"foreach",
"(",
"$",
"memberIDs",
"as",
"$",
"memberID",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"generateCacheKey",
"(",
"$",
"type",
",",
"$",
"memberID",
")",
";",
"$",
"this",
"->",
"cacheService",
"->",
"delete",
"(",
"$",
"key",
")",
";",
"}",
"}",
"}",
"}"
]
| Clear the cache for this instance only
@param array $memberIDs A list of member IDs | [
"Clear",
"the",
"cache",
"for",
"this",
"instance",
"only"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/InheritedPermissions.php#L132-L151 | train |
silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | InheritedPermissions.prePopulatePermissionCache | public function prePopulatePermissionCache($permission = 'edit', $ids = [])
{
switch ($permission) {
case self::EDIT:
$this->canEditMultiple($ids, Security::getCurrentUser(), false);
break;
case self::VIEW:
$this->canViewMultiple($ids, Security::getCurrentUser(), false);
break;
case self::DELETE:
$this->canDeleteMultiple($ids, Security::getCurrentUser(), false);
break;
default:
throw new InvalidArgumentException("Invalid permission type $permission");
}
} | php | public function prePopulatePermissionCache($permission = 'edit', $ids = [])
{
switch ($permission) {
case self::EDIT:
$this->canEditMultiple($ids, Security::getCurrentUser(), false);
break;
case self::VIEW:
$this->canViewMultiple($ids, Security::getCurrentUser(), false);
break;
case self::DELETE:
$this->canDeleteMultiple($ids, Security::getCurrentUser(), false);
break;
default:
throw new InvalidArgumentException("Invalid permission type $permission");
}
} | [
"public",
"function",
"prePopulatePermissionCache",
"(",
"$",
"permission",
"=",
"'edit'",
",",
"$",
"ids",
"=",
"[",
"]",
")",
"{",
"switch",
"(",
"$",
"permission",
")",
"{",
"case",
"self",
"::",
"EDIT",
":",
"$",
"this",
"->",
"canEditMultiple",
"(",
"$",
"ids",
",",
"Security",
"::",
"getCurrentUser",
"(",
")",
",",
"false",
")",
";",
"break",
";",
"case",
"self",
"::",
"VIEW",
":",
"$",
"this",
"->",
"canViewMultiple",
"(",
"$",
"ids",
",",
"Security",
"::",
"getCurrentUser",
"(",
")",
",",
"false",
")",
";",
"break",
";",
"case",
"self",
"::",
"DELETE",
":",
"$",
"this",
"->",
"canDeleteMultiple",
"(",
"$",
"ids",
",",
"Security",
"::",
"getCurrentUser",
"(",
")",
",",
"false",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid permission type $permission\"",
")",
";",
"}",
"}"
]
| Force pre-calculation of a list of permissions for optimisation
@param string $permission
@param array $ids | [
"Force",
"pre",
"-",
"calculation",
"of",
"a",
"list",
"of",
"permissions",
"for",
"optimisation"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/InheritedPermissions.php#L209-L224 | train |
silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | InheritedPermissions.checkDefaultPermissions | protected function checkDefaultPermissions($type, Member $member = null)
{
$defaultPermissions = $this->getDefaultPermissions();
if (!$defaultPermissions) {
return false;
}
switch ($type) {
case self::VIEW:
return $defaultPermissions->canView($member);
case self::EDIT:
return $defaultPermissions->canEdit($member);
case self::DELETE:
return $defaultPermissions->canDelete($member);
default:
return false;
}
} | php | protected function checkDefaultPermissions($type, Member $member = null)
{
$defaultPermissions = $this->getDefaultPermissions();
if (!$defaultPermissions) {
return false;
}
switch ($type) {
case self::VIEW:
return $defaultPermissions->canView($member);
case self::EDIT:
return $defaultPermissions->canEdit($member);
case self::DELETE:
return $defaultPermissions->canDelete($member);
default:
return false;
}
} | [
"protected",
"function",
"checkDefaultPermissions",
"(",
"$",
"type",
",",
"Member",
"$",
"member",
"=",
"null",
")",
"{",
"$",
"defaultPermissions",
"=",
"$",
"this",
"->",
"getDefaultPermissions",
"(",
")",
";",
"if",
"(",
"!",
"$",
"defaultPermissions",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"self",
"::",
"VIEW",
":",
"return",
"$",
"defaultPermissions",
"->",
"canView",
"(",
"$",
"member",
")",
";",
"case",
"self",
"::",
"EDIT",
":",
"return",
"$",
"defaultPermissions",
"->",
"canEdit",
"(",
"$",
"member",
")",
";",
"case",
"self",
"::",
"DELETE",
":",
"return",
"$",
"defaultPermissions",
"->",
"canDelete",
"(",
"$",
"member",
")",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
]
| Determine default permission for a givion check
@param string $type Method to check
@param Member $member
@return bool | [
"Determine",
"default",
"permission",
"for",
"a",
"givion",
"check"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/InheritedPermissions.php#L651-L667 | train |
silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | InheritedPermissions.isVersioned | protected function isVersioned()
{
if (!class_exists(Versioned::class)) {
return false;
}
/** @var Versioned|DataObject $singleton */
$singleton = DataObject::singleton($this->getBaseClass());
return $singleton->hasExtension(Versioned::class) && $singleton->hasStages();
} | php | protected function isVersioned()
{
if (!class_exists(Versioned::class)) {
return false;
}
/** @var Versioned|DataObject $singleton */
$singleton = DataObject::singleton($this->getBaseClass());
return $singleton->hasExtension(Versioned::class) && $singleton->hasStages();
} | [
"protected",
"function",
"isVersioned",
"(",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"Versioned",
"::",
"class",
")",
")",
"{",
"return",
"false",
";",
"}",
"/** @var Versioned|DataObject $singleton */",
"$",
"singleton",
"=",
"DataObject",
"::",
"singleton",
"(",
"$",
"this",
"->",
"getBaseClass",
"(",
")",
")",
";",
"return",
"$",
"singleton",
"->",
"hasExtension",
"(",
"Versioned",
"::",
"class",
")",
"&&",
"$",
"singleton",
"->",
"hasStages",
"(",
")",
";",
"}"
]
| Check if this model has versioning
@return bool | [
"Check",
"if",
"this",
"model",
"has",
"versioning"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/InheritedPermissions.php#L674-L682 | train |
silverstripe/silverstripe-framework | src/Security/InheritedPermissions.php | InheritedPermissions.getCachePermissions | protected function getCachePermissions($cacheKey)
{
// Check local cache
if (isset($this->cachePermissions[$cacheKey])) {
return $this->cachePermissions[$cacheKey];
}
// Check persistent cache
if ($this->cacheService) {
$result = $this->cacheService->get($cacheKey);
// Warm local cache
if ($result) {
$this->cachePermissions[$cacheKey] = $result;
return $result;
}
}
return null;
} | php | protected function getCachePermissions($cacheKey)
{
// Check local cache
if (isset($this->cachePermissions[$cacheKey])) {
return $this->cachePermissions[$cacheKey];
}
// Check persistent cache
if ($this->cacheService) {
$result = $this->cacheService->get($cacheKey);
// Warm local cache
if ($result) {
$this->cachePermissions[$cacheKey] = $result;
return $result;
}
}
return null;
} | [
"protected",
"function",
"getCachePermissions",
"(",
"$",
"cacheKey",
")",
"{",
"// Check local cache",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"cachePermissions",
"[",
"$",
"cacheKey",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"cachePermissions",
"[",
"$",
"cacheKey",
"]",
";",
"}",
"// Check persistent cache",
"if",
"(",
"$",
"this",
"->",
"cacheService",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"cacheService",
"->",
"get",
"(",
"$",
"cacheKey",
")",
";",
"// Warm local cache",
"if",
"(",
"$",
"result",
")",
"{",
"$",
"this",
"->",
"cachePermissions",
"[",
"$",
"cacheKey",
"]",
"=",
"$",
"result",
";",
"return",
"$",
"result",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Gets the permission from cache
@param string $cacheKey
@return mixed | [
"Gets",
"the",
"permission",
"from",
"cache"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/InheritedPermissions.php#L721-L740 | train |
silverstripe/silverstripe-framework | src/ORM/ManyManyThroughQueryManipulator.php | ManyManyThroughQueryManipulator.extractInheritableQueryParameters | public function extractInheritableQueryParameters(DataQuery $query)
{
$params = $query->getQueryParams();
// Remove `Foreign.` query parameters for created objects,
// as this would interfere with relations on those objects.
foreach (array_keys($params) as $key) {
if (stripos($key, 'Foreign.') === 0) {
unset($params[$key]);
}
}
// Get inheritable parameters from an instance of the base query dataclass
$inst = Injector::inst()->create($query->dataClass());
$inst->setSourceQueryParams($params);
return $inst->getInheritableQueryParams();
} | php | public function extractInheritableQueryParameters(DataQuery $query)
{
$params = $query->getQueryParams();
// Remove `Foreign.` query parameters for created objects,
// as this would interfere with relations on those objects.
foreach (array_keys($params) as $key) {
if (stripos($key, 'Foreign.') === 0) {
unset($params[$key]);
}
}
// Get inheritable parameters from an instance of the base query dataclass
$inst = Injector::inst()->create($query->dataClass());
$inst->setSourceQueryParams($params);
return $inst->getInheritableQueryParams();
} | [
"public",
"function",
"extractInheritableQueryParameters",
"(",
"DataQuery",
"$",
"query",
")",
"{",
"$",
"params",
"=",
"$",
"query",
"->",
"getQueryParams",
"(",
")",
";",
"// Remove `Foreign.` query parameters for created objects,",
"// as this would interfere with relations on those objects.",
"foreach",
"(",
"array_keys",
"(",
"$",
"params",
")",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"stripos",
"(",
"$",
"key",
",",
"'Foreign.'",
")",
"===",
"0",
")",
"{",
"unset",
"(",
"$",
"params",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"// Get inheritable parameters from an instance of the base query dataclass",
"$",
"inst",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"query",
"->",
"dataClass",
"(",
")",
")",
";",
"$",
"inst",
"->",
"setSourceQueryParams",
"(",
"$",
"params",
")",
";",
"return",
"$",
"inst",
"->",
"getInheritableQueryParams",
"(",
")",
";",
"}"
]
| Calculate the query parameters that should be inherited from the base many_many
to the nested has_many list.
@param DataQuery $query
@return mixed | [
"Calculate",
"the",
"query",
"parameters",
"that",
"should",
"be",
"inherited",
"from",
"the",
"base",
"many_many",
"to",
"the",
"nested",
"has_many",
"list",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/ManyManyThroughQueryManipulator.php#L199-L215 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/MySQLStatement.php | MySQLStatement.bind | protected function bind()
{
$variables = array();
// Bind each field
while ($field = $this->metadata->fetch_field()) {
$this->columns[] = $field->name;
$this->types[$field->name] = $field->type;
// Note that while boundValues isn't initialised at this point,
// later calls to $this->statement->fetch() Will populate
// $this->boundValues later with the next result.
$variables[] = &$this->boundValues[$field->name];
}
$this->bound = true;
$this->metadata->free();
// Buffer all results
$this->statement->store_result();
call_user_func_array(array($this->statement, 'bind_result'), $variables);
} | php | protected function bind()
{
$variables = array();
// Bind each field
while ($field = $this->metadata->fetch_field()) {
$this->columns[] = $field->name;
$this->types[$field->name] = $field->type;
// Note that while boundValues isn't initialised at this point,
// later calls to $this->statement->fetch() Will populate
// $this->boundValues later with the next result.
$variables[] = &$this->boundValues[$field->name];
}
$this->bound = true;
$this->metadata->free();
// Buffer all results
$this->statement->store_result();
call_user_func_array(array($this->statement, 'bind_result'), $variables);
} | [
"protected",
"function",
"bind",
"(",
")",
"{",
"$",
"variables",
"=",
"array",
"(",
")",
";",
"// Bind each field",
"while",
"(",
"$",
"field",
"=",
"$",
"this",
"->",
"metadata",
"->",
"fetch_field",
"(",
")",
")",
"{",
"$",
"this",
"->",
"columns",
"[",
"]",
"=",
"$",
"field",
"->",
"name",
";",
"$",
"this",
"->",
"types",
"[",
"$",
"field",
"->",
"name",
"]",
"=",
"$",
"field",
"->",
"type",
";",
"// Note that while boundValues isn't initialised at this point,",
"// later calls to $this->statement->fetch() Will populate",
"// $this->boundValues later with the next result.",
"$",
"variables",
"[",
"]",
"=",
"&",
"$",
"this",
"->",
"boundValues",
"[",
"$",
"field",
"->",
"name",
"]",
";",
"}",
"$",
"this",
"->",
"bound",
"=",
"true",
";",
"$",
"this",
"->",
"metadata",
"->",
"free",
"(",
")",
";",
"// Buffer all results",
"$",
"this",
"->",
"statement",
"->",
"store_result",
"(",
")",
";",
"call_user_func_array",
"(",
"array",
"(",
"$",
"this",
"->",
"statement",
",",
"'bind_result'",
")",
",",
"$",
"variables",
")",
";",
"}"
]
| Binds this statement to the variables | [
"Binds",
"this",
"statement",
"to",
"the",
"variables"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLStatement.php#L62-L83 | train |
silverstripe/silverstripe-framework | src/ORM/Filters/SearchFilter.php | SearchFilter.addRelation | protected function addRelation($name)
{
if (strstr($name, '.')) {
$parts = explode('.', $name);
$this->name = array_pop($parts);
$this->relation = $parts;
} else {
$this->name = $name;
}
} | php | protected function addRelation($name)
{
if (strstr($name, '.')) {
$parts = explode('.', $name);
$this->name = array_pop($parts);
$this->relation = $parts;
} else {
$this->name = $name;
}
} | [
"protected",
"function",
"addRelation",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"strstr",
"(",
"$",
"name",
",",
"'.'",
")",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"name",
")",
";",
"$",
"this",
"->",
"name",
"=",
"array_pop",
"(",
"$",
"parts",
")",
";",
"$",
"this",
"->",
"relation",
"=",
"$",
"parts",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"name",
"=",
"$",
"name",
";",
"}",
"}"
]
| Called by constructor to convert a string pathname into
a well defined relationship sequence.
@param string $name | [
"Called",
"by",
"constructor",
"to",
"convert",
"a",
"string",
"pathname",
"into",
"a",
"well",
"defined",
"relationship",
"sequence",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Filters/SearchFilter.php#L105-L114 | train |
silverstripe/silverstripe-framework | src/ORM/Filters/SearchFilter.php | SearchFilter.setModifiers | public function setModifiers(array $modifiers)
{
$modifiers = array_map('strtolower', $modifiers);
// Validate modifiers are supported
$allowed = $this->getSupportedModifiers();
$unsupported = array_diff($modifiers, $allowed);
if ($unsupported) {
throw new InvalidArgumentException(
static::class . ' does not accept ' . implode(', ', $unsupported) . ' as modifiers'
);
}
$this->modifiers = $modifiers;
} | php | public function setModifiers(array $modifiers)
{
$modifiers = array_map('strtolower', $modifiers);
// Validate modifiers are supported
$allowed = $this->getSupportedModifiers();
$unsupported = array_diff($modifiers, $allowed);
if ($unsupported) {
throw new InvalidArgumentException(
static::class . ' does not accept ' . implode(', ', $unsupported) . ' as modifiers'
);
}
$this->modifiers = $modifiers;
} | [
"public",
"function",
"setModifiers",
"(",
"array",
"$",
"modifiers",
")",
"{",
"$",
"modifiers",
"=",
"array_map",
"(",
"'strtolower'",
",",
"$",
"modifiers",
")",
";",
"// Validate modifiers are supported",
"$",
"allowed",
"=",
"$",
"this",
"->",
"getSupportedModifiers",
"(",
")",
";",
"$",
"unsupported",
"=",
"array_diff",
"(",
"$",
"modifiers",
",",
"$",
"allowed",
")",
";",
"if",
"(",
"$",
"unsupported",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"static",
"::",
"class",
".",
"' does not accept '",
".",
"implode",
"(",
"', '",
",",
"$",
"unsupported",
")",
".",
"' as modifiers'",
")",
";",
"}",
"$",
"this",
"->",
"modifiers",
"=",
"$",
"modifiers",
";",
"}"
]
| Set the current modifiers to apply to the filter
@param array $modifiers | [
"Set",
"the",
"current",
"modifiers",
"to",
"apply",
"to",
"the",
"filter"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Filters/SearchFilter.php#L179-L193 | train |
silverstripe/silverstripe-framework | src/ORM/Filters/SearchFilter.php | SearchFilter.getDbName | public function getDbName()
{
// Special handler for "NULL" relations
if ($this->name === "NULL") {
return $this->name;
}
// Ensure that we're dealing with a DataObject.
if (!is_subclass_of($this->model, DataObject::class)) {
throw new InvalidArgumentException(
"Model supplied to " . static::class . " should be an instance of DataObject."
);
}
$tablePrefix = DataQuery::applyRelationPrefix($this->relation);
$schema = DataObject::getSchema();
if ($this->aggregate) {
$column = $this->aggregate['column'];
$function = $this->aggregate['function'];
$table = $column ?
$schema->tableForField($this->model, $column) :
$schema->baseDataTable($this->model);
if (!$table) {
throw new InvalidArgumentException(sprintf(
'Invalid column %s for aggregate function %s on %s',
$column,
$function,
$this->model
));
}
return sprintf(
'%s("%s%s".%s)',
$function,
$tablePrefix,
$table,
$column ? "\"$column\"" : '"ID"'
);
}
// Check if this column is a table on the current model
$table = $schema->tableForField($this->model, $this->name);
if ($table) {
return $schema->sqlColumnForField($this->model, $this->name, $tablePrefix);
}
// fallback to the provided name in the event of a joined column
// name (as the candidate class doesn't check joined records)
$parts = explode('.', $this->fullName);
return '"' . implode('"."', $parts) . '"';
} | php | public function getDbName()
{
// Special handler for "NULL" relations
if ($this->name === "NULL") {
return $this->name;
}
// Ensure that we're dealing with a DataObject.
if (!is_subclass_of($this->model, DataObject::class)) {
throw new InvalidArgumentException(
"Model supplied to " . static::class . " should be an instance of DataObject."
);
}
$tablePrefix = DataQuery::applyRelationPrefix($this->relation);
$schema = DataObject::getSchema();
if ($this->aggregate) {
$column = $this->aggregate['column'];
$function = $this->aggregate['function'];
$table = $column ?
$schema->tableForField($this->model, $column) :
$schema->baseDataTable($this->model);
if (!$table) {
throw new InvalidArgumentException(sprintf(
'Invalid column %s for aggregate function %s on %s',
$column,
$function,
$this->model
));
}
return sprintf(
'%s("%s%s".%s)',
$function,
$tablePrefix,
$table,
$column ? "\"$column\"" : '"ID"'
);
}
// Check if this column is a table on the current model
$table = $schema->tableForField($this->model, $this->name);
if ($table) {
return $schema->sqlColumnForField($this->model, $this->name, $tablePrefix);
}
// fallback to the provided name in the event of a joined column
// name (as the candidate class doesn't check joined records)
$parts = explode('.', $this->fullName);
return '"' . implode('"."', $parts) . '"';
} | [
"public",
"function",
"getDbName",
"(",
")",
"{",
"// Special handler for \"NULL\" relations",
"if",
"(",
"$",
"this",
"->",
"name",
"===",
"\"NULL\"",
")",
"{",
"return",
"$",
"this",
"->",
"name",
";",
"}",
"// Ensure that we're dealing with a DataObject.",
"if",
"(",
"!",
"is_subclass_of",
"(",
"$",
"this",
"->",
"model",
",",
"DataObject",
"::",
"class",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Model supplied to \"",
".",
"static",
"::",
"class",
".",
"\" should be an instance of DataObject.\"",
")",
";",
"}",
"$",
"tablePrefix",
"=",
"DataQuery",
"::",
"applyRelationPrefix",
"(",
"$",
"this",
"->",
"relation",
")",
";",
"$",
"schema",
"=",
"DataObject",
"::",
"getSchema",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"aggregate",
")",
"{",
"$",
"column",
"=",
"$",
"this",
"->",
"aggregate",
"[",
"'column'",
"]",
";",
"$",
"function",
"=",
"$",
"this",
"->",
"aggregate",
"[",
"'function'",
"]",
";",
"$",
"table",
"=",
"$",
"column",
"?",
"$",
"schema",
"->",
"tableForField",
"(",
"$",
"this",
"->",
"model",
",",
"$",
"column",
")",
":",
"$",
"schema",
"->",
"baseDataTable",
"(",
"$",
"this",
"->",
"model",
")",
";",
"if",
"(",
"!",
"$",
"table",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Invalid column %s for aggregate function %s on %s'",
",",
"$",
"column",
",",
"$",
"function",
",",
"$",
"this",
"->",
"model",
")",
")",
";",
"}",
"return",
"sprintf",
"(",
"'%s(\"%s%s\".%s)'",
",",
"$",
"function",
",",
"$",
"tablePrefix",
",",
"$",
"table",
",",
"$",
"column",
"?",
"\"\\\"$column\\\"\"",
":",
"'\"ID\"'",
")",
";",
"}",
"// Check if this column is a table on the current model",
"$",
"table",
"=",
"$",
"schema",
"->",
"tableForField",
"(",
"$",
"this",
"->",
"model",
",",
"$",
"this",
"->",
"name",
")",
";",
"if",
"(",
"$",
"table",
")",
"{",
"return",
"$",
"schema",
"->",
"sqlColumnForField",
"(",
"$",
"this",
"->",
"model",
",",
"$",
"this",
"->",
"name",
",",
"$",
"tablePrefix",
")",
";",
"}",
"// fallback to the provided name in the event of a joined column",
"// name (as the candidate class doesn't check joined records)",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"this",
"->",
"fullName",
")",
";",
"return",
"'\"'",
".",
"implode",
"(",
"'\".\"'",
",",
"$",
"parts",
")",
".",
"'\"'",
";",
"}"
]
| Normalizes the field name to table mapping.
@return string | [
"Normalizes",
"the",
"field",
"name",
"to",
"table",
"mapping",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Filters/SearchFilter.php#L258-L310 | train |
silverstripe/silverstripe-framework | src/ORM/Filters/SearchFilter.php | SearchFilter.getDbFormattedValue | public function getDbFormattedValue()
{
// SRM: This code finds the table where the field named $this->name lives
// Todo: move to somewhere more appropriate, such as DataMapper, the magical class-to-be?
if ($this->aggregate) {
return intval($this->value);
}
/** @var DBField $dbField */
$dbField = singleton($this->model)->dbObject($this->name);
$dbField->setValue($this->value);
return $dbField->RAW();
} | php | public function getDbFormattedValue()
{
// SRM: This code finds the table where the field named $this->name lives
// Todo: move to somewhere more appropriate, such as DataMapper, the magical class-to-be?
if ($this->aggregate) {
return intval($this->value);
}
/** @var DBField $dbField */
$dbField = singleton($this->model)->dbObject($this->name);
$dbField->setValue($this->value);
return $dbField->RAW();
} | [
"public",
"function",
"getDbFormattedValue",
"(",
")",
"{",
"// SRM: This code finds the table where the field named $this->name lives",
"// Todo: move to somewhere more appropriate, such as DataMapper, the magical class-to-be?",
"if",
"(",
"$",
"this",
"->",
"aggregate",
")",
"{",
"return",
"intval",
"(",
"$",
"this",
"->",
"value",
")",
";",
"}",
"/** @var DBField $dbField */",
"$",
"dbField",
"=",
"singleton",
"(",
"$",
"this",
"->",
"model",
")",
"->",
"dbObject",
"(",
"$",
"this",
"->",
"name",
")",
";",
"$",
"dbField",
"->",
"setValue",
"(",
"$",
"this",
"->",
"value",
")",
";",
"return",
"$",
"dbField",
"->",
"RAW",
"(",
")",
";",
"}"
]
| Return the value of the field as processed by the DBField class
@return string | [
"Return",
"the",
"value",
"of",
"the",
"field",
"as",
"processed",
"by",
"the",
"DBField",
"class"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Filters/SearchFilter.php#L317-L330 | train |
silverstripe/silverstripe-framework | src/ORM/Filters/SearchFilter.php | SearchFilter.applyAggregate | public function applyAggregate(DataQuery $query, $having)
{
$schema = DataObject::getSchema();
$baseTable = $schema->baseDataTable($query->dataClass());
return $query
->having($having)
->groupby("\"{$baseTable}\".\"ID\"");
} | php | public function applyAggregate(DataQuery $query, $having)
{
$schema = DataObject::getSchema();
$baseTable = $schema->baseDataTable($query->dataClass());
return $query
->having($having)
->groupby("\"{$baseTable}\".\"ID\"");
} | [
"public",
"function",
"applyAggregate",
"(",
"DataQuery",
"$",
"query",
",",
"$",
"having",
")",
"{",
"$",
"schema",
"=",
"DataObject",
"::",
"getSchema",
"(",
")",
";",
"$",
"baseTable",
"=",
"$",
"schema",
"->",
"baseDataTable",
"(",
"$",
"query",
"->",
"dataClass",
"(",
")",
")",
";",
"return",
"$",
"query",
"->",
"having",
"(",
"$",
"having",
")",
"->",
"groupby",
"(",
"\"\\\"{$baseTable}\\\".\\\"ID\\\"\"",
")",
";",
"}"
]
| Given an escaped HAVING clause, add it along with the appropriate GROUP BY clause
@param DataQuery $query
@param string $having
@return DataQuery | [
"Given",
"an",
"escaped",
"HAVING",
"clause",
"add",
"it",
"along",
"with",
"the",
"appropriate",
"GROUP",
"BY",
"clause"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Filters/SearchFilter.php#L338-L346 | train |
silverstripe/silverstripe-framework | src/ORM/Filters/SearchFilter.php | SearchFilter.exclude | public function exclude(DataQuery $query)
{
if (($key = array_search('not', $this->modifiers)) !== false) {
unset($this->modifiers[$key]);
return $this->apply($query);
}
if (is_array($this->value)) {
return $this->excludeMany($query);
} else {
return $this->excludeOne($query);
}
} | php | public function exclude(DataQuery $query)
{
if (($key = array_search('not', $this->modifiers)) !== false) {
unset($this->modifiers[$key]);
return $this->apply($query);
}
if (is_array($this->value)) {
return $this->excludeMany($query);
} else {
return $this->excludeOne($query);
}
} | [
"public",
"function",
"exclude",
"(",
"DataQuery",
"$",
"query",
")",
"{",
"if",
"(",
"(",
"$",
"key",
"=",
"array_search",
"(",
"'not'",
",",
"$",
"this",
"->",
"modifiers",
")",
")",
"!==",
"false",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"modifiers",
"[",
"$",
"key",
"]",
")",
";",
"return",
"$",
"this",
"->",
"apply",
"(",
"$",
"query",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"value",
")",
")",
"{",
"return",
"$",
"this",
"->",
"excludeMany",
"(",
"$",
"query",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"excludeOne",
"(",
"$",
"query",
")",
";",
"}",
"}"
]
| Exclude filter criteria from a SQL query.
@param DataQuery $query
@return DataQuery | [
"Exclude",
"filter",
"criteria",
"from",
"a",
"SQL",
"query",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Filters/SearchFilter.php#L392-L403 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/DBConnector.php | DBConnector.databaseError | protected function databaseError($msg, $errorLevel = E_USER_ERROR, $sql = null, $parameters = array())
{
// Prevent errors when error checking is set at zero level
if (empty($errorLevel)) {
return;
}
// Format query if given
if (!empty($sql)) {
$formatter = new SQLFormatter();
$formattedSQL = $formatter->formatPlain($sql);
$msg = "Couldn't run query:\n\n{$formattedSQL}\n\n{$msg}";
}
if ($errorLevel === E_USER_ERROR) {
// Treating errors as exceptions better allows for responding to errors
// in code, such as credential checking during installation
throw new DatabaseException($msg, 0, null, $sql, $parameters);
} else {
user_error($msg, $errorLevel);
}
} | php | protected function databaseError($msg, $errorLevel = E_USER_ERROR, $sql = null, $parameters = array())
{
// Prevent errors when error checking is set at zero level
if (empty($errorLevel)) {
return;
}
// Format query if given
if (!empty($sql)) {
$formatter = new SQLFormatter();
$formattedSQL = $formatter->formatPlain($sql);
$msg = "Couldn't run query:\n\n{$formattedSQL}\n\n{$msg}";
}
if ($errorLevel === E_USER_ERROR) {
// Treating errors as exceptions better allows for responding to errors
// in code, such as credential checking during installation
throw new DatabaseException($msg, 0, null, $sql, $parameters);
} else {
user_error($msg, $errorLevel);
}
} | [
"protected",
"function",
"databaseError",
"(",
"$",
"msg",
",",
"$",
"errorLevel",
"=",
"E_USER_ERROR",
",",
"$",
"sql",
"=",
"null",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"// Prevent errors when error checking is set at zero level",
"if",
"(",
"empty",
"(",
"$",
"errorLevel",
")",
")",
"{",
"return",
";",
"}",
"// Format query if given",
"if",
"(",
"!",
"empty",
"(",
"$",
"sql",
")",
")",
"{",
"$",
"formatter",
"=",
"new",
"SQLFormatter",
"(",
")",
";",
"$",
"formattedSQL",
"=",
"$",
"formatter",
"->",
"formatPlain",
"(",
"$",
"sql",
")",
";",
"$",
"msg",
"=",
"\"Couldn't run query:\\n\\n{$formattedSQL}\\n\\n{$msg}\"",
";",
"}",
"if",
"(",
"$",
"errorLevel",
"===",
"E_USER_ERROR",
")",
"{",
"// Treating errors as exceptions better allows for responding to errors",
"// in code, such as credential checking during installation",
"throw",
"new",
"DatabaseException",
"(",
"$",
"msg",
",",
"0",
",",
"null",
",",
"$",
"sql",
",",
"$",
"parameters",
")",
";",
"}",
"else",
"{",
"user_error",
"(",
"$",
"msg",
",",
"$",
"errorLevel",
")",
";",
"}",
"}"
]
| Error handler for database errors.
All database errors will call this function to report the error. It isn't a static function;
it will be called on the object itself and as such can be overridden in a subclass.
Subclasses should run all errors through this function.
@todo hook this into a more well-structured error handling system.
@param string $msg The error message.
@param integer $errorLevel The level of the error to throw.
@param string $sql The SQL related to this query
@param array $parameters Parameters passed to the query
@throws DatabaseException | [
"Error",
"handler",
"for",
"database",
"errors",
".",
"All",
"database",
"errors",
"will",
"call",
"this",
"function",
"to",
"report",
"the",
"error",
".",
"It",
"isn",
"t",
"a",
"static",
"function",
";",
"it",
"will",
"be",
"called",
"on",
"the",
"object",
"itself",
"and",
"as",
"such",
"can",
"be",
"overridden",
"in",
"a",
"subclass",
".",
"Subclasses",
"should",
"run",
"all",
"errors",
"through",
"this",
"function",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBConnector.php#L47-L68 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/DBConnector.php | DBConnector.isQueryDDL | public function isQueryDDL($sql)
{
$operations = Config::inst()->get(static::class, 'ddl_operations');
return $this->isQueryType($sql, $operations);
} | php | public function isQueryDDL($sql)
{
$operations = Config::inst()->get(static::class, 'ddl_operations');
return $this->isQueryType($sql, $operations);
} | [
"public",
"function",
"isQueryDDL",
"(",
"$",
"sql",
")",
"{",
"$",
"operations",
"=",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"static",
"::",
"class",
",",
"'ddl_operations'",
")",
";",
"return",
"$",
"this",
"->",
"isQueryType",
"(",
"$",
"sql",
",",
"$",
"operations",
")",
";",
"}"
]
| Determine if this SQL statement is a DDL operation
@param string $sql
@return bool | [
"Determine",
"if",
"this",
"SQL",
"statement",
"is",
"a",
"DDL",
"operation"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBConnector.php#L91-L95 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/DBConnector.php | DBConnector.isQueryType | protected function isQueryType($sql, $type)
{
if (!preg_match('/^(?<operation>\w+)\b/', $sql, $matches)) {
return false;
}
$operation = $matches['operation'];
if (is_array($type)) {
return in_array(strtolower($operation), $type);
} else {
return strcasecmp($sql, $type) === 0;
}
} | php | protected function isQueryType($sql, $type)
{
if (!preg_match('/^(?<operation>\w+)\b/', $sql, $matches)) {
return false;
}
$operation = $matches['operation'];
if (is_array($type)) {
return in_array(strtolower($operation), $type);
} else {
return strcasecmp($sql, $type) === 0;
}
} | [
"protected",
"function",
"isQueryType",
"(",
"$",
"sql",
",",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/^(?<operation>\\w+)\\b/'",
",",
"$",
"sql",
",",
"$",
"matches",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"operation",
"=",
"$",
"matches",
"[",
"'operation'",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"type",
")",
")",
"{",
"return",
"in_array",
"(",
"strtolower",
"(",
"$",
"operation",
")",
",",
"$",
"type",
")",
";",
"}",
"else",
"{",
"return",
"strcasecmp",
"(",
"$",
"sql",
",",
"$",
"type",
")",
"===",
"0",
";",
"}",
"}"
]
| Determine if a query is of the given type
@param string $sql Raw SQL
@param string|array $type Type or list of types (first word in the query). Must be lowercase
@return bool | [
"Determine",
"if",
"a",
"query",
"is",
"of",
"the",
"given",
"type"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBConnector.php#L117-L128 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/DBConnector.php | DBConnector.parameterValues | protected function parameterValues($parameters)
{
$values = array();
foreach ($parameters as $value) {
$values[] = is_array($value) ? $value['value'] : $value;
}
return $values;
} | php | protected function parameterValues($parameters)
{
$values = array();
foreach ($parameters as $value) {
$values[] = is_array($value) ? $value['value'] : $value;
}
return $values;
} | [
"protected",
"function",
"parameterValues",
"(",
"$",
"parameters",
")",
"{",
"$",
"values",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"parameters",
"as",
"$",
"value",
")",
"{",
"$",
"values",
"[",
"]",
"=",
"is_array",
"(",
"$",
"value",
")",
"?",
"$",
"value",
"[",
"'value'",
"]",
":",
"$",
"value",
";",
"}",
"return",
"$",
"values",
";",
"}"
]
| Extracts only the parameter values for error reporting
@param array $parameters
@return array List of parameter values | [
"Extracts",
"only",
"the",
"parameter",
"values",
"for",
"error",
"reporting"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/DBConnector.php#L136-L143 | train |
silverstripe/silverstripe-framework | src/Security/SecurityToken.php | SecurityToken.getSession | protected function getSession()
{
$injector = Injector::inst();
if ($injector->has(HTTPRequest::class)) {
return $injector->get(HTTPRequest::class)->getSession();
} elseif (Controller::has_curr()) {
return Controller::curr()->getRequest()->getSession();
}
throw new Exception('No HTTPRequest object or controller available yet!');
} | php | protected function getSession()
{
$injector = Injector::inst();
if ($injector->has(HTTPRequest::class)) {
return $injector->get(HTTPRequest::class)->getSession();
} elseif (Controller::has_curr()) {
return Controller::curr()->getRequest()->getSession();
}
throw new Exception('No HTTPRequest object or controller available yet!');
} | [
"protected",
"function",
"getSession",
"(",
")",
"{",
"$",
"injector",
"=",
"Injector",
"::",
"inst",
"(",
")",
";",
"if",
"(",
"$",
"injector",
"->",
"has",
"(",
"HTTPRequest",
"::",
"class",
")",
")",
"{",
"return",
"$",
"injector",
"->",
"get",
"(",
"HTTPRequest",
"::",
"class",
")",
"->",
"getSession",
"(",
")",
";",
"}",
"elseif",
"(",
"Controller",
"::",
"has_curr",
"(",
")",
")",
"{",
"return",
"Controller",
"::",
"curr",
"(",
")",
"->",
"getRequest",
"(",
")",
"->",
"getSession",
"(",
")",
";",
"}",
"throw",
"new",
"Exception",
"(",
"'No HTTPRequest object or controller available yet!'",
")",
";",
"}"
]
| Returns the current session instance from the injector
@return Session
@throws Exception If the HTTPRequest class hasn't been registered as a service and no controllers exist | [
"Returns",
"the",
"current",
"session",
"instance",
"from",
"the",
"injector"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/SecurityToken.php#L183-L192 | train |
silverstripe/silverstripe-framework | src/Security/SecurityToken.php | SecurityToken.getRequestToken | protected function getRequestToken($request)
{
$name = $this->getName();
$header = 'X-' . ucwords(strtolower($name));
if ($token = $request->getHeader($header)) {
return $token;
}
// Get from request var
return $request->requestVar($name);
} | php | protected function getRequestToken($request)
{
$name = $this->getName();
$header = 'X-' . ucwords(strtolower($name));
if ($token = $request->getHeader($header)) {
return $token;
}
// Get from request var
return $request->requestVar($name);
} | [
"protected",
"function",
"getRequestToken",
"(",
"$",
"request",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
";",
"$",
"header",
"=",
"'X-'",
".",
"ucwords",
"(",
"strtolower",
"(",
"$",
"name",
")",
")",
";",
"if",
"(",
"$",
"token",
"=",
"$",
"request",
"->",
"getHeader",
"(",
"$",
"header",
")",
")",
"{",
"return",
"$",
"token",
";",
"}",
"// Get from request var",
"return",
"$",
"request",
"->",
"requestVar",
"(",
"$",
"name",
")",
";",
"}"
]
| Get security token from request
@param HTTPRequest $request
@return string | [
"Get",
"security",
"token",
"from",
"request"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/SecurityToken.php#L237-L247 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBString.php | DBString.setOptions | public function setOptions(array $options = [])
{
parent::setOptions($options);
if (array_key_exists('nullifyEmpty', $options)) {
$this->options['nullifyEmpty'] = (bool) $options['nullifyEmpty'];
}
if (array_key_exists('default', $options)) {
$this->setDefaultValue($options['default']);
}
return $this;
} | php | public function setOptions(array $options = [])
{
parent::setOptions($options);
if (array_key_exists('nullifyEmpty', $options)) {
$this->options['nullifyEmpty'] = (bool) $options['nullifyEmpty'];
}
if (array_key_exists('default', $options)) {
$this->setDefaultValue($options['default']);
}
return $this;
} | [
"public",
"function",
"setOptions",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"parent",
"::",
"setOptions",
"(",
"$",
"options",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"'nullifyEmpty'",
",",
"$",
"options",
")",
")",
"{",
"$",
"this",
"->",
"options",
"[",
"'nullifyEmpty'",
"]",
"=",
"(",
"bool",
")",
"$",
"options",
"[",
"'nullifyEmpty'",
"]",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'default'",
",",
"$",
"options",
")",
")",
"{",
"$",
"this",
"->",
"setDefaultValue",
"(",
"$",
"options",
"[",
"'default'",
"]",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Update the optional parameters for this field.
@param array $options Array of options
The options allowed are:
<ul><li>"nullifyEmpty"
This is a boolean flag.
True (the default) means that empty strings are automatically converted to nulls to be stored in
the database. Set it to false to ensure that nulls and empty strings are kept intact in the database.
</li></ul>
@return $this | [
"Update",
"the",
"optional",
"parameters",
"for",
"this",
"field",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBString.php#L45-L57 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBString.php | DBString.LimitCharactersToClosestWord | public function LimitCharactersToClosestWord($limit = 20, $add = '...')
{
// Safely convert to plain text
$value = $this->Plain();
// Determine if value exceeds limit before limiting characters
if (mb_strlen($value) <= $limit) {
return $value;
}
// Limit to character limit
$value = mb_substr($value, 0, $limit);
// If value exceeds limit, strip punctuation off the end to the last space and apply ellipsis
$value = preg_replace(
'/[^\w_]+$/',
'',
mb_substr($value, 0, mb_strrpos($value, " "))
) . $add;
return $value;
} | php | public function LimitCharactersToClosestWord($limit = 20, $add = '...')
{
// Safely convert to plain text
$value = $this->Plain();
// Determine if value exceeds limit before limiting characters
if (mb_strlen($value) <= $limit) {
return $value;
}
// Limit to character limit
$value = mb_substr($value, 0, $limit);
// If value exceeds limit, strip punctuation off the end to the last space and apply ellipsis
$value = preg_replace(
'/[^\w_]+$/',
'',
mb_substr($value, 0, mb_strrpos($value, " "))
) . $add;
return $value;
} | [
"public",
"function",
"LimitCharactersToClosestWord",
"(",
"$",
"limit",
"=",
"20",
",",
"$",
"add",
"=",
"'...'",
")",
"{",
"// Safely convert to plain text",
"$",
"value",
"=",
"$",
"this",
"->",
"Plain",
"(",
")",
";",
"// Determine if value exceeds limit before limiting characters",
"if",
"(",
"mb_strlen",
"(",
"$",
"value",
")",
"<=",
"$",
"limit",
")",
"{",
"return",
"$",
"value",
";",
"}",
"// Limit to character limit",
"$",
"value",
"=",
"mb_substr",
"(",
"$",
"value",
",",
"0",
",",
"$",
"limit",
")",
";",
"// If value exceeds limit, strip punctuation off the end to the last space and apply ellipsis",
"$",
"value",
"=",
"preg_replace",
"(",
"'/[^\\w_]+$/'",
",",
"''",
",",
"mb_substr",
"(",
"$",
"value",
",",
"0",
",",
"mb_strrpos",
"(",
"$",
"value",
",",
"\" \"",
")",
")",
")",
".",
"$",
"add",
";",
"return",
"$",
"value",
";",
"}"
]
| Limit this field's content by a number of characters and truncate
the field to the closest complete word. All HTML tags are stripped
from the field.
@param int $limit Number of characters to limit by
@param string $add Ellipsis to add to the end of truncated string
@return string Plain text value with limited characters | [
"Limit",
"this",
"field",
"s",
"content",
"by",
"a",
"number",
"of",
"characters",
"and",
"truncate",
"the",
"field",
"to",
"the",
"closest",
"complete",
"word",
".",
"All",
"HTML",
"tags",
"are",
"stripped",
"from",
"the",
"field",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBString.php#L143-L163 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBString.php | DBString.LimitWordCount | public function LimitWordCount($numWords = 26, $add = '...')
{
$value = $this->Plain();
$words = explode(' ', $value);
if (count($words) <= $numWords) {
return $value;
}
// Limit
$words = array_slice($words, 0, $numWords);
return implode(' ', $words) . $add;
} | php | public function LimitWordCount($numWords = 26, $add = '...')
{
$value = $this->Plain();
$words = explode(' ', $value);
if (count($words) <= $numWords) {
return $value;
}
// Limit
$words = array_slice($words, 0, $numWords);
return implode(' ', $words) . $add;
} | [
"public",
"function",
"LimitWordCount",
"(",
"$",
"numWords",
"=",
"26",
",",
"$",
"add",
"=",
"'...'",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"Plain",
"(",
")",
";",
"$",
"words",
"=",
"explode",
"(",
"' '",
",",
"$",
"value",
")",
";",
"if",
"(",
"count",
"(",
"$",
"words",
")",
"<=",
"$",
"numWords",
")",
"{",
"return",
"$",
"value",
";",
"}",
"// Limit",
"$",
"words",
"=",
"array_slice",
"(",
"$",
"words",
",",
"0",
",",
"$",
"numWords",
")",
";",
"return",
"implode",
"(",
"' '",
",",
"$",
"words",
")",
".",
"$",
"add",
";",
"}"
]
| Limit this field's content by a number of words.
@param int $numWords Number of words to limit by.
@param string $add Ellipsis to add to the end of truncated string.
@return string | [
"Limit",
"this",
"field",
"s",
"content",
"by",
"a",
"number",
"of",
"words",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBString.php#L173-L184 | train |
silverstripe/silverstripe-framework | src/View/SSViewer_Scope.php | SSViewer_Scope.locally | public function locally()
{
list(
$this->item,
$this->itemIterator,
$this->itemIteratorTotal,
$this->popIndex,
$this->upIndex,
$this->currentIndex
) = $this->itemStack[$this->localIndex];
// Remember any un-completed (resetLocalScope hasn't been called) lookup chain. Even if there isn't an
// un-completed chain we need to store an empty item, as resetLocalScope doesn't know the difference later
$this->localStack[] = array_splice($this->itemStack, $this->localIndex + 1);
return $this;
} | php | public function locally()
{
list(
$this->item,
$this->itemIterator,
$this->itemIteratorTotal,
$this->popIndex,
$this->upIndex,
$this->currentIndex
) = $this->itemStack[$this->localIndex];
// Remember any un-completed (resetLocalScope hasn't been called) lookup chain. Even if there isn't an
// un-completed chain we need to store an empty item, as resetLocalScope doesn't know the difference later
$this->localStack[] = array_splice($this->itemStack, $this->localIndex + 1);
return $this;
} | [
"public",
"function",
"locally",
"(",
")",
"{",
"list",
"(",
"$",
"this",
"->",
"item",
",",
"$",
"this",
"->",
"itemIterator",
",",
"$",
"this",
"->",
"itemIteratorTotal",
",",
"$",
"this",
"->",
"popIndex",
",",
"$",
"this",
"->",
"upIndex",
",",
"$",
"this",
"->",
"currentIndex",
")",
"=",
"$",
"this",
"->",
"itemStack",
"[",
"$",
"this",
"->",
"localIndex",
"]",
";",
"// Remember any un-completed (resetLocalScope hasn't been called) lookup chain. Even if there isn't an",
"// un-completed chain we need to store an empty item, as resetLocalScope doesn't know the difference later",
"$",
"this",
"->",
"localStack",
"[",
"]",
"=",
"array_splice",
"(",
"$",
"this",
"->",
"itemStack",
",",
"$",
"this",
"->",
"localIndex",
"+",
"1",
")",
";",
"return",
"$",
"this",
";",
"}"
]
| Called at the start of every lookup chain by SSTemplateParser to indicate a new lookup from local scope
@return self | [
"Called",
"at",
"the",
"start",
"of",
"every",
"lookup",
"chain",
"by",
"SSTemplateParser",
"to",
"indicate",
"a",
"new",
"lookup",
"from",
"local",
"scope"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_Scope.php#L131-L147 | train |
silverstripe/silverstripe-framework | src/View/SSViewer_Scope.php | SSViewer_Scope.resetLocalScope | public function resetLocalScope()
{
// Restore previous un-completed lookup chain if set
$previousLocalState = $this->localStack ? array_pop($this->localStack) : null;
array_splice($this->itemStack, $this->localIndex + 1, count($this->itemStack), $previousLocalState);
list(
$this->item,
$this->itemIterator,
$this->itemIteratorTotal,
$this->popIndex,
$this->upIndex,
$this->currentIndex
) = end($this->itemStack);
} | php | public function resetLocalScope()
{
// Restore previous un-completed lookup chain if set
$previousLocalState = $this->localStack ? array_pop($this->localStack) : null;
array_splice($this->itemStack, $this->localIndex + 1, count($this->itemStack), $previousLocalState);
list(
$this->item,
$this->itemIterator,
$this->itemIteratorTotal,
$this->popIndex,
$this->upIndex,
$this->currentIndex
) = end($this->itemStack);
} | [
"public",
"function",
"resetLocalScope",
"(",
")",
"{",
"// Restore previous un-completed lookup chain if set",
"$",
"previousLocalState",
"=",
"$",
"this",
"->",
"localStack",
"?",
"array_pop",
"(",
"$",
"this",
"->",
"localStack",
")",
":",
"null",
";",
"array_splice",
"(",
"$",
"this",
"->",
"itemStack",
",",
"$",
"this",
"->",
"localIndex",
"+",
"1",
",",
"count",
"(",
"$",
"this",
"->",
"itemStack",
")",
",",
"$",
"previousLocalState",
")",
";",
"list",
"(",
"$",
"this",
"->",
"item",
",",
"$",
"this",
"->",
"itemIterator",
",",
"$",
"this",
"->",
"itemIteratorTotal",
",",
"$",
"this",
"->",
"popIndex",
",",
"$",
"this",
"->",
"upIndex",
",",
"$",
"this",
"->",
"currentIndex",
")",
"=",
"end",
"(",
"$",
"this",
"->",
"itemStack",
")",
";",
"}"
]
| Reset the local scope - restores saved state to the "global" item stack. Typically called after
a lookup chain has been completed | [
"Reset",
"the",
"local",
"scope",
"-",
"restores",
"saved",
"state",
"to",
"the",
"global",
"item",
"stack",
".",
"Typically",
"called",
"after",
"a",
"lookup",
"chain",
"has",
"been",
"completed"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_Scope.php#L153-L167 | train |
silverstripe/silverstripe-framework | src/View/SSViewer_Scope.php | SSViewer_Scope.self | public function self()
{
$result = $this->itemIterator ? $this->itemIterator->current() : $this->item;
$this->resetLocalScope();
return $result;
} | php | public function self()
{
$result = $this->itemIterator ? $this->itemIterator->current() : $this->item;
$this->resetLocalScope();
return $result;
} | [
"public",
"function",
"self",
"(",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"itemIterator",
"?",
"$",
"this",
"->",
"itemIterator",
"->",
"current",
"(",
")",
":",
"$",
"this",
"->",
"item",
";",
"$",
"this",
"->",
"resetLocalScope",
"(",
")",
";",
"return",
"$",
"result",
";",
"}"
]
| Gets the current object and resets the scope.
@return object | [
"Gets",
"the",
"current",
"object",
"and",
"resets",
"the",
"scope",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_Scope.php#L240-L246 | train |
silverstripe/silverstripe-framework | src/View/SSViewer_Scope.php | SSViewer_Scope.next | public function next()
{
if (!$this->item) {
return false;
}
if (!$this->itemIterator) {
if (is_array($this->item)) {
$this->itemIterator = new ArrayIterator($this->item);
} else {
$this->itemIterator = $this->item->getIterator();
}
$this->itemStack[$this->localIndex][SSViewer_Scope::ITEM_ITERATOR] = $this->itemIterator;
$this->itemIteratorTotal = iterator_count($this->itemIterator); // Count the total number of items
$this->itemStack[$this->localIndex][SSViewer_Scope::ITEM_ITERATOR_TOTAL] = $this->itemIteratorTotal;
$this->itemIterator->rewind();
} else {
$this->itemIterator->next();
}
$this->resetLocalScope();
if (!$this->itemIterator->valid()) {
return false;
}
return $this->itemIterator->key();
} | php | public function next()
{
if (!$this->item) {
return false;
}
if (!$this->itemIterator) {
if (is_array($this->item)) {
$this->itemIterator = new ArrayIterator($this->item);
} else {
$this->itemIterator = $this->item->getIterator();
}
$this->itemStack[$this->localIndex][SSViewer_Scope::ITEM_ITERATOR] = $this->itemIterator;
$this->itemIteratorTotal = iterator_count($this->itemIterator); // Count the total number of items
$this->itemStack[$this->localIndex][SSViewer_Scope::ITEM_ITERATOR_TOTAL] = $this->itemIteratorTotal;
$this->itemIterator->rewind();
} else {
$this->itemIterator->next();
}
$this->resetLocalScope();
if (!$this->itemIterator->valid()) {
return false;
}
return $this->itemIterator->key();
} | [
"public",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"item",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"itemIterator",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"item",
")",
")",
"{",
"$",
"this",
"->",
"itemIterator",
"=",
"new",
"ArrayIterator",
"(",
"$",
"this",
"->",
"item",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"itemIterator",
"=",
"$",
"this",
"->",
"item",
"->",
"getIterator",
"(",
")",
";",
"}",
"$",
"this",
"->",
"itemStack",
"[",
"$",
"this",
"->",
"localIndex",
"]",
"[",
"SSViewer_Scope",
"::",
"ITEM_ITERATOR",
"]",
"=",
"$",
"this",
"->",
"itemIterator",
";",
"$",
"this",
"->",
"itemIteratorTotal",
"=",
"iterator_count",
"(",
"$",
"this",
"->",
"itemIterator",
")",
";",
"// Count the total number of items",
"$",
"this",
"->",
"itemStack",
"[",
"$",
"this",
"->",
"localIndex",
"]",
"[",
"SSViewer_Scope",
"::",
"ITEM_ITERATOR_TOTAL",
"]",
"=",
"$",
"this",
"->",
"itemIteratorTotal",
";",
"$",
"this",
"->",
"itemIterator",
"->",
"rewind",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"itemIterator",
"->",
"next",
"(",
")",
";",
"}",
"$",
"this",
"->",
"resetLocalScope",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"itemIterator",
"->",
"valid",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"itemIterator",
"->",
"key",
"(",
")",
";",
"}"
]
| Fast-forwards the current iterator to the next item
@return mixed | [
"Fast",
"-",
"forwards",
"the",
"current",
"iterator",
"to",
"the",
"next",
"item"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_Scope.php#L285-L313 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.isDBTemp | protected function isDBTemp($name)
{
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
$result = preg_match(
sprintf('/^%stmpdb_[0-9]+_[0-9]+$/i', preg_quote($prefix, '/')),
$name
);
return $result === 1;
} | php | protected function isDBTemp($name)
{
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
$result = preg_match(
sprintf('/^%stmpdb_[0-9]+_[0-9]+$/i', preg_quote($prefix, '/')),
$name
);
return $result === 1;
} | [
"protected",
"function",
"isDBTemp",
"(",
"$",
"name",
")",
"{",
"$",
"prefix",
"=",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_PREFIX'",
")",
"?",
":",
"'ss_'",
";",
"$",
"result",
"=",
"preg_match",
"(",
"sprintf",
"(",
"'/^%stmpdb_[0-9]+_[0-9]+$/i'",
",",
"preg_quote",
"(",
"$",
"prefix",
",",
"'/'",
")",
")",
",",
"$",
"name",
")",
";",
"return",
"$",
"result",
"===",
"1",
";",
"}"
]
| Check if the given name matches the temp_db pattern
@param string $name
@return bool | [
"Check",
"if",
"the",
"given",
"name",
"matches",
"the",
"temp_db",
"pattern"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L50-L58 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.rollbackTransaction | public function rollbackTransaction()
{
// Ensure a rollback can be performed
$success = static::getConn()->supportsTransactions()
&& static::getConn()->transactionDepth();
if (!$success) {
return false;
}
try {
// Explicit false = gnostic error from transactionRollback
if (static::getConn()->transactionRollback() === false) {
return false;
}
return true;
} catch (DatabaseException $ex) {
return false;
}
} | php | public function rollbackTransaction()
{
// Ensure a rollback can be performed
$success = static::getConn()->supportsTransactions()
&& static::getConn()->transactionDepth();
if (!$success) {
return false;
}
try {
// Explicit false = gnostic error from transactionRollback
if (static::getConn()->transactionRollback() === false) {
return false;
}
return true;
} catch (DatabaseException $ex) {
return false;
}
} | [
"public",
"function",
"rollbackTransaction",
"(",
")",
"{",
"// Ensure a rollback can be performed",
"$",
"success",
"=",
"static",
"::",
"getConn",
"(",
")",
"->",
"supportsTransactions",
"(",
")",
"&&",
"static",
"::",
"getConn",
"(",
")",
"->",
"transactionDepth",
"(",
")",
";",
"if",
"(",
"!",
"$",
"success",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"// Explicit false = gnostic error from transactionRollback",
"if",
"(",
"static",
"::",
"getConn",
"(",
")",
"->",
"transactionRollback",
"(",
")",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"catch",
"(",
"DatabaseException",
"$",
"ex",
")",
"{",
"return",
"false",
";",
"}",
"}"
]
| Rollback a transaction (or trash all data if the DB doesn't support databases
@return bool True if successfully rolled back, false otherwise. On error the DB is
killed and must be re-created. Note that calling rollbackTransaction() when there
is no transaction is counted as a failure, user code should either kill or flush the DB
as necessary | [
"Rollback",
"a",
"transaction",
"(",
"or",
"trash",
"all",
"data",
"if",
"the",
"DB",
"doesn",
"t",
"support",
"databases"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L105-L122 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.kill | public function kill()
{
// Nothing to kill
if (!$this->isUsed()) {
return;
}
// Rollback any transactions (note: Success ignored)
$this->rollbackTransaction();
// Check the database actually exists
$dbConn = $this->getConn();
$dbName = $dbConn->getSelectedDatabase();
if (!$dbConn->databaseExists($dbName)) {
return;
}
// Some DataExtensions keep a static cache of information that needs to
// be reset whenever the database is killed
foreach (ClassInfo::subclassesFor(DataExtension::class) as $class) {
$toCall = array($class, 'on_db_reset');
if (is_callable($toCall)) {
call_user_func($toCall);
}
}
$dbConn->dropSelectedDatabase();
} | php | public function kill()
{
// Nothing to kill
if (!$this->isUsed()) {
return;
}
// Rollback any transactions (note: Success ignored)
$this->rollbackTransaction();
// Check the database actually exists
$dbConn = $this->getConn();
$dbName = $dbConn->getSelectedDatabase();
if (!$dbConn->databaseExists($dbName)) {
return;
}
// Some DataExtensions keep a static cache of information that needs to
// be reset whenever the database is killed
foreach (ClassInfo::subclassesFor(DataExtension::class) as $class) {
$toCall = array($class, 'on_db_reset');
if (is_callable($toCall)) {
call_user_func($toCall);
}
}
$dbConn->dropSelectedDatabase();
} | [
"public",
"function",
"kill",
"(",
")",
"{",
"// Nothing to kill",
"if",
"(",
"!",
"$",
"this",
"->",
"isUsed",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Rollback any transactions (note: Success ignored)",
"$",
"this",
"->",
"rollbackTransaction",
"(",
")",
";",
"// Check the database actually exists",
"$",
"dbConn",
"=",
"$",
"this",
"->",
"getConn",
"(",
")",
";",
"$",
"dbName",
"=",
"$",
"dbConn",
"->",
"getSelectedDatabase",
"(",
")",
";",
"if",
"(",
"!",
"$",
"dbConn",
"->",
"databaseExists",
"(",
"$",
"dbName",
")",
")",
"{",
"return",
";",
"}",
"// Some DataExtensions keep a static cache of information that needs to",
"// be reset whenever the database is killed",
"foreach",
"(",
"ClassInfo",
"::",
"subclassesFor",
"(",
"DataExtension",
"::",
"class",
")",
"as",
"$",
"class",
")",
"{",
"$",
"toCall",
"=",
"array",
"(",
"$",
"class",
",",
"'on_db_reset'",
")",
";",
"if",
"(",
"is_callable",
"(",
"$",
"toCall",
")",
")",
"{",
"call_user_func",
"(",
"$",
"toCall",
")",
";",
"}",
"}",
"$",
"dbConn",
"->",
"dropSelectedDatabase",
"(",
")",
";",
"}"
]
| Destroy the current temp database | [
"Destroy",
"the",
"current",
"temp",
"database"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L127-L154 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.clearAllData | public function clearAllData()
{
if (!$this->isUsed()) {
return;
}
$this->getConn()->clearAllData();
// Some DataExtensions keep a static cache of information that needs to
// be reset whenever the database is cleaned out
$classes = array_merge(
ClassInfo::subclassesFor(DataExtension::class),
ClassInfo::subclassesFor(DataObject::class)
);
foreach ($classes as $class) {
$toCall = array($class, 'on_db_reset');
if (is_callable($toCall)) {
call_user_func($toCall);
}
}
} | php | public function clearAllData()
{
if (!$this->isUsed()) {
return;
}
$this->getConn()->clearAllData();
// Some DataExtensions keep a static cache of information that needs to
// be reset whenever the database is cleaned out
$classes = array_merge(
ClassInfo::subclassesFor(DataExtension::class),
ClassInfo::subclassesFor(DataObject::class)
);
foreach ($classes as $class) {
$toCall = array($class, 'on_db_reset');
if (is_callable($toCall)) {
call_user_func($toCall);
}
}
} | [
"public",
"function",
"clearAllData",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isUsed",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"getConn",
"(",
")",
"->",
"clearAllData",
"(",
")",
";",
"// Some DataExtensions keep a static cache of information that needs to",
"// be reset whenever the database is cleaned out",
"$",
"classes",
"=",
"array_merge",
"(",
"ClassInfo",
"::",
"subclassesFor",
"(",
"DataExtension",
"::",
"class",
")",
",",
"ClassInfo",
"::",
"subclassesFor",
"(",
"DataObject",
"::",
"class",
")",
")",
";",
"foreach",
"(",
"$",
"classes",
"as",
"$",
"class",
")",
"{",
"$",
"toCall",
"=",
"array",
"(",
"$",
"class",
",",
"'on_db_reset'",
")",
";",
"if",
"(",
"is_callable",
"(",
"$",
"toCall",
")",
")",
"{",
"call_user_func",
"(",
"$",
"toCall",
")",
";",
"}",
"}",
"}"
]
| Remove all content from the temporary database. | [
"Remove",
"all",
"content",
"from",
"the",
"temporary",
"database",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L159-L179 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.build | public function build()
{
// Disable PHPUnit error handling
$oldErrorHandler = set_error_handler(null);
// Create a temporary database, and force the connection to use UTC for time
$dbConn = $this->getConn();
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
do {
$dbname = strtolower(sprintf('%stmpdb_%s_%s', $prefix, time(), rand(1000000, 9999999)));
} while ($dbConn->databaseExists($dbname));
$dbConn->selectDatabase($dbname, true);
$this->resetDBSchema();
// Reinstate PHPUnit error handling
set_error_handler($oldErrorHandler);
// Ensure test db is killed on exit
$teardownOnExit = Config::inst()->get(static::class, 'teardown_on_exit');
if ($teardownOnExit) {
register_shutdown_function(function () {
try {
$this->kill();
} catch (Exception $ex) {
// An exception thrown while trying to remove a test database shouldn't fail a build, ignore
}
});
}
return $dbname;
} | php | public function build()
{
// Disable PHPUnit error handling
$oldErrorHandler = set_error_handler(null);
// Create a temporary database, and force the connection to use UTC for time
$dbConn = $this->getConn();
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
do {
$dbname = strtolower(sprintf('%stmpdb_%s_%s', $prefix, time(), rand(1000000, 9999999)));
} while ($dbConn->databaseExists($dbname));
$dbConn->selectDatabase($dbname, true);
$this->resetDBSchema();
// Reinstate PHPUnit error handling
set_error_handler($oldErrorHandler);
// Ensure test db is killed on exit
$teardownOnExit = Config::inst()->get(static::class, 'teardown_on_exit');
if ($teardownOnExit) {
register_shutdown_function(function () {
try {
$this->kill();
} catch (Exception $ex) {
// An exception thrown while trying to remove a test database shouldn't fail a build, ignore
}
});
}
return $dbname;
} | [
"public",
"function",
"build",
"(",
")",
"{",
"// Disable PHPUnit error handling",
"$",
"oldErrorHandler",
"=",
"set_error_handler",
"(",
"null",
")",
";",
"// Create a temporary database, and force the connection to use UTC for time",
"$",
"dbConn",
"=",
"$",
"this",
"->",
"getConn",
"(",
")",
";",
"$",
"prefix",
"=",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_PREFIX'",
")",
"?",
":",
"'ss_'",
";",
"do",
"{",
"$",
"dbname",
"=",
"strtolower",
"(",
"sprintf",
"(",
"'%stmpdb_%s_%s'",
",",
"$",
"prefix",
",",
"time",
"(",
")",
",",
"rand",
"(",
"1000000",
",",
"9999999",
")",
")",
")",
";",
"}",
"while",
"(",
"$",
"dbConn",
"->",
"databaseExists",
"(",
"$",
"dbname",
")",
")",
";",
"$",
"dbConn",
"->",
"selectDatabase",
"(",
"$",
"dbname",
",",
"true",
")",
";",
"$",
"this",
"->",
"resetDBSchema",
"(",
")",
";",
"// Reinstate PHPUnit error handling",
"set_error_handler",
"(",
"$",
"oldErrorHandler",
")",
";",
"// Ensure test db is killed on exit",
"$",
"teardownOnExit",
"=",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"static",
"::",
"class",
",",
"'teardown_on_exit'",
")",
";",
"if",
"(",
"$",
"teardownOnExit",
")",
"{",
"register_shutdown_function",
"(",
"function",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"kill",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"ex",
")",
"{",
"// An exception thrown while trying to remove a test database shouldn't fail a build, ignore",
"}",
"}",
")",
";",
"}",
"return",
"$",
"dbname",
";",
"}"
]
| Create temp DB without creating extra objects
@return string DB name | [
"Create",
"temp",
"DB",
"without",
"creating",
"extra",
"objects"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L186-L218 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.rebuildTables | protected function rebuildTables($extraDataObjects = [])
{
DataObject::reset();
// clear singletons, they're caching old extension info which is used in DatabaseAdmin->doBuild()
Injector::inst()->unregisterObjects(DataObject::class);
$dataClasses = ClassInfo::subclassesFor(DataObject::class);
array_shift($dataClasses);
$schema = $this->getConn()->getSchemaManager();
$schema->quiet();
$schema->schemaUpdate(function () use ($dataClasses, $extraDataObjects) {
foreach ($dataClasses as $dataClass) {
// Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
if (class_exists($dataClass)) {
$SNG = singleton($dataClass);
if (!($SNG instanceof TestOnly)) {
$SNG->requireTable();
}
}
}
// If we have additional dataobjects which need schema, do so here:
if ($extraDataObjects) {
foreach ($extraDataObjects as $dataClass) {
$SNG = singleton($dataClass);
if (singleton($dataClass) instanceof DataObject) {
$SNG->requireTable();
}
}
}
});
ClassInfo::reset_db_cache();
DataObject::singleton()->flushCache();
} | php | protected function rebuildTables($extraDataObjects = [])
{
DataObject::reset();
// clear singletons, they're caching old extension info which is used in DatabaseAdmin->doBuild()
Injector::inst()->unregisterObjects(DataObject::class);
$dataClasses = ClassInfo::subclassesFor(DataObject::class);
array_shift($dataClasses);
$schema = $this->getConn()->getSchemaManager();
$schema->quiet();
$schema->schemaUpdate(function () use ($dataClasses, $extraDataObjects) {
foreach ($dataClasses as $dataClass) {
// Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
if (class_exists($dataClass)) {
$SNG = singleton($dataClass);
if (!($SNG instanceof TestOnly)) {
$SNG->requireTable();
}
}
}
// If we have additional dataobjects which need schema, do so here:
if ($extraDataObjects) {
foreach ($extraDataObjects as $dataClass) {
$SNG = singleton($dataClass);
if (singleton($dataClass) instanceof DataObject) {
$SNG->requireTable();
}
}
}
});
ClassInfo::reset_db_cache();
DataObject::singleton()->flushCache();
} | [
"protected",
"function",
"rebuildTables",
"(",
"$",
"extraDataObjects",
"=",
"[",
"]",
")",
"{",
"DataObject",
"::",
"reset",
"(",
")",
";",
"// clear singletons, they're caching old extension info which is used in DatabaseAdmin->doBuild()",
"Injector",
"::",
"inst",
"(",
")",
"->",
"unregisterObjects",
"(",
"DataObject",
"::",
"class",
")",
";",
"$",
"dataClasses",
"=",
"ClassInfo",
"::",
"subclassesFor",
"(",
"DataObject",
"::",
"class",
")",
";",
"array_shift",
"(",
"$",
"dataClasses",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"getConn",
"(",
")",
"->",
"getSchemaManager",
"(",
")",
";",
"$",
"schema",
"->",
"quiet",
"(",
")",
";",
"$",
"schema",
"->",
"schemaUpdate",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"dataClasses",
",",
"$",
"extraDataObjects",
")",
"{",
"foreach",
"(",
"$",
"dataClasses",
"as",
"$",
"dataClass",
")",
"{",
"// Check if class exists before trying to instantiate - this sidesteps any manifest weirdness",
"if",
"(",
"class_exists",
"(",
"$",
"dataClass",
")",
")",
"{",
"$",
"SNG",
"=",
"singleton",
"(",
"$",
"dataClass",
")",
";",
"if",
"(",
"!",
"(",
"$",
"SNG",
"instanceof",
"TestOnly",
")",
")",
"{",
"$",
"SNG",
"->",
"requireTable",
"(",
")",
";",
"}",
"}",
"}",
"// If we have additional dataobjects which need schema, do so here:",
"if",
"(",
"$",
"extraDataObjects",
")",
"{",
"foreach",
"(",
"$",
"extraDataObjects",
"as",
"$",
"dataClass",
")",
"{",
"$",
"SNG",
"=",
"singleton",
"(",
"$",
"dataClass",
")",
";",
"if",
"(",
"singleton",
"(",
"$",
"dataClass",
")",
"instanceof",
"DataObject",
")",
"{",
"$",
"SNG",
"->",
"requireTable",
"(",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"ClassInfo",
"::",
"reset_db_cache",
"(",
")",
";",
"DataObject",
"::",
"singleton",
"(",
")",
"->",
"flushCache",
"(",
")",
";",
"}"
]
| Rebuild all database tables
@param array $extraDataObjects | [
"Rebuild",
"all",
"database",
"tables"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L225-L261 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.deleteAll | public function deleteAll()
{
$schema = $this->getConn()->getSchemaManager();
foreach ($schema->databaseList() as $dbName) {
if ($this->isDBTemp($dbName)) {
$schema->dropDatabase($dbName);
$schema->alterationMessage("Dropped database \"$dbName\"", 'deleted');
flush();
}
}
} | php | public function deleteAll()
{
$schema = $this->getConn()->getSchemaManager();
foreach ($schema->databaseList() as $dbName) {
if ($this->isDBTemp($dbName)) {
$schema->dropDatabase($dbName);
$schema->alterationMessage("Dropped database \"$dbName\"", 'deleted');
flush();
}
}
} | [
"public",
"function",
"deleteAll",
"(",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"getConn",
"(",
")",
"->",
"getSchemaManager",
"(",
")",
";",
"foreach",
"(",
"$",
"schema",
"->",
"databaseList",
"(",
")",
"as",
"$",
"dbName",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isDBTemp",
"(",
"$",
"dbName",
")",
")",
"{",
"$",
"schema",
"->",
"dropDatabase",
"(",
"$",
"dbName",
")",
";",
"$",
"schema",
"->",
"alterationMessage",
"(",
"\"Dropped database \\\"$dbName\\\"\"",
",",
"'deleted'",
")",
";",
"flush",
"(",
")",
";",
"}",
"}",
"}"
]
| Clear all temp DBs on this connection
Note: This will output results to stdout unless suppressOutput
is set on the current db schema | [
"Clear",
"all",
"temp",
"DBs",
"on",
"this",
"connection"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L269-L279 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/TempDatabase.php | TempDatabase.resetDBSchema | public function resetDBSchema(array $extraDataObjects = [])
{
// Skip if no DB
if (!$this->isUsed()) {
return;
}
try {
$this->rebuildTables($extraDataObjects);
} catch (DatabaseException $ex) {
// In case of error during build force a hard reset
// e.g. pgsql doesn't allow schema updates inside transactions
$this->kill();
$this->build();
$this->rebuildTables($extraDataObjects);
}
} | php | public function resetDBSchema(array $extraDataObjects = [])
{
// Skip if no DB
if (!$this->isUsed()) {
return;
}
try {
$this->rebuildTables($extraDataObjects);
} catch (DatabaseException $ex) {
// In case of error during build force a hard reset
// e.g. pgsql doesn't allow schema updates inside transactions
$this->kill();
$this->build();
$this->rebuildTables($extraDataObjects);
}
} | [
"public",
"function",
"resetDBSchema",
"(",
"array",
"$",
"extraDataObjects",
"=",
"[",
"]",
")",
"{",
"// Skip if no DB",
"if",
"(",
"!",
"$",
"this",
"->",
"isUsed",
"(",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"rebuildTables",
"(",
"$",
"extraDataObjects",
")",
";",
"}",
"catch",
"(",
"DatabaseException",
"$",
"ex",
")",
"{",
"// In case of error during build force a hard reset",
"// e.g. pgsql doesn't allow schema updates inside transactions",
"$",
"this",
"->",
"kill",
"(",
")",
";",
"$",
"this",
"->",
"build",
"(",
")",
";",
"$",
"this",
"->",
"rebuildTables",
"(",
"$",
"extraDataObjects",
")",
";",
"}",
"}"
]
| Reset the testing database's schema.
@param array $extraDataObjects List of extra dataobjects to build | [
"Reset",
"the",
"testing",
"database",
"s",
"schema",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/TempDatabase.php#L286-L302 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/AllowedHostsMiddleware.php | AllowedHostsMiddleware.setAllowedHosts | public function setAllowedHosts($allowedHosts)
{
if (is_string($allowedHosts)) {
$allowedHosts = preg_split('/ *, */', $allowedHosts);
}
$this->allowedHosts = $allowedHosts;
return $this;
} | php | public function setAllowedHosts($allowedHosts)
{
if (is_string($allowedHosts)) {
$allowedHosts = preg_split('/ *, */', $allowedHosts);
}
$this->allowedHosts = $allowedHosts;
return $this;
} | [
"public",
"function",
"setAllowedHosts",
"(",
"$",
"allowedHosts",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"allowedHosts",
")",
")",
"{",
"$",
"allowedHosts",
"=",
"preg_split",
"(",
"'/ *, */'",
",",
"$",
"allowedHosts",
")",
";",
"}",
"$",
"this",
"->",
"allowedHosts",
"=",
"$",
"allowedHosts",
";",
"return",
"$",
"this",
";",
"}"
]
| Sets the list of allowed Host header values
Can also specify a comma separated list
@param array|string $allowedHosts
@return $this | [
"Sets",
"the",
"list",
"of",
"allowed",
"Host",
"header",
"values",
"Can",
"also",
"specify",
"a",
"comma",
"separated",
"list"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/AllowedHostsMiddleware.php#L36-L43 | train |
silverstripe/silverstripe-framework | src/Dev/Debug.php | Debug.caller | public static function caller()
{
$bt = debug_backtrace();
$caller = isset($bt[2]) ? $bt[2] : array();
$caller['line'] = $bt[1]['line'];
$caller['file'] = $bt[1]['file'];
if (!isset($caller['class'])) {
$caller['class'] = '';
}
if (!isset($caller['type'])) {
$caller['type'] = '';
}
if (!isset($caller['function'])) {
$caller['function'] = '';
}
return $caller;
} | php | public static function caller()
{
$bt = debug_backtrace();
$caller = isset($bt[2]) ? $bt[2] : array();
$caller['line'] = $bt[1]['line'];
$caller['file'] = $bt[1]['file'];
if (!isset($caller['class'])) {
$caller['class'] = '';
}
if (!isset($caller['type'])) {
$caller['type'] = '';
}
if (!isset($caller['function'])) {
$caller['function'] = '';
}
return $caller;
} | [
"public",
"static",
"function",
"caller",
"(",
")",
"{",
"$",
"bt",
"=",
"debug_backtrace",
"(",
")",
";",
"$",
"caller",
"=",
"isset",
"(",
"$",
"bt",
"[",
"2",
"]",
")",
"?",
"$",
"bt",
"[",
"2",
"]",
":",
"array",
"(",
")",
";",
"$",
"caller",
"[",
"'line'",
"]",
"=",
"$",
"bt",
"[",
"1",
"]",
"[",
"'line'",
"]",
";",
"$",
"caller",
"[",
"'file'",
"]",
"=",
"$",
"bt",
"[",
"1",
"]",
"[",
"'file'",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"caller",
"[",
"'class'",
"]",
")",
")",
"{",
"$",
"caller",
"[",
"'class'",
"]",
"=",
"''",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"caller",
"[",
"'type'",
"]",
")",
")",
"{",
"$",
"caller",
"[",
"'type'",
"]",
"=",
"''",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"caller",
"[",
"'function'",
"]",
")",
")",
"{",
"$",
"caller",
"[",
"'function'",
"]",
"=",
"''",
";",
"}",
"return",
"$",
"caller",
";",
"}"
]
| Returns the caller for a specific method
@return array | [
"Returns",
"the",
"caller",
"for",
"a",
"specific",
"method"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Debug.php#L60-L76 | train |
silverstripe/silverstripe-framework | src/Dev/Debug.php | Debug.endshow | public static function endshow($val, $showHeader = true, HTTPRequest $request = null)
{
// Don't show on live
if (Director::isLive()) {
return;
}
echo static::create_debug_view($request)
->debugVariable($val, static::caller(), $showHeader);
die();
} | php | public static function endshow($val, $showHeader = true, HTTPRequest $request = null)
{
// Don't show on live
if (Director::isLive()) {
return;
}
echo static::create_debug_view($request)
->debugVariable($val, static::caller(), $showHeader);
die();
} | [
"public",
"static",
"function",
"endshow",
"(",
"$",
"val",
",",
"$",
"showHeader",
"=",
"true",
",",
"HTTPRequest",
"$",
"request",
"=",
"null",
")",
"{",
"// Don't show on live",
"if",
"(",
"Director",
"::",
"isLive",
"(",
")",
")",
"{",
"return",
";",
"}",
"echo",
"static",
"::",
"create_debug_view",
"(",
"$",
"request",
")",
"->",
"debugVariable",
"(",
"$",
"val",
",",
"static",
"::",
"caller",
"(",
")",
",",
"$",
"showHeader",
")",
";",
"die",
"(",
")",
";",
"}"
]
| Close out the show dumper.
Does not work on live mode
@param mixed $val
@param bool $showHeader
@param HTTPRequest $request | [
"Close",
"out",
"the",
"show",
"dumper",
".",
"Does",
"not",
"work",
"on",
"live",
"mode"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Debug.php#L86-L97 | train |
silverstripe/silverstripe-framework | src/Dev/Debug.php | Debug.message | public static function message($message, $showHeader = true, HTTPRequest $request = null)
{
// Don't show on live
if (Director::isLive()) {
return;
}
echo static::create_debug_view($request)
->renderMessage($message, static::caller(), $showHeader);
} | php | public static function message($message, $showHeader = true, HTTPRequest $request = null)
{
// Don't show on live
if (Director::isLive()) {
return;
}
echo static::create_debug_view($request)
->renderMessage($message, static::caller(), $showHeader);
} | [
"public",
"static",
"function",
"message",
"(",
"$",
"message",
",",
"$",
"showHeader",
"=",
"true",
",",
"HTTPRequest",
"$",
"request",
"=",
"null",
")",
"{",
"// Don't show on live",
"if",
"(",
"Director",
"::",
"isLive",
"(",
")",
")",
"{",
"return",
";",
"}",
"echo",
"static",
"::",
"create_debug_view",
"(",
"$",
"request",
")",
"->",
"renderMessage",
"(",
"$",
"message",
",",
"static",
"::",
"caller",
"(",
")",
",",
"$",
"showHeader",
")",
";",
"}"
]
| Show a debugging message.
Does not work on live mode
@param string $message
@param bool $showHeader
@param HTTPRequest|null $request | [
"Show",
"a",
"debugging",
"message",
".",
"Does",
"not",
"work",
"on",
"live",
"mode"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Debug.php#L133-L142 | train |
silverstripe/silverstripe-framework | src/Dev/Debug.php | Debug.create_debug_view | public static function create_debug_view(HTTPRequest $request = null)
{
$service = static::supportsHTML($request)
? DebugView::class
: CliDebugView::class;
return Injector::inst()->get($service);
} | php | public static function create_debug_view(HTTPRequest $request = null)
{
$service = static::supportsHTML($request)
? DebugView::class
: CliDebugView::class;
return Injector::inst()->get($service);
} | [
"public",
"static",
"function",
"create_debug_view",
"(",
"HTTPRequest",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"service",
"=",
"static",
"::",
"supportsHTML",
"(",
"$",
"request",
")",
"?",
"DebugView",
"::",
"class",
":",
"CliDebugView",
"::",
"class",
";",
"return",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"service",
")",
";",
"}"
]
| Create an instance of an appropriate DebugView object.
@param HTTPRequest $request Optional request to target this view for
@return DebugView | [
"Create",
"an",
"instance",
"of",
"an",
"appropriate",
"DebugView",
"object",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Debug.php#L150-L156 | train |
silverstripe/silverstripe-framework | src/Dev/Debug.php | Debug.supportsHTML | protected static function supportsHTML(HTTPRequest $request = null)
{
// No HTML output in CLI
if (Director::is_cli()) {
return false;
}
// Get current request if registered
if (!$request && Injector::inst()->has(HTTPRequest::class)) {
$request = Injector::inst()->get(HTTPRequest::class);
}
if (!$request) {
return false;
}
// Request must include text/html
$accepted = $request->getAcceptMimetypes(false);
// Explicit opt in
if (in_array('text/html', $accepted)) {
return true;
};
// Implicit opt-out
if (in_array('application/json', $accepted)) {
return false;
}
// Fallback to wildcard comparison
if (in_array('*/*', $accepted)) {
return true;
}
return false;
} | php | protected static function supportsHTML(HTTPRequest $request = null)
{
// No HTML output in CLI
if (Director::is_cli()) {
return false;
}
// Get current request if registered
if (!$request && Injector::inst()->has(HTTPRequest::class)) {
$request = Injector::inst()->get(HTTPRequest::class);
}
if (!$request) {
return false;
}
// Request must include text/html
$accepted = $request->getAcceptMimetypes(false);
// Explicit opt in
if (in_array('text/html', $accepted)) {
return true;
};
// Implicit opt-out
if (in_array('application/json', $accepted)) {
return false;
}
// Fallback to wildcard comparison
if (in_array('*/*', $accepted)) {
return true;
}
return false;
} | [
"protected",
"static",
"function",
"supportsHTML",
"(",
"HTTPRequest",
"$",
"request",
"=",
"null",
")",
"{",
"// No HTML output in CLI",
"if",
"(",
"Director",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Get current request if registered",
"if",
"(",
"!",
"$",
"request",
"&&",
"Injector",
"::",
"inst",
"(",
")",
"->",
"has",
"(",
"HTTPRequest",
"::",
"class",
")",
")",
"{",
"$",
"request",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"HTTPRequest",
"::",
"class",
")",
";",
"}",
"if",
"(",
"!",
"$",
"request",
")",
"{",
"return",
"false",
";",
"}",
"// Request must include text/html",
"$",
"accepted",
"=",
"$",
"request",
"->",
"getAcceptMimetypes",
"(",
"false",
")",
";",
"// Explicit opt in",
"if",
"(",
"in_array",
"(",
"'text/html'",
",",
"$",
"accepted",
")",
")",
"{",
"return",
"true",
";",
"}",
";",
"// Implicit opt-out",
"if",
"(",
"in_array",
"(",
"'application/json'",
",",
"$",
"accepted",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Fallback to wildcard comparison",
"if",
"(",
"in_array",
"(",
"'*/*'",
",",
"$",
"accepted",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Determine if the given request supports html output
@param HTTPRequest $request
@return bool | [
"Determine",
"if",
"the",
"given",
"request",
"supports",
"html",
"output"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Debug.php#L164-L196 | train |
silverstripe/silverstripe-framework | src/Dev/Debug.php | Debug.require_developer_login | public static function require_developer_login()
{
// Don't require login for dev mode
if (Director::isDev()) {
return;
}
if (isset($_SESSION['loggedInAs'])) {
// We have to do some raw SQL here, because this method is called in Object::defineMethods().
// This means we have to be careful about what objects we create, as we don't want Object::defineMethods()
// being called again.
// This basically calls Permission::checkMember($_SESSION['loggedInAs'], 'ADMIN');
// @TODO - Rewrite safely using DataList::filter
$memberID = $_SESSION['loggedInAs'];
$permission = DB::prepared_query(
'
SELECT "ID" FROM "Permission"
INNER JOIN "Group_Members" ON "Permission"."GroupID" = "Group_Members"."GroupID"
WHERE "Permission"."Code" = ?
AND "Permission"."Type" = ?
AND "Group_Members"."MemberID" = ?',
array(
'ADMIN', // Code
Permission::GRANT_PERMISSION, // Type
$memberID // MemberID
)
)->value();
if ($permission) {
return;
}
}
// This basically does the same as
// Security::permissionFailure(null, "You need to login with developer access to make use of debugging tools.")
// We have to do this because of how early this method is called in execution.
$_SESSION['SilverStripe\\Security\\Security']['Message']['message']
= "You need to login with developer access to make use of debugging tools.";
$_SESSION['SilverStripe\\Security\\Security']['Message']['type'] = 'warning';
$_SESSION['BackURL'] = $_SERVER['REQUEST_URI'];
header($_SERVER['SERVER_PROTOCOL'] . " 302 Found");
header("Location: " . Director::baseURL() . Security::login_url());
die();
} | php | public static function require_developer_login()
{
// Don't require login for dev mode
if (Director::isDev()) {
return;
}
if (isset($_SESSION['loggedInAs'])) {
// We have to do some raw SQL here, because this method is called in Object::defineMethods().
// This means we have to be careful about what objects we create, as we don't want Object::defineMethods()
// being called again.
// This basically calls Permission::checkMember($_SESSION['loggedInAs'], 'ADMIN');
// @TODO - Rewrite safely using DataList::filter
$memberID = $_SESSION['loggedInAs'];
$permission = DB::prepared_query(
'
SELECT "ID" FROM "Permission"
INNER JOIN "Group_Members" ON "Permission"."GroupID" = "Group_Members"."GroupID"
WHERE "Permission"."Code" = ?
AND "Permission"."Type" = ?
AND "Group_Members"."MemberID" = ?',
array(
'ADMIN', // Code
Permission::GRANT_PERMISSION, // Type
$memberID // MemberID
)
)->value();
if ($permission) {
return;
}
}
// This basically does the same as
// Security::permissionFailure(null, "You need to login with developer access to make use of debugging tools.")
// We have to do this because of how early this method is called in execution.
$_SESSION['SilverStripe\\Security\\Security']['Message']['message']
= "You need to login with developer access to make use of debugging tools.";
$_SESSION['SilverStripe\\Security\\Security']['Message']['type'] = 'warning';
$_SESSION['BackURL'] = $_SERVER['REQUEST_URI'];
header($_SERVER['SERVER_PROTOCOL'] . " 302 Found");
header("Location: " . Director::baseURL() . Security::login_url());
die();
} | [
"public",
"static",
"function",
"require_developer_login",
"(",
")",
"{",
"// Don't require login for dev mode",
"if",
"(",
"Director",
"::",
"isDev",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"_SESSION",
"[",
"'loggedInAs'",
"]",
")",
")",
"{",
"// We have to do some raw SQL here, because this method is called in Object::defineMethods().",
"// This means we have to be careful about what objects we create, as we don't want Object::defineMethods()",
"// being called again.",
"// This basically calls Permission::checkMember($_SESSION['loggedInAs'], 'ADMIN');",
"// @TODO - Rewrite safely using DataList::filter",
"$",
"memberID",
"=",
"$",
"_SESSION",
"[",
"'loggedInAs'",
"]",
";",
"$",
"permission",
"=",
"DB",
"::",
"prepared_query",
"(",
"'\n\t\t\t\tSELECT \"ID\" FROM \"Permission\"\n\t\t\t\tINNER JOIN \"Group_Members\" ON \"Permission\".\"GroupID\" = \"Group_Members\".\"GroupID\"\n\t\t\t\tWHERE \"Permission\".\"Code\" = ?\n\t\t\t\tAND \"Permission\".\"Type\" = ?\n\t\t\t\tAND \"Group_Members\".\"MemberID\" = ?'",
",",
"array",
"(",
"'ADMIN'",
",",
"// Code",
"Permission",
"::",
"GRANT_PERMISSION",
",",
"// Type",
"$",
"memberID",
"// MemberID",
")",
")",
"->",
"value",
"(",
")",
";",
"if",
"(",
"$",
"permission",
")",
"{",
"return",
";",
"}",
"}",
"// This basically does the same as",
"// Security::permissionFailure(null, \"You need to login with developer access to make use of debugging tools.\")",
"// We have to do this because of how early this method is called in execution.",
"$",
"_SESSION",
"[",
"'SilverStripe\\\\Security\\\\Security'",
"]",
"[",
"'Message'",
"]",
"[",
"'message'",
"]",
"=",
"\"You need to login with developer access to make use of debugging tools.\"",
";",
"$",
"_SESSION",
"[",
"'SilverStripe\\\\Security\\\\Security'",
"]",
"[",
"'Message'",
"]",
"[",
"'type'",
"]",
"=",
"'warning'",
";",
"$",
"_SESSION",
"[",
"'BackURL'",
"]",
"=",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
";",
"header",
"(",
"$",
"_SERVER",
"[",
"'SERVER_PROTOCOL'",
"]",
".",
"\" 302 Found\"",
")",
";",
"header",
"(",
"\"Location: \"",
".",
"Director",
"::",
"baseURL",
"(",
")",
".",
"Security",
"::",
"login_url",
"(",
")",
")",
";",
"die",
"(",
")",
";",
"}"
]
| Check if the user has permissions to run URL debug tools,
else redirect them to log in. | [
"Check",
"if",
"the",
"user",
"has",
"permissions",
"to",
"run",
"URL",
"debug",
"tools",
"else",
"redirect",
"them",
"to",
"log",
"in",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Debug.php#L202-L246 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.javascript | public function javascript($file, $options = array())
{
$file = ModuleResourceLoader::singleton()->resolvePath($file);
// Get type
$type = null;
if (isset($this->javascript[$file]['type'])) {
$type = $this->javascript[$file]['type'];
}
if (isset($options['type'])) {
$type = $options['type'];
}
// make sure that async/defer is set if it is set once even if file is included multiple times
$async = (
isset($options['async']) && isset($options['async']) == true
|| (
isset($this->javascript[$file])
&& isset($this->javascript[$file]['async'])
&& $this->javascript[$file]['async'] == true
)
);
$defer = (
isset($options['defer']) && isset($options['defer']) == true
|| (
isset($this->javascript[$file])
&& isset($this->javascript[$file]['defer'])
&& $this->javascript[$file]['defer'] == true
)
);
$this->javascript[$file] = array(
'async' => $async,
'defer' => $defer,
'type' => $type,
);
// Record scripts included in this file
if (isset($options['provides'])) {
$this->providedJavascript[$file] = array_values($options['provides']);
}
} | php | public function javascript($file, $options = array())
{
$file = ModuleResourceLoader::singleton()->resolvePath($file);
// Get type
$type = null;
if (isset($this->javascript[$file]['type'])) {
$type = $this->javascript[$file]['type'];
}
if (isset($options['type'])) {
$type = $options['type'];
}
// make sure that async/defer is set if it is set once even if file is included multiple times
$async = (
isset($options['async']) && isset($options['async']) == true
|| (
isset($this->javascript[$file])
&& isset($this->javascript[$file]['async'])
&& $this->javascript[$file]['async'] == true
)
);
$defer = (
isset($options['defer']) && isset($options['defer']) == true
|| (
isset($this->javascript[$file])
&& isset($this->javascript[$file]['defer'])
&& $this->javascript[$file]['defer'] == true
)
);
$this->javascript[$file] = array(
'async' => $async,
'defer' => $defer,
'type' => $type,
);
// Record scripts included in this file
if (isset($options['provides'])) {
$this->providedJavascript[$file] = array_values($options['provides']);
}
} | [
"public",
"function",
"javascript",
"(",
"$",
"file",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"file",
"=",
"ModuleResourceLoader",
"::",
"singleton",
"(",
")",
"->",
"resolvePath",
"(",
"$",
"file",
")",
";",
"// Get type",
"$",
"type",
"=",
"null",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
"[",
"'type'",
"]",
")",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
"[",
"'type'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'type'",
"]",
")",
")",
"{",
"$",
"type",
"=",
"$",
"options",
"[",
"'type'",
"]",
";",
"}",
"// make sure that async/defer is set if it is set once even if file is included multiple times",
"$",
"async",
"=",
"(",
"isset",
"(",
"$",
"options",
"[",
"'async'",
"]",
")",
"&&",
"isset",
"(",
"$",
"options",
"[",
"'async'",
"]",
")",
"==",
"true",
"||",
"(",
"isset",
"(",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
"[",
"'async'",
"]",
")",
"&&",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
"[",
"'async'",
"]",
"==",
"true",
")",
")",
";",
"$",
"defer",
"=",
"(",
"isset",
"(",
"$",
"options",
"[",
"'defer'",
"]",
")",
"&&",
"isset",
"(",
"$",
"options",
"[",
"'defer'",
"]",
")",
"==",
"true",
"||",
"(",
"isset",
"(",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
"[",
"'defer'",
"]",
")",
"&&",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
"[",
"'defer'",
"]",
"==",
"true",
")",
")",
";",
"$",
"this",
"->",
"javascript",
"[",
"$",
"file",
"]",
"=",
"array",
"(",
"'async'",
"=>",
"$",
"async",
",",
"'defer'",
"=>",
"$",
"defer",
",",
"'type'",
"=>",
"$",
"type",
",",
")",
";",
"// Record scripts included in this file",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'provides'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"providedJavascript",
"[",
"$",
"file",
"]",
"=",
"array_values",
"(",
"$",
"options",
"[",
"'provides'",
"]",
")",
";",
"}",
"}"
]
| Register the given JavaScript file as required.
@param string $file Either relative to docroot or in the form "vendor/package:resource"
@param array $options List of options. Available options include:
- 'provides' : List of scripts files included in this file
- 'async' : Boolean value to set async attribute to script tag
- 'defer' : Boolean value to set defer attribute to script tag
- 'type' : Override script type= value. | [
"Register",
"the",
"given",
"JavaScript",
"file",
"as",
"required",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L404-L444 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.customScript | public function customScript($script, $uniquenessID = null)
{
if ($uniquenessID) {
$this->customScript[$uniquenessID] = $script;
} else {
$this->customScript[] = $script;
}
} | php | public function customScript($script, $uniquenessID = null)
{
if ($uniquenessID) {
$this->customScript[$uniquenessID] = $script;
} else {
$this->customScript[] = $script;
}
} | [
"public",
"function",
"customScript",
"(",
"$",
"script",
",",
"$",
"uniquenessID",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"uniquenessID",
")",
"{",
"$",
"this",
"->",
"customScript",
"[",
"$",
"uniquenessID",
"]",
"=",
"$",
"script",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"customScript",
"[",
"]",
"=",
"$",
"script",
";",
"}",
"}"
]
| Register the given JavaScript code into the list of requirements
@param string $script The script content as a string (without enclosing <script> tag)
@param string $uniquenessID A unique ID that ensures a piece of code is only added once | [
"Register",
"the",
"given",
"JavaScript",
"code",
"into",
"the",
"list",
"of",
"requirements"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L528-L535 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.customCSS | public function customCSS($script, $uniquenessID = null)
{
if ($uniquenessID) {
$this->customCSS[$uniquenessID] = $script;
} else {
$this->customCSS[] = $script;
}
} | php | public function customCSS($script, $uniquenessID = null)
{
if ($uniquenessID) {
$this->customCSS[$uniquenessID] = $script;
} else {
$this->customCSS[] = $script;
}
} | [
"public",
"function",
"customCSS",
"(",
"$",
"script",
",",
"$",
"uniquenessID",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"uniquenessID",
")",
"{",
"$",
"this",
"->",
"customCSS",
"[",
"$",
"uniquenessID",
"]",
"=",
"$",
"script",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"customCSS",
"[",
"]",
"=",
"$",
"script",
";",
"}",
"}"
]
| Register the given CSS styles into the list of requirements
@param string $script CSS selectors as a string (without enclosing <style> tag)
@param string $uniquenessID A unique ID that ensures a piece of code is only added once | [
"Register",
"the",
"given",
"CSS",
"styles",
"into",
"the",
"list",
"of",
"requirements"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L553-L560 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.css | public function css($file, $media = null)
{
$file = ModuleResourceLoader::singleton()->resolvePath($file);
$this->css[$file] = [
"media" => $media
];
} | php | public function css($file, $media = null)
{
$file = ModuleResourceLoader::singleton()->resolvePath($file);
$this->css[$file] = [
"media" => $media
];
} | [
"public",
"function",
"css",
"(",
"$",
"file",
",",
"$",
"media",
"=",
"null",
")",
"{",
"$",
"file",
"=",
"ModuleResourceLoader",
"::",
"singleton",
"(",
")",
"->",
"resolvePath",
"(",
"$",
"file",
")",
";",
"$",
"this",
"->",
"css",
"[",
"$",
"file",
"]",
"=",
"[",
"\"media\"",
"=>",
"$",
"media",
"]",
";",
"}"
]
| Register the given stylesheet into the list of requirements.
@param string $file The CSS file to load, relative to site root
@param string $media Comma-separated list of media types to use in the link tag
(e.g. 'screen,projector') | [
"Register",
"the",
"given",
"stylesheet",
"into",
"the",
"list",
"of",
"requirements",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L635-L642 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.clear | public function clear($fileOrID = null)
{
$types = [
'javascript',
'css',
'customScript',
'customCSS',
'customHeadTags',
'combinedFiles',
];
foreach ($types as $type) {
if ($fileOrID) {
if (isset($this->{$type}[$fileOrID])) {
$this->disabled[$type][$fileOrID] = $this->{$type}[$fileOrID];
unset($this->{$type}[$fileOrID]);
}
} else {
$this->disabled[$type] = $this->{$type};
$this->{$type} = [];
}
}
} | php | public function clear($fileOrID = null)
{
$types = [
'javascript',
'css',
'customScript',
'customCSS',
'customHeadTags',
'combinedFiles',
];
foreach ($types as $type) {
if ($fileOrID) {
if (isset($this->{$type}[$fileOrID])) {
$this->disabled[$type][$fileOrID] = $this->{$type}[$fileOrID];
unset($this->{$type}[$fileOrID]);
}
} else {
$this->disabled[$type] = $this->{$type};
$this->{$type} = [];
}
}
} | [
"public",
"function",
"clear",
"(",
"$",
"fileOrID",
"=",
"null",
")",
"{",
"$",
"types",
"=",
"[",
"'javascript'",
",",
"'css'",
",",
"'customScript'",
",",
"'customCSS'",
",",
"'customHeadTags'",
",",
"'combinedFiles'",
",",
"]",
";",
"foreach",
"(",
"$",
"types",
"as",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"fileOrID",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"{",
"$",
"type",
"}",
"[",
"$",
"fileOrID",
"]",
")",
")",
"{",
"$",
"this",
"->",
"disabled",
"[",
"$",
"type",
"]",
"[",
"$",
"fileOrID",
"]",
"=",
"$",
"this",
"->",
"{",
"$",
"type",
"}",
"[",
"$",
"fileOrID",
"]",
";",
"unset",
"(",
"$",
"this",
"->",
"{",
"$",
"type",
"}",
"[",
"$",
"fileOrID",
"]",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"disabled",
"[",
"$",
"type",
"]",
"=",
"$",
"this",
"->",
"{",
"$",
"type",
"}",
";",
"$",
"this",
"->",
"{",
"$",
"type",
"}",
"=",
"[",
"]",
";",
"}",
"}",
"}"
]
| Clear either a single or all requirements
Caution: Clearing single rules added via customCSS and customScript only works if you
originally specified a $uniquenessID.
@param string|int $fileOrID | [
"Clear",
"either",
"a",
"single",
"or",
"all",
"requirements"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L692-L713 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.block | public function block($fileOrID)
{
if (is_string($fileOrID)) {
$fileOrID = ModuleResourceLoader::singleton()->resolvePath($fileOrID);
}
$this->blocked[$fileOrID] = $fileOrID;
} | php | public function block($fileOrID)
{
if (is_string($fileOrID)) {
$fileOrID = ModuleResourceLoader::singleton()->resolvePath($fileOrID);
}
$this->blocked[$fileOrID] = $fileOrID;
} | [
"public",
"function",
"block",
"(",
"$",
"fileOrID",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"fileOrID",
")",
")",
"{",
"$",
"fileOrID",
"=",
"ModuleResourceLoader",
"::",
"singleton",
"(",
")",
"->",
"resolvePath",
"(",
"$",
"fileOrID",
")",
";",
"}",
"$",
"this",
"->",
"blocked",
"[",
"$",
"fileOrID",
"]",
"=",
"$",
"fileOrID",
";",
"}"
]
| Block inclusion of a specific file
The difference between this and {@link clear} is that the calling order does not matter;
{@link clear} must be called after the initial registration, whereas {@link block} can be
used in advance. This is useful, for example, to block scripts included by a superclass
without having to override entire functions and duplicate a lot of code.
Note that blocking should be used sparingly because it's hard to trace where an file is
being blocked from.
@param string|int $fileOrID Relative path from webroot, module resource reference or
requirement API ID | [
"Block",
"inclusion",
"of",
"a",
"specific",
"file"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L747-L753 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.includeInResponse | public function includeInResponse(HTTPResponse $response)
{
$this->processCombinedFiles();
$jsRequirements = array();
$cssRequirements = array();
foreach ($this->getJavascript() as $file => $attributes) {
$path = $this->pathForFile($file);
if ($path) {
$jsRequirements[] = str_replace(',', '%2C', $path);
}
}
if (count($jsRequirements)) {
$response->addHeader('X-Include-JS', implode(',', $jsRequirements));
}
foreach ($this->getCSS() as $file => $params) {
$path = $this->pathForFile($file);
if ($path) {
$path = str_replace(',', '%2C', $path);
$cssRequirements[] = isset($params['media']) ? "$path:##:$params[media]" : $path;
}
}
if (count($cssRequirements)) {
$response->addHeader('X-Include-CSS', implode(',', $cssRequirements));
}
} | php | public function includeInResponse(HTTPResponse $response)
{
$this->processCombinedFiles();
$jsRequirements = array();
$cssRequirements = array();
foreach ($this->getJavascript() as $file => $attributes) {
$path = $this->pathForFile($file);
if ($path) {
$jsRequirements[] = str_replace(',', '%2C', $path);
}
}
if (count($jsRequirements)) {
$response->addHeader('X-Include-JS', implode(',', $jsRequirements));
}
foreach ($this->getCSS() as $file => $params) {
$path = $this->pathForFile($file);
if ($path) {
$path = str_replace(',', '%2C', $path);
$cssRequirements[] = isset($params['media']) ? "$path:##:$params[media]" : $path;
}
}
if (count($cssRequirements)) {
$response->addHeader('X-Include-CSS', implode(',', $cssRequirements));
}
} | [
"public",
"function",
"includeInResponse",
"(",
"HTTPResponse",
"$",
"response",
")",
"{",
"$",
"this",
"->",
"processCombinedFiles",
"(",
")",
";",
"$",
"jsRequirements",
"=",
"array",
"(",
")",
";",
"$",
"cssRequirements",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getJavascript",
"(",
")",
"as",
"$",
"file",
"=>",
"$",
"attributes",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"pathForFile",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"path",
")",
"{",
"$",
"jsRequirements",
"[",
"]",
"=",
"str_replace",
"(",
"','",
",",
"'%2C'",
",",
"$",
"path",
")",
";",
"}",
"}",
"if",
"(",
"count",
"(",
"$",
"jsRequirements",
")",
")",
"{",
"$",
"response",
"->",
"addHeader",
"(",
"'X-Include-JS'",
",",
"implode",
"(",
"','",
",",
"$",
"jsRequirements",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"getCSS",
"(",
")",
"as",
"$",
"file",
"=>",
"$",
"params",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"pathForFile",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"str_replace",
"(",
"','",
",",
"'%2C'",
",",
"$",
"path",
")",
";",
"$",
"cssRequirements",
"[",
"]",
"=",
"isset",
"(",
"$",
"params",
"[",
"'media'",
"]",
")",
"?",
"\"$path:##:$params[media]\"",
":",
"$",
"path",
";",
"}",
"}",
"if",
"(",
"count",
"(",
"$",
"cssRequirements",
")",
")",
"{",
"$",
"response",
"->",
"addHeader",
"(",
"'X-Include-CSS'",
",",
"implode",
"(",
"','",
",",
"$",
"cssRequirements",
")",
")",
";",
"}",
"}"
]
| Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the given
HTTP Response
@param HTTPResponse $response | [
"Attach",
"requirements",
"inclusion",
"to",
"X",
"-",
"Include",
"-",
"JS",
"and",
"X",
"-",
"Include",
"-",
"CSS",
"headers",
"on",
"the",
"given",
"HTTP",
"Response"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L960-L988 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.pathForFile | protected function pathForFile($fileOrUrl)
{
// Since combined urls could be root relative, treat them as urls here.
if (preg_match('{^(//)|(http[s]?:)}', $fileOrUrl) || Director::is_root_relative_url($fileOrUrl)) {
return $fileOrUrl;
} else {
return Injector::inst()->get(ResourceURLGenerator::class)->urlForResource($fileOrUrl);
}
} | php | protected function pathForFile($fileOrUrl)
{
// Since combined urls could be root relative, treat them as urls here.
if (preg_match('{^(//)|(http[s]?:)}', $fileOrUrl) || Director::is_root_relative_url($fileOrUrl)) {
return $fileOrUrl;
} else {
return Injector::inst()->get(ResourceURLGenerator::class)->urlForResource($fileOrUrl);
}
} | [
"protected",
"function",
"pathForFile",
"(",
"$",
"fileOrUrl",
")",
"{",
"// Since combined urls could be root relative, treat them as urls here.",
"if",
"(",
"preg_match",
"(",
"'{^(//)|(http[s]?:)}'",
",",
"$",
"fileOrUrl",
")",
"||",
"Director",
"::",
"is_root_relative_url",
"(",
"$",
"fileOrUrl",
")",
")",
"{",
"return",
"$",
"fileOrUrl",
";",
"}",
"else",
"{",
"return",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"ResourceURLGenerator",
"::",
"class",
")",
"->",
"urlForResource",
"(",
"$",
"fileOrUrl",
")",
";",
"}",
"}"
]
| Finds the path for specified file
@param string $fileOrUrl
@return string|bool | [
"Finds",
"the",
"path",
"for",
"specified",
"file"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1049-L1057 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.parseCombinedFile | protected function parseCombinedFile($file)
{
// Array with path and type keys
if (is_array($file) && isset($file['path']) && isset($file['type'])) {
return array($file['path'], $file['type']);
}
// Extract value from indexed array
if (is_array($file)) {
$path = array_shift($file);
// See if there's a type specifier
if ($file) {
$type = array_shift($file);
return array($path, $type);
}
// Otherwise convent to string
$file = $path;
}
$type = File::get_file_extension($file);
return array($file, $type);
} | php | protected function parseCombinedFile($file)
{
// Array with path and type keys
if (is_array($file) && isset($file['path']) && isset($file['type'])) {
return array($file['path'], $file['type']);
}
// Extract value from indexed array
if (is_array($file)) {
$path = array_shift($file);
// See if there's a type specifier
if ($file) {
$type = array_shift($file);
return array($path, $type);
}
// Otherwise convent to string
$file = $path;
}
$type = File::get_file_extension($file);
return array($file, $type);
} | [
"protected",
"function",
"parseCombinedFile",
"(",
"$",
"file",
")",
"{",
"// Array with path and type keys",
"if",
"(",
"is_array",
"(",
"$",
"file",
")",
"&&",
"isset",
"(",
"$",
"file",
"[",
"'path'",
"]",
")",
"&&",
"isset",
"(",
"$",
"file",
"[",
"'type'",
"]",
")",
")",
"{",
"return",
"array",
"(",
"$",
"file",
"[",
"'path'",
"]",
",",
"$",
"file",
"[",
"'type'",
"]",
")",
";",
"}",
"// Extract value from indexed array",
"if",
"(",
"is_array",
"(",
"$",
"file",
")",
")",
"{",
"$",
"path",
"=",
"array_shift",
"(",
"$",
"file",
")",
";",
"// See if there's a type specifier",
"if",
"(",
"$",
"file",
")",
"{",
"$",
"type",
"=",
"array_shift",
"(",
"$",
"file",
")",
";",
"return",
"array",
"(",
"$",
"path",
",",
"$",
"type",
")",
";",
"}",
"// Otherwise convent to string",
"$",
"file",
"=",
"$",
"path",
";",
"}",
"$",
"type",
"=",
"File",
"::",
"get_file_extension",
"(",
"$",
"file",
")",
";",
"return",
"array",
"(",
"$",
"file",
",",
"$",
"type",
")",
";",
"}"
]
| Return path and type of given combined file
@param string|array $file Either a file path, or an array spec
@return array array with two elements, path and type of file | [
"Return",
"path",
"and",
"type",
"of",
"given",
"combined",
"file"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1177-L1200 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.processCombinedFiles | public function processCombinedFiles()
{
// Check if combining is enabled
if (!$this->getCombinedFilesEnabled()) {
return;
}
// Before scripts are modified, detect files that are provided by preceding ones
$providedScripts = $this->getProvidedScripts();
// Process each combined files
foreach ($this->getAllCombinedFiles() as $combinedFile => $combinedItem) {
$fileList = $combinedItem['files'];
$type = $combinedItem['type'];
$options = $combinedItem['options'];
// Generate this file, unless blocked
$combinedURL = null;
if (!isset($this->blocked[$combinedFile])) {
// Filter files for blocked / provided
$filteredFileList = array_diff(
$fileList,
$this->getBlocked(),
$providedScripts
);
$combinedURL = $this->getCombinedFileURL($combinedFile, $filteredFileList, $type);
}
// Replace all existing files, injecting the combined file at the position of the first item
// in order to preserve inclusion order.
// Note that we iterate across blocked files in order to get the correct order, and validate
// that the file is included in the correct location (regardless of which files are blocked).
$included = false;
switch ($type) {
case 'css': {
$newCSS = array(); // Assoc array of css file => spec
foreach ($this->getAllCSS() as $css => $spec) {
if (!in_array($css, $fileList)) {
$newCSS[$css] = $spec;
} elseif (!$included && $combinedURL) {
$newCSS[$combinedURL] = array('media' => (isset($options['media']) ? $options['media'] : null));
$included = true;
}
// If already included, or otherwise blocked, then don't add into CSS
}
$this->css = $newCSS;
break;
}
case 'js': {
// Assoc array of file => attributes
$newJS = array();
foreach ($this->getAllJavascript() as $script => $attributes) {
if (!in_array($script, $fileList)) {
$newJS[$script] = $attributes;
} elseif (!$included && $combinedURL) {
$newJS[$combinedURL] = $options;
$included = true;
}
// If already included, or otherwise blocked, then don't add into scripts
}
$this->javascript = $newJS;
break;
}
}
}
} | php | public function processCombinedFiles()
{
// Check if combining is enabled
if (!$this->getCombinedFilesEnabled()) {
return;
}
// Before scripts are modified, detect files that are provided by preceding ones
$providedScripts = $this->getProvidedScripts();
// Process each combined files
foreach ($this->getAllCombinedFiles() as $combinedFile => $combinedItem) {
$fileList = $combinedItem['files'];
$type = $combinedItem['type'];
$options = $combinedItem['options'];
// Generate this file, unless blocked
$combinedURL = null;
if (!isset($this->blocked[$combinedFile])) {
// Filter files for blocked / provided
$filteredFileList = array_diff(
$fileList,
$this->getBlocked(),
$providedScripts
);
$combinedURL = $this->getCombinedFileURL($combinedFile, $filteredFileList, $type);
}
// Replace all existing files, injecting the combined file at the position of the first item
// in order to preserve inclusion order.
// Note that we iterate across blocked files in order to get the correct order, and validate
// that the file is included in the correct location (regardless of which files are blocked).
$included = false;
switch ($type) {
case 'css': {
$newCSS = array(); // Assoc array of css file => spec
foreach ($this->getAllCSS() as $css => $spec) {
if (!in_array($css, $fileList)) {
$newCSS[$css] = $spec;
} elseif (!$included && $combinedURL) {
$newCSS[$combinedURL] = array('media' => (isset($options['media']) ? $options['media'] : null));
$included = true;
}
// If already included, or otherwise blocked, then don't add into CSS
}
$this->css = $newCSS;
break;
}
case 'js': {
// Assoc array of file => attributes
$newJS = array();
foreach ($this->getAllJavascript() as $script => $attributes) {
if (!in_array($script, $fileList)) {
$newJS[$script] = $attributes;
} elseif (!$included && $combinedURL) {
$newJS[$combinedURL] = $options;
$included = true;
}
// If already included, or otherwise blocked, then don't add into scripts
}
$this->javascript = $newJS;
break;
}
}
}
} | [
"public",
"function",
"processCombinedFiles",
"(",
")",
"{",
"// Check if combining is enabled",
"if",
"(",
"!",
"$",
"this",
"->",
"getCombinedFilesEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Before scripts are modified, detect files that are provided by preceding ones",
"$",
"providedScripts",
"=",
"$",
"this",
"->",
"getProvidedScripts",
"(",
")",
";",
"// Process each combined files",
"foreach",
"(",
"$",
"this",
"->",
"getAllCombinedFiles",
"(",
")",
"as",
"$",
"combinedFile",
"=>",
"$",
"combinedItem",
")",
"{",
"$",
"fileList",
"=",
"$",
"combinedItem",
"[",
"'files'",
"]",
";",
"$",
"type",
"=",
"$",
"combinedItem",
"[",
"'type'",
"]",
";",
"$",
"options",
"=",
"$",
"combinedItem",
"[",
"'options'",
"]",
";",
"// Generate this file, unless blocked",
"$",
"combinedURL",
"=",
"null",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"blocked",
"[",
"$",
"combinedFile",
"]",
")",
")",
"{",
"// Filter files for blocked / provided",
"$",
"filteredFileList",
"=",
"array_diff",
"(",
"$",
"fileList",
",",
"$",
"this",
"->",
"getBlocked",
"(",
")",
",",
"$",
"providedScripts",
")",
";",
"$",
"combinedURL",
"=",
"$",
"this",
"->",
"getCombinedFileURL",
"(",
"$",
"combinedFile",
",",
"$",
"filteredFileList",
",",
"$",
"type",
")",
";",
"}",
"// Replace all existing files, injecting the combined file at the position of the first item",
"// in order to preserve inclusion order.",
"// Note that we iterate across blocked files in order to get the correct order, and validate",
"// that the file is included in the correct location (regardless of which files are blocked).",
"$",
"included",
"=",
"false",
";",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'css'",
":",
"{",
"$",
"newCSS",
"=",
"array",
"(",
")",
";",
"// Assoc array of css file => spec",
"foreach",
"(",
"$",
"this",
"->",
"getAllCSS",
"(",
")",
"as",
"$",
"css",
"=>",
"$",
"spec",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"css",
",",
"$",
"fileList",
")",
")",
"{",
"$",
"newCSS",
"[",
"$",
"css",
"]",
"=",
"$",
"spec",
";",
"}",
"elseif",
"(",
"!",
"$",
"included",
"&&",
"$",
"combinedURL",
")",
"{",
"$",
"newCSS",
"[",
"$",
"combinedURL",
"]",
"=",
"array",
"(",
"'media'",
"=>",
"(",
"isset",
"(",
"$",
"options",
"[",
"'media'",
"]",
")",
"?",
"$",
"options",
"[",
"'media'",
"]",
":",
"null",
")",
")",
";",
"$",
"included",
"=",
"true",
";",
"}",
"// If already included, or otherwise blocked, then don't add into CSS",
"}",
"$",
"this",
"->",
"css",
"=",
"$",
"newCSS",
";",
"break",
";",
"}",
"case",
"'js'",
":",
"{",
"// Assoc array of file => attributes",
"$",
"newJS",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAllJavascript",
"(",
")",
"as",
"$",
"script",
"=>",
"$",
"attributes",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"script",
",",
"$",
"fileList",
")",
")",
"{",
"$",
"newJS",
"[",
"$",
"script",
"]",
"=",
"$",
"attributes",
";",
"}",
"elseif",
"(",
"!",
"$",
"included",
"&&",
"$",
"combinedURL",
")",
"{",
"$",
"newJS",
"[",
"$",
"combinedURL",
"]",
"=",
"$",
"options",
";",
"$",
"included",
"=",
"true",
";",
"}",
"// If already included, or otherwise blocked, then don't add into scripts",
"}",
"$",
"this",
"->",
"javascript",
"=",
"$",
"newJS",
";",
"break",
";",
"}",
"}",
"}",
"}"
]
| Do the heavy lifting involved in combining the combined files. | [
"Do",
"the",
"heavy",
"lifting",
"involved",
"in",
"combining",
"the",
"combined",
"files",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1246-L1311 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.hashedCombinedFilename | protected function hashedCombinedFilename($combinedFile, $fileList)
{
$name = pathinfo($combinedFile, PATHINFO_FILENAME);
$hash = $this->hashOfFiles($fileList);
$extension = File::get_file_extension($combinedFile);
return $name . '-' . substr($hash, 0, 7) . '.' . $extension;
} | php | protected function hashedCombinedFilename($combinedFile, $fileList)
{
$name = pathinfo($combinedFile, PATHINFO_FILENAME);
$hash = $this->hashOfFiles($fileList);
$extension = File::get_file_extension($combinedFile);
return $name . '-' . substr($hash, 0, 7) . '.' . $extension;
} | [
"protected",
"function",
"hashedCombinedFilename",
"(",
"$",
"combinedFile",
",",
"$",
"fileList",
")",
"{",
"$",
"name",
"=",
"pathinfo",
"(",
"$",
"combinedFile",
",",
"PATHINFO_FILENAME",
")",
";",
"$",
"hash",
"=",
"$",
"this",
"->",
"hashOfFiles",
"(",
"$",
"fileList",
")",
";",
"$",
"extension",
"=",
"File",
"::",
"get_file_extension",
"(",
"$",
"combinedFile",
")",
";",
"return",
"$",
"name",
".",
"'-'",
".",
"substr",
"(",
"$",
"hash",
",",
"0",
",",
"7",
")",
".",
"'.'",
".",
"$",
"extension",
";",
"}"
]
| Given a filename and list of files, generate a new filename unique to these files
@param string $combinedFile
@param array $fileList
@return string | [
"Given",
"a",
"filename",
"and",
"list",
"of",
"files",
"generate",
"a",
"new",
"filename",
"unique",
"to",
"these",
"files"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1400-L1406 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.getCombinedFilesEnabled | public function getCombinedFilesEnabled()
{
if (isset($this->combinedFilesEnabled)) {
return $this->combinedFilesEnabled;
}
// Non-dev sites are always combined
if (!Director::isDev()) {
return true;
}
// Fallback to default
return Config::inst()->get(__CLASS__, 'combine_in_dev');
} | php | public function getCombinedFilesEnabled()
{
if (isset($this->combinedFilesEnabled)) {
return $this->combinedFilesEnabled;
}
// Non-dev sites are always combined
if (!Director::isDev()) {
return true;
}
// Fallback to default
return Config::inst()->get(__CLASS__, 'combine_in_dev');
} | [
"public",
"function",
"getCombinedFilesEnabled",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"combinedFilesEnabled",
")",
")",
"{",
"return",
"$",
"this",
"->",
"combinedFilesEnabled",
";",
"}",
"// Non-dev sites are always combined",
"if",
"(",
"!",
"Director",
"::",
"isDev",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"// Fallback to default",
"return",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"__CLASS__",
",",
"'combine_in_dev'",
")",
";",
"}"
]
| Check if combined files are enabled
@return bool | [
"Check",
"if",
"combined",
"files",
"are",
"enabled"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1413-L1426 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.hashOfFiles | protected function hashOfFiles($fileList)
{
// Get hash based on hash of each file
$hash = '';
foreach ($fileList as $file) {
$absolutePath = Director::getAbsFile($file);
if (file_exists($absolutePath)) {
$hash .= sha1_file($absolutePath);
} else {
throw new InvalidArgumentException("Combined file {$file} does not exist");
}
}
return sha1($hash);
} | php | protected function hashOfFiles($fileList)
{
// Get hash based on hash of each file
$hash = '';
foreach ($fileList as $file) {
$absolutePath = Director::getAbsFile($file);
if (file_exists($absolutePath)) {
$hash .= sha1_file($absolutePath);
} else {
throw new InvalidArgumentException("Combined file {$file} does not exist");
}
}
return sha1($hash);
} | [
"protected",
"function",
"hashOfFiles",
"(",
"$",
"fileList",
")",
"{",
"// Get hash based on hash of each file",
"$",
"hash",
"=",
"''",
";",
"foreach",
"(",
"$",
"fileList",
"as",
"$",
"file",
")",
"{",
"$",
"absolutePath",
"=",
"Director",
"::",
"getAbsFile",
"(",
"$",
"file",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"absolutePath",
")",
")",
"{",
"$",
"hash",
".=",
"sha1_file",
"(",
"$",
"absolutePath",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Combined file {$file} does not exist\"",
")",
";",
"}",
"}",
"return",
"sha1",
"(",
"$",
"hash",
")",
";",
"}"
]
| For a given filelist, determine some discriminating value to determine if
any of these files have changed.
@param array $fileList List of files
@return string SHA1 bashed file hash | [
"For",
"a",
"given",
"filelist",
"determine",
"some",
"discriminating",
"value",
"to",
"determine",
"if",
"any",
"of",
"these",
"files",
"have",
"changed",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1435-L1448 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.themedCSS | public function themedCSS($name, $media = null)
{
$path = ThemeResourceLoader::inst()->findThemedCSS($name, SSViewer::get_themes());
if ($path) {
$this->css($path, $media);
} else {
throw new InvalidArgumentException(
"The css file doesn't exist. Please check if the file $name.css exists in any context or search for "
. "themedCSS references calling this file in your templates."
);
}
} | php | public function themedCSS($name, $media = null)
{
$path = ThemeResourceLoader::inst()->findThemedCSS($name, SSViewer::get_themes());
if ($path) {
$this->css($path, $media);
} else {
throw new InvalidArgumentException(
"The css file doesn't exist. Please check if the file $name.css exists in any context or search for "
. "themedCSS references calling this file in your templates."
);
}
} | [
"public",
"function",
"themedCSS",
"(",
"$",
"name",
",",
"$",
"media",
"=",
"null",
")",
"{",
"$",
"path",
"=",
"ThemeResourceLoader",
"::",
"inst",
"(",
")",
"->",
"findThemedCSS",
"(",
"$",
"name",
",",
"SSViewer",
"::",
"get_themes",
"(",
")",
")",
";",
"if",
"(",
"$",
"path",
")",
"{",
"$",
"this",
"->",
"css",
"(",
"$",
"path",
",",
"$",
"media",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"The css file doesn't exist. Please check if the file $name.css exists in any context or search for \"",
".",
"\"themedCSS references calling this file in your templates.\"",
")",
";",
"}",
"}"
]
| Registers the given themeable stylesheet as required.
A CSS file in the current theme path name 'themename/css/$name.css' is first searched for,
and it that doesn't exist and the module parameter is set then a CSS file with that name in
the module is used.
@param string $name The name of the file - eg '/css/File.css' would have the name 'File'
@param string $media Comma-separated list of media types to use in the link tag
(e.g. 'screen,projector') | [
"Registers",
"the",
"given",
"themeable",
"stylesheet",
"as",
"required",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1461-L1472 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.themedJavascript | public function themedJavascript($name, $type = null)
{
$path = ThemeResourceLoader::inst()->findThemedJavascript($name, SSViewer::get_themes());
if ($path) {
$opts = [];
if ($type) {
$opts['type'] = $type;
}
$this->javascript($path, $opts);
} else {
throw new InvalidArgumentException(
"The javascript file doesn't exist. Please check if the file $name.js exists in any "
. "context or search for themedJavascript references calling this file in your templates."
);
}
} | php | public function themedJavascript($name, $type = null)
{
$path = ThemeResourceLoader::inst()->findThemedJavascript($name, SSViewer::get_themes());
if ($path) {
$opts = [];
if ($type) {
$opts['type'] = $type;
}
$this->javascript($path, $opts);
} else {
throw new InvalidArgumentException(
"The javascript file doesn't exist. Please check if the file $name.js exists in any "
. "context or search for themedJavascript references calling this file in your templates."
);
}
} | [
"public",
"function",
"themedJavascript",
"(",
"$",
"name",
",",
"$",
"type",
"=",
"null",
")",
"{",
"$",
"path",
"=",
"ThemeResourceLoader",
"::",
"inst",
"(",
")",
"->",
"findThemedJavascript",
"(",
"$",
"name",
",",
"SSViewer",
"::",
"get_themes",
"(",
")",
")",
";",
"if",
"(",
"$",
"path",
")",
"{",
"$",
"opts",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"type",
")",
"{",
"$",
"opts",
"[",
"'type'",
"]",
"=",
"$",
"type",
";",
"}",
"$",
"this",
"->",
"javascript",
"(",
"$",
"path",
",",
"$",
"opts",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"The javascript file doesn't exist. Please check if the file $name.js exists in any \"",
".",
"\"context or search for themedJavascript references calling this file in your templates.\"",
")",
";",
"}",
"}"
]
| Registers the given themeable javascript as required.
A javascript file in the current theme path name 'themename/javascript/$name.js' is first searched for,
and it that doesn't exist and the module parameter is set then a javascript file with that name in
the module is used.
@param string $name The name of the file - eg '/js/File.js' would have the name 'File'
@param string $type Comma-separated list of types to use in the script tag
(e.g. 'text/javascript,text/ecmascript') | [
"Registers",
"the",
"given",
"themeable",
"javascript",
"as",
"required",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1485-L1500 | train |
silverstripe/silverstripe-framework | src/View/Requirements_Backend.php | Requirements_Backend.debug | public function debug()
{
Debug::show($this->javascript);
Debug::show($this->css);
Debug::show($this->customCSS);
Debug::show($this->customScript);
Debug::show($this->customHeadTags);
Debug::show($this->combinedFiles);
} | php | public function debug()
{
Debug::show($this->javascript);
Debug::show($this->css);
Debug::show($this->customCSS);
Debug::show($this->customScript);
Debug::show($this->customHeadTags);
Debug::show($this->combinedFiles);
} | [
"public",
"function",
"debug",
"(",
")",
"{",
"Debug",
"::",
"show",
"(",
"$",
"this",
"->",
"javascript",
")",
";",
"Debug",
"::",
"show",
"(",
"$",
"this",
"->",
"css",
")",
";",
"Debug",
"::",
"show",
"(",
"$",
"this",
"->",
"customCSS",
")",
";",
"Debug",
"::",
"show",
"(",
"$",
"this",
"->",
"customScript",
")",
";",
"Debug",
"::",
"show",
"(",
"$",
"this",
"->",
"customHeadTags",
")",
";",
"Debug",
"::",
"show",
"(",
"$",
"this",
"->",
"combinedFiles",
")",
";",
"}"
]
| Output debugging information. | [
"Output",
"debugging",
"information",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Requirements_Backend.php#L1505-L1513 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallConfig.php | InstallConfig.getDatabaseConfig | public function getDatabaseConfig($request, $databaseClasses, $realPassword = true)
{
// Get config from request
if (isset($request['db']['type'])) {
$type = $request['db']['type'];
if (isset($request['db'][$type])) {
$config = $request['db'][$type];
// The posted placeholder must be substituted with the real password
if (isset($config['password']) && $config['password'] === Installer::PASSWORD_PLACEHOLDER) {
$config['password'] = Environment::getEnv('SS_DATABASE_PASSWORD') ?: '';
}
return array_merge([ 'type' => $type ], $config);
}
}
// Guess database config
return [
'type' => $this->getDatabaseClass($databaseClasses),
'server' => Environment::getEnv('SS_DATABASE_SERVER') ?: 'localhost',
'username' => Environment::getEnv('SS_DATABASE_USERNAME') ?: 'root',
'password' => $realPassword
? (Environment::getEnv('SS_DATABASE_PASSWORD') ?: '')
: Installer::PASSWORD_PLACEHOLDER, // Avoid password disclosure
'database' => Environment::getEnv('SS_DATABASE_NAME') ?: 'SS_mysite',
'path' => Environment::getEnv('SS_DATABASE_PATH')
?: Environment::getEnv('SS_SQLITE_DATABASE_PATH') // sqlite compat
?: null,
'key' => Environment::getEnv('SS_DATABASE_KEY')
?: Environment::getEnv('SS_SQLITE_DATABASE_KEY') // sqlite compat
?: null,
];
} | php | public function getDatabaseConfig($request, $databaseClasses, $realPassword = true)
{
// Get config from request
if (isset($request['db']['type'])) {
$type = $request['db']['type'];
if (isset($request['db'][$type])) {
$config = $request['db'][$type];
// The posted placeholder must be substituted with the real password
if (isset($config['password']) && $config['password'] === Installer::PASSWORD_PLACEHOLDER) {
$config['password'] = Environment::getEnv('SS_DATABASE_PASSWORD') ?: '';
}
return array_merge([ 'type' => $type ], $config);
}
}
// Guess database config
return [
'type' => $this->getDatabaseClass($databaseClasses),
'server' => Environment::getEnv('SS_DATABASE_SERVER') ?: 'localhost',
'username' => Environment::getEnv('SS_DATABASE_USERNAME') ?: 'root',
'password' => $realPassword
? (Environment::getEnv('SS_DATABASE_PASSWORD') ?: '')
: Installer::PASSWORD_PLACEHOLDER, // Avoid password disclosure
'database' => Environment::getEnv('SS_DATABASE_NAME') ?: 'SS_mysite',
'path' => Environment::getEnv('SS_DATABASE_PATH')
?: Environment::getEnv('SS_SQLITE_DATABASE_PATH') // sqlite compat
?: null,
'key' => Environment::getEnv('SS_DATABASE_KEY')
?: Environment::getEnv('SS_SQLITE_DATABASE_KEY') // sqlite compat
?: null,
];
} | [
"public",
"function",
"getDatabaseConfig",
"(",
"$",
"request",
",",
"$",
"databaseClasses",
",",
"$",
"realPassword",
"=",
"true",
")",
"{",
"// Get config from request",
"if",
"(",
"isset",
"(",
"$",
"request",
"[",
"'db'",
"]",
"[",
"'type'",
"]",
")",
")",
"{",
"$",
"type",
"=",
"$",
"request",
"[",
"'db'",
"]",
"[",
"'type'",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"request",
"[",
"'db'",
"]",
"[",
"$",
"type",
"]",
")",
")",
"{",
"$",
"config",
"=",
"$",
"request",
"[",
"'db'",
"]",
"[",
"$",
"type",
"]",
";",
"// The posted placeholder must be substituted with the real password",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'password'",
"]",
")",
"&&",
"$",
"config",
"[",
"'password'",
"]",
"===",
"Installer",
"::",
"PASSWORD_PLACEHOLDER",
")",
"{",
"$",
"config",
"[",
"'password'",
"]",
"=",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_PASSWORD'",
")",
"?",
":",
"''",
";",
"}",
"return",
"array_merge",
"(",
"[",
"'type'",
"=>",
"$",
"type",
"]",
",",
"$",
"config",
")",
";",
"}",
"}",
"// Guess database config",
"return",
"[",
"'type'",
"=>",
"$",
"this",
"->",
"getDatabaseClass",
"(",
"$",
"databaseClasses",
")",
",",
"'server'",
"=>",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_SERVER'",
")",
"?",
":",
"'localhost'",
",",
"'username'",
"=>",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_USERNAME'",
")",
"?",
":",
"'root'",
",",
"'password'",
"=>",
"$",
"realPassword",
"?",
"(",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_PASSWORD'",
")",
"?",
":",
"''",
")",
":",
"Installer",
"::",
"PASSWORD_PLACEHOLDER",
",",
"// Avoid password disclosure",
"'database'",
"=>",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_NAME'",
")",
"?",
":",
"'SS_mysite'",
",",
"'path'",
"=>",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_PATH'",
")",
"?",
":",
"Environment",
"::",
"getEnv",
"(",
"'SS_SQLITE_DATABASE_PATH'",
")",
"// sqlite compat",
"?",
":",
"null",
",",
"'key'",
"=>",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_KEY'",
")",
"?",
":",
"Environment",
"::",
"getEnv",
"(",
"'SS_SQLITE_DATABASE_KEY'",
")",
"// sqlite compat",
"?",
":",
"null",
",",
"]",
";",
"}"
]
| Get database config from the current environment
@param array $request Request object
@param array $databaseClasses Supported database config
@param bool $realPassword Set to true to get the real password. If false, any non-posted
password will be redacted as '********'. Note: Posted passwords are considered disclosed and
never redacted.
@return array | [
"Get",
"database",
"config",
"from",
"the",
"current",
"environment"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallConfig.php#L42-L73 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallConfig.php | InstallConfig.getAdminConfig | public function getAdminConfig($request, $realPassword = true)
{
if (isset($request['admin'])) {
$config = $request['admin'];
if (isset($config['password']) && $config['password'] === Installer::PASSWORD_PLACEHOLDER) {
$config['password'] = Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD') ?: '';
}
return $request['admin'];
}
return [
'username' => Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME') ?: 'admin',
'password' => $realPassword
? (Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD') ?: '')
: Installer::PASSWORD_PLACEHOLDER, // Avoid password disclosure
];
} | php | public function getAdminConfig($request, $realPassword = true)
{
if (isset($request['admin'])) {
$config = $request['admin'];
if (isset($config['password']) && $config['password'] === Installer::PASSWORD_PLACEHOLDER) {
$config['password'] = Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD') ?: '';
}
return $request['admin'];
}
return [
'username' => Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME') ?: 'admin',
'password' => $realPassword
? (Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD') ?: '')
: Installer::PASSWORD_PLACEHOLDER, // Avoid password disclosure
];
} | [
"public",
"function",
"getAdminConfig",
"(",
"$",
"request",
",",
"$",
"realPassword",
"=",
"true",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"request",
"[",
"'admin'",
"]",
")",
")",
"{",
"$",
"config",
"=",
"$",
"request",
"[",
"'admin'",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'password'",
"]",
")",
"&&",
"$",
"config",
"[",
"'password'",
"]",
"===",
"Installer",
"::",
"PASSWORD_PLACEHOLDER",
")",
"{",
"$",
"config",
"[",
"'password'",
"]",
"=",
"Environment",
"::",
"getEnv",
"(",
"'SS_DEFAULT_ADMIN_PASSWORD'",
")",
"?",
":",
"''",
";",
"}",
"return",
"$",
"request",
"[",
"'admin'",
"]",
";",
"}",
"return",
"[",
"'username'",
"=>",
"Environment",
"::",
"getEnv",
"(",
"'SS_DEFAULT_ADMIN_USERNAME'",
")",
"?",
":",
"'admin'",
",",
"'password'",
"=>",
"$",
"realPassword",
"?",
"(",
"Environment",
"::",
"getEnv",
"(",
"'SS_DEFAULT_ADMIN_PASSWORD'",
")",
"?",
":",
"''",
")",
":",
"Installer",
"::",
"PASSWORD_PLACEHOLDER",
",",
"// Avoid password disclosure",
"]",
";",
"}"
]
| Get admin config from the environment
@param array $request
@param bool $realPassword Set to true to get the real password. If false, any non-posted
password will be redacted as '********'. Note: Posted passwords are considered disclosed and
never redacted.
@return array | [
"Get",
"admin",
"config",
"from",
"the",
"environment"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallConfig.php#L84-L100 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallConfig.php | InstallConfig.alreadyInstalled | public function alreadyInstalled()
{
if (file_exists($this->getEnvPath())) {
return true;
}
if (!file_exists($this->getConfigPath())) {
return false;
}
$configContents = file_get_contents($this->getConfigPath());
if (strstr($configContents, '$databaseConfig')) {
return true;
}
if (strstr($configContents, '$database')) {
return true;
}
return false;
} | php | public function alreadyInstalled()
{
if (file_exists($this->getEnvPath())) {
return true;
}
if (!file_exists($this->getConfigPath())) {
return false;
}
$configContents = file_get_contents($this->getConfigPath());
if (strstr($configContents, '$databaseConfig')) {
return true;
}
if (strstr($configContents, '$database')) {
return true;
}
return false;
} | [
"public",
"function",
"alreadyInstalled",
"(",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"getEnvPath",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"getConfigPath",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"configContents",
"=",
"file_get_contents",
"(",
"$",
"this",
"->",
"getConfigPath",
"(",
")",
")",
";",
"if",
"(",
"strstr",
"(",
"$",
"configContents",
",",
"'$databaseConfig'",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"strstr",
"(",
"$",
"configContents",
",",
"'$database'",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Check if this site has already been installed
@return bool | [
"Check",
"if",
"this",
"site",
"has",
"already",
"been",
"installed"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallConfig.php#L107-L123 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallConfig.php | InstallConfig.getDatabaseClass | protected function getDatabaseClass($databaseClasses)
{
$envDatabase = Environment::getEnv('SS_DATABASE_CLASS');
if ($envDatabase) {
return $envDatabase;
}
// Check supported versions
foreach ($this->preferredDatabases as $candidate) {
if (!empty($databaseClasses[$candidate]['supported'])) {
return $candidate;
}
}
return null;
} | php | protected function getDatabaseClass($databaseClasses)
{
$envDatabase = Environment::getEnv('SS_DATABASE_CLASS');
if ($envDatabase) {
return $envDatabase;
}
// Check supported versions
foreach ($this->preferredDatabases as $candidate) {
if (!empty($databaseClasses[$candidate]['supported'])) {
return $candidate;
}
}
return null;
} | [
"protected",
"function",
"getDatabaseClass",
"(",
"$",
"databaseClasses",
")",
"{",
"$",
"envDatabase",
"=",
"Environment",
"::",
"getEnv",
"(",
"'SS_DATABASE_CLASS'",
")",
";",
"if",
"(",
"$",
"envDatabase",
")",
"{",
"return",
"$",
"envDatabase",
";",
"}",
"// Check supported versions",
"foreach",
"(",
"$",
"this",
"->",
"preferredDatabases",
"as",
"$",
"candidate",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"databaseClasses",
"[",
"$",
"candidate",
"]",
"[",
"'supported'",
"]",
")",
")",
"{",
"return",
"$",
"candidate",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Database configs available for configuration
@param array $databaseClasses
@return string | [
"Database",
"configs",
"available",
"for",
"configuration"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallConfig.php#L147-L161 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallConfig.php | InstallConfig.getFrameworkVersion | public function getFrameworkVersion()
{
$composerLockPath = BASE_PATH . '/composer.lock';
if (!file_exists($composerLockPath)) {
return 'unknown';
}
$lockData = json_decode(file_get_contents($composerLockPath), true);
if (json_last_error() || empty($lockData['packages'])) {
return 'unknown';
}
foreach ($lockData['packages'] as $package) {
if ($package['name'] === 'silverstripe/framework') {
return $package['version'];
}
}
return 'unknown';
} | php | public function getFrameworkVersion()
{
$composerLockPath = BASE_PATH . '/composer.lock';
if (!file_exists($composerLockPath)) {
return 'unknown';
}
$lockData = json_decode(file_get_contents($composerLockPath), true);
if (json_last_error() || empty($lockData['packages'])) {
return 'unknown';
}
foreach ($lockData['packages'] as $package) {
if ($package['name'] === 'silverstripe/framework') {
return $package['version'];
}
}
return 'unknown';
} | [
"public",
"function",
"getFrameworkVersion",
"(",
")",
"{",
"$",
"composerLockPath",
"=",
"BASE_PATH",
".",
"'/composer.lock'",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"composerLockPath",
")",
")",
"{",
"return",
"'unknown'",
";",
"}",
"$",
"lockData",
"=",
"json_decode",
"(",
"file_get_contents",
"(",
"$",
"composerLockPath",
")",
",",
"true",
")",
";",
"if",
"(",
"json_last_error",
"(",
")",
"||",
"empty",
"(",
"$",
"lockData",
"[",
"'packages'",
"]",
")",
")",
"{",
"return",
"'unknown'",
";",
"}",
"foreach",
"(",
"$",
"lockData",
"[",
"'packages'",
"]",
"as",
"$",
"package",
")",
"{",
"if",
"(",
"$",
"package",
"[",
"'name'",
"]",
"===",
"'silverstripe/framework'",
")",
"{",
"return",
"$",
"package",
"[",
"'version'",
"]",
";",
"}",
"}",
"return",
"'unknown'",
";",
"}"
]
| Get string representation of the framework version
@return string | [
"Get",
"string",
"representation",
"of",
"the",
"framework",
"version"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallConfig.php#L168-L184 | train |
silverstripe/silverstripe-framework | src/Core/Startup/AbstractConfirmationToken.php | AbstractConfirmationToken.prepare_tokens | public static function prepare_tokens($keys, HTTPRequest $request)
{
$target = null;
foreach ($keys as $key) {
$token = new static($key, $request);
// Validate this token
if ($token->reloadRequired() || $token->reloadRequiredIfError()) {
$token->suppress();
$target = $token;
}
}
return $target;
} | php | public static function prepare_tokens($keys, HTTPRequest $request)
{
$target = null;
foreach ($keys as $key) {
$token = new static($key, $request);
// Validate this token
if ($token->reloadRequired() || $token->reloadRequiredIfError()) {
$token->suppress();
$target = $token;
}
}
return $target;
} | [
"public",
"static",
"function",
"prepare_tokens",
"(",
"$",
"keys",
",",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"target",
"=",
"null",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"$",
"token",
"=",
"new",
"static",
"(",
"$",
"key",
",",
"$",
"request",
")",
";",
"// Validate this token",
"if",
"(",
"$",
"token",
"->",
"reloadRequired",
"(",
")",
"||",
"$",
"token",
"->",
"reloadRequiredIfError",
"(",
")",
")",
"{",
"$",
"token",
"->",
"suppress",
"(",
")",
";",
"$",
"target",
"=",
"$",
"token",
";",
"}",
"}",
"return",
"$",
"target",
";",
"}"
]
| Given a list of token names, suppress all tokens that have not been validated, and
return the non-validated token with the highest priority
@param array $keys List of token keys in ascending priority (low to high)
@param HTTPRequest $request
@return static The token container for the unvalidated $key given with the highest priority | [
"Given",
"a",
"list",
"of",
"token",
"names",
"suppress",
"all",
"tokens",
"that",
"have",
"not",
"been",
"validated",
"and",
"return",
"the",
"non",
"-",
"validated",
"token",
"with",
"the",
"highest",
"priority"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Startup/AbstractConfirmationToken.php#L40-L52 | train |
silverstripe/silverstripe-framework | src/Core/Startup/AbstractConfirmationToken.php | AbstractConfirmationToken.genToken | protected function genToken()
{
// Generate a new random token (as random as possible)
$rg = new RandomGenerator();
$token = $rg->randomToken('md5');
// Store a file in the session save path (safer than /tmp, as open_basedir might limit that)
file_put_contents($this->pathForToken($token), $token);
return $token;
} | php | protected function genToken()
{
// Generate a new random token (as random as possible)
$rg = new RandomGenerator();
$token = $rg->randomToken('md5');
// Store a file in the session save path (safer than /tmp, as open_basedir might limit that)
file_put_contents($this->pathForToken($token), $token);
return $token;
} | [
"protected",
"function",
"genToken",
"(",
")",
"{",
"// Generate a new random token (as random as possible)",
"$",
"rg",
"=",
"new",
"RandomGenerator",
"(",
")",
";",
"$",
"token",
"=",
"$",
"rg",
"->",
"randomToken",
"(",
"'md5'",
")",
";",
"// Store a file in the session save path (safer than /tmp, as open_basedir might limit that)",
"file_put_contents",
"(",
"$",
"this",
"->",
"pathForToken",
"(",
"$",
"token",
")",
",",
"$",
"token",
")",
";",
"return",
"$",
"token",
";",
"}"
]
| Generate a new random token and store it
@return string Token name | [
"Generate",
"a",
"new",
"random",
"token",
"and",
"store",
"it"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Startup/AbstractConfirmationToken.php#L70-L80 | train |
silverstripe/silverstripe-framework | src/Core/Startup/AbstractConfirmationToken.php | AbstractConfirmationToken.reloadWithToken | public function reloadWithToken()
{
$location = $this->redirectURL();
$locationJS = Convert::raw2js($location);
$locationATT = Convert::raw2att($location);
$body = <<<HTML
<script>location.href='$locationJS';</script>
<noscript><meta http-equiv="refresh" content="0; url=$locationATT"></noscript>
You are being redirected. If you are not redirected soon, <a href="$locationATT">click here to continue</a>
HTML;
// Build response
$result = new HTTPResponse($body);
$result->redirect($location);
return $result;
} | php | public function reloadWithToken()
{
$location = $this->redirectURL();
$locationJS = Convert::raw2js($location);
$locationATT = Convert::raw2att($location);
$body = <<<HTML
<script>location.href='$locationJS';</script>
<noscript><meta http-equiv="refresh" content="0; url=$locationATT"></noscript>
You are being redirected. If you are not redirected soon, <a href="$locationATT">click here to continue</a>
HTML;
// Build response
$result = new HTTPResponse($body);
$result->redirect($location);
return $result;
} | [
"public",
"function",
"reloadWithToken",
"(",
")",
"{",
"$",
"location",
"=",
"$",
"this",
"->",
"redirectURL",
"(",
")",
";",
"$",
"locationJS",
"=",
"Convert",
"::",
"raw2js",
"(",
"$",
"location",
")",
";",
"$",
"locationATT",
"=",
"Convert",
"::",
"raw2att",
"(",
"$",
"location",
")",
";",
"$",
"body",
"=",
" <<<HTML\n<script>location.href='$locationJS';</script>\n<noscript><meta http-equiv=\"refresh\" content=\"0; url=$locationATT\"></noscript>\nYou are being redirected. If you are not redirected soon, <a href=\"$locationATT\">click here to continue</a>\nHTML",
";",
"// Build response",
"$",
"result",
"=",
"new",
"HTTPResponse",
"(",
"$",
"body",
")",
";",
"$",
"result",
"->",
"redirect",
"(",
"$",
"location",
")",
";",
"return",
"$",
"result",
";",
"}"
]
| Forces a reload of the request with the token included
@return HTTPResponse | [
"Forces",
"a",
"reload",
"of",
"the",
"request",
"with",
"the",
"token",
"included"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Startup/AbstractConfirmationToken.php#L131-L146 | train |
silverstripe/silverstripe-framework | src/Control/RequestHandler.php | RequestHandler.handleAction | protected function handleAction($request, $action)
{
$classMessage = Director::isLive() ? 'on this handler' : 'on class ' . static::class;
if (!$this->hasMethod($action)) {
return new HTTPResponse("Action '$action' isn't available $classMessage.", 404);
}
$res = $this->extend('beforeCallActionHandler', $request, $action);
if ($res) {
return reset($res);
}
$actionRes = $this->$action($request);
$res = $this->extend('afterCallActionHandler', $request, $action, $actionRes);
if ($res) {
return reset($res);
}
return $actionRes;
} | php | protected function handleAction($request, $action)
{
$classMessage = Director::isLive() ? 'on this handler' : 'on class ' . static::class;
if (!$this->hasMethod($action)) {
return new HTTPResponse("Action '$action' isn't available $classMessage.", 404);
}
$res = $this->extend('beforeCallActionHandler', $request, $action);
if ($res) {
return reset($res);
}
$actionRes = $this->$action($request);
$res = $this->extend('afterCallActionHandler', $request, $action, $actionRes);
if ($res) {
return reset($res);
}
return $actionRes;
} | [
"protected",
"function",
"handleAction",
"(",
"$",
"request",
",",
"$",
"action",
")",
"{",
"$",
"classMessage",
"=",
"Director",
"::",
"isLive",
"(",
")",
"?",
"'on this handler'",
":",
"'on class '",
".",
"static",
"::",
"class",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"hasMethod",
"(",
"$",
"action",
")",
")",
"{",
"return",
"new",
"HTTPResponse",
"(",
"\"Action '$action' isn't available $classMessage.\"",
",",
"404",
")",
";",
"}",
"$",
"res",
"=",
"$",
"this",
"->",
"extend",
"(",
"'beforeCallActionHandler'",
",",
"$",
"request",
",",
"$",
"action",
")",
";",
"if",
"(",
"$",
"res",
")",
"{",
"return",
"reset",
"(",
"$",
"res",
")",
";",
"}",
"$",
"actionRes",
"=",
"$",
"this",
"->",
"$",
"action",
"(",
"$",
"request",
")",
";",
"$",
"res",
"=",
"$",
"this",
"->",
"extend",
"(",
"'afterCallActionHandler'",
",",
"$",
"request",
",",
"$",
"action",
",",
"$",
"actionRes",
")",
";",
"if",
"(",
"$",
"res",
")",
"{",
"return",
"reset",
"(",
"$",
"res",
")",
";",
"}",
"return",
"$",
"actionRes",
";",
"}"
]
| Given a request, and an action name, call that action name on this RequestHandler
Must not raise HTTPResponse_Exceptions - instead it should return
@param $request
@param $action
@return HTTPResponse | [
"Given",
"a",
"request",
"and",
"an",
"action",
"name",
"call",
"that",
"action",
"name",
"on",
"this",
"RequestHandler"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RequestHandler.php#L310-L331 | train |
silverstripe/silverstripe-framework | src/Control/RequestHandler.php | RequestHandler.allowedActions | public function allowedActions($limitToClass = null)
{
if ($limitToClass) {
$actions = Config::forClass($limitToClass)->get('allowed_actions', true);
} else {
$actions = $this->config()->get('allowed_actions');
}
if (is_array($actions)) {
if (array_key_exists('*', $actions)) {
throw new InvalidArgumentException("Invalid allowed_action '*'");
}
// convert all keys and values to lowercase to
// allow for easier comparison, unless it is a permission code
$actions = array_change_key_case($actions, CASE_LOWER);
foreach ($actions as $key => $value) {
if (is_numeric($key)) {
$actions[$key] = strtolower($value);
}
}
return $actions;
} else {
return null;
}
} | php | public function allowedActions($limitToClass = null)
{
if ($limitToClass) {
$actions = Config::forClass($limitToClass)->get('allowed_actions', true);
} else {
$actions = $this->config()->get('allowed_actions');
}
if (is_array($actions)) {
if (array_key_exists('*', $actions)) {
throw new InvalidArgumentException("Invalid allowed_action '*'");
}
// convert all keys and values to lowercase to
// allow for easier comparison, unless it is a permission code
$actions = array_change_key_case($actions, CASE_LOWER);
foreach ($actions as $key => $value) {
if (is_numeric($key)) {
$actions[$key] = strtolower($value);
}
}
return $actions;
} else {
return null;
}
} | [
"public",
"function",
"allowedActions",
"(",
"$",
"limitToClass",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"limitToClass",
")",
"{",
"$",
"actions",
"=",
"Config",
"::",
"forClass",
"(",
"$",
"limitToClass",
")",
"->",
"get",
"(",
"'allowed_actions'",
",",
"true",
")",
";",
"}",
"else",
"{",
"$",
"actions",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'allowed_actions'",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"actions",
")",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"'*'",
",",
"$",
"actions",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid allowed_action '*'\"",
")",
";",
"}",
"// convert all keys and values to lowercase to",
"// allow for easier comparison, unless it is a permission code",
"$",
"actions",
"=",
"array_change_key_case",
"(",
"$",
"actions",
",",
"CASE_LOWER",
")",
";",
"foreach",
"(",
"$",
"actions",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"key",
")",
")",
"{",
"$",
"actions",
"[",
"$",
"key",
"]",
"=",
"strtolower",
"(",
"$",
"value",
")",
";",
"}",
"}",
"return",
"$",
"actions",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
]
| Get a array of allowed actions defined on this controller,
any parent classes or extensions.
Caution: Since 3.1, allowed_actions definitions only apply
to methods on the controller they're defined on,
so it is recommended to use the $class argument
when invoking this method.
@param string $limitToClass
@return array|null | [
"Get",
"a",
"array",
"of",
"allowed",
"actions",
"defined",
"on",
"this",
"controller",
"any",
"parent",
"classes",
"or",
"extensions",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RequestHandler.php#L345-L372 | train |
silverstripe/silverstripe-framework | src/Control/RequestHandler.php | RequestHandler.hasAction | public function hasAction($action)
{
if ($action == 'index') {
return true;
}
// Don't allow access to any non-public methods (inspect instance plus all extensions)
$insts = array_merge([$this], (array) $this->getExtensionInstances());
foreach ($insts as $inst) {
if (!method_exists($inst, $action)) {
continue;
}
$r = new ReflectionClass(get_class($inst));
$m = $r->getMethod($action);
if (!$m || !$m->isPublic()) {
return false;
}
}
$action = strtolower($action);
$actions = $this->allowedActions();
// Check if the action is defined in the allowed actions of any ancestry class
// as either a key or value. Note that if the action is numeric, then keys are not
// searched for actions to prevent actual array keys being recognised as actions.
if (is_array($actions)) {
$isKey = !is_numeric($action) && array_key_exists($action, $actions);
$isValue = in_array($action, $actions, true);
if ($isKey || $isValue) {
return true;
}
}
$actionsWithoutExtra = $this->config()->get('allowed_actions', true);
if (!is_array($actions) || !$actionsWithoutExtra) {
if (!in_array(strtolower($action), ['run', 'doinit']) && method_exists($this, $action)) {
return true;
}
}
return false;
} | php | public function hasAction($action)
{
if ($action == 'index') {
return true;
}
// Don't allow access to any non-public methods (inspect instance plus all extensions)
$insts = array_merge([$this], (array) $this->getExtensionInstances());
foreach ($insts as $inst) {
if (!method_exists($inst, $action)) {
continue;
}
$r = new ReflectionClass(get_class($inst));
$m = $r->getMethod($action);
if (!$m || !$m->isPublic()) {
return false;
}
}
$action = strtolower($action);
$actions = $this->allowedActions();
// Check if the action is defined in the allowed actions of any ancestry class
// as either a key or value. Note that if the action is numeric, then keys are not
// searched for actions to prevent actual array keys being recognised as actions.
if (is_array($actions)) {
$isKey = !is_numeric($action) && array_key_exists($action, $actions);
$isValue = in_array($action, $actions, true);
if ($isKey || $isValue) {
return true;
}
}
$actionsWithoutExtra = $this->config()->get('allowed_actions', true);
if (!is_array($actions) || !$actionsWithoutExtra) {
if (!in_array(strtolower($action), ['run', 'doinit']) && method_exists($this, $action)) {
return true;
}
}
return false;
} | [
"public",
"function",
"hasAction",
"(",
"$",
"action",
")",
"{",
"if",
"(",
"$",
"action",
"==",
"'index'",
")",
"{",
"return",
"true",
";",
"}",
"// Don't allow access to any non-public methods (inspect instance plus all extensions)",
"$",
"insts",
"=",
"array_merge",
"(",
"[",
"$",
"this",
"]",
",",
"(",
"array",
")",
"$",
"this",
"->",
"getExtensionInstances",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"insts",
"as",
"$",
"inst",
")",
"{",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"inst",
",",
"$",
"action",
")",
")",
"{",
"continue",
";",
"}",
"$",
"r",
"=",
"new",
"ReflectionClass",
"(",
"get_class",
"(",
"$",
"inst",
")",
")",
";",
"$",
"m",
"=",
"$",
"r",
"->",
"getMethod",
"(",
"$",
"action",
")",
";",
"if",
"(",
"!",
"$",
"m",
"||",
"!",
"$",
"m",
"->",
"isPublic",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"$",
"action",
"=",
"strtolower",
"(",
"$",
"action",
")",
";",
"$",
"actions",
"=",
"$",
"this",
"->",
"allowedActions",
"(",
")",
";",
"// Check if the action is defined in the allowed actions of any ancestry class",
"// as either a key or value. Note that if the action is numeric, then keys are not",
"// searched for actions to prevent actual array keys being recognised as actions.",
"if",
"(",
"is_array",
"(",
"$",
"actions",
")",
")",
"{",
"$",
"isKey",
"=",
"!",
"is_numeric",
"(",
"$",
"action",
")",
"&&",
"array_key_exists",
"(",
"$",
"action",
",",
"$",
"actions",
")",
";",
"$",
"isValue",
"=",
"in_array",
"(",
"$",
"action",
",",
"$",
"actions",
",",
"true",
")",
";",
"if",
"(",
"$",
"isKey",
"||",
"$",
"isValue",
")",
"{",
"return",
"true",
";",
"}",
"}",
"$",
"actionsWithoutExtra",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'allowed_actions'",
",",
"true",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"actions",
")",
"||",
"!",
"$",
"actionsWithoutExtra",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"strtolower",
"(",
"$",
"action",
")",
",",
"[",
"'run'",
",",
"'doinit'",
"]",
")",
"&&",
"method_exists",
"(",
"$",
"this",
",",
"$",
"action",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Checks if this request handler has a specific action,
even if the current user cannot access it.
Includes class ancestry and extensions in the checks.
@param string $action
@return bool | [
"Checks",
"if",
"this",
"request",
"handler",
"has",
"a",
"specific",
"action",
"even",
"if",
"the",
"current",
"user",
"cannot",
"access",
"it",
".",
"Includes",
"class",
"ancestry",
"and",
"extensions",
"in",
"the",
"checks",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RequestHandler.php#L382-L423 | train |
silverstripe/silverstripe-framework | src/Control/RequestHandler.php | RequestHandler.definingClassForAction | protected function definingClassForAction($actionOrigCasing)
{
$action = strtolower($actionOrigCasing);
$definingClass = null;
$insts = array_merge([$this], (array) $this->getExtensionInstances());
foreach ($insts as $inst) {
if (!method_exists($inst, $action)) {
continue;
}
$r = new ReflectionClass(get_class($inst));
$m = $r->getMethod($actionOrigCasing);
return $m->getDeclaringClass()->getName();
}
return null;
} | php | protected function definingClassForAction($actionOrigCasing)
{
$action = strtolower($actionOrigCasing);
$definingClass = null;
$insts = array_merge([$this], (array) $this->getExtensionInstances());
foreach ($insts as $inst) {
if (!method_exists($inst, $action)) {
continue;
}
$r = new ReflectionClass(get_class($inst));
$m = $r->getMethod($actionOrigCasing);
return $m->getDeclaringClass()->getName();
}
return null;
} | [
"protected",
"function",
"definingClassForAction",
"(",
"$",
"actionOrigCasing",
")",
"{",
"$",
"action",
"=",
"strtolower",
"(",
"$",
"actionOrigCasing",
")",
";",
"$",
"definingClass",
"=",
"null",
";",
"$",
"insts",
"=",
"array_merge",
"(",
"[",
"$",
"this",
"]",
",",
"(",
"array",
")",
"$",
"this",
"->",
"getExtensionInstances",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"insts",
"as",
"$",
"inst",
")",
"{",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"inst",
",",
"$",
"action",
")",
")",
"{",
"continue",
";",
"}",
"$",
"r",
"=",
"new",
"ReflectionClass",
"(",
"get_class",
"(",
"$",
"inst",
")",
")",
";",
"$",
"m",
"=",
"$",
"r",
"->",
"getMethod",
"(",
"$",
"actionOrigCasing",
")",
";",
"return",
"$",
"m",
"->",
"getDeclaringClass",
"(",
")",
"->",
"getName",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Return the class that defines the given action, so that we know where to check allowed_actions.
@param string $actionOrigCasing
@return string | [
"Return",
"the",
"class",
"that",
"defines",
"the",
"given",
"action",
"so",
"that",
"we",
"know",
"where",
"to",
"check",
"allowed_actions",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RequestHandler.php#L431-L446 | train |
silverstripe/silverstripe-framework | src/Control/RequestHandler.php | RequestHandler.Link | public function Link($action = null)
{
// Check configured url_segment
$url = $this->config()->get('url_segment');
if ($url) {
$link = Controller::join_links($url, $action, '/');
// Give extensions the chance to modify by reference
$this->extend('updateLink', $link, $action);
return $link;
}
// no link defined by default
trigger_error(
'Request handler ' . static::class . ' does not have a url_segment defined. ' . 'Relying on this link may be an application error',
E_USER_WARNING
);
return null;
} | php | public function Link($action = null)
{
// Check configured url_segment
$url = $this->config()->get('url_segment');
if ($url) {
$link = Controller::join_links($url, $action, '/');
// Give extensions the chance to modify by reference
$this->extend('updateLink', $link, $action);
return $link;
}
// no link defined by default
trigger_error(
'Request handler ' . static::class . ' does not have a url_segment defined. ' . 'Relying on this link may be an application error',
E_USER_WARNING
);
return null;
} | [
"public",
"function",
"Link",
"(",
"$",
"action",
"=",
"null",
")",
"{",
"// Check configured url_segment",
"$",
"url",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'url_segment'",
")",
";",
"if",
"(",
"$",
"url",
")",
"{",
"$",
"link",
"=",
"Controller",
"::",
"join_links",
"(",
"$",
"url",
",",
"$",
"action",
",",
"'/'",
")",
";",
"// Give extensions the chance to modify by reference",
"$",
"this",
"->",
"extend",
"(",
"'updateLink'",
",",
"$",
"link",
",",
"$",
"action",
")",
";",
"return",
"$",
"link",
";",
"}",
"// no link defined by default",
"trigger_error",
"(",
"'Request handler '",
".",
"static",
"::",
"class",
".",
"' does not have a url_segment defined. '",
".",
"'Relying on this link may be an application error'",
",",
"E_USER_WARNING",
")",
";",
"return",
"null",
";",
"}"
]
| Returns a link to this controller. Overload with your own Link rules if they exist.
@param string $action Optional action
@return string | [
"Returns",
"a",
"link",
"to",
"this",
"controller",
".",
"Overload",
"with",
"your",
"own",
"Link",
"rules",
"if",
"they",
"exist",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RequestHandler.php#L562-L580 | train |
silverstripe/silverstripe-framework | src/Control/RequestHandler.php | RequestHandler.getReturnReferer | public function getReturnReferer()
{
$referer = $this->getReferer();
if ($referer && Director::is_site_url($referer)) {
return $referer;
}
return null;
} | php | public function getReturnReferer()
{
$referer = $this->getReferer();
if ($referer && Director::is_site_url($referer)) {
return $referer;
}
return null;
} | [
"public",
"function",
"getReturnReferer",
"(",
")",
"{",
"$",
"referer",
"=",
"$",
"this",
"->",
"getReferer",
"(",
")",
";",
"if",
"(",
"$",
"referer",
"&&",
"Director",
"::",
"is_site_url",
"(",
"$",
"referer",
")",
")",
"{",
"return",
"$",
"referer",
";",
"}",
"return",
"null",
";",
"}"
]
| Returns the referer, if it is safely validated as an internal URL
and can be redirected to.
@internal called from {@see Form::getValidationErrorResponse}
@return string|null | [
"Returns",
"the",
"referer",
"if",
"it",
"is",
"safely",
"validated",
"as",
"an",
"internal",
"URL",
"and",
"can",
"be",
"redirected",
"to",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/RequestHandler.php#L628-L635 | train |
silverstripe/silverstripe-framework | src/ORM/Queries/SQLUpdate.php | SQLUpdate.create | public static function create($table = null, $assignment = array(), $where = array())
{
return Injector::inst()->createWithArgs(__CLASS__, func_get_args());
} | php | public static function create($table = null, $assignment = array(), $where = array())
{
return Injector::inst()->createWithArgs(__CLASS__, func_get_args());
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"table",
"=",
"null",
",",
"$",
"assignment",
"=",
"array",
"(",
")",
",",
"$",
"where",
"=",
"array",
"(",
")",
")",
"{",
"return",
"Injector",
"::",
"inst",
"(",
")",
"->",
"createWithArgs",
"(",
"__CLASS__",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Construct a new SQLUpdate object
@param string $table Table name to update (ANSI quoted)
@param array $assignment List of column assignments
@param array $where List of where clauses
@return static | [
"Construct",
"a",
"new",
"SQLUpdate",
"object"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLUpdate.php#L29-L32 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/TinyMCECombinedGenerator.php | TinyMCECombinedGenerator.generateContent | public function generateContent(TinyMCEConfig $config)
{
$tinymceDir = $config->getTinyMCEResource();
// List of string / ModuleResource references to embed
$files = [];
// Add core languages
$language = $config->getOption('language');
if ($language) {
$files[] = $this->resolveRelativeResource($tinymceDir, "langs/{$language}");
}
// Add plugins, along with any plugin specific lang files
foreach ($config->getPlugins() as $plugin => $path) {
// Add external plugin
if ($path) {
// Skip external urls
if (is_string($path) && !Director::is_site_url($path)) {
continue;
}
// Convert URLS to relative paths
if (is_string($path)) {
$path = Director::makeRelative($path);
}
// Ensure file exists
if ($this->resourceExists($path)) {
$files[] = $path;
}
continue;
}
// Core tinymce plugin
$files[] = $this->resolveRelativeResource($tinymceDir, "plugins/{$plugin}/plugin");
if ($language) {
$files[] = $this->resolveRelativeResource($tinymceDir, "plugins/{$plugin}/langs/{$language}");
}
}
// Add themes
$theme = $config->getTheme();
if ($theme) {
$files[] = $this->resolveRelativeResource($tinymceDir, "themes/{$theme}/theme");
if ($language) {
$files[] = $this->resolveRelativeResource($tinymceDir, "themes/{$theme}/langs/{$language}");
}
}
// Process source files
$files = array_filter($files);
$libResource = $this->resolveRelativeResource($tinymceDir, 'tinymce');
$libContent = $this->getFileContents($libResource);
// Register vars for config
$baseDirJS = Convert::raw2js(Director::absoluteBaseURL());
$name = Convert::raw2js($this->checkName($config));
$buffer = [];
$buffer[] = <<<SCRIPT
(function() {
var baseTag = window.document.getElementsByTagName('base');
var baseURL = baseTag.length ? baseTag[0].baseURI : '$baseDirJS';
var editorIdentifier = '$name';
SCRIPT;
$buffer[] = <<<SCRIPT
(function() {
// Avoid double-registration
if (window.tinymce) {
return;
}
var tinyMCEPreInit = {
base: baseURL,
suffix: '.min',
};
$libContent
})();
SCRIPT;
// Load all tinymce script files into buffer
foreach ($files as $path) {
$buffer[] = $this->getFileContents($path);
}
// Generate urls for all files
// Note all urls must be relative to base_dir
$fileURLS = array_map(function ($path) {
if ($path instanceof ModuleResource) {
return Director::makeRelative($path->getURL());
}
return $path;
}, $files);
// Join list of paths
$filesList = Convert::raw2js(implode(',', $fileURLS));
// Mark all themes, plugins and languages as done
$buffer[] = "window.tinymce.each('$filesList'.split(',')," . "function(f){tinymce.ScriptLoader.markDone(baseURL+f);});";
$buffer[] = '})();';
return implode("\n", $buffer) . "\n";
} | php | public function generateContent(TinyMCEConfig $config)
{
$tinymceDir = $config->getTinyMCEResource();
// List of string / ModuleResource references to embed
$files = [];
// Add core languages
$language = $config->getOption('language');
if ($language) {
$files[] = $this->resolveRelativeResource($tinymceDir, "langs/{$language}");
}
// Add plugins, along with any plugin specific lang files
foreach ($config->getPlugins() as $plugin => $path) {
// Add external plugin
if ($path) {
// Skip external urls
if (is_string($path) && !Director::is_site_url($path)) {
continue;
}
// Convert URLS to relative paths
if (is_string($path)) {
$path = Director::makeRelative($path);
}
// Ensure file exists
if ($this->resourceExists($path)) {
$files[] = $path;
}
continue;
}
// Core tinymce plugin
$files[] = $this->resolveRelativeResource($tinymceDir, "plugins/{$plugin}/plugin");
if ($language) {
$files[] = $this->resolveRelativeResource($tinymceDir, "plugins/{$plugin}/langs/{$language}");
}
}
// Add themes
$theme = $config->getTheme();
if ($theme) {
$files[] = $this->resolveRelativeResource($tinymceDir, "themes/{$theme}/theme");
if ($language) {
$files[] = $this->resolveRelativeResource($tinymceDir, "themes/{$theme}/langs/{$language}");
}
}
// Process source files
$files = array_filter($files);
$libResource = $this->resolveRelativeResource($tinymceDir, 'tinymce');
$libContent = $this->getFileContents($libResource);
// Register vars for config
$baseDirJS = Convert::raw2js(Director::absoluteBaseURL());
$name = Convert::raw2js($this->checkName($config));
$buffer = [];
$buffer[] = <<<SCRIPT
(function() {
var baseTag = window.document.getElementsByTagName('base');
var baseURL = baseTag.length ? baseTag[0].baseURI : '$baseDirJS';
var editorIdentifier = '$name';
SCRIPT;
$buffer[] = <<<SCRIPT
(function() {
// Avoid double-registration
if (window.tinymce) {
return;
}
var tinyMCEPreInit = {
base: baseURL,
suffix: '.min',
};
$libContent
})();
SCRIPT;
// Load all tinymce script files into buffer
foreach ($files as $path) {
$buffer[] = $this->getFileContents($path);
}
// Generate urls for all files
// Note all urls must be relative to base_dir
$fileURLS = array_map(function ($path) {
if ($path instanceof ModuleResource) {
return Director::makeRelative($path->getURL());
}
return $path;
}, $files);
// Join list of paths
$filesList = Convert::raw2js(implode(',', $fileURLS));
// Mark all themes, plugins and languages as done
$buffer[] = "window.tinymce.each('$filesList'.split(',')," . "function(f){tinymce.ScriptLoader.markDone(baseURL+f);});";
$buffer[] = '})();';
return implode("\n", $buffer) . "\n";
} | [
"public",
"function",
"generateContent",
"(",
"TinyMCEConfig",
"$",
"config",
")",
"{",
"$",
"tinymceDir",
"=",
"$",
"config",
"->",
"getTinyMCEResource",
"(",
")",
";",
"// List of string / ModuleResource references to embed",
"$",
"files",
"=",
"[",
"]",
";",
"// Add core languages",
"$",
"language",
"=",
"$",
"config",
"->",
"getOption",
"(",
"'language'",
")",
";",
"if",
"(",
"$",
"language",
")",
"{",
"$",
"files",
"[",
"]",
"=",
"$",
"this",
"->",
"resolveRelativeResource",
"(",
"$",
"tinymceDir",
",",
"\"langs/{$language}\"",
")",
";",
"}",
"// Add plugins, along with any plugin specific lang files",
"foreach",
"(",
"$",
"config",
"->",
"getPlugins",
"(",
")",
"as",
"$",
"plugin",
"=>",
"$",
"path",
")",
"{",
"// Add external plugin",
"if",
"(",
"$",
"path",
")",
"{",
"// Skip external urls",
"if",
"(",
"is_string",
"(",
"$",
"path",
")",
"&&",
"!",
"Director",
"::",
"is_site_url",
"(",
"$",
"path",
")",
")",
"{",
"continue",
";",
"}",
"// Convert URLS to relative paths",
"if",
"(",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"$",
"path",
"=",
"Director",
"::",
"makeRelative",
"(",
"$",
"path",
")",
";",
"}",
"// Ensure file exists",
"if",
"(",
"$",
"this",
"->",
"resourceExists",
"(",
"$",
"path",
")",
")",
"{",
"$",
"files",
"[",
"]",
"=",
"$",
"path",
";",
"}",
"continue",
";",
"}",
"// Core tinymce plugin",
"$",
"files",
"[",
"]",
"=",
"$",
"this",
"->",
"resolveRelativeResource",
"(",
"$",
"tinymceDir",
",",
"\"plugins/{$plugin}/plugin\"",
")",
";",
"if",
"(",
"$",
"language",
")",
"{",
"$",
"files",
"[",
"]",
"=",
"$",
"this",
"->",
"resolveRelativeResource",
"(",
"$",
"tinymceDir",
",",
"\"plugins/{$plugin}/langs/{$language}\"",
")",
";",
"}",
"}",
"// Add themes",
"$",
"theme",
"=",
"$",
"config",
"->",
"getTheme",
"(",
")",
";",
"if",
"(",
"$",
"theme",
")",
"{",
"$",
"files",
"[",
"]",
"=",
"$",
"this",
"->",
"resolveRelativeResource",
"(",
"$",
"tinymceDir",
",",
"\"themes/{$theme}/theme\"",
")",
";",
"if",
"(",
"$",
"language",
")",
"{",
"$",
"files",
"[",
"]",
"=",
"$",
"this",
"->",
"resolveRelativeResource",
"(",
"$",
"tinymceDir",
",",
"\"themes/{$theme}/langs/{$language}\"",
")",
";",
"}",
"}",
"// Process source files",
"$",
"files",
"=",
"array_filter",
"(",
"$",
"files",
")",
";",
"$",
"libResource",
"=",
"$",
"this",
"->",
"resolveRelativeResource",
"(",
"$",
"tinymceDir",
",",
"'tinymce'",
")",
";",
"$",
"libContent",
"=",
"$",
"this",
"->",
"getFileContents",
"(",
"$",
"libResource",
")",
";",
"// Register vars for config",
"$",
"baseDirJS",
"=",
"Convert",
"::",
"raw2js",
"(",
"Director",
"::",
"absoluteBaseURL",
"(",
")",
")",
";",
"$",
"name",
"=",
"Convert",
"::",
"raw2js",
"(",
"$",
"this",
"->",
"checkName",
"(",
"$",
"config",
")",
")",
";",
"$",
"buffer",
"=",
"[",
"]",
";",
"$",
"buffer",
"[",
"]",
"=",
" <<<SCRIPT\n(function() {\n var baseTag = window.document.getElementsByTagName('base');\n var baseURL = baseTag.length ? baseTag[0].baseURI : '$baseDirJS';\n var editorIdentifier = '$name';\nSCRIPT",
";",
"$",
"buffer",
"[",
"]",
"=",
" <<<SCRIPT\n(function() {\n // Avoid double-registration\n if (window.tinymce) {\n return;\n }\n\n var tinyMCEPreInit = {\n base: baseURL,\n suffix: '.min',\n };\n $libContent\n})();\nSCRIPT",
";",
"// Load all tinymce script files into buffer",
"foreach",
"(",
"$",
"files",
"as",
"$",
"path",
")",
"{",
"$",
"buffer",
"[",
"]",
"=",
"$",
"this",
"->",
"getFileContents",
"(",
"$",
"path",
")",
";",
"}",
"// Generate urls for all files",
"// Note all urls must be relative to base_dir",
"$",
"fileURLS",
"=",
"array_map",
"(",
"function",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"path",
"instanceof",
"ModuleResource",
")",
"{",
"return",
"Director",
"::",
"makeRelative",
"(",
"$",
"path",
"->",
"getURL",
"(",
")",
")",
";",
"}",
"return",
"$",
"path",
";",
"}",
",",
"$",
"files",
")",
";",
"// Join list of paths",
"$",
"filesList",
"=",
"Convert",
"::",
"raw2js",
"(",
"implode",
"(",
"','",
",",
"$",
"fileURLS",
")",
")",
";",
"// Mark all themes, plugins and languages as done",
"$",
"buffer",
"[",
"]",
"=",
"\"window.tinymce.each('$filesList'.split(','),\"",
".",
"\"function(f){tinymce.ScriptLoader.markDone(baseURL+f);});\"",
";",
"$",
"buffer",
"[",
"]",
"=",
"'})();'",
";",
"return",
"implode",
"(",
"\"\\n\"",
",",
"$",
"buffer",
")",
".",
"\"\\n\"",
";",
"}"
]
| Build raw config for tinymce
@param TinyMCEConfig $config
@return string | [
"Build",
"raw",
"config",
"for",
"tinymce"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php#L78-L177 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/TinyMCECombinedGenerator.php | TinyMCECombinedGenerator.checkName | protected function checkName(TinyMCEConfig $config)
{
$configs = HTMLEditorConfig::get_available_configs_map();
foreach ($configs as $id => $name) {
if (HTMLEditorConfig::get($id) === $config) {
return $id;
}
}
return 'custom';
} | php | protected function checkName(TinyMCEConfig $config)
{
$configs = HTMLEditorConfig::get_available_configs_map();
foreach ($configs as $id => $name) {
if (HTMLEditorConfig::get($id) === $config) {
return $id;
}
}
return 'custom';
} | [
"protected",
"function",
"checkName",
"(",
"TinyMCEConfig",
"$",
"config",
")",
"{",
"$",
"configs",
"=",
"HTMLEditorConfig",
"::",
"get_available_configs_map",
"(",
")",
";",
"foreach",
"(",
"$",
"configs",
"as",
"$",
"id",
"=>",
"$",
"name",
")",
"{",
"if",
"(",
"HTMLEditorConfig",
"::",
"get",
"(",
"$",
"id",
")",
"===",
"$",
"config",
")",
"{",
"return",
"$",
"id",
";",
"}",
"}",
"return",
"'custom'",
";",
"}"
]
| Check if this config is registered under a given key
@param TinyMCEConfig $config
@return string | [
"Check",
"if",
"this",
"config",
"is",
"registered",
"under",
"a",
"given",
"key"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php#L211-L220 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/TinyMCECombinedGenerator.php | TinyMCECombinedGenerator.generateFilename | public function generateFilename(TinyMCEConfig $config)
{
$hash = substr(sha1(json_encode($config->getAttributes())), 0, 10);
$name = $this->checkName($config);
$url = str_replace(
['{name}', '{hash}'],
[$name, $hash],
$this->config()->get('filename_base')
);
return $url;
} | php | public function generateFilename(TinyMCEConfig $config)
{
$hash = substr(sha1(json_encode($config->getAttributes())), 0, 10);
$name = $this->checkName($config);
$url = str_replace(
['{name}', '{hash}'],
[$name, $hash],
$this->config()->get('filename_base')
);
return $url;
} | [
"public",
"function",
"generateFilename",
"(",
"TinyMCEConfig",
"$",
"config",
")",
"{",
"$",
"hash",
"=",
"substr",
"(",
"sha1",
"(",
"json_encode",
"(",
"$",
"config",
"->",
"getAttributes",
"(",
")",
")",
")",
",",
"0",
",",
"10",
")",
";",
"$",
"name",
"=",
"$",
"this",
"->",
"checkName",
"(",
"$",
"config",
")",
";",
"$",
"url",
"=",
"str_replace",
"(",
"[",
"'{name}'",
",",
"'{hash}'",
"]",
",",
"[",
"$",
"name",
",",
"$",
"hash",
"]",
",",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'filename_base'",
")",
")",
";",
"return",
"$",
"url",
";",
"}"
]
| Get filename to use for this config
@param TinyMCEConfig $config
@return mixed | [
"Get",
"filename",
"to",
"use",
"for",
"this",
"config"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php#L228-L238 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/TinyMCECombinedGenerator.php | TinyMCECombinedGenerator.resolveRelativeResource | protected function resolveRelativeResource($base, $resource)
{
// Return resource path based on relative resource path
foreach (['', '.min.js', '.js'] as $ext) {
// Map resource
if ($base instanceof ModuleResource) {
$next = $base->getRelativeResource($resource . $ext);
} else {
$next = rtrim($base, '/') . '/' . $resource . $ext;
}
// Ensure resource exists
if ($this->resourceExists($next)) {
return $next;
}
}
return null;
} | php | protected function resolveRelativeResource($base, $resource)
{
// Return resource path based on relative resource path
foreach (['', '.min.js', '.js'] as $ext) {
// Map resource
if ($base instanceof ModuleResource) {
$next = $base->getRelativeResource($resource . $ext);
} else {
$next = rtrim($base, '/') . '/' . $resource . $ext;
}
// Ensure resource exists
if ($this->resourceExists($next)) {
return $next;
}
}
return null;
} | [
"protected",
"function",
"resolveRelativeResource",
"(",
"$",
"base",
",",
"$",
"resource",
")",
"{",
"// Return resource path based on relative resource path",
"foreach",
"(",
"[",
"''",
",",
"'.min.js'",
",",
"'.js'",
"]",
"as",
"$",
"ext",
")",
"{",
"// Map resource",
"if",
"(",
"$",
"base",
"instanceof",
"ModuleResource",
")",
"{",
"$",
"next",
"=",
"$",
"base",
"->",
"getRelativeResource",
"(",
"$",
"resource",
".",
"$",
"ext",
")",
";",
"}",
"else",
"{",
"$",
"next",
"=",
"rtrim",
"(",
"$",
"base",
",",
"'/'",
")",
".",
"'/'",
".",
"$",
"resource",
".",
"$",
"ext",
";",
"}",
"// Ensure resource exists",
"if",
"(",
"$",
"this",
"->",
"resourceExists",
"(",
"$",
"next",
")",
")",
"{",
"return",
"$",
"next",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Get relative resource for a given base and string
@param ModuleResource|string $base
@param string $resource
@return ModuleResource|string | [
"Get",
"relative",
"resource",
"for",
"a",
"given",
"base",
"and",
"string"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php#L260-L276 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/TinyMCECombinedGenerator.php | TinyMCECombinedGenerator.resourceExists | protected function resourceExists($resource)
{
if (!$resource) {
return false;
}
if ($resource instanceof ModuleResource) {
return $resource->exists();
}
$base = rtrim(Director::baseFolder(), '/');
return file_exists($base . '/' . $resource);
} | php | protected function resourceExists($resource)
{
if (!$resource) {
return false;
}
if ($resource instanceof ModuleResource) {
return $resource->exists();
}
$base = rtrim(Director::baseFolder(), '/');
return file_exists($base . '/' . $resource);
} | [
"protected",
"function",
"resourceExists",
"(",
"$",
"resource",
")",
"{",
"if",
"(",
"!",
"$",
"resource",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"resource",
"instanceof",
"ModuleResource",
")",
"{",
"return",
"$",
"resource",
"->",
"exists",
"(",
")",
";",
"}",
"$",
"base",
"=",
"rtrim",
"(",
"Director",
"::",
"baseFolder",
"(",
")",
",",
"'/'",
")",
";",
"return",
"file_exists",
"(",
"$",
"base",
".",
"'/'",
".",
"$",
"resource",
")",
";",
"}"
]
| Check if the given resource exists
@param string|ModuleResource $resource
@return bool | [
"Check",
"if",
"the",
"given",
"resource",
"exists"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCECombinedGenerator.php#L284-L294 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallRequirements.php | InstallRequirements.checkDatabase | public function checkDatabase($databaseConfig)
{
// Check if support is available
if (!$this->requireDatabaseFunctions(
$databaseConfig,
array(
"Database Configuration",
"Database support",
"Database support in PHP",
$this->getDatabaseTypeNice($databaseConfig['type'])
)
)
) {
return false;
}
$path = empty($databaseConfig['path']) ? null : $databaseConfig['path'];
$server = empty($databaseConfig['server']) ? null : $databaseConfig['server'];
// Check if the server is available
$usePath = $path && empty($server);
if (!$this->requireDatabaseServer(
$databaseConfig,
array(
"Database Configuration",
"Database server",
$usePath
? "I couldn't write to path '{$path}'"
: "I couldn't find a database server on '{$server}'",
$usePath
? $path
: $server
)
)
) {
return false;
}
// Check if the connection credentials allow access to the server / database
if (!$this->requireDatabaseConnection(
$databaseConfig,
array(
"Database Configuration",
"Database access credentials",
"That username/password doesn't work"
)
)
) {
return false;
}
// Check the necessary server version is available
if (!$this->requireDatabaseVersion(
$databaseConfig,
array(
"Database Configuration",
"Database server version requirement",
'',
'Version ' . $this->getDatabaseConfigurationHelper($databaseConfig['type'])->getDatabaseVersion($databaseConfig)
)
)
) {
return false;
}
// Check that database creation permissions are available
if (!$this->requireDatabaseOrCreatePermissions(
$databaseConfig,
array(
"Database Configuration",
"Can I access/create the database",
"I can't create new databases and the database '$databaseConfig[database]' doesn't exist"
)
)
) {
return false;
}
// Check alter permission (necessary to create tables etc)
if (!$this->requireDatabaseAlterPermissions(
$databaseConfig,
array(
"Database Configuration",
"Can I ALTER tables",
"I don't have permission to ALTER tables"
)
)
) {
return false;
}
// Success!
return true;
} | php | public function checkDatabase($databaseConfig)
{
// Check if support is available
if (!$this->requireDatabaseFunctions(
$databaseConfig,
array(
"Database Configuration",
"Database support",
"Database support in PHP",
$this->getDatabaseTypeNice($databaseConfig['type'])
)
)
) {
return false;
}
$path = empty($databaseConfig['path']) ? null : $databaseConfig['path'];
$server = empty($databaseConfig['server']) ? null : $databaseConfig['server'];
// Check if the server is available
$usePath = $path && empty($server);
if (!$this->requireDatabaseServer(
$databaseConfig,
array(
"Database Configuration",
"Database server",
$usePath
? "I couldn't write to path '{$path}'"
: "I couldn't find a database server on '{$server}'",
$usePath
? $path
: $server
)
)
) {
return false;
}
// Check if the connection credentials allow access to the server / database
if (!$this->requireDatabaseConnection(
$databaseConfig,
array(
"Database Configuration",
"Database access credentials",
"That username/password doesn't work"
)
)
) {
return false;
}
// Check the necessary server version is available
if (!$this->requireDatabaseVersion(
$databaseConfig,
array(
"Database Configuration",
"Database server version requirement",
'',
'Version ' . $this->getDatabaseConfigurationHelper($databaseConfig['type'])->getDatabaseVersion($databaseConfig)
)
)
) {
return false;
}
// Check that database creation permissions are available
if (!$this->requireDatabaseOrCreatePermissions(
$databaseConfig,
array(
"Database Configuration",
"Can I access/create the database",
"I can't create new databases and the database '$databaseConfig[database]' doesn't exist"
)
)
) {
return false;
}
// Check alter permission (necessary to create tables etc)
if (!$this->requireDatabaseAlterPermissions(
$databaseConfig,
array(
"Database Configuration",
"Can I ALTER tables",
"I don't have permission to ALTER tables"
)
)
) {
return false;
}
// Success!
return true;
} | [
"public",
"function",
"checkDatabase",
"(",
"$",
"databaseConfig",
")",
"{",
"// Check if support is available",
"if",
"(",
"!",
"$",
"this",
"->",
"requireDatabaseFunctions",
"(",
"$",
"databaseConfig",
",",
"array",
"(",
"\"Database Configuration\"",
",",
"\"Database support\"",
",",
"\"Database support in PHP\"",
",",
"$",
"this",
"->",
"getDatabaseTypeNice",
"(",
"$",
"databaseConfig",
"[",
"'type'",
"]",
")",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"path",
"=",
"empty",
"(",
"$",
"databaseConfig",
"[",
"'path'",
"]",
")",
"?",
"null",
":",
"$",
"databaseConfig",
"[",
"'path'",
"]",
";",
"$",
"server",
"=",
"empty",
"(",
"$",
"databaseConfig",
"[",
"'server'",
"]",
")",
"?",
"null",
":",
"$",
"databaseConfig",
"[",
"'server'",
"]",
";",
"// Check if the server is available",
"$",
"usePath",
"=",
"$",
"path",
"&&",
"empty",
"(",
"$",
"server",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"requireDatabaseServer",
"(",
"$",
"databaseConfig",
",",
"array",
"(",
"\"Database Configuration\"",
",",
"\"Database server\"",
",",
"$",
"usePath",
"?",
"\"I couldn't write to path '{$path}'\"",
":",
"\"I couldn't find a database server on '{$server}'\"",
",",
"$",
"usePath",
"?",
"$",
"path",
":",
"$",
"server",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Check if the connection credentials allow access to the server / database",
"if",
"(",
"!",
"$",
"this",
"->",
"requireDatabaseConnection",
"(",
"$",
"databaseConfig",
",",
"array",
"(",
"\"Database Configuration\"",
",",
"\"Database access credentials\"",
",",
"\"That username/password doesn't work\"",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Check the necessary server version is available",
"if",
"(",
"!",
"$",
"this",
"->",
"requireDatabaseVersion",
"(",
"$",
"databaseConfig",
",",
"array",
"(",
"\"Database Configuration\"",
",",
"\"Database server version requirement\"",
",",
"''",
",",
"'Version '",
".",
"$",
"this",
"->",
"getDatabaseConfigurationHelper",
"(",
"$",
"databaseConfig",
"[",
"'type'",
"]",
")",
"->",
"getDatabaseVersion",
"(",
"$",
"databaseConfig",
")",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Check that database creation permissions are available",
"if",
"(",
"!",
"$",
"this",
"->",
"requireDatabaseOrCreatePermissions",
"(",
"$",
"databaseConfig",
",",
"array",
"(",
"\"Database Configuration\"",
",",
"\"Can I access/create the database\"",
",",
"\"I can't create new databases and the database '$databaseConfig[database]' doesn't exist\"",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Check alter permission (necessary to create tables etc)",
"if",
"(",
"!",
"$",
"this",
"->",
"requireDatabaseAlterPermissions",
"(",
"$",
"databaseConfig",
",",
"array",
"(",
"\"Database Configuration\"",
",",
"\"Can I ALTER tables\"",
",",
"\"I don't have permission to ALTER tables\"",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Success!",
"return",
"true",
";",
"}"
]
| Check the database configuration. These are done one after another
starting with checking the database function exists in PHP, and
continuing onto more difficult checks like database permissions.
@param array $databaseConfig The list of database parameters
@return boolean Validity of database configuration details | [
"Check",
"the",
"database",
"configuration",
".",
"These",
"are",
"done",
"one",
"after",
"another",
"starting",
"with",
"checking",
"the",
"database",
"function",
"exists",
"in",
"PHP",
"and",
"continuing",
"onto",
"more",
"difficult",
"checks",
"like",
"database",
"permissions",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallRequirements.php#L66-L159 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallRequirements.php | InstallRequirements.getOriginalIni | protected function getOriginalIni($settingName)
{
if (isset($this->originalIni[$settingName])) {
return $this->originalIni[$settingName];
}
return ini_get($settingName);
} | php | protected function getOriginalIni($settingName)
{
if (isset($this->originalIni[$settingName])) {
return $this->originalIni[$settingName];
}
return ini_get($settingName);
} | [
"protected",
"function",
"getOriginalIni",
"(",
"$",
"settingName",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"originalIni",
"[",
"$",
"settingName",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"originalIni",
"[",
"$",
"settingName",
"]",
";",
"}",
"return",
"ini_get",
"(",
"$",
"settingName",
")",
";",
"}"
]
| Get ini setting
@param string $settingName
@return mixed | [
"Get",
"ini",
"setting"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallRequirements.php#L531-L537 | train |
silverstripe/silverstripe-framework | src/Dev/Install/InstallRequirements.php | InstallRequirements.requireNoClasses | public function requireNoClasses($classNames, $testDetails)
{
$this->testing($testDetails);
$badClasses = array();
foreach ($classNames as $className) {
if (class_exists($className)) {
$badClasses[] = $className;
}
}
if ($badClasses) {
$message = $testDetails[2] . ". The following classes are at fault: " . implode(', ', $badClasses);
$this->error($testDetails, $message);
return false;
}
return true;
} | php | public function requireNoClasses($classNames, $testDetails)
{
$this->testing($testDetails);
$badClasses = array();
foreach ($classNames as $className) {
if (class_exists($className)) {
$badClasses[] = $className;
}
}
if ($badClasses) {
$message = $testDetails[2] . ". The following classes are at fault: " . implode(', ', $badClasses);
$this->error($testDetails, $message);
return false;
}
return true;
} | [
"public",
"function",
"requireNoClasses",
"(",
"$",
"classNames",
",",
"$",
"testDetails",
")",
"{",
"$",
"this",
"->",
"testing",
"(",
"$",
"testDetails",
")",
";",
"$",
"badClasses",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"classNames",
"as",
"$",
"className",
")",
"{",
"if",
"(",
"class_exists",
"(",
"$",
"className",
")",
")",
"{",
"$",
"badClasses",
"[",
"]",
"=",
"$",
"className",
";",
"}",
"}",
"if",
"(",
"$",
"badClasses",
")",
"{",
"$",
"message",
"=",
"$",
"testDetails",
"[",
"2",
"]",
".",
"\". The following classes are at fault: \"",
".",
"implode",
"(",
"', '",
",",
"$",
"badClasses",
")",
";",
"$",
"this",
"->",
"error",
"(",
"$",
"testDetails",
",",
"$",
"message",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Require that the given class doesn't exist
@param array $classNames
@param array $testDetails
@return bool | [
"Require",
"that",
"the",
"given",
"class",
"doesn",
"t",
"exist"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/Install/InstallRequirements.php#L733-L748 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBDate.php | DBDate.DayOfMonth | public function DayOfMonth($includeOrdinal = false)
{
$number = $this->Format('d');
if ($includeOrdinal && $number) {
$formatter = NumberFormatter::create(i18n::get_locale(), NumberFormatter::ORDINAL);
return $formatter->format((int)$number);
}
return $number;
} | php | public function DayOfMonth($includeOrdinal = false)
{
$number = $this->Format('d');
if ($includeOrdinal && $number) {
$formatter = NumberFormatter::create(i18n::get_locale(), NumberFormatter::ORDINAL);
return $formatter->format((int)$number);
}
return $number;
} | [
"public",
"function",
"DayOfMonth",
"(",
"$",
"includeOrdinal",
"=",
"false",
")",
"{",
"$",
"number",
"=",
"$",
"this",
"->",
"Format",
"(",
"'d'",
")",
";",
"if",
"(",
"$",
"includeOrdinal",
"&&",
"$",
"number",
")",
"{",
"$",
"formatter",
"=",
"NumberFormatter",
"::",
"create",
"(",
"i18n",
"::",
"get_locale",
"(",
")",
",",
"NumberFormatter",
"::",
"ORDINAL",
")",
";",
"return",
"$",
"formatter",
"->",
"format",
"(",
"(",
"int",
")",
"$",
"number",
")",
";",
"}",
"return",
"$",
"number",
";",
"}"
]
| Returns the day of the month.
@param bool $includeOrdinal Include ordinal suffix to day, e.g. "th" or "rd"
@return string | [
"Returns",
"the",
"day",
"of",
"the",
"month",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L150-L158 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBDate.php | DBDate.Long | public function Long()
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter(IntlDateFormatter::LONG);
return $formatter->format($this->getTimestamp());
} | php | public function Long()
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter(IntlDateFormatter::LONG);
return $formatter->format($this->getTimestamp());
} | [
"public",
"function",
"Long",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"value",
")",
"{",
"return",
"null",
";",
"}",
"$",
"formatter",
"=",
"$",
"this",
"->",
"getFormatter",
"(",
"IntlDateFormatter",
"::",
"LONG",
")",
";",
"return",
"$",
"formatter",
"->",
"format",
"(",
"$",
"this",
"->",
"getTimestamp",
"(",
")",
")",
";",
"}"
]
| Returns the date in the localised long format
@return string | [
"Returns",
"the",
"date",
"in",
"the",
"localised",
"long",
"format"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L179-L186 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBDate.php | DBDate.Full | public function Full()
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter(IntlDateFormatter::FULL);
return $formatter->format($this->getTimestamp());
} | php | public function Full()
{
if (!$this->value) {
return null;
}
$formatter = $this->getFormatter(IntlDateFormatter::FULL);
return $formatter->format($this->getTimestamp());
} | [
"public",
"function",
"Full",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"value",
")",
"{",
"return",
"null",
";",
"}",
"$",
"formatter",
"=",
"$",
"this",
"->",
"getFormatter",
"(",
"IntlDateFormatter",
"::",
"FULL",
")",
";",
"return",
"$",
"formatter",
"->",
"format",
"(",
"$",
"this",
"->",
"getTimestamp",
"(",
")",
")",
";",
"}"
]
| Returns the date in the localised full format
@return string | [
"Returns",
"the",
"date",
"in",
"the",
"localised",
"full",
"format"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L193-L200 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.