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/Database.php | Database.previewWrite | protected function previewWrite($sql)
{
// Only preview if previewWrite is set, we are in dev mode, and
// the query is mutable
if (isset($_REQUEST['previewwrite'])
&& Director::isDev()
&& $this->connector->isQueryMutable($sql)
) {
// output preview message
Debug::message("Will execute: $sql");
return true;
} else {
return false;
}
} | php | protected function previewWrite($sql)
{
// Only preview if previewWrite is set, we are in dev mode, and
// the query is mutable
if (isset($_REQUEST['previewwrite'])
&& Director::isDev()
&& $this->connector->isQueryMutable($sql)
) {
// output preview message
Debug::message("Will execute: $sql");
return true;
} else {
return false;
}
} | [
"protected",
"function",
"previewWrite",
"(",
"$",
"sql",
")",
"{",
"// Only preview if previewWrite is set, we are in dev mode, and",
"// the query is mutable",
"if",
"(",
"isset",
"(",
"$",
"_REQUEST",
"[",
"'previewwrite'",
"]",
")",
"&&",
"Director",
"::",
"isDev",
"(",
")",
"&&",
"$",
"this",
"->",
"connector",
"->",
"isQueryMutable",
"(",
"$",
"sql",
")",
")",
"{",
"// output preview message",
"Debug",
"::",
"message",
"(",
"\"Will execute: $sql\"",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
]
| Determines if the query should be previewed, and thus interrupted silently.
If so, this function also displays the query via the debuging system.
Subclasess should respect the results of this call for each query, and not
execute any queries that generate a true response.
@param string $sql The query to be executed
@return boolean Flag indicating that the query was previewed | [
"Determines",
"if",
"the",
"query",
"should",
"be",
"previewed",
"and",
"thus",
"interrupted",
"silently",
".",
"If",
"so",
"this",
"function",
"also",
"displays",
"the",
"query",
"via",
"the",
"debuging",
"system",
".",
"Subclasess",
"should",
"respect",
"the",
"results",
"of",
"this",
"call",
"for",
"each",
"query",
"and",
"not",
"execute",
"any",
"queries",
"that",
"generate",
"a",
"true",
"response",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L184-L198 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Database.php | Database.benchmarkQuery | protected function benchmarkQuery($sql, $callback, $parameters = array())
{
if (isset($_REQUEST['showqueries']) && Director::isDev()) {
$this->queryCount++;
$starttime = microtime(true);
$result = $callback($sql);
$endtime = round(microtime(true) - $starttime, 4);
// replace parameters as closely as possible to what we'd expect the DB to put in
if (in_array(strtolower($_REQUEST['showqueries']), ['inline', 'backtrace'])) {
$sql = DB::inline_parameters($sql, $parameters);
}
$queryCount = sprintf("%04d", $this->queryCount);
Debug::message("\n$queryCount: $sql\n{$endtime}s\n", false);
// Show a backtrace if ?showqueries=backtrace
if ($_REQUEST['showqueries'] === 'backtrace') {
Backtrace::backtrace();
}
return $result;
} else {
return $callback($sql);
}
} | php | protected function benchmarkQuery($sql, $callback, $parameters = array())
{
if (isset($_REQUEST['showqueries']) && Director::isDev()) {
$this->queryCount++;
$starttime = microtime(true);
$result = $callback($sql);
$endtime = round(microtime(true) - $starttime, 4);
// replace parameters as closely as possible to what we'd expect the DB to put in
if (in_array(strtolower($_REQUEST['showqueries']), ['inline', 'backtrace'])) {
$sql = DB::inline_parameters($sql, $parameters);
}
$queryCount = sprintf("%04d", $this->queryCount);
Debug::message("\n$queryCount: $sql\n{$endtime}s\n", false);
// Show a backtrace if ?showqueries=backtrace
if ($_REQUEST['showqueries'] === 'backtrace') {
Backtrace::backtrace();
}
return $result;
} else {
return $callback($sql);
}
} | [
"protected",
"function",
"benchmarkQuery",
"(",
"$",
"sql",
",",
"$",
"callback",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_REQUEST",
"[",
"'showqueries'",
"]",
")",
"&&",
"Director",
"::",
"isDev",
"(",
")",
")",
"{",
"$",
"this",
"->",
"queryCount",
"++",
";",
"$",
"starttime",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"result",
"=",
"$",
"callback",
"(",
"$",
"sql",
")",
";",
"$",
"endtime",
"=",
"round",
"(",
"microtime",
"(",
"true",
")",
"-",
"$",
"starttime",
",",
"4",
")",
";",
"// replace parameters as closely as possible to what we'd expect the DB to put in",
"if",
"(",
"in_array",
"(",
"strtolower",
"(",
"$",
"_REQUEST",
"[",
"'showqueries'",
"]",
")",
",",
"[",
"'inline'",
",",
"'backtrace'",
"]",
")",
")",
"{",
"$",
"sql",
"=",
"DB",
"::",
"inline_parameters",
"(",
"$",
"sql",
",",
"$",
"parameters",
")",
";",
"}",
"$",
"queryCount",
"=",
"sprintf",
"(",
"\"%04d\"",
",",
"$",
"this",
"->",
"queryCount",
")",
";",
"Debug",
"::",
"message",
"(",
"\"\\n$queryCount: $sql\\n{$endtime}s\\n\"",
",",
"false",
")",
";",
"// Show a backtrace if ?showqueries=backtrace",
"if",
"(",
"$",
"_REQUEST",
"[",
"'showqueries'",
"]",
"===",
"'backtrace'",
")",
"{",
"Backtrace",
"::",
"backtrace",
"(",
")",
";",
"}",
"return",
"$",
"result",
";",
"}",
"else",
"{",
"return",
"$",
"callback",
"(",
"$",
"sql",
")",
";",
"}",
"}"
]
| Allows the display and benchmarking of queries as they are being run
@param string $sql Query to run, and single parameter to callback
@param callable $callback Callback to execute code
@param array $parameters Parameters for any parameterised query
@return mixed Result of query | [
"Allows",
"the",
"display",
"and",
"benchmarking",
"of",
"queries",
"as",
"they",
"are",
"being",
"run"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L208-L230 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Database.php | Database.escapeColumnKeys | protected function escapeColumnKeys($fieldValues)
{
$out = array();
foreach ($fieldValues as $field => $value) {
$out[$this->escapeIdentifier($field)] = $value;
}
return $out;
} | php | protected function escapeColumnKeys($fieldValues)
{
$out = array();
foreach ($fieldValues as $field => $value) {
$out[$this->escapeIdentifier($field)] = $value;
}
return $out;
} | [
"protected",
"function",
"escapeColumnKeys",
"(",
"$",
"fieldValues",
")",
"{",
"$",
"out",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"fieldValues",
"as",
"$",
"field",
"=>",
"$",
"value",
")",
"{",
"$",
"out",
"[",
"$",
"this",
"->",
"escapeIdentifier",
"(",
"$",
"field",
")",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"out",
";",
"}"
]
| Escapes unquoted columns keys in an associative array
@param array $fieldValues
@return array List of field values with the keys as escaped column names | [
"Escapes",
"unquoted",
"columns",
"keys",
"in",
"an",
"associative",
"array"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L303-L310 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Database.php | Database.clearAllData | public function clearAllData()
{
$tables = $this->getSchemaManager()->tableList();
foreach ($tables as $table) {
$this->clearTable($table);
}
} | php | public function clearAllData()
{
$tables = $this->getSchemaManager()->tableList();
foreach ($tables as $table) {
$this->clearTable($table);
}
} | [
"public",
"function",
"clearAllData",
"(",
")",
"{",
"$",
"tables",
"=",
"$",
"this",
"->",
"getSchemaManager",
"(",
")",
"->",
"tableList",
"(",
")",
";",
"foreach",
"(",
"$",
"tables",
"as",
"$",
"table",
")",
"{",
"$",
"this",
"->",
"clearTable",
"(",
"$",
"table",
")",
";",
"}",
"}"
]
| Clear all data out of the database | [
"Clear",
"all",
"data",
"out",
"of",
"the",
"database"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L391-L397 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Database.php | Database.connect | public function connect($parameters)
{
// Ensure that driver is available (required by PDO)
if (empty($parameters['driver'])) {
$parameters['driver'] = $this->getDatabaseServer();
}
// Notify connector of parameters
$this->connector->connect($parameters);
// SS_Database subclass maintains responsibility for selecting database
// once connected in order to correctly handle schema queries about
// existence of database, error handling at the correct level, etc
if (!empty($parameters['database'])) {
$this->selectDatabase($parameters['database'], false, false);
}
} | php | public function connect($parameters)
{
// Ensure that driver is available (required by PDO)
if (empty($parameters['driver'])) {
$parameters['driver'] = $this->getDatabaseServer();
}
// Notify connector of parameters
$this->connector->connect($parameters);
// SS_Database subclass maintains responsibility for selecting database
// once connected in order to correctly handle schema queries about
// existence of database, error handling at the correct level, etc
if (!empty($parameters['database'])) {
$this->selectDatabase($parameters['database'], false, false);
}
} | [
"public",
"function",
"connect",
"(",
"$",
"parameters",
")",
"{",
"// Ensure that driver is available (required by PDO)",
"if",
"(",
"empty",
"(",
"$",
"parameters",
"[",
"'driver'",
"]",
")",
")",
"{",
"$",
"parameters",
"[",
"'driver'",
"]",
"=",
"$",
"this",
"->",
"getDatabaseServer",
"(",
")",
";",
"}",
"// Notify connector of parameters",
"$",
"this",
"->",
"connector",
"->",
"connect",
"(",
"$",
"parameters",
")",
";",
"// SS_Database subclass maintains responsibility for selecting database",
"// once connected in order to correctly handle schema queries about",
"// existence of database, error handling at the correct level, etc",
"if",
"(",
"!",
"empty",
"(",
"$",
"parameters",
"[",
"'database'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"selectDatabase",
"(",
"$",
"parameters",
"[",
"'database'",
"]",
",",
"false",
",",
"false",
")",
";",
"}",
"}"
]
| Instruct the database to generate a live connection
@param array $parameters An map of parameters, which should include:
- server: The server, eg, localhost
- username: The username to log on with
- password: The password to log on with
- database: The database to connect to
- charset: The character set to use. Defaults to utf8
- timezone: (optional) The timezone offset. For example: +12:00, "Pacific/Auckland", or "SYSTEM"
- driver: (optional) Driver name | [
"Instruct",
"the",
"database",
"to",
"generate",
"a",
"live",
"connection"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L772-L788 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Database.php | Database.selectDatabase | public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR)
{
// In case our live environment is locked down, we can bypass a SHOW DATABASE check
$canConnect = Config::inst()->get(static::class, 'optimistic_connect')
|| $this->schemaManager->databaseExists($name);
if ($canConnect) {
return $this->connector->selectDatabase($name);
}
// Check DB creation permisson
if (!$create) {
if ($errorLevel !== false) {
user_error("Attempted to connect to non-existing database \"$name\"", $errorLevel);
}
// Unselect database
$this->connector->unloadDatabase();
return false;
}
$this->schemaManager->createDatabase($name);
return $this->connector->selectDatabase($name);
} | php | public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR)
{
// In case our live environment is locked down, we can bypass a SHOW DATABASE check
$canConnect = Config::inst()->get(static::class, 'optimistic_connect')
|| $this->schemaManager->databaseExists($name);
if ($canConnect) {
return $this->connector->selectDatabase($name);
}
// Check DB creation permisson
if (!$create) {
if ($errorLevel !== false) {
user_error("Attempted to connect to non-existing database \"$name\"", $errorLevel);
}
// Unselect database
$this->connector->unloadDatabase();
return false;
}
$this->schemaManager->createDatabase($name);
return $this->connector->selectDatabase($name);
} | [
"public",
"function",
"selectDatabase",
"(",
"$",
"name",
",",
"$",
"create",
"=",
"false",
",",
"$",
"errorLevel",
"=",
"E_USER_ERROR",
")",
"{",
"// In case our live environment is locked down, we can bypass a SHOW DATABASE check",
"$",
"canConnect",
"=",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"static",
"::",
"class",
",",
"'optimistic_connect'",
")",
"||",
"$",
"this",
"->",
"schemaManager",
"->",
"databaseExists",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"canConnect",
")",
"{",
"return",
"$",
"this",
"->",
"connector",
"->",
"selectDatabase",
"(",
"$",
"name",
")",
";",
"}",
"// Check DB creation permisson",
"if",
"(",
"!",
"$",
"create",
")",
"{",
"if",
"(",
"$",
"errorLevel",
"!==",
"false",
")",
"{",
"user_error",
"(",
"\"Attempted to connect to non-existing database \\\"$name\\\"\"",
",",
"$",
"errorLevel",
")",
";",
"}",
"// Unselect database",
"$",
"this",
"->",
"connector",
"->",
"unloadDatabase",
"(",
")",
";",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"schemaManager",
"->",
"createDatabase",
"(",
"$",
"name",
")",
";",
"return",
"$",
"this",
"->",
"connector",
"->",
"selectDatabase",
"(",
"$",
"name",
")",
";",
"}"
]
| Change the connection to the specified database, optionally creating the
database if it doesn't exist in the current schema.
@param string $name Name of the database
@param bool $create Flag indicating whether the database should be created
if it doesn't exist. If $create is false and the database doesn't exist
then an error will be raised
@param int|bool $errorLevel The level of error reporting to enable for the query, or false if no error
should be raised
@return bool Flag indicating success | [
"Change",
"the",
"connection",
"to",
"the",
"specified",
"database",
"optionally",
"creating",
"the",
"database",
"if",
"it",
"doesn",
"t",
"exist",
"in",
"the",
"current",
"schema",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L823-L843 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/Database.php | Database.dropSelectedDatabase | public function dropSelectedDatabase()
{
$databaseName = $this->connector->getSelectedDatabase();
if ($databaseName) {
$this->connector->unloadDatabase();
$this->schemaManager->dropDatabase($databaseName);
}
} | php | public function dropSelectedDatabase()
{
$databaseName = $this->connector->getSelectedDatabase();
if ($databaseName) {
$this->connector->unloadDatabase();
$this->schemaManager->dropDatabase($databaseName);
}
} | [
"public",
"function",
"dropSelectedDatabase",
"(",
")",
"{",
"$",
"databaseName",
"=",
"$",
"this",
"->",
"connector",
"->",
"getSelectedDatabase",
"(",
")",
";",
"if",
"(",
"$",
"databaseName",
")",
"{",
"$",
"this",
"->",
"connector",
"->",
"unloadDatabase",
"(",
")",
";",
"$",
"this",
"->",
"schemaManager",
"->",
"dropDatabase",
"(",
"$",
"databaseName",
")",
";",
"}",
"}"
]
| Drop the database that this object is currently connected to.
Use with caution. | [
"Drop",
"the",
"database",
"that",
"this",
"object",
"is",
"currently",
"connected",
"to",
".",
"Use",
"with",
"caution",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/Database.php#L849-L856 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/CanonicalURLMiddleware.php | CanonicalURLMiddleware.getRedirect | protected function getRedirect(HTTPRequest $request)
{
// Check global disable
if (!$this->isEnabled()) {
return null;
}
// Get properties of current request
$host = $request->getHost();
$scheme = $request->getScheme();
// Check https
if ($this->requiresSSL($request)) {
$scheme = 'https';
// Promote ssl domain if configured
$host = $this->getForceSSLDomain() ?: $host;
}
// Check www.
if ($this->getForceWWW() && strpos($host, 'www.') !== 0) {
$host = "www.{$host}";
}
// No-op if no changes
if ($request->getScheme() === $scheme && $request->getHost() === $host) {
return null;
}
return $this->redirectToScheme($request, $scheme, $host);
} | php | protected function getRedirect(HTTPRequest $request)
{
// Check global disable
if (!$this->isEnabled()) {
return null;
}
// Get properties of current request
$host = $request->getHost();
$scheme = $request->getScheme();
// Check https
if ($this->requiresSSL($request)) {
$scheme = 'https';
// Promote ssl domain if configured
$host = $this->getForceSSLDomain() ?: $host;
}
// Check www.
if ($this->getForceWWW() && strpos($host, 'www.') !== 0) {
$host = "www.{$host}";
}
// No-op if no changes
if ($request->getScheme() === $scheme && $request->getHost() === $host) {
return null;
}
return $this->redirectToScheme($request, $scheme, $host);
} | [
"protected",
"function",
"getRedirect",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"// Check global disable",
"if",
"(",
"!",
"$",
"this",
"->",
"isEnabled",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Get properties of current request",
"$",
"host",
"=",
"$",
"request",
"->",
"getHost",
"(",
")",
";",
"$",
"scheme",
"=",
"$",
"request",
"->",
"getScheme",
"(",
")",
";",
"// Check https",
"if",
"(",
"$",
"this",
"->",
"requiresSSL",
"(",
"$",
"request",
")",
")",
"{",
"$",
"scheme",
"=",
"'https'",
";",
"// Promote ssl domain if configured",
"$",
"host",
"=",
"$",
"this",
"->",
"getForceSSLDomain",
"(",
")",
"?",
":",
"$",
"host",
";",
"}",
"// Check www.",
"if",
"(",
"$",
"this",
"->",
"getForceWWW",
"(",
")",
"&&",
"strpos",
"(",
"$",
"host",
",",
"'www.'",
")",
"!==",
"0",
")",
"{",
"$",
"host",
"=",
"\"www.{$host}\"",
";",
"}",
"// No-op if no changes",
"if",
"(",
"$",
"request",
"->",
"getScheme",
"(",
")",
"===",
"$",
"scheme",
"&&",
"$",
"request",
"->",
"getHost",
"(",
")",
"===",
"$",
"host",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"redirectToScheme",
"(",
"$",
"request",
",",
"$",
"scheme",
",",
"$",
"host",
")",
";",
"}"
]
| Given request object determine if we should redirect.
@param HTTPRequest $request Pre-validated request object
@return HTTPResponse|null If a redirect is needed return the response | [
"Given",
"request",
"object",
"determine",
"if",
"we",
"should",
"redirect",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/CanonicalURLMiddleware.php#L205-L235 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/CanonicalURLMiddleware.php | CanonicalURLMiddleware.throwRedirectIfNeeded | public function throwRedirectIfNeeded(HTTPRequest $request = null)
{
$request = $this->getOrValidateRequest($request);
if (!$request) {
return;
}
$response = $this->getRedirect($request);
if ($response) {
throw new HTTPResponse_Exception($response);
}
} | php | public function throwRedirectIfNeeded(HTTPRequest $request = null)
{
$request = $this->getOrValidateRequest($request);
if (!$request) {
return;
}
$response = $this->getRedirect($request);
if ($response) {
throw new HTTPResponse_Exception($response);
}
} | [
"public",
"function",
"throwRedirectIfNeeded",
"(",
"HTTPRequest",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"getOrValidateRequest",
"(",
"$",
"request",
")",
";",
"if",
"(",
"!",
"$",
"request",
")",
"{",
"return",
";",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"getRedirect",
"(",
"$",
"request",
")",
";",
"if",
"(",
"$",
"response",
")",
"{",
"throw",
"new",
"HTTPResponse_Exception",
"(",
"$",
"response",
")",
";",
"}",
"}"
]
| Handles redirection to canonical urls outside of the main middleware chain
using HTTPResponseException.
Will not do anything if a current HTTPRequest isn't available
@param HTTPRequest|null $request Allow HTTPRequest to be used for the base comparison
@throws HTTPResponse_Exception | [
"Handles",
"redirection",
"to",
"canonical",
"urls",
"outside",
"of",
"the",
"main",
"middleware",
"chain",
"using",
"HTTPResponseException",
".",
"Will",
"not",
"do",
"anything",
"if",
"a",
"current",
"HTTPRequest",
"isn",
"t",
"available"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/CanonicalURLMiddleware.php#L245-L255 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/CanonicalURLMiddleware.php | CanonicalURLMiddleware.getOrValidateRequest | protected function getOrValidateRequest(HTTPRequest $request = null)
{
if ($request instanceof HTTPRequest) {
return $request;
}
if (Injector::inst()->has(HTTPRequest::class)) {
return Injector::inst()->get(HTTPRequest::class);
}
return null;
} | php | protected function getOrValidateRequest(HTTPRequest $request = null)
{
if ($request instanceof HTTPRequest) {
return $request;
}
if (Injector::inst()->has(HTTPRequest::class)) {
return Injector::inst()->get(HTTPRequest::class);
}
return null;
} | [
"protected",
"function",
"getOrValidateRequest",
"(",
"HTTPRequest",
"$",
"request",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"request",
"instanceof",
"HTTPRequest",
")",
"{",
"return",
"$",
"request",
";",
"}",
"if",
"(",
"Injector",
"::",
"inst",
"(",
")",
"->",
"has",
"(",
"HTTPRequest",
"::",
"class",
")",
")",
"{",
"return",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"HTTPRequest",
"::",
"class",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Return a valid request, if one is available, or null if none is available
@param HTTPRequest $request
@return HTTPRequest|null | [
"Return",
"a",
"valid",
"request",
"if",
"one",
"is",
"available",
"or",
"null",
"if",
"none",
"is",
"available"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/CanonicalURLMiddleware.php#L263-L272 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/CanonicalURLMiddleware.php | CanonicalURLMiddleware.requiresSSL | protected function requiresSSL(HTTPRequest $request)
{
// Check if force SSL is enabled
if (!$this->getForceSSL()) {
return false;
}
// Already on SSL
if ($request->getScheme() === 'https') {
return false;
}
// Veto if any existing patterns fail
$patterns = $this->getForceSSLPatterns();
if (!$patterns) {
return true;
}
// Filter redirect based on url
$relativeURL = $request->getURL(true);
foreach ($patterns as $pattern) {
if (preg_match($pattern, $relativeURL)) {
return true;
}
}
// No patterns match
return false;
} | php | protected function requiresSSL(HTTPRequest $request)
{
// Check if force SSL is enabled
if (!$this->getForceSSL()) {
return false;
}
// Already on SSL
if ($request->getScheme() === 'https') {
return false;
}
// Veto if any existing patterns fail
$patterns = $this->getForceSSLPatterns();
if (!$patterns) {
return true;
}
// Filter redirect based on url
$relativeURL = $request->getURL(true);
foreach ($patterns as $pattern) {
if (preg_match($pattern, $relativeURL)) {
return true;
}
}
// No patterns match
return false;
} | [
"protected",
"function",
"requiresSSL",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"// Check if force SSL is enabled",
"if",
"(",
"!",
"$",
"this",
"->",
"getForceSSL",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Already on SSL",
"if",
"(",
"$",
"request",
"->",
"getScheme",
"(",
")",
"===",
"'https'",
")",
"{",
"return",
"false",
";",
"}",
"// Veto if any existing patterns fail",
"$",
"patterns",
"=",
"$",
"this",
"->",
"getForceSSLPatterns",
"(",
")",
";",
"if",
"(",
"!",
"$",
"patterns",
")",
"{",
"return",
"true",
";",
"}",
"// Filter redirect based on url",
"$",
"relativeURL",
"=",
"$",
"request",
"->",
"getURL",
"(",
"true",
")",
";",
"foreach",
"(",
"$",
"patterns",
"as",
"$",
"pattern",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"relativeURL",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"// No patterns match",
"return",
"false",
";",
"}"
]
| Check if a redirect for SSL is necessary
@param HTTPRequest $request
@return bool | [
"Check",
"if",
"a",
"redirect",
"for",
"SSL",
"is",
"necessary"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/CanonicalURLMiddleware.php#L280-L308 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/CanonicalURLMiddleware.php | CanonicalURLMiddleware.isEnabled | protected function isEnabled()
{
// At least one redirect must be enabled
if (!$this->getForceWWW() && !$this->getForceSSL()) {
return false;
}
// Filter by env vars
$enabledEnvs = $this->getEnabledEnvs();
if (is_bool($enabledEnvs)) {
return $enabledEnvs;
}
// If CLI, EnabledEnvs must contain CLI
if (Director::is_cli() && !in_array('cli', $enabledEnvs)) {
return false;
}
// Check other envs
return empty($enabledEnvs) || in_array(Director::get_environment_type(), $enabledEnvs);
} | php | protected function isEnabled()
{
// At least one redirect must be enabled
if (!$this->getForceWWW() && !$this->getForceSSL()) {
return false;
}
// Filter by env vars
$enabledEnvs = $this->getEnabledEnvs();
if (is_bool($enabledEnvs)) {
return $enabledEnvs;
}
// If CLI, EnabledEnvs must contain CLI
if (Director::is_cli() && !in_array('cli', $enabledEnvs)) {
return false;
}
// Check other envs
return empty($enabledEnvs) || in_array(Director::get_environment_type(), $enabledEnvs);
} | [
"protected",
"function",
"isEnabled",
"(",
")",
"{",
"// At least one redirect must be enabled",
"if",
"(",
"!",
"$",
"this",
"->",
"getForceWWW",
"(",
")",
"&&",
"!",
"$",
"this",
"->",
"getForceSSL",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Filter by env vars",
"$",
"enabledEnvs",
"=",
"$",
"this",
"->",
"getEnabledEnvs",
"(",
")",
";",
"if",
"(",
"is_bool",
"(",
"$",
"enabledEnvs",
")",
")",
"{",
"return",
"$",
"enabledEnvs",
";",
"}",
"// If CLI, EnabledEnvs must contain CLI",
"if",
"(",
"Director",
"::",
"is_cli",
"(",
")",
"&&",
"!",
"in_array",
"(",
"'cli'",
",",
"$",
"enabledEnvs",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Check other envs",
"return",
"empty",
"(",
"$",
"enabledEnvs",
")",
"||",
"in_array",
"(",
"Director",
"::",
"get_environment_type",
"(",
")",
",",
"$",
"enabledEnvs",
")",
";",
"}"
]
| Ensure this middleware is enabled | [
"Ensure",
"this",
"middleware",
"is",
"enabled"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/CanonicalURLMiddleware.php#L355-L375 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/CanonicalURLMiddleware.php | CanonicalURLMiddleware.hasBasicAuthPrompt | protected function hasBasicAuthPrompt(HTTPResponse $response = null)
{
if (!$response) {
return false;
}
return ($response->getStatusCode() === 401 && $response->getHeader('WWW-Authenticate'));
} | php | protected function hasBasicAuthPrompt(HTTPResponse $response = null)
{
if (!$response) {
return false;
}
return ($response->getStatusCode() === 401 && $response->getHeader('WWW-Authenticate'));
} | [
"protected",
"function",
"hasBasicAuthPrompt",
"(",
"HTTPResponse",
"$",
"response",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"response",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"===",
"401",
"&&",
"$",
"response",
"->",
"getHeader",
"(",
"'WWW-Authenticate'",
")",
")",
";",
"}"
]
| Determine whether the executed middlewares have added a basic authentication prompt
@param HTTPResponse $response
@return bool | [
"Determine",
"whether",
"the",
"executed",
"middlewares",
"have",
"added",
"a",
"basic",
"authentication",
"prompt"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/CanonicalURLMiddleware.php#L383-L389 | train |
silverstripe/silverstripe-framework | src/Control/Middleware/CanonicalURLMiddleware.php | CanonicalURLMiddleware.redirectToScheme | protected function redirectToScheme(HTTPRequest $request, $scheme, $host = null)
{
if (!$host) {
$host = $request->getHost();
}
$url = Controller::join_links("{$scheme}://{$host}", Director::baseURL(), $request->getURL(true));
// Force redirect
$response = HTTPResponse::create();
$response->redirect($url, $this->getRedirectType());
return $response;
} | php | protected function redirectToScheme(HTTPRequest $request, $scheme, $host = null)
{
if (!$host) {
$host = $request->getHost();
}
$url = Controller::join_links("{$scheme}://{$host}", Director::baseURL(), $request->getURL(true));
// Force redirect
$response = HTTPResponse::create();
$response->redirect($url, $this->getRedirectType());
return $response;
} | [
"protected",
"function",
"redirectToScheme",
"(",
"HTTPRequest",
"$",
"request",
",",
"$",
"scheme",
",",
"$",
"host",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"host",
")",
"{",
"$",
"host",
"=",
"$",
"request",
"->",
"getHost",
"(",
")",
";",
"}",
"$",
"url",
"=",
"Controller",
"::",
"join_links",
"(",
"\"{$scheme}://{$host}\"",
",",
"Director",
"::",
"baseURL",
"(",
")",
",",
"$",
"request",
"->",
"getURL",
"(",
"true",
")",
")",
";",
"// Force redirect",
"$",
"response",
"=",
"HTTPResponse",
"::",
"create",
"(",
")",
";",
"$",
"response",
"->",
"redirect",
"(",
"$",
"url",
",",
"$",
"this",
"->",
"getRedirectType",
"(",
")",
")",
";",
"return",
"$",
"response",
";",
"}"
]
| Redirect the current URL to the specified HTTP scheme
@param HTTPRequest $request
@param string $scheme
@param string $host
@return HTTPResponse | [
"Redirect",
"the",
"current",
"URL",
"to",
"the",
"specified",
"HTTP",
"scheme"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/CanonicalURLMiddleware.php#L399-L412 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/HTMLEditorSanitiser.php | HTMLEditorSanitiser.getRuleForElement | protected function getRuleForElement($tag)
{
if (isset($this->elements[$tag])) {
return $this->elements[$tag];
}
foreach ($this->elementPatterns as $element) {
if (preg_match($element->pattern, $tag)) {
return $element;
}
}
return null;
} | php | protected function getRuleForElement($tag)
{
if (isset($this->elements[$tag])) {
return $this->elements[$tag];
}
foreach ($this->elementPatterns as $element) {
if (preg_match($element->pattern, $tag)) {
return $element;
}
}
return null;
} | [
"protected",
"function",
"getRuleForElement",
"(",
"$",
"tag",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"tag",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"elements",
"[",
"$",
"tag",
"]",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"elementPatterns",
"as",
"$",
"element",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"element",
"->",
"pattern",
",",
"$",
"tag",
")",
")",
"{",
"return",
"$",
"element",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Given an element tag, return the rule structure for that element
@param string $tag The element tag
@return stdClass The element rule | [
"Given",
"an",
"element",
"tag",
"return",
"the",
"rule",
"structure",
"for",
"that",
"element"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/HTMLEditorSanitiser.php#L175-L186 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/HTMLEditorSanitiser.php | HTMLEditorSanitiser.getRuleForAttribute | protected function getRuleForAttribute($elementRule, $name)
{
if (isset($elementRule->attributes[$name])) {
return $elementRule->attributes[$name];
}
foreach ($elementRule->attributePatterns as $attribute) {
if (preg_match($attribute->pattern, $name)) {
return $attribute;
}
}
return null;
} | php | protected function getRuleForAttribute($elementRule, $name)
{
if (isset($elementRule->attributes[$name])) {
return $elementRule->attributes[$name];
}
foreach ($elementRule->attributePatterns as $attribute) {
if (preg_match($attribute->pattern, $name)) {
return $attribute;
}
}
return null;
} | [
"protected",
"function",
"getRuleForAttribute",
"(",
"$",
"elementRule",
",",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"elementRule",
"->",
"attributes",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"elementRule",
"->",
"attributes",
"[",
"$",
"name",
"]",
";",
"}",
"foreach",
"(",
"$",
"elementRule",
"->",
"attributePatterns",
"as",
"$",
"attribute",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"attribute",
"->",
"pattern",
",",
"$",
"name",
")",
")",
"{",
"return",
"$",
"attribute",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Given an attribute name, return the rule structure for that attribute
@param object $elementRule
@param string $name The attribute name
@return stdClass The attribute rule | [
"Given",
"an",
"attribute",
"name",
"return",
"the",
"rule",
"structure",
"for",
"that",
"attribute"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/HTMLEditorSanitiser.php#L195-L206 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/HTMLEditorSanitiser.php | HTMLEditorSanitiser.elementMatchesRule | protected function elementMatchesRule($element, $rule = null)
{
// If the rule doesn't exist at all, the element isn't allowed
if (!$rule) {
return false;
}
// If the rule has attributes required, check them to see if this element has at least one
if ($rule->attributesRequired) {
$hasMatch = false;
foreach ($rule->attributesRequired as $attr) {
if ($element->getAttribute($attr)) {
$hasMatch = true;
break;
}
}
if (!$hasMatch) {
return false;
}
}
// If the rule says to remove empty elements, and this element is empty, remove it
if ($rule->removeEmpty && !$element->firstChild) {
return false;
}
// No further tests required, element passes
return true;
} | php | protected function elementMatchesRule($element, $rule = null)
{
// If the rule doesn't exist at all, the element isn't allowed
if (!$rule) {
return false;
}
// If the rule has attributes required, check them to see if this element has at least one
if ($rule->attributesRequired) {
$hasMatch = false;
foreach ($rule->attributesRequired as $attr) {
if ($element->getAttribute($attr)) {
$hasMatch = true;
break;
}
}
if (!$hasMatch) {
return false;
}
}
// If the rule says to remove empty elements, and this element is empty, remove it
if ($rule->removeEmpty && !$element->firstChild) {
return false;
}
// No further tests required, element passes
return true;
} | [
"protected",
"function",
"elementMatchesRule",
"(",
"$",
"element",
",",
"$",
"rule",
"=",
"null",
")",
"{",
"// If the rule doesn't exist at all, the element isn't allowed",
"if",
"(",
"!",
"$",
"rule",
")",
"{",
"return",
"false",
";",
"}",
"// If the rule has attributes required, check them to see if this element has at least one",
"if",
"(",
"$",
"rule",
"->",
"attributesRequired",
")",
"{",
"$",
"hasMatch",
"=",
"false",
";",
"foreach",
"(",
"$",
"rule",
"->",
"attributesRequired",
"as",
"$",
"attr",
")",
"{",
"if",
"(",
"$",
"element",
"->",
"getAttribute",
"(",
"$",
"attr",
")",
")",
"{",
"$",
"hasMatch",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"$",
"hasMatch",
")",
"{",
"return",
"false",
";",
"}",
"}",
"// If the rule says to remove empty elements, and this element is empty, remove it",
"if",
"(",
"$",
"rule",
"->",
"removeEmpty",
"&&",
"!",
"$",
"element",
"->",
"firstChild",
")",
"{",
"return",
"false",
";",
"}",
"// No further tests required, element passes",
"return",
"true",
";",
"}"
]
| Given a DOMElement and an element rule, check if that element passes the rule
@param DOMElement $element The element to check
@param stdClass $rule The rule to check against
@return bool True if the element passes (and so can be kept), false if it fails (and so needs stripping) | [
"Given",
"a",
"DOMElement",
"and",
"an",
"element",
"rule",
"check",
"if",
"that",
"element",
"passes",
"the",
"rule"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/HTMLEditorSanitiser.php#L214-L244 | train |
silverstripe/silverstripe-framework | src/Forms/HTMLEditor/HTMLEditorSanitiser.php | HTMLEditorSanitiser.attributeMatchesRule | protected function attributeMatchesRule($attr, $rule = null)
{
// If the rule doesn't exist at all, the attribute isn't allowed
if (!$rule) {
return false;
}
// If the rule has a set of valid values, check them to see if this attribute is one
if (isset($rule->validValues) && !in_array($attr->value, $rule->validValues)) {
return false;
}
// No further tests required, attribute passes
return true;
} | php | protected function attributeMatchesRule($attr, $rule = null)
{
// If the rule doesn't exist at all, the attribute isn't allowed
if (!$rule) {
return false;
}
// If the rule has a set of valid values, check them to see if this attribute is one
if (isset($rule->validValues) && !in_array($attr->value, $rule->validValues)) {
return false;
}
// No further tests required, attribute passes
return true;
} | [
"protected",
"function",
"attributeMatchesRule",
"(",
"$",
"attr",
",",
"$",
"rule",
"=",
"null",
")",
"{",
"// If the rule doesn't exist at all, the attribute isn't allowed",
"if",
"(",
"!",
"$",
"rule",
")",
"{",
"return",
"false",
";",
"}",
"// If the rule has a set of valid values, check them to see if this attribute is one",
"if",
"(",
"isset",
"(",
"$",
"rule",
"->",
"validValues",
")",
"&&",
"!",
"in_array",
"(",
"$",
"attr",
"->",
"value",
",",
"$",
"rule",
"->",
"validValues",
")",
")",
"{",
"return",
"false",
";",
"}",
"// No further tests required, attribute passes",
"return",
"true",
";",
"}"
]
| Given a DOMAttr and an attribute rule, check if that attribute passes the rule
@param DOMAttr $attr - the attribute to check
@param stdClass $rule - the rule to check against
@return bool - true if the attribute passes (and so can be kept), false if it fails (and so needs stripping) | [
"Given",
"a",
"DOMAttr",
"and",
"an",
"attribute",
"rule",
"check",
"if",
"that",
"attribute",
"passes",
"the",
"rule"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/HTMLEditorSanitiser.php#L252-L266 | train |
silverstripe/silverstripe-framework | src/Core/Manifest/ModuleResource.php | ModuleResource.getRelativePath | public function getRelativePath()
{
// Root module
$parent = $this->module->getRelativePath();
if (!$parent) {
return $this->relativePath;
}
return Path::join($parent, $this->relativePath);
} | php | public function getRelativePath()
{
// Root module
$parent = $this->module->getRelativePath();
if (!$parent) {
return $this->relativePath;
}
return Path::join($parent, $this->relativePath);
} | [
"public",
"function",
"getRelativePath",
"(",
")",
"{",
"// Root module",
"$",
"parent",
"=",
"$",
"this",
"->",
"module",
"->",
"getRelativePath",
"(",
")",
";",
"if",
"(",
"!",
"$",
"parent",
")",
"{",
"return",
"$",
"this",
"->",
"relativePath",
";",
"}",
"return",
"Path",
"::",
"join",
"(",
"$",
"parent",
",",
"$",
"this",
"->",
"relativePath",
")",
";",
"}"
]
| Get the path of this resource relative to the base path.
Note: In the case that this resource is mapped to the `_resources` folder, this will
return the original rather than the copy / symlink.
@return string Relative path (no leading /) | [
"Get",
"the",
"path",
"of",
"this",
"resource",
"relative",
"to",
"the",
"base",
"path",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ModuleResource.php#L70-L78 | train |
silverstripe/silverstripe-framework | src/Control/CookieJar.php | CookieJar.get | public function get($name, $includeUnsent = true)
{
$cookies = $includeUnsent ? $this->current : $this->existing;
if (isset($cookies[$name])) {
return $cookies[$name];
}
//Normalise cookie names by replacing '.' with '_'
$safeName = str_replace('.', '_', $name);
if (isset($cookies[$safeName])) {
return $cookies[$safeName];
}
return null;
} | php | public function get($name, $includeUnsent = true)
{
$cookies = $includeUnsent ? $this->current : $this->existing;
if (isset($cookies[$name])) {
return $cookies[$name];
}
//Normalise cookie names by replacing '.' with '_'
$safeName = str_replace('.', '_', $name);
if (isset($cookies[$safeName])) {
return $cookies[$safeName];
}
return null;
} | [
"public",
"function",
"get",
"(",
"$",
"name",
",",
"$",
"includeUnsent",
"=",
"true",
")",
"{",
"$",
"cookies",
"=",
"$",
"includeUnsent",
"?",
"$",
"this",
"->",
"current",
":",
"$",
"this",
"->",
"existing",
";",
"if",
"(",
"isset",
"(",
"$",
"cookies",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"cookies",
"[",
"$",
"name",
"]",
";",
"}",
"//Normalise cookie names by replacing '.' with '_'",
"$",
"safeName",
"=",
"str_replace",
"(",
"'.'",
",",
"'_'",
",",
"$",
"name",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"cookies",
"[",
"$",
"safeName",
"]",
")",
")",
"{",
"return",
"$",
"cookies",
"[",
"$",
"safeName",
"]",
";",
"}",
"return",
"null",
";",
"}"
]
| Get the cookie value by name
Cookie names are normalised to work around PHP's behaviour of replacing incoming variable name . with _
@param string $name The name of the cookie to get
@param boolean $includeUnsent Include cookies we've yet to send when fetching values
@return string|null The cookie value or null if unset | [
"Get",
"the",
"cookie",
"value",
"by",
"name"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/CookieJar.php#L108-L121 | train |
silverstripe/silverstripe-framework | src/Control/CookieJar.php | CookieJar.forceExpiry | public function forceExpiry($name, $path = null, $domain = null, $secure = false, $httpOnly = true)
{
$this->set($name, false, -1, $path, $domain, $secure, $httpOnly);
} | php | public function forceExpiry($name, $path = null, $domain = null, $secure = false, $httpOnly = true)
{
$this->set($name, false, -1, $path, $domain, $secure, $httpOnly);
} | [
"public",
"function",
"forceExpiry",
"(",
"$",
"name",
",",
"$",
"path",
"=",
"null",
",",
"$",
"domain",
"=",
"null",
",",
"$",
"secure",
"=",
"false",
",",
"$",
"httpOnly",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"set",
"(",
"$",
"name",
",",
"false",
",",
"-",
"1",
",",
"$",
"path",
",",
"$",
"domain",
",",
"$",
"secure",
",",
"$",
"httpOnly",
")",
";",
"}"
]
| Force the expiry of a cookie by name
@param string $name The name of the cookie to expire
@param string $path The path to save the cookie on (falls back to site base)
@param string $domain The domain to make the cookie available on
@param boolean $secure Can the cookie only be sent over SSL?
@param boolean $httpOnly Prevent the cookie being accessible by JS | [
"Force",
"the",
"expiry",
"of",
"a",
"cookie",
"by",
"name"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/CookieJar.php#L143-L146 | train |
silverstripe/silverstripe-framework | src/Control/CookieJar.php | CookieJar.outputCookie | protected function outputCookie(
$name,
$value,
$expiry = 90,
$path = null,
$domain = null,
$secure = false,
$httpOnly = true
) {
// if headers aren't sent, we can set the cookie
if (!headers_sent($file, $line)) {
return setcookie($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
}
if (Cookie::config()->uninherited('report_errors')) {
throw new LogicException(
"Cookie '$name' can't be set. The site started outputting content at line $line in $file"
);
}
return false;
} | php | protected function outputCookie(
$name,
$value,
$expiry = 90,
$path = null,
$domain = null,
$secure = false,
$httpOnly = true
) {
// if headers aren't sent, we can set the cookie
if (!headers_sent($file, $line)) {
return setcookie($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
}
if (Cookie::config()->uninherited('report_errors')) {
throw new LogicException(
"Cookie '$name' can't be set. The site started outputting content at line $line in $file"
);
}
return false;
} | [
"protected",
"function",
"outputCookie",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"expiry",
"=",
"90",
",",
"$",
"path",
"=",
"null",
",",
"$",
"domain",
"=",
"null",
",",
"$",
"secure",
"=",
"false",
",",
"$",
"httpOnly",
"=",
"true",
")",
"{",
"// if headers aren't sent, we can set the cookie",
"if",
"(",
"!",
"headers_sent",
"(",
"$",
"file",
",",
"$",
"line",
")",
")",
"{",
"return",
"setcookie",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"expiry",
",",
"$",
"path",
",",
"$",
"domain",
",",
"$",
"secure",
",",
"$",
"httpOnly",
")",
";",
"}",
"if",
"(",
"Cookie",
"::",
"config",
"(",
")",
"->",
"uninherited",
"(",
"'report_errors'",
")",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"\"Cookie '$name' can't be set. The site started outputting content at line $line in $file\"",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| The function that actually sets the cookie using PHP
@see http://uk3.php.net/manual/en/function.setcookie.php
@param string $name The name of the cookie
@param string|array $value The value for the cookie to hold
@param int $expiry The number of days until expiry
@param string $path The path to save the cookie on (falls back to site base)
@param string $domain The domain to make the cookie available on
@param boolean $secure Can the cookie only be sent over SSL?
@param boolean $httpOnly Prevent the cookie being accessible by JS
@return boolean If the cookie was set or not; doesn't mean it's accepted by the browser | [
"The",
"function",
"that",
"actually",
"sets",
"the",
"cookie",
"using",
"PHP"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/CookieJar.php#L162-L182 | train |
silverstripe/silverstripe-framework | src/Forms/CurrencyField_Disabled.php | CurrencyField_Disabled.Field | public function Field($properties = array())
{
if ($this->value) {
$val = Convert::raw2xml($this->value);
$val = DBCurrency::config()->get('currency_symbol')
. number_format(preg_replace('/[^0-9.-]/', '', $val), 2);
$valforInput = Convert::raw2att($val);
} else {
$valforInput = '';
}
return "<input class=\"text\" type=\"text\" disabled=\"disabled\""
. " name=\"" . $this->name . "\" value=\"" . $valforInput . "\" />";
} | php | public function Field($properties = array())
{
if ($this->value) {
$val = Convert::raw2xml($this->value);
$val = DBCurrency::config()->get('currency_symbol')
. number_format(preg_replace('/[^0-9.-]/', '', $val), 2);
$valforInput = Convert::raw2att($val);
} else {
$valforInput = '';
}
return "<input class=\"text\" type=\"text\" disabled=\"disabled\""
. " name=\"" . $this->name . "\" value=\"" . $valforInput . "\" />";
} | [
"public",
"function",
"Field",
"(",
"$",
"properties",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"value",
")",
"{",
"$",
"val",
"=",
"Convert",
"::",
"raw2xml",
"(",
"$",
"this",
"->",
"value",
")",
";",
"$",
"val",
"=",
"DBCurrency",
"::",
"config",
"(",
")",
"->",
"get",
"(",
"'currency_symbol'",
")",
".",
"number_format",
"(",
"preg_replace",
"(",
"'/[^0-9.-]/'",
",",
"''",
",",
"$",
"val",
")",
",",
"2",
")",
";",
"$",
"valforInput",
"=",
"Convert",
"::",
"raw2att",
"(",
"$",
"val",
")",
";",
"}",
"else",
"{",
"$",
"valforInput",
"=",
"''",
";",
"}",
"return",
"\"<input class=\\\"text\\\" type=\\\"text\\\" disabled=\\\"disabled\\\"\"",
".",
"\" name=\\\"\"",
".",
"$",
"this",
"->",
"name",
".",
"\"\\\" value=\\\"\"",
".",
"$",
"valforInput",
".",
"\"\\\" />\"",
";",
"}"
]
| Overloaded to display the correctly formatted value for this data type
@param array $properties
@return string | [
"Overloaded",
"to",
"display",
"the",
"correctly",
"formatted",
"value",
"for",
"this",
"data",
"type"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/CurrencyField_Disabled.php#L22-L34 | train |
silverstripe/silverstripe-framework | src/View/Parsers/Diff.php | Diff.cleanHTML | public static function cleanHTML($content, $cleaner = null)
{
if (!$cleaner) {
if (self::$html_cleaner_class && class_exists(self::$html_cleaner_class)) {
$cleaner = Injector::inst()->create(self::$html_cleaner_class);
} else {
//load cleaner if the dependent class is available
$cleaner = HTMLCleaner::inst();
}
}
if ($cleaner) {
$content = $cleaner->cleanHTML($content);
} else {
// At most basic level of cleaning, use DOMDocument to save valid XML.
$doc = HTMLValue::create($content);
$content = $doc->getContent();
}
// Remove empty <ins /> and <del /> tags because browsers hate them
$content = preg_replace('/<(ins|del)[^>]*\/>/', '', $content);
return $content;
} | php | public static function cleanHTML($content, $cleaner = null)
{
if (!$cleaner) {
if (self::$html_cleaner_class && class_exists(self::$html_cleaner_class)) {
$cleaner = Injector::inst()->create(self::$html_cleaner_class);
} else {
//load cleaner if the dependent class is available
$cleaner = HTMLCleaner::inst();
}
}
if ($cleaner) {
$content = $cleaner->cleanHTML($content);
} else {
// At most basic level of cleaning, use DOMDocument to save valid XML.
$doc = HTMLValue::create($content);
$content = $doc->getContent();
}
// Remove empty <ins /> and <del /> tags because browsers hate them
$content = preg_replace('/<(ins|del)[^>]*\/>/', '', $content);
return $content;
} | [
"public",
"static",
"function",
"cleanHTML",
"(",
"$",
"content",
",",
"$",
"cleaner",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"cleaner",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"html_cleaner_class",
"&&",
"class_exists",
"(",
"self",
"::",
"$",
"html_cleaner_class",
")",
")",
"{",
"$",
"cleaner",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"self",
"::",
"$",
"html_cleaner_class",
")",
";",
"}",
"else",
"{",
"//load cleaner if the dependent class is available",
"$",
"cleaner",
"=",
"HTMLCleaner",
"::",
"inst",
"(",
")",
";",
"}",
"}",
"if",
"(",
"$",
"cleaner",
")",
"{",
"$",
"content",
"=",
"$",
"cleaner",
"->",
"cleanHTML",
"(",
"$",
"content",
")",
";",
"}",
"else",
"{",
"// At most basic level of cleaning, use DOMDocument to save valid XML.",
"$",
"doc",
"=",
"HTMLValue",
"::",
"create",
"(",
"$",
"content",
")",
";",
"$",
"content",
"=",
"$",
"doc",
"->",
"getContent",
"(",
")",
";",
"}",
"// Remove empty <ins /> and <del /> tags because browsers hate them",
"$",
"content",
"=",
"preg_replace",
"(",
"'/<(ins|del)[^>]*\\/>/'",
",",
"''",
",",
"$",
"content",
")",
";",
"return",
"$",
"content",
";",
"}"
]
| Attempt to clean invalid HTML, which messes up diffs.
This cleans code if possible, using an instance of HTMLCleaner
NB: By default, only extremely simple tidying is performed,
by passing through DomDocument::loadHTML and saveXML
@param string $content HTML content
@param HTMLCleaner $cleaner Optional instance of a HTMLCleaner class to
use, overriding self::$html_cleaner_class
@return mixed|string | [
"Attempt",
"to",
"clean",
"invalid",
"HTML",
"which",
"messes",
"up",
"diffs",
".",
"This",
"cleans",
"code",
"if",
"possible",
"using",
"an",
"instance",
"of",
"HTMLCleaner"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Parsers/Diff.php#L30-L53 | train |
silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | SQLInsert.addRow | public function addRow($data = null)
{
// Clear existing empty row
if (($current = $this->currentRow()) && $current->isEmpty()) {
array_pop($this->rows);
}
// Append data
if ($data instanceof SQLAssignmentRow) {
$this->rows[] = $data;
} else {
$this->rows[] = new SQLAssignmentRow($data);
}
return $this;
} | php | public function addRow($data = null)
{
// Clear existing empty row
if (($current = $this->currentRow()) && $current->isEmpty()) {
array_pop($this->rows);
}
// Append data
if ($data instanceof SQLAssignmentRow) {
$this->rows[] = $data;
} else {
$this->rows[] = new SQLAssignmentRow($data);
}
return $this;
} | [
"public",
"function",
"addRow",
"(",
"$",
"data",
"=",
"null",
")",
"{",
"// Clear existing empty row",
"if",
"(",
"(",
"$",
"current",
"=",
"$",
"this",
"->",
"currentRow",
"(",
")",
")",
"&&",
"$",
"current",
"->",
"isEmpty",
"(",
")",
")",
"{",
"array_pop",
"(",
"$",
"this",
"->",
"rows",
")",
";",
"}",
"// Append data",
"if",
"(",
"$",
"data",
"instanceof",
"SQLAssignmentRow",
")",
"{",
"$",
"this",
"->",
"rows",
"[",
"]",
"=",
"$",
"data",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"rows",
"[",
"]",
"=",
"new",
"SQLAssignmentRow",
"(",
"$",
"data",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Appends a new row to insert
@param array|SQLAssignmentRow $data A list of data to include for this row
@return $this The self reference to this query | [
"Appends",
"a",
"new",
"row",
"to",
"insert"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLInsert.php#L87-L101 | train |
silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | SQLInsert.getColumns | public function getColumns()
{
$columns = array();
foreach ($this->getRows() as $row) {
$columns = array_merge($columns, $row->getColumns());
}
return array_unique($columns);
} | php | public function getColumns()
{
$columns = array();
foreach ($this->getRows() as $row) {
$columns = array_merge($columns, $row->getColumns());
}
return array_unique($columns);
} | [
"public",
"function",
"getColumns",
"(",
")",
"{",
"$",
"columns",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getRows",
"(",
")",
"as",
"$",
"row",
")",
"{",
"$",
"columns",
"=",
"array_merge",
"(",
"$",
"columns",
",",
"$",
"row",
"->",
"getColumns",
"(",
")",
")",
";",
"}",
"return",
"array_unique",
"(",
"$",
"columns",
")",
";",
"}"
]
| Returns the list of distinct column names used in this insert
@return array | [
"Returns",
"the",
"list",
"of",
"distinct",
"column",
"names",
"used",
"in",
"this",
"insert"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLInsert.php#L118-L125 | train |
silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | SQLInsert.currentRow | public function currentRow($create = false)
{
$current = end($this->rows);
if ($create && !$current) {
$this->rows[] = $current = new SQLAssignmentRow();
}
return $current;
} | php | public function currentRow($create = false)
{
$current = end($this->rows);
if ($create && !$current) {
$this->rows[] = $current = new SQLAssignmentRow();
}
return $current;
} | [
"public",
"function",
"currentRow",
"(",
"$",
"create",
"=",
"false",
")",
"{",
"$",
"current",
"=",
"end",
"(",
"$",
"this",
"->",
"rows",
")",
";",
"if",
"(",
"$",
"create",
"&&",
"!",
"$",
"current",
")",
"{",
"$",
"this",
"->",
"rows",
"[",
"]",
"=",
"$",
"current",
"=",
"new",
"SQLAssignmentRow",
"(",
")",
";",
"}",
"return",
"$",
"current",
";",
"}"
]
| Returns the currently set row
@param boolean $create Flag to indicate if a row should be created if none exists
@return SQLAssignmentRow|false The row, or false if none exists | [
"Returns",
"the",
"currently",
"set",
"row"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLInsert.php#L158-L165 | train |
silverstripe/silverstripe-framework | src/Forms/DateField.php | DateField.getDateFormat | public function getDateFormat()
{
// Browsers expect ISO 8601 dates, localisation is handled on the client
if ($this->getHTML5()) {
return DBDate::ISO_DATE;
}
if ($this->dateFormat) {
return $this->dateFormat;
}
// Get from locale
return $this->getFrontendFormatter()->getPattern();
} | php | public function getDateFormat()
{
// Browsers expect ISO 8601 dates, localisation is handled on the client
if ($this->getHTML5()) {
return DBDate::ISO_DATE;
}
if ($this->dateFormat) {
return $this->dateFormat;
}
// Get from locale
return $this->getFrontendFormatter()->getPattern();
} | [
"public",
"function",
"getDateFormat",
"(",
")",
"{",
"// Browsers expect ISO 8601 dates, localisation is handled on the client",
"if",
"(",
"$",
"this",
"->",
"getHTML5",
"(",
")",
")",
"{",
"return",
"DBDate",
"::",
"ISO_DATE",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"dateFormat",
")",
"{",
"return",
"$",
"this",
"->",
"dateFormat",
";",
"}",
"// Get from locale",
"return",
"$",
"this",
"->",
"getFrontendFormatter",
"(",
")",
"->",
"getPattern",
"(",
")",
";",
"}"
]
| Get date format in CLDR standard format
This can be set explicitly. If not, this will be generated from the current locale
with the current date length.
@see http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Field-Symbol-Table | [
"Get",
"date",
"format",
"in",
"CLDR",
"standard",
"format"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/DateField.php#L174-L187 | train |
silverstripe/silverstripe-framework | src/Forms/TreeDropdownField.php | TreeDropdownField.setFilterFunction | public function setFilterFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setFilterCallback(): not passed a valid callback');
}
$this->filterCallback = $callback;
return $this;
} | php | public function setFilterFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setFilterCallback(): not passed a valid callback');
}
$this->filterCallback = $callback;
return $this;
} | [
"public",
"function",
"setFilterFunction",
"(",
"$",
"callback",
")",
"{",
"if",
"(",
"!",
"is_callable",
"(",
"$",
"callback",
",",
"true",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'TreeDropdownField->setFilterCallback(): not passed a valid callback'",
")",
";",
"}",
"$",
"this",
"->",
"filterCallback",
"=",
"$",
"callback",
";",
"return",
"$",
"this",
";",
"}"
]
| Set a callback used to filter the values of the tree before
displaying to the user.
@param callable $callback
@return $this | [
"Set",
"a",
"callback",
"used",
"to",
"filter",
"the",
"values",
"of",
"the",
"tree",
"before",
"displaying",
"to",
"the",
"user",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TreeDropdownField.php#L295-L303 | train |
silverstripe/silverstripe-framework | src/Forms/TreeDropdownField.php | TreeDropdownField.setDisableFunction | public function setDisableFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setDisableFunction(): not passed a valid callback');
}
$this->disableCallback = $callback;
return $this;
} | php | public function setDisableFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setDisableFunction(): not passed a valid callback');
}
$this->disableCallback = $callback;
return $this;
} | [
"public",
"function",
"setDisableFunction",
"(",
"$",
"callback",
")",
"{",
"if",
"(",
"!",
"is_callable",
"(",
"$",
"callback",
",",
"true",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'TreeDropdownField->setDisableFunction(): not passed a valid callback'",
")",
";",
"}",
"$",
"this",
"->",
"disableCallback",
"=",
"$",
"callback",
";",
"return",
"$",
"this",
";",
"}"
]
| Set a callback used to disable checkboxes for some items in the tree
@param callable $callback
@return $this | [
"Set",
"a",
"callback",
"used",
"to",
"disable",
"checkboxes",
"for",
"some",
"items",
"in",
"the",
"tree"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TreeDropdownField.php#L321-L329 | train |
silverstripe/silverstripe-framework | src/Forms/TreeDropdownField.php | TreeDropdownField.setSearchFunction | public function setSearchFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setSearchFunction(): not passed a valid callback');
}
$this->searchCallback = $callback;
return $this;
} | php | public function setSearchFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setSearchFunction(): not passed a valid callback');
}
$this->searchCallback = $callback;
return $this;
} | [
"public",
"function",
"setSearchFunction",
"(",
"$",
"callback",
")",
"{",
"if",
"(",
"!",
"is_callable",
"(",
"$",
"callback",
",",
"true",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'TreeDropdownField->setSearchFunction(): not passed a valid callback'",
")",
";",
"}",
"$",
"this",
"->",
"searchCallback",
"=",
"$",
"callback",
";",
"return",
"$",
"this",
";",
"}"
]
| Set a callback used to search the hierarchy globally, even before
applying the filter.
@param callable $callback
@return $this | [
"Set",
"a",
"callback",
"used",
"to",
"search",
"the",
"hierarchy",
"globally",
"even",
"before",
"applying",
"the",
"filter",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TreeDropdownField.php#L349-L357 | train |
silverstripe/silverstripe-framework | src/Forms/TreeDropdownField.php | TreeDropdownField.filterMarking | public function filterMarking($node)
{
$callback = $this->getFilterFunction();
if ($callback && !call_user_func($callback, $node)) {
return false;
}
if ($this->search) {
return isset($this->searchIds[$node->ID]) && $this->searchIds[$node->ID] ? true : false;
}
return true;
} | php | public function filterMarking($node)
{
$callback = $this->getFilterFunction();
if ($callback && !call_user_func($callback, $node)) {
return false;
}
if ($this->search) {
return isset($this->searchIds[$node->ID]) && $this->searchIds[$node->ID] ? true : false;
}
return true;
} | [
"public",
"function",
"filterMarking",
"(",
"$",
"node",
")",
"{",
"$",
"callback",
"=",
"$",
"this",
"->",
"getFilterFunction",
"(",
")",
";",
"if",
"(",
"$",
"callback",
"&&",
"!",
"call_user_func",
"(",
"$",
"callback",
",",
"$",
"node",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"search",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"searchIds",
"[",
"$",
"node",
"->",
"ID",
"]",
")",
"&&",
"$",
"this",
"->",
"searchIds",
"[",
"$",
"node",
"->",
"ID",
"]",
"?",
"true",
":",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Marking public function for the tree, which combines different filters sensibly.
If a filter function has been set, that will be called. And if search text is set,
filter on that too. Return true if all applicable conditions are true, false otherwise.
@param DataObject $node
@return bool | [
"Marking",
"public",
"function",
"for",
"the",
"tree",
"which",
"combines",
"different",
"filters",
"sensibly",
".",
"If",
"a",
"filter",
"function",
"has",
"been",
"set",
"that",
"will",
"be",
"called",
".",
"And",
"if",
"search",
"text",
"is",
"set",
"filter",
"on",
"that",
"too",
".",
"Return",
"true",
"if",
"all",
"applicable",
"conditions",
"are",
"true",
"false",
"otherwise",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TreeDropdownField.php#L574-L586 | train |
silverstripe/silverstripe-framework | src/Forms/TreeDropdownField.php | TreeDropdownField.flattenChildrenArray | protected function flattenChildrenArray($children, $parentTitles = [])
{
$output = [];
foreach ($children as $child) {
$childTitles = array_merge($parentTitles, [$child['title']]);
$grandChildren = $child['children'];
$contextString = implode('/', $parentTitles);
$child['contextString'] = ($contextString !== '') ? $contextString . '/' : '';
unset($child['children']);
if (!$this->search || in_array($child['id'], $this->realSearchIds)) {
$output[] = $child;
}
$output = array_merge($output, $this->flattenChildrenArray($grandChildren, $childTitles));
}
return $output;
} | php | protected function flattenChildrenArray($children, $parentTitles = [])
{
$output = [];
foreach ($children as $child) {
$childTitles = array_merge($parentTitles, [$child['title']]);
$grandChildren = $child['children'];
$contextString = implode('/', $parentTitles);
$child['contextString'] = ($contextString !== '') ? $contextString . '/' : '';
unset($child['children']);
if (!$this->search || in_array($child['id'], $this->realSearchIds)) {
$output[] = $child;
}
$output = array_merge($output, $this->flattenChildrenArray($grandChildren, $childTitles));
}
return $output;
} | [
"protected",
"function",
"flattenChildrenArray",
"(",
"$",
"children",
",",
"$",
"parentTitles",
"=",
"[",
"]",
")",
"{",
"$",
"output",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"children",
"as",
"$",
"child",
")",
"{",
"$",
"childTitles",
"=",
"array_merge",
"(",
"$",
"parentTitles",
",",
"[",
"$",
"child",
"[",
"'title'",
"]",
"]",
")",
";",
"$",
"grandChildren",
"=",
"$",
"child",
"[",
"'children'",
"]",
";",
"$",
"contextString",
"=",
"implode",
"(",
"'/'",
",",
"$",
"parentTitles",
")",
";",
"$",
"child",
"[",
"'contextString'",
"]",
"=",
"(",
"$",
"contextString",
"!==",
"''",
")",
"?",
"$",
"contextString",
".",
"'/'",
":",
"''",
";",
"unset",
"(",
"$",
"child",
"[",
"'children'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"search",
"||",
"in_array",
"(",
"$",
"child",
"[",
"'id'",
"]",
",",
"$",
"this",
"->",
"realSearchIds",
")",
")",
"{",
"$",
"output",
"[",
"]",
"=",
"$",
"child",
";",
"}",
"$",
"output",
"=",
"array_merge",
"(",
"$",
"output",
",",
"$",
"this",
"->",
"flattenChildrenArray",
"(",
"$",
"grandChildren",
",",
"$",
"childTitles",
")",
")",
";",
"}",
"return",
"$",
"output",
";",
"}"
]
| Flattens a given list of children array items, so the data is no longer
structured in a hierarchy
NOTE: uses {@link TreeDropdownField::$realSearchIds} to filter items by if there is a search
@param array $children - the list of children, which could contain their own children
@param array $parentTitles - a list of parent titles, which we use to construct the contextString
@return array - flattened list of children | [
"Flattens",
"a",
"given",
"list",
"of",
"children",
"array",
"items",
"so",
"the",
"data",
"is",
"no",
"longer",
"structured",
"in",
"a",
"hierarchy"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TreeDropdownField.php#L713-L732 | train |
silverstripe/silverstripe-framework | src/Forms/TreeDropdownField.php | TreeDropdownField.getSearchResults | protected function getSearchResults()
{
$callback = $this->getSearchFunction();
if ($callback) {
return call_user_func($callback, $this->getSourceObject(), $this->getLabelField(), $this->search);
}
$sourceObject = $this->getSourceObject();
$filters = array();
$sourceObjectInstance = DataObject::singleton($sourceObject);
$candidates = array_unique([
$this->getLabelField(),
$this->getTitleField(),
'Title',
'Name'
]);
foreach ($candidates as $candidate) {
if ($sourceObjectInstance->hasDatabaseField($candidate)) {
$filters["{$candidate}:PartialMatch"] = $this->search;
}
}
if (empty($filters)) {
throw new InvalidArgumentException(sprintf(
'Cannot query by %s.%s, not a valid database column',
$sourceObject,
$this->getTitleField()
));
}
return DataObject::get($this->getSourceObject())->filterAny($filters);
} | php | protected function getSearchResults()
{
$callback = $this->getSearchFunction();
if ($callback) {
return call_user_func($callback, $this->getSourceObject(), $this->getLabelField(), $this->search);
}
$sourceObject = $this->getSourceObject();
$filters = array();
$sourceObjectInstance = DataObject::singleton($sourceObject);
$candidates = array_unique([
$this->getLabelField(),
$this->getTitleField(),
'Title',
'Name'
]);
foreach ($candidates as $candidate) {
if ($sourceObjectInstance->hasDatabaseField($candidate)) {
$filters["{$candidate}:PartialMatch"] = $this->search;
}
}
if (empty($filters)) {
throw new InvalidArgumentException(sprintf(
'Cannot query by %s.%s, not a valid database column',
$sourceObject,
$this->getTitleField()
));
}
return DataObject::get($this->getSourceObject())->filterAny($filters);
} | [
"protected",
"function",
"getSearchResults",
"(",
")",
"{",
"$",
"callback",
"=",
"$",
"this",
"->",
"getSearchFunction",
"(",
")",
";",
"if",
"(",
"$",
"callback",
")",
"{",
"return",
"call_user_func",
"(",
"$",
"callback",
",",
"$",
"this",
"->",
"getSourceObject",
"(",
")",
",",
"$",
"this",
"->",
"getLabelField",
"(",
")",
",",
"$",
"this",
"->",
"search",
")",
";",
"}",
"$",
"sourceObject",
"=",
"$",
"this",
"->",
"getSourceObject",
"(",
")",
";",
"$",
"filters",
"=",
"array",
"(",
")",
";",
"$",
"sourceObjectInstance",
"=",
"DataObject",
"::",
"singleton",
"(",
"$",
"sourceObject",
")",
";",
"$",
"candidates",
"=",
"array_unique",
"(",
"[",
"$",
"this",
"->",
"getLabelField",
"(",
")",
",",
"$",
"this",
"->",
"getTitleField",
"(",
")",
",",
"'Title'",
",",
"'Name'",
"]",
")",
";",
"foreach",
"(",
"$",
"candidates",
"as",
"$",
"candidate",
")",
"{",
"if",
"(",
"$",
"sourceObjectInstance",
"->",
"hasDatabaseField",
"(",
"$",
"candidate",
")",
")",
"{",
"$",
"filters",
"[",
"\"{$candidate}:PartialMatch\"",
"]",
"=",
"$",
"this",
"->",
"search",
";",
"}",
"}",
"if",
"(",
"empty",
"(",
"$",
"filters",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Cannot query by %s.%s, not a valid database column'",
",",
"$",
"sourceObject",
",",
"$",
"this",
"->",
"getTitleField",
"(",
")",
")",
")",
";",
"}",
"return",
"DataObject",
"::",
"get",
"(",
"$",
"this",
"->",
"getSourceObject",
"(",
")",
")",
"->",
"filterAny",
"(",
"$",
"filters",
")",
";",
"}"
]
| Get the DataObjects that matches the searched parameter.
@return DataList | [
"Get",
"the",
"DataObjects",
"that",
"matches",
"the",
"searched",
"parameter",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TreeDropdownField.php#L779-L809 | train |
silverstripe/silverstripe-framework | src/Forms/TreeDropdownField.php | TreeDropdownField.getCacheKey | protected function getCacheKey()
{
$target = $this->getSourceObject();
if (!isset(self::$cacheKeyCache[$target])) {
self::$cacheKeyCache[$target] = DataList::create($target)->max('LastEdited');
}
return self::$cacheKeyCache[$target];
} | php | protected function getCacheKey()
{
$target = $this->getSourceObject();
if (!isset(self::$cacheKeyCache[$target])) {
self::$cacheKeyCache[$target] = DataList::create($target)->max('LastEdited');
}
return self::$cacheKeyCache[$target];
} | [
"protected",
"function",
"getCacheKey",
"(",
")",
"{",
"$",
"target",
"=",
"$",
"this",
"->",
"getSourceObject",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"cacheKeyCache",
"[",
"$",
"target",
"]",
")",
")",
"{",
"self",
"::",
"$",
"cacheKeyCache",
"[",
"$",
"target",
"]",
"=",
"DataList",
"::",
"create",
"(",
"$",
"target",
")",
"->",
"max",
"(",
"'LastEdited'",
")",
";",
"}",
"return",
"self",
"::",
"$",
"cacheKeyCache",
"[",
"$",
"target",
"]",
";",
"}"
]
| Ensure cache is keyed by last modified datetime of the underlying list.
Caches the key for the respective underlying list types, since it doesn't need to query again.
@return DBDatetime | [
"Ensure",
"cache",
"is",
"keyed",
"by",
"last",
"modified",
"datetime",
"of",
"the",
"underlying",
"list",
".",
"Caches",
"the",
"key",
"for",
"the",
"respective",
"underlying",
"list",
"types",
"since",
"it",
"doesn",
"t",
"need",
"to",
"query",
"again",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/TreeDropdownField.php#L889-L896 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBComposite.php | DBComposite.writeToManipulation | public function writeToManipulation(&$manipulation)
{
foreach ($this->compositeDatabaseFields() as $field => $spec) {
// Write sub-manipulation
$fieldObject = $this->dbObject($field);
$fieldObject->writeToManipulation($manipulation);
}
} | php | public function writeToManipulation(&$manipulation)
{
foreach ($this->compositeDatabaseFields() as $field => $spec) {
// Write sub-manipulation
$fieldObject = $this->dbObject($field);
$fieldObject->writeToManipulation($manipulation);
}
} | [
"public",
"function",
"writeToManipulation",
"(",
"&",
"$",
"manipulation",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"compositeDatabaseFields",
"(",
")",
"as",
"$",
"field",
"=>",
"$",
"spec",
")",
"{",
"// Write sub-manipulation",
"$",
"fieldObject",
"=",
"$",
"this",
"->",
"dbObject",
"(",
"$",
"field",
")",
";",
"$",
"fieldObject",
"->",
"writeToManipulation",
"(",
"$",
"manipulation",
")",
";",
"}",
"}"
]
| Write all nested fields into a manipulation
@param array $manipulation | [
"Write",
"all",
"nested",
"fields",
"into",
"a",
"manipulation"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBComposite.php#L78-L85 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBComposite.php | DBComposite.isChanged | public function isChanged()
{
// When unbound, use the local changed flag
if (! ($this->record instanceof DataObject)) {
return $this->isChanged;
}
// Defer to parent record
foreach ($this->compositeDatabaseFields() as $field => $spec) {
$key = $this->getName() . $field;
if ($this->record->isChanged($key)) {
return true;
}
}
return false;
} | php | public function isChanged()
{
// When unbound, use the local changed flag
if (! ($this->record instanceof DataObject)) {
return $this->isChanged;
}
// Defer to parent record
foreach ($this->compositeDatabaseFields() as $field => $spec) {
$key = $this->getName() . $field;
if ($this->record->isChanged($key)) {
return true;
}
}
return false;
} | [
"public",
"function",
"isChanged",
"(",
")",
"{",
"// When unbound, use the local changed flag",
"if",
"(",
"!",
"(",
"$",
"this",
"->",
"record",
"instanceof",
"DataObject",
")",
")",
"{",
"return",
"$",
"this",
"->",
"isChanged",
";",
"}",
"// Defer to parent record",
"foreach",
"(",
"$",
"this",
"->",
"compositeDatabaseFields",
"(",
")",
"as",
"$",
"field",
"=>",
"$",
"spec",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
".",
"$",
"field",
";",
"if",
"(",
"$",
"this",
"->",
"record",
"->",
"isChanged",
"(",
"$",
"key",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Returns true if this composite field has changed.
For fields bound to a DataObject, this will be cleared when the DataObject is written. | [
"Returns",
"true",
"if",
"this",
"composite",
"field",
"has",
"changed",
".",
"For",
"fields",
"bound",
"to",
"a",
"DataObject",
"this",
"will",
"be",
"cleared",
"when",
"the",
"DataObject",
"is",
"written",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBComposite.php#L126-L141 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBComposite.php | DBComposite.exists | public function exists()
{
// By default all fields
foreach ($this->compositeDatabaseFields() as $field => $spec) {
$fieldObject = $this->dbObject($field);
if (!$fieldObject->exists()) {
return false;
}
}
return true;
} | php | public function exists()
{
// By default all fields
foreach ($this->compositeDatabaseFields() as $field => $spec) {
$fieldObject = $this->dbObject($field);
if (!$fieldObject->exists()) {
return false;
}
}
return true;
} | [
"public",
"function",
"exists",
"(",
")",
"{",
"// By default all fields",
"foreach",
"(",
"$",
"this",
"->",
"compositeDatabaseFields",
"(",
")",
"as",
"$",
"field",
"=>",
"$",
"spec",
")",
"{",
"$",
"fieldObject",
"=",
"$",
"this",
"->",
"dbObject",
"(",
"$",
"field",
")",
";",
"if",
"(",
"!",
"$",
"fieldObject",
"->",
"exists",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| Composite field defaults to exists only if all fields have values
@return boolean | [
"Composite",
"field",
"defaults",
"to",
"exists",
"only",
"if",
"all",
"fields",
"have",
"values"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBComposite.php#L148-L158 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBComposite.php | DBComposite.getField | public function getField($field)
{
// Skip invalid fields
$fields = $this->compositeDatabaseFields();
if (!isset($fields[$field])) {
return null;
}
// Check bound object
if ($this->record instanceof DataObject) {
$key = $this->getName() . $field;
return $this->record->getField($key);
}
// Check local record
if (isset($this->record[$field])) {
return $this->record[$field];
}
return null;
} | php | public function getField($field)
{
// Skip invalid fields
$fields = $this->compositeDatabaseFields();
if (!isset($fields[$field])) {
return null;
}
// Check bound object
if ($this->record instanceof DataObject) {
$key = $this->getName() . $field;
return $this->record->getField($key);
}
// Check local record
if (isset($this->record[$field])) {
return $this->record[$field];
}
return null;
} | [
"public",
"function",
"getField",
"(",
"$",
"field",
")",
"{",
"// Skip invalid fields",
"$",
"fields",
"=",
"$",
"this",
"->",
"compositeDatabaseFields",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"fields",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Check bound object",
"if",
"(",
"$",
"this",
"->",
"record",
"instanceof",
"DataObject",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
".",
"$",
"field",
";",
"return",
"$",
"this",
"->",
"record",
"->",
"getField",
"(",
"$",
"key",
")",
";",
"}",
"// Check local record",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"record",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"record",
"[",
"$",
"field",
"]",
";",
"}",
"return",
"null",
";",
"}"
]
| get value of a single composite field
@param string $field
@return mixed | [
"get",
"value",
"of",
"a",
"single",
"composite",
"field"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBComposite.php#L234-L253 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBComposite.php | DBComposite.setField | public function setField($field, $value, $markChanged = true)
{
$this->objCacheClear();
// Non-db fields get assigned as normal properties
if (!$this->hasField($field)) {
parent::setField($field, $value);
return $this;
}
// Set changed
if ($markChanged) {
$this->isChanged = true;
}
// Set bound object
if ($this->record instanceof DataObject) {
$key = $this->getName() . $field;
$this->record->setField($key, $value);
return $this;
}
// Set local record
$this->record[$field] = $value;
return $this;
} | php | public function setField($field, $value, $markChanged = true)
{
$this->objCacheClear();
// Non-db fields get assigned as normal properties
if (!$this->hasField($field)) {
parent::setField($field, $value);
return $this;
}
// Set changed
if ($markChanged) {
$this->isChanged = true;
}
// Set bound object
if ($this->record instanceof DataObject) {
$key = $this->getName() . $field;
$this->record->setField($key, $value);
return $this;
}
// Set local record
$this->record[$field] = $value;
return $this;
} | [
"public",
"function",
"setField",
"(",
"$",
"field",
",",
"$",
"value",
",",
"$",
"markChanged",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"objCacheClear",
"(",
")",
";",
"// Non-db fields get assigned as normal properties",
"if",
"(",
"!",
"$",
"this",
"->",
"hasField",
"(",
"$",
"field",
")",
")",
"{",
"parent",
"::",
"setField",
"(",
"$",
"field",
",",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"}",
"// Set changed",
"if",
"(",
"$",
"markChanged",
")",
"{",
"$",
"this",
"->",
"isChanged",
"=",
"true",
";",
"}",
"// Set bound object",
"if",
"(",
"$",
"this",
"->",
"record",
"instanceof",
"DataObject",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
".",
"$",
"field",
";",
"$",
"this",
"->",
"record",
"->",
"setField",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"}",
"// Set local record",
"$",
"this",
"->",
"record",
"[",
"$",
"field",
"]",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
]
| Set value of a single composite field
@param string $field
@param mixed $value
@param bool $markChanged
@return $this | [
"Set",
"value",
"of",
"a",
"single",
"composite",
"field"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBComposite.php#L269-L295 | train |
silverstripe/silverstripe-framework | src/ORM/FieldType/DBComposite.php | DBComposite.dbObject | public function dbObject($field)
{
$fields = $this->compositeDatabaseFields();
if (!isset($fields[$field])) {
return null;
}
// Build nested field
$key = $this->getName() . $field;
$spec = $fields[$field];
/** @var DBField $fieldObject */
$fieldObject = Injector::inst()->create($spec, $key);
$fieldObject->setValue($this->getField($field), null, false);
return $fieldObject;
} | php | public function dbObject($field)
{
$fields = $this->compositeDatabaseFields();
if (!isset($fields[$field])) {
return null;
}
// Build nested field
$key = $this->getName() . $field;
$spec = $fields[$field];
/** @var DBField $fieldObject */
$fieldObject = Injector::inst()->create($spec, $key);
$fieldObject->setValue($this->getField($field), null, false);
return $fieldObject;
} | [
"public",
"function",
"dbObject",
"(",
"$",
"field",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"compositeDatabaseFields",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"fields",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Build nested field",
"$",
"key",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
".",
"$",
"field",
";",
"$",
"spec",
"=",
"$",
"fields",
"[",
"$",
"field",
"]",
";",
"/** @var DBField $fieldObject */",
"$",
"fieldObject",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"spec",
",",
"$",
"key",
")",
";",
"$",
"fieldObject",
"->",
"setValue",
"(",
"$",
"this",
"->",
"getField",
"(",
"$",
"field",
")",
",",
"null",
",",
"false",
")",
";",
"return",
"$",
"fieldObject",
";",
"}"
]
| Get a db object for the named field
@param string $field Field name
@return DBField|null | [
"Get",
"a",
"db",
"object",
"for",
"the",
"named",
"field"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBComposite.php#L303-L317 | train |
silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldDetailForm.php | GridFieldDetailForm.getItemRequestHandler | protected function getItemRequestHandler($gridField, $record, $requestHandler)
{
$class = $this->getItemRequestClass();
$assignedClass = $this->itemRequestClass;
$this->extend('updateItemRequestClass', $class, $gridField, $record, $requestHandler, $assignedClass);
/** @var GridFieldDetailForm_ItemRequest $handler */
$handler = Injector::inst()->createWithArgs(
$class,
array($gridField, $this, $record, $requestHandler, $this->name)
);
if ($template = $this->getTemplate()) {
$handler->setTemplate($template);
}
$this->extend('updateItemRequestHandler', $handler);
return $handler;
} | php | protected function getItemRequestHandler($gridField, $record, $requestHandler)
{
$class = $this->getItemRequestClass();
$assignedClass = $this->itemRequestClass;
$this->extend('updateItemRequestClass', $class, $gridField, $record, $requestHandler, $assignedClass);
/** @var GridFieldDetailForm_ItemRequest $handler */
$handler = Injector::inst()->createWithArgs(
$class,
array($gridField, $this, $record, $requestHandler, $this->name)
);
if ($template = $this->getTemplate()) {
$handler->setTemplate($template);
}
$this->extend('updateItemRequestHandler', $handler);
return $handler;
} | [
"protected",
"function",
"getItemRequestHandler",
"(",
"$",
"gridField",
",",
"$",
"record",
",",
"$",
"requestHandler",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getItemRequestClass",
"(",
")",
";",
"$",
"assignedClass",
"=",
"$",
"this",
"->",
"itemRequestClass",
";",
"$",
"this",
"->",
"extend",
"(",
"'updateItemRequestClass'",
",",
"$",
"class",
",",
"$",
"gridField",
",",
"$",
"record",
",",
"$",
"requestHandler",
",",
"$",
"assignedClass",
")",
";",
"/** @var GridFieldDetailForm_ItemRequest $handler */",
"$",
"handler",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"createWithArgs",
"(",
"$",
"class",
",",
"array",
"(",
"$",
"gridField",
",",
"$",
"this",
",",
"$",
"record",
",",
"$",
"requestHandler",
",",
"$",
"this",
"->",
"name",
")",
")",
";",
"if",
"(",
"$",
"template",
"=",
"$",
"this",
"->",
"getTemplate",
"(",
")",
")",
"{",
"$",
"handler",
"->",
"setTemplate",
"(",
"$",
"template",
")",
";",
"}",
"$",
"this",
"->",
"extend",
"(",
"'updateItemRequestHandler'",
",",
"$",
"handler",
")",
";",
"return",
"$",
"handler",
";",
"}"
]
| Build a request handler for the given record
@param GridField $gridField
@param DataObject $record
@param RequestHandler $requestHandler
@return GridFieldDetailForm_ItemRequest | [
"Build",
"a",
"request",
"handler",
"for",
"the",
"given",
"record"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldDetailForm.php#L146-L161 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.duplicate | public function duplicate($doWrite = true, $relations = null)
{
// Handle legacy behaviour
if (is_string($relations) || $relations === true) {
if ($relations === true) {
$relations = 'many_many';
}
Deprecation::notice('5.0', 'Use cascade_duplicates config instead of providing a string to duplicate()');
$relations = array_keys($this->config()->get($relations)) ?: [];
}
// Get duplicates
if ($relations === null) {
$relations = $this->config()->get('cascade_duplicates');
// Remove any duplicate entries before duplicating them
if (is_array($relations)) {
$relations = array_unique($relations);
}
}
// Create unsaved raw duplicate
$map = $this->toMap();
unset($map['Created']);
/** @var static $clone */
$clone = Injector::inst()->create(static::class, $map, false, $this->getSourceQueryParams());
$clone->ID = 0;
// Note: Extensions such as versioned may update $relations here
$clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite, $relations);
if ($relations) {
$this->duplicateRelations($this, $clone, $relations);
}
if ($doWrite) {
$clone->write();
}
$clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite, $relations);
return $clone;
} | php | public function duplicate($doWrite = true, $relations = null)
{
// Handle legacy behaviour
if (is_string($relations) || $relations === true) {
if ($relations === true) {
$relations = 'many_many';
}
Deprecation::notice('5.0', 'Use cascade_duplicates config instead of providing a string to duplicate()');
$relations = array_keys($this->config()->get($relations)) ?: [];
}
// Get duplicates
if ($relations === null) {
$relations = $this->config()->get('cascade_duplicates');
// Remove any duplicate entries before duplicating them
if (is_array($relations)) {
$relations = array_unique($relations);
}
}
// Create unsaved raw duplicate
$map = $this->toMap();
unset($map['Created']);
/** @var static $clone */
$clone = Injector::inst()->create(static::class, $map, false, $this->getSourceQueryParams());
$clone->ID = 0;
// Note: Extensions such as versioned may update $relations here
$clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite, $relations);
if ($relations) {
$this->duplicateRelations($this, $clone, $relations);
}
if ($doWrite) {
$clone->write();
}
$clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite, $relations);
return $clone;
} | [
"public",
"function",
"duplicate",
"(",
"$",
"doWrite",
"=",
"true",
",",
"$",
"relations",
"=",
"null",
")",
"{",
"// Handle legacy behaviour",
"if",
"(",
"is_string",
"(",
"$",
"relations",
")",
"||",
"$",
"relations",
"===",
"true",
")",
"{",
"if",
"(",
"$",
"relations",
"===",
"true",
")",
"{",
"$",
"relations",
"=",
"'many_many'",
";",
"}",
"Deprecation",
"::",
"notice",
"(",
"'5.0'",
",",
"'Use cascade_duplicates config instead of providing a string to duplicate()'",
")",
";",
"$",
"relations",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"$",
"relations",
")",
")",
"?",
":",
"[",
"]",
";",
"}",
"// Get duplicates",
"if",
"(",
"$",
"relations",
"===",
"null",
")",
"{",
"$",
"relations",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'cascade_duplicates'",
")",
";",
"// Remove any duplicate entries before duplicating them",
"if",
"(",
"is_array",
"(",
"$",
"relations",
")",
")",
"{",
"$",
"relations",
"=",
"array_unique",
"(",
"$",
"relations",
")",
";",
"}",
"}",
"// Create unsaved raw duplicate",
"$",
"map",
"=",
"$",
"this",
"->",
"toMap",
"(",
")",
";",
"unset",
"(",
"$",
"map",
"[",
"'Created'",
"]",
")",
";",
"/** @var static $clone */",
"$",
"clone",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"static",
"::",
"class",
",",
"$",
"map",
",",
"false",
",",
"$",
"this",
"->",
"getSourceQueryParams",
"(",
")",
")",
";",
"$",
"clone",
"->",
"ID",
"=",
"0",
";",
"// Note: Extensions such as versioned may update $relations here",
"$",
"clone",
"->",
"invokeWithExtensions",
"(",
"'onBeforeDuplicate'",
",",
"$",
"this",
",",
"$",
"doWrite",
",",
"$",
"relations",
")",
";",
"if",
"(",
"$",
"relations",
")",
"{",
"$",
"this",
"->",
"duplicateRelations",
"(",
"$",
"this",
",",
"$",
"clone",
",",
"$",
"relations",
")",
";",
"}",
"if",
"(",
"$",
"doWrite",
")",
"{",
"$",
"clone",
"->",
"write",
"(",
")",
";",
"}",
"$",
"clone",
"->",
"invokeWithExtensions",
"(",
"'onAfterDuplicate'",
",",
"$",
"this",
",",
"$",
"doWrite",
",",
"$",
"relations",
")",
";",
"return",
"$",
"clone",
";",
"}"
]
| Create a duplicate of this node. Can duplicate many_many relations
@param bool $doWrite Perform a write() operation before returning the object.
If this is true, it will create the duplicate in the database.
@param array|null|false $relations List of relations to duplicate.
Will default to `cascade_duplicates` if null.
Set to 'false' to force none.
Set to specific array of names to duplicate to override these.
Note: If using versioned, this will additionally failover to `owns` config.
@return static A duplicate of this node. The exact type will be the type of this node. | [
"Create",
"a",
"duplicate",
"of",
"this",
"node",
".",
"Can",
"duplicate",
"many_many",
"relations"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L425-L463 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.duplicateRelations | protected function duplicateRelations($sourceObject, $destinationObject, $relations)
{
// Get list of duplicable relation types
$manyMany = $sourceObject->manyMany();
$hasMany = $sourceObject->hasMany();
$hasOne = $sourceObject->hasOne();
$belongsTo = $sourceObject->belongsTo();
// Duplicate each relation based on type
foreach ($relations as $relation) {
switch (true) {
case array_key_exists($relation, $manyMany): {
$this->duplicateManyManyRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $hasMany): {
$this->duplicateHasManyRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $hasOne): {
$this->duplicateHasOneRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $belongsTo): {
$this->duplicateBelongsToRelation($sourceObject, $destinationObject, $relation);
break;
}
default: {
$sourceType = get_class($sourceObject);
throw new InvalidArgumentException(
"Cannot duplicate unknown relation {$relation} on parent type {$sourceType}"
);
}
}
}
} | php | protected function duplicateRelations($sourceObject, $destinationObject, $relations)
{
// Get list of duplicable relation types
$manyMany = $sourceObject->manyMany();
$hasMany = $sourceObject->hasMany();
$hasOne = $sourceObject->hasOne();
$belongsTo = $sourceObject->belongsTo();
// Duplicate each relation based on type
foreach ($relations as $relation) {
switch (true) {
case array_key_exists($relation, $manyMany): {
$this->duplicateManyManyRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $hasMany): {
$this->duplicateHasManyRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $hasOne): {
$this->duplicateHasOneRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $belongsTo): {
$this->duplicateBelongsToRelation($sourceObject, $destinationObject, $relation);
break;
}
default: {
$sourceType = get_class($sourceObject);
throw new InvalidArgumentException(
"Cannot duplicate unknown relation {$relation} on parent type {$sourceType}"
);
}
}
}
} | [
"protected",
"function",
"duplicateRelations",
"(",
"$",
"sourceObject",
",",
"$",
"destinationObject",
",",
"$",
"relations",
")",
"{",
"// Get list of duplicable relation types",
"$",
"manyMany",
"=",
"$",
"sourceObject",
"->",
"manyMany",
"(",
")",
";",
"$",
"hasMany",
"=",
"$",
"sourceObject",
"->",
"hasMany",
"(",
")",
";",
"$",
"hasOne",
"=",
"$",
"sourceObject",
"->",
"hasOne",
"(",
")",
";",
"$",
"belongsTo",
"=",
"$",
"sourceObject",
"->",
"belongsTo",
"(",
")",
";",
"// Duplicate each relation based on type",
"foreach",
"(",
"$",
"relations",
"as",
"$",
"relation",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"array_key_exists",
"(",
"$",
"relation",
",",
"$",
"manyMany",
")",
":",
"{",
"$",
"this",
"->",
"duplicateManyManyRelation",
"(",
"$",
"sourceObject",
",",
"$",
"destinationObject",
",",
"$",
"relation",
")",
";",
"break",
";",
"}",
"case",
"array_key_exists",
"(",
"$",
"relation",
",",
"$",
"hasMany",
")",
":",
"{",
"$",
"this",
"->",
"duplicateHasManyRelation",
"(",
"$",
"sourceObject",
",",
"$",
"destinationObject",
",",
"$",
"relation",
")",
";",
"break",
";",
"}",
"case",
"array_key_exists",
"(",
"$",
"relation",
",",
"$",
"hasOne",
")",
":",
"{",
"$",
"this",
"->",
"duplicateHasOneRelation",
"(",
"$",
"sourceObject",
",",
"$",
"destinationObject",
",",
"$",
"relation",
")",
";",
"break",
";",
"}",
"case",
"array_key_exists",
"(",
"$",
"relation",
",",
"$",
"belongsTo",
")",
":",
"{",
"$",
"this",
"->",
"duplicateBelongsToRelation",
"(",
"$",
"sourceObject",
",",
"$",
"destinationObject",
",",
"$",
"relation",
")",
";",
"break",
";",
"}",
"default",
":",
"{",
"$",
"sourceType",
"=",
"get_class",
"(",
"$",
"sourceObject",
")",
";",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Cannot duplicate unknown relation {$relation} on parent type {$sourceType}\"",
")",
";",
"}",
"}",
"}",
"}"
]
| Copies the given relations from this object to the destination
@param DataObject $sourceObject the source object to duplicate from
@param DataObject $destinationObject the destination object to populate with the duplicated relations
@param array $relations List of relations | [
"Copies",
"the",
"given",
"relations",
"from",
"this",
"object",
"to",
"the",
"destination"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L472-L507 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.duplicateManyManyRelations | protected function duplicateManyManyRelations($sourceObject, $destinationObject, $filter)
{
Deprecation::notice('5.0', 'Use duplicateRelations() instead');
// Get list of relations to duplicate
if ($filter === 'many_many' || $filter === 'belongs_many_many') {
$relations = $sourceObject->config()->get($filter);
} elseif ($filter === true) {
$relations = $sourceObject->manyMany();
} else {
throw new InvalidArgumentException("Invalid many_many duplication filter");
}
foreach ($relations as $manyManyName => $type) {
$this->duplicateManyManyRelation($sourceObject, $destinationObject, $manyManyName);
}
} | php | protected function duplicateManyManyRelations($sourceObject, $destinationObject, $filter)
{
Deprecation::notice('5.0', 'Use duplicateRelations() instead');
// Get list of relations to duplicate
if ($filter === 'many_many' || $filter === 'belongs_many_many') {
$relations = $sourceObject->config()->get($filter);
} elseif ($filter === true) {
$relations = $sourceObject->manyMany();
} else {
throw new InvalidArgumentException("Invalid many_many duplication filter");
}
foreach ($relations as $manyManyName => $type) {
$this->duplicateManyManyRelation($sourceObject, $destinationObject, $manyManyName);
}
} | [
"protected",
"function",
"duplicateManyManyRelations",
"(",
"$",
"sourceObject",
",",
"$",
"destinationObject",
",",
"$",
"filter",
")",
"{",
"Deprecation",
"::",
"notice",
"(",
"'5.0'",
",",
"'Use duplicateRelations() instead'",
")",
";",
"// Get list of relations to duplicate",
"if",
"(",
"$",
"filter",
"===",
"'many_many'",
"||",
"$",
"filter",
"===",
"'belongs_many_many'",
")",
"{",
"$",
"relations",
"=",
"$",
"sourceObject",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"$",
"filter",
")",
";",
"}",
"elseif",
"(",
"$",
"filter",
"===",
"true",
")",
"{",
"$",
"relations",
"=",
"$",
"sourceObject",
"->",
"manyMany",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid many_many duplication filter\"",
")",
";",
"}",
"foreach",
"(",
"$",
"relations",
"as",
"$",
"manyManyName",
"=>",
"$",
"type",
")",
"{",
"$",
"this",
"->",
"duplicateManyManyRelation",
"(",
"$",
"sourceObject",
",",
"$",
"destinationObject",
",",
"$",
"manyManyName",
")",
";",
"}",
"}"
]
| Copies the many_many and belongs_many_many relations from one object to another instance of the name of object.
@deprecated 4.1.0:5.0.0 Use duplicateRelations() instead
@param DataObject $sourceObject the source object to duplicate from
@param DataObject $destinationObject the destination object to populate with the duplicated relations
@param bool|string $filter | [
"Copies",
"the",
"many_many",
"and",
"belongs_many_many",
"relations",
"from",
"one",
"object",
"to",
"another",
"instance",
"of",
"the",
"name",
"of",
"object",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L517-L532 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.update | public function update($data)
{
foreach ($data as $key => $value) {
// Implement dot syntax for updates
if (strpos($key, '.') !== false) {
$relations = explode('.', $key);
$fieldName = array_pop($relations);
/** @var static $relObj */
$relObj = $this;
$relation = null;
foreach ($relations as $i => $relation) {
// no support for has_many or many_many relationships,
// as the updater wouldn't know which object to write to (or create)
if ($relObj->$relation() instanceof DataObject) {
$parentObj = $relObj;
$relObj = $relObj->$relation();
// If the intermediate relationship objects haven't been created, then write them
if ($i < sizeof($relations) - 1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) {
$relObj->write();
$relatedFieldName = $relation . "ID";
$parentObj->$relatedFieldName = $relObj->ID;
$parentObj->write();
}
} else {
user_error(
"DataObject::update(): Can't traverse relationship '$relation'," .
"it has to be a has_one relationship or return a single DataObject",
E_USER_NOTICE
);
// unset relation object so we don't write properties to the wrong object
$relObj = null;
break;
}
}
if ($relObj) {
$relObj->$fieldName = $value;
$relObj->write();
$relatedFieldName = $relation . "ID";
$this->$relatedFieldName = $relObj->ID;
$relObj->flushCache();
} else {
$class = static::class;
user_error("Couldn't follow dot syntax '{$key}' on '{$class}' object", E_USER_WARNING);
}
} else {
$this->$key = $value;
}
}
return $this;
} | php | public function update($data)
{
foreach ($data as $key => $value) {
// Implement dot syntax for updates
if (strpos($key, '.') !== false) {
$relations = explode('.', $key);
$fieldName = array_pop($relations);
/** @var static $relObj */
$relObj = $this;
$relation = null;
foreach ($relations as $i => $relation) {
// no support for has_many or many_many relationships,
// as the updater wouldn't know which object to write to (or create)
if ($relObj->$relation() instanceof DataObject) {
$parentObj = $relObj;
$relObj = $relObj->$relation();
// If the intermediate relationship objects haven't been created, then write them
if ($i < sizeof($relations) - 1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) {
$relObj->write();
$relatedFieldName = $relation . "ID";
$parentObj->$relatedFieldName = $relObj->ID;
$parentObj->write();
}
} else {
user_error(
"DataObject::update(): Can't traverse relationship '$relation'," .
"it has to be a has_one relationship or return a single DataObject",
E_USER_NOTICE
);
// unset relation object so we don't write properties to the wrong object
$relObj = null;
break;
}
}
if ($relObj) {
$relObj->$fieldName = $value;
$relObj->write();
$relatedFieldName = $relation . "ID";
$this->$relatedFieldName = $relObj->ID;
$relObj->flushCache();
} else {
$class = static::class;
user_error("Couldn't follow dot syntax '{$key}' on '{$class}' object", E_USER_WARNING);
}
} else {
$this->$key = $value;
}
}
return $this;
} | [
"public",
"function",
"update",
"(",
"$",
"data",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"// Implement dot syntax for updates",
"if",
"(",
"strpos",
"(",
"$",
"key",
",",
"'.'",
")",
"!==",
"false",
")",
"{",
"$",
"relations",
"=",
"explode",
"(",
"'.'",
",",
"$",
"key",
")",
";",
"$",
"fieldName",
"=",
"array_pop",
"(",
"$",
"relations",
")",
";",
"/** @var static $relObj */",
"$",
"relObj",
"=",
"$",
"this",
";",
"$",
"relation",
"=",
"null",
";",
"foreach",
"(",
"$",
"relations",
"as",
"$",
"i",
"=>",
"$",
"relation",
")",
"{",
"// no support for has_many or many_many relationships,",
"// as the updater wouldn't know which object to write to (or create)",
"if",
"(",
"$",
"relObj",
"->",
"$",
"relation",
"(",
")",
"instanceof",
"DataObject",
")",
"{",
"$",
"parentObj",
"=",
"$",
"relObj",
";",
"$",
"relObj",
"=",
"$",
"relObj",
"->",
"$",
"relation",
"(",
")",
";",
"// If the intermediate relationship objects haven't been created, then write them",
"if",
"(",
"$",
"i",
"<",
"sizeof",
"(",
"$",
"relations",
")",
"-",
"1",
"&&",
"!",
"$",
"relObj",
"->",
"ID",
"||",
"(",
"!",
"$",
"relObj",
"->",
"ID",
"&&",
"$",
"parentObj",
"!==",
"$",
"this",
")",
")",
"{",
"$",
"relObj",
"->",
"write",
"(",
")",
";",
"$",
"relatedFieldName",
"=",
"$",
"relation",
".",
"\"ID\"",
";",
"$",
"parentObj",
"->",
"$",
"relatedFieldName",
"=",
"$",
"relObj",
"->",
"ID",
";",
"$",
"parentObj",
"->",
"write",
"(",
")",
";",
"}",
"}",
"else",
"{",
"user_error",
"(",
"\"DataObject::update(): Can't traverse relationship '$relation',\"",
".",
"\"it has to be a has_one relationship or return a single DataObject\"",
",",
"E_USER_NOTICE",
")",
";",
"// unset relation object so we don't write properties to the wrong object",
"$",
"relObj",
"=",
"null",
";",
"break",
";",
"}",
"}",
"if",
"(",
"$",
"relObj",
")",
"{",
"$",
"relObj",
"->",
"$",
"fieldName",
"=",
"$",
"value",
";",
"$",
"relObj",
"->",
"write",
"(",
")",
";",
"$",
"relatedFieldName",
"=",
"$",
"relation",
".",
"\"ID\"",
";",
"$",
"this",
"->",
"$",
"relatedFieldName",
"=",
"$",
"relObj",
"->",
"ID",
";",
"$",
"relObj",
"->",
"flushCache",
"(",
")",
";",
"}",
"else",
"{",
"$",
"class",
"=",
"static",
"::",
"class",
";",
"user_error",
"(",
"\"Couldn't follow dot syntax '{$key}' on '{$class}' object\"",
",",
"E_USER_WARNING",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"$",
"key",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
]
| Update a number of fields on this object, given a map of the desired changes.
The field names can be simple names, or you can use a dot syntax to access $has_one relations.
For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
Doesn't write the main object, but if you use the dot syntax, it will write()
the related objects that it alters.
When using this method with user supplied data, it's very important to
whitelist the allowed keys.
@param array $data A map of field name to data values to update.
@return DataObject $this | [
"Update",
"a",
"number",
"of",
"fields",
"on",
"this",
"object",
"given",
"a",
"map",
"of",
"the",
"desired",
"changes",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L959-L1009 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.merge | public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false)
{
$leftObj = $this;
if ($leftObj->ClassName != $rightObj->ClassName) {
// we can't merge similiar subclasses because they might have additional relations
user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
(expected '{$leftObj->ClassName}').", E_USER_WARNING);
return false;
}
if (!$rightObj->ID) {
user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
to make sure all relations are transferred properly.').", E_USER_WARNING);
return false;
}
// makes sure we don't merge data like ID or ClassName
$rightData = DataObject::getSchema()->fieldSpecs(get_class($rightObj));
foreach ($rightData as $key => $rightSpec) {
// Don't merge ID
if ($key === 'ID') {
continue;
}
// Only merge relations if allowed
if ($rightSpec === 'ForeignKey' && !$includeRelations) {
continue;
}
// don't merge conflicting values if priority is 'left'
if ($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) {
continue;
}
// don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
if ($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) {
continue;
}
// TODO remove redundant merge of has_one fields
$leftObj->{$key} = $rightObj->{$key};
}
// merge relations
if ($includeRelations) {
if ($manyMany = $this->manyMany()) {
foreach ($manyMany as $relationship => $class) {
/** @var DataObject $leftComponents */
$leftComponents = $leftObj->getManyManyComponents($relationship);
$rightComponents = $rightObj->getManyManyComponents($relationship);
if ($rightComponents && $rightComponents->exists()) {
$leftComponents->addMany($rightComponents->column('ID'));
}
$leftComponents->write();
}
}
if ($hasMany = $this->hasMany()) {
foreach ($hasMany as $relationship => $class) {
$leftComponents = $leftObj->getComponents($relationship);
$rightComponents = $rightObj->getComponents($relationship);
if ($rightComponents && $rightComponents->exists()) {
$leftComponents->addMany($rightComponents->column('ID'));
}
$leftComponents->write();
}
}
}
return true;
} | php | public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false)
{
$leftObj = $this;
if ($leftObj->ClassName != $rightObj->ClassName) {
// we can't merge similiar subclasses because they might have additional relations
user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
(expected '{$leftObj->ClassName}').", E_USER_WARNING);
return false;
}
if (!$rightObj->ID) {
user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
to make sure all relations are transferred properly.').", E_USER_WARNING);
return false;
}
// makes sure we don't merge data like ID or ClassName
$rightData = DataObject::getSchema()->fieldSpecs(get_class($rightObj));
foreach ($rightData as $key => $rightSpec) {
// Don't merge ID
if ($key === 'ID') {
continue;
}
// Only merge relations if allowed
if ($rightSpec === 'ForeignKey' && !$includeRelations) {
continue;
}
// don't merge conflicting values if priority is 'left'
if ($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) {
continue;
}
// don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
if ($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) {
continue;
}
// TODO remove redundant merge of has_one fields
$leftObj->{$key} = $rightObj->{$key};
}
// merge relations
if ($includeRelations) {
if ($manyMany = $this->manyMany()) {
foreach ($manyMany as $relationship => $class) {
/** @var DataObject $leftComponents */
$leftComponents = $leftObj->getManyManyComponents($relationship);
$rightComponents = $rightObj->getManyManyComponents($relationship);
if ($rightComponents && $rightComponents->exists()) {
$leftComponents->addMany($rightComponents->column('ID'));
}
$leftComponents->write();
}
}
if ($hasMany = $this->hasMany()) {
foreach ($hasMany as $relationship => $class) {
$leftComponents = $leftObj->getComponents($relationship);
$rightComponents = $rightObj->getComponents($relationship);
if ($rightComponents && $rightComponents->exists()) {
$leftComponents->addMany($rightComponents->column('ID'));
}
$leftComponents->write();
}
}
}
return true;
} | [
"public",
"function",
"merge",
"(",
"$",
"rightObj",
",",
"$",
"priority",
"=",
"'right'",
",",
"$",
"includeRelations",
"=",
"true",
",",
"$",
"overwriteWithEmpty",
"=",
"false",
")",
"{",
"$",
"leftObj",
"=",
"$",
"this",
";",
"if",
"(",
"$",
"leftObj",
"->",
"ClassName",
"!=",
"$",
"rightObj",
"->",
"ClassName",
")",
"{",
"// we can't merge similiar subclasses because they might have additional relations",
"user_error",
"(",
"\"DataObject->merge(): Invalid object class '{$rightObj->ClassName}'\n\t\t\t(expected '{$leftObj->ClassName}').\"",
",",
"E_USER_WARNING",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"rightObj",
"->",
"ID",
")",
"{",
"user_error",
"(",
"\"DataObject->merge(): Please write your merged-in object to the database before merging,\n\t\t\t\tto make sure all relations are transferred properly.').\"",
",",
"E_USER_WARNING",
")",
";",
"return",
"false",
";",
"}",
"// makes sure we don't merge data like ID or ClassName",
"$",
"rightData",
"=",
"DataObject",
"::",
"getSchema",
"(",
")",
"->",
"fieldSpecs",
"(",
"get_class",
"(",
"$",
"rightObj",
")",
")",
";",
"foreach",
"(",
"$",
"rightData",
"as",
"$",
"key",
"=>",
"$",
"rightSpec",
")",
"{",
"// Don't merge ID",
"if",
"(",
"$",
"key",
"===",
"'ID'",
")",
"{",
"continue",
";",
"}",
"// Only merge relations if allowed",
"if",
"(",
"$",
"rightSpec",
"===",
"'ForeignKey'",
"&&",
"!",
"$",
"includeRelations",
")",
"{",
"continue",
";",
"}",
"// don't merge conflicting values if priority is 'left'",
"if",
"(",
"$",
"priority",
"==",
"'left'",
"&&",
"$",
"leftObj",
"->",
"{",
"$",
"key",
"}",
"!==",
"$",
"rightObj",
"->",
"{",
"$",
"key",
"}",
")",
"{",
"continue",
";",
"}",
"// don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)",
"if",
"(",
"$",
"priority",
"==",
"'right'",
"&&",
"!",
"$",
"overwriteWithEmpty",
"&&",
"empty",
"(",
"$",
"rightObj",
"->",
"{",
"$",
"key",
"}",
")",
")",
"{",
"continue",
";",
"}",
"// TODO remove redundant merge of has_one fields",
"$",
"leftObj",
"->",
"{",
"$",
"key",
"}",
"=",
"$",
"rightObj",
"->",
"{",
"$",
"key",
"}",
";",
"}",
"// merge relations",
"if",
"(",
"$",
"includeRelations",
")",
"{",
"if",
"(",
"$",
"manyMany",
"=",
"$",
"this",
"->",
"manyMany",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"manyMany",
"as",
"$",
"relationship",
"=>",
"$",
"class",
")",
"{",
"/** @var DataObject $leftComponents */",
"$",
"leftComponents",
"=",
"$",
"leftObj",
"->",
"getManyManyComponents",
"(",
"$",
"relationship",
")",
";",
"$",
"rightComponents",
"=",
"$",
"rightObj",
"->",
"getManyManyComponents",
"(",
"$",
"relationship",
")",
";",
"if",
"(",
"$",
"rightComponents",
"&&",
"$",
"rightComponents",
"->",
"exists",
"(",
")",
")",
"{",
"$",
"leftComponents",
"->",
"addMany",
"(",
"$",
"rightComponents",
"->",
"column",
"(",
"'ID'",
")",
")",
";",
"}",
"$",
"leftComponents",
"->",
"write",
"(",
")",
";",
"}",
"}",
"if",
"(",
"$",
"hasMany",
"=",
"$",
"this",
"->",
"hasMany",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"hasMany",
"as",
"$",
"relationship",
"=>",
"$",
"class",
")",
"{",
"$",
"leftComponents",
"=",
"$",
"leftObj",
"->",
"getComponents",
"(",
"$",
"relationship",
")",
";",
"$",
"rightComponents",
"=",
"$",
"rightObj",
"->",
"getComponents",
"(",
"$",
"relationship",
")",
";",
"if",
"(",
"$",
"rightComponents",
"&&",
"$",
"rightComponents",
"->",
"exists",
"(",
")",
")",
"{",
"$",
"leftComponents",
"->",
"addMany",
"(",
"$",
"rightComponents",
"->",
"column",
"(",
"'ID'",
")",
")",
";",
"}",
"$",
"leftComponents",
"->",
"write",
"(",
")",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
]
| Merges data and relations from another object of same class,
without conflict resolution. Allows to specify which
dataset takes priority in case its not empty.
has_one-relations are just transferred with priority 'right'.
has_many and many_many-relations are added regardless of priority.
Caution: has_many/many_many relations are moved rather than duplicated,
meaning they are not connected to the merged object any longer.
Caution: Just saves updated has_many/many_many relations to the database,
doesn't write the updated object itself (just writes the object-properties).
Caution: Does not delete the merged object.
Caution: Does now overwrite Created date on the original object.
@param DataObject $rightObj
@param string $priority left|right Determines who wins in case of a conflict (optional)
@param bool $includeRelations Merge any existing relations (optional)
@param bool $overwriteWithEmpty Overwrite existing left values with empty right values.
Only applicable with $priority='right'. (optional)
@return Boolean | [
"Merges",
"data",
"and",
"relations",
"from",
"another",
"object",
"of",
"same",
"class",
"without",
"conflict",
"resolution",
".",
"Allows",
"to",
"specify",
"which",
"dataset",
"takes",
"priority",
"in",
"case",
"its",
"not",
"empty",
".",
"has_one",
"-",
"relations",
"are",
"just",
"transferred",
"with",
"priority",
"right",
".",
"has_many",
"and",
"many_many",
"-",
"relations",
"are",
"added",
"regardless",
"of",
"priority",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1049-L1120 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.forceChange | public function forceChange()
{
// Ensure lazy fields loaded
$this->loadLazyFields();
// Populate the null values in record so that they actually get written
foreach (array_keys(static::getSchema()->fieldSpecs(static::class)) as $fieldName) {
if (!isset($this->record[$fieldName])) {
$this->record[$fieldName] = null;
}
}
$this->changeForced = true;
return $this;
} | php | public function forceChange()
{
// Ensure lazy fields loaded
$this->loadLazyFields();
// Populate the null values in record so that they actually get written
foreach (array_keys(static::getSchema()->fieldSpecs(static::class)) as $fieldName) {
if (!isset($this->record[$fieldName])) {
$this->record[$fieldName] = null;
}
}
$this->changeForced = true;
return $this;
} | [
"public",
"function",
"forceChange",
"(",
")",
"{",
"// Ensure lazy fields loaded",
"$",
"this",
"->",
"loadLazyFields",
"(",
")",
";",
"// Populate the null values in record so that they actually get written",
"foreach",
"(",
"array_keys",
"(",
"static",
"::",
"getSchema",
"(",
")",
"->",
"fieldSpecs",
"(",
"static",
"::",
"class",
")",
")",
"as",
"$",
"fieldName",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"record",
"[",
"$",
"fieldName",
"]",
")",
")",
"{",
"$",
"this",
"->",
"record",
"[",
"$",
"fieldName",
"]",
"=",
"null",
";",
"}",
"}",
"$",
"this",
"->",
"changeForced",
"=",
"true",
";",
"return",
"$",
"this",
";",
"}"
]
| Forces the record to think that all its data has changed.
Doesn't write to the database. Force-change preseved until
next write. Existing CHANGE_VALUE or CHANGE_STRICT values
are preserved.
@return $this | [
"Forces",
"the",
"record",
"to",
"think",
"that",
"all",
"its",
"data",
"has",
"changed",
".",
"Doesn",
"t",
"write",
"to",
"the",
"database",
".",
"Force",
"-",
"change",
"preseved",
"until",
"next",
"write",
".",
"Existing",
"CHANGE_VALUE",
"or",
"CHANGE_STRICT",
"values",
"are",
"preserved",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1130-L1145 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.validateWrite | protected function validateWrite()
{
if ($this->ObsoleteClassName) {
return new ValidationException(
"Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " .
"you need to change the ClassName before you can write it"
);
}
// Note: Validation can only be disabled at the global level, not per-model
if (DataObject::config()->uninherited('validation_enabled')) {
$result = $this->validate();
if (!$result->isValid()) {
return new ValidationException($result);
}
}
return null;
} | php | protected function validateWrite()
{
if ($this->ObsoleteClassName) {
return new ValidationException(
"Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " .
"you need to change the ClassName before you can write it"
);
}
// Note: Validation can only be disabled at the global level, not per-model
if (DataObject::config()->uninherited('validation_enabled')) {
$result = $this->validate();
if (!$result->isValid()) {
return new ValidationException($result);
}
}
return null;
} | [
"protected",
"function",
"validateWrite",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ObsoleteClassName",
")",
"{",
"return",
"new",
"ValidationException",
"(",
"\"Object is of class '{$this->ObsoleteClassName}' which doesn't exist - \"",
".",
"\"you need to change the ClassName before you can write it\"",
")",
";",
"}",
"// Note: Validation can only be disabled at the global level, not per-model",
"if",
"(",
"DataObject",
"::",
"config",
"(",
")",
"->",
"uninherited",
"(",
"'validation_enabled'",
")",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"validate",
"(",
")",
";",
"if",
"(",
"!",
"$",
"result",
"->",
"isValid",
"(",
")",
")",
"{",
"return",
"new",
"ValidationException",
"(",
"$",
"result",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Determine validation of this object prior to write
@return ValidationException Exception generated by this write, or null if valid | [
"Determine",
"validation",
"of",
"this",
"object",
"prior",
"to",
"write"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1305-L1322 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.preWrite | protected function preWrite()
{
// Validate this object
if ($writeException = $this->validateWrite()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->invokeWithExtensions('onAfterSkippedWrite');
throw $writeException;
}
// Check onBeforeWrite
$this->brokenOnWrite = true;
$this->onBeforeWrite();
if ($this->brokenOnWrite) {
user_error(static::class . " has a broken onBeforeWrite() function."
. " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
} | php | protected function preWrite()
{
// Validate this object
if ($writeException = $this->validateWrite()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->invokeWithExtensions('onAfterSkippedWrite');
throw $writeException;
}
// Check onBeforeWrite
$this->brokenOnWrite = true;
$this->onBeforeWrite();
if ($this->brokenOnWrite) {
user_error(static::class . " has a broken onBeforeWrite() function."
. " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
} | [
"protected",
"function",
"preWrite",
"(",
")",
"{",
"// Validate this object",
"if",
"(",
"$",
"writeException",
"=",
"$",
"this",
"->",
"validateWrite",
"(",
")",
")",
"{",
"// Used by DODs to clean up after themselves, eg, Versioned",
"$",
"this",
"->",
"invokeWithExtensions",
"(",
"'onAfterSkippedWrite'",
")",
";",
"throw",
"$",
"writeException",
";",
"}",
"// Check onBeforeWrite",
"$",
"this",
"->",
"brokenOnWrite",
"=",
"true",
";",
"$",
"this",
"->",
"onBeforeWrite",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"brokenOnWrite",
")",
"{",
"user_error",
"(",
"static",
"::",
"class",
".",
"\" has a broken onBeforeWrite() function.\"",
".",
"\" Make sure that you call parent::onBeforeWrite().\"",
",",
"E_USER_ERROR",
")",
";",
"}",
"}"
]
| Prepare an object prior to write
@throws ValidationException | [
"Prepare",
"an",
"object",
"prior",
"to",
"write"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1329-L1345 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.updateChanges | protected function updateChanges($forceChanges = false)
{
if ($forceChanges) {
// Force changes, but only for loaded fields
foreach ($this->record as $field => $value) {
$this->changed[$field] = static::CHANGE_VALUE;
}
return true;
}
return $this->isChanged();
} | php | protected function updateChanges($forceChanges = false)
{
if ($forceChanges) {
// Force changes, but only for loaded fields
foreach ($this->record as $field => $value) {
$this->changed[$field] = static::CHANGE_VALUE;
}
return true;
}
return $this->isChanged();
} | [
"protected",
"function",
"updateChanges",
"(",
"$",
"forceChanges",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"forceChanges",
")",
"{",
"// Force changes, but only for loaded fields",
"foreach",
"(",
"$",
"this",
"->",
"record",
"as",
"$",
"field",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"changed",
"[",
"$",
"field",
"]",
"=",
"static",
"::",
"CHANGE_VALUE",
";",
"}",
"return",
"true",
";",
"}",
"return",
"$",
"this",
"->",
"isChanged",
"(",
")",
";",
"}"
]
| Detects and updates all changes made to this object
@param bool $forceChanges If set to true, force all fields to be treated as changed
@return bool True if any changes are detected | [
"Detects",
"and",
"updates",
"all",
"changes",
"made",
"to",
"this",
"object"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1353-L1363 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.prepareManipulationTable | protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class)
{
$schema = $this->getSchema();
$table = $schema->tableName($class);
$manipulation[$table] = array();
$changed = $this->getChangedFields();
// Extract records for this table
foreach ($this->record as $fieldName => $fieldValue) {
// we're not attempting to reset the BaseTable->ID
// Ignore unchanged fields or attempts to reset the BaseTable->ID
if (empty($changed[$fieldName]) || ($table === $baseTable && $fieldName === 'ID')) {
continue;
}
// Ensure this field pertains to this table
$specification = $schema->fieldSpec(
$class,
$fieldName,
DataObjectSchema::DB_ONLY | DataObjectSchema::UNINHERITED
);
if (!$specification) {
continue;
}
// if database column doesn't correlate to a DBField instance...
$fieldObj = $this->dbObject($fieldName);
if (!$fieldObj) {
$fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
}
// Write to manipulation
$fieldObj->writeToManipulation($manipulation[$table]);
}
// Ensure update of Created and LastEdited columns
if ($baseTable === $table) {
$manipulation[$table]['fields']['LastEdited'] = $now;
if ($isNewRecord) {
$manipulation[$table]['fields']['Created'] = empty($this->record['Created'])
? $now
: $this->record['Created'];
$manipulation[$table]['fields']['ClassName'] = static::class;
}
}
// Inserts done one the base table are performed in another step, so the manipulation should instead
// attempt an update, as though it were a normal update.
$manipulation[$table]['command'] = $isNewRecord ? 'insert' : 'update';
$manipulation[$table]['class'] = $class;
if ($this->isInDB()) {
$manipulation[$table]['id'] = $this->record['ID'];
}
} | php | protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class)
{
$schema = $this->getSchema();
$table = $schema->tableName($class);
$manipulation[$table] = array();
$changed = $this->getChangedFields();
// Extract records for this table
foreach ($this->record as $fieldName => $fieldValue) {
// we're not attempting to reset the BaseTable->ID
// Ignore unchanged fields or attempts to reset the BaseTable->ID
if (empty($changed[$fieldName]) || ($table === $baseTable && $fieldName === 'ID')) {
continue;
}
// Ensure this field pertains to this table
$specification = $schema->fieldSpec(
$class,
$fieldName,
DataObjectSchema::DB_ONLY | DataObjectSchema::UNINHERITED
);
if (!$specification) {
continue;
}
// if database column doesn't correlate to a DBField instance...
$fieldObj = $this->dbObject($fieldName);
if (!$fieldObj) {
$fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
}
// Write to manipulation
$fieldObj->writeToManipulation($manipulation[$table]);
}
// Ensure update of Created and LastEdited columns
if ($baseTable === $table) {
$manipulation[$table]['fields']['LastEdited'] = $now;
if ($isNewRecord) {
$manipulation[$table]['fields']['Created'] = empty($this->record['Created'])
? $now
: $this->record['Created'];
$manipulation[$table]['fields']['ClassName'] = static::class;
}
}
// Inserts done one the base table are performed in another step, so the manipulation should instead
// attempt an update, as though it were a normal update.
$manipulation[$table]['command'] = $isNewRecord ? 'insert' : 'update';
$manipulation[$table]['class'] = $class;
if ($this->isInDB()) {
$manipulation[$table]['id'] = $this->record['ID'];
}
} | [
"protected",
"function",
"prepareManipulationTable",
"(",
"$",
"baseTable",
",",
"$",
"now",
",",
"$",
"isNewRecord",
",",
"&",
"$",
"manipulation",
",",
"$",
"class",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"getSchema",
"(",
")",
";",
"$",
"table",
"=",
"$",
"schema",
"->",
"tableName",
"(",
"$",
"class",
")",
";",
"$",
"manipulation",
"[",
"$",
"table",
"]",
"=",
"array",
"(",
")",
";",
"$",
"changed",
"=",
"$",
"this",
"->",
"getChangedFields",
"(",
")",
";",
"// Extract records for this table",
"foreach",
"(",
"$",
"this",
"->",
"record",
"as",
"$",
"fieldName",
"=>",
"$",
"fieldValue",
")",
"{",
"// we're not attempting to reset the BaseTable->ID",
"// Ignore unchanged fields or attempts to reset the BaseTable->ID",
"if",
"(",
"empty",
"(",
"$",
"changed",
"[",
"$",
"fieldName",
"]",
")",
"||",
"(",
"$",
"table",
"===",
"$",
"baseTable",
"&&",
"$",
"fieldName",
"===",
"'ID'",
")",
")",
"{",
"continue",
";",
"}",
"// Ensure this field pertains to this table",
"$",
"specification",
"=",
"$",
"schema",
"->",
"fieldSpec",
"(",
"$",
"class",
",",
"$",
"fieldName",
",",
"DataObjectSchema",
"::",
"DB_ONLY",
"|",
"DataObjectSchema",
"::",
"UNINHERITED",
")",
";",
"if",
"(",
"!",
"$",
"specification",
")",
"{",
"continue",
";",
"}",
"// if database column doesn't correlate to a DBField instance...",
"$",
"fieldObj",
"=",
"$",
"this",
"->",
"dbObject",
"(",
"$",
"fieldName",
")",
";",
"if",
"(",
"!",
"$",
"fieldObj",
")",
"{",
"$",
"fieldObj",
"=",
"DBField",
"::",
"create_field",
"(",
"'Varchar'",
",",
"$",
"fieldValue",
",",
"$",
"fieldName",
")",
";",
"}",
"// Write to manipulation",
"$",
"fieldObj",
"->",
"writeToManipulation",
"(",
"$",
"manipulation",
"[",
"$",
"table",
"]",
")",
";",
"}",
"// Ensure update of Created and LastEdited columns",
"if",
"(",
"$",
"baseTable",
"===",
"$",
"table",
")",
"{",
"$",
"manipulation",
"[",
"$",
"table",
"]",
"[",
"'fields'",
"]",
"[",
"'LastEdited'",
"]",
"=",
"$",
"now",
";",
"if",
"(",
"$",
"isNewRecord",
")",
"{",
"$",
"manipulation",
"[",
"$",
"table",
"]",
"[",
"'fields'",
"]",
"[",
"'Created'",
"]",
"=",
"empty",
"(",
"$",
"this",
"->",
"record",
"[",
"'Created'",
"]",
")",
"?",
"$",
"now",
":",
"$",
"this",
"->",
"record",
"[",
"'Created'",
"]",
";",
"$",
"manipulation",
"[",
"$",
"table",
"]",
"[",
"'fields'",
"]",
"[",
"'ClassName'",
"]",
"=",
"static",
"::",
"class",
";",
"}",
"}",
"// Inserts done one the base table are performed in another step, so the manipulation should instead",
"// attempt an update, as though it were a normal update.",
"$",
"manipulation",
"[",
"$",
"table",
"]",
"[",
"'command'",
"]",
"=",
"$",
"isNewRecord",
"?",
"'insert'",
":",
"'update'",
";",
"$",
"manipulation",
"[",
"$",
"table",
"]",
"[",
"'class'",
"]",
"=",
"$",
"class",
";",
"if",
"(",
"$",
"this",
"->",
"isInDB",
"(",
")",
")",
"{",
"$",
"manipulation",
"[",
"$",
"table",
"]",
"[",
"'id'",
"]",
"=",
"$",
"this",
"->",
"record",
"[",
"'ID'",
"]",
";",
"}",
"}"
]
| Writes a subset of changes for a specific table to the given manipulation
@param string $baseTable Base table
@param string $now Timestamp to use for the current time
@param bool $isNewRecord Whether this should be treated as a new record write
@param array $manipulation Manipulation to write to
@param string $class Class of table to manipulate | [
"Writes",
"a",
"subset",
"of",
"changes",
"for",
"a",
"specific",
"table",
"to",
"the",
"given",
"manipulation"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1374-L1428 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.writeBaseRecord | protected function writeBaseRecord($baseTable, $now)
{
// Generate new ID if not specified
if ($this->isInDB()) {
return;
}
// Perform an insert on the base table
$manipulation = [];
$this->prepareManipulationTable($baseTable, $now, true, $manipulation, $this->baseClass());
DB::manipulate($manipulation);
$this->changed['ID'] = self::CHANGE_VALUE;
$this->record['ID'] = DB::get_generated_id($baseTable);
} | php | protected function writeBaseRecord($baseTable, $now)
{
// Generate new ID if not specified
if ($this->isInDB()) {
return;
}
// Perform an insert on the base table
$manipulation = [];
$this->prepareManipulationTable($baseTable, $now, true, $manipulation, $this->baseClass());
DB::manipulate($manipulation);
$this->changed['ID'] = self::CHANGE_VALUE;
$this->record['ID'] = DB::get_generated_id($baseTable);
} | [
"protected",
"function",
"writeBaseRecord",
"(",
"$",
"baseTable",
",",
"$",
"now",
")",
"{",
"// Generate new ID if not specified",
"if",
"(",
"$",
"this",
"->",
"isInDB",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Perform an insert on the base table",
"$",
"manipulation",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"prepareManipulationTable",
"(",
"$",
"baseTable",
",",
"$",
"now",
",",
"true",
",",
"$",
"manipulation",
",",
"$",
"this",
"->",
"baseClass",
"(",
")",
")",
";",
"DB",
"::",
"manipulate",
"(",
"$",
"manipulation",
")",
";",
"$",
"this",
"->",
"changed",
"[",
"'ID'",
"]",
"=",
"self",
"::",
"CHANGE_VALUE",
";",
"$",
"this",
"->",
"record",
"[",
"'ID'",
"]",
"=",
"DB",
"::",
"get_generated_id",
"(",
"$",
"baseTable",
")",
";",
"}"
]
| Ensures that a blank base record exists with the basic fixed fields for this dataobject
Does nothing if an ID is already assigned for this record
@param string $baseTable Base table
@param string $now Timestamp to use for the current time | [
"Ensures",
"that",
"a",
"blank",
"base",
"record",
"exists",
"with",
"the",
"basic",
"fixed",
"fields",
"for",
"this",
"dataobject"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1438-L1452 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.writeManipulation | protected function writeManipulation($baseTable, $now, $isNewRecord)
{
// Generate database manipulations for each class
$manipulation = array();
foreach (ClassInfo::ancestry(static::class, true) as $class) {
$this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
}
// Allow extensions to extend this manipulation
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if ($isNewRecord) {
$manipulation[$baseTable]['command'] = 'update';
}
// Make sure none of our field assignment are arrays
foreach ($manipulation as $tableManipulation) {
if (!isset($tableManipulation['fields'])) {
continue;
}
foreach ($tableManipulation['fields'] as $fieldName => $fieldValue) {
if (is_array($fieldValue)) {
$dbObject = $this->dbObject($fieldName);
// If the field allows non-scalar values we'll let it do dynamic assignments
if ($dbObject && $dbObject->scalarValueOnly()) {
throw new InvalidArgumentException(
'DataObject::writeManipulation: parameterised field assignments are disallowed'
);
}
}
}
}
// Perform the manipulation
DB::manipulate($manipulation);
} | php | protected function writeManipulation($baseTable, $now, $isNewRecord)
{
// Generate database manipulations for each class
$manipulation = array();
foreach (ClassInfo::ancestry(static::class, true) as $class) {
$this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
}
// Allow extensions to extend this manipulation
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if ($isNewRecord) {
$manipulation[$baseTable]['command'] = 'update';
}
// Make sure none of our field assignment are arrays
foreach ($manipulation as $tableManipulation) {
if (!isset($tableManipulation['fields'])) {
continue;
}
foreach ($tableManipulation['fields'] as $fieldName => $fieldValue) {
if (is_array($fieldValue)) {
$dbObject = $this->dbObject($fieldName);
// If the field allows non-scalar values we'll let it do dynamic assignments
if ($dbObject && $dbObject->scalarValueOnly()) {
throw new InvalidArgumentException(
'DataObject::writeManipulation: parameterised field assignments are disallowed'
);
}
}
}
}
// Perform the manipulation
DB::manipulate($manipulation);
} | [
"protected",
"function",
"writeManipulation",
"(",
"$",
"baseTable",
",",
"$",
"now",
",",
"$",
"isNewRecord",
")",
"{",
"// Generate database manipulations for each class",
"$",
"manipulation",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"ClassInfo",
"::",
"ancestry",
"(",
"static",
"::",
"class",
",",
"true",
")",
"as",
"$",
"class",
")",
"{",
"$",
"this",
"->",
"prepareManipulationTable",
"(",
"$",
"baseTable",
",",
"$",
"now",
",",
"$",
"isNewRecord",
",",
"$",
"manipulation",
",",
"$",
"class",
")",
";",
"}",
"// Allow extensions to extend this manipulation",
"$",
"this",
"->",
"extend",
"(",
"'augmentWrite'",
",",
"$",
"manipulation",
")",
";",
"// New records have their insert into the base data table done first, so that they can pass the",
"// generated ID on to the rest of the manipulation",
"if",
"(",
"$",
"isNewRecord",
")",
"{",
"$",
"manipulation",
"[",
"$",
"baseTable",
"]",
"[",
"'command'",
"]",
"=",
"'update'",
";",
"}",
"// Make sure none of our field assignment are arrays",
"foreach",
"(",
"$",
"manipulation",
"as",
"$",
"tableManipulation",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"tableManipulation",
"[",
"'fields'",
"]",
")",
")",
"{",
"continue",
";",
"}",
"foreach",
"(",
"$",
"tableManipulation",
"[",
"'fields'",
"]",
"as",
"$",
"fieldName",
"=>",
"$",
"fieldValue",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"fieldValue",
")",
")",
"{",
"$",
"dbObject",
"=",
"$",
"this",
"->",
"dbObject",
"(",
"$",
"fieldName",
")",
";",
"// If the field allows non-scalar values we'll let it do dynamic assignments",
"if",
"(",
"$",
"dbObject",
"&&",
"$",
"dbObject",
"->",
"scalarValueOnly",
"(",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'DataObject::writeManipulation: parameterised field assignments are disallowed'",
")",
";",
"}",
"}",
"}",
"}",
"// Perform the manipulation",
"DB",
"::",
"manipulate",
"(",
"$",
"manipulation",
")",
";",
"}"
]
| Generate and write the database manipulation for all changed fields
@param string $baseTable Base table
@param string $now Timestamp to use for the current time
@param bool $isNewRecord If this is a new record
@throws InvalidArgumentException | [
"Generate",
"and",
"write",
"the",
"database",
"manipulation",
"for",
"all",
"changed",
"fields"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1462-L1499 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.writeRelations | public function writeRelations()
{
if (!$this->isInDB()) {
return;
}
// If there's any relations that couldn't be saved before, save them now (we have an ID here)
if ($this->unsavedRelations) {
foreach ($this->unsavedRelations as $name => $list) {
$list->changeToList($this->$name());
}
$this->unsavedRelations = array();
}
} | php | public function writeRelations()
{
if (!$this->isInDB()) {
return;
}
// If there's any relations that couldn't be saved before, save them now (we have an ID here)
if ($this->unsavedRelations) {
foreach ($this->unsavedRelations as $name => $list) {
$list->changeToList($this->$name());
}
$this->unsavedRelations = array();
}
} | [
"public",
"function",
"writeRelations",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isInDB",
"(",
")",
")",
"{",
"return",
";",
"}",
"// If there's any relations that couldn't be saved before, save them now (we have an ID here)",
"if",
"(",
"$",
"this",
"->",
"unsavedRelations",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"unsavedRelations",
"as",
"$",
"name",
"=>",
"$",
"list",
")",
"{",
"$",
"list",
"->",
"changeToList",
"(",
"$",
"this",
"->",
"$",
"name",
"(",
")",
")",
";",
"}",
"$",
"this",
"->",
"unsavedRelations",
"=",
"array",
"(",
")",
";",
"}",
"}"
]
| Writes cached relation lists to the database, if possible | [
"Writes",
"cached",
"relation",
"lists",
"to",
"the",
"database",
"if",
"possible"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1578-L1591 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.writeComponents | public function writeComponents($recursive = false)
{
foreach ($this->components as $component) {
$component->write(false, false, false, $recursive);
}
if ($join = $this->getJoin()) {
$join->write(false, false, false, $recursive);
}
return $this;
} | php | public function writeComponents($recursive = false)
{
foreach ($this->components as $component) {
$component->write(false, false, false, $recursive);
}
if ($join = $this->getJoin()) {
$join->write(false, false, false, $recursive);
}
return $this;
} | [
"public",
"function",
"writeComponents",
"(",
"$",
"recursive",
"=",
"false",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"components",
"as",
"$",
"component",
")",
"{",
"$",
"component",
"->",
"write",
"(",
"false",
",",
"false",
",",
"false",
",",
"$",
"recursive",
")",
";",
"}",
"if",
"(",
"$",
"join",
"=",
"$",
"this",
"->",
"getJoin",
"(",
")",
")",
"{",
"$",
"join",
"->",
"write",
"(",
"false",
",",
"false",
",",
"false",
",",
"$",
"recursive",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Write the cached components to the database. Cached components could refer to two different instances of the
same record.
@param bool $recursive Recursively write components
@return DataObject $this | [
"Write",
"the",
"cached",
"components",
"to",
"the",
"database",
".",
"Cached",
"components",
"could",
"refer",
"to",
"two",
"different",
"instances",
"of",
"the",
"same",
"record",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1600-L1611 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.delete_by_id | public static function delete_by_id($className, $id)
{
$obj = DataObject::get_by_id($className, $id);
if ($obj) {
$obj->delete();
} else {
user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
}
} | php | public static function delete_by_id($className, $id)
{
$obj = DataObject::get_by_id($className, $id);
if ($obj) {
$obj->delete();
} else {
user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
}
} | [
"public",
"static",
"function",
"delete_by_id",
"(",
"$",
"className",
",",
"$",
"id",
")",
"{",
"$",
"obj",
"=",
"DataObject",
"::",
"get_by_id",
"(",
"$",
"className",
",",
"$",
"id",
")",
";",
"if",
"(",
"$",
"obj",
")",
"{",
"$",
"obj",
"->",
"delete",
"(",
")",
";",
"}",
"else",
"{",
"user_error",
"(",
"\"$className object #$id wasn't found when calling DataObject::delete_by_id\"",
",",
"E_USER_WARNING",
")",
";",
"}",
"}"
]
| Delete the record with the given ID.
@param string $className The class name of the record to be deleted
@param int $id ID of record to be deleted | [
"Delete",
"the",
"record",
"with",
"the",
"given",
"ID",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1663-L1671 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.getComponent | public function getComponent($componentName)
{
if (isset($this->components[$componentName])) {
return $this->components[$componentName];
}
$schema = static::getSchema();
if ($class = $schema->hasOneComponent(static::class, $componentName)) {
$joinField = $componentName . 'ID';
$joinID = $this->getField($joinField);
// Extract class name for polymorphic relations
if ($class === self::class) {
$class = $this->getField($componentName . 'Class');
if (empty($class)) {
return null;
}
}
if ($joinID) {
// Ensure that the selected object originates from the same stage, subsite, etc
$component = DataObject::get($class)
->filter('ID', $joinID)
->setDataQueryParam($this->getInheritableQueryParams())
->first();
}
if (empty($component)) {
$component = Injector::inst()->create($class);
}
} elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
$joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
$joinID = $this->ID;
if ($joinID) {
// Prepare filter for appropriate join type
if ($polymorphic) {
$filter = array(
"{$joinField}ID" => $joinID,
"{$joinField}Class" => static::class,
);
} else {
$filter = array(
$joinField => $joinID
);
}
// Ensure that the selected object originates from the same stage, subsite, etc
$component = DataObject::get($class)
->filter($filter)
->setDataQueryParam($this->getInheritableQueryParams())
->first();
}
if (empty($component)) {
$component = Injector::inst()->create($class);
if ($polymorphic) {
$component->{$joinField . 'ID'} = $this->ID;
$component->{$joinField . 'Class'} = static::class;
} else {
$component->$joinField = $this->ID;
}
}
} else {
throw new InvalidArgumentException(
"DataObject->getComponent(): Could not find component '$componentName'."
);
}
$this->components[$componentName] = $component;
return $component;
} | php | public function getComponent($componentName)
{
if (isset($this->components[$componentName])) {
return $this->components[$componentName];
}
$schema = static::getSchema();
if ($class = $schema->hasOneComponent(static::class, $componentName)) {
$joinField = $componentName . 'ID';
$joinID = $this->getField($joinField);
// Extract class name for polymorphic relations
if ($class === self::class) {
$class = $this->getField($componentName . 'Class');
if (empty($class)) {
return null;
}
}
if ($joinID) {
// Ensure that the selected object originates from the same stage, subsite, etc
$component = DataObject::get($class)
->filter('ID', $joinID)
->setDataQueryParam($this->getInheritableQueryParams())
->first();
}
if (empty($component)) {
$component = Injector::inst()->create($class);
}
} elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
$joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
$joinID = $this->ID;
if ($joinID) {
// Prepare filter for appropriate join type
if ($polymorphic) {
$filter = array(
"{$joinField}ID" => $joinID,
"{$joinField}Class" => static::class,
);
} else {
$filter = array(
$joinField => $joinID
);
}
// Ensure that the selected object originates from the same stage, subsite, etc
$component = DataObject::get($class)
->filter($filter)
->setDataQueryParam($this->getInheritableQueryParams())
->first();
}
if (empty($component)) {
$component = Injector::inst()->create($class);
if ($polymorphic) {
$component->{$joinField . 'ID'} = $this->ID;
$component->{$joinField . 'Class'} = static::class;
} else {
$component->$joinField = $this->ID;
}
}
} else {
throw new InvalidArgumentException(
"DataObject->getComponent(): Could not find component '$componentName'."
);
}
$this->components[$componentName] = $component;
return $component;
} | [
"public",
"function",
"getComponent",
"(",
"$",
"componentName",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"components",
"[",
"$",
"componentName",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"components",
"[",
"$",
"componentName",
"]",
";",
"}",
"$",
"schema",
"=",
"static",
"::",
"getSchema",
"(",
")",
";",
"if",
"(",
"$",
"class",
"=",
"$",
"schema",
"->",
"hasOneComponent",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
")",
")",
"{",
"$",
"joinField",
"=",
"$",
"componentName",
".",
"'ID'",
";",
"$",
"joinID",
"=",
"$",
"this",
"->",
"getField",
"(",
"$",
"joinField",
")",
";",
"// Extract class name for polymorphic relations",
"if",
"(",
"$",
"class",
"===",
"self",
"::",
"class",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getField",
"(",
"$",
"componentName",
".",
"'Class'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"class",
")",
")",
"{",
"return",
"null",
";",
"}",
"}",
"if",
"(",
"$",
"joinID",
")",
"{",
"// Ensure that the selected object originates from the same stage, subsite, etc",
"$",
"component",
"=",
"DataObject",
"::",
"get",
"(",
"$",
"class",
")",
"->",
"filter",
"(",
"'ID'",
",",
"$",
"joinID",
")",
"->",
"setDataQueryParam",
"(",
"$",
"this",
"->",
"getInheritableQueryParams",
"(",
")",
")",
"->",
"first",
"(",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"component",
")",
")",
"{",
"$",
"component",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"class",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"class",
"=",
"$",
"schema",
"->",
"belongsToComponent",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
")",
")",
"{",
"$",
"joinField",
"=",
"$",
"schema",
"->",
"getRemoteJoinField",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
",",
"'belongs_to'",
",",
"$",
"polymorphic",
")",
";",
"$",
"joinID",
"=",
"$",
"this",
"->",
"ID",
";",
"if",
"(",
"$",
"joinID",
")",
"{",
"// Prepare filter for appropriate join type",
"if",
"(",
"$",
"polymorphic",
")",
"{",
"$",
"filter",
"=",
"array",
"(",
"\"{$joinField}ID\"",
"=>",
"$",
"joinID",
",",
"\"{$joinField}Class\"",
"=>",
"static",
"::",
"class",
",",
")",
";",
"}",
"else",
"{",
"$",
"filter",
"=",
"array",
"(",
"$",
"joinField",
"=>",
"$",
"joinID",
")",
";",
"}",
"// Ensure that the selected object originates from the same stage, subsite, etc",
"$",
"component",
"=",
"DataObject",
"::",
"get",
"(",
"$",
"class",
")",
"->",
"filter",
"(",
"$",
"filter",
")",
"->",
"setDataQueryParam",
"(",
"$",
"this",
"->",
"getInheritableQueryParams",
"(",
")",
")",
"->",
"first",
"(",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"component",
")",
")",
"{",
"$",
"component",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"class",
")",
";",
"if",
"(",
"$",
"polymorphic",
")",
"{",
"$",
"component",
"->",
"{",
"$",
"joinField",
".",
"'ID'",
"}",
"=",
"$",
"this",
"->",
"ID",
";",
"$",
"component",
"->",
"{",
"$",
"joinField",
".",
"'Class'",
"}",
"=",
"static",
"::",
"class",
";",
"}",
"else",
"{",
"$",
"component",
"->",
"$",
"joinField",
"=",
"$",
"this",
"->",
"ID",
";",
"}",
"}",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"DataObject->getComponent(): Could not find component '$componentName'.\"",
")",
";",
"}",
"$",
"this",
"->",
"components",
"[",
"$",
"componentName",
"]",
"=",
"$",
"component",
";",
"return",
"$",
"component",
";",
"}"
]
| Return a unary component object from a one to one relationship, as a DataObject.
If no component is available, an 'empty component' will be returned for
non-polymorphic relations, or for polymorphic relations with a class set.
@param string $componentName Name of the component
@return DataObject The component object. It's exact type will be that of the component.
@throws Exception | [
"Return",
"a",
"unary",
"component",
"object",
"from",
"a",
"one",
"to",
"one",
"relationship",
"as",
"a",
"DataObject",
".",
"If",
"no",
"component",
"is",
"available",
"an",
"empty",
"component",
"will",
"be",
"returned",
"for",
"non",
"-",
"polymorphic",
"relations",
"or",
"for",
"polymorphic",
"relations",
"with",
"a",
"class",
"set",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1695-L1766 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.setComponent | public function setComponent($componentName, $item)
{
// Validate component
$schema = static::getSchema();
if ($class = $schema->hasOneComponent(static::class, $componentName)) {
// Force item to be written if not by this point
// @todo This could be lazy-written in a beforeWrite hook, but force write here for simplicity
// https://github.com/silverstripe/silverstripe-framework/issues/7818
if ($item && !$item->isInDB()) {
$item->write();
}
// Update local ID
$joinField = $componentName . 'ID';
$this->setField($joinField, $item ? $item->ID : null);
// Update Class (Polymorphic has_one)
// Extract class name for polymorphic relations
if ($class === self::class) {
$this->setField($componentName . 'Class', $item ? get_class($item) : null);
}
} elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
if ($item) {
// For belongs_to, add to has_one on other component
$joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
if (!$polymorphic) {
$joinField = substr($joinField, 0, -2);
}
$item->setComponent($joinField, $this);
}
} else {
throw new InvalidArgumentException(
"DataObject->setComponent(): Could not find component '$componentName'."
);
}
$this->components[$componentName] = $item;
return $this;
} | php | public function setComponent($componentName, $item)
{
// Validate component
$schema = static::getSchema();
if ($class = $schema->hasOneComponent(static::class, $componentName)) {
// Force item to be written if not by this point
// @todo This could be lazy-written in a beforeWrite hook, but force write here for simplicity
// https://github.com/silverstripe/silverstripe-framework/issues/7818
if ($item && !$item->isInDB()) {
$item->write();
}
// Update local ID
$joinField = $componentName . 'ID';
$this->setField($joinField, $item ? $item->ID : null);
// Update Class (Polymorphic has_one)
// Extract class name for polymorphic relations
if ($class === self::class) {
$this->setField($componentName . 'Class', $item ? get_class($item) : null);
}
} elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
if ($item) {
// For belongs_to, add to has_one on other component
$joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
if (!$polymorphic) {
$joinField = substr($joinField, 0, -2);
}
$item->setComponent($joinField, $this);
}
} else {
throw new InvalidArgumentException(
"DataObject->setComponent(): Could not find component '$componentName'."
);
}
$this->components[$componentName] = $item;
return $this;
} | [
"public",
"function",
"setComponent",
"(",
"$",
"componentName",
",",
"$",
"item",
")",
"{",
"// Validate component",
"$",
"schema",
"=",
"static",
"::",
"getSchema",
"(",
")",
";",
"if",
"(",
"$",
"class",
"=",
"$",
"schema",
"->",
"hasOneComponent",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
")",
")",
"{",
"// Force item to be written if not by this point",
"// @todo This could be lazy-written in a beforeWrite hook, but force write here for simplicity",
"// https://github.com/silverstripe/silverstripe-framework/issues/7818",
"if",
"(",
"$",
"item",
"&&",
"!",
"$",
"item",
"->",
"isInDB",
"(",
")",
")",
"{",
"$",
"item",
"->",
"write",
"(",
")",
";",
"}",
"// Update local ID",
"$",
"joinField",
"=",
"$",
"componentName",
".",
"'ID'",
";",
"$",
"this",
"->",
"setField",
"(",
"$",
"joinField",
",",
"$",
"item",
"?",
"$",
"item",
"->",
"ID",
":",
"null",
")",
";",
"// Update Class (Polymorphic has_one)",
"// Extract class name for polymorphic relations",
"if",
"(",
"$",
"class",
"===",
"self",
"::",
"class",
")",
"{",
"$",
"this",
"->",
"setField",
"(",
"$",
"componentName",
".",
"'Class'",
",",
"$",
"item",
"?",
"get_class",
"(",
"$",
"item",
")",
":",
"null",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"class",
"=",
"$",
"schema",
"->",
"belongsToComponent",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
")",
")",
"{",
"if",
"(",
"$",
"item",
")",
"{",
"// For belongs_to, add to has_one on other component",
"$",
"joinField",
"=",
"$",
"schema",
"->",
"getRemoteJoinField",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
",",
"'belongs_to'",
",",
"$",
"polymorphic",
")",
";",
"if",
"(",
"!",
"$",
"polymorphic",
")",
"{",
"$",
"joinField",
"=",
"substr",
"(",
"$",
"joinField",
",",
"0",
",",
"-",
"2",
")",
";",
"}",
"$",
"item",
"->",
"setComponent",
"(",
"$",
"joinField",
",",
"$",
"this",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"DataObject->setComponent(): Could not find component '$componentName'.\"",
")",
";",
"}",
"$",
"this",
"->",
"components",
"[",
"$",
"componentName",
"]",
"=",
"$",
"item",
";",
"return",
"$",
"this",
";",
"}"
]
| Assign an item to the given component
@param string $componentName
@param DataObject|null $item
@return $this | [
"Assign",
"an",
"item",
"to",
"the",
"given",
"component"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1775-L1812 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.getComponents | public function getComponents($componentName, $id = null)
{
if (!isset($id)) {
$id = $this->ID;
}
$result = null;
$schema = $this->getSchema();
$componentClass = $schema->hasManyComponent(static::class, $componentName);
if (!$componentClass) {
throw new InvalidArgumentException(sprintf(
"DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
$componentName,
static::class
));
}
// If we haven't been written yet, we can't save these relations, so use a list that handles this case
if (!$id) {
if (!isset($this->unsavedRelations[$componentName])) {
$this->unsavedRelations[$componentName] =
new UnsavedRelationList(static::class, $componentName, $componentClass);
}
return $this->unsavedRelations[$componentName];
}
// Determine type and nature of foreign relation
$joinField = $schema->getRemoteJoinField(static::class, $componentName, 'has_many', $polymorphic);
/** @var HasManyList $result */
if ($polymorphic) {
$result = PolymorphicHasManyList::create($componentClass, $joinField, static::class);
} else {
$result = HasManyList::create($componentClass, $joinField);
}
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($id);
} | php | public function getComponents($componentName, $id = null)
{
if (!isset($id)) {
$id = $this->ID;
}
$result = null;
$schema = $this->getSchema();
$componentClass = $schema->hasManyComponent(static::class, $componentName);
if (!$componentClass) {
throw new InvalidArgumentException(sprintf(
"DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
$componentName,
static::class
));
}
// If we haven't been written yet, we can't save these relations, so use a list that handles this case
if (!$id) {
if (!isset($this->unsavedRelations[$componentName])) {
$this->unsavedRelations[$componentName] =
new UnsavedRelationList(static::class, $componentName, $componentClass);
}
return $this->unsavedRelations[$componentName];
}
// Determine type and nature of foreign relation
$joinField = $schema->getRemoteJoinField(static::class, $componentName, 'has_many', $polymorphic);
/** @var HasManyList $result */
if ($polymorphic) {
$result = PolymorphicHasManyList::create($componentClass, $joinField, static::class);
} else {
$result = HasManyList::create($componentClass, $joinField);
}
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($id);
} | [
"public",
"function",
"getComponents",
"(",
"$",
"componentName",
",",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"id",
")",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"ID",
";",
"}",
"$",
"result",
"=",
"null",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"getSchema",
"(",
")",
";",
"$",
"componentClass",
"=",
"$",
"schema",
"->",
"hasManyComponent",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
")",
";",
"if",
"(",
"!",
"$",
"componentClass",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'\"",
",",
"$",
"componentName",
",",
"static",
"::",
"class",
")",
")",
";",
"}",
"// If we haven't been written yet, we can't save these relations, so use a list that handles this case",
"if",
"(",
"!",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"unsavedRelations",
"[",
"$",
"componentName",
"]",
")",
")",
"{",
"$",
"this",
"->",
"unsavedRelations",
"[",
"$",
"componentName",
"]",
"=",
"new",
"UnsavedRelationList",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
",",
"$",
"componentClass",
")",
";",
"}",
"return",
"$",
"this",
"->",
"unsavedRelations",
"[",
"$",
"componentName",
"]",
";",
"}",
"// Determine type and nature of foreign relation",
"$",
"joinField",
"=",
"$",
"schema",
"->",
"getRemoteJoinField",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
",",
"'has_many'",
",",
"$",
"polymorphic",
")",
";",
"/** @var HasManyList $result */",
"if",
"(",
"$",
"polymorphic",
")",
"{",
"$",
"result",
"=",
"PolymorphicHasManyList",
"::",
"create",
"(",
"$",
"componentClass",
",",
"$",
"joinField",
",",
"static",
"::",
"class",
")",
";",
"}",
"else",
"{",
"$",
"result",
"=",
"HasManyList",
"::",
"create",
"(",
"$",
"componentClass",
",",
"$",
"joinField",
")",
";",
"}",
"return",
"$",
"result",
"->",
"setDataQueryParam",
"(",
"$",
"this",
"->",
"getInheritableQueryParams",
"(",
")",
")",
"->",
"forForeignID",
"(",
"$",
"id",
")",
";",
"}"
]
| Returns a one-to-many relation as a HasManyList
@param string $componentName Name of the component
@param int|array $id Optional ID(s) for parent of this relation, if not the current record
@return HasManyList|UnsavedRelationList The components of the one-to-many relationship. | [
"Returns",
"a",
"one",
"-",
"to",
"-",
"many",
"relation",
"as",
"a",
"HasManyList"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1821-L1859 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.getRelationClass | public function getRelationClass($relationName)
{
// Parse many_many
$manyManyComponent = $this->getSchema()->manyManyComponent(static::class, $relationName);
if ($manyManyComponent) {
return $manyManyComponent['childClass'];
}
// Go through all relationship configuration fields.
$config = $this->config();
$candidates = array_merge(
($relations = $config->get('has_one')) ? $relations : array(),
($relations = $config->get('has_many')) ? $relations : array(),
($relations = $config->get('belongs_to')) ? $relations : array()
);
if (isset($candidates[$relationName])) {
$remoteClass = $candidates[$relationName];
// If dot notation is present, extract just the first part that contains the class.
if (($fieldPos = strpos($remoteClass, '.')) !== false) {
return substr($remoteClass, 0, $fieldPos);
}
// Otherwise just return the class
return $remoteClass;
}
return null;
} | php | public function getRelationClass($relationName)
{
// Parse many_many
$manyManyComponent = $this->getSchema()->manyManyComponent(static::class, $relationName);
if ($manyManyComponent) {
return $manyManyComponent['childClass'];
}
// Go through all relationship configuration fields.
$config = $this->config();
$candidates = array_merge(
($relations = $config->get('has_one')) ? $relations : array(),
($relations = $config->get('has_many')) ? $relations : array(),
($relations = $config->get('belongs_to')) ? $relations : array()
);
if (isset($candidates[$relationName])) {
$remoteClass = $candidates[$relationName];
// If dot notation is present, extract just the first part that contains the class.
if (($fieldPos = strpos($remoteClass, '.')) !== false) {
return substr($remoteClass, 0, $fieldPos);
}
// Otherwise just return the class
return $remoteClass;
}
return null;
} | [
"public",
"function",
"getRelationClass",
"(",
"$",
"relationName",
")",
"{",
"// Parse many_many",
"$",
"manyManyComponent",
"=",
"$",
"this",
"->",
"getSchema",
"(",
")",
"->",
"manyManyComponent",
"(",
"static",
"::",
"class",
",",
"$",
"relationName",
")",
";",
"if",
"(",
"$",
"manyManyComponent",
")",
"{",
"return",
"$",
"manyManyComponent",
"[",
"'childClass'",
"]",
";",
"}",
"// Go through all relationship configuration fields.",
"$",
"config",
"=",
"$",
"this",
"->",
"config",
"(",
")",
";",
"$",
"candidates",
"=",
"array_merge",
"(",
"(",
"$",
"relations",
"=",
"$",
"config",
"->",
"get",
"(",
"'has_one'",
")",
")",
"?",
"$",
"relations",
":",
"array",
"(",
")",
",",
"(",
"$",
"relations",
"=",
"$",
"config",
"->",
"get",
"(",
"'has_many'",
")",
")",
"?",
"$",
"relations",
":",
"array",
"(",
")",
",",
"(",
"$",
"relations",
"=",
"$",
"config",
"->",
"get",
"(",
"'belongs_to'",
")",
")",
"?",
"$",
"relations",
":",
"array",
"(",
")",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"candidates",
"[",
"$",
"relationName",
"]",
")",
")",
"{",
"$",
"remoteClass",
"=",
"$",
"candidates",
"[",
"$",
"relationName",
"]",
";",
"// If dot notation is present, extract just the first part that contains the class.",
"if",
"(",
"(",
"$",
"fieldPos",
"=",
"strpos",
"(",
"$",
"remoteClass",
",",
"'.'",
")",
")",
"!==",
"false",
")",
"{",
"return",
"substr",
"(",
"$",
"remoteClass",
",",
"0",
",",
"$",
"fieldPos",
")",
";",
"}",
"// Otherwise just return the class",
"return",
"$",
"remoteClass",
";",
"}",
"return",
"null",
";",
"}"
]
| Find the foreign class of a relation on this DataObject, regardless of the relation type.
@param string $relationName Relation name.
@return string Class name, or null if not found. | [
"Find",
"the",
"foreign",
"class",
"of",
"a",
"relation",
"on",
"this",
"DataObject",
"regardless",
"of",
"the",
"relation",
"type",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1867-L1896 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.getRelationType | public function getRelationType($component)
{
$types = array('has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to');
$config = $this->config();
foreach ($types as $type) {
$relations = $config->get($type);
if ($relations && isset($relations[$component])) {
return $type;
}
}
return null;
} | php | public function getRelationType($component)
{
$types = array('has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to');
$config = $this->config();
foreach ($types as $type) {
$relations = $config->get($type);
if ($relations && isset($relations[$component])) {
return $type;
}
}
return null;
} | [
"public",
"function",
"getRelationType",
"(",
"$",
"component",
")",
"{",
"$",
"types",
"=",
"array",
"(",
"'has_one'",
",",
"'has_many'",
",",
"'many_many'",
",",
"'belongs_many_many'",
",",
"'belongs_to'",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"config",
"(",
")",
";",
"foreach",
"(",
"$",
"types",
"as",
"$",
"type",
")",
"{",
"$",
"relations",
"=",
"$",
"config",
"->",
"get",
"(",
"$",
"type",
")",
";",
"if",
"(",
"$",
"relations",
"&&",
"isset",
"(",
"$",
"relations",
"[",
"$",
"component",
"]",
")",
")",
"{",
"return",
"$",
"type",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Given a relation name, determine the relation type
@param string $component Name of component
@return string has_one, has_many, many_many, belongs_many_many or belongs_to | [
"Given",
"a",
"relation",
"name",
"determine",
"the",
"relation",
"type"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1904-L1915 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.inferReciprocalComponent | public function inferReciprocalComponent($remoteClass, $remoteRelation)
{
$remote = DataObject::singleton($remoteClass);
$class = $remote->getRelationClass($remoteRelation);
$schema = static::getSchema();
// Validate arguments
if (!$this->isInDB()) {
throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects");
}
if (empty($class)) {
throw new InvalidArgumentException(sprintf(
"%s invoked with invalid relation %s.%s",
__METHOD__,
$remoteClass,
$remoteRelation
));
}
// If relation is polymorphic, do not infer recriprocal relationship
if ($class === self::class) {
return null;
}
if (!is_a($this, $class, true)) {
throw new InvalidArgumentException(sprintf(
"Relation %s on %s does not refer to objects of type %s",
$remoteRelation,
$remoteClass,
static::class
));
}
// Check the relation type to mock
$relationType = $remote->getRelationType($remoteRelation);
switch ($relationType) {
case 'has_one': {
// Mock has_many
$joinField = "{$remoteRelation}ID";
$componentClass = $schema->classForField($remoteClass, $joinField);
$result = HasManyList::create($componentClass, $joinField);
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($this->ID);
}
case 'belongs_to':
case 'has_many': {
// These relations must have a has_one on the other end, so find it
$joinField = $schema->getRemoteJoinField(
$remoteClass,
$remoteRelation,
$relationType,
$polymorphic
);
// If relation is polymorphic, do not infer recriprocal relationship automatically
if ($polymorphic) {
return null;
}
$joinID = $this->getField($joinField);
if (empty($joinID)) {
return null;
}
// Get object by joined ID
return DataObject::get($remoteClass)
->filter('ID', $joinID)
->setDataQueryParam($this->getInheritableQueryParams())
->first();
}
case 'many_many':
case 'belongs_many_many': {
// Get components and extra fields from parent
$manyMany = $remote->getSchema()->manyManyComponent($remoteClass, $remoteRelation);
$extraFields = $schema->manyManyExtraFieldsForComponent($remoteClass, $remoteRelation) ?: array();
// Reverse parent and component fields and create an inverse ManyManyList
/** @var RelationList $result */
$result = Injector::inst()->create(
$manyMany['relationClass'],
$manyMany['parentClass'], // Substitute parent class for dataClass
$manyMany['join'],
$manyMany['parentField'], // Reversed parent / child field
$manyMany['childField'], // Reversed parent / child field
$extraFields,
$manyMany['childClass'], // substitute child class for parentClass
$remoteClass // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
);
$this->extend('updateManyManyComponents', $result);
// If this is called on a singleton, then we return an 'orphaned relation' that can have the
// foreignID set elsewhere.
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($this->ID);
}
default: {
return null;
}
}
} | php | public function inferReciprocalComponent($remoteClass, $remoteRelation)
{
$remote = DataObject::singleton($remoteClass);
$class = $remote->getRelationClass($remoteRelation);
$schema = static::getSchema();
// Validate arguments
if (!$this->isInDB()) {
throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects");
}
if (empty($class)) {
throw new InvalidArgumentException(sprintf(
"%s invoked with invalid relation %s.%s",
__METHOD__,
$remoteClass,
$remoteRelation
));
}
// If relation is polymorphic, do not infer recriprocal relationship
if ($class === self::class) {
return null;
}
if (!is_a($this, $class, true)) {
throw new InvalidArgumentException(sprintf(
"Relation %s on %s does not refer to objects of type %s",
$remoteRelation,
$remoteClass,
static::class
));
}
// Check the relation type to mock
$relationType = $remote->getRelationType($remoteRelation);
switch ($relationType) {
case 'has_one': {
// Mock has_many
$joinField = "{$remoteRelation}ID";
$componentClass = $schema->classForField($remoteClass, $joinField);
$result = HasManyList::create($componentClass, $joinField);
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($this->ID);
}
case 'belongs_to':
case 'has_many': {
// These relations must have a has_one on the other end, so find it
$joinField = $schema->getRemoteJoinField(
$remoteClass,
$remoteRelation,
$relationType,
$polymorphic
);
// If relation is polymorphic, do not infer recriprocal relationship automatically
if ($polymorphic) {
return null;
}
$joinID = $this->getField($joinField);
if (empty($joinID)) {
return null;
}
// Get object by joined ID
return DataObject::get($remoteClass)
->filter('ID', $joinID)
->setDataQueryParam($this->getInheritableQueryParams())
->first();
}
case 'many_many':
case 'belongs_many_many': {
// Get components and extra fields from parent
$manyMany = $remote->getSchema()->manyManyComponent($remoteClass, $remoteRelation);
$extraFields = $schema->manyManyExtraFieldsForComponent($remoteClass, $remoteRelation) ?: array();
// Reverse parent and component fields and create an inverse ManyManyList
/** @var RelationList $result */
$result = Injector::inst()->create(
$manyMany['relationClass'],
$manyMany['parentClass'], // Substitute parent class for dataClass
$manyMany['join'],
$manyMany['parentField'], // Reversed parent / child field
$manyMany['childField'], // Reversed parent / child field
$extraFields,
$manyMany['childClass'], // substitute child class for parentClass
$remoteClass // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
);
$this->extend('updateManyManyComponents', $result);
// If this is called on a singleton, then we return an 'orphaned relation' that can have the
// foreignID set elsewhere.
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($this->ID);
}
default: {
return null;
}
}
} | [
"public",
"function",
"inferReciprocalComponent",
"(",
"$",
"remoteClass",
",",
"$",
"remoteRelation",
")",
"{",
"$",
"remote",
"=",
"DataObject",
"::",
"singleton",
"(",
"$",
"remoteClass",
")",
";",
"$",
"class",
"=",
"$",
"remote",
"->",
"getRelationClass",
"(",
"$",
"remoteRelation",
")",
";",
"$",
"schema",
"=",
"static",
"::",
"getSchema",
"(",
")",
";",
"// Validate arguments",
"if",
"(",
"!",
"$",
"this",
"->",
"isInDB",
"(",
")",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"__METHOD__",
".",
"\" cannot be called on unsaved objects\"",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"class",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"%s invoked with invalid relation %s.%s\"",
",",
"__METHOD__",
",",
"$",
"remoteClass",
",",
"$",
"remoteRelation",
")",
")",
";",
"}",
"// If relation is polymorphic, do not infer recriprocal relationship",
"if",
"(",
"$",
"class",
"===",
"self",
"::",
"class",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"is_a",
"(",
"$",
"this",
",",
"$",
"class",
",",
"true",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"Relation %s on %s does not refer to objects of type %s\"",
",",
"$",
"remoteRelation",
",",
"$",
"remoteClass",
",",
"static",
"::",
"class",
")",
")",
";",
"}",
"// Check the relation type to mock",
"$",
"relationType",
"=",
"$",
"remote",
"->",
"getRelationType",
"(",
"$",
"remoteRelation",
")",
";",
"switch",
"(",
"$",
"relationType",
")",
"{",
"case",
"'has_one'",
":",
"{",
"// Mock has_many",
"$",
"joinField",
"=",
"\"{$remoteRelation}ID\"",
";",
"$",
"componentClass",
"=",
"$",
"schema",
"->",
"classForField",
"(",
"$",
"remoteClass",
",",
"$",
"joinField",
")",
";",
"$",
"result",
"=",
"HasManyList",
"::",
"create",
"(",
"$",
"componentClass",
",",
"$",
"joinField",
")",
";",
"return",
"$",
"result",
"->",
"setDataQueryParam",
"(",
"$",
"this",
"->",
"getInheritableQueryParams",
"(",
")",
")",
"->",
"forForeignID",
"(",
"$",
"this",
"->",
"ID",
")",
";",
"}",
"case",
"'belongs_to'",
":",
"case",
"'has_many'",
":",
"{",
"// These relations must have a has_one on the other end, so find it",
"$",
"joinField",
"=",
"$",
"schema",
"->",
"getRemoteJoinField",
"(",
"$",
"remoteClass",
",",
"$",
"remoteRelation",
",",
"$",
"relationType",
",",
"$",
"polymorphic",
")",
";",
"// If relation is polymorphic, do not infer recriprocal relationship automatically",
"if",
"(",
"$",
"polymorphic",
")",
"{",
"return",
"null",
";",
"}",
"$",
"joinID",
"=",
"$",
"this",
"->",
"getField",
"(",
"$",
"joinField",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"joinID",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Get object by joined ID",
"return",
"DataObject",
"::",
"get",
"(",
"$",
"remoteClass",
")",
"->",
"filter",
"(",
"'ID'",
",",
"$",
"joinID",
")",
"->",
"setDataQueryParam",
"(",
"$",
"this",
"->",
"getInheritableQueryParams",
"(",
")",
")",
"->",
"first",
"(",
")",
";",
"}",
"case",
"'many_many'",
":",
"case",
"'belongs_many_many'",
":",
"{",
"// Get components and extra fields from parent",
"$",
"manyMany",
"=",
"$",
"remote",
"->",
"getSchema",
"(",
")",
"->",
"manyManyComponent",
"(",
"$",
"remoteClass",
",",
"$",
"remoteRelation",
")",
";",
"$",
"extraFields",
"=",
"$",
"schema",
"->",
"manyManyExtraFieldsForComponent",
"(",
"$",
"remoteClass",
",",
"$",
"remoteRelation",
")",
"?",
":",
"array",
"(",
")",
";",
"// Reverse parent and component fields and create an inverse ManyManyList",
"/** @var RelationList $result */",
"$",
"result",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"manyMany",
"[",
"'relationClass'",
"]",
",",
"$",
"manyMany",
"[",
"'parentClass'",
"]",
",",
"// Substitute parent class for dataClass",
"$",
"manyMany",
"[",
"'join'",
"]",
",",
"$",
"manyMany",
"[",
"'parentField'",
"]",
",",
"// Reversed parent / child field",
"$",
"manyMany",
"[",
"'childField'",
"]",
",",
"// Reversed parent / child field",
"$",
"extraFields",
",",
"$",
"manyMany",
"[",
"'childClass'",
"]",
",",
"// substitute child class for parentClass",
"$",
"remoteClass",
"// In case ManyManyThroughList needs to use PolymorphicHasManyList internally",
")",
";",
"$",
"this",
"->",
"extend",
"(",
"'updateManyManyComponents'",
",",
"$",
"result",
")",
";",
"// If this is called on a singleton, then we return an 'orphaned relation' that can have the",
"// foreignID set elsewhere.",
"return",
"$",
"result",
"->",
"setDataQueryParam",
"(",
"$",
"this",
"->",
"getInheritableQueryParams",
"(",
")",
")",
"->",
"forForeignID",
"(",
"$",
"this",
"->",
"ID",
")",
";",
"}",
"default",
":",
"{",
"return",
"null",
";",
"}",
"}",
"}"
]
| Given a relation declared on a remote class, generate a substitute component for the opposite
side of the relation.
Notes on behaviour:
- This can still be used on components that are defined on both sides, but do not need to be.
- All has_ones on remote class will be treated as local has_many, even if they are belongs_to
- Polymorphic relationships do not have two natural endpoints (only on one side)
and thus attempting to infer them will return nothing.
- Cannot be used on unsaved objects.
@param string $remoteClass
@param string $remoteRelation
@return DataList|DataObject The component, either as a list or single object
@throws BadMethodCallException
@throws InvalidArgumentException | [
"Given",
"a",
"relation",
"declared",
"on",
"a",
"remote",
"class",
"generate",
"a",
"substitute",
"component",
"for",
"the",
"opposite",
"side",
"of",
"the",
"relation",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L1934-L2030 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.getManyManyComponents | public function getManyManyComponents($componentName, $id = null)
{
if (!isset($id)) {
$id = $this->ID;
}
$schema = static::getSchema();
$manyManyComponent = $schema->manyManyComponent(static::class, $componentName);
if (!$manyManyComponent) {
throw new InvalidArgumentException(sprintf(
"DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'",
$componentName,
static::class
));
}
// If we haven't been written yet, we can't save these relations, so use a list that handles this case
if (!$id) {
if (!isset($this->unsavedRelations[$componentName])) {
$this->unsavedRelations[$componentName] =
new UnsavedRelationList(
$manyManyComponent['parentClass'],
$componentName,
$manyManyComponent['childClass']
);
}
return $this->unsavedRelations[$componentName];
}
$extraFields = $schema->manyManyExtraFieldsForComponent(static::class, $componentName) ?: array();
/** @var RelationList $result */
$result = Injector::inst()->create(
$manyManyComponent['relationClass'],
$manyManyComponent['childClass'],
$manyManyComponent['join'],
$manyManyComponent['childField'],
$manyManyComponent['parentField'],
$extraFields,
$manyManyComponent['parentClass'],
static::class // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
);
// Store component data in query meta-data
$result = $result->alterDataQuery(function ($query) use ($extraFields) {
/** @var DataQuery $query */
$query->setQueryParam('Component.ExtraFields', $extraFields);
});
// If we have a default sort set for our "join" then we should overwrite any default already set.
$joinSort = Config::inst()->get($manyManyComponent['join'], 'default_sort');
if (!empty($joinSort)) {
$result = $result->sort($joinSort);
}
$this->extend('updateManyManyComponents', $result);
// If this is called on a singleton, then we return an 'orphaned relation' that can have the
// foreignID set elsewhere.
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($id);
} | php | public function getManyManyComponents($componentName, $id = null)
{
if (!isset($id)) {
$id = $this->ID;
}
$schema = static::getSchema();
$manyManyComponent = $schema->manyManyComponent(static::class, $componentName);
if (!$manyManyComponent) {
throw new InvalidArgumentException(sprintf(
"DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'",
$componentName,
static::class
));
}
// If we haven't been written yet, we can't save these relations, so use a list that handles this case
if (!$id) {
if (!isset($this->unsavedRelations[$componentName])) {
$this->unsavedRelations[$componentName] =
new UnsavedRelationList(
$manyManyComponent['parentClass'],
$componentName,
$manyManyComponent['childClass']
);
}
return $this->unsavedRelations[$componentName];
}
$extraFields = $schema->manyManyExtraFieldsForComponent(static::class, $componentName) ?: array();
/** @var RelationList $result */
$result = Injector::inst()->create(
$manyManyComponent['relationClass'],
$manyManyComponent['childClass'],
$manyManyComponent['join'],
$manyManyComponent['childField'],
$manyManyComponent['parentField'],
$extraFields,
$manyManyComponent['parentClass'],
static::class // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
);
// Store component data in query meta-data
$result = $result->alterDataQuery(function ($query) use ($extraFields) {
/** @var DataQuery $query */
$query->setQueryParam('Component.ExtraFields', $extraFields);
});
// If we have a default sort set for our "join" then we should overwrite any default already set.
$joinSort = Config::inst()->get($manyManyComponent['join'], 'default_sort');
if (!empty($joinSort)) {
$result = $result->sort($joinSort);
}
$this->extend('updateManyManyComponents', $result);
// If this is called on a singleton, then we return an 'orphaned relation' that can have the
// foreignID set elsewhere.
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($id);
} | [
"public",
"function",
"getManyManyComponents",
"(",
"$",
"componentName",
",",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"id",
")",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"ID",
";",
"}",
"$",
"schema",
"=",
"static",
"::",
"getSchema",
"(",
")",
";",
"$",
"manyManyComponent",
"=",
"$",
"schema",
"->",
"manyManyComponent",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
")",
";",
"if",
"(",
"!",
"$",
"manyManyComponent",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'\"",
",",
"$",
"componentName",
",",
"static",
"::",
"class",
")",
")",
";",
"}",
"// If we haven't been written yet, we can't save these relations, so use a list that handles this case",
"if",
"(",
"!",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"unsavedRelations",
"[",
"$",
"componentName",
"]",
")",
")",
"{",
"$",
"this",
"->",
"unsavedRelations",
"[",
"$",
"componentName",
"]",
"=",
"new",
"UnsavedRelationList",
"(",
"$",
"manyManyComponent",
"[",
"'parentClass'",
"]",
",",
"$",
"componentName",
",",
"$",
"manyManyComponent",
"[",
"'childClass'",
"]",
")",
";",
"}",
"return",
"$",
"this",
"->",
"unsavedRelations",
"[",
"$",
"componentName",
"]",
";",
"}",
"$",
"extraFields",
"=",
"$",
"schema",
"->",
"manyManyExtraFieldsForComponent",
"(",
"static",
"::",
"class",
",",
"$",
"componentName",
")",
"?",
":",
"array",
"(",
")",
";",
"/** @var RelationList $result */",
"$",
"result",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"manyManyComponent",
"[",
"'relationClass'",
"]",
",",
"$",
"manyManyComponent",
"[",
"'childClass'",
"]",
",",
"$",
"manyManyComponent",
"[",
"'join'",
"]",
",",
"$",
"manyManyComponent",
"[",
"'childField'",
"]",
",",
"$",
"manyManyComponent",
"[",
"'parentField'",
"]",
",",
"$",
"extraFields",
",",
"$",
"manyManyComponent",
"[",
"'parentClass'",
"]",
",",
"static",
"::",
"class",
"// In case ManyManyThroughList needs to use PolymorphicHasManyList internally",
")",
";",
"// Store component data in query meta-data",
"$",
"result",
"=",
"$",
"result",
"->",
"alterDataQuery",
"(",
"function",
"(",
"$",
"query",
")",
"use",
"(",
"$",
"extraFields",
")",
"{",
"/** @var DataQuery $query */",
"$",
"query",
"->",
"setQueryParam",
"(",
"'Component.ExtraFields'",
",",
"$",
"extraFields",
")",
";",
"}",
")",
";",
"// If we have a default sort set for our \"join\" then we should overwrite any default already set.",
"$",
"joinSort",
"=",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"manyManyComponent",
"[",
"'join'",
"]",
",",
"'default_sort'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"joinSort",
")",
")",
"{",
"$",
"result",
"=",
"$",
"result",
"->",
"sort",
"(",
"$",
"joinSort",
")",
";",
"}",
"$",
"this",
"->",
"extend",
"(",
"'updateManyManyComponents'",
",",
"$",
"result",
")",
";",
"// If this is called on a singleton, then we return an 'orphaned relation' that can have the",
"// foreignID set elsewhere.",
"return",
"$",
"result",
"->",
"setDataQueryParam",
"(",
"$",
"this",
"->",
"getInheritableQueryParams",
"(",
")",
")",
"->",
"forForeignID",
"(",
"$",
"id",
")",
";",
"}"
]
| Returns a many-to-many component, as a ManyManyList.
@param string $componentName Name of the many-many component
@param int|array $id Optional ID for parent of this relation, if not the current record
@return ManyManyList|UnsavedRelationList The set of components | [
"Returns",
"a",
"many",
"-",
"to",
"-",
"many",
"component",
"as",
"a",
"ManyManyList",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L2038-L2098 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.belongsTo | public function belongsTo($classOnly = true)
{
$belongsTo = (array)$this->config()->get('belongs_to');
if ($belongsTo && $classOnly) {
return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
} else {
return $belongsTo ? $belongsTo : array();
}
} | php | public function belongsTo($classOnly = true)
{
$belongsTo = (array)$this->config()->get('belongs_to');
if ($belongsTo && $classOnly) {
return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
} else {
return $belongsTo ? $belongsTo : array();
}
} | [
"public",
"function",
"belongsTo",
"(",
"$",
"classOnly",
"=",
"true",
")",
"{",
"$",
"belongsTo",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'belongs_to'",
")",
";",
"if",
"(",
"$",
"belongsTo",
"&&",
"$",
"classOnly",
")",
"{",
"return",
"preg_replace",
"(",
"'/(.+)?\\..+/'",
",",
"'$1'",
",",
"$",
"belongsTo",
")",
";",
"}",
"else",
"{",
"return",
"$",
"belongsTo",
"?",
"$",
"belongsTo",
":",
"array",
"(",
")",
";",
"}",
"}"
]
| Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
their class name will be returned.
@param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
the field data stripped off. It defaults to TRUE.
@return string|array | [
"Returns",
"the",
"class",
"of",
"a",
"remote",
"belongs_to",
"relationship",
".",
"If",
"no",
"component",
"is",
"specified",
"a",
"map",
"of",
"all",
"components",
"and",
"their",
"class",
"name",
"will",
"be",
"returned",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L2120-L2128 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.loadLazyFields | protected function loadLazyFields($class = null)
{
if (!$this->isInDB() || !is_numeric($this->ID)) {
return false;
}
if (!$class) {
$loaded = array();
foreach ($this->record as $key => $value) {
if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
$this->loadLazyFields($value);
$loaded[$value] = $value;
}
}
return false;
}
$dataQuery = new DataQuery($class);
// Reset query parameter context to that of this DataObject
if ($params = $this->getSourceQueryParams()) {
foreach ($params as $key => $value) {
$dataQuery->setQueryParam($key, $value);
}
}
// Limit query to the current record, unless it has the Versioned extension,
// in which case it requires special handling through augmentLoadLazyFields()
$schema = static::getSchema();
$baseIDColumn = $schema->sqlColumnForField($this, 'ID');
$dataQuery->where([
$baseIDColumn => $this->record['ID']
])->limit(1);
$columns = array();
// Add SQL for fields, both simple & multi-value
// TODO: This is copy & pasted from buildSQL(), it could be moved into a method
$databaseFields = $schema->databaseFields($class, false);
foreach ($databaseFields as $k => $v) {
if (!isset($this->record[$k]) || $this->record[$k] === null) {
$columns[] = $k;
}
}
if ($columns) {
$query = $dataQuery->query();
$this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
$this->extend('augmentSQL', $query, $dataQuery);
$dataQuery->setQueriedColumns($columns);
$newData = $dataQuery->execute()->record();
// Load the data into record
if ($newData) {
foreach ($newData as $k => $v) {
if (in_array($k, $columns)) {
$this->record[$k] = $v;
$this->original[$k] = $v;
unset($this->record[$k . '_Lazy']);
}
}
// No data means that the query returned nothing; assign 'null' to all the requested fields
} else {
foreach ($columns as $k) {
$this->record[$k] = null;
$this->original[$k] = null;
unset($this->record[$k . '_Lazy']);
}
}
}
return true;
} | php | protected function loadLazyFields($class = null)
{
if (!$this->isInDB() || !is_numeric($this->ID)) {
return false;
}
if (!$class) {
$loaded = array();
foreach ($this->record as $key => $value) {
if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
$this->loadLazyFields($value);
$loaded[$value] = $value;
}
}
return false;
}
$dataQuery = new DataQuery($class);
// Reset query parameter context to that of this DataObject
if ($params = $this->getSourceQueryParams()) {
foreach ($params as $key => $value) {
$dataQuery->setQueryParam($key, $value);
}
}
// Limit query to the current record, unless it has the Versioned extension,
// in which case it requires special handling through augmentLoadLazyFields()
$schema = static::getSchema();
$baseIDColumn = $schema->sqlColumnForField($this, 'ID');
$dataQuery->where([
$baseIDColumn => $this->record['ID']
])->limit(1);
$columns = array();
// Add SQL for fields, both simple & multi-value
// TODO: This is copy & pasted from buildSQL(), it could be moved into a method
$databaseFields = $schema->databaseFields($class, false);
foreach ($databaseFields as $k => $v) {
if (!isset($this->record[$k]) || $this->record[$k] === null) {
$columns[] = $k;
}
}
if ($columns) {
$query = $dataQuery->query();
$this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
$this->extend('augmentSQL', $query, $dataQuery);
$dataQuery->setQueriedColumns($columns);
$newData = $dataQuery->execute()->record();
// Load the data into record
if ($newData) {
foreach ($newData as $k => $v) {
if (in_array($k, $columns)) {
$this->record[$k] = $v;
$this->original[$k] = $v;
unset($this->record[$k . '_Lazy']);
}
}
// No data means that the query returned nothing; assign 'null' to all the requested fields
} else {
foreach ($columns as $k) {
$this->record[$k] = null;
$this->original[$k] = null;
unset($this->record[$k . '_Lazy']);
}
}
}
return true;
} | [
"protected",
"function",
"loadLazyFields",
"(",
"$",
"class",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isInDB",
"(",
")",
"||",
"!",
"is_numeric",
"(",
"$",
"this",
"->",
"ID",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"class",
")",
"{",
"$",
"loaded",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"record",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"key",
")",
">",
"5",
"&&",
"substr",
"(",
"$",
"key",
",",
"-",
"5",
")",
"==",
"'_Lazy'",
"&&",
"!",
"array_key_exists",
"(",
"$",
"value",
",",
"$",
"loaded",
")",
")",
"{",
"$",
"this",
"->",
"loadLazyFields",
"(",
"$",
"value",
")",
";",
"$",
"loaded",
"[",
"$",
"value",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"false",
";",
"}",
"$",
"dataQuery",
"=",
"new",
"DataQuery",
"(",
"$",
"class",
")",
";",
"// Reset query parameter context to that of this DataObject",
"if",
"(",
"$",
"params",
"=",
"$",
"this",
"->",
"getSourceQueryParams",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"dataQuery",
"->",
"setQueryParam",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"}",
"// Limit query to the current record, unless it has the Versioned extension,",
"// in which case it requires special handling through augmentLoadLazyFields()",
"$",
"schema",
"=",
"static",
"::",
"getSchema",
"(",
")",
";",
"$",
"baseIDColumn",
"=",
"$",
"schema",
"->",
"sqlColumnForField",
"(",
"$",
"this",
",",
"'ID'",
")",
";",
"$",
"dataQuery",
"->",
"where",
"(",
"[",
"$",
"baseIDColumn",
"=>",
"$",
"this",
"->",
"record",
"[",
"'ID'",
"]",
"]",
")",
"->",
"limit",
"(",
"1",
")",
";",
"$",
"columns",
"=",
"array",
"(",
")",
";",
"// Add SQL for fields, both simple & multi-value",
"// TODO: This is copy & pasted from buildSQL(), it could be moved into a method",
"$",
"databaseFields",
"=",
"$",
"schema",
"->",
"databaseFields",
"(",
"$",
"class",
",",
"false",
")",
";",
"foreach",
"(",
"$",
"databaseFields",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"record",
"[",
"$",
"k",
"]",
")",
"||",
"$",
"this",
"->",
"record",
"[",
"$",
"k",
"]",
"===",
"null",
")",
"{",
"$",
"columns",
"[",
"]",
"=",
"$",
"k",
";",
"}",
"}",
"if",
"(",
"$",
"columns",
")",
"{",
"$",
"query",
"=",
"$",
"dataQuery",
"->",
"query",
"(",
")",
";",
"$",
"this",
"->",
"extend",
"(",
"'augmentLoadLazyFields'",
",",
"$",
"query",
",",
"$",
"dataQuery",
",",
"$",
"this",
")",
";",
"$",
"this",
"->",
"extend",
"(",
"'augmentSQL'",
",",
"$",
"query",
",",
"$",
"dataQuery",
")",
";",
"$",
"dataQuery",
"->",
"setQueriedColumns",
"(",
"$",
"columns",
")",
";",
"$",
"newData",
"=",
"$",
"dataQuery",
"->",
"execute",
"(",
")",
"->",
"record",
"(",
")",
";",
"// Load the data into record",
"if",
"(",
"$",
"newData",
")",
"{",
"foreach",
"(",
"$",
"newData",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"k",
",",
"$",
"columns",
")",
")",
"{",
"$",
"this",
"->",
"record",
"[",
"$",
"k",
"]",
"=",
"$",
"v",
";",
"$",
"this",
"->",
"original",
"[",
"$",
"k",
"]",
"=",
"$",
"v",
";",
"unset",
"(",
"$",
"this",
"->",
"record",
"[",
"$",
"k",
".",
"'_Lazy'",
"]",
")",
";",
"}",
"}",
"// No data means that the query returned nothing; assign 'null' to all the requested fields",
"}",
"else",
"{",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"k",
")",
"{",
"$",
"this",
"->",
"record",
"[",
"$",
"k",
"]",
"=",
"null",
";",
"$",
"this",
"->",
"original",
"[",
"$",
"k",
"]",
"=",
"null",
";",
"unset",
"(",
"$",
"this",
"->",
"record",
"[",
"$",
"k",
".",
"'_Lazy'",
"]",
")",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
]
| Loads all the stub fields that an initial lazy load didn't load fully.
@param string $class Class to load the values from. Others are joined as required.
Not specifying a tableClass will load all lazy fields from all tables.
@return bool Flag if lazy loading succeeded | [
"Loads",
"all",
"the",
"stub",
"fields",
"that",
"an",
"initial",
"lazy",
"load",
"didn",
"t",
"load",
"fully",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L2451-L2526 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.getChangedFields | public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT)
{
$changedFields = array();
// Update the changed array with references to changed obj-fields
foreach ($this->record as $k => $v) {
// Prevents DBComposite infinite looping on isChanged
if (is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
continue;
}
if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = self::CHANGE_VALUE;
}
}
// If change was forced, then derive change data from $this->record
if ($this->changeForced && $changeLevel <= self::CHANGE_STRICT) {
$changed = array_combine(
array_keys($this->record),
array_fill(0, count($this->record), self::CHANGE_STRICT)
);
// @todo Find better way to allow versioned to write a new version after forceChange
unset($changed['Version']);
} else {
$changed = $this->changed;
}
if (is_array($databaseFieldsOnly)) {
$fields = array_intersect_key($changed, array_flip($databaseFieldsOnly));
} elseif ($databaseFieldsOnly) {
$fieldsSpecs = static::getSchema()->fieldSpecs(static::class);
$fields = array_intersect_key($changed, $fieldsSpecs);
} else {
$fields = $changed;
}
// Filter the list to those of a certain change level
if ($changeLevel > self::CHANGE_STRICT) {
if ($fields) {
foreach ($fields as $name => $level) {
if ($level < $changeLevel) {
unset($fields[$name]);
}
}
}
}
if ($fields) {
foreach ($fields as $name => $level) {
$changedFields[$name] = array(
'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
'level' => $level
);
}
}
return $changedFields;
} | php | public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT)
{
$changedFields = array();
// Update the changed array with references to changed obj-fields
foreach ($this->record as $k => $v) {
// Prevents DBComposite infinite looping on isChanged
if (is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
continue;
}
if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = self::CHANGE_VALUE;
}
}
// If change was forced, then derive change data from $this->record
if ($this->changeForced && $changeLevel <= self::CHANGE_STRICT) {
$changed = array_combine(
array_keys($this->record),
array_fill(0, count($this->record), self::CHANGE_STRICT)
);
// @todo Find better way to allow versioned to write a new version after forceChange
unset($changed['Version']);
} else {
$changed = $this->changed;
}
if (is_array($databaseFieldsOnly)) {
$fields = array_intersect_key($changed, array_flip($databaseFieldsOnly));
} elseif ($databaseFieldsOnly) {
$fieldsSpecs = static::getSchema()->fieldSpecs(static::class);
$fields = array_intersect_key($changed, $fieldsSpecs);
} else {
$fields = $changed;
}
// Filter the list to those of a certain change level
if ($changeLevel > self::CHANGE_STRICT) {
if ($fields) {
foreach ($fields as $name => $level) {
if ($level < $changeLevel) {
unset($fields[$name]);
}
}
}
}
if ($fields) {
foreach ($fields as $name => $level) {
$changedFields[$name] = array(
'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
'level' => $level
);
}
}
return $changedFields;
} | [
"public",
"function",
"getChangedFields",
"(",
"$",
"databaseFieldsOnly",
"=",
"false",
",",
"$",
"changeLevel",
"=",
"self",
"::",
"CHANGE_STRICT",
")",
"{",
"$",
"changedFields",
"=",
"array",
"(",
")",
";",
"// Update the changed array with references to changed obj-fields",
"foreach",
"(",
"$",
"this",
"->",
"record",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"// Prevents DBComposite infinite looping on isChanged",
"if",
"(",
"is_array",
"(",
"$",
"databaseFieldsOnly",
")",
"&&",
"!",
"in_array",
"(",
"$",
"k",
",",
"$",
"databaseFieldsOnly",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"is_object",
"(",
"$",
"v",
")",
"&&",
"method_exists",
"(",
"$",
"v",
",",
"'isChanged'",
")",
"&&",
"$",
"v",
"->",
"isChanged",
"(",
")",
")",
"{",
"$",
"this",
"->",
"changed",
"[",
"$",
"k",
"]",
"=",
"self",
"::",
"CHANGE_VALUE",
";",
"}",
"}",
"// If change was forced, then derive change data from $this->record",
"if",
"(",
"$",
"this",
"->",
"changeForced",
"&&",
"$",
"changeLevel",
"<=",
"self",
"::",
"CHANGE_STRICT",
")",
"{",
"$",
"changed",
"=",
"array_combine",
"(",
"array_keys",
"(",
"$",
"this",
"->",
"record",
")",
",",
"array_fill",
"(",
"0",
",",
"count",
"(",
"$",
"this",
"->",
"record",
")",
",",
"self",
"::",
"CHANGE_STRICT",
")",
")",
";",
"// @todo Find better way to allow versioned to write a new version after forceChange",
"unset",
"(",
"$",
"changed",
"[",
"'Version'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"changed",
"=",
"$",
"this",
"->",
"changed",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"databaseFieldsOnly",
")",
")",
"{",
"$",
"fields",
"=",
"array_intersect_key",
"(",
"$",
"changed",
",",
"array_flip",
"(",
"$",
"databaseFieldsOnly",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"databaseFieldsOnly",
")",
"{",
"$",
"fieldsSpecs",
"=",
"static",
"::",
"getSchema",
"(",
")",
"->",
"fieldSpecs",
"(",
"static",
"::",
"class",
")",
";",
"$",
"fields",
"=",
"array_intersect_key",
"(",
"$",
"changed",
",",
"$",
"fieldsSpecs",
")",
";",
"}",
"else",
"{",
"$",
"fields",
"=",
"$",
"changed",
";",
"}",
"// Filter the list to those of a certain change level",
"if",
"(",
"$",
"changeLevel",
">",
"self",
"::",
"CHANGE_STRICT",
")",
"{",
"if",
"(",
"$",
"fields",
")",
"{",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"name",
"=>",
"$",
"level",
")",
"{",
"if",
"(",
"$",
"level",
"<",
"$",
"changeLevel",
")",
"{",
"unset",
"(",
"$",
"fields",
"[",
"$",
"name",
"]",
")",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"$",
"fields",
")",
"{",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"name",
"=>",
"$",
"level",
")",
"{",
"$",
"changedFields",
"[",
"$",
"name",
"]",
"=",
"array",
"(",
"'before'",
"=>",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"original",
")",
"?",
"$",
"this",
"->",
"original",
"[",
"$",
"name",
"]",
":",
"null",
",",
"'after'",
"=>",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"record",
")",
"?",
"$",
"this",
"->",
"record",
"[",
"$",
"name",
"]",
":",
"null",
",",
"'level'",
"=>",
"$",
"level",
")",
";",
"}",
"}",
"return",
"$",
"changedFields",
";",
"}"
]
| Return the fields that have changed since the last write.
The change level affects what the functions defines as "changed":
- Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
- Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
for example a change from 0 to null would not be included.
Example return:
<code>
array(
'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
)
</code>
@param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true
to return all database fields, or an array for an explicit filter. false returns all fields.
@param int $changeLevel The strictness of what is defined as change. Defaults to strict
@return array | [
"Return",
"the",
"fields",
"that",
"have",
"changed",
"since",
"the",
"last",
"write",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L2548-L2606 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.hasDatabaseField | public function hasDatabaseField($field)
{
$spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY);
return !empty($spec);
} | php | public function hasDatabaseField($field)
{
$spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY);
return !empty($spec);
} | [
"public",
"function",
"hasDatabaseField",
"(",
"$",
"field",
")",
"{",
"$",
"spec",
"=",
"static",
"::",
"getSchema",
"(",
")",
"->",
"fieldSpec",
"(",
"static",
"::",
"class",
",",
"$",
"field",
",",
"DataObjectSchema",
"::",
"DB_ONLY",
")",
";",
"return",
"!",
"empty",
"(",
"$",
"spec",
")",
";",
"}"
]
| Returns true if the given field exists as a database column
@param string $field Name of the field
@return boolean | [
"Returns",
"true",
"if",
"the",
"given",
"field",
"exists",
"as",
"a",
"database",
"column"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L2793-L2797 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.relObject | public function relObject($fieldPath)
{
$object = null;
$component = $this;
// Parse all relations
foreach (explode('.', $fieldPath) as $relation) {
if (!$component) {
return null;
}
// Inspect relation type
if (ClassInfo::hasMethod($component, $relation)) {
$component = $component->$relation();
} elseif ($component instanceof Relation || $component instanceof DataList) {
// $relation could either be a field (aggregate), or another relation
$singleton = DataObject::singleton($component->dataClass());
$component = $singleton->dbObject($relation) ?: $component->relation($relation);
} elseif ($component instanceof DataObject && ($dbObject = $component->dbObject($relation))) {
$component = $dbObject;
} elseif ($component instanceof ViewableData && $component->hasField($relation)) {
$component = $component->obj($relation);
} else {
throw new LogicException(
"$relation is not a relation/field on " . get_class($component)
);
}
}
return $component;
} | php | public function relObject($fieldPath)
{
$object = null;
$component = $this;
// Parse all relations
foreach (explode('.', $fieldPath) as $relation) {
if (!$component) {
return null;
}
// Inspect relation type
if (ClassInfo::hasMethod($component, $relation)) {
$component = $component->$relation();
} elseif ($component instanceof Relation || $component instanceof DataList) {
// $relation could either be a field (aggregate), or another relation
$singleton = DataObject::singleton($component->dataClass());
$component = $singleton->dbObject($relation) ?: $component->relation($relation);
} elseif ($component instanceof DataObject && ($dbObject = $component->dbObject($relation))) {
$component = $dbObject;
} elseif ($component instanceof ViewableData && $component->hasField($relation)) {
$component = $component->obj($relation);
} else {
throw new LogicException(
"$relation is not a relation/field on " . get_class($component)
);
}
}
return $component;
} | [
"public",
"function",
"relObject",
"(",
"$",
"fieldPath",
")",
"{",
"$",
"object",
"=",
"null",
";",
"$",
"component",
"=",
"$",
"this",
";",
"// Parse all relations",
"foreach",
"(",
"explode",
"(",
"'.'",
",",
"$",
"fieldPath",
")",
"as",
"$",
"relation",
")",
"{",
"if",
"(",
"!",
"$",
"component",
")",
"{",
"return",
"null",
";",
"}",
"// Inspect relation type",
"if",
"(",
"ClassInfo",
"::",
"hasMethod",
"(",
"$",
"component",
",",
"$",
"relation",
")",
")",
"{",
"$",
"component",
"=",
"$",
"component",
"->",
"$",
"relation",
"(",
")",
";",
"}",
"elseif",
"(",
"$",
"component",
"instanceof",
"Relation",
"||",
"$",
"component",
"instanceof",
"DataList",
")",
"{",
"// $relation could either be a field (aggregate), or another relation",
"$",
"singleton",
"=",
"DataObject",
"::",
"singleton",
"(",
"$",
"component",
"->",
"dataClass",
"(",
")",
")",
";",
"$",
"component",
"=",
"$",
"singleton",
"->",
"dbObject",
"(",
"$",
"relation",
")",
"?",
":",
"$",
"component",
"->",
"relation",
"(",
"$",
"relation",
")",
";",
"}",
"elseif",
"(",
"$",
"component",
"instanceof",
"DataObject",
"&&",
"(",
"$",
"dbObject",
"=",
"$",
"component",
"->",
"dbObject",
"(",
"$",
"relation",
")",
")",
")",
"{",
"$",
"component",
"=",
"$",
"dbObject",
";",
"}",
"elseif",
"(",
"$",
"component",
"instanceof",
"ViewableData",
"&&",
"$",
"component",
"->",
"hasField",
"(",
"$",
"relation",
")",
")",
"{",
"$",
"component",
"=",
"$",
"component",
"->",
"obj",
"(",
"$",
"relation",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"LogicException",
"(",
"\"$relation is not a relation/field on \"",
".",
"get_class",
"(",
"$",
"component",
")",
")",
";",
"}",
"}",
"return",
"$",
"component",
";",
"}"
]
| Traverses to a DBField referenced by relationships between data objects.
The path to the related field is specified with dot separated syntax
(eg: Parent.Child.Child.FieldName).
If a relation is blank, this will return null instead.
If a relation name is invalid (e.g. non-relation on a parent) this
can throw a LogicException.
@param string $fieldPath List of paths on this object. All items in this path
must be ViewableData implementors
@return mixed DBField of the field on the object or a DataList instance.
@throws LogicException If accessing invalid relations | [
"Traverses",
"to",
"a",
"DBField",
"referenced",
"by",
"relationships",
"between",
"data",
"objects",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3001-L3030 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.getReverseAssociation | public function getReverseAssociation($className)
{
if (is_array($this->manyMany())) {
$many_many = array_flip($this->manyMany());
if (array_key_exists($className, $many_many)) {
return $many_many[$className];
}
}
if (is_array($this->hasMany())) {
$has_many = array_flip($this->hasMany());
if (array_key_exists($className, $has_many)) {
return $has_many[$className];
}
}
if (is_array($this->hasOne())) {
$has_one = array_flip($this->hasOne());
if (array_key_exists($className, $has_one)) {
return $has_one[$className];
}
}
return false;
} | php | public function getReverseAssociation($className)
{
if (is_array($this->manyMany())) {
$many_many = array_flip($this->manyMany());
if (array_key_exists($className, $many_many)) {
return $many_many[$className];
}
}
if (is_array($this->hasMany())) {
$has_many = array_flip($this->hasMany());
if (array_key_exists($className, $has_many)) {
return $has_many[$className];
}
}
if (is_array($this->hasOne())) {
$has_one = array_flip($this->hasOne());
if (array_key_exists($className, $has_one)) {
return $has_one[$className];
}
}
return false;
} | [
"public",
"function",
"getReverseAssociation",
"(",
"$",
"className",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"manyMany",
"(",
")",
")",
")",
"{",
"$",
"many_many",
"=",
"array_flip",
"(",
"$",
"this",
"->",
"manyMany",
"(",
")",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"className",
",",
"$",
"many_many",
")",
")",
"{",
"return",
"$",
"many_many",
"[",
"$",
"className",
"]",
";",
"}",
"}",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"hasMany",
"(",
")",
")",
")",
"{",
"$",
"has_many",
"=",
"array_flip",
"(",
"$",
"this",
"->",
"hasMany",
"(",
")",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"className",
",",
"$",
"has_many",
")",
")",
"{",
"return",
"$",
"has_many",
"[",
"$",
"className",
"]",
";",
"}",
"}",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"hasOne",
"(",
")",
")",
")",
"{",
"$",
"has_one",
"=",
"array_flip",
"(",
"$",
"this",
"->",
"hasOne",
"(",
")",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"className",
",",
"$",
"has_one",
")",
")",
"{",
"return",
"$",
"has_one",
"[",
"$",
"className",
"]",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Temporary hack to return an association name, based on class, to get around the mangle
of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
@param string $className
@return string | [
"Temporary",
"hack",
"to",
"return",
"an",
"association",
"name",
"based",
"on",
"class",
"to",
"get",
"around",
"the",
"mangle",
"of",
"having",
"to",
"deal",
"with",
"reverse",
"lookup",
"of",
"relationships",
"to",
"determine",
"autogenerated",
"foreign",
"keys",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3066-L3088 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.get | public static function get(
$callerClass = null,
$filter = "",
$sort = "",
$join = "",
$limit = null,
$containerClass = DataList::class
) {
// Validate arguments
if ($callerClass == null) {
$callerClass = get_called_class();
if ($callerClass === self::class) {
throw new InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
}
if ($filter || $sort || $join || $limit || ($containerClass !== DataList::class)) {
throw new InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
. ' arguments');
}
} elseif ($callerClass === self::class) {
throw new InvalidArgumentException('DataObject::get() cannot query non-subclass DataObject directly');
}
if ($join) {
throw new InvalidArgumentException(
'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
);
}
// Build and decorate with args
$result = DataList::create($callerClass);
if ($filter) {
$result = $result->where($filter);
}
if ($sort) {
$result = $result->sort($sort);
}
if ($limit && strpos($limit, ',') !== false) {
$limitArguments = explode(',', $limit);
$result = $result->limit($limitArguments[1], $limitArguments[0]);
} elseif ($limit) {
$result = $result->limit($limit);
}
return $result;
} | php | public static function get(
$callerClass = null,
$filter = "",
$sort = "",
$join = "",
$limit = null,
$containerClass = DataList::class
) {
// Validate arguments
if ($callerClass == null) {
$callerClass = get_called_class();
if ($callerClass === self::class) {
throw new InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
}
if ($filter || $sort || $join || $limit || ($containerClass !== DataList::class)) {
throw new InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
. ' arguments');
}
} elseif ($callerClass === self::class) {
throw new InvalidArgumentException('DataObject::get() cannot query non-subclass DataObject directly');
}
if ($join) {
throw new InvalidArgumentException(
'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
);
}
// Build and decorate with args
$result = DataList::create($callerClass);
if ($filter) {
$result = $result->where($filter);
}
if ($sort) {
$result = $result->sort($sort);
}
if ($limit && strpos($limit, ',') !== false) {
$limitArguments = explode(',', $limit);
$result = $result->limit($limitArguments[1], $limitArguments[0]);
} elseif ($limit) {
$result = $result->limit($limit);
}
return $result;
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"callerClass",
"=",
"null",
",",
"$",
"filter",
"=",
"\"\"",
",",
"$",
"sort",
"=",
"\"\"",
",",
"$",
"join",
"=",
"\"\"",
",",
"$",
"limit",
"=",
"null",
",",
"$",
"containerClass",
"=",
"DataList",
"::",
"class",
")",
"{",
"// Validate arguments",
"if",
"(",
"$",
"callerClass",
"==",
"null",
")",
"{",
"$",
"callerClass",
"=",
"get_called_class",
"(",
")",
";",
"if",
"(",
"$",
"callerClass",
"===",
"self",
"::",
"class",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Call <classname>::get() instead of DataObject::get()'",
")",
";",
"}",
"if",
"(",
"$",
"filter",
"||",
"$",
"sort",
"||",
"$",
"join",
"||",
"$",
"limit",
"||",
"(",
"$",
"containerClass",
"!==",
"DataList",
"::",
"class",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'If calling <classname>::get() then you shouldn\\'t pass any other'",
".",
"' arguments'",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"callerClass",
"===",
"self",
"::",
"class",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'DataObject::get() cannot query non-subclass DataObject directly'",
")",
";",
"}",
"if",
"(",
"$",
"join",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'",
")",
";",
"}",
"// Build and decorate with args",
"$",
"result",
"=",
"DataList",
"::",
"create",
"(",
"$",
"callerClass",
")",
";",
"if",
"(",
"$",
"filter",
")",
"{",
"$",
"result",
"=",
"$",
"result",
"->",
"where",
"(",
"$",
"filter",
")",
";",
"}",
"if",
"(",
"$",
"sort",
")",
"{",
"$",
"result",
"=",
"$",
"result",
"->",
"sort",
"(",
"$",
"sort",
")",
";",
"}",
"if",
"(",
"$",
"limit",
"&&",
"strpos",
"(",
"$",
"limit",
",",
"','",
")",
"!==",
"false",
")",
"{",
"$",
"limitArguments",
"=",
"explode",
"(",
"','",
",",
"$",
"limit",
")",
";",
"$",
"result",
"=",
"$",
"result",
"->",
"limit",
"(",
"$",
"limitArguments",
"[",
"1",
"]",
",",
"$",
"limitArguments",
"[",
"0",
"]",
")",
";",
"}",
"elseif",
"(",
"$",
"limit",
")",
"{",
"$",
"result",
"=",
"$",
"result",
"->",
"limit",
"(",
"$",
"limit",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
]
| Return all objects matching the filter
sub-classes are automatically selected and included
@param string $callerClass The class of objects to be returned
@param string|array $filter A filter to be inserted into the WHERE clause.
Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
@param string|array $sort A sort expression to be inserted into the ORDER
BY clause. If omitted, self::$default_sort will be used.
@param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
@param string|array $limit A limit expression to be inserted into the LIMIT clause.
@param string $containerClass The container class to return the results in.
@todo $containerClass is Ignored, why?
@return DataList The objects matching the filter, in the class specified by $containerClass | [
"Return",
"all",
"objects",
"matching",
"the",
"filter",
"sub",
"-",
"classes",
"are",
"automatically",
"selected",
"and",
"included"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3107-L3150 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.flush_and_destroy_cache | public static function flush_and_destroy_cache()
{
if (self::$_cache_get_one) {
foreach (self::$_cache_get_one as $class => $items) {
if (is_array($items)) {
foreach ($items as $item) {
if ($item) {
$item->destroy();
}
}
}
}
}
self::$_cache_get_one = array();
} | php | public static function flush_and_destroy_cache()
{
if (self::$_cache_get_one) {
foreach (self::$_cache_get_one as $class => $items) {
if (is_array($items)) {
foreach ($items as $item) {
if ($item) {
$item->destroy();
}
}
}
}
}
self::$_cache_get_one = array();
} | [
"public",
"static",
"function",
"flush_and_destroy_cache",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"_cache_get_one",
")",
"{",
"foreach",
"(",
"self",
"::",
"$",
"_cache_get_one",
"as",
"$",
"class",
"=>",
"$",
"items",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"items",
")",
")",
"{",
"foreach",
"(",
"$",
"items",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"$",
"item",
")",
"{",
"$",
"item",
"->",
"destroy",
"(",
")",
";",
"}",
"}",
"}",
"}",
"}",
"self",
"::",
"$",
"_cache_get_one",
"=",
"array",
"(",
")",
";",
"}"
]
| Flush the get_one global cache and destroy associated objects. | [
"Flush",
"the",
"get_one",
"global",
"cache",
"and",
"destroy",
"associated",
"objects",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3228-L3242 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.reset | public static function reset()
{
// @todo Decouple these
DBEnum::flushCache();
ClassInfo::reset_db_cache();
static::getSchema()->reset();
self::$_cache_get_one = array();
self::$_cache_field_labels = array();
} | php | public static function reset()
{
// @todo Decouple these
DBEnum::flushCache();
ClassInfo::reset_db_cache();
static::getSchema()->reset();
self::$_cache_get_one = array();
self::$_cache_field_labels = array();
} | [
"public",
"static",
"function",
"reset",
"(",
")",
"{",
"// @todo Decouple these",
"DBEnum",
"::",
"flushCache",
"(",
")",
";",
"ClassInfo",
"::",
"reset_db_cache",
"(",
")",
";",
"static",
"::",
"getSchema",
"(",
")",
"->",
"reset",
"(",
")",
";",
"self",
"::",
"$",
"_cache_get_one",
"=",
"array",
"(",
")",
";",
"self",
"::",
"$",
"_cache_field_labels",
"=",
"array",
"(",
")",
";",
"}"
]
| Reset all global caches associated with DataObject. | [
"Reset",
"all",
"global",
"caches",
"associated",
"with",
"DataObject",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3247-L3255 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.get_by_id | public static function get_by_id($classOrID, $idOrCache = null, $cache = true)
{
// Shift arguments if passing id in first or second argument
list ($class, $id, $cached) = is_numeric($classOrID)
? [get_called_class(), $classOrID, isset($idOrCache) ? $idOrCache : $cache]
: [$classOrID, $idOrCache, $cache];
// Validate class
if ($class === self::class) {
throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly');
}
// Pass to get_one
$column = static::getSchema()->sqlColumnForField($class, 'ID');
return DataObject::get_one($class, [$column => $id], $cached);
} | php | public static function get_by_id($classOrID, $idOrCache = null, $cache = true)
{
// Shift arguments if passing id in first or second argument
list ($class, $id, $cached) = is_numeric($classOrID)
? [get_called_class(), $classOrID, isset($idOrCache) ? $idOrCache : $cache]
: [$classOrID, $idOrCache, $cache];
// Validate class
if ($class === self::class) {
throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly');
}
// Pass to get_one
$column = static::getSchema()->sqlColumnForField($class, 'ID');
return DataObject::get_one($class, [$column => $id], $cached);
} | [
"public",
"static",
"function",
"get_by_id",
"(",
"$",
"classOrID",
",",
"$",
"idOrCache",
"=",
"null",
",",
"$",
"cache",
"=",
"true",
")",
"{",
"// Shift arguments if passing id in first or second argument",
"list",
"(",
"$",
"class",
",",
"$",
"id",
",",
"$",
"cached",
")",
"=",
"is_numeric",
"(",
"$",
"classOrID",
")",
"?",
"[",
"get_called_class",
"(",
")",
",",
"$",
"classOrID",
",",
"isset",
"(",
"$",
"idOrCache",
")",
"?",
"$",
"idOrCache",
":",
"$",
"cache",
"]",
":",
"[",
"$",
"classOrID",
",",
"$",
"idOrCache",
",",
"$",
"cache",
"]",
";",
"// Validate class",
"if",
"(",
"$",
"class",
"===",
"self",
"::",
"class",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'DataObject::get_by_id() cannot query non-subclass DataObject directly'",
")",
";",
"}",
"// Pass to get_one",
"$",
"column",
"=",
"static",
"::",
"getSchema",
"(",
")",
"->",
"sqlColumnForField",
"(",
"$",
"class",
",",
"'ID'",
")",
";",
"return",
"DataObject",
"::",
"get_one",
"(",
"$",
"class",
",",
"[",
"$",
"column",
"=>",
"$",
"id",
"]",
",",
"$",
"cached",
")",
";",
"}"
]
| Return the given element, searching by ID.
This can be called either via `DataObject::get_by_id(MyClass::class, $id)`
or `MyClass::get_by_id($id)`
@param string|int $classOrID The class of the object to be returned, or id if called on target class
@param int|bool $idOrCache The id of the element, or cache if called on target class
@param boolean $cache See {@link get_one()}
@return static The element | [
"Return",
"the",
"given",
"element",
"searching",
"by",
"ID",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3269-L3284 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.fieldLabels | public function fieldLabels($includerelations = true)
{
$cacheKey = static::class . '_' . $includerelations;
if (!isset(self::$_cache_field_labels[$cacheKey])) {
$customLabels = $this->config()->get('field_labels');
$autoLabels = array();
// get all translated static properties as defined in i18nCollectStatics()
$ancestry = ClassInfo::ancestry(static::class);
$ancestry = array_reverse($ancestry);
if ($ancestry) {
foreach ($ancestry as $ancestorClass) {
if ($ancestorClass === ViewableData::class) {
break;
}
$types = [
'db' => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
];
if ($includerelations) {
$types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
$types['has_many'] = (array)Config::inst()->get(
$ancestorClass,
'has_many',
Config::UNINHERITED
);
$types['many_many'] = (array)Config::inst()->get(
$ancestorClass,
'many_many',
Config::UNINHERITED
);
$types['belongs_many_many'] = (array)Config::inst()->get(
$ancestorClass,
'belongs_many_many',
Config::UNINHERITED
);
}
foreach ($types as $type => $attrs) {
foreach ($attrs as $name => $spec) {
$autoLabels[$name] = _t(
"{$ancestorClass}.{$type}_{$name}",
FormField::name_to_label($name)
);
}
}
}
}
$labels = array_merge((array)$autoLabels, (array)$customLabels);
$this->extend('updateFieldLabels', $labels);
self::$_cache_field_labels[$cacheKey] = $labels;
}
return self::$_cache_field_labels[$cacheKey];
} | php | public function fieldLabels($includerelations = true)
{
$cacheKey = static::class . '_' . $includerelations;
if (!isset(self::$_cache_field_labels[$cacheKey])) {
$customLabels = $this->config()->get('field_labels');
$autoLabels = array();
// get all translated static properties as defined in i18nCollectStatics()
$ancestry = ClassInfo::ancestry(static::class);
$ancestry = array_reverse($ancestry);
if ($ancestry) {
foreach ($ancestry as $ancestorClass) {
if ($ancestorClass === ViewableData::class) {
break;
}
$types = [
'db' => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
];
if ($includerelations) {
$types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
$types['has_many'] = (array)Config::inst()->get(
$ancestorClass,
'has_many',
Config::UNINHERITED
);
$types['many_many'] = (array)Config::inst()->get(
$ancestorClass,
'many_many',
Config::UNINHERITED
);
$types['belongs_many_many'] = (array)Config::inst()->get(
$ancestorClass,
'belongs_many_many',
Config::UNINHERITED
);
}
foreach ($types as $type => $attrs) {
foreach ($attrs as $name => $spec) {
$autoLabels[$name] = _t(
"{$ancestorClass}.{$type}_{$name}",
FormField::name_to_label($name)
);
}
}
}
}
$labels = array_merge((array)$autoLabels, (array)$customLabels);
$this->extend('updateFieldLabels', $labels);
self::$_cache_field_labels[$cacheKey] = $labels;
}
return self::$_cache_field_labels[$cacheKey];
} | [
"public",
"function",
"fieldLabels",
"(",
"$",
"includerelations",
"=",
"true",
")",
"{",
"$",
"cacheKey",
"=",
"static",
"::",
"class",
".",
"'_'",
".",
"$",
"includerelations",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"_cache_field_labels",
"[",
"$",
"cacheKey",
"]",
")",
")",
"{",
"$",
"customLabels",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'field_labels'",
")",
";",
"$",
"autoLabels",
"=",
"array",
"(",
")",
";",
"// get all translated static properties as defined in i18nCollectStatics()",
"$",
"ancestry",
"=",
"ClassInfo",
"::",
"ancestry",
"(",
"static",
"::",
"class",
")",
";",
"$",
"ancestry",
"=",
"array_reverse",
"(",
"$",
"ancestry",
")",
";",
"if",
"(",
"$",
"ancestry",
")",
"{",
"foreach",
"(",
"$",
"ancestry",
"as",
"$",
"ancestorClass",
")",
"{",
"if",
"(",
"$",
"ancestorClass",
"===",
"ViewableData",
"::",
"class",
")",
"{",
"break",
";",
"}",
"$",
"types",
"=",
"[",
"'db'",
"=>",
"(",
"array",
")",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"ancestorClass",
",",
"'db'",
",",
"Config",
"::",
"UNINHERITED",
")",
"]",
";",
"if",
"(",
"$",
"includerelations",
")",
"{",
"$",
"types",
"[",
"'has_one'",
"]",
"=",
"(",
"array",
")",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"ancestorClass",
",",
"'has_one'",
",",
"Config",
"::",
"UNINHERITED",
")",
";",
"$",
"types",
"[",
"'has_many'",
"]",
"=",
"(",
"array",
")",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"ancestorClass",
",",
"'has_many'",
",",
"Config",
"::",
"UNINHERITED",
")",
";",
"$",
"types",
"[",
"'many_many'",
"]",
"=",
"(",
"array",
")",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"ancestorClass",
",",
"'many_many'",
",",
"Config",
"::",
"UNINHERITED",
")",
";",
"$",
"types",
"[",
"'belongs_many_many'",
"]",
"=",
"(",
"array",
")",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"ancestorClass",
",",
"'belongs_many_many'",
",",
"Config",
"::",
"UNINHERITED",
")",
";",
"}",
"foreach",
"(",
"$",
"types",
"as",
"$",
"type",
"=>",
"$",
"attrs",
")",
"{",
"foreach",
"(",
"$",
"attrs",
"as",
"$",
"name",
"=>",
"$",
"spec",
")",
"{",
"$",
"autoLabels",
"[",
"$",
"name",
"]",
"=",
"_t",
"(",
"\"{$ancestorClass}.{$type}_{$name}\"",
",",
"FormField",
"::",
"name_to_label",
"(",
"$",
"name",
")",
")",
";",
"}",
"}",
"}",
"}",
"$",
"labels",
"=",
"array_merge",
"(",
"(",
"array",
")",
"$",
"autoLabels",
",",
"(",
"array",
")",
"$",
"customLabels",
")",
";",
"$",
"this",
"->",
"extend",
"(",
"'updateFieldLabels'",
",",
"$",
"labels",
")",
";",
"self",
"::",
"$",
"_cache_field_labels",
"[",
"$",
"cacheKey",
"]",
"=",
"$",
"labels",
";",
"}",
"return",
"self",
"::",
"$",
"_cache_field_labels",
"[",
"$",
"cacheKey",
"]",
";",
"}"
]
| Get any user defined searchable fields labels that
exist. Allows overriding of default field names in the form
interface actually presented to the user.
The reason for keeping this separate from searchable_fields,
which would be a logical place for this functionality, is to
avoid bloating and complicating the configuration array. Currently
much of this system is based on sensible defaults, and this property
would generally only be set in the case of more complex relationships
between data object being required in the search interface.
Generates labels based on name of the field itself, if no static property
{@link self::field_labels} exists.
@uses $field_labels
@uses FormField::name_to_label()
@param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
@return array Array of all element labels | [
"Get",
"any",
"user",
"defined",
"searchable",
"fields",
"labels",
"that",
"exist",
".",
"Allows",
"overriding",
"of",
"default",
"field",
"names",
"in",
"the",
"form",
"interface",
"actually",
"presented",
"to",
"the",
"user",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3582-L3636 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.summaryFields | public function summaryFields()
{
$rawFields = $this->config()->get('summary_fields');
// Merge associative / numeric keys
$fields = [];
foreach ($rawFields as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$fields[$key] = $value;
}
if (!$fields) {
$fields = array();
// try to scaffold a couple of usual suspects
if ($this->hasField('Name')) {
$fields['Name'] = 'Name';
}
if (static::getSchema()->fieldSpec($this, 'Title')) {
$fields['Title'] = 'Title';
}
if ($this->hasField('Description')) {
$fields['Description'] = 'Description';
}
if ($this->hasField('FirstName')) {
$fields['FirstName'] = 'First Name';
}
}
$this->extend("updateSummaryFields", $fields);
// Final fail-over, just list ID field
if (!$fields) {
$fields['ID'] = 'ID';
}
// Localize fields (if possible)
foreach ($this->fieldLabels(false) as $name => $label) {
// only attempt to localize if the label definition is the same as the field name.
// this will preserve any custom labels set in the summary_fields configuration
if (isset($fields[$name]) && $name === $fields[$name]) {
$fields[$name] = $label;
}
}
return $fields;
} | php | public function summaryFields()
{
$rawFields = $this->config()->get('summary_fields');
// Merge associative / numeric keys
$fields = [];
foreach ($rawFields as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$fields[$key] = $value;
}
if (!$fields) {
$fields = array();
// try to scaffold a couple of usual suspects
if ($this->hasField('Name')) {
$fields['Name'] = 'Name';
}
if (static::getSchema()->fieldSpec($this, 'Title')) {
$fields['Title'] = 'Title';
}
if ($this->hasField('Description')) {
$fields['Description'] = 'Description';
}
if ($this->hasField('FirstName')) {
$fields['FirstName'] = 'First Name';
}
}
$this->extend("updateSummaryFields", $fields);
// Final fail-over, just list ID field
if (!$fields) {
$fields['ID'] = 'ID';
}
// Localize fields (if possible)
foreach ($this->fieldLabels(false) as $name => $label) {
// only attempt to localize if the label definition is the same as the field name.
// this will preserve any custom labels set in the summary_fields configuration
if (isset($fields[$name]) && $name === $fields[$name]) {
$fields[$name] = $label;
}
}
return $fields;
} | [
"public",
"function",
"summaryFields",
"(",
")",
"{",
"$",
"rawFields",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'summary_fields'",
")",
";",
"// Merge associative / numeric keys",
"$",
"fields",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"rawFields",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"key",
")",
")",
"{",
"$",
"key",
"=",
"$",
"value",
";",
"}",
"$",
"fields",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"if",
"(",
"!",
"$",
"fields",
")",
"{",
"$",
"fields",
"=",
"array",
"(",
")",
";",
"// try to scaffold a couple of usual suspects",
"if",
"(",
"$",
"this",
"->",
"hasField",
"(",
"'Name'",
")",
")",
"{",
"$",
"fields",
"[",
"'Name'",
"]",
"=",
"'Name'",
";",
"}",
"if",
"(",
"static",
"::",
"getSchema",
"(",
")",
"->",
"fieldSpec",
"(",
"$",
"this",
",",
"'Title'",
")",
")",
"{",
"$",
"fields",
"[",
"'Title'",
"]",
"=",
"'Title'",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"hasField",
"(",
"'Description'",
")",
")",
"{",
"$",
"fields",
"[",
"'Description'",
"]",
"=",
"'Description'",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"hasField",
"(",
"'FirstName'",
")",
")",
"{",
"$",
"fields",
"[",
"'FirstName'",
"]",
"=",
"'First Name'",
";",
"}",
"}",
"$",
"this",
"->",
"extend",
"(",
"\"updateSummaryFields\"",
",",
"$",
"fields",
")",
";",
"// Final fail-over, just list ID field",
"if",
"(",
"!",
"$",
"fields",
")",
"{",
"$",
"fields",
"[",
"'ID'",
"]",
"=",
"'ID'",
";",
"}",
"// Localize fields (if possible)",
"foreach",
"(",
"$",
"this",
"->",
"fieldLabels",
"(",
"false",
")",
"as",
"$",
"name",
"=>",
"$",
"label",
")",
"{",
"// only attempt to localize if the label definition is the same as the field name.",
"// this will preserve any custom labels set in the summary_fields configuration",
"if",
"(",
"isset",
"(",
"$",
"fields",
"[",
"$",
"name",
"]",
")",
"&&",
"$",
"name",
"===",
"$",
"fields",
"[",
"$",
"name",
"]",
")",
"{",
"$",
"fields",
"[",
"$",
"name",
"]",
"=",
"$",
"label",
";",
"}",
"}",
"return",
"$",
"fields",
";",
"}"
]
| Get the default summary fields for this object.
@todo use the translation apparatus to return a default field selection for the language
@return array | [
"Get",
"the",
"default",
"summary",
"fields",
"for",
"this",
"object",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3661-L3707 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.defaultSearchFilters | public function defaultSearchFilters()
{
$filters = array();
foreach ($this->searchableFields() as $name => $spec) {
if (empty($spec['filter'])) {
/** @skipUpgrade */
$filters[$name] = 'PartialMatchFilter';
} elseif ($spec['filter'] instanceof SearchFilter) {
$filters[$name] = $spec['filter'];
} else {
$filters[$name] = Injector::inst()->create($spec['filter'], $name);
}
}
return $filters;
} | php | public function defaultSearchFilters()
{
$filters = array();
foreach ($this->searchableFields() as $name => $spec) {
if (empty($spec['filter'])) {
/** @skipUpgrade */
$filters[$name] = 'PartialMatchFilter';
} elseif ($spec['filter'] instanceof SearchFilter) {
$filters[$name] = $spec['filter'];
} else {
$filters[$name] = Injector::inst()->create($spec['filter'], $name);
}
}
return $filters;
} | [
"public",
"function",
"defaultSearchFilters",
"(",
")",
"{",
"$",
"filters",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"searchableFields",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"spec",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"spec",
"[",
"'filter'",
"]",
")",
")",
"{",
"/** @skipUpgrade */",
"$",
"filters",
"[",
"$",
"name",
"]",
"=",
"'PartialMatchFilter'",
";",
"}",
"elseif",
"(",
"$",
"spec",
"[",
"'filter'",
"]",
"instanceof",
"SearchFilter",
")",
"{",
"$",
"filters",
"[",
"$",
"name",
"]",
"=",
"$",
"spec",
"[",
"'filter'",
"]",
";",
"}",
"else",
"{",
"$",
"filters",
"[",
"$",
"name",
"]",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"create",
"(",
"$",
"spec",
"[",
"'filter'",
"]",
",",
"$",
"name",
")",
";",
"}",
"}",
"return",
"$",
"filters",
";",
"}"
]
| Defines a default list of filters for the search context.
If a filter class mapping is defined on the data object,
it is constructed here. Otherwise, the default filter specified in
{@link DBField} is used.
@todo error handling/type checking for valid FormField and SearchFilter subclasses?
@return array | [
"Defines",
"a",
"default",
"list",
"of",
"filters",
"for",
"the",
"search",
"context",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L3720-L3736 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.setJoin | public function setJoin(DataObject $object, $alias = null)
{
$this->joinRecord = $object;
if ($alias) {
if (static::getSchema()->fieldSpec(static::class, $alias)) {
throw new InvalidArgumentException(
"Joined record $alias cannot also be a db field"
);
}
$this->record[$alias] = $object;
}
return $this;
} | php | public function setJoin(DataObject $object, $alias = null)
{
$this->joinRecord = $object;
if ($alias) {
if (static::getSchema()->fieldSpec(static::class, $alias)) {
throw new InvalidArgumentException(
"Joined record $alias cannot also be a db field"
);
}
$this->record[$alias] = $object;
}
return $this;
} | [
"public",
"function",
"setJoin",
"(",
"DataObject",
"$",
"object",
",",
"$",
"alias",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"joinRecord",
"=",
"$",
"object",
";",
"if",
"(",
"$",
"alias",
")",
"{",
"if",
"(",
"static",
"::",
"getSchema",
"(",
")",
"->",
"fieldSpec",
"(",
"static",
"::",
"class",
",",
"$",
"alias",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Joined record $alias cannot also be a db field\"",
")",
";",
"}",
"$",
"this",
"->",
"record",
"[",
"$",
"alias",
"]",
"=",
"$",
"object",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Set joining object
@param DataObject $object
@param string $alias Alias
@return $this | [
"Set",
"joining",
"object"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L4035-L4047 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.findRelatedObjects | public function findRelatedObjects($source, $recursive = true, $list = null)
{
if (!$list) {
$list = new ArrayList();
}
// Skip search for unsaved records
if (!$this->isInDB()) {
return $list;
}
$relationships = $this->config()->get($source) ?: [];
foreach ($relationships as $relationship) {
// Warn if invalid config
if (!$this->hasMethod($relationship)) {
trigger_error(sprintf(
"Invalid %s config value \"%s\" on object on class \"%s\"",
$source,
$relationship,
get_class($this)
), E_USER_WARNING);
continue;
}
// Inspect value of this relationship
$items = $this->{$relationship}();
// Merge any new item
$newItems = $this->mergeRelatedObjects($list, $items);
// Recurse if necessary
if ($recursive) {
foreach ($newItems as $item) {
/** @var DataObject $item */
$item->findRelatedObjects($source, true, $list);
}
}
}
return $list;
} | php | public function findRelatedObjects($source, $recursive = true, $list = null)
{
if (!$list) {
$list = new ArrayList();
}
// Skip search for unsaved records
if (!$this->isInDB()) {
return $list;
}
$relationships = $this->config()->get($source) ?: [];
foreach ($relationships as $relationship) {
// Warn if invalid config
if (!$this->hasMethod($relationship)) {
trigger_error(sprintf(
"Invalid %s config value \"%s\" on object on class \"%s\"",
$source,
$relationship,
get_class($this)
), E_USER_WARNING);
continue;
}
// Inspect value of this relationship
$items = $this->{$relationship}();
// Merge any new item
$newItems = $this->mergeRelatedObjects($list, $items);
// Recurse if necessary
if ($recursive) {
foreach ($newItems as $item) {
/** @var DataObject $item */
$item->findRelatedObjects($source, true, $list);
}
}
}
return $list;
} | [
"public",
"function",
"findRelatedObjects",
"(",
"$",
"source",
",",
"$",
"recursive",
"=",
"true",
",",
"$",
"list",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"list",
")",
"{",
"$",
"list",
"=",
"new",
"ArrayList",
"(",
")",
";",
"}",
"// Skip search for unsaved records",
"if",
"(",
"!",
"$",
"this",
"->",
"isInDB",
"(",
")",
")",
"{",
"return",
"$",
"list",
";",
"}",
"$",
"relationships",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"$",
"source",
")",
"?",
":",
"[",
"]",
";",
"foreach",
"(",
"$",
"relationships",
"as",
"$",
"relationship",
")",
"{",
"// Warn if invalid config",
"if",
"(",
"!",
"$",
"this",
"->",
"hasMethod",
"(",
"$",
"relationship",
")",
")",
"{",
"trigger_error",
"(",
"sprintf",
"(",
"\"Invalid %s config value \\\"%s\\\" on object on class \\\"%s\\\"\"",
",",
"$",
"source",
",",
"$",
"relationship",
",",
"get_class",
"(",
"$",
"this",
")",
")",
",",
"E_USER_WARNING",
")",
";",
"continue",
";",
"}",
"// Inspect value of this relationship",
"$",
"items",
"=",
"$",
"this",
"->",
"{",
"$",
"relationship",
"}",
"(",
")",
";",
"// Merge any new item",
"$",
"newItems",
"=",
"$",
"this",
"->",
"mergeRelatedObjects",
"(",
"$",
"list",
",",
"$",
"items",
")",
";",
"// Recurse if necessary",
"if",
"(",
"$",
"recursive",
")",
"{",
"foreach",
"(",
"$",
"newItems",
"as",
"$",
"item",
")",
"{",
"/** @var DataObject $item */",
"$",
"item",
"->",
"findRelatedObjects",
"(",
"$",
"source",
",",
"true",
",",
"$",
"list",
")",
";",
"}",
"}",
"}",
"return",
"$",
"list",
";",
"}"
]
| Find objects in the given relationships, merging them into the given list
@param string $source Config property to extract relationships from
@param bool $recursive True if recursive
@param ArrayList $list If specified, items will be added to this list. If not, a new
instance of ArrayList will be constructed and returned
@return ArrayList The list of related objects | [
"Find",
"objects",
"in",
"the",
"given",
"relationships",
"merging",
"them",
"into",
"the",
"given",
"list"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L4058-L4097 | train |
silverstripe/silverstripe-framework | src/ORM/DataObject.php | DataObject.mergeRelatedObject | protected function mergeRelatedObject($list, $added, $item)
{
// Identify item
$itemKey = get_class($item) . '/' . $item->ID;
// Write if saved, versioned, and not already added
if ($item->isInDB() && !isset($list[$itemKey])) {
$list[$itemKey] = $item;
$added[$itemKey] = $item;
}
// Add joined record (from many_many through) automatically
$joined = $item->getJoin();
if ($joined) {
$this->mergeRelatedObject($list, $added, $joined);
}
} | php | protected function mergeRelatedObject($list, $added, $item)
{
// Identify item
$itemKey = get_class($item) . '/' . $item->ID;
// Write if saved, versioned, and not already added
if ($item->isInDB() && !isset($list[$itemKey])) {
$list[$itemKey] = $item;
$added[$itemKey] = $item;
}
// Add joined record (from many_many through) automatically
$joined = $item->getJoin();
if ($joined) {
$this->mergeRelatedObject($list, $added, $joined);
}
} | [
"protected",
"function",
"mergeRelatedObject",
"(",
"$",
"list",
",",
"$",
"added",
",",
"$",
"item",
")",
"{",
"// Identify item",
"$",
"itemKey",
"=",
"get_class",
"(",
"$",
"item",
")",
".",
"'/'",
".",
"$",
"item",
"->",
"ID",
";",
"// Write if saved, versioned, and not already added",
"if",
"(",
"$",
"item",
"->",
"isInDB",
"(",
")",
"&&",
"!",
"isset",
"(",
"$",
"list",
"[",
"$",
"itemKey",
"]",
")",
")",
"{",
"$",
"list",
"[",
"$",
"itemKey",
"]",
"=",
"$",
"item",
";",
"$",
"added",
"[",
"$",
"itemKey",
"]",
"=",
"$",
"item",
";",
"}",
"// Add joined record (from many_many through) automatically",
"$",
"joined",
"=",
"$",
"item",
"->",
"getJoin",
"(",
")",
";",
"if",
"(",
"$",
"joined",
")",
"{",
"$",
"this",
"->",
"mergeRelatedObject",
"(",
"$",
"list",
",",
"$",
"added",
",",
"$",
"joined",
")",
";",
"}",
"}"
]
| Merge single object into a list, but ensures that existing objects are not
re-added.
@param ArrayList $list Global list
@param ArrayList $added Additional list to insert into
@param DataObject $item Item to add | [
"Merge",
"single",
"object",
"into",
"a",
"list",
"but",
"ensures",
"that",
"existing",
"objects",
"are",
"not",
"re",
"-",
"added",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/DataObject.php#L4132-L4148 | train |
silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPrintButton.php | GridFieldPrintButton.handleAction | public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if ($actionName == 'print') {
return $this->handlePrint($gridField);
}
} | php | public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if ($actionName == 'print') {
return $this->handlePrint($gridField);
}
} | [
"public",
"function",
"handleAction",
"(",
"GridField",
"$",
"gridField",
",",
"$",
"actionName",
",",
"$",
"arguments",
",",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"actionName",
"==",
"'print'",
")",
"{",
"return",
"$",
"this",
"->",
"handlePrint",
"(",
"$",
"gridField",
")",
";",
"}",
"}"
]
| Handle the print action.
@param GridField $gridField
@param string $actionName
@param array $arguments
@param array $data
@return DBHTMLText | [
"Handle",
"the",
"print",
"action",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldPrintButton.php#L99-L104 | train |
silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPrintButton.php | GridFieldPrintButton.handlePrint | public function handlePrint($gridField, $request = null)
{
set_time_limit(60);
Requirements::clear();
$data = $this->generatePrintData($gridField);
$this->extend('updatePrintData', $data);
if ($data) {
return $data->renderWith([
get_class($gridField) . '_print',
GridField::class . '_print',
]);
}
return null;
} | php | public function handlePrint($gridField, $request = null)
{
set_time_limit(60);
Requirements::clear();
$data = $this->generatePrintData($gridField);
$this->extend('updatePrintData', $data);
if ($data) {
return $data->renderWith([
get_class($gridField) . '_print',
GridField::class . '_print',
]);
}
return null;
} | [
"public",
"function",
"handlePrint",
"(",
"$",
"gridField",
",",
"$",
"request",
"=",
"null",
")",
"{",
"set_time_limit",
"(",
"60",
")",
";",
"Requirements",
"::",
"clear",
"(",
")",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"generatePrintData",
"(",
"$",
"gridField",
")",
";",
"$",
"this",
"->",
"extend",
"(",
"'updatePrintData'",
",",
"$",
"data",
")",
";",
"if",
"(",
"$",
"data",
")",
"{",
"return",
"$",
"data",
"->",
"renderWith",
"(",
"[",
"get_class",
"(",
"$",
"gridField",
")",
".",
"'_print'",
",",
"GridField",
"::",
"class",
".",
"'_print'",
",",
"]",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Handle the print, for both the action button and the URL
@param GridField $gridField
@param HTTPRequest $request
@return DBHTMLText | [
"Handle",
"the",
"print",
"for",
"both",
"the",
"action",
"button",
"and",
"the",
"URL"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldPrintButton.php#L126-L143 | train |
silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPrintButton.php | GridFieldPrintButton.getPrintColumnsForGridField | protected function getPrintColumnsForGridField(GridField $gridField)
{
if ($this->printColumns) {
return $this->printColumns;
}
/** @var GridFieldDataColumns $dataCols */
$dataCols = $gridField->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
if ($dataCols) {
return $dataCols->getDisplayFields($gridField);
}
return DataObject::singleton($gridField->getModelClass())->summaryFields();
} | php | protected function getPrintColumnsForGridField(GridField $gridField)
{
if ($this->printColumns) {
return $this->printColumns;
}
/** @var GridFieldDataColumns $dataCols */
$dataCols = $gridField->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
if ($dataCols) {
return $dataCols->getDisplayFields($gridField);
}
return DataObject::singleton($gridField->getModelClass())->summaryFields();
} | [
"protected",
"function",
"getPrintColumnsForGridField",
"(",
"GridField",
"$",
"gridField",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"printColumns",
")",
"{",
"return",
"$",
"this",
"->",
"printColumns",
";",
"}",
"/** @var GridFieldDataColumns $dataCols */",
"$",
"dataCols",
"=",
"$",
"gridField",
"->",
"getConfig",
"(",
")",
"->",
"getComponentByType",
"(",
"'SilverStripe\\\\Forms\\\\GridField\\\\GridFieldDataColumns'",
")",
";",
"if",
"(",
"$",
"dataCols",
")",
"{",
"return",
"$",
"dataCols",
"->",
"getDisplayFields",
"(",
"$",
"gridField",
")",
";",
"}",
"return",
"DataObject",
"::",
"singleton",
"(",
"$",
"gridField",
"->",
"getModelClass",
"(",
")",
")",
"->",
"summaryFields",
"(",
")",
";",
"}"
]
| Return the columns to print
@param GridField
@return array | [
"Return",
"the",
"columns",
"to",
"print"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldPrintButton.php#L152-L165 | train |
silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPrintButton.php | GridFieldPrintButton.getTitle | public function getTitle(GridField $gridField)
{
$form = $gridField->getForm();
$currentController = $gridField->getForm()->getController();
$title = '';
if (method_exists($currentController, 'Title')) {
$title = $currentController->Title();
} else {
if ($currentController->Title) {
$title = $currentController->Title;
} elseif ($form->getName()) {
$title = $form->getName();
}
}
if ($fieldTitle = $gridField->Title()) {
if ($title) {
$title .= " - ";
}
$title .= $fieldTitle;
}
return $title;
} | php | public function getTitle(GridField $gridField)
{
$form = $gridField->getForm();
$currentController = $gridField->getForm()->getController();
$title = '';
if (method_exists($currentController, 'Title')) {
$title = $currentController->Title();
} else {
if ($currentController->Title) {
$title = $currentController->Title;
} elseif ($form->getName()) {
$title = $form->getName();
}
}
if ($fieldTitle = $gridField->Title()) {
if ($title) {
$title .= " - ";
}
$title .= $fieldTitle;
}
return $title;
} | [
"public",
"function",
"getTitle",
"(",
"GridField",
"$",
"gridField",
")",
"{",
"$",
"form",
"=",
"$",
"gridField",
"->",
"getForm",
"(",
")",
";",
"$",
"currentController",
"=",
"$",
"gridField",
"->",
"getForm",
"(",
")",
"->",
"getController",
"(",
")",
";",
"$",
"title",
"=",
"''",
";",
"if",
"(",
"method_exists",
"(",
"$",
"currentController",
",",
"'Title'",
")",
")",
"{",
"$",
"title",
"=",
"$",
"currentController",
"->",
"Title",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"currentController",
"->",
"Title",
")",
"{",
"$",
"title",
"=",
"$",
"currentController",
"->",
"Title",
";",
"}",
"elseif",
"(",
"$",
"form",
"->",
"getName",
"(",
")",
")",
"{",
"$",
"title",
"=",
"$",
"form",
"->",
"getName",
"(",
")",
";",
"}",
"}",
"if",
"(",
"$",
"fieldTitle",
"=",
"$",
"gridField",
"->",
"Title",
"(",
")",
")",
"{",
"if",
"(",
"$",
"title",
")",
"{",
"$",
"title",
".=",
"\" - \"",
";",
"}",
"$",
"title",
".=",
"$",
"fieldTitle",
";",
"}",
"return",
"$",
"title",
";",
"}"
]
| Return the title of the printed page
@param GridField
@return array | [
"Return",
"the",
"title",
"of",
"the",
"printed",
"page"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldPrintButton.php#L174-L199 | train |
silverstripe/silverstripe-framework | src/Forms/GridField/GridFieldPrintButton.php | GridFieldPrintButton.generatePrintData | public function generatePrintData(GridField $gridField)
{
$printColumns = $this->getPrintColumnsForGridField($gridField);
$header = null;
if ($this->printHasHeader) {
$header = new ArrayList();
foreach ($printColumns as $field => $label) {
$header->push(new ArrayData(array(
"CellString" => $label,
)));
}
}
$items = $gridField->getManipulatedList();
$itemRows = new ArrayList();
/** @var DataObject $item */
foreach ($items->limit(null) as $item) {
$itemRow = new ArrayList();
foreach ($printColumns as $field => $label) {
$value = $gridField->getDataFieldValue($item, $field);
$itemRow->push(new ArrayData(array(
"CellString" => $value,
)));
}
$itemRows->push(new ArrayData(array(
"ItemRow" => $itemRow
)));
if ($item->hasMethod('destroy')) {
$item->destroy();
}
}
$ret = new ArrayData(array(
"Title" => $this->getTitle($gridField),
"Header" => $header,
"ItemRows" => $itemRows,
"Datetime" => DBDatetime::now(),
"Member" => Security::getCurrentUser(),
));
return $ret;
} | php | public function generatePrintData(GridField $gridField)
{
$printColumns = $this->getPrintColumnsForGridField($gridField);
$header = null;
if ($this->printHasHeader) {
$header = new ArrayList();
foreach ($printColumns as $field => $label) {
$header->push(new ArrayData(array(
"CellString" => $label,
)));
}
}
$items = $gridField->getManipulatedList();
$itemRows = new ArrayList();
/** @var DataObject $item */
foreach ($items->limit(null) as $item) {
$itemRow = new ArrayList();
foreach ($printColumns as $field => $label) {
$value = $gridField->getDataFieldValue($item, $field);
$itemRow->push(new ArrayData(array(
"CellString" => $value,
)));
}
$itemRows->push(new ArrayData(array(
"ItemRow" => $itemRow
)));
if ($item->hasMethod('destroy')) {
$item->destroy();
}
}
$ret = new ArrayData(array(
"Title" => $this->getTitle($gridField),
"Header" => $header,
"ItemRows" => $itemRows,
"Datetime" => DBDatetime::now(),
"Member" => Security::getCurrentUser(),
));
return $ret;
} | [
"public",
"function",
"generatePrintData",
"(",
"GridField",
"$",
"gridField",
")",
"{",
"$",
"printColumns",
"=",
"$",
"this",
"->",
"getPrintColumnsForGridField",
"(",
"$",
"gridField",
")",
";",
"$",
"header",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"printHasHeader",
")",
"{",
"$",
"header",
"=",
"new",
"ArrayList",
"(",
")",
";",
"foreach",
"(",
"$",
"printColumns",
"as",
"$",
"field",
"=>",
"$",
"label",
")",
"{",
"$",
"header",
"->",
"push",
"(",
"new",
"ArrayData",
"(",
"array",
"(",
"\"CellString\"",
"=>",
"$",
"label",
",",
")",
")",
")",
";",
"}",
"}",
"$",
"items",
"=",
"$",
"gridField",
"->",
"getManipulatedList",
"(",
")",
";",
"$",
"itemRows",
"=",
"new",
"ArrayList",
"(",
")",
";",
"/** @var DataObject $item */",
"foreach",
"(",
"$",
"items",
"->",
"limit",
"(",
"null",
")",
"as",
"$",
"item",
")",
"{",
"$",
"itemRow",
"=",
"new",
"ArrayList",
"(",
")",
";",
"foreach",
"(",
"$",
"printColumns",
"as",
"$",
"field",
"=>",
"$",
"label",
")",
"{",
"$",
"value",
"=",
"$",
"gridField",
"->",
"getDataFieldValue",
"(",
"$",
"item",
",",
"$",
"field",
")",
";",
"$",
"itemRow",
"->",
"push",
"(",
"new",
"ArrayData",
"(",
"array",
"(",
"\"CellString\"",
"=>",
"$",
"value",
",",
")",
")",
")",
";",
"}",
"$",
"itemRows",
"->",
"push",
"(",
"new",
"ArrayData",
"(",
"array",
"(",
"\"ItemRow\"",
"=>",
"$",
"itemRow",
")",
")",
")",
";",
"if",
"(",
"$",
"item",
"->",
"hasMethod",
"(",
"'destroy'",
")",
")",
"{",
"$",
"item",
"->",
"destroy",
"(",
")",
";",
"}",
"}",
"$",
"ret",
"=",
"new",
"ArrayData",
"(",
"array",
"(",
"\"Title\"",
"=>",
"$",
"this",
"->",
"getTitle",
"(",
"$",
"gridField",
")",
",",
"\"Header\"",
"=>",
"$",
"header",
",",
"\"ItemRows\"",
"=>",
"$",
"itemRows",
",",
"\"Datetime\"",
"=>",
"DBDatetime",
"::",
"now",
"(",
")",
",",
"\"Member\"",
"=>",
"Security",
"::",
"getCurrentUser",
"(",
")",
",",
")",
")",
";",
"return",
"$",
"ret",
";",
"}"
]
| Export core.
@param GridField $gridField
@return ArrayData | [
"Export",
"core",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldPrintButton.php#L207-L255 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.restoreFormState | public function restoreFormState()
{
// Restore messages
$result = $this->getSessionValidationResult();
if (isset($result)) {
$this->loadMessagesFrom($result);
}
// load data in from previous submission upon error
$data = $this->getSessionData();
if (isset($data)) {
$this->loadDataFrom($data, self::MERGE_AS_INTERNAL_VALUE);
}
return $this;
} | php | public function restoreFormState()
{
// Restore messages
$result = $this->getSessionValidationResult();
if (isset($result)) {
$this->loadMessagesFrom($result);
}
// load data in from previous submission upon error
$data = $this->getSessionData();
if (isset($data)) {
$this->loadDataFrom($data, self::MERGE_AS_INTERNAL_VALUE);
}
return $this;
} | [
"public",
"function",
"restoreFormState",
"(",
")",
"{",
"// Restore messages",
"$",
"result",
"=",
"$",
"this",
"->",
"getSessionValidationResult",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"result",
")",
")",
"{",
"$",
"this",
"->",
"loadMessagesFrom",
"(",
"$",
"result",
")",
";",
"}",
"// load data in from previous submission upon error",
"$",
"data",
"=",
"$",
"this",
"->",
"getSessionData",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"data",
")",
")",
"{",
"$",
"this",
"->",
"loadDataFrom",
"(",
"$",
"data",
",",
"self",
"::",
"MERGE_AS_INTERNAL_VALUE",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Load form state from session state
@return $this | [
"Load",
"form",
"state",
"from",
"session",
"state"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L341-L355 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.getRequest | protected function getRequest()
{
// Check if current request handler has a request object
$controller = $this->getController();
if ($controller && !($controller->getRequest() instanceof NullHTTPRequest)) {
return $controller->getRequest();
}
// Fall back to current controller
if (Controller::has_curr() && !(Controller::curr()->getRequest() instanceof NullHTTPRequest)) {
return Controller::curr()->getRequest();
}
return null;
} | php | protected function getRequest()
{
// Check if current request handler has a request object
$controller = $this->getController();
if ($controller && !($controller->getRequest() instanceof NullHTTPRequest)) {
return $controller->getRequest();
}
// Fall back to current controller
if (Controller::has_curr() && !(Controller::curr()->getRequest() instanceof NullHTTPRequest)) {
return Controller::curr()->getRequest();
}
return null;
} | [
"protected",
"function",
"getRequest",
"(",
")",
"{",
"// Check if current request handler has a request object",
"$",
"controller",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
";",
"if",
"(",
"$",
"controller",
"&&",
"!",
"(",
"$",
"controller",
"->",
"getRequest",
"(",
")",
"instanceof",
"NullHTTPRequest",
")",
")",
"{",
"return",
"$",
"controller",
"->",
"getRequest",
"(",
")",
";",
"}",
"// Fall back to current controller",
"if",
"(",
"Controller",
"::",
"has_curr",
"(",
")",
"&&",
"!",
"(",
"Controller",
"::",
"curr",
"(",
")",
"->",
"getRequest",
"(",
")",
"instanceof",
"NullHTTPRequest",
")",
")",
"{",
"return",
"Controller",
"::",
"curr",
"(",
")",
"->",
"getRequest",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Helper to get current request for this form
@return HTTPRequest | [
"Helper",
"to",
"get",
"current",
"request",
"for",
"this",
"form"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L376-L388 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.getSessionValidationResult | public function getSessionValidationResult()
{
$resultData = $this->getSession()->get("FormInfo.{$this->FormName()}.result");
if (isset($resultData)) {
return unserialize($resultData);
}
return null;
} | php | public function getSessionValidationResult()
{
$resultData = $this->getSession()->get("FormInfo.{$this->FormName()}.result");
if (isset($resultData)) {
return unserialize($resultData);
}
return null;
} | [
"public",
"function",
"getSessionValidationResult",
"(",
")",
"{",
"$",
"resultData",
"=",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"get",
"(",
"\"FormInfo.{$this->FormName()}.result\"",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"resultData",
")",
")",
"{",
"return",
"unserialize",
"(",
"$",
"resultData",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Return any ValidationResult instance stored for this object
@return ValidationResult The ValidationResult object stored in the session | [
"Return",
"any",
"ValidationResult",
"instance",
"stored",
"for",
"this",
"object"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L431-L438 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.setSessionValidationResult | public function setSessionValidationResult(ValidationResult $result, $combineWithExisting = false)
{
// Combine with existing result
if ($combineWithExisting) {
$existingResult = $this->getSessionValidationResult();
if ($existingResult) {
if ($result) {
$existingResult->combineAnd($result);
} else {
$result = $existingResult;
}
}
}
// Serialise
$resultData = $result ? serialize($result) : null;
$this->getSession()->set("FormInfo.{$this->FormName()}.result", $resultData);
return $this;
} | php | public function setSessionValidationResult(ValidationResult $result, $combineWithExisting = false)
{
// Combine with existing result
if ($combineWithExisting) {
$existingResult = $this->getSessionValidationResult();
if ($existingResult) {
if ($result) {
$existingResult->combineAnd($result);
} else {
$result = $existingResult;
}
}
}
// Serialise
$resultData = $result ? serialize($result) : null;
$this->getSession()->set("FormInfo.{$this->FormName()}.result", $resultData);
return $this;
} | [
"public",
"function",
"setSessionValidationResult",
"(",
"ValidationResult",
"$",
"result",
",",
"$",
"combineWithExisting",
"=",
"false",
")",
"{",
"// Combine with existing result",
"if",
"(",
"$",
"combineWithExisting",
")",
"{",
"$",
"existingResult",
"=",
"$",
"this",
"->",
"getSessionValidationResult",
"(",
")",
";",
"if",
"(",
"$",
"existingResult",
")",
"{",
"if",
"(",
"$",
"result",
")",
"{",
"$",
"existingResult",
"->",
"combineAnd",
"(",
"$",
"result",
")",
";",
"}",
"else",
"{",
"$",
"result",
"=",
"$",
"existingResult",
";",
"}",
"}",
"}",
"// Serialise",
"$",
"resultData",
"=",
"$",
"result",
"?",
"serialize",
"(",
"$",
"result",
")",
":",
"null",
";",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"set",
"(",
"\"FormInfo.{$this->FormName()}.result\"",
",",
"$",
"resultData",
")",
";",
"return",
"$",
"this",
";",
"}"
]
| Sets the ValidationResult in the session to be used with the next view of this form.
@param ValidationResult $result The result to save
@param bool $combineWithExisting If true, then this will be added to the existing result.
@return $this | [
"Sets",
"the",
"ValidationResult",
"in",
"the",
"session",
"to",
"be",
"used",
"with",
"the",
"next",
"view",
"of",
"this",
"form",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L446-L464 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.setFieldMessage | public function setFieldMessage(
$fieldName,
$message,
$messageType = ValidationResult::TYPE_ERROR,
$messageCast = ValidationResult::CAST_TEXT
) {
$field = $this->fields->dataFieldByName($fieldName);
if ($field) {
$field->setMessage($message, $messageType, $messageCast);
}
return $this;
} | php | public function setFieldMessage(
$fieldName,
$message,
$messageType = ValidationResult::TYPE_ERROR,
$messageCast = ValidationResult::CAST_TEXT
) {
$field = $this->fields->dataFieldByName($fieldName);
if ($field) {
$field->setMessage($message, $messageType, $messageCast);
}
return $this;
} | [
"public",
"function",
"setFieldMessage",
"(",
"$",
"fieldName",
",",
"$",
"message",
",",
"$",
"messageType",
"=",
"ValidationResult",
"::",
"TYPE_ERROR",
",",
"$",
"messageCast",
"=",
"ValidationResult",
"::",
"CAST_TEXT",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"fields",
"->",
"dataFieldByName",
"(",
"$",
"fieldName",
")",
";",
"if",
"(",
"$",
"field",
")",
"{",
"$",
"field",
"->",
"setMessage",
"(",
"$",
"message",
",",
"$",
"messageType",
",",
"$",
"messageCast",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Set message on a given field name. This message will not persist via redirect.
@param string $fieldName
@param string $message
@param string $messageType
@param string $messageCast
@return $this | [
"Set",
"message",
"on",
"a",
"given",
"field",
"name",
".",
"This",
"message",
"will",
"not",
"persist",
"via",
"redirect",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L511-L522 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.setupDefaultClasses | protected function setupDefaultClasses()
{
$defaultClasses = self::config()->get('default_classes');
if ($defaultClasses) {
foreach ($defaultClasses as $class) {
$this->addExtraClass($class);
}
}
} | php | protected function setupDefaultClasses()
{
$defaultClasses = self::config()->get('default_classes');
if ($defaultClasses) {
foreach ($defaultClasses as $class) {
$this->addExtraClass($class);
}
}
} | [
"protected",
"function",
"setupDefaultClasses",
"(",
")",
"{",
"$",
"defaultClasses",
"=",
"self",
"::",
"config",
"(",
")",
"->",
"get",
"(",
"'default_classes'",
")",
";",
"if",
"(",
"$",
"defaultClasses",
")",
"{",
"foreach",
"(",
"$",
"defaultClasses",
"as",
"$",
"class",
")",
"{",
"$",
"this",
"->",
"addExtraClass",
"(",
"$",
"class",
")",
";",
"}",
"}",
"}"
]
| set up the default classes for the form. This is done on construct so that the default classes can be removed
after instantiation | [
"set",
"up",
"the",
"default",
"classes",
"for",
"the",
"form",
".",
"This",
"is",
"done",
"on",
"construct",
"so",
"that",
"the",
"default",
"classes",
"can",
"be",
"removed",
"after",
"instantiation"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L537-L545 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.actionIsValidationExempt | public function actionIsValidationExempt($action)
{
// Non-actions don't bypass validation
if (!$action) {
return false;
}
if ($action->getValidationExempt()) {
return true;
}
if (in_array($action->actionName(), $this->getValidationExemptActions())) {
return true;
}
return false;
} | php | public function actionIsValidationExempt($action)
{
// Non-actions don't bypass validation
if (!$action) {
return false;
}
if ($action->getValidationExempt()) {
return true;
}
if (in_array($action->actionName(), $this->getValidationExemptActions())) {
return true;
}
return false;
} | [
"public",
"function",
"actionIsValidationExempt",
"(",
"$",
"action",
")",
"{",
"// Non-actions don't bypass validation",
"if",
"(",
"!",
"$",
"action",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"action",
"->",
"getValidationExempt",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"action",
"->",
"actionName",
"(",
")",
",",
"$",
"this",
"->",
"getValidationExemptActions",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Passed a FormAction, returns true if that action is exempt from Form validation
@param FormAction $action
@return bool | [
"Passed",
"a",
"FormAction",
"returns",
"true",
"if",
"that",
"action",
"is",
"exempt",
"from",
"Form",
"validation"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L692-L705 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.Fields | public function Fields()
{
foreach ($this->getExtraFields() as $field) {
if (!$this->fields->fieldByName($field->getName())) {
$this->fields->push($field);
}
}
return $this->fields;
} | php | public function Fields()
{
foreach ($this->getExtraFields() as $field) {
if (!$this->fields->fieldByName($field->getName())) {
$this->fields->push($field);
}
}
return $this->fields;
} | [
"public",
"function",
"Fields",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getExtraFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"fields",
"->",
"fieldByName",
"(",
"$",
"field",
"->",
"getName",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"fields",
"->",
"push",
"(",
"$",
"field",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"fields",
";",
"}"
]
| Return the form's fields - used by the templates
@return FieldList The form fields | [
"Return",
"the",
"form",
"s",
"fields",
"-",
"used",
"by",
"the",
"templates"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L740-L749 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.getAttributesHTML | public function getAttributesHTML($attrs = null)
{
$exclude = (is_string($attrs)) ? func_get_args() : null;
$attrs = $this->getAttributes();
// Remove empty
$attrs = array_filter((array)$attrs, function ($value) {
return ($value || $value === 0);
});
// Remove excluded
if ($exclude) {
$attrs = array_diff_key($attrs, array_flip($exclude));
}
// Prepare HTML-friendly 'method' attribute (lower-case)
if (isset($attrs['method'])) {
$attrs['method'] = strtolower($attrs['method']);
}
// Create markup
$parts = array();
foreach ($attrs as $name => $value) {
$parts[] = ($value === true) ? "{$name}=\"{$name}\"" : "{$name}=\"" . Convert::raw2att($value) . "\"";
}
return implode(' ', $parts);
} | php | public function getAttributesHTML($attrs = null)
{
$exclude = (is_string($attrs)) ? func_get_args() : null;
$attrs = $this->getAttributes();
// Remove empty
$attrs = array_filter((array)$attrs, function ($value) {
return ($value || $value === 0);
});
// Remove excluded
if ($exclude) {
$attrs = array_diff_key($attrs, array_flip($exclude));
}
// Prepare HTML-friendly 'method' attribute (lower-case)
if (isset($attrs['method'])) {
$attrs['method'] = strtolower($attrs['method']);
}
// Create markup
$parts = array();
foreach ($attrs as $name => $value) {
$parts[] = ($value === true) ? "{$name}=\"{$name}\"" : "{$name}=\"" . Convert::raw2att($value) . "\"";
}
return implode(' ', $parts);
} | [
"public",
"function",
"getAttributesHTML",
"(",
"$",
"attrs",
"=",
"null",
")",
"{",
"$",
"exclude",
"=",
"(",
"is_string",
"(",
"$",
"attrs",
")",
")",
"?",
"func_get_args",
"(",
")",
":",
"null",
";",
"$",
"attrs",
"=",
"$",
"this",
"->",
"getAttributes",
"(",
")",
";",
"// Remove empty",
"$",
"attrs",
"=",
"array_filter",
"(",
"(",
"array",
")",
"$",
"attrs",
",",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"(",
"$",
"value",
"||",
"$",
"value",
"===",
"0",
")",
";",
"}",
")",
";",
"// Remove excluded",
"if",
"(",
"$",
"exclude",
")",
"{",
"$",
"attrs",
"=",
"array_diff_key",
"(",
"$",
"attrs",
",",
"array_flip",
"(",
"$",
"exclude",
")",
")",
";",
"}",
"// Prepare HTML-friendly 'method' attribute (lower-case)",
"if",
"(",
"isset",
"(",
"$",
"attrs",
"[",
"'method'",
"]",
")",
")",
"{",
"$",
"attrs",
"[",
"'method'",
"]",
"=",
"strtolower",
"(",
"$",
"attrs",
"[",
"'method'",
"]",
")",
";",
"}",
"// Create markup",
"$",
"parts",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"attrs",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"parts",
"[",
"]",
"=",
"(",
"$",
"value",
"===",
"true",
")",
"?",
"\"{$name}=\\\"{$name}\\\"\"",
":",
"\"{$name}=\\\"\"",
".",
"Convert",
"::",
"raw2att",
"(",
"$",
"value",
")",
".",
"\"\\\"\"",
";",
"}",
"return",
"implode",
"(",
"' '",
",",
"$",
"parts",
")",
";",
"}"
]
| Return the attributes of the form tag - used by the templates.
@param array $attrs Custom attributes to process. Falls back to {@link getAttributes()}.
If at least one argument is passed as a string, all arguments act as excludes by name.
@return string HTML attributes, ready for insertion into an HTML tag | [
"Return",
"the",
"attributes",
"of",
"the",
"form",
"tag",
"-",
"used",
"by",
"the",
"templates",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L876-L904 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.getEncType | public function getEncType()
{
if ($this->encType) {
return $this->encType;
}
if ($fields = $this->fields->dataFields()) {
foreach ($fields as $field) {
if ($field instanceof FileField) {
return self::ENC_TYPE_MULTIPART;
}
}
}
return self::ENC_TYPE_URLENCODED;
} | php | public function getEncType()
{
if ($this->encType) {
return $this->encType;
}
if ($fields = $this->fields->dataFields()) {
foreach ($fields as $field) {
if ($field instanceof FileField) {
return self::ENC_TYPE_MULTIPART;
}
}
}
return self::ENC_TYPE_URLENCODED;
} | [
"public",
"function",
"getEncType",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"encType",
")",
"{",
"return",
"$",
"this",
"->",
"encType",
";",
"}",
"if",
"(",
"$",
"fields",
"=",
"$",
"this",
"->",
"fields",
"->",
"dataFields",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"$",
"field",
"instanceof",
"FileField",
")",
"{",
"return",
"self",
"::",
"ENC_TYPE_MULTIPART",
";",
"}",
"}",
"}",
"return",
"self",
"::",
"ENC_TYPE_URLENCODED",
";",
"}"
]
| Returns the encoding type for the form.
By default this will be URL encoded, unless there is a file field present
in which case multipart is used. You can also set the enc type using
{@link setEncType}. | [
"Returns",
"the",
"encoding",
"type",
"for",
"the",
"form",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L1014-L1029 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.sessionMessage | public function sessionMessage($message, $type = ValidationResult::TYPE_ERROR, $cast = ValidationResult::CAST_TEXT)
{
$this->setMessage($message, $type, $cast);
$result = $this->getSessionValidationResult() ?: ValidationResult::create();
$result->addMessage($message, $type, null, $cast);
$this->setSessionValidationResult($result);
} | php | public function sessionMessage($message, $type = ValidationResult::TYPE_ERROR, $cast = ValidationResult::CAST_TEXT)
{
$this->setMessage($message, $type, $cast);
$result = $this->getSessionValidationResult() ?: ValidationResult::create();
$result->addMessage($message, $type, null, $cast);
$this->setSessionValidationResult($result);
} | [
"public",
"function",
"sessionMessage",
"(",
"$",
"message",
",",
"$",
"type",
"=",
"ValidationResult",
"::",
"TYPE_ERROR",
",",
"$",
"cast",
"=",
"ValidationResult",
"::",
"CAST_TEXT",
")",
"{",
"$",
"this",
"->",
"setMessage",
"(",
"$",
"message",
",",
"$",
"type",
",",
"$",
"cast",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"getSessionValidationResult",
"(",
")",
"?",
":",
"ValidationResult",
"::",
"create",
"(",
")",
";",
"$",
"result",
"->",
"addMessage",
"(",
"$",
"message",
",",
"$",
"type",
",",
"null",
",",
"$",
"cast",
")",
";",
"$",
"this",
"->",
"setSessionValidationResult",
"(",
"$",
"result",
")",
";",
"}"
]
| Set a message to the session, for display next time this form is shown.
@param string $message the text of the message
@param string $type Should be set to good, bad, or warning.
@param string|bool $cast Cast type; One of the CAST_ constant definitions.
Bool values will be treated as plain text flag. | [
"Set",
"a",
"message",
"to",
"the",
"session",
"for",
"display",
"next",
"time",
"this",
"form",
"is",
"shown",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L1249-L1255 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.sessionError | public function sessionError($message, $type = ValidationResult::TYPE_ERROR, $cast = ValidationResult::CAST_TEXT)
{
$this->setMessage($message, $type, $cast);
$result = $this->getSessionValidationResult() ?: ValidationResult::create();
$result->addError($message, $type, null, $cast);
$this->setSessionValidationResult($result);
} | php | public function sessionError($message, $type = ValidationResult::TYPE_ERROR, $cast = ValidationResult::CAST_TEXT)
{
$this->setMessage($message, $type, $cast);
$result = $this->getSessionValidationResult() ?: ValidationResult::create();
$result->addError($message, $type, null, $cast);
$this->setSessionValidationResult($result);
} | [
"public",
"function",
"sessionError",
"(",
"$",
"message",
",",
"$",
"type",
"=",
"ValidationResult",
"::",
"TYPE_ERROR",
",",
"$",
"cast",
"=",
"ValidationResult",
"::",
"CAST_TEXT",
")",
"{",
"$",
"this",
"->",
"setMessage",
"(",
"$",
"message",
",",
"$",
"type",
",",
"$",
"cast",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"getSessionValidationResult",
"(",
")",
"?",
":",
"ValidationResult",
"::",
"create",
"(",
")",
";",
"$",
"result",
"->",
"addError",
"(",
"$",
"message",
",",
"$",
"type",
",",
"null",
",",
"$",
"cast",
")",
";",
"$",
"this",
"->",
"setSessionValidationResult",
"(",
"$",
"result",
")",
";",
"}"
]
| Set an error to the session, for display next time this form is shown.
@param string $message the text of the message
@param string $type Should be set to good, bad, or warning.
@param string|bool $cast Cast type; One of the CAST_ constant definitions.
Bool values will be treated as plain text flag. | [
"Set",
"an",
"error",
"to",
"the",
"session",
"for",
"display",
"next",
"time",
"this",
"form",
"is",
"shown",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L1265-L1271 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.forTemplate | public function forTemplate()
{
if (!$this->canBeCached()) {
HTTPCacheControlMiddleware::singleton()->disableCache();
}
$return = $this->renderWith($this->getTemplates());
// Now that we're rendered, clear message
$this->clearMessage();
return $return;
} | php | public function forTemplate()
{
if (!$this->canBeCached()) {
HTTPCacheControlMiddleware::singleton()->disableCache();
}
$return = $this->renderWith($this->getTemplates());
// Now that we're rendered, clear message
$this->clearMessage();
return $return;
} | [
"public",
"function",
"forTemplate",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"canBeCached",
"(",
")",
")",
"{",
"HTTPCacheControlMiddleware",
"::",
"singleton",
"(",
")",
"->",
"disableCache",
"(",
")",
";",
"}",
"$",
"return",
"=",
"$",
"this",
"->",
"renderWith",
"(",
"$",
"this",
"->",
"getTemplates",
"(",
")",
")",
";",
"// Now that we're rendered, clear message",
"$",
"this",
"->",
"clearMessage",
"(",
")",
";",
"return",
"$",
"return",
";",
"}"
]
| Return a rendered version of this form.
This is returned when you access a form as $FormObject rather
than <% with FormObject %>
@return DBHTMLText | [
"Return",
"a",
"rendered",
"version",
"of",
"this",
"form",
"."
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L1576-L1588 | train |
silverstripe/silverstripe-framework | src/Forms/Form.php | Form.canBeCached | protected function canBeCached()
{
if ($this->getSecurityToken()->isEnabled()) {
return false;
}
if ($this->FormMethod() !== 'GET') {
return false;
}
// Don't cache if there are required fields, or some other complex validator
$validator = $this->getValidator();
if ($validator instanceof RequiredFields) {
if (count($this->validator->getRequired())) {
return false;
}
} else {
return false;
}
return true;
} | php | protected function canBeCached()
{
if ($this->getSecurityToken()->isEnabled()) {
return false;
}
if ($this->FormMethod() !== 'GET') {
return false;
}
// Don't cache if there are required fields, or some other complex validator
$validator = $this->getValidator();
if ($validator instanceof RequiredFields) {
if (count($this->validator->getRequired())) {
return false;
}
} else {
return false;
}
return true;
} | [
"protected",
"function",
"canBeCached",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getSecurityToken",
"(",
")",
"->",
"isEnabled",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"FormMethod",
"(",
")",
"!==",
"'GET'",
")",
"{",
"return",
"false",
";",
"}",
"// Don't cache if there are required fields, or some other complex validator",
"$",
"validator",
"=",
"$",
"this",
"->",
"getValidator",
"(",
")",
";",
"if",
"(",
"$",
"validator",
"instanceof",
"RequiredFields",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"validator",
"->",
"getRequired",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Can the body of this form be cached?
@return bool | [
"Can",
"the",
"body",
"of",
"this",
"form",
"be",
"cached?"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Form.php#L1843-L1862 | train |
silverstripe/silverstripe-framework | src/ORM/Connect/MySQLiConnector.php | MySQLiConnector.prepareStatement | public function prepareStatement($sql, &$success)
{
// Record last statement for error reporting
$statement = $this->dbConn->stmt_init();
$this->setLastStatement($statement);
$success = $statement->prepare($sql);
return $statement;
} | php | public function prepareStatement($sql, &$success)
{
// Record last statement for error reporting
$statement = $this->dbConn->stmt_init();
$this->setLastStatement($statement);
$success = $statement->prepare($sql);
return $statement;
} | [
"public",
"function",
"prepareStatement",
"(",
"$",
"sql",
",",
"&",
"$",
"success",
")",
"{",
"// Record last statement for error reporting",
"$",
"statement",
"=",
"$",
"this",
"->",
"dbConn",
"->",
"stmt_init",
"(",
")",
";",
"$",
"this",
"->",
"setLastStatement",
"(",
"$",
"statement",
")",
";",
"$",
"success",
"=",
"$",
"statement",
"->",
"prepare",
"(",
"$",
"sql",
")",
";",
"return",
"$",
"statement",
";",
"}"
]
| Retrieve a prepared statement for a given SQL string
@param string $sql
@param boolean &$success
@return mysqli_stmt | [
"Retrieve",
"a",
"prepared",
"statement",
"for",
"a",
"given",
"SQL",
"string"
]
| ed7aaff7da61eefa172fe213ec25e35d2568bc20 | https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Connect/MySQLiConnector.php#L61-L68 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.