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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
tractorcow-farm/silverstripe-fluent | src/Extension/FluentDirectorExtension.php | FluentDirectorExtension.updateRules | public function updateRules(&$rules)
{
$originalRules = $rules;
$fluentRules = $this->getExplicitRoutes($rules);
// Insert Fluent Rules before the default '$URLSegment//$Action/$ID/$OtherID'
$rules = $this->insertRuleBefore($rules, '$URLSegment//$Action/$ID/$OtherID', $fluentRules);
$request = Injector::inst()->get(HTTPRequest::class);
if (!$request) {
throw new Exception('No request found');
}
// Ensure InitStateMddleware is called here to set the correct defaultLocale
Injector::inst()->create(InitStateMiddleware::class)->process($request, function () {
});
$defaultLocale = Locale::getDefault(true);
if (!$defaultLocale) {
return;
}
// If we do not wish to detect the locale automatically, fix the home page route
// to the default locale for this domain.
if (!static::config()->get('detect_locale')) {
// Respect existing home controller
$rules[''] = [
'Controller' => $this->getRuleController($originalRules[''], $defaultLocale),
static::config()->get('query_param') => $defaultLocale->Locale,
];
}
// If default locale doesn't have prefix, replace default route with
// the default locale for this domain
if (static::config()->get('disable_default_prefix')) {
$rules['$URLSegment//$Action/$ID/$OtherID'] = [
'Controller' => $this->getRuleController($originalRules['$URLSegment//$Action/$ID/$OtherID'], $defaultLocale),
static::config()->get('query_param') => $defaultLocale->Locale
];
}
} | php | public function updateRules(&$rules)
{
$originalRules = $rules;
$fluentRules = $this->getExplicitRoutes($rules);
// Insert Fluent Rules before the default '$URLSegment//$Action/$ID/$OtherID'
$rules = $this->insertRuleBefore($rules, '$URLSegment//$Action/$ID/$OtherID', $fluentRules);
$request = Injector::inst()->get(HTTPRequest::class);
if (!$request) {
throw new Exception('No request found');
}
// Ensure InitStateMddleware is called here to set the correct defaultLocale
Injector::inst()->create(InitStateMiddleware::class)->process($request, function () {
});
$defaultLocale = Locale::getDefault(true);
if (!$defaultLocale) {
return;
}
// If we do not wish to detect the locale automatically, fix the home page route
// to the default locale for this domain.
if (!static::config()->get('detect_locale')) {
// Respect existing home controller
$rules[''] = [
'Controller' => $this->getRuleController($originalRules[''], $defaultLocale),
static::config()->get('query_param') => $defaultLocale->Locale,
];
}
// If default locale doesn't have prefix, replace default route with
// the default locale for this domain
if (static::config()->get('disable_default_prefix')) {
$rules['$URLSegment//$Action/$ID/$OtherID'] = [
'Controller' => $this->getRuleController($originalRules['$URLSegment//$Action/$ID/$OtherID'], $defaultLocale),
static::config()->get('query_param') => $defaultLocale->Locale
];
}
} | [
"public",
"function",
"updateRules",
"(",
"&",
"$",
"rules",
")",
"{",
"$",
"originalRules",
"=",
"$",
"rules",
";",
"$",
"fluentRules",
"=",
"$",
"this",
"->",
"getExplicitRoutes",
"(",
"$",
"rules",
")",
";",
"// Insert Fluent Rules before the default '$URLSeg... | Forces regeneration of all locale routes
@param array &$rules | [
"Forces",
"regeneration",
"of",
"all",
"locale",
"routes"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentDirectorExtension.php#L68-L108 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentDirectorExtension.php | FluentDirectorExtension.getExplicitRoutes | protected function getExplicitRoutes($originalRules)
{
$queryParam = static::config()->get('query_param');
$rules = [];
/** @var Locale $localeObj */
foreach (Locale::getCached() as $localeObj) {
$locale = $localeObj->getLocale();
$url = $localeObj->getURLSegment();
// apply encode so we could route urls that contain multi-byte charaters
$url = urlencode($url);
// Apply to nested page url
$controller = $this->getRuleController($originalRules['$URLSegment//$Action/$ID/$OtherID'], $localeObj);
$rules[$url . '/$URLSegment!//$Action/$ID/$OtherID'] = [
'Controller' => $controller,
$queryParam => $locale,
];
// Home url for that locale
$controller = $this->getRuleController($originalRules[''], $localeObj);
$rules[$url] = [
'Controller' => $controller,
$queryParam => $locale,
];
}
return $rules;
} | php | protected function getExplicitRoutes($originalRules)
{
$queryParam = static::config()->get('query_param');
$rules = [];
/** @var Locale $localeObj */
foreach (Locale::getCached() as $localeObj) {
$locale = $localeObj->getLocale();
$url = $localeObj->getURLSegment();
// apply encode so we could route urls that contain multi-byte charaters
$url = urlencode($url);
// Apply to nested page url
$controller = $this->getRuleController($originalRules['$URLSegment//$Action/$ID/$OtherID'], $localeObj);
$rules[$url . '/$URLSegment!//$Action/$ID/$OtherID'] = [
'Controller' => $controller,
$queryParam => $locale,
];
// Home url for that locale
$controller = $this->getRuleController($originalRules[''], $localeObj);
$rules[$url] = [
'Controller' => $controller,
$queryParam => $locale,
];
}
return $rules;
} | [
"protected",
"function",
"getExplicitRoutes",
"(",
"$",
"originalRules",
")",
"{",
"$",
"queryParam",
"=",
"static",
"::",
"config",
"(",
")",
"->",
"get",
"(",
"'query_param'",
")",
";",
"$",
"rules",
"=",
"[",
"]",
";",
"/** @var Locale $localeObj */",
"fo... | Generate an array of explicit routing rules for each locale
@param array $originalRules
@return array | [
"Generate",
"an",
"array",
"of",
"explicit",
"routing",
"rules",
"for",
"each",
"locale"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentDirectorExtension.php#L116-L143 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentDirectorExtension.php | FluentDirectorExtension.getRuleController | protected function getRuleController($existingRule, $localeObj)
{
$controller = isset($existingRule['Controller']) ? $existingRule['Controller'] : $existingRule;
// Decorate Director class to override controllers for a specific locale
$this->owner->extend('updateLocalePageController', $controller, $localeObj);
return $controller;
} | php | protected function getRuleController($existingRule, $localeObj)
{
$controller = isset($existingRule['Controller']) ? $existingRule['Controller'] : $existingRule;
// Decorate Director class to override controllers for a specific locale
$this->owner->extend('updateLocalePageController', $controller, $localeObj);
return $controller;
} | [
"protected",
"function",
"getRuleController",
"(",
"$",
"existingRule",
",",
"$",
"localeObj",
")",
"{",
"$",
"controller",
"=",
"isset",
"(",
"$",
"existingRule",
"[",
"'Controller'",
"]",
")",
"?",
"$",
"existingRule",
"[",
"'Controller'",
"]",
":",
"$",
... | Get controller that fluent should inject
@param array|string $existingRule
@param Locale $localeObj
@return string Class name of controller to use | [
"Get",
"controller",
"that",
"fluent",
"should",
"inject"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentDirectorExtension.php#L151-L157 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getLocalisedFields | public function getLocalisedFields($class = null)
{
if (!$class) {
$class = get_class($this->owner);
}
if (isset($this->localisedFields[$class])) {
return $this->localisedFields[$class];
}
// List of DB fields
$fields = DataObject::getSchema()->databaseFields($class, false);
$filter = Config::inst()->get($class, 'translate', Config::UNINHERITED);
if ($filter === self::TRANSLATE_NONE || empty($fields)) {
return $this->localisedFields[$class] = [];
}
// filter out DB
foreach ($fields as $field => $type) {
if (!$this->isFieldLocalised($field, $type, $class)) {
unset($fields[$field]);
}
}
return $this->localisedFields[$class] = $fields;
} | php | public function getLocalisedFields($class = null)
{
if (!$class) {
$class = get_class($this->owner);
}
if (isset($this->localisedFields[$class])) {
return $this->localisedFields[$class];
}
// List of DB fields
$fields = DataObject::getSchema()->databaseFields($class, false);
$filter = Config::inst()->get($class, 'translate', Config::UNINHERITED);
if ($filter === self::TRANSLATE_NONE || empty($fields)) {
return $this->localisedFields[$class] = [];
}
// filter out DB
foreach ($fields as $field => $type) {
if (!$this->isFieldLocalised($field, $type, $class)) {
unset($fields[$field]);
}
}
return $this->localisedFields[$class] = $fields;
} | [
"public",
"function",
"getLocalisedFields",
"(",
"$",
"class",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"class",
")",
"{",
"$",
"class",
"=",
"get_class",
"(",
"$",
"this",
"->",
"owner",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"-... | Get list of fields that are localised
@param string $class Class to get fields for (if parent)
@return array | [
"Get",
"list",
"of",
"fields",
"that",
"are",
"localised"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L146-L170 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.isFieldLocalised | protected function isFieldLocalised($field, $type, $class)
{
// Explicit per-table filter
$filter = Config::inst()->get($class, 'translate', Config::UNINHERITED);
if ($filter === self::TRANSLATE_NONE) {
return false;
}
if ($filter && is_array($filter)) {
return in_array($field, $filter);
}
// Named blacklist
$fieldsExclude = Config::inst()->get($class, 'field_exclude');
if ($fieldsExclude && $this->anyMatch($field, $fieldsExclude)) {
return false;
}
// Named whitelist
$fieldsInclude = Config::inst()->get($class, 'field_include');
if ($fieldsInclude && $this->anyMatch($field, $fieldsInclude)) {
return true;
}
// Typed blacklist
$dataExclude = Config::inst()->get($class, 'data_exclude');
if ($dataExclude && $this->anyMatch($type, $dataExclude)) {
return false;
}
// Typed whitelist
$dataInclude = Config::inst()->get($class, 'data_include');
if ($dataInclude && $this->anyMatch($type, $dataInclude)) {
return true;
}
return false;
} | php | protected function isFieldLocalised($field, $type, $class)
{
// Explicit per-table filter
$filter = Config::inst()->get($class, 'translate', Config::UNINHERITED);
if ($filter === self::TRANSLATE_NONE) {
return false;
}
if ($filter && is_array($filter)) {
return in_array($field, $filter);
}
// Named blacklist
$fieldsExclude = Config::inst()->get($class, 'field_exclude');
if ($fieldsExclude && $this->anyMatch($field, $fieldsExclude)) {
return false;
}
// Named whitelist
$fieldsInclude = Config::inst()->get($class, 'field_include');
if ($fieldsInclude && $this->anyMatch($field, $fieldsInclude)) {
return true;
}
// Typed blacklist
$dataExclude = Config::inst()->get($class, 'data_exclude');
if ($dataExclude && $this->anyMatch($type, $dataExclude)) {
return false;
}
// Typed whitelist
$dataInclude = Config::inst()->get($class, 'data_include');
if ($dataInclude && $this->anyMatch($type, $dataInclude)) {
return true;
}
return false;
} | [
"protected",
"function",
"isFieldLocalised",
"(",
"$",
"field",
",",
"$",
"type",
",",
"$",
"class",
")",
"{",
"// Explicit per-table filter",
"$",
"filter",
"=",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"$",
"class",
",",
"'translate'",
",",
... | Check if a field is marked for localisation
@param string $field Field name
@param string $type Field type
@param string $class Class this field is defined in
@return bool | [
"Check",
"if",
"a",
"field",
"is",
"marked",
"for",
"localisation"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L180-L216 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getLocalisedTables | public function getLocalisedTables()
{
$includedTables = [];
$baseClass = $this->owner->baseClass();
$tableClasses = ClassInfo::ancestry($this->owner, true);
foreach ($tableClasses as $class) {
// Check translated fields for this class (except base table, which is always scaffolded)
$translatedFields = $this->getLocalisedFields($class);
if (empty($translatedFields) && $class !== $baseClass) {
continue;
}
// Mark this table as translatable
$table = DataObject::getSchema()->tableName($class);
$includedTables[$table] = array_keys($translatedFields);
}
return $includedTables;
} | php | public function getLocalisedTables()
{
$includedTables = [];
$baseClass = $this->owner->baseClass();
$tableClasses = ClassInfo::ancestry($this->owner, true);
foreach ($tableClasses as $class) {
// Check translated fields for this class (except base table, which is always scaffolded)
$translatedFields = $this->getLocalisedFields($class);
if (empty($translatedFields) && $class !== $baseClass) {
continue;
}
// Mark this table as translatable
$table = DataObject::getSchema()->tableName($class);
$includedTables[$table] = array_keys($translatedFields);
}
return $includedTables;
} | [
"public",
"function",
"getLocalisedTables",
"(",
")",
"{",
"$",
"includedTables",
"=",
"[",
"]",
";",
"$",
"baseClass",
"=",
"$",
"this",
"->",
"owner",
"->",
"baseClass",
"(",
")",
";",
"$",
"tableClasses",
"=",
"ClassInfo",
"::",
"ancestry",
"(",
"$",
... | Get all database tables in the class ancestry and their respective
translatable fields
@return array | [
"Get",
"all",
"database",
"tables",
"in",
"the",
"class",
"ancestry",
"and",
"their",
"respective",
"translatable",
"fields"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L224-L241 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.anyMatch | protected function anyMatch($value, $patterns)
{
// Test both explicit value, as well as the value stripped of any trailing parameters
$valueBase = preg_replace('/\(.*/', '', $value);
foreach ($patterns as $pattern) {
if (strpos($pattern, '/') === 0) {
// Assume value prefaced with '/' are regexp
if (preg_match($pattern, $value) || preg_match($pattern, $valueBase)) {
return true;
}
} else {
// Assume simple string comparison otherwise
if ($pattern === $value || $pattern === $valueBase) {
return true;
}
}
}
return false;
} | php | protected function anyMatch($value, $patterns)
{
// Test both explicit value, as well as the value stripped of any trailing parameters
$valueBase = preg_replace('/\(.*/', '', $value);
foreach ($patterns as $pattern) {
if (strpos($pattern, '/') === 0) {
// Assume value prefaced with '/' are regexp
if (preg_match($pattern, $value) || preg_match($pattern, $valueBase)) {
return true;
}
} else {
// Assume simple string comparison otherwise
if ($pattern === $value || $pattern === $valueBase) {
return true;
}
}
}
return false;
} | [
"protected",
"function",
"anyMatch",
"(",
"$",
"value",
",",
"$",
"patterns",
")",
"{",
"// Test both explicit value, as well as the value stripped of any trailing parameters",
"$",
"valueBase",
"=",
"preg_replace",
"(",
"'/\\(.*/'",
",",
"''",
",",
"$",
"value",
")",
... | Helper function to check if the value given is present in any of the patterns.
This function is case sensitive by default.
@param string $value A string value to check against, potentially with parameters (E.g. 'Varchar(1023)')
@param array $patterns A list of strings, some of which may be regular expressions
@return bool True if this $value is present in any of the $patterns | [
"Helper",
"function",
"to",
"check",
"if",
"the",
"value",
"given",
"is",
"present",
"in",
"any",
"of",
"the",
"patterns",
".",
"This",
"function",
"is",
"case",
"sensitive",
"by",
"default",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L251-L269 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.augmentDatabaseRequireTable | protected function augmentDatabaseRequireTable($localisedTable, $fields, $indexes)
{
DB::require_table($localisedTable, $fields, $indexes, false);
} | php | protected function augmentDatabaseRequireTable($localisedTable, $fields, $indexes)
{
DB::require_table($localisedTable, $fields, $indexes, false);
} | [
"protected",
"function",
"augmentDatabaseRequireTable",
"(",
"$",
"localisedTable",
",",
"$",
"fields",
",",
"$",
"indexes",
")",
"{",
"DB",
"::",
"require_table",
"(",
"$",
"localisedTable",
",",
"$",
"fields",
",",
"$",
"indexes",
",",
"false",
")",
";",
... | Require the given localisation table
@param string $localisedTable
@param array $fields
@param array $indexes | [
"Require",
"the",
"given",
"localisation",
"table"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L307-L310 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.updateDeleteTables | public function updateDeleteTables(&$queriedTables)
{
// Ensure a locale exists
$locale = Locale::getCurrentLocale();
if (!$locale) {
return;
}
// Fluent takes over deletion of objects
$queriedTables = [];
$localisedTables = $this->getLocalisedTables();
$tableClasses = ClassInfo::ancestry($this->owner, true);
foreach ($tableClasses as $class) {
// Check main table name
$table = DataObject::getSchema()->tableName($class);
// Create root table delete
$rootTable = $this->getDeleteTableTarget($table);
$rootDelete = SQLDelete::create("\"{$rootTable}\"")
->addWhere(["\"{$rootTable}\".\"ID\"" => $this->owner->ID]);
// If table isn't localised, simple delete
if (!isset($localisedTables[$table])) {
$baseTable = $this->getDeleteTableTarget($this->owner->baseTable());
// The base table isn't localised? Delete the record then.
if ($baseTable === $rootTable) {
$rootDelete->execute();
continue;
}
$rootDelete
->setDelete("\"{$rootTable}\"")
->addLeftJoin(
$baseTable,
"\"{$rootTable}\".\"ID\" = \"{$baseTable}\".\"ID\""
)
// Only when join matches no localisations is it safe to delete
->addWhere("\"{$baseTable}\".\"ID\" IS NULL")
->execute();
continue;
}
// Remove _Localised record
$localisedTable = $this->getDeleteTableTarget($table, $locale);
$localisedDelete = SQLDelete::create(
"\"{$localisedTable}\"",
[
'"Locale"' => $locale->Locale,
'"RecordID"' => $this->owner->ID,
]
);
$localisedDelete->execute();
// Remove orphaned ONLY base table (delete after deleting last localised row)
// Note: No "Locale" filter as we are excluding any tables that have any localised records
$rootDelete
->setDelete("\"{$rootTable}\"")
->addLeftJoin(
$localisedTable,
"\"{$rootTable}\".\"ID\" = \"{$localisedTable}\".\"RecordID\""
)
// Only when join matches no localisations is it safe to delete
->addWhere("\"{$localisedTable}\".\"ID\" IS NULL")
->execute();
}
} | php | public function updateDeleteTables(&$queriedTables)
{
// Ensure a locale exists
$locale = Locale::getCurrentLocale();
if (!$locale) {
return;
}
// Fluent takes over deletion of objects
$queriedTables = [];
$localisedTables = $this->getLocalisedTables();
$tableClasses = ClassInfo::ancestry($this->owner, true);
foreach ($tableClasses as $class) {
// Check main table name
$table = DataObject::getSchema()->tableName($class);
// Create root table delete
$rootTable = $this->getDeleteTableTarget($table);
$rootDelete = SQLDelete::create("\"{$rootTable}\"")
->addWhere(["\"{$rootTable}\".\"ID\"" => $this->owner->ID]);
// If table isn't localised, simple delete
if (!isset($localisedTables[$table])) {
$baseTable = $this->getDeleteTableTarget($this->owner->baseTable());
// The base table isn't localised? Delete the record then.
if ($baseTable === $rootTable) {
$rootDelete->execute();
continue;
}
$rootDelete
->setDelete("\"{$rootTable}\"")
->addLeftJoin(
$baseTable,
"\"{$rootTable}\".\"ID\" = \"{$baseTable}\".\"ID\""
)
// Only when join matches no localisations is it safe to delete
->addWhere("\"{$baseTable}\".\"ID\" IS NULL")
->execute();
continue;
}
// Remove _Localised record
$localisedTable = $this->getDeleteTableTarget($table, $locale);
$localisedDelete = SQLDelete::create(
"\"{$localisedTable}\"",
[
'"Locale"' => $locale->Locale,
'"RecordID"' => $this->owner->ID,
]
);
$localisedDelete->execute();
// Remove orphaned ONLY base table (delete after deleting last localised row)
// Note: No "Locale" filter as we are excluding any tables that have any localised records
$rootDelete
->setDelete("\"{$rootTable}\"")
->addLeftJoin(
$localisedTable,
"\"{$rootTable}\".\"ID\" = \"{$localisedTable}\".\"RecordID\""
)
// Only when join matches no localisations is it safe to delete
->addWhere("\"{$localisedTable}\".\"ID\" IS NULL")
->execute();
}
} | [
"public",
"function",
"updateDeleteTables",
"(",
"&",
"$",
"queriedTables",
")",
"{",
"// Ensure a locale exists",
"$",
"locale",
"=",
"Locale",
"::",
"getCurrentLocale",
"(",
")",
";",
"if",
"(",
"!",
"$",
"locale",
")",
"{",
"return",
";",
"}",
"// Fluent ... | Override delete behaviour
@param array $queriedTables | [
"Override",
"delete",
"behaviour"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L435-L502 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.onBeforeWrite | public function onBeforeWrite()
{
/** @var string $currentLocale */
$currentLocale = FluentState::singleton()->getLocale();
if (!$currentLocale) {
return;
}
// If the record is not versioned, force change
if (!$this->owner->hasExtension(FluentVersionedExtension::class)) {
$this->owner->forceChange();
return;
}
// Force a change if the record doesn't already exist in the current locale
if (!$this->owner->existsInLocale($currentLocale)) {
$this->owner->forceChange();
}
} | php | public function onBeforeWrite()
{
/** @var string $currentLocale */
$currentLocale = FluentState::singleton()->getLocale();
if (!$currentLocale) {
return;
}
// If the record is not versioned, force change
if (!$this->owner->hasExtension(FluentVersionedExtension::class)) {
$this->owner->forceChange();
return;
}
// Force a change if the record doesn't already exist in the current locale
if (!$this->owner->existsInLocale($currentLocale)) {
$this->owner->forceChange();
}
} | [
"public",
"function",
"onBeforeWrite",
"(",
")",
"{",
"/** @var string $currentLocale */",
"$",
"currentLocale",
"=",
"FluentState",
"::",
"singleton",
"(",
")",
"->",
"getLocale",
"(",
")",
";",
"if",
"(",
"!",
"$",
"currentLocale",
")",
"{",
"return",
";",
... | Force all changes, since we may need to cross-publish unchanged records between locales. Without this,
loading a page in a different locale and pressing "save" won't actually make the record available in
this locale. | [
"Force",
"all",
"changes",
"since",
"we",
"may",
"need",
"to",
"cross",
"-",
"publish",
"unchanged",
"records",
"between",
"locales",
".",
"Without",
"this",
"loading",
"a",
"page",
"in",
"a",
"different",
"locale",
"and",
"pressing",
"save",
"won",
"t",
"... | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L509-L527 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.localiseManipulationTable | protected function localiseManipulationTable(&$manipulation, $table, $localeTable, $localisedFields, Locale $locale)
{
// Skip if manipulation table, or fields, are empty
if (empty($manipulation[$table]['fields'])) {
return;
}
// Get ID field
$updates = $manipulation[$table];
$id = $this->getManipulationRecordID($updates);
if (!$id) {
throw new LogicException("Missing record ID for table manipulation {$table}");
}
// Copy entire manipulation to the localised table
$localisedUpdate = $updates;
// Filter fields by localised fields
$localisedUpdate['fields'] = array_intersect_key(
$updates['fields'],
array_combine($localisedFields, $localisedFields)
);
unset($localisedUpdate['fields']['id']);
// Skip if no fields are being saved after filtering
if (empty($localisedUpdate['fields'])) {
return;
}
// Populate Locale / RecordID fields
$localisedUpdate['fields']['RecordID'] = $id;
$localisedUpdate['fields']['Locale'] = $locale->getLocale();
// Convert ID filter to RecordID / Locale
unset($localisedUpdate['id']);
$localisedUpdate['where'] = [
"\"{$localeTable}\".\"RecordID\"" => $id,
"\"{$localeTable}\".\"Locale\"" => $locale->getLocale(),
];
// Save back modifications to the manipulation
$manipulation[$localeTable] = $localisedUpdate;
} | php | protected function localiseManipulationTable(&$manipulation, $table, $localeTable, $localisedFields, Locale $locale)
{
// Skip if manipulation table, or fields, are empty
if (empty($manipulation[$table]['fields'])) {
return;
}
// Get ID field
$updates = $manipulation[$table];
$id = $this->getManipulationRecordID($updates);
if (!$id) {
throw new LogicException("Missing record ID for table manipulation {$table}");
}
// Copy entire manipulation to the localised table
$localisedUpdate = $updates;
// Filter fields by localised fields
$localisedUpdate['fields'] = array_intersect_key(
$updates['fields'],
array_combine($localisedFields, $localisedFields)
);
unset($localisedUpdate['fields']['id']);
// Skip if no fields are being saved after filtering
if (empty($localisedUpdate['fields'])) {
return;
}
// Populate Locale / RecordID fields
$localisedUpdate['fields']['RecordID'] = $id;
$localisedUpdate['fields']['Locale'] = $locale->getLocale();
// Convert ID filter to RecordID / Locale
unset($localisedUpdate['id']);
$localisedUpdate['where'] = [
"\"{$localeTable}\".\"RecordID\"" => $id,
"\"{$localeTable}\".\"Locale\"" => $locale->getLocale(),
];
// Save back modifications to the manipulation
$manipulation[$localeTable] = $localisedUpdate;
} | [
"protected",
"function",
"localiseManipulationTable",
"(",
"&",
"$",
"manipulation",
",",
"$",
"table",
",",
"$",
"localeTable",
",",
"$",
"localisedFields",
",",
"Locale",
"$",
"locale",
")",
"{",
"// Skip if manipulation table, or fields, are empty",
"if",
"(",
"e... | Localise a database manipluation from one table to another
@param array $manipulation
@param string $table Table in manipulation to copy from
@param string $localeTable Table to copy manipulation to
@param array $localisedFields List of fields to filter write to
@param Locale $locale | [
"Localise",
"a",
"database",
"manipluation",
"from",
"one",
"table",
"to",
"another"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L564-L606 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.augmentDataQueryCreation | public function augmentDataQueryCreation(SQLSelect $query, DataQuery $dataQuery)
{
$state = FluentState::singleton();
$dataQuery
->setQueryParam('Fluent.Locale', $state->getLocale())
->setQueryParam('Fluent.IsFrontend', $state->getIsFrontend());
} | php | public function augmentDataQueryCreation(SQLSelect $query, DataQuery $dataQuery)
{
$state = FluentState::singleton();
$dataQuery
->setQueryParam('Fluent.Locale', $state->getLocale())
->setQueryParam('Fluent.IsFrontend', $state->getIsFrontend());
} | [
"public",
"function",
"augmentDataQueryCreation",
"(",
"SQLSelect",
"$",
"query",
",",
"DataQuery",
"$",
"dataQuery",
")",
"{",
"$",
"state",
"=",
"FluentState",
"::",
"singleton",
"(",
")",
";",
"$",
"dataQuery",
"->",
"setQueryParam",
"(",
"'Fluent.Locale'",
... | Amend freshly created DataQuery objects with the current locale and frontend status
@param SQLSelect $query
@param DataQuery $dataQuery | [
"Amend",
"freshly",
"created",
"DataQuery",
"objects",
"with",
"the",
"current",
"locale",
"and",
"frontend",
"status"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L614-L620 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getLocalisedTable | public function getLocalisedTable($tableName, $locale = '')
{
$localisedTable = $tableName . '_' . self::SUFFIX;
if ($locale) {
$localisedTable .= '_' . $locale;
}
return $localisedTable;
} | php | public function getLocalisedTable($tableName, $locale = '')
{
$localisedTable = $tableName . '_' . self::SUFFIX;
if ($locale) {
$localisedTable .= '_' . $locale;
}
return $localisedTable;
} | [
"public",
"function",
"getLocalisedTable",
"(",
"$",
"tableName",
",",
"$",
"locale",
"=",
"''",
")",
"{",
"$",
"localisedTable",
"=",
"$",
"tableName",
".",
"'_'",
".",
"self",
"::",
"SUFFIX",
";",
"if",
"(",
"$",
"locale",
")",
"{",
"$",
"localisedTa... | Get the localised table name with the localised suffix and optionally with a locale suffix for aliases
@param string $tableName
@param string $locale
@return string | [
"Get",
"the",
"localised",
"table",
"name",
"with",
"the",
"localised",
"suffix",
"and",
"optionally",
"with",
"a",
"locale",
"suffix",
"for",
"aliases"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L629-L636 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.localiseSelect | protected function localiseSelect($table, $field, Locale $locale)
{
// Build case for each locale down the chain
$query = "CASE\n";
foreach ($locale->getChain() as $joinLocale) {
$joinAlias = $this->getLocalisedTable($table, $joinLocale->Locale);
$query .= "\tWHEN \"{$joinAlias}\".\"ID\" IS NOT NULL THEN \"{$joinAlias}\".\"{$field}\"\n";
}
// Note: In CMS only we fall back to value in root table (in case not yet migrated)
// On the frontend this row would have been filtered already (see augmentSQL logic)
$sqlDefault = "\"{$table}\".\"{$field}\"";
$this->owner->invokeWithExtensions('updateLocaliseSelectDefault', $sqlDefault, $table, $field, $locale);
$query .= "\tELSE $sqlDefault END\n";
// Fall back to null by default, but allow extensions to override this entire fragment
// Note: Extensions are responsible for SQL escaping
$this->owner->invokeWithExtensions('updateLocaliseSelect', $query, $table, $field, $locale);
return $query;
} | php | protected function localiseSelect($table, $field, Locale $locale)
{
// Build case for each locale down the chain
$query = "CASE\n";
foreach ($locale->getChain() as $joinLocale) {
$joinAlias = $this->getLocalisedTable($table, $joinLocale->Locale);
$query .= "\tWHEN \"{$joinAlias}\".\"ID\" IS NOT NULL THEN \"{$joinAlias}\".\"{$field}\"\n";
}
// Note: In CMS only we fall back to value in root table (in case not yet migrated)
// On the frontend this row would have been filtered already (see augmentSQL logic)
$sqlDefault = "\"{$table}\".\"{$field}\"";
$this->owner->invokeWithExtensions('updateLocaliseSelectDefault', $sqlDefault, $table, $field, $locale);
$query .= "\tELSE $sqlDefault END\n";
// Fall back to null by default, but allow extensions to override this entire fragment
// Note: Extensions are responsible for SQL escaping
$this->owner->invokeWithExtensions('updateLocaliseSelect', $query, $table, $field, $locale);
return $query;
} | [
"protected",
"function",
"localiseSelect",
"(",
"$",
"table",
",",
"$",
"field",
",",
"Locale",
"$",
"locale",
")",
"{",
"// Build case for each locale down the chain",
"$",
"query",
"=",
"\"CASE\\n\"",
";",
"foreach",
"(",
"$",
"locale",
"->",
"getChain",
"(",
... | Generates a select fragment based on a field with a fallback
@param string $table
@param string $field
@param Locale $locale
@return string Select fragment | [
"Generates",
"a",
"select",
"fragment",
"based",
"on",
"a",
"field",
"with",
"a",
"fallback"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L662-L681 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getDataQueryLocale | protected function getDataQueryLocale(DataQuery $dataQuery = null)
{
if (!$dataQuery) {
return null;
}
$localeCode = $dataQuery->getQueryParam('Fluent.Locale') ?: FluentState::singleton()->getLocale();
if ($localeCode) {
return Locale::getByLocale($localeCode);
}
return null;
} | php | protected function getDataQueryLocale(DataQuery $dataQuery = null)
{
if (!$dataQuery) {
return null;
}
$localeCode = $dataQuery->getQueryParam('Fluent.Locale') ?: FluentState::singleton()->getLocale();
if ($localeCode) {
return Locale::getByLocale($localeCode);
}
return null;
} | [
"protected",
"function",
"getDataQueryLocale",
"(",
"DataQuery",
"$",
"dataQuery",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"dataQuery",
")",
"{",
"return",
"null",
";",
"}",
"$",
"localeCode",
"=",
"$",
"dataQuery",
"->",
"getQueryParam",
"(",
"'Fluent... | Get current locale from given dataquery
@param DataQuery $dataQuery
@return Locale|null | [
"Get",
"current",
"locale",
"from",
"given",
"dataquery"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L720-L730 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getRecordLocale | protected function getRecordLocale()
{
$localeCode = $this->owner->getSourceQueryParam('Fluent.Locale');
if ($localeCode) {
$locale = Locale::getByLocale($localeCode);
if ($locale) {
return $locale;
}
}
return Locale::getCurrentLocale();
} | php | protected function getRecordLocale()
{
$localeCode = $this->owner->getSourceQueryParam('Fluent.Locale');
if ($localeCode) {
$locale = Locale::getByLocale($localeCode);
if ($locale) {
return $locale;
}
}
return Locale::getCurrentLocale();
} | [
"protected",
"function",
"getRecordLocale",
"(",
")",
"{",
"$",
"localeCode",
"=",
"$",
"this",
"->",
"owner",
"->",
"getSourceQueryParam",
"(",
"'Fluent.Locale'",
")",
";",
"if",
"(",
"$",
"localeCode",
")",
"{",
"$",
"locale",
"=",
"Locale",
"::",
"getBy... | Get locale this record was originally queried from, or belongs to
@return Locale|null | [
"Get",
"locale",
"this",
"record",
"was",
"originally",
"queried",
"from",
"or",
"belongs",
"to"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L737-L747 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getSourceLocale | public function getSourceLocale()
{
$sourceLocale = $this->owner->getField('SourceLocale');
if ($sourceLocale) {
return Locale::getByLocale($sourceLocale);
}
return Locale::getDefault();
} | php | public function getSourceLocale()
{
$sourceLocale = $this->owner->getField('SourceLocale');
if ($sourceLocale) {
return Locale::getByLocale($sourceLocale);
}
return Locale::getDefault();
} | [
"public",
"function",
"getSourceLocale",
"(",
")",
"{",
"$",
"sourceLocale",
"=",
"$",
"this",
"->",
"owner",
"->",
"getField",
"(",
"'SourceLocale'",
")",
";",
"if",
"(",
"$",
"sourceLocale",
")",
"{",
"return",
"Locale",
"::",
"getByLocale",
"(",
"$",
... | Returns the source locale that will display the content for this record
@return Locale|null | [
"Returns",
"the",
"source",
"locale",
"that",
"will",
"display",
"the",
"content",
"for",
"this",
"record"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L755-L762 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getManipulationRecordID | protected function getManipulationRecordID($updates)
{
if (isset($updates['id'])) {
return $updates['id'];
}
if (isset($updates['fields']['ID'])) {
return $updates['fields']['ID'];
}
if (isset($updates['fields']['RecordID'])) {
return $updates['fields']['RecordID'];
}
return null;
} | php | protected function getManipulationRecordID($updates)
{
if (isset($updates['id'])) {
return $updates['id'];
}
if (isset($updates['fields']['ID'])) {
return $updates['fields']['ID'];
}
if (isset($updates['fields']['RecordID'])) {
return $updates['fields']['RecordID'];
}
return null;
} | [
"protected",
"function",
"getManipulationRecordID",
"(",
"$",
"updates",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"updates",
"[",
"'id'",
"]",
")",
")",
"{",
"return",
"$",
"updates",
"[",
"'id'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"updates"... | Extract the RecordID value for the given write
@param array $updates Updates for the current table
@return null|int Record ID, or null if not found | [
"Extract",
"the",
"RecordID",
"value",
"for",
"the",
"given",
"write"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L770-L782 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.Locales | public function Locales()
{
$data = [];
foreach (Locale::getCached() as $localeObj) {
/** @var Locale $localeObj */
$data[] = $this->owner->LocaleInformation($localeObj->getLocale());
}
return ArrayList::create($data);
} | php | public function Locales()
{
$data = [];
foreach (Locale::getCached() as $localeObj) {
/** @var Locale $localeObj */
$data[] = $this->owner->LocaleInformation($localeObj->getLocale());
}
return ArrayList::create($data);
} | [
"public",
"function",
"Locales",
"(",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"Locale",
"::",
"getCached",
"(",
")",
"as",
"$",
"localeObj",
")",
"{",
"/** @var Locale $localeObj */",
"$",
"data",
"[",
"]",
"=",
"$",
"this",
"->",
... | Templatable list of all locales
@return ArrayList | [
"Templatable",
"list",
"of",
"all",
"locales"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L789-L797 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.LocaleInformation | public function LocaleInformation($locale = null)
{
// Check locale and get object
if ($locale) {
$localeObj = Locale::getByLocale($locale);
} else {
$localeObj = Locale::getDefault();
}
$locale = $localeObj->getLocale();
// Check linking mode
$linkingMode = $this->getLinkingMode($locale);
// Check link
$link = $this->LocaleLink($locale);
// Store basic locale information
return ArrayData::create([
'Locale' => $locale,
'LocaleRFC1766' => i18n::convert_rfc1766($locale),
'URLSegment' => $localeObj->getURLSegment(),
'Title' => $localeObj->getTitle(),
'LanguageNative' => $localeObj->getNativeName(),
'Language' => i18n::getData()->langFromLocale($locale),
'Link' => $link,
'AbsoluteLink' => $link ? Director::absoluteURL($link) : null,
'LinkingMode' => $linkingMode
]);
} | php | public function LocaleInformation($locale = null)
{
// Check locale and get object
if ($locale) {
$localeObj = Locale::getByLocale($locale);
} else {
$localeObj = Locale::getDefault();
}
$locale = $localeObj->getLocale();
// Check linking mode
$linkingMode = $this->getLinkingMode($locale);
// Check link
$link = $this->LocaleLink($locale);
// Store basic locale information
return ArrayData::create([
'Locale' => $locale,
'LocaleRFC1766' => i18n::convert_rfc1766($locale),
'URLSegment' => $localeObj->getURLSegment(),
'Title' => $localeObj->getTitle(),
'LanguageNative' => $localeObj->getNativeName(),
'Language' => i18n::getData()->langFromLocale($locale),
'Link' => $link,
'AbsoluteLink' => $link ? Director::absoluteURL($link) : null,
'LinkingMode' => $linkingMode
]);
} | [
"public",
"function",
"LocaleInformation",
"(",
"$",
"locale",
"=",
"null",
")",
"{",
"// Check locale and get object",
"if",
"(",
"$",
"locale",
")",
"{",
"$",
"localeObj",
"=",
"Locale",
"::",
"getByLocale",
"(",
"$",
"locale",
")",
";",
"}",
"else",
"{"... | Retrieves information about this object in the specified locale
@param string $locale The locale (code) information to request, or null to use the default locale
@return ArrayData Mapped list of locale properties | [
"Retrieves",
"information",
"about",
"this",
"object",
"in",
"the",
"specified",
"locale"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L805-L833 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.getLinkingMode | public function getLinkingMode($locale)
{
if ($this->owner->hasMethod('canViewInLocale') && !$this->owner->canViewInLocale($locale)) {
return 'invalid';
}
if ($locale === FluentState::singleton()->getLocale()) {
return 'current';
}
return 'link';
} | php | public function getLinkingMode($locale)
{
if ($this->owner->hasMethod('canViewInLocale') && !$this->owner->canViewInLocale($locale)) {
return 'invalid';
}
if ($locale === FluentState::singleton()->getLocale()) {
return 'current';
}
return 'link';
} | [
"public",
"function",
"getLinkingMode",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"owner",
"->",
"hasMethod",
"(",
"'canViewInLocale'",
")",
"&&",
"!",
"$",
"this",
"->",
"owner",
"->",
"canViewInLocale",
"(",
"$",
"locale",
")",
")",
... | Return the linking mode for the current locale and object
@param string $locale
@return string | [
"Return",
"the",
"linking",
"mode",
"for",
"the",
"current",
"locale",
"and",
"object"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L841-L852 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentExtension.php | FluentExtension.requireSavedInLocale | protected function requireSavedInLocale()
{
if (FluentState::singleton()->getIsFrontend()) {
return $this->owner->config()->get('frontend_publish_required');
}
return $this->owner->config()->get('cms_publish_required');
} | php | protected function requireSavedInLocale()
{
if (FluentState::singleton()->getIsFrontend()) {
return $this->owner->config()->get('frontend_publish_required');
}
return $this->owner->config()->get('cms_publish_required');
} | [
"protected",
"function",
"requireSavedInLocale",
"(",
")",
"{",
"if",
"(",
"FluentState",
"::",
"singleton",
"(",
")",
"->",
"getIsFrontend",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"owner",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'frontend... | Require that this record is saved in the given locale for it to be visible
@return bool | [
"Require",
"that",
"this",
"record",
"is",
"saved",
"in",
"the",
"given",
"locale",
"for",
"it",
"to",
"be",
"visible"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentExtension.php#L952-L959 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentSiteTreeExtension.php | FluentSiteTreeExtension.updateRelativeLink | public function updateRelativeLink(&$base, &$action)
{
// Don't inject locale to subpages
if ($this->owner->ParentID && SiteTree::config()->get('nested_urls')) {
return;
}
// Get appropriate locale for this record
$localeObj = $this->getRecordLocale();
if (!$localeObj) {
return;
}
// For blank/temp pages such as Security controller fallback to querystring
if (!$this->owner->exists()) {
$base = Controller::join_links(
$base,
'?' . FluentDirectorExtension::config()->get('query_param') . '=' . urlencode($localeObj->Locale)
);
return;
}
// Check if this locale is the default for its own domain
if ($localeObj->getIsDefault()) {
// For home page in the default locale, do not alter home URL
if ($base === null || $base === RootURLController::get_homepage_link()) {
return;
}
// If default locale shouldn't have prefix, then don't add prefix
if (FluentDirectorExtension::config()->get('disable_default_prefix')) {
return;
}
// For all pages on a domain where there is only a single locale,
// then the domain itself is sufficient to distinguish that domain
// See https://github.com/tractorcow/silverstripe-fluent/issues/75
if ($localeObj->getIsOnlyLocale()) {
return;
}
}
// Simply join locale root with base relative URL
$base = Controller::join_links($localeObj->getURLSegment(), $base);
} | php | public function updateRelativeLink(&$base, &$action)
{
// Don't inject locale to subpages
if ($this->owner->ParentID && SiteTree::config()->get('nested_urls')) {
return;
}
// Get appropriate locale for this record
$localeObj = $this->getRecordLocale();
if (!$localeObj) {
return;
}
// For blank/temp pages such as Security controller fallback to querystring
if (!$this->owner->exists()) {
$base = Controller::join_links(
$base,
'?' . FluentDirectorExtension::config()->get('query_param') . '=' . urlencode($localeObj->Locale)
);
return;
}
// Check if this locale is the default for its own domain
if ($localeObj->getIsDefault()) {
// For home page in the default locale, do not alter home URL
if ($base === null || $base === RootURLController::get_homepage_link()) {
return;
}
// If default locale shouldn't have prefix, then don't add prefix
if (FluentDirectorExtension::config()->get('disable_default_prefix')) {
return;
}
// For all pages on a domain where there is only a single locale,
// then the domain itself is sufficient to distinguish that domain
// See https://github.com/tractorcow/silverstripe-fluent/issues/75
if ($localeObj->getIsOnlyLocale()) {
return;
}
}
// Simply join locale root with base relative URL
$base = Controller::join_links($localeObj->getURLSegment(), $base);
} | [
"public",
"function",
"updateRelativeLink",
"(",
"&",
"$",
"base",
",",
"&",
"$",
"action",
")",
"{",
"// Don't inject locale to subpages",
"if",
"(",
"$",
"this",
"->",
"owner",
"->",
"ParentID",
"&&",
"SiteTree",
"::",
"config",
"(",
")",
"->",
"get",
"(... | Add the current locale's URL segment to the start of the URL
@param string &$base
@param string &$action | [
"Add",
"the",
"current",
"locale",
"s",
"URL",
"segment",
"to",
"the",
"start",
"of",
"the",
"URL"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentSiteTreeExtension.php#L47-L91 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentSiteTreeExtension.php | FluentSiteTreeExtension.updateLink | public function updateLink(&$link, &$action, &$relativeLink)
{
// Get appropriate locale for this record
$localeObj = $this->getRecordLocale();
if (!$localeObj) {
return;
}
// Don't rewrite outside of domain mode
$domain = $localeObj->getDomain();
if (!$domain) {
return;
}
// Don't need to prepend domain if on the same domain
if (FluentState::singleton()->getDomain() === $domain->Domain) {
return;
}
// Prefix with domain
$link = Controller::join_links($domain->Link(), $link);
} | php | public function updateLink(&$link, &$action, &$relativeLink)
{
// Get appropriate locale for this record
$localeObj = $this->getRecordLocale();
if (!$localeObj) {
return;
}
// Don't rewrite outside of domain mode
$domain = $localeObj->getDomain();
if (!$domain) {
return;
}
// Don't need to prepend domain if on the same domain
if (FluentState::singleton()->getDomain() === $domain->Domain) {
return;
}
// Prefix with domain
$link = Controller::join_links($domain->Link(), $link);
} | [
"public",
"function",
"updateLink",
"(",
"&",
"$",
"link",
",",
"&",
"$",
"action",
",",
"&",
"$",
"relativeLink",
")",
"{",
"// Get appropriate locale for this record",
"$",
"localeObj",
"=",
"$",
"this",
"->",
"getRecordLocale",
"(",
")",
";",
"if",
"(",
... | Update link to include hostname if in domain mode
@param string $link root-relative url (includes baseurl)
@param string $action
@param string $relativeLink | [
"Update",
"link",
"to",
"include",
"hostname",
"if",
"in",
"domain",
"mode"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentSiteTreeExtension.php#L100-L121 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentSiteTreeExtension.php | FluentSiteTreeExtension.updateStatusFlags | public function updateStatusFlags(&$flags)
{
// If there is no current FluentState, then we shouldn't update.
if (!FluentState::singleton()->getLocale()) {
return;
}
// If this page does not exist it should be "invisible"
if (!$this->isDraftedInLocale() && !$this->isPublishedInLocale()) {
$flags['fluentinvisible'] = [
'text' => '',
'title' => '',
];
}
} | php | public function updateStatusFlags(&$flags)
{
// If there is no current FluentState, then we shouldn't update.
if (!FluentState::singleton()->getLocale()) {
return;
}
// If this page does not exist it should be "invisible"
if (!$this->isDraftedInLocale() && !$this->isPublishedInLocale()) {
$flags['fluentinvisible'] = [
'text' => '',
'title' => '',
];
}
} | [
"public",
"function",
"updateStatusFlags",
"(",
"&",
"$",
"flags",
")",
"{",
"// If there is no current FluentState, then we shouldn't update.",
"if",
"(",
"!",
"FluentState",
"::",
"singleton",
"(",
")",
"->",
"getLocale",
"(",
")",
")",
"{",
"return",
";",
"}",
... | Check whether the current page is exists in the current locale.
If it is invisible then we add a class to show it slightly greyed out in the site tree.
@param array $flags | [
"Check",
"whether",
"the",
"current",
"page",
"is",
"exists",
"in",
"the",
"current",
"locale",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentSiteTreeExtension.php#L130-L144 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentSiteTreeExtension.php | FluentSiteTreeExtension.addLocaleStatusMessage | protected function addLocaleStatusMessage(FieldList $fields)
{
// Don't display these messages if the owner class has asked us not to.
if (!$this->owner->config()->get('locale_published_status_message')) {
return;
}
// If the field is already present, don't add it a second time.
if ($fields->fieldByName('LocaleStatusMessage')) {
return;
}
// We don't need to add a status warning if a version of this Page has already been published for this Locale.
if ($this->isPublishedInLocale()) {
return;
}
$message = null;
if ($this->owner->config()->get('frontend_publish_required')) {
// If publishing is required, then we can just check whether or not this locale has been published.
if (!$this->isPublishedInLocale()) {
$message = _t(
__CLASS__ . '.LOCALESTATUSFLUENTINVISIBLE',
'This page will not be visible in this locale until it has been published.'
);
}
} else {
// If frontend publishing is *not* required, then we have two possibilities.
if (!$this->isDraftedInLocale()) {
// Our content hasn't been drafted or published. If this Locale has a Fallback, then content might be
// getting inherited from that Fallback.
$message = _t(
__CLASS__ . '.LOCALESTATUSFLUENTINHERITED',
'Content for this page may be inherited from another locale. If you wish you make an ' .
'independent copy of this page, please use one of the "Copy" actions provided.'
);
} elseif (!$this->isPublishedInLocale()) {
// Our content has been saved to draft, but hasn't yet been published. That published content may be
// coming from a Fallback.
$message = _t(
__CLASS__ . '.LOCALESTATUSFLUENTDRAFT',
'A draft has been created for this locale, however, published content may still be ' .
'inherited from another. To publish this content for this locale, use the "Save & publish" ' .
'action provided.'
);
}
}
if ($message === null) {
return;
}
$fields->unshift(
LiteralField::create(
'LocaleStatusMessage',
sprintf(
'<p class="alert alert-info">%s</p>',
$message
)
)
);
} | php | protected function addLocaleStatusMessage(FieldList $fields)
{
// Don't display these messages if the owner class has asked us not to.
if (!$this->owner->config()->get('locale_published_status_message')) {
return;
}
// If the field is already present, don't add it a second time.
if ($fields->fieldByName('LocaleStatusMessage')) {
return;
}
// We don't need to add a status warning if a version of this Page has already been published for this Locale.
if ($this->isPublishedInLocale()) {
return;
}
$message = null;
if ($this->owner->config()->get('frontend_publish_required')) {
// If publishing is required, then we can just check whether or not this locale has been published.
if (!$this->isPublishedInLocale()) {
$message = _t(
__CLASS__ . '.LOCALESTATUSFLUENTINVISIBLE',
'This page will not be visible in this locale until it has been published.'
);
}
} else {
// If frontend publishing is *not* required, then we have two possibilities.
if (!$this->isDraftedInLocale()) {
// Our content hasn't been drafted or published. If this Locale has a Fallback, then content might be
// getting inherited from that Fallback.
$message = _t(
__CLASS__ . '.LOCALESTATUSFLUENTINHERITED',
'Content for this page may be inherited from another locale. If you wish you make an ' .
'independent copy of this page, please use one of the "Copy" actions provided.'
);
} elseif (!$this->isPublishedInLocale()) {
// Our content has been saved to draft, but hasn't yet been published. That published content may be
// coming from a Fallback.
$message = _t(
__CLASS__ . '.LOCALESTATUSFLUENTDRAFT',
'A draft has been created for this locale, however, published content may still be ' .
'inherited from another. To publish this content for this locale, use the "Save & publish" ' .
'action provided.'
);
}
}
if ($message === null) {
return;
}
$fields->unshift(
LiteralField::create(
'LocaleStatusMessage',
sprintf(
'<p class="alert alert-info">%s</p>',
$message
)
)
);
} | [
"protected",
"function",
"addLocaleStatusMessage",
"(",
"FieldList",
"$",
"fields",
")",
"{",
"// Don't display these messages if the owner class has asked us not to.",
"if",
"(",
"!",
"$",
"this",
"->",
"owner",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'locale_pu... | Adds a UI message to indicate whether you're editing in the default locale or not
@param FieldList $fields | [
"Adds",
"a",
"UI",
"message",
"to",
"indicate",
"whether",
"you",
"re",
"editing",
"in",
"the",
"default",
"locale",
"or",
"not"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentSiteTreeExtension.php#L179-L241 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentSiteTreeExtension.php | FluentSiteTreeExtension.addLocalePrefixToUrlSegment | protected function addLocalePrefixToUrlSegment(FieldList $fields)
{
// Ensure the field is available in the list
$segmentField = $fields->fieldByName('Root.Main.URLSegment');
if (!$segmentField || !($segmentField instanceof SiteTreeURLSegmentField)) {
return $this;
}
// Mock frontend and get link to parent object / page
$baseURL = FluentState::singleton()
->withState(function (FluentState $tempState) {
$tempState->setIsDomainMode(true);
$tempState->setIsFrontend(true);
// Get relative link up until the current URL segment
if (SiteTree::config()->get('nested_urls') && $this->owner->ParentID) {
$parentRelative = $this->owner->Parent()->RelativeLink();
} else {
$parentRelative = '/';
$action = null;
$this->updateRelativeLink($parentRelative, $action);
}
// Get absolute base path
$domain = Locale::getCurrentLocale()->getDomain();
if ($domain) {
$parentBase = Controller::join_links($domain->Link(), Director::baseURL());
} else {
$parentBase = Director::absoluteBaseURL();
}
// Join base / relative links
return Controller::join_links($parentBase, $parentRelative);
});
$segmentField->setURLPrefix($baseURL);
return $this;
} | php | protected function addLocalePrefixToUrlSegment(FieldList $fields)
{
// Ensure the field is available in the list
$segmentField = $fields->fieldByName('Root.Main.URLSegment');
if (!$segmentField || !($segmentField instanceof SiteTreeURLSegmentField)) {
return $this;
}
// Mock frontend and get link to parent object / page
$baseURL = FluentState::singleton()
->withState(function (FluentState $tempState) {
$tempState->setIsDomainMode(true);
$tempState->setIsFrontend(true);
// Get relative link up until the current URL segment
if (SiteTree::config()->get('nested_urls') && $this->owner->ParentID) {
$parentRelative = $this->owner->Parent()->RelativeLink();
} else {
$parentRelative = '/';
$action = null;
$this->updateRelativeLink($parentRelative, $action);
}
// Get absolute base path
$domain = Locale::getCurrentLocale()->getDomain();
if ($domain) {
$parentBase = Controller::join_links($domain->Link(), Director::baseURL());
} else {
$parentBase = Director::absoluteBaseURL();
}
// Join base / relative links
return Controller::join_links($parentBase, $parentRelative);
});
$segmentField->setURLPrefix($baseURL);
return $this;
} | [
"protected",
"function",
"addLocalePrefixToUrlSegment",
"(",
"FieldList",
"$",
"fields",
")",
"{",
"// Ensure the field is available in the list",
"$",
"segmentField",
"=",
"$",
"fields",
"->",
"fieldByName",
"(",
"'Root.Main.URLSegment'",
")",
";",
"if",
"(",
"!",
"$... | Add the locale's URLSegment to the URL prefix for a page's URL segment field
@param FieldList $fields
@return $this | [
"Add",
"the",
"locale",
"s",
"URLSegment",
"to",
"the",
"URL",
"prefix",
"for",
"a",
"page",
"s",
"URL",
"segment",
"field"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentSiteTreeExtension.php#L249-L287 | train |
tractorcow-farm/silverstripe-fluent | src/Model/CachableModel.php | CachableModel.databaseIsReady | protected static function databaseIsReady()
{
$object = DataObject::singleton(static::class);
// if any of the tables aren't created in the database
$table = $object->baseTable();
if (!ClassInfo::hasTable($table)) {
return false;
}
// if any of the tables don't have all fields mapped as table columns
$dbFields = DB::field_list($table);
if (!$dbFields) {
return false;
}
$objFields = $object->getSchema()->databaseFields($object, false);
$missingFields = array_diff_key($objFields, $dbFields);
if ($missingFields) {
return false;
}
return true;
} | php | protected static function databaseIsReady()
{
$object = DataObject::singleton(static::class);
// if any of the tables aren't created in the database
$table = $object->baseTable();
if (!ClassInfo::hasTable($table)) {
return false;
}
// if any of the tables don't have all fields mapped as table columns
$dbFields = DB::field_list($table);
if (!$dbFields) {
return false;
}
$objFields = $object->getSchema()->databaseFields($object, false);
$missingFields = array_diff_key($objFields, $dbFields);
if ($missingFields) {
return false;
}
return true;
} | [
"protected",
"static",
"function",
"databaseIsReady",
"(",
")",
"{",
"$",
"object",
"=",
"DataObject",
"::",
"singleton",
"(",
"static",
"::",
"class",
")",
";",
"// if any of the tables aren't created in the database",
"$",
"table",
"=",
"$",
"object",
"->",
"bas... | Check if the DB is able to safely query this model
@return bool | [
"Check",
"if",
"the",
"DB",
"is",
"able",
"to",
"safely",
"query",
"this",
"model"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/CachableModel.php#L70-L94 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Domain.php | Domain.DefaultLocale | public function DefaultLocale()
{
// Return explicit default locale
if ($this->DefaultLocaleID) {
$locale = Locale::getCached()->byID($this->DefaultLocaleID);
if ($locale) {
return $locale;
}
}
// Use IsGlobalDefault if this is a member of this locale, or the first in the list of children
$locales = Locale::getCached()->filter('DomainID', $this->ID);
return $locales->filter('IsGlobalDefault', 1)->first()
?: $locales->first();
} | php | public function DefaultLocale()
{
// Return explicit default locale
if ($this->DefaultLocaleID) {
$locale = Locale::getCached()->byID($this->DefaultLocaleID);
if ($locale) {
return $locale;
}
}
// Use IsGlobalDefault if this is a member of this locale, or the first in the list of children
$locales = Locale::getCached()->filter('DomainID', $this->ID);
return $locales->filter('IsGlobalDefault', 1)->first()
?: $locales->first();
} | [
"public",
"function",
"DefaultLocale",
"(",
")",
"{",
"// Return explicit default locale",
"if",
"(",
"$",
"this",
"->",
"DefaultLocaleID",
")",
"{",
"$",
"locale",
"=",
"Locale",
"::",
"getCached",
"(",
")",
"->",
"byID",
"(",
"$",
"this",
"->",
"DefaultLoc... | Get default locale for this domain
@return Locale | [
"Get",
"default",
"locale",
"for",
"this",
"domain"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Domain.php#L126-L140 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Domain.php | Domain.getByDomain | public static function getByDomain($domain)
{
// Map true -> actual domain
if ($domain === true) {
$state = FluentState::singleton();
$domain = $state->getIsDomainMode() ? $state->getDomain() : null;
}
// No domain found
if (!$domain) {
return null;
}
if ($domain instanceof Domain) {
return $domain;
}
// Get filtered domain
return static::getCached()
->filter('Domain', $domain)
->first();
} | php | public static function getByDomain($domain)
{
// Map true -> actual domain
if ($domain === true) {
$state = FluentState::singleton();
$domain = $state->getIsDomainMode() ? $state->getDomain() : null;
}
// No domain found
if (!$domain) {
return null;
}
if ($domain instanceof Domain) {
return $domain;
}
// Get filtered domain
return static::getCached()
->filter('Domain', $domain)
->first();
} | [
"public",
"static",
"function",
"getByDomain",
"(",
"$",
"domain",
")",
"{",
"// Map true -> actual domain",
"if",
"(",
"$",
"domain",
"===",
"true",
")",
"{",
"$",
"state",
"=",
"FluentState",
"::",
"singleton",
"(",
")",
";",
"$",
"domain",
"=",
"$",
"... | Get domain by the specifed hostname.
If `true` is passed, and the site is in domain mode, this will return current domain instead.
@param string|true|Domain $domain
@return Domain | [
"Get",
"domain",
"by",
"the",
"specifed",
"hostname",
".",
"If",
"true",
"is",
"passed",
"and",
"the",
"site",
"is",
"in",
"domain",
"mode",
"this",
"will",
"return",
"current",
"domain",
"instead",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Domain.php#L161-L182 | train |
tractorcow-farm/silverstripe-fluent | src/State/BrowserLocaleDetector.php | BrowserLocaleDetector.detectLocale | public function detectLocale(HTTPRequest $request)
{
// Given multiple canditates, narrow down the final result using the client's preferred languages
$inputLocales = $request->getHeader('Accept-Language');
if (empty($inputLocales)) {
return null;
}
// Generate mapping of priority => list of locales at this priority
// break up string into pieces (languages and q factors)
preg_match_all(
'/(?<code>[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?<priority>1|0\.[0-9]+))?/i',
$inputLocales,
$parsedLocales
);
$prioritisedLocales = [];
if (count($parsedLocales['code'])) {
// create a list like "en" => 0.8
$parsedLocales = array_combine($parsedLocales['code'], $parsedLocales['priority']);
// Generate nested list of priorities => [locales]
foreach ($parsedLocales as $locale => $priority) {
$priority = empty($priority) ? "1.0" : (string)floatval($priority);
if (empty($prioritisedLocales[$priority])) {
$prioritisedLocales[$priority] = [];
}
$prioritisedLocales[$priority][] = $locale;
}
// sort list based on value
krsort($prioritisedLocales, SORT_NUMERIC);
}
// Check each requested locale against loaded locales
$locales = Locale::getLocales(true);
foreach ($prioritisedLocales as $priority => $parsedLocales) {
foreach ($parsedLocales as $browserLocale) {
foreach ($locales as $localeObj) {
/** @var Locale $localeObj */
if ($localeObj->isLocale($browserLocale)) {
return $localeObj;
}
}
}
}
return null;
} | php | public function detectLocale(HTTPRequest $request)
{
// Given multiple canditates, narrow down the final result using the client's preferred languages
$inputLocales = $request->getHeader('Accept-Language');
if (empty($inputLocales)) {
return null;
}
// Generate mapping of priority => list of locales at this priority
// break up string into pieces (languages and q factors)
preg_match_all(
'/(?<code>[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?<priority>1|0\.[0-9]+))?/i',
$inputLocales,
$parsedLocales
);
$prioritisedLocales = [];
if (count($parsedLocales['code'])) {
// create a list like "en" => 0.8
$parsedLocales = array_combine($parsedLocales['code'], $parsedLocales['priority']);
// Generate nested list of priorities => [locales]
foreach ($parsedLocales as $locale => $priority) {
$priority = empty($priority) ? "1.0" : (string)floatval($priority);
if (empty($prioritisedLocales[$priority])) {
$prioritisedLocales[$priority] = [];
}
$prioritisedLocales[$priority][] = $locale;
}
// sort list based on value
krsort($prioritisedLocales, SORT_NUMERIC);
}
// Check each requested locale against loaded locales
$locales = Locale::getLocales(true);
foreach ($prioritisedLocales as $priority => $parsedLocales) {
foreach ($parsedLocales as $browserLocale) {
foreach ($locales as $localeObj) {
/** @var Locale $localeObj */
if ($localeObj->isLocale($browserLocale)) {
return $localeObj;
}
}
}
}
return null;
} | [
"public",
"function",
"detectLocale",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"// Given multiple canditates, narrow down the final result using the client's preferred languages",
"$",
"inputLocales",
"=",
"$",
"request",
"->",
"getHeader",
"(",
"'Accept-Language'",
")",
... | Determines the locale best matching the given list of browser locales
@param HTTPRequest $request
@return Locale The matching locale, or null if none could be determined | [
"Determines",
"the",
"locale",
"best",
"matching",
"the",
"given",
"list",
"of",
"browser",
"locales"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/State/BrowserLocaleDetector.php#L29-L76 | train |
tractorcow-farm/silverstripe-fluent | src/Task/ConvertTranslatableTask.php | ConvertTranslatableTask.checkInstalled | protected function checkInstalled()
{
// Assert that fluent is configured
$locales = Locale::getLocales();
if (empty($locales)) {
throw new Exception("Please configure Fluent locales (in the CMS) prior to migrating from translatable");
}
$defaultLocale = Locale::getDefault();
if (empty($defaultLocale)) {
throw new Exception(
"Please configure a Fluent default locale (in the CMS) prior to migrating from translatable"
);
}
} | php | protected function checkInstalled()
{
// Assert that fluent is configured
$locales = Locale::getLocales();
if (empty($locales)) {
throw new Exception("Please configure Fluent locales (in the CMS) prior to migrating from translatable");
}
$defaultLocale = Locale::getDefault();
if (empty($defaultLocale)) {
throw new Exception(
"Please configure a Fluent default locale (in the CMS) prior to migrating from translatable"
);
}
} | [
"protected",
"function",
"checkInstalled",
"(",
")",
"{",
"// Assert that fluent is configured",
"$",
"locales",
"=",
"Locale",
"::",
"getLocales",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"locales",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Pl... | Checks that fluent is configured correctly
@throws ConvertTranslatableTask\Exception | [
"Checks",
"that",
"fluent",
"is",
"configured",
"correctly"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Task/ConvertTranslatableTask.php#L48-L62 | train |
tractorcow-farm/silverstripe-fluent | src/Task/ConvertTranslatableTask.php | ConvertTranslatableTask.fluentClasses | public function fluentClasses()
{
$classes = [];
$dataClasses = ClassInfo::subclassesFor(DataObject::class);
array_shift($dataClasses);
foreach ($dataClasses as $class) {
$base = DataObject::getSchema()->baseDataClass($class);
foreach (DataObject::get_extensions($base) as $extension) {
if (is_a($extension, FluentExtension::class, true)) {
$classes[] = $base;
break;
}
}
}
return array_unique($classes);
} | php | public function fluentClasses()
{
$classes = [];
$dataClasses = ClassInfo::subclassesFor(DataObject::class);
array_shift($dataClasses);
foreach ($dataClasses as $class) {
$base = DataObject::getSchema()->baseDataClass($class);
foreach (DataObject::get_extensions($base) as $extension) {
if (is_a($extension, FluentExtension::class, true)) {
$classes[] = $base;
break;
}
}
}
return array_unique($classes);
} | [
"public",
"function",
"fluentClasses",
"(",
")",
"{",
"$",
"classes",
"=",
"[",
"]",
";",
"$",
"dataClasses",
"=",
"ClassInfo",
"::",
"subclassesFor",
"(",
"DataObject",
"::",
"class",
")",
";",
"array_shift",
"(",
"$",
"dataClasses",
")",
";",
"foreach",
... | Gets all classes with FluentExtension
@return array Array of classes to migrate | [
"Gets",
"all",
"classes",
"with",
"FluentExtension"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Task/ConvertTranslatableTask.php#L69-L84 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/DetectLocaleMiddleware.php | DetectLocaleMiddleware.process | public function process(HTTPRequest $request, callable $delegate)
{
$state = FluentState::singleton();
$locale = $state->getLocale();
if (!$locale) {
$locale = $this->getLocale($request);
$state->setLocale($locale);
}
if ($locale && $state->getIsFrontend()) {
i18n::set_locale($state->getLocale());
}
// Persist the current locale if it has a value.
// Distinguishes null from empty strings in order to unset locales.
$newLocale = $state->getLocale();
if (!is_null($newLocale)) {
$this->setPersistLocale($request, $newLocale);
}
return $delegate($request);
} | php | public function process(HTTPRequest $request, callable $delegate)
{
$state = FluentState::singleton();
$locale = $state->getLocale();
if (!$locale) {
$locale = $this->getLocale($request);
$state->setLocale($locale);
}
if ($locale && $state->getIsFrontend()) {
i18n::set_locale($state->getLocale());
}
// Persist the current locale if it has a value.
// Distinguishes null from empty strings in order to unset locales.
$newLocale = $state->getLocale();
if (!is_null($newLocale)) {
$this->setPersistLocale($request, $newLocale);
}
return $delegate($request);
} | [
"public",
"function",
"process",
"(",
"HTTPRequest",
"$",
"request",
",",
"callable",
"$",
"delegate",
")",
"{",
"$",
"state",
"=",
"FluentState",
"::",
"singleton",
"(",
")",
";",
"$",
"locale",
"=",
"$",
"state",
"->",
"getLocale",
"(",
")",
";",
"if... | Sets the current locale to the FluentState, provided no previous middleware has set it first
{@inheritDoc} | [
"Sets",
"the",
"current",
"locale",
"to",
"the",
"FluentState",
"provided",
"no",
"previous",
"middleware",
"has",
"set",
"it",
"first"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/DetectLocaleMiddleware.php#L85-L107 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/DetectLocaleMiddleware.php | DetectLocaleMiddleware.getLocale | protected function getLocale(HTTPRequest $request)
{
// Check direct request from either routing params, or request (e.g. GET) vars, in that order
$locale = $this->getParamLocale($request);
// Check against domain (non-ambiguous locale only)
if (empty($locale)) {
$locale = $this->getDomainLocale();
}
// Look for persisted locale
if (empty($locale)) {
$locale = $this->getPersistLocale($request);
}
// Use locale detector (if configured)
if (empty($locale)) {
$locale = $this->getDetectedLocale($request);
}
// Fallback to default if empty or invalid
if (empty($locale) || !Locale::getByLocale($locale)) {
$locale = $this->getDefaultLocale();
}
return (string) $locale;
} | php | protected function getLocale(HTTPRequest $request)
{
// Check direct request from either routing params, or request (e.g. GET) vars, in that order
$locale = $this->getParamLocale($request);
// Check against domain (non-ambiguous locale only)
if (empty($locale)) {
$locale = $this->getDomainLocale();
}
// Look for persisted locale
if (empty($locale)) {
$locale = $this->getPersistLocale($request);
}
// Use locale detector (if configured)
if (empty($locale)) {
$locale = $this->getDetectedLocale($request);
}
// Fallback to default if empty or invalid
if (empty($locale) || !Locale::getByLocale($locale)) {
$locale = $this->getDefaultLocale();
}
return (string) $locale;
} | [
"protected",
"function",
"getLocale",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"// Check direct request from either routing params, or request (e.g. GET) vars, in that order",
"$",
"locale",
"=",
"$",
"this",
"->",
"getParamLocale",
"(",
"$",
"request",
")",
";",
"//... | Get the current locale from routing parameters, persistence, browser locale, etc
@param HTTPRequest $request
@return string | [
"Get",
"the",
"current",
"locale",
"from",
"routing",
"parameters",
"persistence",
"browser",
"locale",
"etc"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/DetectLocaleMiddleware.php#L115-L141 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/DetectLocaleMiddleware.php | DetectLocaleMiddleware.getPersistLocale | protected function getPersistLocale(HTTPRequest $request)
{
$key = $this->getPersistKey();
// Skip persist if key is unset
if (empty($key)) {
return null;
}
// check session then cookies
$session = $request->getSession();
if ($session->isStarted() && ($locale = $session->get($key))) {
return $locale;
}
if (static::config()->get('persist_cookie') && ($locale = Cookie::get($key))) {
return $locale;
}
return null;
} | php | protected function getPersistLocale(HTTPRequest $request)
{
$key = $this->getPersistKey();
// Skip persist if key is unset
if (empty($key)) {
return null;
}
// check session then cookies
$session = $request->getSession();
if ($session->isStarted() && ($locale = $session->get($key))) {
return $locale;
}
if (static::config()->get('persist_cookie') && ($locale = Cookie::get($key))) {
return $locale;
}
return null;
} | [
"protected",
"function",
"getPersistLocale",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getPersistKey",
"(",
")",
";",
"// Skip persist if key is unset",
"if",
"(",
"empty",
"(",
"$",
"key",
")",
")",
"{",
"return",
... | Gets the locale currently set within either the session or cookie.
@param HTTPRequest $request
@return null|string The locale, if available | [
"Gets",
"the",
"locale",
"currently",
"set",
"within",
"either",
"the",
"session",
"or",
"cookie",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/DetectLocaleMiddleware.php#L149-L169 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/DetectLocaleMiddleware.php | DetectLocaleMiddleware.getParamLocale | protected function getParamLocale(HTTPRequest $request)
{
$queryParam = FluentDirectorExtension::config()->get('query_param');
$locale = (string)($request->param($queryParam) ?: $request->requestVar($queryParam));
return $locale;
} | php | protected function getParamLocale(HTTPRequest $request)
{
$queryParam = FluentDirectorExtension::config()->get('query_param');
$locale = (string)($request->param($queryParam) ?: $request->requestVar($queryParam));
return $locale;
} | [
"protected",
"function",
"getParamLocale",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"queryParam",
"=",
"FluentDirectorExtension",
"::",
"config",
"(",
")",
"->",
"get",
"(",
"'query_param'",
")",
";",
"$",
"locale",
"=",
"(",
"string",
")",
"(",
... | Get locale from the query_param
@param HTTPRequest $request
@return mixed | [
"Get",
"locale",
"from",
"the",
"query_param"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/DetectLocaleMiddleware.php#L235-L240 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/DetectLocaleMiddleware.php | DetectLocaleMiddleware.getDomainLocale | protected function getDomainLocale()
{
$state = FluentState::singleton();
// Ensure a domain is configured
if (!$state->getIsDomainMode()) {
return null;
}
$domain = $state->getDomain();
if (!$domain) {
return null;
}
// Get domain
$domainObj = Domain::getByDomain($domain);
if (!$domainObj) {
return null;
}
// If the current domain has exactly one locale, the locale is non-ambiguous
$locales = Locale::getCached()->filter('DomainID', $domainObj->ID);
/** @var Locale $localeObject */
$localeObject = $locales->first();
if ($localeObject) {
return $localeObject->getLocale();
}
return null;
} | php | protected function getDomainLocale()
{
$state = FluentState::singleton();
// Ensure a domain is configured
if (!$state->getIsDomainMode()) {
return null;
}
$domain = $state->getDomain();
if (!$domain) {
return null;
}
// Get domain
$domainObj = Domain::getByDomain($domain);
if (!$domainObj) {
return null;
}
// If the current domain has exactly one locale, the locale is non-ambiguous
$locales = Locale::getCached()->filter('DomainID', $domainObj->ID);
/** @var Locale $localeObject */
$localeObject = $locales->first();
if ($localeObject) {
return $localeObject->getLocale();
}
return null;
} | [
"protected",
"function",
"getDomainLocale",
"(",
")",
"{",
"$",
"state",
"=",
"FluentState",
"::",
"singleton",
"(",
")",
";",
"// Ensure a domain is configured",
"if",
"(",
"!",
"$",
"state",
"->",
"getIsDomainMode",
"(",
")",
")",
"{",
"return",
"null",
";... | Get locale from the domain, if the current domain has exactly one locale
@return string | [
"Get",
"locale",
"from",
"the",
"domain",
"if",
"the",
"current",
"domain",
"has",
"exactly",
"one",
"locale"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/DetectLocaleMiddleware.php#L247-L275 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/DetectLocaleMiddleware.php | DetectLocaleMiddleware.getDetectedLocale | protected function getDetectedLocale(HTTPRequest $request)
{
// Only detect on home page (landing page)
if ($request->getURL() !== '') {
return null;
}
// Respect config disable
if (!FluentDirectorExtension::config()->get('detect_locale')) {
return null;
}
/** @var LocaleDetector $detector */
$detector = Injector::inst()->get(LocaleDetector::class);
$localeObj = $detector->detectLocale($request);
if ($localeObj) {
return $localeObj->getLocale();
}
return null;
} | php | protected function getDetectedLocale(HTTPRequest $request)
{
// Only detect on home page (landing page)
if ($request->getURL() !== '') {
return null;
}
// Respect config disable
if (!FluentDirectorExtension::config()->get('detect_locale')) {
return null;
}
/** @var LocaleDetector $detector */
$detector = Injector::inst()->get(LocaleDetector::class);
$localeObj = $detector->detectLocale($request);
if ($localeObj) {
return $localeObj->getLocale();
}
return null;
} | [
"protected",
"function",
"getDetectedLocale",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"// Only detect on home page (landing page)",
"if",
"(",
"$",
"request",
"->",
"getURL",
"(",
")",
"!==",
"''",
")",
"{",
"return",
"null",
";",
"}",
"// Respect config dis... | Use the configured LocaleDetector to guess the locale
@param HTTPRequest $request
@return string | [
"Use",
"the",
"configured",
"LocaleDetector",
"to",
"guess",
"the",
"locale"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/DetectLocaleMiddleware.php#L283-L301 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentVersionedExtension.php | FluentVersionedExtension.rewriteVersionedTables | protected function rewriteVersionedTables(SQLSelect $query, array $tables, Locale $locale)
{
foreach ($tables as $tableName => $fields) {
// Rename to _Versions suffixed versions
$localisedTable = $this->getLocalisedTable($tableName);
$query->renameTable($localisedTable, $localisedTable . self::SUFFIX_VERSIONS);
// Add the chain of locale fallbacks
$this->addLocaleFallbackChain($query, $tableName, $locale);
}
} | php | protected function rewriteVersionedTables(SQLSelect $query, array $tables, Locale $locale)
{
foreach ($tables as $tableName => $fields) {
// Rename to _Versions suffixed versions
$localisedTable = $this->getLocalisedTable($tableName);
$query->renameTable($localisedTable, $localisedTable . self::SUFFIX_VERSIONS);
// Add the chain of locale fallbacks
$this->addLocaleFallbackChain($query, $tableName, $locale);
}
} | [
"protected",
"function",
"rewriteVersionedTables",
"(",
"SQLSelect",
"$",
"query",
",",
"array",
"$",
"tables",
",",
"Locale",
"$",
"locale",
")",
"{",
"foreach",
"(",
"$",
"tables",
"as",
"$",
"tableName",
"=>",
"$",
"fields",
")",
"{",
"// Rename to _Versi... | Rewrite all joined tables
@param SQLSelect $query
@param array $tables
@param Locale $locale | [
"Rewrite",
"all",
"joined",
"tables"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentVersionedExtension.php#L155-L165 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentVersionedExtension.php | FluentVersionedExtension.augmentWrite | public function augmentWrite(&$manipulation)
{
parent::augmentWrite($manipulation);
// Only rewrite if the locale is valid
$locale = Locale::getCurrentLocale();
if (!$locale) {
return;
}
// Get all tables to translate fields for, and their respective field names
$includedTables = $this->getLocalisedTables();
foreach ($includedTables as $table => $localisedFields) {
// Localise both _Versions and _Live writes
foreach ([self::SUFFIX_LIVE, self::SUFFIX_VERSIONS] as $suffix) {
$versionedTable = $table . $suffix;
$localisedTable = $this->getLocalisedTable($table) . $suffix;
// Add extra case for "Version" column when localising Versions
$localisedVersionFields = $localisedFields;
if ($suffix === self::SUFFIX_VERSIONS) {
$localisedVersionFields = array_merge(
$localisedVersionFields,
array_keys($this->defaultVersionsFields)
);
}
// Rewrite manipulation
$this->localiseManipulationTable(
$manipulation,
$versionedTable,
$localisedTable,
$localisedVersionFields,
$locale
);
}
}
} | php | public function augmentWrite(&$manipulation)
{
parent::augmentWrite($manipulation);
// Only rewrite if the locale is valid
$locale = Locale::getCurrentLocale();
if (!$locale) {
return;
}
// Get all tables to translate fields for, and their respective field names
$includedTables = $this->getLocalisedTables();
foreach ($includedTables as $table => $localisedFields) {
// Localise both _Versions and _Live writes
foreach ([self::SUFFIX_LIVE, self::SUFFIX_VERSIONS] as $suffix) {
$versionedTable = $table . $suffix;
$localisedTable = $this->getLocalisedTable($table) . $suffix;
// Add extra case for "Version" column when localising Versions
$localisedVersionFields = $localisedFields;
if ($suffix === self::SUFFIX_VERSIONS) {
$localisedVersionFields = array_merge(
$localisedVersionFields,
array_keys($this->defaultVersionsFields)
);
}
// Rewrite manipulation
$this->localiseManipulationTable(
$manipulation,
$versionedTable,
$localisedTable,
$localisedVersionFields,
$locale
);
}
}
} | [
"public",
"function",
"augmentWrite",
"(",
"&",
"$",
"manipulation",
")",
"{",
"parent",
"::",
"augmentWrite",
"(",
"$",
"manipulation",
")",
";",
"// Only rewrite if the locale is valid",
"$",
"locale",
"=",
"Locale",
"::",
"getCurrentLocale",
"(",
")",
";",
"i... | Apply versioning to write
@param array $manipulation | [
"Apply",
"versioning",
"to",
"write"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentVersionedExtension.php#L211-L248 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentVersionedExtension.php | FluentVersionedExtension.getDeleteTableTarget | protected function getDeleteTableTarget($tableName, $locale = '')
{
// Rewrite to _Live when deleting from live / unpublishing
$table = parent::getDeleteTableTarget($tableName, $locale);
if (Versioned::get_stage() === Versioned::LIVE) {
$table .= self::SUFFIX_LIVE;
}
return $table;
} | php | protected function getDeleteTableTarget($tableName, $locale = '')
{
// Rewrite to _Live when deleting from live / unpublishing
$table = parent::getDeleteTableTarget($tableName, $locale);
if (Versioned::get_stage() === Versioned::LIVE) {
$table .= self::SUFFIX_LIVE;
}
return $table;
} | [
"protected",
"function",
"getDeleteTableTarget",
"(",
"$",
"tableName",
",",
"$",
"locale",
"=",
"''",
")",
"{",
"// Rewrite to _Live when deleting from live / unpublishing",
"$",
"table",
"=",
"parent",
"::",
"getDeleteTableTarget",
"(",
"$",
"tableName",
",",
"$",
... | Decorate table to delete with _Live suffix as necessary
@param string $tableName
@param string $locale
@return string | [
"Decorate",
"table",
"to",
"delete",
"with",
"_Live",
"suffix",
"as",
"necessary"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentVersionedExtension.php#L257-L265 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentVersionedExtension.php | FluentVersionedExtension.isLocalisedInStage | protected function isLocalisedInStage($stage, $locale = null)
{
// Get locale
if (!$locale) {
$locale = FluentState::singleton()->getLocale();
// Potentially no Locales have been created in the system yet.
if (!$locale) {
return false;
}
}
// Get table
$baseTable = $this->owner->baseTable();
$table = $this->getLocalisedTable($baseTable);
if ($stage === Versioned::LIVE) {
$table .= self::SUFFIX_LIVE;
}
// Check for a cached item in the full list of all objects. These are populated optimistically.
if (isset(static::$idsInLocaleCache[$locale][$table][$this->owner->ID])) {
return (bool) static::$idsInLocaleCache[$locale][$table][$this->owner->ID];
}
if (!empty(static::$idsInLocaleCache[$locale][$table]['_complete'])) {
return false;
}
// Set cache and return
return static::$idsInLocaleCache[$locale][$table][$this->owner->ID]
= $this->findRecordInLocale($locale, $table, $this->owner->ID);
} | php | protected function isLocalisedInStage($stage, $locale = null)
{
// Get locale
if (!$locale) {
$locale = FluentState::singleton()->getLocale();
// Potentially no Locales have been created in the system yet.
if (!$locale) {
return false;
}
}
// Get table
$baseTable = $this->owner->baseTable();
$table = $this->getLocalisedTable($baseTable);
if ($stage === Versioned::LIVE) {
$table .= self::SUFFIX_LIVE;
}
// Check for a cached item in the full list of all objects. These are populated optimistically.
if (isset(static::$idsInLocaleCache[$locale][$table][$this->owner->ID])) {
return (bool) static::$idsInLocaleCache[$locale][$table][$this->owner->ID];
}
if (!empty(static::$idsInLocaleCache[$locale][$table]['_complete'])) {
return false;
}
// Set cache and return
return static::$idsInLocaleCache[$locale][$table][$this->owner->ID]
= $this->findRecordInLocale($locale, $table, $this->owner->ID);
} | [
"protected",
"function",
"isLocalisedInStage",
"(",
"$",
"stage",
",",
"$",
"locale",
"=",
"null",
")",
"{",
"// Get locale",
"if",
"(",
"!",
"$",
"locale",
")",
"{",
"$",
"locale",
"=",
"FluentState",
"::",
"singleton",
"(",
")",
"->",
"getLocale",
"(",... | Check to see whether or not a record exists for a specific Locale in a specific stage.
@param string $stage Version stage
@param string $locale Locale to check. Defaults to current locale.
@return bool | [
"Check",
"to",
"see",
"whether",
"or",
"not",
"a",
"record",
"exists",
"for",
"a",
"specific",
"Locale",
"in",
"a",
"specific",
"stage",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentVersionedExtension.php#L307-L338 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentVersionedExtension.php | FluentVersionedExtension.findRecordInLocale | protected function findRecordInLocale($locale, $table, $id)
{
$query = SQLSelect::create('"ID"');
$query->addFrom('"'. $table . '"');
$query->addWhere([
'"RecordID"' => $id,
'"Locale"' => $locale,
]);
return $query->firstRow()->execute()->value() !== null;
} | php | protected function findRecordInLocale($locale, $table, $id)
{
$query = SQLSelect::create('"ID"');
$query->addFrom('"'. $table . '"');
$query->addWhere([
'"RecordID"' => $id,
'"Locale"' => $locale,
]);
return $query->firstRow()->execute()->value() !== null;
} | [
"protected",
"function",
"findRecordInLocale",
"(",
"$",
"locale",
",",
"$",
"table",
",",
"$",
"id",
")",
"{",
"$",
"query",
"=",
"SQLSelect",
"::",
"create",
"(",
"'\"ID\"'",
")",
";",
"$",
"query",
"->",
"addFrom",
"(",
"'\"'",
".",
"$",
"table",
... | Checks whether the given record ID exists in the given locale, in the given table. Skips using the ORM because
we don't need it for this call.
@param string $locale
@param string $table
@param int $id
@return bool | [
"Checks",
"whether",
"the",
"given",
"record",
"ID",
"exists",
"in",
"the",
"given",
"locale",
"in",
"the",
"given",
"table",
".",
"Skips",
"using",
"the",
"ORM",
"because",
"we",
"don",
"t",
"need",
"it",
"for",
"this",
"call",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentVersionedExtension.php#L349-L359 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentVersionedExtension.php | FluentVersionedExtension.prepoulateIdsInLocale | public static function prepoulateIdsInLocale($locale, $dataObjectClass, $populateLive = true, $populateDraft = true)
{
// Get the table for the given DataObject class
/** @var DataObject|FluentExtension $dataObject */
$dataObject = DataObject::singleton($dataObjectClass);
$table = $dataObject->getLocalisedTable($dataObject->baseTable());
// If we already have items then we've been here before...
if (isset(self::$idsInLocaleCache[$locale][$table])) {
return;
}
$tables = [];
if ($populateDraft) {
$tables[] = $table;
}
if ($populateLive) {
$tables[] = $table . self::SUFFIX_LIVE;
}
// Populate both the draft and live stages
foreach ($tables as $table) {
/** @var SQLSelect $select */
$select = SQLSelect::create(
['"RecordID"'],
'"' . $table . '"',
['"Locale"' => $locale]
);
$result = $select->execute();
$ids = $result->column('RecordID');
// We need to execute ourselves as the param is lost from the subSelect
self::$idsInLocaleCache[$locale][$table] = array_combine($ids, $ids);
self::$idsInLocaleCache[$locale][$table]['_complete'] = true;
}
} | php | public static function prepoulateIdsInLocale($locale, $dataObjectClass, $populateLive = true, $populateDraft = true)
{
// Get the table for the given DataObject class
/** @var DataObject|FluentExtension $dataObject */
$dataObject = DataObject::singleton($dataObjectClass);
$table = $dataObject->getLocalisedTable($dataObject->baseTable());
// If we already have items then we've been here before...
if (isset(self::$idsInLocaleCache[$locale][$table])) {
return;
}
$tables = [];
if ($populateDraft) {
$tables[] = $table;
}
if ($populateLive) {
$tables[] = $table . self::SUFFIX_LIVE;
}
// Populate both the draft and live stages
foreach ($tables as $table) {
/** @var SQLSelect $select */
$select = SQLSelect::create(
['"RecordID"'],
'"' . $table . '"',
['"Locale"' => $locale]
);
$result = $select->execute();
$ids = $result->column('RecordID');
// We need to execute ourselves as the param is lost from the subSelect
self::$idsInLocaleCache[$locale][$table] = array_combine($ids, $ids);
self::$idsInLocaleCache[$locale][$table]['_complete'] = true;
}
} | [
"public",
"static",
"function",
"prepoulateIdsInLocale",
"(",
"$",
"locale",
",",
"$",
"dataObjectClass",
",",
"$",
"populateLive",
"=",
"true",
",",
"$",
"populateDraft",
"=",
"true",
")",
"{",
"// Get the table for the given DataObject class",
"/** @var DataObject|Flu... | Prepopulate the cache of IDs in a locale, to optimise batch calls to isLocalisedInStage.
@param string $locale
@param string $dataObjectClass
@param bool $populateLive
@param bool $populateDraft | [
"Prepopulate",
"the",
"cache",
"of",
"IDs",
"in",
"a",
"locale",
"to",
"optimise",
"batch",
"calls",
"to",
"isLocalisedInStage",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentVersionedExtension.php#L399-L434 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/InitStateMiddleware.php | InitStateMiddleware.getIsFrontend | public function getIsFrontend(HTTPRequest $request)
{
$adminPaths = static::config()->get('admin_url_paths');
$adminPaths[] = AdminRootController::config()->get('url_base') . '/';
$currentPath = rtrim($request->getURL(), '/') . '/';
foreach ($adminPaths as $adminPath) {
if (substr($currentPath, 0, strlen($adminPath)) === $adminPath) {
return false;
}
}
// If using the CMS preview, do not treat the site as frontend
if ($request->getVar('CMSPreview')) {
return false;
}
return true;
} | php | public function getIsFrontend(HTTPRequest $request)
{
$adminPaths = static::config()->get('admin_url_paths');
$adminPaths[] = AdminRootController::config()->get('url_base') . '/';
$currentPath = rtrim($request->getURL(), '/') . '/';
foreach ($adminPaths as $adminPath) {
if (substr($currentPath, 0, strlen($adminPath)) === $adminPath) {
return false;
}
}
// If using the CMS preview, do not treat the site as frontend
if ($request->getVar('CMSPreview')) {
return false;
}
return true;
} | [
"public",
"function",
"getIsFrontend",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"adminPaths",
"=",
"static",
"::",
"config",
"(",
")",
"->",
"get",
"(",
"'admin_url_paths'",
")",
";",
"$",
"adminPaths",
"[",
"]",
"=",
"AdminRootController",
"::",
... | Determine whether the website is being viewed from the frontend or not
@param HTTPRequest $request
@return bool | [
"Determine",
"whether",
"the",
"website",
"is",
"being",
"viewed",
"from",
"the",
"frontend",
"or",
"not"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/InitStateMiddleware.php#L63-L81 | train |
tractorcow-farm/silverstripe-fluent | src/Middleware/InitStateMiddleware.php | InitStateMiddleware.getIsDomainMode | public function getIsDomainMode(HTTPRequest $request)
{
// Don't act in domain mode if none exist
if (!Domain::getCached()->exists()) {
return false;
}
// Check environment for a forced override
if (Environment::getEnv('SS_FLUENT_FORCE_DOMAIN')) {
return true;
}
// Check config for a forced override
if (FluentDirectorExtension::config()->get('force_domain')) {
return true;
}
// Check if the current domain is included in the list of configured domains (default)
return Domain::getCached()->filter('Domain', Director::host($request))->exists();
} | php | public function getIsDomainMode(HTTPRequest $request)
{
// Don't act in domain mode if none exist
if (!Domain::getCached()->exists()) {
return false;
}
// Check environment for a forced override
if (Environment::getEnv('SS_FLUENT_FORCE_DOMAIN')) {
return true;
}
// Check config for a forced override
if (FluentDirectorExtension::config()->get('force_domain')) {
return true;
}
// Check if the current domain is included in the list of configured domains (default)
return Domain::getCached()->filter('Domain', Director::host($request))->exists();
} | [
"public",
"function",
"getIsDomainMode",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"// Don't act in domain mode if none exist",
"if",
"(",
"!",
"Domain",
"::",
"getCached",
"(",
")",
"->",
"exists",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Chec... | Determine whether the website is running in domain segmentation mode
@param HTTPRequest $request
@return bool | [
"Determine",
"whether",
"the",
"website",
"is",
"running",
"in",
"domain",
"segmentation",
"mode"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Middleware/InitStateMiddleware.php#L89-L108 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentBadgeExtension.php | FluentBadgeExtension.updateBadge | public function updateBadge(&$badgeField)
{
/** @var DataObject $record */
$record = $this->owner->getRecord();
$badgeField = $this->addFluentBadge($badgeField, $record);
} | php | public function updateBadge(&$badgeField)
{
/** @var DataObject $record */
$record = $this->owner->getRecord();
$badgeField = $this->addFluentBadge($badgeField, $record);
} | [
"public",
"function",
"updateBadge",
"(",
"&",
"$",
"badgeField",
")",
"{",
"/** @var DataObject $record */",
"$",
"record",
"=",
"$",
"this",
"->",
"owner",
"->",
"getRecord",
"(",
")",
";",
"$",
"badgeField",
"=",
"$",
"this",
"->",
"addFluentBadge",
"(",
... | Push a badge to indicate the language that owns the current item
@param DBField|null $badgeField | [
"Push",
"a",
"badge",
"to",
"indicate",
"the",
"language",
"that",
"owns",
"the",
"current",
"item"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentBadgeExtension.php#L19-L25 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentBadgeExtension.php | FluentBadgeExtension.addFluentBadge | protected function addFluentBadge($badgeField, DataObject $record)
{
// Check for a fluent state before continuing
if (!FluentState::singleton()->getLocale()
|| !$record->has_extension(FluentVersionedExtension::class)
) {
return null;
}
$fluentBadge = $this->getBadge($record);
// Add fluent badge before any existing badges
$newBadge = DBField::create_field('HTMLFragment', $fluentBadge . $badgeField);
return $newBadge;
} | php | protected function addFluentBadge($badgeField, DataObject $record)
{
// Check for a fluent state before continuing
if (!FluentState::singleton()->getLocale()
|| !$record->has_extension(FluentVersionedExtension::class)
) {
return null;
}
$fluentBadge = $this->getBadge($record);
// Add fluent badge before any existing badges
$newBadge = DBField::create_field('HTMLFragment', $fluentBadge . $badgeField);
return $newBadge;
} | [
"protected",
"function",
"addFluentBadge",
"(",
"$",
"badgeField",
",",
"DataObject",
"$",
"record",
")",
"{",
"// Check for a fluent state before continuing",
"if",
"(",
"!",
"FluentState",
"::",
"singleton",
"(",
")",
"->",
"getLocale",
"(",
")",
"||",
"!",
"$... | Add the Fluent state badge before any existing badges and return the result
@param DBField|null $badgeField
@param DataObject $record
@return DBField|null | [
"Add",
"the",
"Fluent",
"state",
"badge",
"before",
"any",
"existing",
"badges",
"and",
"return",
"the",
"result"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentBadgeExtension.php#L55-L69 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentBadgeExtension.php | FluentBadgeExtension.getBadge | public function getBadge(DataObject $record)
{
/** @var Locale $currentLocale */
$currentLocale = Locale::getCurrentLocale();
$badgeClasses = ['badge', 'fluent-badge'];
if ($currentLocale->getIsDefault()) {
// Current locale should always show a "default" or green state badge
$badgeClasses[] = 'fluent-badge--default';
$tooltip = _t(__CLASS__ . '.BadgeDefault', 'Default locale');
} elseif ($record->existsInLocale($currentLocale->Locale)) {
// If the object has been localised in the current locale, show a "localised" state
$badgeClasses[] = 'fluent-badge--localised';
$tooltip = _t(__CLASS__ . '.BadgeInvisible', 'Localised in {locale}', [
'locale' => $currentLocale->getTitle(),
]);
} else {
// Otherwise the state is that it hasn't yet been localised in the current locale, so is "invisible"
$badgeClasses[] = 'fluent-badge--invisible';
$tooltip = _t(__CLASS__ . '.BadgeLocalised', '{type} is not visible in this locale', [
'type' => $record->i18n_singular_name(),
]);
}
return DBField::create_field(
'HTMLFragment',
sprintf(
'<span class="%s" title="%s">%s</span>',
implode(' ', $badgeClasses),
$tooltip,
$record->getSourceLocale()->getBadgeLabel()
)
);
} | php | public function getBadge(DataObject $record)
{
/** @var Locale $currentLocale */
$currentLocale = Locale::getCurrentLocale();
$badgeClasses = ['badge', 'fluent-badge'];
if ($currentLocale->getIsDefault()) {
// Current locale should always show a "default" or green state badge
$badgeClasses[] = 'fluent-badge--default';
$tooltip = _t(__CLASS__ . '.BadgeDefault', 'Default locale');
} elseif ($record->existsInLocale($currentLocale->Locale)) {
// If the object has been localised in the current locale, show a "localised" state
$badgeClasses[] = 'fluent-badge--localised';
$tooltip = _t(__CLASS__ . '.BadgeInvisible', 'Localised in {locale}', [
'locale' => $currentLocale->getTitle(),
]);
} else {
// Otherwise the state is that it hasn't yet been localised in the current locale, so is "invisible"
$badgeClasses[] = 'fluent-badge--invisible';
$tooltip = _t(__CLASS__ . '.BadgeLocalised', '{type} is not visible in this locale', [
'type' => $record->i18n_singular_name(),
]);
}
return DBField::create_field(
'HTMLFragment',
sprintf(
'<span class="%s" title="%s">%s</span>',
implode(' ', $badgeClasses),
$tooltip,
$record->getSourceLocale()->getBadgeLabel()
)
);
} | [
"public",
"function",
"getBadge",
"(",
"DataObject",
"$",
"record",
")",
"{",
"/** @var Locale $currentLocale */",
"$",
"currentLocale",
"=",
"Locale",
"::",
"getCurrentLocale",
"(",
")",
";",
"$",
"badgeClasses",
"=",
"[",
"'badge'",
",",
"'fluent-badge'",
"]",
... | Given a record with Fluent enabled, return a badge that represents the state of it in the current locale
@param DataObject&FluentVersionedExtension $record
@return DBField | [
"Given",
"a",
"record",
"with",
"Fluent",
"enabled",
"return",
"a",
"badge",
"that",
"represents",
"the",
"state",
"of",
"it",
"in",
"the",
"current",
"locale"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentBadgeExtension.php#L77-L110 | train |
tractorcow-farm/silverstripe-fluent | src/State/FluentState.php | FluentState.setLocale | public function setLocale($locale)
{
if ($locale && !is_string($locale)) {
throw new InvalidArgumentException("Invalid locale");
}
$this->locale = $locale;
return $this;
} | php | public function setLocale($locale)
{
if ($locale && !is_string($locale)) {
throw new InvalidArgumentException("Invalid locale");
}
$this->locale = $locale;
return $this;
} | [
"public",
"function",
"setLocale",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"$",
"locale",
"&&",
"!",
"is_string",
"(",
"$",
"locale",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid locale\"",
")",
";",
"}",
"$",
"this",
"->",... | Set the currently active locale code
@param string $locale
@return $this | [
"Set",
"the",
"currently",
"active",
"locale",
"code"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/State/FluentState.php#L60-L67 | train |
tractorcow-farm/silverstripe-fluent | src/State/FluentState.php | FluentState.withState | public function withState(callable $callback)
{
$newState = clone $this;
try {
Injector::inst()->registerService($newState);
return $callback($newState);
} finally {
Injector::inst()->registerService($this);
}
} | php | public function withState(callable $callback)
{
$newState = clone $this;
try {
Injector::inst()->registerService($newState);
return $callback($newState);
} finally {
Injector::inst()->registerService($this);
}
} | [
"public",
"function",
"withState",
"(",
"callable",
"$",
"callback",
")",
"{",
"$",
"newState",
"=",
"clone",
"$",
"this",
";",
"try",
"{",
"Injector",
"::",
"inst",
"(",
")",
"->",
"registerService",
"(",
"$",
"newState",
")",
";",
"return",
"$",
"cal... | Perform the given operation in an isolated state.
On return, the state will be restored, so any modifications are temporary.
@param callable $callback Callback to run. Will be passed the nested state as a parameter
@return mixed Result of callback | [
"Perform",
"the",
"given",
"operation",
"in",
"an",
"isolated",
"state",
".",
"On",
"return",
"the",
"state",
"will",
"be",
"restored",
"so",
"any",
"modifications",
"are",
"temporary",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/State/FluentState.php#L145-L154 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentFilteredExtension.php | FluentFilteredExtension.updateStatusFlags | public function updateStatusFlags(&$flags)
{
// If there is no current FluentState, then we shouldn't update.
if (!FluentState::singleton()->getLocale()) {
return;
}
// No need to update flags if the Page is available in this Locale.
if ($this->isAvailableInLocale()) {
return;
}
// Add new status flag for "not visible".
$flags['fluentfiltered'] = [
'text' => null,
'title' => _t(__CLASS__ . '.LOCALEFILTEREDHELP', 'This page is not visible in this locale')
];
} | php | public function updateStatusFlags(&$flags)
{
// If there is no current FluentState, then we shouldn't update.
if (!FluentState::singleton()->getLocale()) {
return;
}
// No need to update flags if the Page is available in this Locale.
if ($this->isAvailableInLocale()) {
return;
}
// Add new status flag for "not visible".
$flags['fluentfiltered'] = [
'text' => null,
'title' => _t(__CLASS__ . '.LOCALEFILTEREDHELP', 'This page is not visible in this locale')
];
} | [
"public",
"function",
"updateStatusFlags",
"(",
"&",
"$",
"flags",
")",
"{",
"// If there is no current FluentState, then we shouldn't update.",
"if",
"(",
"!",
"FluentState",
"::",
"singleton",
"(",
")",
"->",
"getLocale",
"(",
")",
")",
"{",
"return",
";",
"}",
... | This method is only called if the Extension has been applied to SiteTree. If you are using this Extension on
other DataObjects you will need to implement your own Extension or method on that DataObject for flagging the
"filtered" state.
@param array $flags | [
"This",
"method",
"is",
"only",
"called",
"if",
"the",
"Extension",
"has",
"been",
"applied",
"to",
"SiteTree",
".",
"If",
"you",
"are",
"using",
"this",
"Extension",
"on",
"other",
"DataObjects",
"you",
"will",
"need",
"to",
"implement",
"your",
"own",
"E... | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentFilteredExtension.php#L67-L84 | train |
tractorcow-farm/silverstripe-fluent | src/Extension/FluentFilteredExtension.php | FluentFilteredExtension.getModeIsStage | protected function getModeIsStage()
{
$readingMode = Versioned::get_reading_mode();
$draft = Versioned::DRAFT;
if (strlen($readingMode) === 0) {
$readingMode = Versioned::DEFAULT_MODE;
}
return substr_compare($readingMode, $draft, strlen($readingMode) - strlen($draft), strlen($draft)) === 0;
} | php | protected function getModeIsStage()
{
$readingMode = Versioned::get_reading_mode();
$draft = Versioned::DRAFT;
if (strlen($readingMode) === 0) {
$readingMode = Versioned::DEFAULT_MODE;
}
return substr_compare($readingMode, $draft, strlen($readingMode) - strlen($draft), strlen($draft)) === 0;
} | [
"protected",
"function",
"getModeIsStage",
"(",
")",
"{",
"$",
"readingMode",
"=",
"Versioned",
"::",
"get_reading_mode",
"(",
")",
";",
"$",
"draft",
"=",
"Versioned",
"::",
"DRAFT",
";",
"if",
"(",
"strlen",
"(",
"$",
"readingMode",
")",
"===",
"0",
")... | There are two different DRAFT modes. One when browsing stage, and one when browsing archive. Both modes have
"Stage" at the very end of their reading_mode name.
@return bool | [
"There",
"are",
"two",
"different",
"DRAFT",
"modes",
".",
"One",
"when",
"browsing",
"stage",
"and",
"one",
"when",
"browsing",
"archive",
".",
"Both",
"modes",
"have",
"Stage",
"at",
"the",
"very",
"end",
"of",
"their",
"reading_mode",
"name",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Extension/FluentFilteredExtension.php#L164-L174 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Locale.php | Locale.getByLocale | public static function getByLocale($locale)
{
if (!$locale) {
return null;
}
if ($locale instanceof Locale) {
return $locale;
}
if (!static::$locales_by_title) {
static::$locales_by_title = [];
foreach (Locale::getCached() as $localeObj) {
static::$locales_by_title[$localeObj->Locale] = $localeObj;
}
}
// Get filtered locale
return isset(static::$locales_by_title[$locale]) ? static::$locales_by_title[$locale] : null;
} | php | public static function getByLocale($locale)
{
if (!$locale) {
return null;
}
if ($locale instanceof Locale) {
return $locale;
}
if (!static::$locales_by_title) {
static::$locales_by_title = [];
foreach (Locale::getCached() as $localeObj) {
static::$locales_by_title[$localeObj->Locale] = $localeObj;
}
}
// Get filtered locale
return isset(static::$locales_by_title[$locale]) ? static::$locales_by_title[$locale] : null;
} | [
"public",
"static",
"function",
"getByLocale",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"!",
"$",
"locale",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"locale",
"instanceof",
"Locale",
")",
"{",
"return",
"$",
"locale",
";",
"}",
"if",
"... | Get object by locale code.
@param string|Locale $locale
@return Locale | [
"Get",
"object",
"by",
"locale",
"code",
"."
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Locale.php#L324-L343 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Locale.php | Locale.isLocale | public function isLocale($locale)
{
return stripos(i18n::convert_rfc1766($locale), i18n::convert_rfc1766($this->Locale)) === 0;
} | php | public function isLocale($locale)
{
return stripos(i18n::convert_rfc1766($locale), i18n::convert_rfc1766($this->Locale)) === 0;
} | [
"public",
"function",
"isLocale",
"(",
"$",
"locale",
")",
"{",
"return",
"stripos",
"(",
"i18n",
"::",
"convert_rfc1766",
"(",
"$",
"locale",
")",
",",
"i18n",
"::",
"convert_rfc1766",
"(",
"$",
"this",
"->",
"Locale",
")",
")",
"===",
"0",
";",
"}"
] | Returns whether the given locale matches the current Locale object
@param string $locale E.g. en_NZ, en-NZ, en-nz-1990
@return bool | [
"Returns",
"whether",
"the",
"given",
"locale",
"matches",
"the",
"current",
"Locale",
"object"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Locale.php#L351-L354 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Locale.php | Locale.getDomain | public function getDomain()
{
if (FluentState::singleton()->getIsDomainMode() && $this->DomainID) {
return Domain::getCached()->byID($this->DomainID);
}
return null;
} | php | public function getDomain()
{
if (FluentState::singleton()->getIsDomainMode() && $this->DomainID) {
return Domain::getCached()->byID($this->DomainID);
}
return null;
} | [
"public",
"function",
"getDomain",
"(",
")",
"{",
"if",
"(",
"FluentState",
"::",
"singleton",
"(",
")",
"->",
"getIsDomainMode",
"(",
")",
"&&",
"$",
"this",
"->",
"DomainID",
")",
"{",
"return",
"Domain",
"::",
"getCached",
"(",
")",
"->",
"byID",
"(... | Get domain if in domain mode
@return Domain|null Domain found, or null if not in domain mode (or no domain) | [
"Get",
"domain",
"if",
"in",
"domain",
"mode"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Locale.php#L376-L382 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Locale.php | Locale.getLocales | public static function getLocales($domain = null)
{
// Optionally filter by domain
$domainObj = Domain::getByDomain($domain);
if ($domainObj) {
return $domainObj->getLocales();
}
return Locale::getCached();
} | php | public static function getLocales($domain = null)
{
// Optionally filter by domain
$domainObj = Domain::getByDomain($domain);
if ($domainObj) {
return $domainObj->getLocales();
}
return Locale::getCached();
} | [
"public",
"static",
"function",
"getLocales",
"(",
"$",
"domain",
"=",
"null",
")",
"{",
"// Optionally filter by domain",
"$",
"domainObj",
"=",
"Domain",
"::",
"getByDomain",
"(",
"$",
"domain",
")",
";",
"if",
"(",
"$",
"domainObj",
")",
"{",
"return",
... | Get available locales
@param string|null|true $domain If provided, locales for the given domain will be returned.
If true, then the current state domain will be used (if in domain mode).
@return ArrayList | [
"Get",
"available",
"locales"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Locale.php#L404-L413 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Locale.php | Locale.getChain | public function getChain()
{
if ($this->chain) {
return $this->chain;
}
// Build list
$this->chain = ArrayList::create();
$this->chain->push($this);
$this->chain->merge($this->Fallbacks());
return $this->chain;
} | php | public function getChain()
{
if ($this->chain) {
return $this->chain;
}
// Build list
$this->chain = ArrayList::create();
$this->chain->push($this);
$this->chain->merge($this->Fallbacks());
return $this->chain;
} | [
"public",
"function",
"getChain",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"chain",
")",
"{",
"return",
"$",
"this",
"->",
"chain",
";",
"}",
"// Build list",
"$",
"this",
"->",
"chain",
"=",
"ArrayList",
"::",
"create",
"(",
")",
";",
"$",
"th... | Get chain of all locales that should be preferred when this locale is current
@return ArrayList | [
"Get",
"chain",
"of",
"all",
"locales",
"that",
"should",
"be",
"preferred",
"when",
"this",
"locale",
"is",
"current"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Locale.php#L434-L446 | train |
tractorcow-farm/silverstripe-fluent | src/Model/Locale.php | Locale.getBaseURL | public function getBaseURL()
{
$base = Director::baseURL();
// Prepend hostname for domain mode
$domain = $this->getDomain();
if ($domain) {
$base = Controller::join_links($domain->Link(), $base);
}
// Determine if base suffix should be appended
$append = true;
if ($this->getIsDefault()) {
// Apply config
$append = !(bool) Config::inst()->get(FluentDirectorExtension::class, 'disable_default_prefix');
}
if ($append) {
// Append locale url segment
$base = Controller::join_links($base, $this->getURLSegment(), '/');
}
return $base;
} | php | public function getBaseURL()
{
$base = Director::baseURL();
// Prepend hostname for domain mode
$domain = $this->getDomain();
if ($domain) {
$base = Controller::join_links($domain->Link(), $base);
}
// Determine if base suffix should be appended
$append = true;
if ($this->getIsDefault()) {
// Apply config
$append = !(bool) Config::inst()->get(FluentDirectorExtension::class, 'disable_default_prefix');
}
if ($append) {
// Append locale url segment
$base = Controller::join_links($base, $this->getURLSegment(), '/');
}
return $base;
} | [
"public",
"function",
"getBaseURL",
"(",
")",
"{",
"$",
"base",
"=",
"Director",
"::",
"baseURL",
"(",
")",
";",
"// Prepend hostname for domain mode",
"$",
"domain",
"=",
"$",
"this",
"->",
"getDomain",
"(",
")",
";",
"if",
"(",
"$",
"domain",
")",
"{",... | Determine the base URL within the current locale
@return string | [
"Determine",
"the",
"base",
"URL",
"within",
"the",
"current",
"locale"
] | 4a20df64c1aa2b17b0f330bfe4a642958ea66751 | https://github.com/tractorcow-farm/silverstripe-fluent/blob/4a20df64c1aa2b17b0f330bfe4a642958ea66751/src/Model/Locale.php#L471-L494 | train |
Tustin/psn-php | src/Http/ResponseParser.php | ResponseParser.parse | public static function parse(Response $response)
{
$contents = $response->getBody()->getContents();
$data = json_decode($contents);
return (json_last_error() === JSON_ERROR_NONE) ? $data : (empty($contents) ? $response : $contents);
} | php | public static function parse(Response $response)
{
$contents = $response->getBody()->getContents();
$data = json_decode($contents);
return (json_last_error() === JSON_ERROR_NONE) ? $data : (empty($contents) ? $response : $contents);
} | [
"public",
"static",
"function",
"parse",
"(",
"Response",
"$",
"response",
")",
"{",
"$",
"contents",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
";",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"contents",
")",
";",
... | Parses a GuzzleHttp Response.
Will return one of three types of values:
1. JSON - will attempt to parse the response as JSON first.
2. String - if JSON was invalid and there is a response body, it will just return it as a string.
3. Response - if the JSON failed and the response body was empty, the entire Response object will be returned.
@param Response $response
@return | [
"Parses",
"a",
"GuzzleHttp",
"Response",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Http/ResponseParser.php#L20-L27 | train |
Tustin/psn-php | src/Api/Trophy.php | Trophy.earned | public function earned() : bool
{
return $this->comparing() ?
$this->trophy->comparedUser->earned :
$this->trophy->fromUser->earned;
} | php | public function earned() : bool
{
return $this->comparing() ?
$this->trophy->comparedUser->earned :
$this->trophy->fromUser->earned;
} | [
"public",
"function",
"earned",
"(",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"comparing",
"(",
")",
"?",
"$",
"this",
"->",
"trophy",
"->",
"comparedUser",
"->",
"earned",
":",
"$",
"this",
"->",
"trophy",
"->",
"fromUser",
"->",
"earned",
... | Checks if User has earned the Trophy.
@return boolean | [
"Checks",
"if",
"User",
"has",
"earned",
"the",
"Trophy",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Trophy.php#L98-L103 | train |
Tustin/psn-php | src/Api/Trophy.php | Trophy.earnedDate | public function earnedDate() : ?\DateTime
{
if (!$this->earned()) return null;
return new \DateTime(
$this->comparing() ?
$this->trophy->comparedUser->earnedDate :
$this->trophy->fromUser->earnedDate
);
} | php | public function earnedDate() : ?\DateTime
{
if (!$this->earned()) return null;
return new \DateTime(
$this->comparing() ?
$this->trophy->comparedUser->earnedDate :
$this->trophy->fromUser->earnedDate
);
} | [
"public",
"function",
"earnedDate",
"(",
")",
":",
"?",
"\\",
"DateTime",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"earned",
"(",
")",
")",
"return",
"null",
";",
"return",
"new",
"\\",
"DateTime",
"(",
"$",
"this",
"->",
"comparing",
"(",
")",
"?",... | Gets when the User earned the Trophy.
@return \DateTime|null | [
"Gets",
"when",
"the",
"User",
"earned",
"the",
"Trophy",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Trophy.php#L110-L119 | train |
Tustin/psn-php | src/Api/Trophy.php | Trophy.calculateTrophies | public static function calculateTrophies(object $trophyTypes) : int
{
return ($trophyTypes->bronze + $trophyTypes->silver + $trophyTypes->gold + $trophyTypes->platinum);
} | php | public static function calculateTrophies(object $trophyTypes) : int
{
return ($trophyTypes->bronze + $trophyTypes->silver + $trophyTypes->gold + $trophyTypes->platinum);
} | [
"public",
"static",
"function",
"calculateTrophies",
"(",
"object",
"$",
"trophyTypes",
")",
":",
"int",
"{",
"return",
"(",
"$",
"trophyTypes",
"->",
"bronze",
"+",
"$",
"trophyTypes",
"->",
"silver",
"+",
"$",
"trophyTypes",
"->",
"gold",
"+",
"$",
"trop... | Calculate all the types of Trophies.
@param object $trophyTypes Trophy type information.
@return integer | [
"Calculate",
"all",
"the",
"types",
"of",
"Trophies",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Trophy.php#L157-L160 | train |
Tustin/psn-php | src/Api/Community.php | Community.setImage | public function setImage(string $imageData) : void
{
$url = $this->uploadImage('communityProfileImage', $imageData);
$this->set([
'profileImage' => [
'sourceUrl' => $url
]
]);
} | php | public function setImage(string $imageData) : void
{
$url = $this->uploadImage('communityProfileImage', $imageData);
$this->set([
'profileImage' => [
'sourceUrl' => $url
]
]);
} | [
"public",
"function",
"setImage",
"(",
"string",
"$",
"imageData",
")",
":",
"void",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"uploadImage",
"(",
"'communityProfileImage'",
",",
"$",
"imageData",
")",
";",
"$",
"this",
"->",
"set",
"(",
"[",
"'profileIma... | Sets the image for the Community.
@param string $imageData Raw bytes of the image.
@return void | [
"Sets",
"the",
"image",
"for",
"the",
"Community",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L80-L89 | train |
Tustin/psn-php | src/Api/Community.php | Community.setBackgroundImage | public function setBackgroundImage(string $imageData) : void
{
$url = $this->uploadImage('communityBackgroundImage', $imageData);
$this->set([
'backgroundImage' => [
'sourceUrl' => $url
]
]);
} | php | public function setBackgroundImage(string $imageData) : void
{
$url = $this->uploadImage('communityBackgroundImage', $imageData);
$this->set([
'backgroundImage' => [
'sourceUrl' => $url
]
]);
} | [
"public",
"function",
"setBackgroundImage",
"(",
"string",
"$",
"imageData",
")",
":",
"void",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"uploadImage",
"(",
"'communityBackgroundImage'",
",",
"$",
"imageData",
")",
";",
"$",
"this",
"->",
"set",
"(",
"[",
... | Sets the background image for the Community.
@param string $imageData Raw bytes of the image.
@return void | [
"Sets",
"the",
"background",
"image",
"for",
"the",
"Community",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L97-L106 | train |
Tustin/psn-php | src/Api/Community.php | Community.setBackgroundColor | public function setBackgroundColor(int $color) : void
{
$background = $this->info(true)->backgroundImage;
$this->set([
'backgroundImage' => [
'color' => sprintf('%06X', $color),
'sourceUrl' => $background->sourceUrl ?? ''
]
]);
} | php | public function setBackgroundColor(int $color) : void
{
$background = $this->info(true)->backgroundImage;
$this->set([
'backgroundImage' => [
'color' => sprintf('%06X', $color),
'sourceUrl' => $background->sourceUrl ?? ''
]
]);
} | [
"public",
"function",
"setBackgroundColor",
"(",
"int",
"$",
"color",
")",
":",
"void",
"{",
"$",
"background",
"=",
"$",
"this",
"->",
"info",
"(",
"true",
")",
"->",
"backgroundImage",
";",
"$",
"this",
"->",
"set",
"(",
"[",
"'backgroundImage'",
"=>",... | Sets the background color for the Community.
@param integer $color RGB value (e.g. 0x000000).
@return void | [
"Sets",
"the",
"background",
"color",
"for",
"the",
"Community",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L114-L124 | train |
Tustin/psn-php | src/Api/Community.php | Community.invite | public function invite(array $users) : void
{
$data = (object)[
'onlineIds' => $users
];
$this->postJson(sprintf(self::COMMUNITY_ENDPOINT . 'communities/%s/members', $this->id()), $data);
} | php | public function invite(array $users) : void
{
$data = (object)[
'onlineIds' => $users
];
$this->postJson(sprintf(self::COMMUNITY_ENDPOINT . 'communities/%s/members', $this->id()), $data);
} | [
"public",
"function",
"invite",
"(",
"array",
"$",
"users",
")",
":",
"void",
"{",
"$",
"data",
"=",
"(",
"object",
")",
"[",
"'onlineIds'",
"=>",
"$",
"users",
"]",
";",
"$",
"this",
"->",
"postJson",
"(",
"sprintf",
"(",
"self",
"::",
"COMMUNITY_EN... | Invite one or more Users to the Community.
@param array $users Array of each User's onlineId as string.
@return void | [
"Invite",
"one",
"or",
"more",
"Users",
"to",
"the",
"Community",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L145-L152 | train |
Tustin/psn-php | src/Api/Community.php | Community.members | public function members(int $limit = 100) : array
{
$returnMembers = [];
$members = $this->get(sprintf(self::COMMUNITY_ENDPOINT . 'communities/%s/members', $this->id()), [
'limit' => $limit
]);
if ($members->size === 0) return $returnMembers;
foreach ($members->members as $member) {
$returnMembers[] = new User($this->client, $member->onlineId);
}
return $returnMembers;
} | php | public function members(int $limit = 100) : array
{
$returnMembers = [];
$members = $this->get(sprintf(self::COMMUNITY_ENDPOINT . 'communities/%s/members', $this->id()), [
'limit' => $limit
]);
if ($members->size === 0) return $returnMembers;
foreach ($members->members as $member) {
$returnMembers[] = new User($this->client, $member->onlineId);
}
return $returnMembers;
} | [
"public",
"function",
"members",
"(",
"int",
"$",
"limit",
"=",
"100",
")",
":",
"array",
"{",
"$",
"returnMembers",
"=",
"[",
"]",
";",
"$",
"members",
"=",
"$",
"this",
"->",
"get",
"(",
"sprintf",
"(",
"self",
"::",
"COMMUNITY_ENDPOINT",
".",
"'co... | Get the Users in the Community.
@param integer $limit Amount of Users to return.
@return array Array of Api\User. | [
"Get",
"the",
"Users",
"in",
"the",
"Community",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L160-L175 | train |
Tustin/psn-php | src/Api/Community.php | Community.game | public function game() : ?Game
{
if (!isset($this->info()->titleId)) return null;
return new Game($this->client, $this->info()->titleId);
} | php | public function game() : ?Game
{
if (!isset($this->info()->titleId)) return null;
return new Game($this->client, $this->info()->titleId);
} | [
"public",
"function",
"game",
"(",
")",
":",
"?",
"Game",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"info",
"(",
")",
"->",
"titleId",
")",
")",
"return",
"null",
";",
"return",
"new",
"Game",
"(",
"$",
"this",
"->",
"client",
",",
... | Gets the Game the Community is associated with.
@return Game|null | [
"Gets",
"the",
"Game",
"the",
"Community",
"is",
"associated",
"with",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L191-L196 | train |
Tustin/psn-php | src/Api/Community.php | Community.uploadImage | private function uploadImage(string $purpose, string $imageData) : string
{
$parameters = [
[
'name' => 'purpose',
'contents' => $purpose,
],
[
'name' => 'file',
'filename' => 'dummy_file_name',
'contents' => $imageData,
'headers' => [
'Content-Type' => 'image/jpeg'
]
],
[
'name' => 'mimeType',
'contents' => 'image/jpeg',
]
];
$response = $this->postMultiPart(sprintf(self::SATCHEL_ENDPOINT, $this->id()), $parameters);
return $response->url;
} | php | private function uploadImage(string $purpose, string $imageData) : string
{
$parameters = [
[
'name' => 'purpose',
'contents' => $purpose,
],
[
'name' => 'file',
'filename' => 'dummy_file_name',
'contents' => $imageData,
'headers' => [
'Content-Type' => 'image/jpeg'
]
],
[
'name' => 'mimeType',
'contents' => 'image/jpeg',
]
];
$response = $this->postMultiPart(sprintf(self::SATCHEL_ENDPOINT, $this->id()), $parameters);
return $response->url;
} | [
"private",
"function",
"uploadImage",
"(",
"string",
"$",
"purpose",
",",
"string",
"$",
"imageData",
")",
":",
"string",
"{",
"$",
"parameters",
"=",
"[",
"[",
"'name'",
"=>",
"'purpose'",
",",
"'contents'",
"=>",
"$",
"purpose",
",",
"]",
",",
"[",
"... | Uploads an image to Sony's CDN and returns the URL.
Sony requires all images (profile images, community images, etc) to be set with this CDN URL.
@param string $purpose
@return string | [
"Uploads",
"an",
"image",
"to",
"Sony",
"s",
"CDN",
"and",
"returns",
"the",
"URL",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L206-L230 | train |
Tustin/psn-php | src/Api/Community.php | Community.set | private function set(array $postData)
{
return $this->putJson(sprintf(self::COMMUNITY_ENDPOINT . 'communities/%s', $this->id()), $postData);
} | php | private function set(array $postData)
{
return $this->putJson(sprintf(self::COMMUNITY_ENDPOINT . 'communities/%s', $this->id()), $postData);
} | [
"private",
"function",
"set",
"(",
"array",
"$",
"postData",
")",
"{",
"return",
"$",
"this",
"->",
"putJson",
"(",
"sprintf",
"(",
"self",
"::",
"COMMUNITY_ENDPOINT",
".",
"'communities/%s'",
",",
"$",
"this",
"->",
"id",
"(",
")",
")",
",",
"$",
"pos... | Sets a property on the Community.
@param array $postData
@return object | [
"Sets",
"a",
"property",
"on",
"the",
"Community",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Community.php#L238-L241 | train |
Tustin/psn-php | src/Api/Story.php | Story.caption | public function caption() : string
{
$template = $this->info()->captionTemplate;
foreach ($this->info()->captionComponents as $variable) {
$template = str_replace('$' . $variable->key, $variable->value, $template);
}
return $template;
} | php | public function caption() : string
{
$template = $this->info()->captionTemplate;
foreach ($this->info()->captionComponents as $variable) {
$template = str_replace('$' . $variable->key, $variable->value, $template);
}
return $template;
} | [
"public",
"function",
"caption",
"(",
")",
":",
"string",
"{",
"$",
"template",
"=",
"$",
"this",
"->",
"info",
"(",
")",
"->",
"captionTemplate",
";",
"foreach",
"(",
"$",
"this",
"->",
"info",
"(",
")",
"->",
"captionComponents",
"as",
"$",
"variable... | Generates the caption shown on PlayStation.
@return string | [
"Generates",
"the",
"caption",
"shown",
"on",
"PlayStation",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Story.php#L118-L127 | train |
Tustin/psn-php | src/Api/Story.php | Story.comment | public function comment(string $message) : ?Comment
{
$comment = $this->postJson(sprintf(self::ACTIVITY_ENDPOINT . 'v1/users/me/comment/%s', $this->storyId()), [
'commentString' => $message
]);
// Since I couldn't find an endpoint that gave me a comment's info using just it's comment id, let's just grab the newest comment.
$newest = $this->comments(0, 1, 'ASC');
if (count($newest) === 0) return null;
return $newest[0];
} | php | public function comment(string $message) : ?Comment
{
$comment = $this->postJson(sprintf(self::ACTIVITY_ENDPOINT . 'v1/users/me/comment/%s', $this->storyId()), [
'commentString' => $message
]);
// Since I couldn't find an endpoint that gave me a comment's info using just it's comment id, let's just grab the newest comment.
$newest = $this->comments(0, 1, 'ASC');
if (count($newest) === 0) return null;
return $newest[0];
} | [
"public",
"function",
"comment",
"(",
"string",
"$",
"message",
")",
":",
"?",
"Comment",
"{",
"$",
"comment",
"=",
"$",
"this",
"->",
"postJson",
"(",
"sprintf",
"(",
"self",
"::",
"ACTIVITY_ENDPOINT",
".",
"'v1/users/me/comment/%s'",
",",
"$",
"this",
"-... | Leave a comment on the Story.
@param string $message The comment.
@return Comment|null | [
"Leave",
"a",
"comment",
"on",
"the",
"Story",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Story.php#L145-L157 | train |
Tustin/psn-php | src/Api/Story.php | Story.comments | public function comments(int $start = 0, int $count = 10, string $sort = 'ASC') : array
{
$returnComments = [];
if ($this->commentCount() === 0) return $returnComments;
$comments = $this->get(sprintf(self::ACTIVITY_ENDPOINT . 'v1/users/%s/stories/%s/comments', $this->user()->onlineIdParameter(), $this->storyId()), [
'start' => $start,
'count' => $count,
'sort' => $sort
]);
foreach ($comments->userComments as $comment) {
$returnComments[] = new Comment($this->client, $comment, $this);
}
return $returnComments;
} | php | public function comments(int $start = 0, int $count = 10, string $sort = 'ASC') : array
{
$returnComments = [];
if ($this->commentCount() === 0) return $returnComments;
$comments = $this->get(sprintf(self::ACTIVITY_ENDPOINT . 'v1/users/%s/stories/%s/comments', $this->user()->onlineIdParameter(), $this->storyId()), [
'start' => $start,
'count' => $count,
'sort' => $sort
]);
foreach ($comments->userComments as $comment) {
$returnComments[] = new Comment($this->client, $comment, $this);
}
return $returnComments;
} | [
"public",
"function",
"comments",
"(",
"int",
"$",
"start",
"=",
"0",
",",
"int",
"$",
"count",
"=",
"10",
",",
"string",
"$",
"sort",
"=",
"'ASC'",
")",
":",
"array",
"{",
"$",
"returnComments",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
... | Gets all the Comments for the Story.
@param integer $start Which comments to start from.
@param integer $count How many comments to get.
@param string $sort How comments are sorted (ASC/DESC).
@return array Array of API\Comment. | [
"Gets",
"all",
"the",
"Comments",
"for",
"the",
"Story",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Story.php#L167-L184 | train |
Tustin/psn-php | src/Api/TrophyGroup.php | TrophyGroup.progress | public function progress() : int
{
return $this->comparing() ?
$this->group->comparedUser->progress :
$this->group->fromUser->progress;
} | php | public function progress() : int
{
return $this->comparing() ?
$this->group->comparedUser->progress :
$this->group->fromUser->progress;
} | [
"public",
"function",
"progress",
"(",
")",
":",
"int",
"{",
"return",
"$",
"this",
"->",
"comparing",
"(",
")",
"?",
"$",
"this",
"->",
"group",
"->",
"comparedUser",
"->",
"progress",
":",
"$",
"this",
"->",
"group",
"->",
"fromUser",
"->",
"progress... | Get completion progress of TrophyGroup.
@return integer | [
"Get",
"completion",
"progress",
"of",
"TrophyGroup",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/TrophyGroup.php#L76-L81 | train |
Tustin/psn-php | src/Api/TrophyGroup.php | TrophyGroup.lastEarnedDate | public function lastEarnedDate() : \DateTime
{
return new \DateTime(
$this->comparing() ?
$this->group->comparedUser->lastUpdateDate :
$this->group->fromUser->lastUpdateDate
);
} | php | public function lastEarnedDate() : \DateTime
{
return new \DateTime(
$this->comparing() ?
$this->group->comparedUser->lastUpdateDate :
$this->group->fromUser->lastUpdateDate
);
} | [
"public",
"function",
"lastEarnedDate",
"(",
")",
":",
"\\",
"DateTime",
"{",
"return",
"new",
"\\",
"DateTime",
"(",
"$",
"this",
"->",
"comparing",
"(",
")",
"?",
"$",
"this",
"->",
"group",
"->",
"comparedUser",
"->",
"lastUpdateDate",
":",
"$",
"this... | Get Trophy earn date.
@return \DateTime | [
"Get",
"Trophy",
"earn",
"date",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/TrophyGroup.php#L88-L95 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.info | public function info(int $count = 1, bool $force = false) : object
{
if ($this->messageThread === null || $force) {
$this->messageThread = $this->get(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'threads/%s', $this->messageThreadId), [
'fields' => 'threadMembers,threadNameDetail,threadThumbnailDetail,threadProperty,latestTakedownEventDetail,newArrivalEventDetail,threadEvents',
'count' => $count,
]);
}
return $this->messageThread;
} | php | public function info(int $count = 1, bool $force = false) : object
{
if ($this->messageThread === null || $force) {
$this->messageThread = $this->get(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'threads/%s', $this->messageThreadId), [
'fields' => 'threadMembers,threadNameDetail,threadThumbnailDetail,threadProperty,latestTakedownEventDetail,newArrivalEventDetail,threadEvents',
'count' => $count,
]);
}
return $this->messageThread;
} | [
"public",
"function",
"info",
"(",
"int",
"$",
"count",
"=",
"1",
",",
"bool",
"$",
"force",
"=",
"false",
")",
":",
"object",
"{",
"if",
"(",
"$",
"this",
"->",
"messageThread",
"===",
"null",
"||",
"$",
"force",
")",
"{",
"$",
"this",
"->",
"me... | Get the MessageThread info.
@param integer $count Amount of messages to return.
@param boolean $force Force an update.
@return object | [
"Get",
"the",
"MessageThread",
"info",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L37-L47 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.thumbnailUrl | public function thumbnailUrl() : string
{
return ($this->info()->threadThumbnailDetail->status == 2) ?
"" :
$this->info()->threadThumbnailDetail->resourcePath;
} | php | public function thumbnailUrl() : string
{
return ($this->info()->threadThumbnailDetail->status == 2) ?
"" :
$this->info()->threadThumbnailDetail->resourcePath;
} | [
"public",
"function",
"thumbnailUrl",
"(",
")",
":",
"string",
"{",
"return",
"(",
"$",
"this",
"->",
"info",
"(",
")",
"->",
"threadThumbnailDetail",
"->",
"status",
"==",
"2",
")",
"?",
"\"\"",
":",
"$",
"this",
"->",
"info",
"(",
")",
"->",
"threa... | Gets the MessageThread thumbnail URL.
@return string | [
"Gets",
"the",
"MessageThread",
"thumbnail",
"URL",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L84-L89 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.members | public function members() : array
{
$members = [];
if (!isset($this->info()->threadMembers) || $this->info()->threadMembers <= 0) return null;
foreach ($this->info()->threadMembers as $member) {
$members[] = new User($this->client, $member->onlineId);
}
return $members;
} | php | public function members() : array
{
$members = [];
if (!isset($this->info()->threadMembers) || $this->info()->threadMembers <= 0) return null;
foreach ($this->info()->threadMembers as $member) {
$members[] = new User($this->client, $member->onlineId);
}
return $members;
} | [
"public",
"function",
"members",
"(",
")",
":",
"array",
"{",
"$",
"members",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"info",
"(",
")",
"->",
"threadMembers",
")",
"||",
"$",
"this",
"->",
"info",
"(",
")",
"->",
"t... | Get members in the MessageThread.
@return array Array of Api\User. | [
"Get",
"members",
"in",
"the",
"MessageThread",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L116-L127 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.setName | public function setName(string $name) : void
{
$data = (object)[
'threadNameDetail' => (object)[
'threadName' => $name
]
];
$this->putJson(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'threads/%s/name', $this->messageThreadId), $data);
} | php | public function setName(string $name) : void
{
$data = (object)[
'threadNameDetail' => (object)[
'threadName' => $name
]
];
$this->putJson(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'threads/%s/name', $this->messageThreadId), $data);
} | [
"public",
"function",
"setName",
"(",
"string",
"$",
"name",
")",
":",
"void",
"{",
"$",
"data",
"=",
"(",
"object",
")",
"[",
"'threadNameDetail'",
"=>",
"(",
"object",
")",
"[",
"'threadName'",
"=>",
"$",
"name",
"]",
"]",
";",
"$",
"this",
"->",
... | Set the name of the MessageThread.
@param string $name Name of the MessageThread.
@return void | [
"Set",
"the",
"name",
"of",
"the",
"MessageThread",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L136-L145 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.favorite | public function favorite() : void
{
$data = (object)[
'favoriteDetail' => (object)[
'favoriteFlag' => true
]
];
$this->putJson(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'users/me/threads/%s/favorites', $this->messageThreadId), $data);
} | php | public function favorite() : void
{
$data = (object)[
'favoriteDetail' => (object)[
'favoriteFlag' => true
]
];
$this->putJson(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'users/me/threads/%s/favorites', $this->messageThreadId), $data);
} | [
"public",
"function",
"favorite",
"(",
")",
":",
"void",
"{",
"$",
"data",
"=",
"(",
"object",
")",
"[",
"'favoriteDetail'",
"=>",
"(",
"object",
")",
"[",
"'favoriteFlag'",
"=>",
"true",
"]",
"]",
";",
"$",
"this",
"->",
"putJson",
"(",
"sprintf",
"... | Favorite the MessageThread.
@return void | [
"Favorite",
"the",
"MessageThread",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L152-L161 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.unfavorite | public function unfavorite() : void
{
$data = (object)[
'favoriteDetail' => (object)[
'favoriteFlag' => false
]
];
$this->putJson(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'users/me/threads/%s/favorites', $this->messageThreadId), $data);
} | php | public function unfavorite() : void
{
$data = (object)[
'favoriteDetail' => (object)[
'favoriteFlag' => false
]
];
$this->putJson(sprintf(self::MESSAGE_THREAD_ENDPOINT . 'users/me/threads/%s/favorites', $this->messageThreadId), $data);
} | [
"public",
"function",
"unfavorite",
"(",
")",
":",
"void",
"{",
"$",
"data",
"=",
"(",
"object",
")",
"[",
"'favoriteDetail'",
"=>",
"(",
"object",
")",
"[",
"'favoriteFlag'",
"=>",
"false",
"]",
"]",
";",
"$",
"this",
"->",
"putJson",
"(",
"sprintf",
... | Unfavorite the MessageThread.
@return void | [
"Unfavorite",
"the",
"MessageThread",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L168-L177 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.sendAudio | public function sendAudio(string $audioContents, int $audioLengthSeconds) : ?Message
{
$data = (object)[
'messageEventDetail' => (object)[
'eventCategoryCode' => MessageType::Audio,
'messageDetail' => (object)[
'body' => '',
'voiceDetail' => (object)[
'playbackTime' => $audioLengthSeconds
]
]
]
];
$parameters =
[
[
'name' => 'messageEventDetail',
'contents' => json_encode($data, JSON_PRETTY_PRINT),
'headers' => [
'Content-Type' => 'application/json; charset=utf-8'
]
],
[
'name' => 'voiceData',
'contents' => $audioContents,
'headers' => [
'Content-Type' => 'audio/3gpp',
'Content-Transfer-Encoding' => 'binary',
]
]
];
$response = $this->postMultiPart(sprintf(MessageThread::MESSAGE_THREAD_ENDPOINT . 'threads/%s/messages', $this->messageThreadId), $parameters);
$messageFields = $this->info(1, true);
if (!isset($messageFields->threadEvents)) return null;
$messageData = $messageFields->threadEvents[0];
return new Message($this->client, $messageData->messageEventDetail, $this);
} | php | public function sendAudio(string $audioContents, int $audioLengthSeconds) : ?Message
{
$data = (object)[
'messageEventDetail' => (object)[
'eventCategoryCode' => MessageType::Audio,
'messageDetail' => (object)[
'body' => '',
'voiceDetail' => (object)[
'playbackTime' => $audioLengthSeconds
]
]
]
];
$parameters =
[
[
'name' => 'messageEventDetail',
'contents' => json_encode($data, JSON_PRETTY_PRINT),
'headers' => [
'Content-Type' => 'application/json; charset=utf-8'
]
],
[
'name' => 'voiceData',
'contents' => $audioContents,
'headers' => [
'Content-Type' => 'audio/3gpp',
'Content-Transfer-Encoding' => 'binary',
]
]
];
$response = $this->postMultiPart(sprintf(MessageThread::MESSAGE_THREAD_ENDPOINT . 'threads/%s/messages', $this->messageThreadId), $parameters);
$messageFields = $this->info(1, true);
if (!isset($messageFields->threadEvents)) return null;
$messageData = $messageFields->threadEvents[0];
return new Message($this->client, $messageData->messageEventDetail, $this);
} | [
"public",
"function",
"sendAudio",
"(",
"string",
"$",
"audioContents",
",",
"int",
"$",
"audioLengthSeconds",
")",
":",
"?",
"Message",
"{",
"$",
"data",
"=",
"(",
"object",
")",
"[",
"'messageEventDetail'",
"=>",
"(",
"object",
")",
"[",
"'eventCategoryCod... | Send an audio message.
@param string $audioContents Raw bytes of the audio.
@param integer $audioLengthSeconds Length of the audio in seconds.
@return Message|null | [
"Send",
"an",
"audio",
"message",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L271-L313 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.messages | public function messages(int $count = 200) : array
{
$messages = [];
$messageFields = $this->info($count, true);
foreach ($messageFields->threadEvents as $message) {
$messages[] = new Message($this->client, $message->messageEventDetail, $this);
}
return $messages;
} | php | public function messages(int $count = 200) : array
{
$messages = [];
$messageFields = $this->info($count, true);
foreach ($messageFields->threadEvents as $message) {
$messages[] = new Message($this->client, $message->messageEventDetail, $this);
}
return $messages;
} | [
"public",
"function",
"messages",
"(",
"int",
"$",
"count",
"=",
"200",
")",
":",
"array",
"{",
"$",
"messages",
"=",
"[",
"]",
";",
"$",
"messageFields",
"=",
"$",
"this",
"->",
"info",
"(",
"$",
"count",
",",
"true",
")",
";",
"foreach",
"(",
"... | Get all the messages.
@param integer $count Amount of messages to send.
@return array Array of Api\Message. | [
"Get",
"all",
"the",
"messages",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L321-L332 | train |
Tustin/psn-php | src/Api/MessageThread.php | MessageThread.setThumbnail | public function setThumbnail(string $imageContents) : void
{
$parameters = [
[
'name' => 'threadThumbnail',
'contents' => $imageContents,
'headers' => [
'Content-Type' => 'image/jpeg',
'Content-Transfer-Encoding' => 'binary',
]
]
];
$this->putMultiPart(sprintf(MessageThread::MESSAGE_THREAD_ENDPOINT . 'threads/%s/thumbnail', $this->messageThreadId), $parameters);
} | php | public function setThumbnail(string $imageContents) : void
{
$parameters = [
[
'name' => 'threadThumbnail',
'contents' => $imageContents,
'headers' => [
'Content-Type' => 'image/jpeg',
'Content-Transfer-Encoding' => 'binary',
]
]
];
$this->putMultiPart(sprintf(MessageThread::MESSAGE_THREAD_ENDPOINT . 'threads/%s/thumbnail', $this->messageThreadId), $parameters);
} | [
"public",
"function",
"setThumbnail",
"(",
"string",
"$",
"imageContents",
")",
":",
"void",
"{",
"$",
"parameters",
"=",
"[",
"[",
"'name'",
"=>",
"'threadThumbnail'",
",",
"'contents'",
"=>",
"$",
"imageContents",
",",
"'headers'",
"=>",
"[",
"'Content-Type'... | Set the MessageThread thumbnail
@param string $imageContents Raw bytes of the image.
@return void | [
"Set",
"the",
"MessageThread",
"thumbnail"
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/MessageThread.php#L340-L354 | train |
Tustin/psn-php | src/Api/Game.php | Game.earnedPlatinum | public function earnedPlatinum() : bool
{
if (
$this->trophyInfo() === null ||
!isset($this->trophyInfo()->definedTrophies->platinum) ||
!$this->trophyInfo()->definedTrophies->platinum
) {
return false;
}
$user = $this->hasPlayed();
return ($user === false) ? false : boolval($user->earnedTrophies->platinum);
} | php | public function earnedPlatinum() : bool
{
if (
$this->trophyInfo() === null ||
!isset($this->trophyInfo()->definedTrophies->platinum) ||
!$this->trophyInfo()->definedTrophies->platinum
) {
return false;
}
$user = $this->hasPlayed();
return ($user === false) ? false : boolval($user->earnedTrophies->platinum);
} | [
"public",
"function",
"earnedPlatinum",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"trophyInfo",
"(",
")",
"===",
"null",
"||",
"!",
"isset",
"(",
"$",
"this",
"->",
"trophyInfo",
"(",
")",
"->",
"definedTrophies",
"->",
"platinum",
")",... | Checks if the User has earned the platinum trophy.
@return boolean | [
"Checks",
"if",
"the",
"User",
"has",
"earned",
"the",
"platinum",
"trophy",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Game.php#L90-L103 | train |
Tustin/psn-php | src/Api/Game.php | Game.trophyInfo | public function trophyInfo() : ?object
{
if ($this->game === null) {
// Kind of a hack here.
// This endpoint doesn't give exactly the same information as the proper Game endpoint would,
// But I wasn't able to find a way to get info from the Game endpoint with just a titleId.
// It works, but I'd rather it be more consistent with the other endpoint.
$game = $this->get(Trophy::TROPHY_ENDPOINT . 'apps/trophyTitles', [
'npTitleIds' => $this->titleId,
'fields' => '@default',
'npLanguage' => 'en'
]);
if (!count($game->apps) || !count($game->apps[0]->trophyTitles)) return null;
$this->npCommunicationId = $game->apps[0]->trophyTitles[0]->npCommunicationId;
$data = [
'npLanguage' => 'en'
];
if ($this->comparing()) {
$data['comparedUser'] = $this->user()->onlineId();
}
$game = $this->get(sprintf(Trophy::TROPHY_ENDPOINT . 'trophyTitles/%s', $this->npCommunicationId), $data);
if ($game->totalResults !== 1 || !count($game->trophyTitles)) return null;
$this->game = $game->trophyTitles[0];
}
return $this->game;
} | php | public function trophyInfo() : ?object
{
if ($this->game === null) {
// Kind of a hack here.
// This endpoint doesn't give exactly the same information as the proper Game endpoint would,
// But I wasn't able to find a way to get info from the Game endpoint with just a titleId.
// It works, but I'd rather it be more consistent with the other endpoint.
$game = $this->get(Trophy::TROPHY_ENDPOINT . 'apps/trophyTitles', [
'npTitleIds' => $this->titleId,
'fields' => '@default',
'npLanguage' => 'en'
]);
if (!count($game->apps) || !count($game->apps[0]->trophyTitles)) return null;
$this->npCommunicationId = $game->apps[0]->trophyTitles[0]->npCommunicationId;
$data = [
'npLanguage' => 'en'
];
if ($this->comparing()) {
$data['comparedUser'] = $this->user()->onlineId();
}
$game = $this->get(sprintf(Trophy::TROPHY_ENDPOINT . 'trophyTitles/%s', $this->npCommunicationId), $data);
if ($game->totalResults !== 1 || !count($game->trophyTitles)) return null;
$this->game = $game->trophyTitles[0];
}
return $this->game;
} | [
"public",
"function",
"trophyInfo",
"(",
")",
":",
"?",
"object",
"{",
"if",
"(",
"$",
"this",
"->",
"game",
"===",
"null",
")",
"{",
"// Kind of a hack here.",
"// This endpoint doesn't give exactly the same information as the proper Game endpoint would,",
"// But I wasn't... | Gets the trophy information for the Game.
@return object|null | [
"Gets",
"the",
"trophy",
"information",
"for",
"the",
"Game",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Game.php#L110-L143 | train |
Tustin/psn-php | src/Api/Game.php | Game.players | public function players() : array
{
$returnPlayers = [];
$players = $this->get(sprintf(self::GAME_ENDPOINT . 'titles/%s/players', $this->titleId));
if ($players->size === 0) return $returnPlayers;
foreach ($players->data as $player) {
$returnPlayers[] = new User($this->client, $player->onlineId);
}
return $returnPlayers;
} | php | public function players() : array
{
$returnPlayers = [];
$players = $this->get(sprintf(self::GAME_ENDPOINT . 'titles/%s/players', $this->titleId));
if ($players->size === 0) return $returnPlayers;
foreach ($players->data as $player) {
$returnPlayers[] = new User($this->client, $player->onlineId);
}
return $returnPlayers;
} | [
"public",
"function",
"players",
"(",
")",
":",
"array",
"{",
"$",
"returnPlayers",
"=",
"[",
"]",
";",
"$",
"players",
"=",
"$",
"this",
"->",
"get",
"(",
"sprintf",
"(",
"self",
"::",
"GAME_ENDPOINT",
".",
"'titles/%s/players'",
",",
"$",
"this",
"->... | Gets the Users who have played this game.
@return array Array of Api\User. | [
"Gets",
"the",
"Users",
"who",
"have",
"played",
"this",
"game",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Game.php#L151-L164 | train |
Tustin/psn-php | src/Api/Game.php | Game.trophyGroups | public function trophyGroups() : array
{
$returnGroups = [];
$data = [
'fields' => '@default,trophyTitleSmallIconUrl,trophyGroupSmallIconUrl',
'iconSize' => 'm',
'npLanguage' => 'en'
];
if ($this->comparing()) {
$data['comparedUser'] = $this->user()->onlineId();
}
$groups = $this->get(sprintf(Trophy::TROPHY_ENDPOINT . 'trophyTitles/%s/trophyGroups', $this->communicationId()), $data);
foreach ($groups->trophyGroups as $group) {
$returnGroups[] = new TrophyGroup($this->client, $group, $this);
}
return $returnGroups;
} | php | public function trophyGroups() : array
{
$returnGroups = [];
$data = [
'fields' => '@default,trophyTitleSmallIconUrl,trophyGroupSmallIconUrl',
'iconSize' => 'm',
'npLanguage' => 'en'
];
if ($this->comparing()) {
$data['comparedUser'] = $this->user()->onlineId();
}
$groups = $this->get(sprintf(Trophy::TROPHY_ENDPOINT . 'trophyTitles/%s/trophyGroups', $this->communicationId()), $data);
foreach ($groups->trophyGroups as $group) {
$returnGroups[] = new TrophyGroup($this->client, $group, $this);
}
return $returnGroups;
} | [
"public",
"function",
"trophyGroups",
"(",
")",
":",
"array",
"{",
"$",
"returnGroups",
"=",
"[",
"]",
";",
"$",
"data",
"=",
"[",
"'fields'",
"=>",
"'@default,trophyTitleSmallIconUrl,trophyGroupSmallIconUrl'",
",",
"'iconSize'",
"=>",
"'m'",
",",
"'npLanguage'",
... | Gets the TrophyGroups for this Game.
@return array Array of Api\TrophyGroup | [
"Gets",
"the",
"TrophyGroups",
"for",
"this",
"Game",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Game.php#L171-L192 | train |
Tustin/psn-php | src/Api/Game.php | Game.comparing | public function comparing() : bool
{
if ($this->user() === null) return false;
return ($this->user()->onlineId() !== null);
} | php | public function comparing() : bool
{
if ($this->user() === null) return false;
return ($this->user()->onlineId() !== null);
} | [
"public",
"function",
"comparing",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"user",
"(",
")",
"===",
"null",
")",
"return",
"false",
";",
"return",
"(",
"$",
"this",
"->",
"user",
"(",
")",
"->",
"onlineId",
"(",
")",
"!==",
"nul... | Gets whether we're getting trophies for the logged in User or another User.
@return boolean | [
"Gets",
"whether",
"we",
"re",
"getting",
"trophies",
"for",
"the",
"logged",
"in",
"User",
"or",
"another",
"User",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Game.php#L240-L245 | train |
Tustin/psn-php | src/Api/Game.php | Game.hasPlayed | public function hasPlayed() : bool
{
if ($this->comparing() && isset($this->trophyInfo()->comparedUser)) {
return $this->trophyInfo()->comparedUser;
} else if (isset($this->trophyInfo()->fromUser)) {
return $this->trophyInfo()->fromUser;
}
return false;
} | php | public function hasPlayed() : bool
{
if ($this->comparing() && isset($this->trophyInfo()->comparedUser)) {
return $this->trophyInfo()->comparedUser;
} else if (isset($this->trophyInfo()->fromUser)) {
return $this->trophyInfo()->fromUser;
}
return false;
} | [
"public",
"function",
"hasPlayed",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"comparing",
"(",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"trophyInfo",
"(",
")",
"->",
"comparedUser",
")",
")",
"{",
"return",
"$",
"this",
"->",
"tr... | Gets whether the User has played the game or not.
@return boolean | [
"Gets",
"whether",
"the",
"User",
"has",
"played",
"the",
"game",
"or",
"not",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Game.php#L252-L261 | train |
Tustin/psn-php | src/Client.php | Client.login | public function login(string $ticketUuidOrRefreshToken, string $code = null)
{
if ($code === null) {
$response = $this->httpClient()->post(self::AUTH_API . 'oauth/token', [
"app_context" => "inapp_ios",
"client_id" => self::CLIENT_ID,
"client_secret" => self::CLIENT_SECRET,
"refresh_token" => $ticketUuidOrRefreshToken,
"duid" => self::DUID,
"grant_type" => "refresh_token",
"scope" => self::SCOPE
]);
} else {
$response = $this->httpClient()->post(self::AUTH_API . 'ssocookie', [
'authentication_type' => 'two_step',
'ticket_uuid' => $ticketUuidOrRefreshToken,
'code' => $code,
'client_id' => self::CLIENT_ID
]);
$npsso = $response->npsso;
$response = $this->httpClient()->get(self::AUTH_API . 'oauth/authorize', [
'duid' => self::DUID,
'client_id' => self::CLIENT_ID,
'response_type' => 'code',
'scope' => self::SCOPE,
'redirect_uri' => 'com.playstation.PlayStationApp://redirect'
], [
'Cookie' => 'npsso=' . $npsso
]);
if (($response instanceof Response) === false) {
throw new \Exception('Unexpected response');
}
$grant = $response->getHeaderLine('X-NP-GRANT-CODE');
if (empty($grant)) {
throw new \Exception('Unable to get X-NP-GRANT-CODE');
}
$response = $this->httpClient()->post(self::AUTH_API . 'oauth/token', [
'client_id' => self::CLIENT_ID,
'client_secret' => self::CLIENT_SECRET,
'duid' => self::DUID,
'scope' => self::SCOPE,
'redirect_uri' => 'com.playstation.PlayStationApp://redirect',
'code' => $grant,
'grant_type' => 'authorization_code'
]);
}
$this->accessToken = $response->access_token;
$this->refreshToken = $response->refresh_token;
$this->expiresIn = $response->expires_in;
$handler = \GuzzleHttp\HandlerStack::create();
$handler->push(Middleware::mapRequest(new TokenMiddleware($this->accessToken(), $this->refreshToken(), $this->expireDate())));
$newOptions = array_merge(['handler' => $handler], $this->options);
$this->httpClient = new HttpClient(new \GuzzleHttp\Client($newOptions));
} | php | public function login(string $ticketUuidOrRefreshToken, string $code = null)
{
if ($code === null) {
$response = $this->httpClient()->post(self::AUTH_API . 'oauth/token', [
"app_context" => "inapp_ios",
"client_id" => self::CLIENT_ID,
"client_secret" => self::CLIENT_SECRET,
"refresh_token" => $ticketUuidOrRefreshToken,
"duid" => self::DUID,
"grant_type" => "refresh_token",
"scope" => self::SCOPE
]);
} else {
$response = $this->httpClient()->post(self::AUTH_API . 'ssocookie', [
'authentication_type' => 'two_step',
'ticket_uuid' => $ticketUuidOrRefreshToken,
'code' => $code,
'client_id' => self::CLIENT_ID
]);
$npsso = $response->npsso;
$response = $this->httpClient()->get(self::AUTH_API . 'oauth/authorize', [
'duid' => self::DUID,
'client_id' => self::CLIENT_ID,
'response_type' => 'code',
'scope' => self::SCOPE,
'redirect_uri' => 'com.playstation.PlayStationApp://redirect'
], [
'Cookie' => 'npsso=' . $npsso
]);
if (($response instanceof Response) === false) {
throw new \Exception('Unexpected response');
}
$grant = $response->getHeaderLine('X-NP-GRANT-CODE');
if (empty($grant)) {
throw new \Exception('Unable to get X-NP-GRANT-CODE');
}
$response = $this->httpClient()->post(self::AUTH_API . 'oauth/token', [
'client_id' => self::CLIENT_ID,
'client_secret' => self::CLIENT_SECRET,
'duid' => self::DUID,
'scope' => self::SCOPE,
'redirect_uri' => 'com.playstation.PlayStationApp://redirect',
'code' => $grant,
'grant_type' => 'authorization_code'
]);
}
$this->accessToken = $response->access_token;
$this->refreshToken = $response->refresh_token;
$this->expiresIn = $response->expires_in;
$handler = \GuzzleHttp\HandlerStack::create();
$handler->push(Middleware::mapRequest(new TokenMiddleware($this->accessToken(), $this->refreshToken(), $this->expireDate())));
$newOptions = array_merge(['handler' => $handler], $this->options);
$this->httpClient = new HttpClient(new \GuzzleHttp\Client($newOptions));
} | [
"public",
"function",
"login",
"(",
"string",
"$",
"ticketUuidOrRefreshToken",
",",
"string",
"$",
"code",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"code",
"===",
"null",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"httpClient",
"(",
")",
"->",
... | Login to PlayStation network using a refresh token or 2FA.
@param string $ticketUuidOrRefreshToken Ticket UUID for 2FA, or the refresh token.
@param string $code 2FA code sent to your device (ignore if using refresh token).
@return void | [
"Login",
"to",
"PlayStation",
"network",
"using",
"a",
"refresh",
"token",
"or",
"2FA",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Client.php#L48-L112 | train |
Tustin/psn-php | src/Client.php | Client.onlineId | public function onlineId() : string
{
if ($this->onlineId === null) {
$response = $this->httpClient()->get(sprintf(User::USERS_ENDPOINT . 'profile2', 'me'), [
'fields' => 'onlineId'
]);
$this->onlineId = $response->profile->onlineId;
}
return $this->onlineId;
} | php | public function onlineId() : string
{
if ($this->onlineId === null) {
$response = $this->httpClient()->get(sprintf(User::USERS_ENDPOINT . 'profile2', 'me'), [
'fields' => 'onlineId'
]);
$this->onlineId = $response->profile->onlineId;
}
return $this->onlineId;
} | [
"public",
"function",
"onlineId",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"onlineId",
"===",
"null",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"httpClient",
"(",
")",
"->",
"get",
"(",
"sprintf",
"(",
"User",
"::",
"USE... | Gets the logged in user's onlineId.
@return string | [
"Gets",
"the",
"logged",
"in",
"user",
"s",
"onlineId",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Client.php#L129-L139 | train |
Tustin/psn-php | src/Client.php | Client.messageThreads | public function messageThreads(int $offset = 0, int $limit = 20) : object
{
if ($this->messageThreads === null) {
$response = $this->httpClient()->get(MessageThread::MESSAGE_THREAD_ENDPOINT . 'threads/', [
'fields' => 'threadMembers',
'limit' => $limit,
'offset' => $offset,
'sinceReceivedDate' => '1970-01-01T00:00:00Z' // Don't hardcode
]);
$this->messageThreads = $response;
}
return $this->messageThreads;
} | php | public function messageThreads(int $offset = 0, int $limit = 20) : object
{
if ($this->messageThreads === null) {
$response = $this->httpClient()->get(MessageThread::MESSAGE_THREAD_ENDPOINT . 'threads/', [
'fields' => 'threadMembers',
'limit' => $limit,
'offset' => $offset,
'sinceReceivedDate' => '1970-01-01T00:00:00Z' // Don't hardcode
]);
$this->messageThreads = $response;
}
return $this->messageThreads;
} | [
"public",
"function",
"messageThreads",
"(",
"int",
"$",
"offset",
"=",
"0",
",",
"int",
"$",
"limit",
"=",
"20",
")",
":",
"object",
"{",
"if",
"(",
"$",
"this",
"->",
"messageThreads",
"===",
"null",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"... | Gets all MessageThreads for the current Client.
@param integer $offset Where to start.
@param integer $limit Amount of threads.
@return object | [
"Gets",
"all",
"MessageThreads",
"for",
"the",
"current",
"Client",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Client.php#L178-L191 | train |
Tustin/psn-php | src/Client.php | Client.community | public function community(string $communityIdOrName, string $type = '', string $titleId = '') : Community
{
if (!empty($type) && !empty($titleId)) {
// Create the Community.
$response = $this->httpClient()->post(Community::COMMUNITY_ENDPOINT . 'communities?action=create', [
'name' => $communityIdOrName,
'type' => $type,
'titleId' => $titleId
], HttpClient::JSON);
$communityIdOrName = $response->id;
}
return new Community($this, $communityIdOrName);
} | php | public function community(string $communityIdOrName, string $type = '', string $titleId = '') : Community
{
if (!empty($type) && !empty($titleId)) {
// Create the Community.
$response = $this->httpClient()->post(Community::COMMUNITY_ENDPOINT . 'communities?action=create', [
'name' => $communityIdOrName,
'type' => $type,
'titleId' => $titleId
], HttpClient::JSON);
$communityIdOrName = $response->id;
}
return new Community($this, $communityIdOrName);
} | [
"public",
"function",
"community",
"(",
"string",
"$",
"communityIdOrName",
",",
"string",
"$",
"type",
"=",
"''",
",",
"string",
"$",
"titleId",
"=",
"''",
")",
":",
"Community",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"type",
")",
"&&",
"!",
"empty... | Get or create a Community.
@param string $communityIdOrName Community ID or the name of the new community.
@param string $type
@param string $titleId Game to associate your Community with.
@return Community | [
"Get",
"or",
"create",
"a",
"Community",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Client.php#L223-L237 | train |
Tustin/psn-php | src/Api/Session.php | Session.gameName | public function gameName() : ?string
{
if ($this->titleType() & SessionType::Unknown) return null;
return $this->session->npTitleDetail->npTitleName;
} | php | public function gameName() : ?string
{
if ($this->titleType() & SessionType::Unknown) return null;
return $this->session->npTitleDetail->npTitleName;
} | [
"public",
"function",
"gameName",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"titleType",
"(",
")",
"&",
"SessionType",
"::",
"Unknown",
")",
"return",
"null",
";",
"return",
"$",
"this",
"->",
"session",
"->",
"npTitleDetail",
"-... | Get name of the game the Session is for.
@return string|null | [
"Get",
"name",
"of",
"the",
"game",
"the",
"Session",
"is",
"for",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Session.php#L88-L93 | train |
Tustin/psn-php | src/Api/Session.php | Session.gameTitleId | public function gameTitleId() : ?string
{
if ($this->titleType() & SessionType::Unknown) return null;
return $this->session->npTitleDetail->npTitleId;
} | php | public function gameTitleId() : ?string
{
if ($this->titleType() & SessionType::Unknown) return null;
return $this->session->npTitleDetail->npTitleId;
} | [
"public",
"function",
"gameTitleId",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"titleType",
"(",
")",
"&",
"SessionType",
"::",
"Unknown",
")",
"return",
"null",
";",
"return",
"$",
"this",
"->",
"session",
"->",
"npTitleDetail",
... | Get title ID of the game the Session is for.
@return string|null | [
"Get",
"title",
"ID",
"of",
"the",
"game",
"the",
"Session",
"is",
"for",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Session.php#L100-L105 | train |
Tustin/psn-php | src/Api/Session.php | Session.gameIconUrl | public function gameIconUrl() : ?string
{
if ($this->titleType() & SessionType::Unknown) return null;
return $this->session->npTitleDetail->npTitleIconUrl;
} | php | public function gameIconUrl() : ?string
{
if ($this->titleType() & SessionType::Unknown) return null;
return $this->session->npTitleDetail->npTitleIconUrl;
} | [
"public",
"function",
"gameIconUrl",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"titleType",
"(",
")",
"&",
"SessionType",
"::",
"Unknown",
")",
"return",
"null",
";",
"return",
"$",
"this",
"->",
"session",
"->",
"npTitleDetail",
... | Get icon URL of the game the Session is for.
@return string|null | [
"Get",
"icon",
"URL",
"of",
"the",
"game",
"the",
"Session",
"is",
"for",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Session.php#L112-L117 | train |
Tustin/psn-php | src/Api/Session.php | Session.members | public function members() : array
{
$members = [];
if (!isset($this->session->members) || $this->session->memberCount <= 0) return $members;
foreach ($this->session->members as $member) {
$members[] = new User($this->client, $member->onlineId);
}
return $members;
} | php | public function members() : array
{
$members = [];
if (!isset($this->session->members) || $this->session->memberCount <= 0) return $members;
foreach ($this->session->members as $member) {
$members[] = new User($this->client, $member->onlineId);
}
return $members;
} | [
"public",
"function",
"members",
"(",
")",
":",
"array",
"{",
"$",
"members",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"session",
"->",
"members",
")",
"||",
"$",
"this",
"->",
"session",
"->",
"memberCount",
"<=",
"0",
... | Get Users in the Session.
@return array|null Array of Api\User. | [
"Get",
"Users",
"in",
"the",
"Session",
"."
] | 2f640b8790efa8f8570bc7e6a69dae115148c999 | https://github.com/Tustin/psn-php/blob/2f640b8790efa8f8570bc7e6a69dae115148c999/src/Api/Session.php#L124-L135 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.