repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.getFormatter
public function getFormatter($dateLength = IntlDateFormatter::MEDIUM, $timeLength = IntlDateFormatter::NONE) { return $this->getCustomFormatter(null, null, $dateLength, $timeLength); }
php
public function getFormatter($dateLength = IntlDateFormatter::MEDIUM, $timeLength = IntlDateFormatter::NONE) { return $this->getCustomFormatter(null, null, $dateLength, $timeLength); }
[ "public", "function", "getFormatter", "(", "$", "dateLength", "=", "IntlDateFormatter", "::", "MEDIUM", ",", "$", "timeLength", "=", "IntlDateFormatter", "::", "NONE", ")", "{", "return", "$", "this", "->", "getCustomFormatter", "(", "null", ",", "null", ",", "$", "dateLength", ",", "$", "timeLength", ")", ";", "}" ]
Get date formatter @param int $dateLength @param int $timeLength @return IntlDateFormatter
[ "Get", "date", "formatter" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L209-L212
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.FormatFromSettings
public function FormatFromSettings($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // Fall back to nice if (!$member) { return $this->Nice(); } // Get user format return $this->Format($member->getDateFormat(), $member->getLocale()); }
php
public function FormatFromSettings($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // Fall back to nice if (!$member) { return $this->Nice(); } // Get user format return $this->Format($member->getDateFormat(), $member->getLocale()); }
[ "public", "function", "FormatFromSettings", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "// Fall back to nice", "if", "(", "!", "$", "member", ")", "{", "return", "$", "this", "->", "Nice", "(", ")", ";", "}", "// Get user format", "return", "$", "this", "->", "Format", "(", "$", "member", "->", "getDateFormat", "(", ")", ",", "$", "member", "->", "getLocale", "(", ")", ")", ";", "}" ]
Return a date formatted as per a CMS user's settings. @param Member $member @return boolean | string A date formatted as per user-defined settings.
[ "Return", "a", "date", "formatted", "as", "per", "a", "CMS", "user", "s", "settings", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L305-L318
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.RangeString
public function RangeString($otherDateObj, $includeOrdinals = false) { $d1 = $this->DayOfMonth($includeOrdinals); $d2 = $otherDateObj->DayOfMonth($includeOrdinals); $m1 = $this->ShortMonth(); $m2 = $otherDateObj->ShortMonth(); $y1 = $this->Year(); $y2 = $otherDateObj->Year(); if ($y1 != $y2) { return "$d1 $m1 $y1 - $d2 $m2 $y2"; } elseif ($m1 != $m2) { return "$d1 $m1 - $d2 $m2 $y1"; } else { return "$d1 - $d2 $m1 $y1"; } }
php
public function RangeString($otherDateObj, $includeOrdinals = false) { $d1 = $this->DayOfMonth($includeOrdinals); $d2 = $otherDateObj->DayOfMonth($includeOrdinals); $m1 = $this->ShortMonth(); $m2 = $otherDateObj->ShortMonth(); $y1 = $this->Year(); $y2 = $otherDateObj->Year(); if ($y1 != $y2) { return "$d1 $m1 $y1 - $d2 $m2 $y2"; } elseif ($m1 != $m2) { return "$d1 $m1 - $d2 $m2 $y1"; } else { return "$d1 - $d2 $m1 $y1"; } }
[ "public", "function", "RangeString", "(", "$", "otherDateObj", ",", "$", "includeOrdinals", "=", "false", ")", "{", "$", "d1", "=", "$", "this", "->", "DayOfMonth", "(", "$", "includeOrdinals", ")", ";", "$", "d2", "=", "$", "otherDateObj", "->", "DayOfMonth", "(", "$", "includeOrdinals", ")", ";", "$", "m1", "=", "$", "this", "->", "ShortMonth", "(", ")", ";", "$", "m2", "=", "$", "otherDateObj", "->", "ShortMonth", "(", ")", ";", "$", "y1", "=", "$", "this", "->", "Year", "(", ")", ";", "$", "y2", "=", "$", "otherDateObj", "->", "Year", "(", ")", ";", "if", "(", "$", "y1", "!=", "$", "y2", ")", "{", "return", "\"$d1 $m1 $y1 - $d2 $m2 $y2\"", ";", "}", "elseif", "(", "$", "m1", "!=", "$", "m2", ")", "{", "return", "\"$d1 $m1 - $d2 $m2 $y1\"", ";", "}", "else", "{", "return", "\"$d1 - $d2 $m1 $y1\"", ";", "}", "}" ]
Return a string in the form "12 - 16 Sept" or "12 Aug - 16 Sept" @param DBDate $otherDateObj Another date object specifying the end of the range @param bool $includeOrdinals Include ordinal suffix to day, e.g. "th" or "rd" @return string
[ "Return", "a", "string", "in", "the", "form", "12", "-", "16", "Sept", "or", "12", "Aug", "-", "16", "Sept" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L327-L343
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.Rfc2822
public function Rfc2822() { $formatter = $this->getInternalFormatter(); $formatter->setPattern('y-MM-dd HH:mm:ss'); return $formatter->format($this->getTimestamp()); }
php
public function Rfc2822() { $formatter = $this->getInternalFormatter(); $formatter->setPattern('y-MM-dd HH:mm:ss'); return $formatter->format($this->getTimestamp()); }
[ "public", "function", "Rfc2822", "(", ")", "{", "$", "formatter", "=", "$", "this", "->", "getInternalFormatter", "(", ")", ";", "$", "formatter", "->", "setPattern", "(", "'y-MM-dd HH:mm:ss'", ")", ";", "return", "$", "formatter", "->", "format", "(", "$", "this", "->", "getTimestamp", "(", ")", ")", ";", "}" ]
Return date in RFC2822 format @return string
[ "Return", "date", "in", "RFC2822", "format" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L363-L368
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.TimeDiffIn
public function TimeDiffIn($format) { if (!$this->value) { return null; } $now = DBDatetime::now()->getTimestamp(); $time = $this->getTimestamp(); $ago = abs($time - $now); switch ($format) { case "seconds": $span = $ago; return _t( __CLASS__ . '.SECONDS_SHORT_PLURALS', '{count} sec|{count} secs', ['count' => $span] ); case "minutes": $span = round($ago / 60); return _t( __CLASS__ . '.MINUTES_SHORT_PLURALS', '{count} min|{count} mins', ['count' => $span] ); case "hours": $span = round($ago / 3600); return _t( __CLASS__ . '.HOURS_SHORT_PLURALS', '{count} hour|{count} hours', ['count' => $span] ); case "days": $span = round($ago / 86400); return _t( __CLASS__ . '.DAYS_SHORT_PLURALS', '{count} day|{count} days', ['count' => $span] ); case "months": $span = round($ago / 86400 / 30); return _t( __CLASS__ . '.MONTHS_SHORT_PLURALS', '{count} month|{count} months', ['count' => $span] ); case "years": $span = round($ago / 86400 / 365); return _t( __CLASS__ . '.YEARS_SHORT_PLURALS', '{count} year|{count} years', ['count' => $span] ); default: throw new \InvalidArgumentException("Invalid format $format"); } }
php
public function TimeDiffIn($format) { if (!$this->value) { return null; } $now = DBDatetime::now()->getTimestamp(); $time = $this->getTimestamp(); $ago = abs($time - $now); switch ($format) { case "seconds": $span = $ago; return _t( __CLASS__ . '.SECONDS_SHORT_PLURALS', '{count} sec|{count} secs', ['count' => $span] ); case "minutes": $span = round($ago / 60); return _t( __CLASS__ . '.MINUTES_SHORT_PLURALS', '{count} min|{count} mins', ['count' => $span] ); case "hours": $span = round($ago / 3600); return _t( __CLASS__ . '.HOURS_SHORT_PLURALS', '{count} hour|{count} hours', ['count' => $span] ); case "days": $span = round($ago / 86400); return _t( __CLASS__ . '.DAYS_SHORT_PLURALS', '{count} day|{count} days', ['count' => $span] ); case "months": $span = round($ago / 86400 / 30); return _t( __CLASS__ . '.MONTHS_SHORT_PLURALS', '{count} month|{count} months', ['count' => $span] ); case "years": $span = round($ago / 86400 / 365); return _t( __CLASS__ . '.YEARS_SHORT_PLURALS', '{count} year|{count} years', ['count' => $span] ); default: throw new \InvalidArgumentException("Invalid format $format"); } }
[ "public", "function", "TimeDiffIn", "(", "$", "format", ")", "{", "if", "(", "!", "$", "this", "->", "value", ")", "{", "return", "null", ";", "}", "$", "now", "=", "DBDatetime", "::", "now", "(", ")", "->", "getTimestamp", "(", ")", ";", "$", "time", "=", "$", "this", "->", "getTimestamp", "(", ")", ";", "$", "ago", "=", "abs", "(", "$", "time", "-", "$", "now", ")", ";", "switch", "(", "$", "format", ")", "{", "case", "\"seconds\"", ":", "$", "span", "=", "$", "ago", ";", "return", "_t", "(", "__CLASS__", ".", "'.SECONDS_SHORT_PLURALS'", ",", "'{count} sec|{count} secs'", ",", "[", "'count'", "=>", "$", "span", "]", ")", ";", "case", "\"minutes\"", ":", "$", "span", "=", "round", "(", "$", "ago", "/", "60", ")", ";", "return", "_t", "(", "__CLASS__", ".", "'.MINUTES_SHORT_PLURALS'", ",", "'{count} min|{count} mins'", ",", "[", "'count'", "=>", "$", "span", "]", ")", ";", "case", "\"hours\"", ":", "$", "span", "=", "round", "(", "$", "ago", "/", "3600", ")", ";", "return", "_t", "(", "__CLASS__", ".", "'.HOURS_SHORT_PLURALS'", ",", "'{count} hour|{count} hours'", ",", "[", "'count'", "=>", "$", "span", "]", ")", ";", "case", "\"days\"", ":", "$", "span", "=", "round", "(", "$", "ago", "/", "86400", ")", ";", "return", "_t", "(", "__CLASS__", ".", "'.DAYS_SHORT_PLURALS'", ",", "'{count} day|{count} days'", ",", "[", "'count'", "=>", "$", "span", "]", ")", ";", "case", "\"months\"", ":", "$", "span", "=", "round", "(", "$", "ago", "/", "86400", "/", "30", ")", ";", "return", "_t", "(", "__CLASS__", ".", "'.MONTHS_SHORT_PLURALS'", ",", "'{count} month|{count} months'", ",", "[", "'count'", "=>", "$", "span", "]", ")", ";", "case", "\"years\"", ":", "$", "span", "=", "round", "(", "$", "ago", "/", "86400", "/", "365", ")", ";", "return", "_t", "(", "__CLASS__", ".", "'.YEARS_SHORT_PLURALS'", ",", "'{count} year|{count} years'", ",", "[", "'count'", "=>", "$", "span", "]", ")", ";", "default", ":", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Invalid format $format\"", ")", ";", "}", "}" ]
Gets the time difference, but always returns it in a certain format @param string $format The format, could be one of these: 'seconds', 'minutes', 'hours', 'days', 'months', 'years'. @return string The resulting formatted period
[ "Gets", "the", "time", "difference", "but", "always", "returns", "it", "in", "a", "certain", "format" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L449-L510
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.IsToday
public function IsToday() { return $this->Format(self::ISO_DATE) === DBDatetime::now()->Format(self::ISO_DATE); }
php
public function IsToday() { return $this->Format(self::ISO_DATE) === DBDatetime::now()->Format(self::ISO_DATE); }
[ "public", "function", "IsToday", "(", ")", "{", "return", "$", "this", "->", "Format", "(", "self", "::", "ISO_DATE", ")", "===", "DBDatetime", "::", "now", "(", ")", "->", "Format", "(", "self", "::", "ISO_DATE", ")", ";", "}" ]
Returns true if date is today. @return boolean
[ "Returns", "true", "if", "date", "is", "today", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L541-L544
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.fixInputDate
protected function fixInputDate($value) { // split list($year, $month, $day, $time) = $this->explodeDateString($value); if ((int)$year === 0 && (int)$month === 0 && (int)$day === 0) { return null; } // Validate date if (!checkdate($month, $day, $year)) { throw new InvalidArgumentException( "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." ); } // Convert to y-m-d return sprintf('%d-%02d-%02d%s', $year, $month, $day, $time); }
php
protected function fixInputDate($value) { // split list($year, $month, $day, $time) = $this->explodeDateString($value); if ((int)$year === 0 && (int)$month === 0 && (int)$day === 0) { return null; } // Validate date if (!checkdate($month, $day, $year)) { throw new InvalidArgumentException( "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." ); } // Convert to y-m-d return sprintf('%d-%02d-%02d%s', $year, $month, $day, $time); }
[ "protected", "function", "fixInputDate", "(", "$", "value", ")", "{", "// split", "list", "(", "$", "year", ",", "$", "month", ",", "$", "day", ",", "$", "time", ")", "=", "$", "this", "->", "explodeDateString", "(", "$", "value", ")", ";", "if", "(", "(", "int", ")", "$", "year", "===", "0", "&&", "(", "int", ")", "$", "month", "===", "0", "&&", "(", "int", ")", "$", "day", "===", "0", ")", "{", "return", "null", ";", "}", "// Validate date", "if", "(", "!", "checkdate", "(", "$", "month", ",", "$", "day", ",", "$", "year", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid date: '$value'. Use \"", ".", "self", "::", "ISO_DATE", ".", "\" to prevent this error.\"", ")", ";", "}", "// Convert to y-m-d", "return", "sprintf", "(", "'%d-%02d-%02d%s'", ",", "$", "year", ",", "$", "month", ",", "$", "day", ",", "$", "time", ")", ";", "}" ]
Fix non-iso dates @param string $value @return string
[ "Fix", "non", "-", "iso", "dates" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L570-L587
train
silverstripe/silverstripe-framework
src/ORM/FieldType/DBDate.php
DBDate.explodeDateString
protected function explodeDateString($value) { // split on known delimiters (. / -) if (!preg_match( '#^(?<first>\\d+)[-/\\.](?<second>\\d+)[-/\\.](?<third>\\d+)(?<time>.*)$#', $value, $matches )) { throw new InvalidArgumentException( "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." ); } $parts = [ $matches['first'], $matches['second'], $matches['third'] ]; // Flip d-m-y to y-m-d if ($parts[0] < 1000 && $parts[2] > 1000) { $parts = array_reverse($parts); } if ($parts[0] < 1000 && (int)$parts[0] !== 0) { throw new InvalidArgumentException( "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." ); } $parts[] = $matches['time']; return $parts; }
php
protected function explodeDateString($value) { // split on known delimiters (. / -) if (!preg_match( '#^(?<first>\\d+)[-/\\.](?<second>\\d+)[-/\\.](?<third>\\d+)(?<time>.*)$#', $value, $matches )) { throw new InvalidArgumentException( "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." ); } $parts = [ $matches['first'], $matches['second'], $matches['third'] ]; // Flip d-m-y to y-m-d if ($parts[0] < 1000 && $parts[2] > 1000) { $parts = array_reverse($parts); } if ($parts[0] < 1000 && (int)$parts[0] !== 0) { throw new InvalidArgumentException( "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." ); } $parts[] = $matches['time']; return $parts; }
[ "protected", "function", "explodeDateString", "(", "$", "value", ")", "{", "// split on known delimiters (. / -)", "if", "(", "!", "preg_match", "(", "'#^(?<first>\\\\d+)[-/\\\\.](?<second>\\\\d+)[-/\\\\.](?<third>\\\\d+)(?<time>.*)$#'", ",", "$", "value", ",", "$", "matches", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid date: '$value'. Use \"", ".", "self", "::", "ISO_DATE", ".", "\" to prevent this error.\"", ")", ";", "}", "$", "parts", "=", "[", "$", "matches", "[", "'first'", "]", ",", "$", "matches", "[", "'second'", "]", ",", "$", "matches", "[", "'third'", "]", "]", ";", "// Flip d-m-y to y-m-d", "if", "(", "$", "parts", "[", "0", "]", "<", "1000", "&&", "$", "parts", "[", "2", "]", ">", "1000", ")", "{", "$", "parts", "=", "array_reverse", "(", "$", "parts", ")", ";", "}", "if", "(", "$", "parts", "[", "0", "]", "<", "1000", "&&", "(", "int", ")", "$", "parts", "[", "0", "]", "!==", "0", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid date: '$value'. Use \"", ".", "self", "::", "ISO_DATE", ".", "\" to prevent this error.\"", ")", ";", "}", "$", "parts", "[", "]", "=", "$", "matches", "[", "'time'", "]", ";", "return", "$", "parts", ";", "}" ]
Attempt to split date string into year, month, day, and timestamp components. @param string $value @return array
[ "Attempt", "to", "split", "date", "string", "into", "year", "month", "day", "and", "timestamp", "components", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/FieldType/DBDate.php#L595-L624
train
silverstripe/silverstripe-framework
src/Forms/FormTemplateHelper.php
FormTemplateHelper.generateFieldID
public function generateFieldID($field) { if ($form = $field->getForm()) { return sprintf( "%s_%s", $this->generateFormID($form), Convert::raw2htmlid($field->getName()) ); } return Convert::raw2htmlid($field->getName()); }
php
public function generateFieldID($field) { if ($form = $field->getForm()) { return sprintf( "%s_%s", $this->generateFormID($form), Convert::raw2htmlid($field->getName()) ); } return Convert::raw2htmlid($field->getName()); }
[ "public", "function", "generateFieldID", "(", "$", "field", ")", "{", "if", "(", "$", "form", "=", "$", "field", "->", "getForm", "(", ")", ")", "{", "return", "sprintf", "(", "\"%s_%s\"", ",", "$", "this", "->", "generateFormID", "(", "$", "form", ")", ",", "Convert", "::", "raw2htmlid", "(", "$", "field", "->", "getName", "(", ")", ")", ")", ";", "}", "return", "Convert", "::", "raw2htmlid", "(", "$", "field", "->", "getName", "(", ")", ")", ";", "}" ]
Generate the field ID value @param FormField $field @return string
[ "Generate", "the", "field", "ID", "value" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormTemplateHelper.php#L62-L73
train
silverstripe/silverstripe-framework
src/View/SSViewer_DataPresenter.php
SSViewer_DataPresenter.cacheIteratorProperties
protected function cacheIteratorProperties() { if (self::$iteratorProperties !== null) { return; } self::$iteratorProperties = $this->getPropertiesFromProvider( TemplateIteratorProvider::class, 'get_template_iterator_variables', true // Call non-statically ); }
php
protected function cacheIteratorProperties() { if (self::$iteratorProperties !== null) { return; } self::$iteratorProperties = $this->getPropertiesFromProvider( TemplateIteratorProvider::class, 'get_template_iterator_variables', true // Call non-statically ); }
[ "protected", "function", "cacheIteratorProperties", "(", ")", "{", "if", "(", "self", "::", "$", "iteratorProperties", "!==", "null", ")", "{", "return", ";", "}", "self", "::", "$", "iteratorProperties", "=", "$", "this", "->", "getPropertiesFromProvider", "(", "TemplateIteratorProvider", "::", "class", ",", "'get_template_iterator_variables'", ",", "true", "// Call non-statically", ")", ";", "}" ]
Build cache of global iterator properties
[ "Build", "cache", "of", "global", "iterator", "properties" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_DataPresenter.php#L87-L98
train
silverstripe/silverstripe-framework
src/View/SSViewer_DataPresenter.php
SSViewer_DataPresenter.popScope
public function popScope() { $upIndex = $this->getUpIndex(); if ($upIndex !== null) { $itemStack = $this->getItemStack(); $this->overlay = $itemStack[$this->getUpIndex()][SSViewer_Scope::ITEM_OVERLAY]; } return parent::popScope(); }
php
public function popScope() { $upIndex = $this->getUpIndex(); if ($upIndex !== null) { $itemStack = $this->getItemStack(); $this->overlay = $itemStack[$this->getUpIndex()][SSViewer_Scope::ITEM_OVERLAY]; } return parent::popScope(); }
[ "public", "function", "popScope", "(", ")", "{", "$", "upIndex", "=", "$", "this", "->", "getUpIndex", "(", ")", ";", "if", "(", "$", "upIndex", "!==", "null", ")", "{", "$", "itemStack", "=", "$", "this", "->", "getItemStack", "(", ")", ";", "$", "this", "->", "overlay", "=", "$", "itemStack", "[", "$", "this", "->", "getUpIndex", "(", ")", "]", "[", "SSViewer_Scope", "::", "ITEM_OVERLAY", "]", ";", "}", "return", "parent", "::", "popScope", "(", ")", ";", "}" ]
Now that we're going to jump up an item in the item stack, we need to restore the overlay that was previously stored against the next item "up" in the stack from the current one @return SSViewer_Scope
[ "Now", "that", "we", "re", "going", "to", "jump", "up", "an", "item", "in", "the", "item", "stack", "we", "need", "to", "restore", "the", "overlay", "that", "was", "previously", "stored", "against", "the", "next", "item", "up", "in", "the", "stack", "from", "the", "current", "one" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_DataPresenter.php#L222-L232
train
silverstripe/silverstripe-framework
src/View/SSViewer_DataPresenter.php
SSViewer_DataPresenter.processTemplateOverride
protected function processTemplateOverride($property, $overrides) { if (!isset($overrides[$property])) { return null; } // Detect override type $override = $overrides[$property]; // Late-evaluate this value if (!is_string($override) && is_callable($override)) { $override = $override(); // Late override may yet return null if (!isset($override)) { return null; } } return [ 'value' => $override ]; }
php
protected function processTemplateOverride($property, $overrides) { if (!isset($overrides[$property])) { return null; } // Detect override type $override = $overrides[$property]; // Late-evaluate this value if (!is_string($override) && is_callable($override)) { $override = $override(); // Late override may yet return null if (!isset($override)) { return null; } } return [ 'value' => $override ]; }
[ "protected", "function", "processTemplateOverride", "(", "$", "property", ",", "$", "overrides", ")", "{", "if", "(", "!", "isset", "(", "$", "overrides", "[", "$", "property", "]", ")", ")", "{", "return", "null", ";", "}", "// Detect override type", "$", "override", "=", "$", "overrides", "[", "$", "property", "]", ";", "// Late-evaluate this value", "if", "(", "!", "is_string", "(", "$", "override", ")", "&&", "is_callable", "(", "$", "override", ")", ")", "{", "$", "override", "=", "$", "override", "(", ")", ";", "// Late override may yet return null", "if", "(", "!", "isset", "(", "$", "override", ")", ")", "{", "return", "null", ";", "}", "}", "return", "[", "'value'", "=>", "$", "override", "]", ";", "}" ]
Evaluate a template override @param string $property Name of override requested @param array $overrides List of overrides available @return null|array Null if not provided, or array with 'value' or 'callable' key
[ "Evaluate", "a", "template", "override" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_DataPresenter.php#L319-L339
train
silverstripe/silverstripe-framework
src/View/SSViewer_DataPresenter.php
SSViewer_DataPresenter.getValueSource
protected function getValueSource($property) { // Check for a presenter-specific override $overlay = $this->processTemplateOverride($property, $this->overlay); if (isset($overlay)) { return $overlay; } // Check if the method to-be-called exists on the target object - if so, don't check any further // injection locations $on = $this->itemIterator ? $this->itemIterator->current() : $this->item; if (isset($on->$property) || method_exists($on, $property)) { return null; } // Check for a presenter-specific override $underlay = $this->processTemplateOverride($property, $this->underlay); if (isset($underlay)) { return $underlay; } // Then for iterator-specific overrides if (array_key_exists($property, self::$iteratorProperties)) { $source = self::$iteratorProperties[$property]; /** @var TemplateIteratorProvider $implementor */ $implementor = $source['implementor']; if ($this->itemIterator) { // Set the current iterator position and total (the object instance is the first item in // the callable array) $implementor->iteratorProperties( $this->itemIterator->key(), $this->itemIteratorTotal ); } else { // If we don't actually have an iterator at the moment, act like a list of length 1 $implementor->iteratorProperties(0, 1); } return $source; } // And finally for global overrides if (array_key_exists($property, self::$globalProperties)) { return self::$globalProperties[$property]; //get the method call } // No value return null; }
php
protected function getValueSource($property) { // Check for a presenter-specific override $overlay = $this->processTemplateOverride($property, $this->overlay); if (isset($overlay)) { return $overlay; } // Check if the method to-be-called exists on the target object - if so, don't check any further // injection locations $on = $this->itemIterator ? $this->itemIterator->current() : $this->item; if (isset($on->$property) || method_exists($on, $property)) { return null; } // Check for a presenter-specific override $underlay = $this->processTemplateOverride($property, $this->underlay); if (isset($underlay)) { return $underlay; } // Then for iterator-specific overrides if (array_key_exists($property, self::$iteratorProperties)) { $source = self::$iteratorProperties[$property]; /** @var TemplateIteratorProvider $implementor */ $implementor = $source['implementor']; if ($this->itemIterator) { // Set the current iterator position and total (the object instance is the first item in // the callable array) $implementor->iteratorProperties( $this->itemIterator->key(), $this->itemIteratorTotal ); } else { // If we don't actually have an iterator at the moment, act like a list of length 1 $implementor->iteratorProperties(0, 1); } return $source; } // And finally for global overrides if (array_key_exists($property, self::$globalProperties)) { return self::$globalProperties[$property]; //get the method call } // No value return null; }
[ "protected", "function", "getValueSource", "(", "$", "property", ")", "{", "// Check for a presenter-specific override", "$", "overlay", "=", "$", "this", "->", "processTemplateOverride", "(", "$", "property", ",", "$", "this", "->", "overlay", ")", ";", "if", "(", "isset", "(", "$", "overlay", ")", ")", "{", "return", "$", "overlay", ";", "}", "// Check if the method to-be-called exists on the target object - if so, don't check any further", "// injection locations", "$", "on", "=", "$", "this", "->", "itemIterator", "?", "$", "this", "->", "itemIterator", "->", "current", "(", ")", ":", "$", "this", "->", "item", ";", "if", "(", "isset", "(", "$", "on", "->", "$", "property", ")", "||", "method_exists", "(", "$", "on", ",", "$", "property", ")", ")", "{", "return", "null", ";", "}", "// Check for a presenter-specific override", "$", "underlay", "=", "$", "this", "->", "processTemplateOverride", "(", "$", "property", ",", "$", "this", "->", "underlay", ")", ";", "if", "(", "isset", "(", "$", "underlay", ")", ")", "{", "return", "$", "underlay", ";", "}", "// Then for iterator-specific overrides", "if", "(", "array_key_exists", "(", "$", "property", ",", "self", "::", "$", "iteratorProperties", ")", ")", "{", "$", "source", "=", "self", "::", "$", "iteratorProperties", "[", "$", "property", "]", ";", "/** @var TemplateIteratorProvider $implementor */", "$", "implementor", "=", "$", "source", "[", "'implementor'", "]", ";", "if", "(", "$", "this", "->", "itemIterator", ")", "{", "// Set the current iterator position and total (the object instance is the first item in", "// the callable array)", "$", "implementor", "->", "iteratorProperties", "(", "$", "this", "->", "itemIterator", "->", "key", "(", ")", ",", "$", "this", "->", "itemIteratorTotal", ")", ";", "}", "else", "{", "// If we don't actually have an iterator at the moment, act like a list of length 1", "$", "implementor", "->", "iteratorProperties", "(", "0", ",", "1", ")", ";", "}", "return", "$", "source", ";", "}", "// And finally for global overrides", "if", "(", "array_key_exists", "(", "$", "property", ",", "self", "::", "$", "globalProperties", ")", ")", "{", "return", "self", "::", "$", "globalProperties", "[", "$", "property", "]", ";", "//get the method call", "}", "// No value", "return", "null", ";", "}" ]
Determine source to use for getInjectedValue @param string $property @return array|null
[ "Determine", "source", "to", "use", "for", "getInjectedValue" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_DataPresenter.php#L347-L394
train
silverstripe/silverstripe-framework
src/View/SSViewer_DataPresenter.php
SSViewer_DataPresenter.castValue
protected function castValue($value, $source) { // Already cast if (is_object($value)) { return $value; } // Get provided or default cast $casting = empty($source['casting']) ? ViewableData::config()->uninherited('default_cast') : $source['casting']; return DBField::create_field($casting, $value); }
php
protected function castValue($value, $source) { // Already cast if (is_object($value)) { return $value; } // Get provided or default cast $casting = empty($source['casting']) ? ViewableData::config()->uninherited('default_cast') : $source['casting']; return DBField::create_field($casting, $value); }
[ "protected", "function", "castValue", "(", "$", "value", ",", "$", "source", ")", "{", "// Already cast", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "// Get provided or default cast", "$", "casting", "=", "empty", "(", "$", "source", "[", "'casting'", "]", ")", "?", "ViewableData", "::", "config", "(", ")", "->", "uninherited", "(", "'default_cast'", ")", ":", "$", "source", "[", "'casting'", "]", ";", "return", "DBField", "::", "create_field", "(", "$", "casting", ",", "$", "value", ")", ";", "}" ]
Ensure the value is cast safely @param mixed $value @param array $source @return DBField
[ "Ensure", "the", "value", "is", "cast", "safely" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/SSViewer_DataPresenter.php#L403-L416
train
silverstripe/silverstripe-framework
src/Control/Email/SwiftPlugin.php
SwiftPlugin.beforeSendPerformed
public function beforeSendPerformed(\Swift_Events_SendEvent $evt) { /** @var \Swift_Message $message */ $message = $evt->getMessage(); $sendAllTo = Email::getSendAllEmailsTo(); if (!empty($sendAllTo)) { $this->setTo($message, $sendAllTo); } $ccAllTo = Email::getCCAllEmailsTo(); if (!empty($ccAllTo)) { foreach ($ccAllTo as $address => $name) { $message->addCc($address, $name); } } $bccAllTo = Email::getBCCAllEmailsTo(); if (!empty($bccAllTo)) { foreach ($bccAllTo as $address => $name) { $message->addBcc($address, $name); } } $sendAllFrom = Email::getSendAllEmailsFrom(); if (!empty($sendAllFrom)) { $this->setFrom($message, $sendAllFrom); } }
php
public function beforeSendPerformed(\Swift_Events_SendEvent $evt) { /** @var \Swift_Message $message */ $message = $evt->getMessage(); $sendAllTo = Email::getSendAllEmailsTo(); if (!empty($sendAllTo)) { $this->setTo($message, $sendAllTo); } $ccAllTo = Email::getCCAllEmailsTo(); if (!empty($ccAllTo)) { foreach ($ccAllTo as $address => $name) { $message->addCc($address, $name); } } $bccAllTo = Email::getBCCAllEmailsTo(); if (!empty($bccAllTo)) { foreach ($bccAllTo as $address => $name) { $message->addBcc($address, $name); } } $sendAllFrom = Email::getSendAllEmailsFrom(); if (!empty($sendAllFrom)) { $this->setFrom($message, $sendAllFrom); } }
[ "public", "function", "beforeSendPerformed", "(", "\\", "Swift_Events_SendEvent", "$", "evt", ")", "{", "/** @var \\Swift_Message $message */", "$", "message", "=", "$", "evt", "->", "getMessage", "(", ")", ";", "$", "sendAllTo", "=", "Email", "::", "getSendAllEmailsTo", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "sendAllTo", ")", ")", "{", "$", "this", "->", "setTo", "(", "$", "message", ",", "$", "sendAllTo", ")", ";", "}", "$", "ccAllTo", "=", "Email", "::", "getCCAllEmailsTo", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "ccAllTo", ")", ")", "{", "foreach", "(", "$", "ccAllTo", "as", "$", "address", "=>", "$", "name", ")", "{", "$", "message", "->", "addCc", "(", "$", "address", ",", "$", "name", ")", ";", "}", "}", "$", "bccAllTo", "=", "Email", "::", "getBCCAllEmailsTo", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "bccAllTo", ")", ")", "{", "foreach", "(", "$", "bccAllTo", "as", "$", "address", "=>", "$", "name", ")", "{", "$", "message", "->", "addBcc", "(", "$", "address", ",", "$", "name", ")", ";", "}", "}", "$", "sendAllFrom", "=", "Email", "::", "getSendAllEmailsFrom", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "sendAllFrom", ")", ")", "{", "$", "this", "->", "setFrom", "(", "$", "message", ",", "$", "sendAllFrom", ")", ";", "}", "}" ]
Before sending a message make sure all our overrides are taken into account @param \Swift_Events_SendEvent $evt
[ "Before", "sending", "a", "message", "make", "sure", "all", "our", "overrides", "are", "taken", "into", "account" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Email/SwiftPlugin.php#L12-L40
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.getChildren
protected function getChildren(DataObject $node) { $method = $this->getChildrenMethod(); return $node->$method() ?: ArrayList::create(); }
php
protected function getChildren(DataObject $node) { $method = $this->getChildrenMethod(); return $node->$method() ?: ArrayList::create(); }
[ "protected", "function", "getChildren", "(", "DataObject", "$", "node", ")", "{", "$", "method", "=", "$", "this", "->", "getChildrenMethod", "(", ")", ";", "return", "$", "node", "->", "$", "method", "(", ")", "?", ":", "ArrayList", "::", "create", "(", ")", ";", "}" ]
Get children from this node @param DataObject $node @return SS_List
[ "Get", "children", "from", "this", "node" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L192-L196
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.setChildrenMethod
public function setChildrenMethod($method) { // Check method is valid if (!$this->rootNode->hasMethod($method)) { throw new InvalidArgumentException(sprintf( "Can't find the method '%s' on class '%s' for getting tree children", $method, get_class($this->rootNode) )); } $this->childrenMethod = $method; return $this; }
php
public function setChildrenMethod($method) { // Check method is valid if (!$this->rootNode->hasMethod($method)) { throw new InvalidArgumentException(sprintf( "Can't find the method '%s' on class '%s' for getting tree children", $method, get_class($this->rootNode) )); } $this->childrenMethod = $method; return $this; }
[ "public", "function", "setChildrenMethod", "(", "$", "method", ")", "{", "// Check method is valid", "if", "(", "!", "$", "this", "->", "rootNode", "->", "hasMethod", "(", "$", "method", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "\"Can't find the method '%s' on class '%s' for getting tree children\"", ",", "$", "method", ",", "get_class", "(", "$", "this", "->", "rootNode", ")", ")", ")", ";", "}", "$", "this", "->", "childrenMethod", "=", "$", "method", ";", "return", "$", "this", ";", "}" ]
Set method to use for getting children @param string $method @throws InvalidArgumentException @return $this
[ "Set", "method", "to", "use", "for", "getting", "children" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L205-L217
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.setNumChildrenMethod
public function setNumChildrenMethod($method) { // Check method is valid if (!$this->rootNode->hasMethod($method)) { throw new InvalidArgumentException(sprintf( "Can't find the method '%s' on class '%s' for counting tree children", $method, get_class($this->rootNode) )); } $this->numChildrenMethod = $method; return $this; }
php
public function setNumChildrenMethod($method) { // Check method is valid if (!$this->rootNode->hasMethod($method)) { throw new InvalidArgumentException(sprintf( "Can't find the method '%s' on class '%s' for counting tree children", $method, get_class($this->rootNode) )); } $this->numChildrenMethod = $method; return $this; }
[ "public", "function", "setNumChildrenMethod", "(", "$", "method", ")", "{", "// Check method is valid", "if", "(", "!", "$", "this", "->", "rootNode", "->", "hasMethod", "(", "$", "method", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "\"Can't find the method '%s' on class '%s' for counting tree children\"", ",", "$", "method", ",", "get_class", "(", "$", "this", "->", "rootNode", ")", ")", ")", ";", "}", "$", "this", "->", "numChildrenMethod", "=", "$", "method", ";", "return", "$", "this", ";", "}" ]
Set method name to get num children @param string $method @return $this
[ "Set", "method", "name", "to", "get", "num", "children" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L247-L259
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.getChildrenAsArray
public function getChildrenAsArray($serialiseEval = null) { if (!$serialiseEval) { $serialiseEval = function ($data) { /** @var DataObject $node */ $node = $data['node']; return [ 'id' => $node->ID, 'title' => $node->getTitle() ]; }; } $tree = $this->getSubtree($this->rootNode, 0); return $this->getSubtreeAsArray($tree, $serialiseEval); }
php
public function getChildrenAsArray($serialiseEval = null) { if (!$serialiseEval) { $serialiseEval = function ($data) { /** @var DataObject $node */ $node = $data['node']; return [ 'id' => $node->ID, 'title' => $node->getTitle() ]; }; } $tree = $this->getSubtree($this->rootNode, 0); return $this->getSubtreeAsArray($tree, $serialiseEval); }
[ "public", "function", "getChildrenAsArray", "(", "$", "serialiseEval", "=", "null", ")", "{", "if", "(", "!", "$", "serialiseEval", ")", "{", "$", "serialiseEval", "=", "function", "(", "$", "data", ")", "{", "/** @var DataObject $node */", "$", "node", "=", "$", "data", "[", "'node'", "]", ";", "return", "[", "'id'", "=>", "$", "node", "->", "ID", ",", "'title'", "=>", "$", "node", "->", "getTitle", "(", ")", "]", ";", "}", ";", "}", "$", "tree", "=", "$", "this", "->", "getSubtree", "(", "$", "this", "->", "rootNode", ",", "0", ")", ";", "return", "$", "this", "->", "getSubtreeAsArray", "(", "$", "tree", ",", "$", "serialiseEval", ")", ";", "}" ]
Get child data formatted as JSON @param callable $serialiseEval A callback that takes a DataObject as a single parameter, and should return an array containing a simple array representation. This result will replace the 'node' property at each point in the tree. @return array
[ "Get", "child", "data", "formatted", "as", "JSON" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L294-L310
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.renderSubtree
protected function renderSubtree($data, $template, $context = []) { // Render children $childNodes = new ArrayList(); foreach ($data['children'] as $child) { $childData = $this->renderSubtree($child, $template, $context); $childNodes->push($childData); } // Build parent node $parentNode = new ArrayData($data); $parentNode->setField('children', $childNodes); // Replace raw array with template-friendly list $parentNode->setField('markingClasses', $this->markingClasses($data['node'])); // Evaluate custom context if (!is_string($context) && is_callable($context)) { $context = call_user_func($context, $data['node']); } if ($context) { foreach ($context as $key => $value) { $parentNode->setField($key, $value); } } // Render $subtree = $parentNode->renderWith($template); $parentNode->setField('SubTree', $subtree); return $parentNode; }
php
protected function renderSubtree($data, $template, $context = []) { // Render children $childNodes = new ArrayList(); foreach ($data['children'] as $child) { $childData = $this->renderSubtree($child, $template, $context); $childNodes->push($childData); } // Build parent node $parentNode = new ArrayData($data); $parentNode->setField('children', $childNodes); // Replace raw array with template-friendly list $parentNode->setField('markingClasses', $this->markingClasses($data['node'])); // Evaluate custom context if (!is_string($context) && is_callable($context)) { $context = call_user_func($context, $data['node']); } if ($context) { foreach ($context as $key => $value) { $parentNode->setField($key, $value); } } // Render $subtree = $parentNode->renderWith($template); $parentNode->setField('SubTree', $subtree); return $parentNode; }
[ "protected", "function", "renderSubtree", "(", "$", "data", ",", "$", "template", ",", "$", "context", "=", "[", "]", ")", "{", "// Render children", "$", "childNodes", "=", "new", "ArrayList", "(", ")", ";", "foreach", "(", "$", "data", "[", "'children'", "]", "as", "$", "child", ")", "{", "$", "childData", "=", "$", "this", "->", "renderSubtree", "(", "$", "child", ",", "$", "template", ",", "$", "context", ")", ";", "$", "childNodes", "->", "push", "(", "$", "childData", ")", ";", "}", "// Build parent node", "$", "parentNode", "=", "new", "ArrayData", "(", "$", "data", ")", ";", "$", "parentNode", "->", "setField", "(", "'children'", ",", "$", "childNodes", ")", ";", "// Replace raw array with template-friendly list", "$", "parentNode", "->", "setField", "(", "'markingClasses'", ",", "$", "this", "->", "markingClasses", "(", "$", "data", "[", "'node'", "]", ")", ")", ";", "// Evaluate custom context", "if", "(", "!", "is_string", "(", "$", "context", ")", "&&", "is_callable", "(", "$", "context", ")", ")", "{", "$", "context", "=", "call_user_func", "(", "$", "context", ",", "$", "data", "[", "'node'", "]", ")", ";", "}", "if", "(", "$", "context", ")", "{", "foreach", "(", "$", "context", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "parentNode", "->", "setField", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "// Render", "$", "subtree", "=", "$", "parentNode", "->", "renderWith", "(", "$", "template", ")", ";", "$", "parentNode", "->", "setField", "(", "'SubTree'", ",", "$", "subtree", ")", ";", "return", "$", "parentNode", ";", "}" ]
Render a node in the tree with the given template @param array $data array data for current node @param string|array $template Template to use @param array|callable $context Additional arguments to add to template when rendering due to excessive line length. If callable, this will be executed with the current node dataobject @return ArrayData Viewable object representing the root node. use getField('SubTree') to get HTML
[ "Render", "a", "node", "in", "the", "tree", "with", "the", "given", "template" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L321-L349
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.getSubtreeAsArray
protected function getSubtreeAsArray($data, $serialiseEval) { $output = $data; // Serialise node $serialised = $serialiseEval($data['node']); // Force serialisation of DBField instances if (is_array($serialised)) { foreach ($serialised as $key => $value) { if ($value instanceof DBField) { $serialised[$key] = $value->getSchemaValue(); } } // Merge with top level array unset($output['node']); $output = array_merge($output, $serialised); } else { if ($serialised instanceof DBField) { $serialised = $serialised->getSchemaValue(); } // Replace node with serialised value $output['node'] = $serialised; } // Replace children with serialised elements $output['children'] = []; foreach ($data['children'] as $child) { $output['children'][] = $this->getSubtreeAsArray($child, $serialiseEval); } return $output; }
php
protected function getSubtreeAsArray($data, $serialiseEval) { $output = $data; // Serialise node $serialised = $serialiseEval($data['node']); // Force serialisation of DBField instances if (is_array($serialised)) { foreach ($serialised as $key => $value) { if ($value instanceof DBField) { $serialised[$key] = $value->getSchemaValue(); } } // Merge with top level array unset($output['node']); $output = array_merge($output, $serialised); } else { if ($serialised instanceof DBField) { $serialised = $serialised->getSchemaValue(); } // Replace node with serialised value $output['node'] = $serialised; } // Replace children with serialised elements $output['children'] = []; foreach ($data['children'] as $child) { $output['children'][] = $this->getSubtreeAsArray($child, $serialiseEval); } return $output; }
[ "protected", "function", "getSubtreeAsArray", "(", "$", "data", ",", "$", "serialiseEval", ")", "{", "$", "output", "=", "$", "data", ";", "// Serialise node", "$", "serialised", "=", "$", "serialiseEval", "(", "$", "data", "[", "'node'", "]", ")", ";", "// Force serialisation of DBField instances", "if", "(", "is_array", "(", "$", "serialised", ")", ")", "{", "foreach", "(", "$", "serialised", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "DBField", ")", "{", "$", "serialised", "[", "$", "key", "]", "=", "$", "value", "->", "getSchemaValue", "(", ")", ";", "}", "}", "// Merge with top level array", "unset", "(", "$", "output", "[", "'node'", "]", ")", ";", "$", "output", "=", "array_merge", "(", "$", "output", ",", "$", "serialised", ")", ";", "}", "else", "{", "if", "(", "$", "serialised", "instanceof", "DBField", ")", "{", "$", "serialised", "=", "$", "serialised", "->", "getSchemaValue", "(", ")", ";", "}", "// Replace node with serialised value", "$", "output", "[", "'node'", "]", "=", "$", "serialised", ";", "}", "// Replace children with serialised elements", "$", "output", "[", "'children'", "]", "=", "[", "]", ";", "foreach", "(", "$", "data", "[", "'children'", "]", "as", "$", "child", ")", "{", "$", "output", "[", "'children'", "]", "[", "]", "=", "$", "this", "->", "getSubtreeAsArray", "(", "$", "child", ",", "$", "serialiseEval", ")", ";", "}", "return", "$", "output", ";", "}" ]
Return sub-tree as json array @param array $data @param callable $serialiseEval A callback that takes a DataObject as a single parameter, and should return an array containing a simple array representation. This result will replace the 'node' property at each point in the tree. @return mixed|string
[ "Return", "sub", "-", "tree", "as", "json", "array" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L360-L393
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.getSubtree
protected function getSubtree($node, $depth = 0) { // Check if this node is limited due to child count $numChildren = $this->getNumChildren($node); $limited = $this->isNodeLimited($node, $numChildren); // Build root rode $expanded = $this->isExpanded($node); $opened = $this->isTreeOpened($node); $count = ($limited && $numChildren > $this->getMaxChildNodes()) ? 0 : $numChildren; $output = [ 'node' => $node, 'marked' => $this->isMarked($node), 'expanded' => $expanded, 'opened' => $opened, 'depth' => $depth, 'count' => $count, // Count of DB children 'limited' => $limited, // Flag whether 'items' has been limited 'children' => [], // Children to return in this request ]; // Don't iterate children if past limit // or not expanded (requires subsequent request to get) if ($limited || !$expanded) { return $output; } // Get children $children = $this->getChildren($node); foreach ($children as $child) { // Recurse if ($this->isMarked($child)) { $output['children'][] = $this->getSubtree($child, $depth + 1); } } return $output; }
php
protected function getSubtree($node, $depth = 0) { // Check if this node is limited due to child count $numChildren = $this->getNumChildren($node); $limited = $this->isNodeLimited($node, $numChildren); // Build root rode $expanded = $this->isExpanded($node); $opened = $this->isTreeOpened($node); $count = ($limited && $numChildren > $this->getMaxChildNodes()) ? 0 : $numChildren; $output = [ 'node' => $node, 'marked' => $this->isMarked($node), 'expanded' => $expanded, 'opened' => $opened, 'depth' => $depth, 'count' => $count, // Count of DB children 'limited' => $limited, // Flag whether 'items' has been limited 'children' => [], // Children to return in this request ]; // Don't iterate children if past limit // or not expanded (requires subsequent request to get) if ($limited || !$expanded) { return $output; } // Get children $children = $this->getChildren($node); foreach ($children as $child) { // Recurse if ($this->isMarked($child)) { $output['children'][] = $this->getSubtree($child, $depth + 1); } } return $output; }
[ "protected", "function", "getSubtree", "(", "$", "node", ",", "$", "depth", "=", "0", ")", "{", "// Check if this node is limited due to child count", "$", "numChildren", "=", "$", "this", "->", "getNumChildren", "(", "$", "node", ")", ";", "$", "limited", "=", "$", "this", "->", "isNodeLimited", "(", "$", "node", ",", "$", "numChildren", ")", ";", "// Build root rode", "$", "expanded", "=", "$", "this", "->", "isExpanded", "(", "$", "node", ")", ";", "$", "opened", "=", "$", "this", "->", "isTreeOpened", "(", "$", "node", ")", ";", "$", "count", "=", "(", "$", "limited", "&&", "$", "numChildren", ">", "$", "this", "->", "getMaxChildNodes", "(", ")", ")", "?", "0", ":", "$", "numChildren", ";", "$", "output", "=", "[", "'node'", "=>", "$", "node", ",", "'marked'", "=>", "$", "this", "->", "isMarked", "(", "$", "node", ")", ",", "'expanded'", "=>", "$", "expanded", ",", "'opened'", "=>", "$", "opened", ",", "'depth'", "=>", "$", "depth", ",", "'count'", "=>", "$", "count", ",", "// Count of DB children", "'limited'", "=>", "$", "limited", ",", "// Flag whether 'items' has been limited", "'children'", "=>", "[", "]", ",", "// Children to return in this request", "]", ";", "// Don't iterate children if past limit", "// or not expanded (requires subsequent request to get)", "if", "(", "$", "limited", "||", "!", "$", "expanded", ")", "{", "return", "$", "output", ";", "}", "// Get children", "$", "children", "=", "$", "this", "->", "getChildren", "(", "$", "node", ")", ";", "foreach", "(", "$", "children", "as", "$", "child", ")", "{", "// Recurse", "if", "(", "$", "this", "->", "isMarked", "(", "$", "child", ")", ")", "{", "$", "output", "[", "'children'", "]", "[", "]", "=", "$", "this", "->", "getSubtree", "(", "$", "child", ",", "$", "depth", "+", "1", ")", ";", "}", "}", "return", "$", "output", ";", "}" ]
Get tree data for node @param DataObject $node @param int $depth @return array|string
[ "Get", "tree", "data", "for", "node" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L402-L438
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.markClosed
public function markClosed(DataObject $node) { $id = $node->ID ?: 0; $this->markedNodes[$id] = $node; unset($this->treeOpened[$id]); return $this; }
php
public function markClosed(DataObject $node) { $id = $node->ID ?: 0; $this->markedNodes[$id] = $node; unset($this->treeOpened[$id]); return $this; }
[ "public", "function", "markClosed", "(", "DataObject", "$", "node", ")", "{", "$", "id", "=", "$", "node", "->", "ID", "?", ":", "0", ";", "$", "this", "->", "markedNodes", "[", "$", "id", "]", "=", "$", "node", ";", "unset", "(", "$", "this", "->", "treeOpened", "[", "$", "id", "]", ")", ";", "return", "$", "this", ";", "}" ]
Mark this DataObject's tree as closed. @param DataObject $node @return $this
[ "Mark", "this", "DataObject", "s", "tree", "as", "closed", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L730-L736
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.isExpanded
public function isExpanded(DataObject $node) { $id = $node->ID ?: 0; return !empty($this->expanded[$id]); }
php
public function isExpanded(DataObject $node) { $id = $node->ID ?: 0; return !empty($this->expanded[$id]); }
[ "public", "function", "isExpanded", "(", "DataObject", "$", "node", ")", "{", "$", "id", "=", "$", "node", "->", "ID", "?", ":", "0", ";", "return", "!", "empty", "(", "$", "this", "->", "expanded", "[", "$", "id", "]", ")", ";", "}" ]
Check if this DataObject is expanded. An expanded object has had it's children iterated through. @param DataObject $node @return bool
[ "Check", "if", "this", "DataObject", "is", "expanded", ".", "An", "expanded", "object", "has", "had", "it", "s", "children", "iterated", "through", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L757-L761
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.isTreeOpened
public function isTreeOpened(DataObject $node) { $id = $node->ID ?: 0; return !empty($this->treeOpened[$id]); }
php
public function isTreeOpened(DataObject $node) { $id = $node->ID ?: 0; return !empty($this->treeOpened[$id]); }
[ "public", "function", "isTreeOpened", "(", "DataObject", "$", "node", ")", "{", "$", "id", "=", "$", "node", "->", "ID", "?", ":", "0", ";", "return", "!", "empty", "(", "$", "this", "->", "treeOpened", "[", "$", "id", "]", ")", ";", "}" ]
Check if this DataObject's tree is opened. This is an expanded node which also should have children visually shown. @param DataObject $node @return bool
[ "Check", "if", "this", "DataObject", "s", "tree", "is", "opened", ".", "This", "is", "an", "expanded", "node", "which", "also", "should", "have", "children", "visually", "shown", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L770-L774
train
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
MarkedSet.isNodeLimited
protected function isNodeLimited(DataObject $node, $count = null) { // Singleton root node isn't limited if (!$node->ID) { return false; } // Check if limiting is enabled first if (!$this->getLimitingEnabled()) { return false; } // Count children for this node and compare to max if (!isset($count)) { $count = $this->getNumChildren($node); } return $count > $this->getMaxChildNodes(); }
php
protected function isNodeLimited(DataObject $node, $count = null) { // Singleton root node isn't limited if (!$node->ID) { return false; } // Check if limiting is enabled first if (!$this->getLimitingEnabled()) { return false; } // Count children for this node and compare to max if (!isset($count)) { $count = $this->getNumChildren($node); } return $count > $this->getMaxChildNodes(); }
[ "protected", "function", "isNodeLimited", "(", "DataObject", "$", "node", ",", "$", "count", "=", "null", ")", "{", "// Singleton root node isn't limited", "if", "(", "!", "$", "node", "->", "ID", ")", "{", "return", "false", ";", "}", "// Check if limiting is enabled first", "if", "(", "!", "$", "this", "->", "getLimitingEnabled", "(", ")", ")", "{", "return", "false", ";", "}", "// Count children for this node and compare to max", "if", "(", "!", "isset", "(", "$", "count", ")", ")", "{", "$", "count", "=", "$", "this", "->", "getNumChildren", "(", "$", "node", ")", ";", "}", "return", "$", "count", ">", "$", "this", "->", "getMaxChildNodes", "(", ")", ";", "}" ]
Check if this node has too many children @param DataObject|Hierarchy $node @param int $count Children count (if already calculated) @return bool
[ "Check", "if", "this", "node", "has", "too", "many", "children" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Hierarchy/MarkedSet.php#L783-L800
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.getInternalPlugins
public function getInternalPlugins() { // Return only plugins with no custom url $plugins = []; foreach ($this->getPlugins() as $name => $url) { if (empty($url)) { $plugins[] = $name; } } return $plugins; }
php
public function getInternalPlugins() { // Return only plugins with no custom url $plugins = []; foreach ($this->getPlugins() as $name => $url) { if (empty($url)) { $plugins[] = $name; } } return $plugins; }
[ "public", "function", "getInternalPlugins", "(", ")", "{", "// Return only plugins with no custom url", "$", "plugins", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getPlugins", "(", ")", "as", "$", "name", "=>", "$", "url", ")", "{", "if", "(", "empty", "(", "$", "url", ")", ")", "{", "$", "plugins", "[", "]", "=", "$", "name", ";", "}", "}", "return", "$", "plugins", ";", "}" ]
Get list of plugins without custom locations, which is the set of plugins which can be loaded via the standard plugin path, and could potentially be minified @return array
[ "Get", "list", "of", "plugins", "without", "custom", "locations", "which", "is", "the", "set", "of", "plugins", "which", "can", "be", "loaded", "via", "the", "standard", "plugin", "path", "and", "could", "potentially", "be", "minified" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L454-L464
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.setButtonsForLine
public function setButtonsForLine($line, $buttons) { if (func_num_args() > 2) { $buttons = func_get_args(); array_shift($buttons); } $this->buttons[$line] = is_array($buttons) ? $buttons : array($buttons); return $this; }
php
public function setButtonsForLine($line, $buttons) { if (func_num_args() > 2) { $buttons = func_get_args(); array_shift($buttons); } $this->buttons[$line] = is_array($buttons) ? $buttons : array($buttons); return $this; }
[ "public", "function", "setButtonsForLine", "(", "$", "line", ",", "$", "buttons", ")", "{", "if", "(", "func_num_args", "(", ")", ">", "2", ")", "{", "$", "buttons", "=", "func_get_args", "(", ")", ";", "array_shift", "(", "$", "buttons", ")", ";", "}", "$", "this", "->", "buttons", "[", "$", "line", "]", "=", "is_array", "(", "$", "buttons", ")", "?", "$", "buttons", ":", "array", "(", "$", "buttons", ")", ";", "return", "$", "this", ";", "}" ]
Totally re-set the buttons on a given line @param int $line The line number to redefine, from 1 to 3 @param string $buttons,... A string or several strings, or a single array of strings. The button names to assign to this line. @return $this
[ "Totally", "re", "-", "set", "the", "buttons", "on", "a", "given", "line" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L484-L492
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.modifyButtons
protected function modifyButtons($name, $offset, $del = 0, $add = null) { foreach ($this->buttons as &$buttons) { if (($idx = array_search($name, $buttons)) !== false) { if ($add) { array_splice($buttons, $idx + $offset, $del, $add); } else { array_splice($buttons, $idx + $offset, $del); } return true; } } return false; }
php
protected function modifyButtons($name, $offset, $del = 0, $add = null) { foreach ($this->buttons as &$buttons) { if (($idx = array_search($name, $buttons)) !== false) { if ($add) { array_splice($buttons, $idx + $offset, $del, $add); } else { array_splice($buttons, $idx + $offset, $del); } return true; } } return false; }
[ "protected", "function", "modifyButtons", "(", "$", "name", ",", "$", "offset", ",", "$", "del", "=", "0", ",", "$", "add", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "buttons", "as", "&", "$", "buttons", ")", "{", "if", "(", "(", "$", "idx", "=", "array_search", "(", "$", "name", ",", "$", "buttons", ")", ")", "!==", "false", ")", "{", "if", "(", "$", "add", ")", "{", "array_splice", "(", "$", "buttons", ",", "$", "idx", "+", "$", "offset", ",", "$", "del", ",", "$", "add", ")", ";", "}", "else", "{", "array_splice", "(", "$", "buttons", ",", "$", "idx", "+", "$", "offset", ",", "$", "del", ")", ";", "}", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Internal function for adding and removing buttons related to another button @param string $name The name of the button to modify @param int $offset The offset relative to that button to perform an array_splice at. 0 for before $name, 1 for after. @param int $del The number of buttons to remove at the position given by index(string) + offset @param mixed $add An array or single item to insert at the position given by index(string) + offset, or null for no insertion @return bool True if $name matched a button, false otherwise
[ "Internal", "function", "for", "adding", "and", "removing", "buttons", "related", "to", "another", "button" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L526-L539
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.removeButtons
public function removeButtons($buttons) { if (func_num_args() > 1) { $buttons = func_get_args(); } if (!is_array($buttons)) { $buttons = [$buttons]; } foreach ($buttons as $button) { $this->modifyButtons($button, 0, 1); } }
php
public function removeButtons($buttons) { if (func_num_args() > 1) { $buttons = func_get_args(); } if (!is_array($buttons)) { $buttons = [$buttons]; } foreach ($buttons as $button) { $this->modifyButtons($button, 0, 1); } }
[ "public", "function", "removeButtons", "(", "$", "buttons", ")", "{", "if", "(", "func_num_args", "(", ")", ">", "1", ")", "{", "$", "buttons", "=", "func_get_args", "(", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "buttons", ")", ")", "{", "$", "buttons", "=", "[", "$", "buttons", "]", ";", "}", "foreach", "(", "$", "buttons", "as", "$", "button", ")", "{", "$", "this", "->", "modifyButtons", "(", "$", "button", ",", "0", ",", "1", ")", ";", "}", "}" ]
Remove the first occurance of buttons @param string $buttons,... one or more strings - the name of the buttons to remove
[ "Remove", "the", "first", "occurance", "of", "buttons" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L583-L594
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.getEditorCSS
protected function getEditorCSS() { $editor = []; $resourceLoader = ModuleResourceLoader::singleton(); foreach ($this->getContentCSS() as $contentCSS) { $editor[] = $resourceLoader->resolveURL($contentCSS); } return $editor; }
php
protected function getEditorCSS() { $editor = []; $resourceLoader = ModuleResourceLoader::singleton(); foreach ($this->getContentCSS() as $contentCSS) { $editor[] = $resourceLoader->resolveURL($contentCSS); } return $editor; }
[ "protected", "function", "getEditorCSS", "(", ")", "{", "$", "editor", "=", "[", "]", ";", "$", "resourceLoader", "=", "ModuleResourceLoader", "::", "singleton", "(", ")", ";", "foreach", "(", "$", "this", "->", "getContentCSS", "(", ")", "as", "$", "contentCSS", ")", "{", "$", "editor", "[", "]", "=", "$", "resourceLoader", "->", "resolveURL", "(", "$", "contentCSS", ")", ";", "}", "return", "$", "editor", ";", "}" ]
Get location of all editor.css files. All resource specifiers are resolved to urls. @return array
[ "Get", "location", "of", "all", "editor", ".", "css", "files", ".", "All", "resource", "specifiers", "are", "resolved", "to", "urls", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L674-L682
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.getContentCSS
public function getContentCSS() { // Prioritise instance specific content if (isset($this->contentCSS)) { return $this->contentCSS; } // Add standard editor.css $editor = []; $editorCSSFiles = $this->config()->get('editor_css'); if ($editorCSSFiles) { foreach ($editorCSSFiles as $editorCSS) { $editor[] = $editorCSS; } } // Themed editor.css $themes = HTMLEditorConfig::getThemes() ?: SSViewer::get_themes(); $themedEditor = ThemeResourceLoader::inst()->findThemedCSS('editor', $themes); if ($themedEditor) { $editor[] = $themedEditor; } return $editor; }
php
public function getContentCSS() { // Prioritise instance specific content if (isset($this->contentCSS)) { return $this->contentCSS; } // Add standard editor.css $editor = []; $editorCSSFiles = $this->config()->get('editor_css'); if ($editorCSSFiles) { foreach ($editorCSSFiles as $editorCSS) { $editor[] = $editorCSS; } } // Themed editor.css $themes = HTMLEditorConfig::getThemes() ?: SSViewer::get_themes(); $themedEditor = ThemeResourceLoader::inst()->findThemedCSS('editor', $themes); if ($themedEditor) { $editor[] = $themedEditor; } return $editor; }
[ "public", "function", "getContentCSS", "(", ")", "{", "// Prioritise instance specific content", "if", "(", "isset", "(", "$", "this", "->", "contentCSS", ")", ")", "{", "return", "$", "this", "->", "contentCSS", ";", "}", "// Add standard editor.css", "$", "editor", "=", "[", "]", ";", "$", "editorCSSFiles", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'editor_css'", ")", ";", "if", "(", "$", "editorCSSFiles", ")", "{", "foreach", "(", "$", "editorCSSFiles", "as", "$", "editorCSS", ")", "{", "$", "editor", "[", "]", "=", "$", "editorCSS", ";", "}", "}", "// Themed editor.css", "$", "themes", "=", "HTMLEditorConfig", "::", "getThemes", "(", ")", "?", ":", "SSViewer", "::", "get_themes", "(", ")", ";", "$", "themedEditor", "=", "ThemeResourceLoader", "::", "inst", "(", ")", "->", "findThemedCSS", "(", "'editor'", ",", "$", "themes", ")", ";", "if", "(", "$", "themedEditor", ")", "{", "$", "editor", "[", "]", "=", "$", "themedEditor", ";", "}", "return", "$", "editor", ";", "}" ]
Get list of resource paths to css files. Will default to `editor_css` config, as well as any themed `editor.css` files. Use setContentCSS() to override. @return string[]
[ "Get", "list", "of", "resource", "paths", "to", "css", "files", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L692-L715
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.get_tinymce_lang
public static function get_tinymce_lang() { $lang = static::config()->get('tinymce_lang'); $locale = i18n::get_locale(); if (isset($lang[$locale])) { return $lang[$locale]; } return 'en'; }
php
public static function get_tinymce_lang() { $lang = static::config()->get('tinymce_lang'); $locale = i18n::get_locale(); if (isset($lang[$locale])) { return $lang[$locale]; } return 'en'; }
[ "public", "static", "function", "get_tinymce_lang", "(", ")", "{", "$", "lang", "=", "static", "::", "config", "(", ")", "->", "get", "(", "'tinymce_lang'", ")", ";", "$", "locale", "=", "i18n", "::", "get_locale", "(", ")", ";", "if", "(", "isset", "(", "$", "lang", "[", "$", "locale", "]", ")", ")", "{", "return", "$", "lang", "[", "$", "locale", "]", ";", "}", "return", "'en'", ";", "}" ]
Get the current tinyMCE language @return string Language
[ "Get", "the", "current", "tinyMCE", "language" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L766-L774
train
silverstripe/silverstripe-framework
src/Forms/HTMLEditor/TinyMCEConfig.php
TinyMCEConfig.getTinyMCEResource
public function getTinyMCEResource() { $configDir = static::config()->get('base_dir'); if ($configDir) { return ModuleResourceLoader::singleton()->resolveResource($configDir); } throw new Exception(sprintf( 'If the silverstripe/admin module is not installed you must set the TinyMCE path in %s.base_dir', __CLASS__ )); }
php
public function getTinyMCEResource() { $configDir = static::config()->get('base_dir'); if ($configDir) { return ModuleResourceLoader::singleton()->resolveResource($configDir); } throw new Exception(sprintf( 'If the silverstripe/admin module is not installed you must set the TinyMCE path in %s.base_dir', __CLASS__ )); }
[ "public", "function", "getTinyMCEResource", "(", ")", "{", "$", "configDir", "=", "static", "::", "config", "(", ")", "->", "get", "(", "'base_dir'", ")", ";", "if", "(", "$", "configDir", ")", "{", "return", "ModuleResourceLoader", "::", "singleton", "(", ")", "->", "resolveResource", "(", "$", "configDir", ")", ";", "}", "throw", "new", "Exception", "(", "sprintf", "(", "'If the silverstripe/admin module is not installed you must set the TinyMCE path in %s.base_dir'", ",", "__CLASS__", ")", ")", ";", "}" ]
Get resource root for TinyMCE, either as a string or ModuleResource instance Path will be relative to BASE_PATH if string. @return ModuleResource|string @throws Exception
[ "Get", "resource", "root", "for", "TinyMCE", "either", "as", "a", "string", "or", "ModuleResource", "instance", "Path", "will", "be", "relative", "to", "BASE_PATH", "if", "string", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/HTMLEditor/TinyMCEConfig.php#L816-L827
train
silverstripe/silverstripe-framework
src/Control/HTTPApplication.php
HTTPApplication.handle
public function handle(HTTPRequest $request) { $flush = array_key_exists('flush', $request->getVars()) || ($request->getURL() === 'dev/build'); // Ensure boot is invoked return $this->execute($request, function (HTTPRequest $request) { return Director::singleton()->handleRequest($request); }, $flush); }
php
public function handle(HTTPRequest $request) { $flush = array_key_exists('flush', $request->getVars()) || ($request->getURL() === 'dev/build'); // Ensure boot is invoked return $this->execute($request, function (HTTPRequest $request) { return Director::singleton()->handleRequest($request); }, $flush); }
[ "public", "function", "handle", "(", "HTTPRequest", "$", "request", ")", "{", "$", "flush", "=", "array_key_exists", "(", "'flush'", ",", "$", "request", "->", "getVars", "(", ")", ")", "||", "(", "$", "request", "->", "getURL", "(", ")", "===", "'dev/build'", ")", ";", "// Ensure boot is invoked", "return", "$", "this", "->", "execute", "(", "$", "request", ",", "function", "(", "HTTPRequest", "$", "request", ")", "{", "return", "Director", "::", "singleton", "(", ")", "->", "handleRequest", "(", "$", "request", ")", ";", "}", ",", "$", "flush", ")", ";", "}" ]
Handle the given HTTP request @param HTTPRequest $request @return HTTPResponse
[ "Handle", "the", "given", "HTTP", "request" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPApplication.php#L42-L50
train
silverstripe/silverstripe-framework
src/Control/HTTPApplication.php
HTTPApplication.execute
public function execute(HTTPRequest $request, callable $callback, $flush = false) { try { return $this->callMiddleware($request, function ($request) use ($callback, $flush) { // Pre-request boot $this->getKernel()->boot($flush); return call_user_func($callback, $request); }); } catch (HTTPResponse_Exception $ex) { return $ex->getResponse(); } finally { $this->getKernel()->shutdown(); } }
php
public function execute(HTTPRequest $request, callable $callback, $flush = false) { try { return $this->callMiddleware($request, function ($request) use ($callback, $flush) { // Pre-request boot $this->getKernel()->boot($flush); return call_user_func($callback, $request); }); } catch (HTTPResponse_Exception $ex) { return $ex->getResponse(); } finally { $this->getKernel()->shutdown(); } }
[ "public", "function", "execute", "(", "HTTPRequest", "$", "request", ",", "callable", "$", "callback", ",", "$", "flush", "=", "false", ")", "{", "try", "{", "return", "$", "this", "->", "callMiddleware", "(", "$", "request", ",", "function", "(", "$", "request", ")", "use", "(", "$", "callback", ",", "$", "flush", ")", "{", "// Pre-request boot", "$", "this", "->", "getKernel", "(", ")", "->", "boot", "(", "$", "flush", ")", ";", "return", "call_user_func", "(", "$", "callback", ",", "$", "request", ")", ";", "}", ")", ";", "}", "catch", "(", "HTTPResponse_Exception", "$", "ex", ")", "{", "return", "$", "ex", "->", "getResponse", "(", ")", ";", "}", "finally", "{", "$", "this", "->", "getKernel", "(", ")", "->", "shutdown", "(", ")", ";", "}", "}" ]
Safely boot the application and execute the given main action @param HTTPRequest $request @param callable $callback @param bool $flush @return HTTPResponse
[ "Safely", "boot", "the", "application", "and", "execute", "the", "given", "main", "action" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/HTTPApplication.php#L60-L73
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.destroy
public function destroy($removeCookie = true) { if (session_id()) { if ($removeCookie) { $path = $this->config()->get('cookie_path') ?: Director::baseURL(); $domain = $this->config()->get('cookie_domain'); $secure = $this->config()->get('cookie_secure'); Cookie::force_expiry(session_name(), $path, $domain, $secure, true); } session_destroy(); } // Clean up the superglobal - session_destroy does not do it. // http://nz1.php.net/manual/en/function.session-destroy.php unset($_SESSION); $this->data = null; }
php
public function destroy($removeCookie = true) { if (session_id()) { if ($removeCookie) { $path = $this->config()->get('cookie_path') ?: Director::baseURL(); $domain = $this->config()->get('cookie_domain'); $secure = $this->config()->get('cookie_secure'); Cookie::force_expiry(session_name(), $path, $domain, $secure, true); } session_destroy(); } // Clean up the superglobal - session_destroy does not do it. // http://nz1.php.net/manual/en/function.session-destroy.php unset($_SESSION); $this->data = null; }
[ "public", "function", "destroy", "(", "$", "removeCookie", "=", "true", ")", "{", "if", "(", "session_id", "(", ")", ")", "{", "if", "(", "$", "removeCookie", ")", "{", "$", "path", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'cookie_path'", ")", "?", ":", "Director", "::", "baseURL", "(", ")", ";", "$", "domain", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'cookie_domain'", ")", ";", "$", "secure", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'cookie_secure'", ")", ";", "Cookie", "::", "force_expiry", "(", "session_name", "(", ")", ",", "$", "path", ",", "$", "domain", ",", "$", "secure", ",", "true", ")", ";", "}", "session_destroy", "(", ")", ";", "}", "// Clean up the superglobal - session_destroy does not do it.", "// http://nz1.php.net/manual/en/function.session-destroy.php", "unset", "(", "$", "_SESSION", ")", ";", "$", "this", "->", "data", "=", "null", ";", "}" ]
Destroy this session @param bool $removeCookie
[ "Destroy", "this", "session" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L357-L372
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.set
public function set($name, $val) { $var = &$this->nestedValueRef($name, $this->data); // Mark changed if ($var !== $val) { $var = $val; $this->markChanged($name); } return $this; }
php
public function set($name, $val) { $var = &$this->nestedValueRef($name, $this->data); // Mark changed if ($var !== $val) { $var = $val; $this->markChanged($name); } return $this; }
[ "public", "function", "set", "(", "$", "name", ",", "$", "val", ")", "{", "$", "var", "=", "&", "$", "this", "->", "nestedValueRef", "(", "$", "name", ",", "$", "this", "->", "data", ")", ";", "// Mark changed", "if", "(", "$", "var", "!==", "$", "val", ")", "{", "$", "var", "=", "$", "val", ";", "$", "this", "->", "markChanged", "(", "$", "name", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set session value @param string $name @param mixed $val @return $this
[ "Set", "session", "value" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L381-L391
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.markChanged
protected function markChanged($name) { $diffVar = &$this->changedData; foreach (explode('.', $name) as $namePart) { if (!isset($diffVar[$namePart])) { $diffVar[$namePart] = []; } $diffVar = &$diffVar[$namePart]; // Already diffed if ($diffVar === true) { return; } } // Mark changed $diffVar = true; }
php
protected function markChanged($name) { $diffVar = &$this->changedData; foreach (explode('.', $name) as $namePart) { if (!isset($diffVar[$namePart])) { $diffVar[$namePart] = []; } $diffVar = &$diffVar[$namePart]; // Already diffed if ($diffVar === true) { return; } } // Mark changed $diffVar = true; }
[ "protected", "function", "markChanged", "(", "$", "name", ")", "{", "$", "diffVar", "=", "&", "$", "this", "->", "changedData", ";", "foreach", "(", "explode", "(", "'.'", ",", "$", "name", ")", "as", "$", "namePart", ")", "{", "if", "(", "!", "isset", "(", "$", "diffVar", "[", "$", "namePart", "]", ")", ")", "{", "$", "diffVar", "[", "$", "namePart", "]", "=", "[", "]", ";", "}", "$", "diffVar", "=", "&", "$", "diffVar", "[", "$", "namePart", "]", ";", "// Already diffed", "if", "(", "$", "diffVar", "===", "true", ")", "{", "return", ";", "}", "}", "// Mark changed", "$", "diffVar", "=", "true", ";", "}" ]
Mark key as changed @internal @param string $name
[ "Mark", "key", "as", "changed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L399-L415
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.addToArray
public function addToArray($name, $val) { $names = explode('.', $name); // We still want to do this even if we have strict path checking for legacy code $var = &$this->data; $diffVar = &$this->changedData; foreach ($names as $n) { $var = &$var[$n]; $diffVar = &$diffVar[$n]; } $var[] = $val; $diffVar[sizeof($var) - 1] = $val; }
php
public function addToArray($name, $val) { $names = explode('.', $name); // We still want to do this even if we have strict path checking for legacy code $var = &$this->data; $diffVar = &$this->changedData; foreach ($names as $n) { $var = &$var[$n]; $diffVar = &$diffVar[$n]; } $var[] = $val; $diffVar[sizeof($var) - 1] = $val; }
[ "public", "function", "addToArray", "(", "$", "name", ",", "$", "val", ")", "{", "$", "names", "=", "explode", "(", "'.'", ",", "$", "name", ")", ";", "// We still want to do this even if we have strict path checking for legacy code", "$", "var", "=", "&", "$", "this", "->", "data", ";", "$", "diffVar", "=", "&", "$", "this", "->", "changedData", ";", "foreach", "(", "$", "names", "as", "$", "n", ")", "{", "$", "var", "=", "&", "$", "var", "[", "$", "n", "]", ";", "$", "diffVar", "=", "&", "$", "diffVar", "[", "$", "n", "]", ";", "}", "$", "var", "[", "]", "=", "$", "val", ";", "$", "diffVar", "[", "sizeof", "(", "$", "var", ")", "-", "1", "]", "=", "$", "val", ";", "}" ]
Merge value with array @param string $name @param mixed $val
[ "Merge", "value", "with", "array" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L423-L438
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.clear
public function clear($name) { // Get var by path $var = $this->nestedValue($name, $this->data); // Unset var if ($var !== null) { // Unset parent key $parentParts = explode('.', $name); $basePart = array_pop($parentParts); if ($parentParts) { $parent = &$this->nestedValueRef(implode('.', $parentParts), $this->data); unset($parent[$basePart]); } else { unset($this->data[$name]); } $this->markChanged($name); } return $this; }
php
public function clear($name) { // Get var by path $var = $this->nestedValue($name, $this->data); // Unset var if ($var !== null) { // Unset parent key $parentParts = explode('.', $name); $basePart = array_pop($parentParts); if ($parentParts) { $parent = &$this->nestedValueRef(implode('.', $parentParts), $this->data); unset($parent[$basePart]); } else { unset($this->data[$name]); } $this->markChanged($name); } return $this; }
[ "public", "function", "clear", "(", "$", "name", ")", "{", "// Get var by path", "$", "var", "=", "$", "this", "->", "nestedValue", "(", "$", "name", ",", "$", "this", "->", "data", ")", ";", "// Unset var", "if", "(", "$", "var", "!==", "null", ")", "{", "// Unset parent key", "$", "parentParts", "=", "explode", "(", "'.'", ",", "$", "name", ")", ";", "$", "basePart", "=", "array_pop", "(", "$", "parentParts", ")", ";", "if", "(", "$", "parentParts", ")", "{", "$", "parent", "=", "&", "$", "this", "->", "nestedValueRef", "(", "implode", "(", "'.'", ",", "$", "parentParts", ")", ",", "$", "this", "->", "data", ")", ";", "unset", "(", "$", "parent", "[", "$", "basePart", "]", ")", ";", "}", "else", "{", "unset", "(", "$", "this", "->", "data", "[", "$", "name", "]", ")", ";", "}", "$", "this", "->", "markChanged", "(", "$", "name", ")", ";", "}", "return", "$", "this", ";", "}" ]
Clear session value @param string $name @return $this
[ "Clear", "session", "value" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L457-L476
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.clearAll
public function clearAll() { if ($this->data && is_array($this->data)) { foreach (array_keys($this->data) as $key) { $this->clear($key); } } }
php
public function clearAll() { if ($this->data && is_array($this->data)) { foreach (array_keys($this->data) as $key) { $this->clear($key); } } }
[ "public", "function", "clearAll", "(", ")", "{", "if", "(", "$", "this", "->", "data", "&&", "is_array", "(", "$", "this", "->", "data", ")", ")", "{", "foreach", "(", "array_keys", "(", "$", "this", "->", "data", ")", "as", "$", "key", ")", "{", "$", "this", "->", "clear", "(", "$", "key", ")", ";", "}", "}", "}" ]
Clear all values
[ "Clear", "all", "values" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L481-L488
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.&
protected function &nestedValueRef($name, &$source) { // Find var to change $var = &$source; foreach (explode('.', $name) as $namePart) { if (!isset($var)) { $var = []; } if (!isset($var[$namePart])) { $var[$namePart] = null; } $var = &$var[$namePart]; } return $var; }
php
protected function &nestedValueRef($name, &$source) { // Find var to change $var = &$source; foreach (explode('.', $name) as $namePart) { if (!isset($var)) { $var = []; } if (!isset($var[$namePart])) { $var[$namePart] = null; } $var = &$var[$namePart]; } return $var; }
[ "protected", "function", "&", "nestedValueRef", "(", "$", "name", ",", "&", "$", "source", ")", "{", "// Find var to change", "$", "var", "=", "&", "$", "source", ";", "foreach", "(", "explode", "(", "'.'", ",", "$", "name", ")", "as", "$", "namePart", ")", "{", "if", "(", "!", "isset", "(", "$", "var", ")", ")", "{", "$", "var", "=", "[", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "var", "[", "$", "namePart", "]", ")", ")", "{", "$", "var", "[", "$", "namePart", "]", "=", "null", ";", "}", "$", "var", "=", "&", "$", "var", "[", "$", "namePart", "]", ";", "}", "return", "$", "var", ";", "}" ]
Navigate to nested value in source array by name, creating a null placeholder if it doesn't exist. @internal @param string $name @param array $source @return mixed Reference to value in $source
[ "Navigate", "to", "nested", "value", "in", "source", "array", "by", "name", "creating", "a", "null", "placeholder", "if", "it", "doesn", "t", "exist", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L572-L586
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.nestedValue
protected function nestedValue($name, $source) { // Find var to change $var = $source; foreach (explode('.', $name) as $namePart) { if (!isset($var[$namePart])) { return null; } $var = $var[$namePart]; } return $var; }
php
protected function nestedValue($name, $source) { // Find var to change $var = $source; foreach (explode('.', $name) as $namePart) { if (!isset($var[$namePart])) { return null; } $var = $var[$namePart]; } return $var; }
[ "protected", "function", "nestedValue", "(", "$", "name", ",", "$", "source", ")", "{", "// Find var to change", "$", "var", "=", "$", "source", ";", "foreach", "(", "explode", "(", "'.'", ",", "$", "name", ")", "as", "$", "namePart", ")", "{", "if", "(", "!", "isset", "(", "$", "var", "[", "$", "namePart", "]", ")", ")", "{", "return", "null", ";", "}", "$", "var", "=", "$", "var", "[", "$", "namePart", "]", ";", "}", "return", "$", "var", ";", "}" ]
Navigate to nested value in source array by name, returning null if it doesn't exist. @internal @param string $name @param array $source @return mixed Value in array in $source
[ "Navigate", "to", "nested", "value", "in", "source", "array", "by", "name", "returning", "null", "if", "it", "doesn", "t", "exist", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L597-L608
train
silverstripe/silverstripe-framework
src/Control/Session.php
Session.recursivelyApplyChanges
protected function recursivelyApplyChanges($changes, $source, &$destination) { $source = $source ?: []; foreach ($changes as $key => $changed) { if ($changed === true) { // Determine if replacement or removal if (array_key_exists($key, $source)) { $destination[$key] = $source[$key]; } else { unset($destination[$key]); } } else { // Recursively apply $destVal = &$this->nestedValueRef($key, $destination); $sourceVal = $this->nestedValue($key, $source); $this->recursivelyApplyChanges($changed, $sourceVal, $destVal); } } }
php
protected function recursivelyApplyChanges($changes, $source, &$destination) { $source = $source ?: []; foreach ($changes as $key => $changed) { if ($changed === true) { // Determine if replacement or removal if (array_key_exists($key, $source)) { $destination[$key] = $source[$key]; } else { unset($destination[$key]); } } else { // Recursively apply $destVal = &$this->nestedValueRef($key, $destination); $sourceVal = $this->nestedValue($key, $source); $this->recursivelyApplyChanges($changed, $sourceVal, $destVal); } } }
[ "protected", "function", "recursivelyApplyChanges", "(", "$", "changes", ",", "$", "source", ",", "&", "$", "destination", ")", "{", "$", "source", "=", "$", "source", "?", ":", "[", "]", ";", "foreach", "(", "$", "changes", "as", "$", "key", "=>", "$", "changed", ")", "{", "if", "(", "$", "changed", "===", "true", ")", "{", "// Determine if replacement or removal", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "source", ")", ")", "{", "$", "destination", "[", "$", "key", "]", "=", "$", "source", "[", "$", "key", "]", ";", "}", "else", "{", "unset", "(", "$", "destination", "[", "$", "key", "]", ")", ";", "}", "}", "else", "{", "// Recursively apply", "$", "destVal", "=", "&", "$", "this", "->", "nestedValueRef", "(", "$", "key", ",", "$", "destination", ")", ";", "$", "sourceVal", "=", "$", "this", "->", "nestedValue", "(", "$", "key", ",", "$", "source", ")", ";", "$", "this", "->", "recursivelyApplyChanges", "(", "$", "changed", ",", "$", "sourceVal", ",", "$", "destVal", ")", ";", "}", "}", "}" ]
Apply all changes using separate keys and data sources and a destination @internal @param array $changes @param array $source @param array $destination
[ "Apply", "all", "changes", "using", "separate", "keys", "and", "data", "sources", "and", "a", "destination" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Session.php#L618-L636
train
silverstripe/silverstripe-framework
src/Core/Startup/ErrorControlChain.php
ErrorControlChain.lastErrorWasFatal
protected function lastErrorWasFatal() { if ($this->lastException) { return true; } $error = error_get_last(); return $error && ($error['type'] & self::$fatal_errors) != 0; }
php
protected function lastErrorWasFatal() { if ($this->lastException) { return true; } $error = error_get_last(); return $error && ($error['type'] & self::$fatal_errors) != 0; }
[ "protected", "function", "lastErrorWasFatal", "(", ")", "{", "if", "(", "$", "this", "->", "lastException", ")", "{", "return", "true", ";", "}", "$", "error", "=", "error_get_last", "(", ")", ";", "return", "$", "error", "&&", "(", "$", "error", "[", "'type'", "]", "&", "self", "::", "$", "fatal_errors", ")", "!=", "0", ";", "}" ]
Return true if the last error was fatal @return boolean
[ "Return", "true", "if", "the", "last", "error", "was", "fatal" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Startup/ErrorControlChain.php#L170-L177
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.recursiveWalk
public function recursiveWalk(callable $callback) { $stack = $this->toArray(); while (!empty($stack)) { /** @var FormField $field */ $field = array_shift($stack); $callback($field); if ($field instanceof CompositeField) { $stack = array_merge($field->getChildren()->toArray(), $stack); } } }
php
public function recursiveWalk(callable $callback) { $stack = $this->toArray(); while (!empty($stack)) { /** @var FormField $field */ $field = array_shift($stack); $callback($field); if ($field instanceof CompositeField) { $stack = array_merge($field->getChildren()->toArray(), $stack); } } }
[ "public", "function", "recursiveWalk", "(", "callable", "$", "callback", ")", "{", "$", "stack", "=", "$", "this", "->", "toArray", "(", ")", ";", "while", "(", "!", "empty", "(", "$", "stack", ")", ")", "{", "/** @var FormField $field */", "$", "field", "=", "array_shift", "(", "$", "stack", ")", ";", "$", "callback", "(", "$", "field", ")", ";", "if", "(", "$", "field", "instanceof", "CompositeField", ")", "{", "$", "stack", "=", "array_merge", "(", "$", "field", "->", "getChildren", "(", ")", "->", "toArray", "(", ")", ",", "$", "stack", ")", ";", "}", "}", "}" ]
Iterate over each field in the current list recursively @param callable $callback
[ "Iterate", "over", "each", "field", "in", "the", "current", "list", "recursively" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L66-L77
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.flattenFields
public function flattenFields() { $fields = []; $this->recursiveWalk(function (FormField $field) use (&$fields) { $fields[] = $field; }); return static::create($fields); }
php
public function flattenFields() { $fields = []; $this->recursiveWalk(function (FormField $field) use (&$fields) { $fields[] = $field; }); return static::create($fields); }
[ "public", "function", "flattenFields", "(", ")", "{", "$", "fields", "=", "[", "]", ";", "$", "this", "->", "recursiveWalk", "(", "function", "(", "FormField", "$", "field", ")", "use", "(", "&", "$", "fields", ")", "{", "$", "fields", "[", "]", "=", "$", "field", ";", "}", ")", ";", "return", "static", "::", "create", "(", "$", "fields", ")", ";", "}" ]
Return a flattened list of all fields @return static
[ "Return", "a", "flattened", "list", "of", "all", "fields" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L84-L91
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.fieldNameError
protected function fieldNameError(FormField $field, $functionName) { if ($this->form) { $errorSuffix = sprintf( " in your '%s' form called '%s'", get_class($this->form), $this->form->getName() ); } else { $errorSuffix = ''; } user_error( sprintf( "%s() I noticed that a field called '%s' appears twice%s", $functionName, $field->getName(), $errorSuffix ), E_USER_ERROR ); }
php
protected function fieldNameError(FormField $field, $functionName) { if ($this->form) { $errorSuffix = sprintf( " in your '%s' form called '%s'", get_class($this->form), $this->form->getName() ); } else { $errorSuffix = ''; } user_error( sprintf( "%s() I noticed that a field called '%s' appears twice%s", $functionName, $field->getName(), $errorSuffix ), E_USER_ERROR ); }
[ "protected", "function", "fieldNameError", "(", "FormField", "$", "field", ",", "$", "functionName", ")", "{", "if", "(", "$", "this", "->", "form", ")", "{", "$", "errorSuffix", "=", "sprintf", "(", "\" in your '%s' form called '%s'\"", ",", "get_class", "(", "$", "this", "->", "form", ")", ",", "$", "this", "->", "form", "->", "getName", "(", ")", ")", ";", "}", "else", "{", "$", "errorSuffix", "=", "''", ";", "}", "user_error", "(", "sprintf", "(", "\"%s() I noticed that a field called '%s' appears twice%s\"", ",", "$", "functionName", ",", "$", "field", "->", "getName", "(", ")", ",", "$", "errorSuffix", ")", ",", "E_USER_ERROR", ")", ";", "}" ]
Trigger an error for duplicate field names @param FormField $field @param $functionName
[ "Trigger", "an", "error", "for", "duplicate", "field", "names" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L156-L177
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.removeFieldFromTab
public function removeFieldFromTab($tabName, $fieldName) { $this->flushFieldsCache(); // Find the tab $tab = $this->findTab($tabName); if ($tab) { $tab->removeByName($fieldName); } return $this; }
php
public function removeFieldFromTab($tabName, $fieldName) { $this->flushFieldsCache(); // Find the tab $tab = $this->findTab($tabName); if ($tab) { $tab->removeByName($fieldName); } return $this; }
[ "public", "function", "removeFieldFromTab", "(", "$", "tabName", ",", "$", "fieldName", ")", "{", "$", "this", "->", "flushFieldsCache", "(", ")", ";", "// Find the tab", "$", "tab", "=", "$", "this", "->", "findTab", "(", "$", "tabName", ")", ";", "if", "(", "$", "tab", ")", "{", "$", "tab", "->", "removeByName", "(", "$", "fieldName", ")", ";", "}", "return", "$", "this", ";", "}" ]
Remove the given field from the given tab in the field. @param string $tabName The name of the tab @param string $fieldName The name of the field @return $this
[ "Remove", "the", "given", "field", "from", "the", "given", "tab", "in", "the", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L297-L308
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.removeByName
public function removeByName($fieldName, $dataFieldOnly = false) { if (!$fieldName) { user_error('FieldList::removeByName() was called with a blank field name.', E_USER_WARNING); } // Handle array syntax if (is_array($fieldName)) { foreach ($fieldName as $field) { $this->removeByName($field, $dataFieldOnly); } return $this; } $this->flushFieldsCache(); foreach ($this as $i => $child) { $childName = $child->getName(); if (!$childName) { $childName = $child->Title(); } if (($childName == $fieldName) && (!$dataFieldOnly || $child->hasData())) { array_splice($this->items, $i, 1); break; } elseif ($child instanceof CompositeField) { $child->removeByName($fieldName, $dataFieldOnly); } } return $this; }
php
public function removeByName($fieldName, $dataFieldOnly = false) { if (!$fieldName) { user_error('FieldList::removeByName() was called with a blank field name.', E_USER_WARNING); } // Handle array syntax if (is_array($fieldName)) { foreach ($fieldName as $field) { $this->removeByName($field, $dataFieldOnly); } return $this; } $this->flushFieldsCache(); foreach ($this as $i => $child) { $childName = $child->getName(); if (!$childName) { $childName = $child->Title(); } if (($childName == $fieldName) && (!$dataFieldOnly || $child->hasData())) { array_splice($this->items, $i, 1); break; } elseif ($child instanceof CompositeField) { $child->removeByName($fieldName, $dataFieldOnly); } } return $this; }
[ "public", "function", "removeByName", "(", "$", "fieldName", ",", "$", "dataFieldOnly", "=", "false", ")", "{", "if", "(", "!", "$", "fieldName", ")", "{", "user_error", "(", "'FieldList::removeByName() was called with a blank field name.'", ",", "E_USER_WARNING", ")", ";", "}", "// Handle array syntax", "if", "(", "is_array", "(", "$", "fieldName", ")", ")", "{", "foreach", "(", "$", "fieldName", "as", "$", "field", ")", "{", "$", "this", "->", "removeByName", "(", "$", "field", ",", "$", "dataFieldOnly", ")", ";", "}", "return", "$", "this", ";", "}", "$", "this", "->", "flushFieldsCache", "(", ")", ";", "foreach", "(", "$", "this", "as", "$", "i", "=>", "$", "child", ")", "{", "$", "childName", "=", "$", "child", "->", "getName", "(", ")", ";", "if", "(", "!", "$", "childName", ")", "{", "$", "childName", "=", "$", "child", "->", "Title", "(", ")", ";", "}", "if", "(", "(", "$", "childName", "==", "$", "fieldName", ")", "&&", "(", "!", "$", "dataFieldOnly", "||", "$", "child", "->", "hasData", "(", ")", ")", ")", "{", "array_splice", "(", "$", "this", "->", "items", ",", "$", "i", ",", "1", ")", ";", "break", ";", "}", "elseif", "(", "$", "child", "instanceof", "CompositeField", ")", "{", "$", "child", "->", "removeByName", "(", "$", "fieldName", ",", "$", "dataFieldOnly", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Remove a field or fields from this FieldList by Name. The field could also be inside a CompositeField. @param string|array $fieldName The name of, or an array with the field(s) or tab(s) @param boolean $dataFieldOnly If this is true, then a field will only be removed if it's a data field. Dataless fields, such as tabs, will be left as-is. @return $this
[ "Remove", "a", "field", "or", "fields", "from", "this", "FieldList", "by", "Name", ".", "The", "field", "could", "also", "be", "inside", "a", "CompositeField", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L345-L375
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.replaceField
public function replaceField($fieldName, $newField, $dataFieldOnly = true) { $this->flushFieldsCache(); foreach ($this as $i => $field) { if ($field->getName() == $fieldName && (!$dataFieldOnly || $field->hasData())) { $this->items[$i] = $newField; return true; } elseif ($field instanceof CompositeField) { if ($field->replaceField($fieldName, $newField)) { return true; } } } return false; }
php
public function replaceField($fieldName, $newField, $dataFieldOnly = true) { $this->flushFieldsCache(); foreach ($this as $i => $field) { if ($field->getName() == $fieldName && (!$dataFieldOnly || $field->hasData())) { $this->items[$i] = $newField; return true; } elseif ($field instanceof CompositeField) { if ($field->replaceField($fieldName, $newField)) { return true; } } } return false; }
[ "public", "function", "replaceField", "(", "$", "fieldName", ",", "$", "newField", ",", "$", "dataFieldOnly", "=", "true", ")", "{", "$", "this", "->", "flushFieldsCache", "(", ")", ";", "foreach", "(", "$", "this", "as", "$", "i", "=>", "$", "field", ")", "{", "if", "(", "$", "field", "->", "getName", "(", ")", "==", "$", "fieldName", "&&", "(", "!", "$", "dataFieldOnly", "||", "$", "field", "->", "hasData", "(", ")", ")", ")", "{", "$", "this", "->", "items", "[", "$", "i", "]", "=", "$", "newField", ";", "return", "true", ";", "}", "elseif", "(", "$", "field", "instanceof", "CompositeField", ")", "{", "if", "(", "$", "field", "->", "replaceField", "(", "$", "fieldName", ",", "$", "newField", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Replace a single field with another. Ignores dataless fields such as Tabs and TabSets @param string $fieldName The name of the field to replace @param FormField $newField The field object to replace with @param boolean $dataFieldOnly If this is true, then a field will only be replaced if it's a data field. Dataless fields, such as tabs, will be not be considered for replacement. @return boolean TRUE field was successfully replaced FALSE field wasn't found, nothing changed
[ "Replace", "a", "single", "field", "with", "another", ".", "Ignores", "dataless", "fields", "such", "as", "Tabs", "and", "TabSets" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L387-L401
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.renameField
public function renameField($fieldName, $newFieldTitle) { $field = $this->dataFieldByName($fieldName); if (!$field) { return false; } $field->setTitle($newFieldTitle); return $field->Title() == $newFieldTitle; }
php
public function renameField($fieldName, $newFieldTitle) { $field = $this->dataFieldByName($fieldName); if (!$field) { return false; } $field->setTitle($newFieldTitle); return $field->Title() == $newFieldTitle; }
[ "public", "function", "renameField", "(", "$", "fieldName", ",", "$", "newFieldTitle", ")", "{", "$", "field", "=", "$", "this", "->", "dataFieldByName", "(", "$", "fieldName", ")", ";", "if", "(", "!", "$", "field", ")", "{", "return", "false", ";", "}", "$", "field", "->", "setTitle", "(", "$", "newFieldTitle", ")", ";", "return", "$", "field", "->", "Title", "(", ")", "==", "$", "newFieldTitle", ";", "}" ]
Rename the title of a particular field name in this set. @param string $fieldName Name of field to rename title of @param string $newFieldTitle New title of field @return boolean
[ "Rename", "the", "title", "of", "a", "particular", "field", "name", "in", "this", "set", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L410-L420
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.findTab
public function findTab($tabName) { $parts = explode('.', $tabName); $last_idx = count($parts) - 1; $currentPointer = $this; foreach ($parts as $k => $part) { $parentPointer = $currentPointer; /** @var FormField $currentPointer */ $currentPointer = $currentPointer->fieldByName($part); } return $currentPointer; }
php
public function findTab($tabName) { $parts = explode('.', $tabName); $last_idx = count($parts) - 1; $currentPointer = $this; foreach ($parts as $k => $part) { $parentPointer = $currentPointer; /** @var FormField $currentPointer */ $currentPointer = $currentPointer->fieldByName($part); } return $currentPointer; }
[ "public", "function", "findTab", "(", "$", "tabName", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "tabName", ")", ";", "$", "last_idx", "=", "count", "(", "$", "parts", ")", "-", "1", ";", "$", "currentPointer", "=", "$", "this", ";", "foreach", "(", "$", "parts", "as", "$", "k", "=>", "$", "part", ")", "{", "$", "parentPointer", "=", "$", "currentPointer", ";", "/** @var FormField $currentPointer */", "$", "currentPointer", "=", "$", "currentPointer", "->", "fieldByName", "(", "$", "part", ")", ";", "}", "return", "$", "currentPointer", ";", "}" ]
Returns the specified tab object, if it exists @param string $tabName The tab to return, in the form "Tab.Subtab.Subsubtab". @return Tab|null The found or null
[ "Returns", "the", "specified", "tab", "object", "if", "it", "exists" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L442-L456
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.findOrMakeTab
public function findOrMakeTab($tabName, $title = null) { $parts = explode('.', $tabName); $last_idx = count($parts) - 1; // We could have made this recursive, but I've chosen to keep all the logic code within FieldList rather than // add it to TabSet and Tab too. $currentPointer = $this; foreach ($parts as $k => $part) { $parentPointer = $currentPointer; /** @var FormField $currentPointer */ $currentPointer = $currentPointer->fieldByName($part); // Create any missing tabs if (!$currentPointer) { if ($parentPointer instanceof TabSet) { // use $title on the innermost tab only if ($k == $last_idx) { $currentPointer = isset($title) ? new Tab($part, $title) : new Tab($part); } else { $currentPointer = new TabSet($part); } $parentPointer->push($currentPointer); } else { $withName = $parentPointer instanceof FormField ? " named '{$parentPointer->getName()}'" : null; $parentPointerClass = get_class($parentPointer); user_error( "FieldList::addFieldToTab() Tried to add a tab to object" . " '{$parentPointerClass}'{$withName} - '{$part}' didn't exist.", E_USER_ERROR ); } } } return $currentPointer; }
php
public function findOrMakeTab($tabName, $title = null) { $parts = explode('.', $tabName); $last_idx = count($parts) - 1; // We could have made this recursive, but I've chosen to keep all the logic code within FieldList rather than // add it to TabSet and Tab too. $currentPointer = $this; foreach ($parts as $k => $part) { $parentPointer = $currentPointer; /** @var FormField $currentPointer */ $currentPointer = $currentPointer->fieldByName($part); // Create any missing tabs if (!$currentPointer) { if ($parentPointer instanceof TabSet) { // use $title on the innermost tab only if ($k == $last_idx) { $currentPointer = isset($title) ? new Tab($part, $title) : new Tab($part); } else { $currentPointer = new TabSet($part); } $parentPointer->push($currentPointer); } else { $withName = $parentPointer instanceof FormField ? " named '{$parentPointer->getName()}'" : null; $parentPointerClass = get_class($parentPointer); user_error( "FieldList::addFieldToTab() Tried to add a tab to object" . " '{$parentPointerClass}'{$withName} - '{$part}' didn't exist.", E_USER_ERROR ); } } } return $currentPointer; }
[ "public", "function", "findOrMakeTab", "(", "$", "tabName", ",", "$", "title", "=", "null", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "tabName", ")", ";", "$", "last_idx", "=", "count", "(", "$", "parts", ")", "-", "1", ";", "// We could have made this recursive, but I've chosen to keep all the logic code within FieldList rather than", "// add it to TabSet and Tab too.", "$", "currentPointer", "=", "$", "this", ";", "foreach", "(", "$", "parts", "as", "$", "k", "=>", "$", "part", ")", "{", "$", "parentPointer", "=", "$", "currentPointer", ";", "/** @var FormField $currentPointer */", "$", "currentPointer", "=", "$", "currentPointer", "->", "fieldByName", "(", "$", "part", ")", ";", "// Create any missing tabs", "if", "(", "!", "$", "currentPointer", ")", "{", "if", "(", "$", "parentPointer", "instanceof", "TabSet", ")", "{", "// use $title on the innermost tab only", "if", "(", "$", "k", "==", "$", "last_idx", ")", "{", "$", "currentPointer", "=", "isset", "(", "$", "title", ")", "?", "new", "Tab", "(", "$", "part", ",", "$", "title", ")", ":", "new", "Tab", "(", "$", "part", ")", ";", "}", "else", "{", "$", "currentPointer", "=", "new", "TabSet", "(", "$", "part", ")", ";", "}", "$", "parentPointer", "->", "push", "(", "$", "currentPointer", ")", ";", "}", "else", "{", "$", "withName", "=", "$", "parentPointer", "instanceof", "FormField", "?", "\" named '{$parentPointer->getName()}'\"", ":", "null", ";", "$", "parentPointerClass", "=", "get_class", "(", "$", "parentPointer", ")", ";", "user_error", "(", "\"FieldList::addFieldToTab() Tried to add a tab to object\"", ".", "\" '{$parentPointerClass}'{$withName} - '{$part}' didn't exist.\"", ",", "E_USER_ERROR", ")", ";", "}", "}", "}", "return", "$", "currentPointer", ";", "}" ]
Returns the specified tab object, creating it if necessary. @todo Support recursive creation of TabSets @param string $tabName The tab to return, in the form "Tab.Subtab.Subsubtab". Caution: Does not recursively create TabSet instances, you need to make sure everything up until the last tab in the chain exists. @param string $title Natural language title of the tab. If {@link $tabName} is passed in dot notation, the title parameter will only apply to the innermost referenced tab. The title is only changed if the tab doesn't exist already. @return Tab The found or newly created Tab instance
[ "Returns", "the", "specified", "tab", "object", "creating", "it", "if", "necessary", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L471-L507
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.fieldByName
public function fieldByName($name) { if (strpos($name, '.') !== false) { list($name, $remainder) = explode('.', $name, 2); } else { $remainder = null; } foreach ($this as $child) { if (trim($name) == trim($child->getName()) || $name == $child->id) { if ($remainder) { if ($child instanceof CompositeField) { return $child->fieldByName($remainder); } else { $childClass = get_class($child); user_error( "Trying to get field '{$remainder}' from non-composite field {$childClass}.{$name}", E_USER_WARNING ); return null; } } else { return $child; } } } return null; }
php
public function fieldByName($name) { if (strpos($name, '.') !== false) { list($name, $remainder) = explode('.', $name, 2); } else { $remainder = null; } foreach ($this as $child) { if (trim($name) == trim($child->getName()) || $name == $child->id) { if ($remainder) { if ($child instanceof CompositeField) { return $child->fieldByName($remainder); } else { $childClass = get_class($child); user_error( "Trying to get field '{$remainder}' from non-composite field {$childClass}.{$name}", E_USER_WARNING ); return null; } } else { return $child; } } } return null; }
[ "public", "function", "fieldByName", "(", "$", "name", ")", "{", "if", "(", "strpos", "(", "$", "name", ",", "'.'", ")", "!==", "false", ")", "{", "list", "(", "$", "name", ",", "$", "remainder", ")", "=", "explode", "(", "'.'", ",", "$", "name", ",", "2", ")", ";", "}", "else", "{", "$", "remainder", "=", "null", ";", "}", "foreach", "(", "$", "this", "as", "$", "child", ")", "{", "if", "(", "trim", "(", "$", "name", ")", "==", "trim", "(", "$", "child", "->", "getName", "(", ")", ")", "||", "$", "name", "==", "$", "child", "->", "id", ")", "{", "if", "(", "$", "remainder", ")", "{", "if", "(", "$", "child", "instanceof", "CompositeField", ")", "{", "return", "$", "child", "->", "fieldByName", "(", "$", "remainder", ")", ";", "}", "else", "{", "$", "childClass", "=", "get_class", "(", "$", "child", ")", ";", "user_error", "(", "\"Trying to get field '{$remainder}' from non-composite field {$childClass}.{$name}\"", ",", "E_USER_WARNING", ")", ";", "return", "null", ";", "}", "}", "else", "{", "return", "$", "child", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns a named field. You can use dot syntax to get fields from child composite fields @todo Implement similarly to dataFieldByName() to support nested sets - or merge with dataFields() @param string $name @return FormField
[ "Returns", "a", "named", "field", ".", "You", "can", "use", "dot", "syntax", "to", "get", "fields", "from", "child", "composite", "fields" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L518-L545
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.dataFieldByName
public function dataFieldByName($name) { if ($dataFields = $this->dataFields()) { foreach ($dataFields as $child) { if (trim($name) == trim($child->getName()) || $name == $child->id) { return $child; } } } return null; }
php
public function dataFieldByName($name) { if ($dataFields = $this->dataFields()) { foreach ($dataFields as $child) { if (trim($name) == trim($child->getName()) || $name == $child->id) { return $child; } } } return null; }
[ "public", "function", "dataFieldByName", "(", "$", "name", ")", "{", "if", "(", "$", "dataFields", "=", "$", "this", "->", "dataFields", "(", ")", ")", "{", "foreach", "(", "$", "dataFields", "as", "$", "child", ")", "{", "if", "(", "trim", "(", "$", "name", ")", "==", "trim", "(", "$", "child", "->", "getName", "(", ")", ")", "||", "$", "name", "==", "$", "child", "->", "id", ")", "{", "return", "$", "child", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns a named field in a sequential set. Use this if you're using nested FormFields. @param string $name The name of the field to return @return FormField instance
[ "Returns", "a", "named", "field", "in", "a", "sequential", "set", ".", "Use", "this", "if", "you", "re", "using", "nested", "FormFields", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L554-L564
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.push
public function push($item) { $this->onBeforeInsert($item); $item->setContainerFieldList($this); return parent::push($item); }
php
public function push($item) { $this->onBeforeInsert($item); $item->setContainerFieldList($this); return parent::push($item); }
[ "public", "function", "push", "(", "$", "item", ")", "{", "$", "this", "->", "onBeforeInsert", "(", "$", "item", ")", ";", "$", "item", "->", "setContainerFieldList", "(", "$", "this", ")", ";", "return", "parent", "::", "push", "(", "$", "item", ")", ";", "}" ]
Push a single field onto the end of this FieldList instance. @param FormField $item The FormField to add
[ "Push", "a", "single", "field", "onto", "the", "end", "of", "this", "FieldList", "instance", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L655-L661
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.unshift
public function unshift($item) { $this->onBeforeInsert($item); $item->setContainerFieldList($this); return parent::unshift($item); }
php
public function unshift($item) { $this->onBeforeInsert($item); $item->setContainerFieldList($this); return parent::unshift($item); }
[ "public", "function", "unshift", "(", "$", "item", ")", "{", "$", "this", "->", "onBeforeInsert", "(", "$", "item", ")", ";", "$", "item", "->", "setContainerFieldList", "(", "$", "this", ")", ";", "return", "parent", "::", "unshift", "(", "$", "item", ")", ";", "}" ]
Push a single field onto the beginning of this FieldList instance. @param FormField $item The FormField to add
[ "Push", "a", "single", "field", "onto", "the", "beginning", "of", "this", "FieldList", "instance", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L668-L674
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.onBeforeInsert
protected function onBeforeInsert($item) { $this->flushFieldsCache(); if ($item->getName()) { $this->rootFieldList()->removeByName($item->getName(), true); } }
php
protected function onBeforeInsert($item) { $this->flushFieldsCache(); if ($item->getName()) { $this->rootFieldList()->removeByName($item->getName(), true); } }
[ "protected", "function", "onBeforeInsert", "(", "$", "item", ")", "{", "$", "this", "->", "flushFieldsCache", "(", ")", ";", "if", "(", "$", "item", "->", "getName", "(", ")", ")", "{", "$", "this", "->", "rootFieldList", "(", ")", "->", "removeByName", "(", "$", "item", "->", "getName", "(", ")", ",", "true", ")", ";", "}", "}" ]
Handler method called before the FieldList is going to be manipulated. @param FormField $item
[ "Handler", "method", "called", "before", "the", "FieldList", "is", "going", "to", "be", "manipulated", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L681-L688
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.setValues
public function setValues($data) { foreach ($this->dataFields() as $field) { $fieldName = $field->getName(); if (isset($data[$fieldName])) { $field->setValue($data[$fieldName]); } } return $this; }
php
public function setValues($data) { foreach ($this->dataFields() as $field) { $fieldName = $field->getName(); if (isset($data[$fieldName])) { $field->setValue($data[$fieldName]); } } return $this; }
[ "public", "function", "setValues", "(", "$", "data", ")", "{", "foreach", "(", "$", "this", "->", "dataFields", "(", ")", "as", "$", "field", ")", "{", "$", "fieldName", "=", "$", "field", "->", "getName", "(", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "$", "fieldName", "]", ")", ")", "{", "$", "field", "->", "setValue", "(", "$", "data", "[", "$", "fieldName", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Load the given data into this form. @param array $data An map of data to load into the FieldList @return $this
[ "Load", "the", "given", "data", "into", "this", "form", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L712-L721
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.VisibleFields
public function VisibleFields() { $visibleFields = new FieldList(); foreach ($this as $field) { if (!($field instanceof HiddenField)) { $visibleFields->push($field); } } return $visibleFields; }
php
public function VisibleFields() { $visibleFields = new FieldList(); foreach ($this as $field) { if (!($field instanceof HiddenField)) { $visibleFields->push($field); } } return $visibleFields; }
[ "public", "function", "VisibleFields", "(", ")", "{", "$", "visibleFields", "=", "new", "FieldList", "(", ")", ";", "foreach", "(", "$", "this", "as", "$", "field", ")", "{", "if", "(", "!", "(", "$", "field", "instanceof", "HiddenField", ")", ")", "{", "$", "visibleFields", "->", "push", "(", "$", "field", ")", ";", "}", "}", "return", "$", "visibleFields", ";", "}" ]
Return all fields except for the hidden fields. Useful when making your own simplified form layouts.
[ "Return", "all", "fields", "except", "for", "the", "hidden", "fields", ".", "Useful", "when", "making", "your", "own", "simplified", "form", "layouts", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L750-L761
train
silverstripe/silverstripe-framework
src/Forms/FieldList.php
FieldList.makeFieldReadonly
public function makeFieldReadonly($field) { if (!is_array($field)) { $field = [$field]; } foreach ($field as $item) { $fieldName = ($item instanceof FormField) ? $item->getName() : $item; $srcField = $this->dataFieldByName($fieldName); if ($srcField) { $this->replaceField($fieldName, $srcField->performReadonlyTransformation()); } else { user_error("Trying to make field '$fieldName' readonly, but it does not exist in the list", E_USER_WARNING); } } }
php
public function makeFieldReadonly($field) { if (!is_array($field)) { $field = [$field]; } foreach ($field as $item) { $fieldName = ($item instanceof FormField) ? $item->getName() : $item; $srcField = $this->dataFieldByName($fieldName); if ($srcField) { $this->replaceField($fieldName, $srcField->performReadonlyTransformation()); } else { user_error("Trying to make field '$fieldName' readonly, but it does not exist in the list", E_USER_WARNING); } } }
[ "public", "function", "makeFieldReadonly", "(", "$", "field", ")", "{", "if", "(", "!", "is_array", "(", "$", "field", ")", ")", "{", "$", "field", "=", "[", "$", "field", "]", ";", "}", "foreach", "(", "$", "field", "as", "$", "item", ")", "{", "$", "fieldName", "=", "(", "$", "item", "instanceof", "FormField", ")", "?", "$", "item", "->", "getName", "(", ")", ":", "$", "item", ";", "$", "srcField", "=", "$", "this", "->", "dataFieldByName", "(", "$", "fieldName", ")", ";", "if", "(", "$", "srcField", ")", "{", "$", "this", "->", "replaceField", "(", "$", "fieldName", ",", "$", "srcField", "->", "performReadonlyTransformation", "(", ")", ")", ";", "}", "else", "{", "user_error", "(", "\"Trying to make field '$fieldName' readonly, but it does not exist in the list\"", ",", "E_USER_WARNING", ")", ";", "}", "}", "}" ]
Transform the named field into a readonly field. @param string|array|FormField $field
[ "Transform", "the", "named", "field", "into", "a", "readonly", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FieldList.php#L827-L842
train
silverstripe/silverstripe-framework
src/Logging/DetailedErrorFormatter.php
DetailedErrorFormatter.findInTrace
protected function findInTrace(array $trace, $file, $line) { foreach ($trace as $i => $call) { if (isset($call['file']) && isset($call['line']) && $call['file'] == $file && $call['line'] == $line) { return $i; } } return null; }
php
protected function findInTrace(array $trace, $file, $line) { foreach ($trace as $i => $call) { if (isset($call['file']) && isset($call['line']) && $call['file'] == $file && $call['line'] == $line) { return $i; } } return null; }
[ "protected", "function", "findInTrace", "(", "array", "$", "trace", ",", "$", "file", ",", "$", "line", ")", "{", "foreach", "(", "$", "trace", "as", "$", "i", "=>", "$", "call", ")", "{", "if", "(", "isset", "(", "$", "call", "[", "'file'", "]", ")", "&&", "isset", "(", "$", "call", "[", "'line'", "]", ")", "&&", "$", "call", "[", "'file'", "]", "==", "$", "file", "&&", "$", "call", "[", "'line'", "]", "==", "$", "line", ")", "{", "return", "$", "i", ";", "}", "}", "return", "null", ";", "}" ]
Find a call on the given file & line in the trace @param array $trace The result of debug_backtrace() @param string $file The filename to look for @param string $line The line number to look for @return int|null The matching row number, if found, or null if not found
[ "Find", "a", "call", "on", "the", "given", "file", "&", "line", "in", "the", "trace" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Logging/DetailedErrorFormatter.php#L70-L78
train
silverstripe/silverstripe-framework
src/Logging/DetailedErrorFormatter.php
DetailedErrorFormatter.output
protected function output($errno, $errstr, $errfile, $errline, $errcontext) { $reporter = Debug::create_debug_view(); // Coupling alert: This relies on knowledge of how the director gets its URL, it could be improved. $httpRequest = null; if (isset($_SERVER['REQUEST_URI'])) { $httpRequest = $_SERVER['REQUEST_URI']; } if (isset($_SERVER['REQUEST_METHOD'])) { $httpRequest = $_SERVER['REQUEST_METHOD'] . ' ' . $httpRequest; } $output = $reporter->renderHeader(); $output .= $reporter->renderError($httpRequest, $errno, $errstr, $errfile, $errline); if (file_exists($errfile)) { $lines = file($errfile); // Make the array 1-based array_unshift($lines, ""); unset($lines[0]); $offset = $errline-10; $lines = array_slice($lines, $offset, 16, true); $output .= $reporter->renderSourceFragment($lines, $errline); } $output .= $reporter->renderTrace($errcontext); $output .= $reporter->renderFooter(); return $output; }
php
protected function output($errno, $errstr, $errfile, $errline, $errcontext) { $reporter = Debug::create_debug_view(); // Coupling alert: This relies on knowledge of how the director gets its URL, it could be improved. $httpRequest = null; if (isset($_SERVER['REQUEST_URI'])) { $httpRequest = $_SERVER['REQUEST_URI']; } if (isset($_SERVER['REQUEST_METHOD'])) { $httpRequest = $_SERVER['REQUEST_METHOD'] . ' ' . $httpRequest; } $output = $reporter->renderHeader(); $output .= $reporter->renderError($httpRequest, $errno, $errstr, $errfile, $errline); if (file_exists($errfile)) { $lines = file($errfile); // Make the array 1-based array_unshift($lines, ""); unset($lines[0]); $offset = $errline-10; $lines = array_slice($lines, $offset, 16, true); $output .= $reporter->renderSourceFragment($lines, $errline); } $output .= $reporter->renderTrace($errcontext); $output .= $reporter->renderFooter(); return $output; }
[ "protected", "function", "output", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ",", "$", "errcontext", ")", "{", "$", "reporter", "=", "Debug", "::", "create_debug_view", "(", ")", ";", "// Coupling alert: This relies on knowledge of how the director gets its URL, it could be improved.", "$", "httpRequest", "=", "null", ";", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ")", "{", "$", "httpRequest", "=", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ")", ")", "{", "$", "httpRequest", "=", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ".", "' '", ".", "$", "httpRequest", ";", "}", "$", "output", "=", "$", "reporter", "->", "renderHeader", "(", ")", ";", "$", "output", ".=", "$", "reporter", "->", "renderError", "(", "$", "httpRequest", ",", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ")", ";", "if", "(", "file_exists", "(", "$", "errfile", ")", ")", "{", "$", "lines", "=", "file", "(", "$", "errfile", ")", ";", "// Make the array 1-based", "array_unshift", "(", "$", "lines", ",", "\"\"", ")", ";", "unset", "(", "$", "lines", "[", "0", "]", ")", ";", "$", "offset", "=", "$", "errline", "-", "10", ";", "$", "lines", "=", "array_slice", "(", "$", "lines", ",", "$", "offset", ",", "16", ",", "true", ")", ";", "$", "output", ".=", "$", "reporter", "->", "renderSourceFragment", "(", "$", "lines", ",", "$", "errline", ")", ";", "}", "$", "output", ".=", "$", "reporter", "->", "renderTrace", "(", "$", "errcontext", ")", ";", "$", "output", ".=", "$", "reporter", "->", "renderFooter", "(", ")", ";", "return", "$", "output", ";", "}" ]
Render a developer facing error page, showing the stack trace and details of the code where the error occurred. @param int $errno @param string $errstr @param string $errfile @param int $errline @param array $errcontext @return string
[ "Render", "a", "developer", "facing", "error", "page", "showing", "the", "stack", "trace", "and", "details", "of", "the", "code", "where", "the", "error", "occurred", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Logging/DetailedErrorFormatter.php#L91-L123
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/SessionAuthenticationHandler.php
SessionAuthenticationHandler.regenerateSessionId
protected static function regenerateSessionId() { if (!Member::config()->get('session_regenerate_id')) { return; } // This can be called via CLI during testing. if (Director::is_cli()) { return; } $file = ''; $line = ''; // @ is to supress win32 warnings/notices when session wasn't cleaned up properly // There's nothing we can do about this, because it's an operating system function! if (!headers_sent($file, $line)) { @session_regenerate_id(true); } }
php
protected static function regenerateSessionId() { if (!Member::config()->get('session_regenerate_id')) { return; } // This can be called via CLI during testing. if (Director::is_cli()) { return; } $file = ''; $line = ''; // @ is to supress win32 warnings/notices when session wasn't cleaned up properly // There's nothing we can do about this, because it's an operating system function! if (!headers_sent($file, $line)) { @session_regenerate_id(true); } }
[ "protected", "static", "function", "regenerateSessionId", "(", ")", "{", "if", "(", "!", "Member", "::", "config", "(", ")", "->", "get", "(", "'session_regenerate_id'", ")", ")", "{", "return", ";", "}", "// This can be called via CLI during testing.", "if", "(", "Director", "::", "is_cli", "(", ")", ")", "{", "return", ";", "}", "$", "file", "=", "''", ";", "$", "line", "=", "''", ";", "// @ is to supress win32 warnings/notices when session wasn't cleaned up properly", "// There's nothing we can do about this, because it's an operating system function!", "if", "(", "!", "headers_sent", "(", "$", "file", ",", "$", "line", ")", ")", "{", "@", "session_regenerate_id", "(", "true", ")", ";", "}", "}" ]
Regenerate the session_id.
[ "Regenerate", "the", "session_id", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/SessionAuthenticationHandler.php#L87-L106
train
silverstripe/silverstripe-framework
src/Dev/CLI.php
CLI.supports_colour
public static function supports_colour() { // Special case for buildbot if (isset($_ENV['_']) && strpos($_ENV['_'], 'buildbot') !== false) { return false; } if (!defined('STDOUT')) { define('STDOUT', fopen("php://stdout", "w")); } return function_exists('posix_isatty') ? @posix_isatty(STDOUT) : false; }
php
public static function supports_colour() { // Special case for buildbot if (isset($_ENV['_']) && strpos($_ENV['_'], 'buildbot') !== false) { return false; } if (!defined('STDOUT')) { define('STDOUT', fopen("php://stdout", "w")); } return function_exists('posix_isatty') ? @posix_isatty(STDOUT) : false; }
[ "public", "static", "function", "supports_colour", "(", ")", "{", "// Special case for buildbot", "if", "(", "isset", "(", "$", "_ENV", "[", "'_'", "]", ")", "&&", "strpos", "(", "$", "_ENV", "[", "'_'", "]", ",", "'buildbot'", ")", "!==", "false", ")", "{", "return", "false", ";", "}", "if", "(", "!", "defined", "(", "'STDOUT'", ")", ")", "{", "define", "(", "'STDOUT'", ",", "fopen", "(", "\"php://stdout\"", ",", "\"w\"", ")", ")", ";", "}", "return", "function_exists", "(", "'posix_isatty'", ")", "?", "@", "posix_isatty", "(", "STDOUT", ")", ":", "false", ";", "}" ]
Returns true if the current STDOUT supports the use of colour control codes.
[ "Returns", "true", "if", "the", "current", "STDOUT", "supports", "the", "use", "of", "colour", "control", "codes", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CLI.php#L14-L25
train
silverstripe/silverstripe-framework
src/Dev/CLI.php
CLI.text
public static function text($text, $fgColour = null, $bgColour = null, $bold = false) { if (!self::supports_colour()) { return $text; } if ($fgColour || $bgColour || $bold) { $prefix = self::start_colour($fgColour, $bgColour, $bold); $suffix = self::end_colour(); } else { $prefix = $suffix = ""; } return $prefix . $text . $suffix; }
php
public static function text($text, $fgColour = null, $bgColour = null, $bold = false) { if (!self::supports_colour()) { return $text; } if ($fgColour || $bgColour || $bold) { $prefix = self::start_colour($fgColour, $bgColour, $bold); $suffix = self::end_colour(); } else { $prefix = $suffix = ""; } return $prefix . $text . $suffix; }
[ "public", "static", "function", "text", "(", "$", "text", ",", "$", "fgColour", "=", "null", ",", "$", "bgColour", "=", "null", ",", "$", "bold", "=", "false", ")", "{", "if", "(", "!", "self", "::", "supports_colour", "(", ")", ")", "{", "return", "$", "text", ";", "}", "if", "(", "$", "fgColour", "||", "$", "bgColour", "||", "$", "bold", ")", "{", "$", "prefix", "=", "self", "::", "start_colour", "(", "$", "fgColour", ",", "$", "bgColour", ",", "$", "bold", ")", ";", "$", "suffix", "=", "self", "::", "end_colour", "(", ")", ";", "}", "else", "{", "$", "prefix", "=", "$", "suffix", "=", "\"\"", ";", "}", "return", "$", "prefix", ".", "$", "text", ".", "$", "suffix", ";", "}" ]
Return text encoded for CLI output, optionally coloured @param string $text @param string $fgColour The foreground colour - black, red, green, yellow, blue, magenta, cyan, white. Null is default. @param string $bgColour The foreground colour - black, red, green, yellow, blue, magenta, cyan, white. Null is default. @param bool $bold A boolean variable - bold or not. @return string
[ "Return", "text", "encoded", "for", "CLI", "output", "optionally", "coloured" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CLI.php#L38-L52
train
silverstripe/silverstripe-framework
src/Dev/CLI.php
CLI.start_colour
public static function start_colour($fgColour = null, $bgColour = null, $bold = false) { if (!self::supports_colour()) { return ""; } $colours = array( 'black' => 0, 'red' => 1, 'green' => 2, 'yellow' => 3, 'blue' => 4, 'magenta' => 5, 'cyan' => 6, 'white' => 7, ); $prefix = ""; if ($fgColour || $bold) { if (!$fgColour) { $fgColour = "white"; } $prefix .= "\033[" . ($bold ? "1;" :"") . "3" . $colours[$fgColour] . "m"; } if ($bgColour) { $prefix .= "\033[4" . $colours[$bgColour] . "m"; } return $prefix; }
php
public static function start_colour($fgColour = null, $bgColour = null, $bold = false) { if (!self::supports_colour()) { return ""; } $colours = array( 'black' => 0, 'red' => 1, 'green' => 2, 'yellow' => 3, 'blue' => 4, 'magenta' => 5, 'cyan' => 6, 'white' => 7, ); $prefix = ""; if ($fgColour || $bold) { if (!$fgColour) { $fgColour = "white"; } $prefix .= "\033[" . ($bold ? "1;" :"") . "3" . $colours[$fgColour] . "m"; } if ($bgColour) { $prefix .= "\033[4" . $colours[$bgColour] . "m"; } return $prefix; }
[ "public", "static", "function", "start_colour", "(", "$", "fgColour", "=", "null", ",", "$", "bgColour", "=", "null", ",", "$", "bold", "=", "false", ")", "{", "if", "(", "!", "self", "::", "supports_colour", "(", ")", ")", "{", "return", "\"\"", ";", "}", "$", "colours", "=", "array", "(", "'black'", "=>", "0", ",", "'red'", "=>", "1", ",", "'green'", "=>", "2", ",", "'yellow'", "=>", "3", ",", "'blue'", "=>", "4", ",", "'magenta'", "=>", "5", ",", "'cyan'", "=>", "6", ",", "'white'", "=>", "7", ",", ")", ";", "$", "prefix", "=", "\"\"", ";", "if", "(", "$", "fgColour", "||", "$", "bold", ")", "{", "if", "(", "!", "$", "fgColour", ")", "{", "$", "fgColour", "=", "\"white\"", ";", "}", "$", "prefix", ".=", "\"\\033[\"", ".", "(", "$", "bold", "?", "\"1;\"", ":", "\"\"", ")", ".", "\"3\"", ".", "$", "colours", "[", "$", "fgColour", "]", ".", "\"m\"", ";", "}", "if", "(", "$", "bgColour", ")", "{", "$", "prefix", ".=", "\"\\033[4\"", ".", "$", "colours", "[", "$", "bgColour", "]", ".", "\"m\"", ";", "}", "return", "$", "prefix", ";", "}" ]
Send control codes for changing text to the given colour @param string $fgColour The foreground colour - black, red, green, yellow, blue, magenta, cyan, white. Null is default. @param string $bgColour The foreground colour - black, red, green, yellow, blue, magenta, cyan, white. Null is default. @param bool $bold A boolean variable - bold or not. @return string
[ "Send", "control", "codes", "for", "changing", "text", "to", "the", "given", "colour" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/CLI.php#L63-L94
train
silverstripe/silverstripe-framework
src/Dev/YamlFixture.php
YamlFixture.writeInto
public function writeInto(FixtureFactory $factory) { $parser = new Parser(); if (isset($this->fixtureString)) { $fixtureContent = $parser->parse($this->fixtureString); } else { if (!file_exists($this->fixtureFile)) { return; } $contents = file_get_contents($this->fixtureFile); $fixtureContent = $parser->parse($contents); if (!$fixtureContent) { return; } } foreach ($fixtureContent as $class => $items) { foreach ($items as $identifier => $data) { if (ClassInfo::exists($class)) { $factory->createObject($class, $identifier, $data); } else { $factory->createRaw($class, $identifier, $data); } } } }
php
public function writeInto(FixtureFactory $factory) { $parser = new Parser(); if (isset($this->fixtureString)) { $fixtureContent = $parser->parse($this->fixtureString); } else { if (!file_exists($this->fixtureFile)) { return; } $contents = file_get_contents($this->fixtureFile); $fixtureContent = $parser->parse($contents); if (!$fixtureContent) { return; } } foreach ($fixtureContent as $class => $items) { foreach ($items as $identifier => $data) { if (ClassInfo::exists($class)) { $factory->createObject($class, $identifier, $data); } else { $factory->createRaw($class, $identifier, $data); } } } }
[ "public", "function", "writeInto", "(", "FixtureFactory", "$", "factory", ")", "{", "$", "parser", "=", "new", "Parser", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "fixtureString", ")", ")", "{", "$", "fixtureContent", "=", "$", "parser", "->", "parse", "(", "$", "this", "->", "fixtureString", ")", ";", "}", "else", "{", "if", "(", "!", "file_exists", "(", "$", "this", "->", "fixtureFile", ")", ")", "{", "return", ";", "}", "$", "contents", "=", "file_get_contents", "(", "$", "this", "->", "fixtureFile", ")", ";", "$", "fixtureContent", "=", "$", "parser", "->", "parse", "(", "$", "contents", ")", ";", "if", "(", "!", "$", "fixtureContent", ")", "{", "return", ";", "}", "}", "foreach", "(", "$", "fixtureContent", "as", "$", "class", "=>", "$", "items", ")", "{", "foreach", "(", "$", "items", "as", "$", "identifier", "=>", "$", "data", ")", "{", "if", "(", "ClassInfo", "::", "exists", "(", "$", "class", ")", ")", "{", "$", "factory", "->", "createObject", "(", "$", "class", ",", "$", "identifier", ",", "$", "data", ")", ";", "}", "else", "{", "$", "factory", "->", "createRaw", "(", "$", "class", ",", "$", "identifier", ",", "$", "data", ")", ";", "}", "}", "}", "}" ]
Persists the YAML data in a FixtureFactory, which in turn saves them into the database. Please use the passed in factory to access the fixtures afterwards. @param FixtureFactory $factory
[ "Persists", "the", "YAML", "data", "in", "a", "FixtureFactory", "which", "in", "turn", "saves", "them", "into", "the", "database", ".", "Please", "use", "the", "passed", "in", "factory", "to", "access", "the", "fixtures", "afterwards", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/YamlFixture.php#L133-L160
train
silverstripe/silverstripe-framework
src/Core/Environment.php
Environment.getVariables
public static function getVariables() { // Suppress return by-ref $vars = [ 'env' => static::$env ]; // needs to use a for loop, using `array_merge([], $GLOBALS);` left reference traces somehow foreach ($GLOBALS as $varName => $varValue) { $vars[$varName] = $varValue; } return $vars; }
php
public static function getVariables() { // Suppress return by-ref $vars = [ 'env' => static::$env ]; // needs to use a for loop, using `array_merge([], $GLOBALS);` left reference traces somehow foreach ($GLOBALS as $varName => $varValue) { $vars[$varName] = $varValue; } return $vars; }
[ "public", "static", "function", "getVariables", "(", ")", "{", "// Suppress return by-ref", "$", "vars", "=", "[", "'env'", "=>", "static", "::", "$", "env", "]", ";", "// needs to use a for loop, using `array_merge([], $GLOBALS);` left reference traces somehow", "foreach", "(", "$", "GLOBALS", "as", "$", "varName", "=>", "$", "varValue", ")", "{", "$", "vars", "[", "$", "varName", "]", "=", "$", "varValue", ";", "}", "return", "$", "vars", ";", "}" ]
Extract env vars prior to modification @return array List of all super globals
[ "Extract", "env", "vars", "prior", "to", "modification" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Environment.php#L43-L53
train
silverstripe/silverstripe-framework
src/Core/Environment.php
Environment.getEnv
public static function getEnv($name) { switch (true) { case is_array(static::$env) && array_key_exists($name, static::$env): return static::$env[$name]; case is_array($_ENV) && array_key_exists($name, $_ENV): return $_ENV[$name]; case is_array($_SERVER) && array_key_exists($name, $_SERVER): return $_SERVER[$name]; default: return getenv($name); } }
php
public static function getEnv($name) { switch (true) { case is_array(static::$env) && array_key_exists($name, static::$env): return static::$env[$name]; case is_array($_ENV) && array_key_exists($name, $_ENV): return $_ENV[$name]; case is_array($_SERVER) && array_key_exists($name, $_SERVER): return $_SERVER[$name]; default: return getenv($name); } }
[ "public", "static", "function", "getEnv", "(", "$", "name", ")", "{", "switch", "(", "true", ")", "{", "case", "is_array", "(", "static", "::", "$", "env", ")", "&&", "array_key_exists", "(", "$", "name", ",", "static", "::", "$", "env", ")", ":", "return", "static", "::", "$", "env", "[", "$", "name", "]", ";", "case", "is_array", "(", "$", "_ENV", ")", "&&", "array_key_exists", "(", "$", "name", ",", "$", "_ENV", ")", ":", "return", "$", "_ENV", "[", "$", "name", "]", ";", "case", "is_array", "(", "$", "_SERVER", ")", "&&", "array_key_exists", "(", "$", "name", ",", "$", "_SERVER", ")", ":", "return", "$", "_SERVER", "[", "$", "name", "]", ";", "default", ":", "return", "getenv", "(", "$", "name", ")", ";", "}", "}" ]
Get value of environment variable @param string $name @return mixed Value of the environment variable, or false if not set
[ "Get", "value", "of", "environment", "variable" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Environment.php#L185-L197
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.collect
public function collect($restrictToModules = array(), $mergeWithExisting = false) { $entitiesByModule = $this->getEntitiesByModule(); // Resolve conflicts between duplicate keys across modules $entitiesByModule = $this->resolveDuplicateConflicts($entitiesByModule); // Optionally merge with existing master strings if ($mergeWithExisting) { $entitiesByModule = $this->mergeWithExisting($entitiesByModule); } // Restrict modules we update to just the specified ones (if any passed) if (!empty($restrictToModules)) { // Normalise module names $modules = array_filter(array_map(function ($name) { $module = ModuleLoader::inst()->getManifest()->getModule($name); return $module ? $module->getName() : null; }, $restrictToModules)); // Remove modules foreach (array_diff(array_keys($entitiesByModule), $modules) as $module) { unset($entitiesByModule[$module]); } } return $entitiesByModule; }
php
public function collect($restrictToModules = array(), $mergeWithExisting = false) { $entitiesByModule = $this->getEntitiesByModule(); // Resolve conflicts between duplicate keys across modules $entitiesByModule = $this->resolveDuplicateConflicts($entitiesByModule); // Optionally merge with existing master strings if ($mergeWithExisting) { $entitiesByModule = $this->mergeWithExisting($entitiesByModule); } // Restrict modules we update to just the specified ones (if any passed) if (!empty($restrictToModules)) { // Normalise module names $modules = array_filter(array_map(function ($name) { $module = ModuleLoader::inst()->getManifest()->getModule($name); return $module ? $module->getName() : null; }, $restrictToModules)); // Remove modules foreach (array_diff(array_keys($entitiesByModule), $modules) as $module) { unset($entitiesByModule[$module]); } } return $entitiesByModule; }
[ "public", "function", "collect", "(", "$", "restrictToModules", "=", "array", "(", ")", ",", "$", "mergeWithExisting", "=", "false", ")", "{", "$", "entitiesByModule", "=", "$", "this", "->", "getEntitiesByModule", "(", ")", ";", "// Resolve conflicts between duplicate keys across modules", "$", "entitiesByModule", "=", "$", "this", "->", "resolveDuplicateConflicts", "(", "$", "entitiesByModule", ")", ";", "// Optionally merge with existing master strings", "if", "(", "$", "mergeWithExisting", ")", "{", "$", "entitiesByModule", "=", "$", "this", "->", "mergeWithExisting", "(", "$", "entitiesByModule", ")", ";", "}", "// Restrict modules we update to just the specified ones (if any passed)", "if", "(", "!", "empty", "(", "$", "restrictToModules", ")", ")", "{", "// Normalise module names", "$", "modules", "=", "array_filter", "(", "array_map", "(", "function", "(", "$", "name", ")", "{", "$", "module", "=", "ModuleLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getModule", "(", "$", "name", ")", ";", "return", "$", "module", "?", "$", "module", "->", "getName", "(", ")", ":", "null", ";", "}", ",", "$", "restrictToModules", ")", ")", ";", "// Remove modules", "foreach", "(", "array_diff", "(", "array_keys", "(", "$", "entitiesByModule", ")", ",", "$", "modules", ")", "as", "$", "module", ")", "{", "unset", "(", "$", "entitiesByModule", "[", "$", "module", "]", ")", ";", "}", "}", "return", "$", "entitiesByModule", ";", "}" ]
Extract all strings from modules and return these grouped by module name @param array $restrictToModules @param bool $mergeWithExisting @return array
[ "Extract", "all", "strings", "from", "modules", "and", "return", "these", "grouped", "by", "module", "name" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L198-L223
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.resolveDuplicateConflicts
protected function resolveDuplicateConflicts($entitiesByModule) { // Find all keys that exist across multiple modules $conflicts = $this->getConflicts($entitiesByModule); foreach ($conflicts as $conflict) { // Determine if we can narrow down the ownership $bestModule = $this->getBestModuleForKey($entitiesByModule, $conflict); if (!$bestModule || !isset($entitiesByModule[$bestModule])) { continue; } // Remove foreign duplicates foreach ($entitiesByModule as $module => $entities) { if ($module !== $bestModule) { unset($entitiesByModule[$module][$conflict]); } } } return $entitiesByModule; }
php
protected function resolveDuplicateConflicts($entitiesByModule) { // Find all keys that exist across multiple modules $conflicts = $this->getConflicts($entitiesByModule); foreach ($conflicts as $conflict) { // Determine if we can narrow down the ownership $bestModule = $this->getBestModuleForKey($entitiesByModule, $conflict); if (!$bestModule || !isset($entitiesByModule[$bestModule])) { continue; } // Remove foreign duplicates foreach ($entitiesByModule as $module => $entities) { if ($module !== $bestModule) { unset($entitiesByModule[$module][$conflict]); } } } return $entitiesByModule; }
[ "protected", "function", "resolveDuplicateConflicts", "(", "$", "entitiesByModule", ")", "{", "// Find all keys that exist across multiple modules", "$", "conflicts", "=", "$", "this", "->", "getConflicts", "(", "$", "entitiesByModule", ")", ";", "foreach", "(", "$", "conflicts", "as", "$", "conflict", ")", "{", "// Determine if we can narrow down the ownership", "$", "bestModule", "=", "$", "this", "->", "getBestModuleForKey", "(", "$", "entitiesByModule", ",", "$", "conflict", ")", ";", "if", "(", "!", "$", "bestModule", "||", "!", "isset", "(", "$", "entitiesByModule", "[", "$", "bestModule", "]", ")", ")", "{", "continue", ";", "}", "// Remove foreign duplicates", "foreach", "(", "$", "entitiesByModule", "as", "$", "module", "=>", "$", "entities", ")", "{", "if", "(", "$", "module", "!==", "$", "bestModule", ")", "{", "unset", "(", "$", "entitiesByModule", "[", "$", "module", "]", "[", "$", "conflict", "]", ")", ";", "}", "}", "}", "return", "$", "entitiesByModule", ";", "}" ]
Resolve conflicts between duplicate keys across modules @param array $entitiesByModule List of all modules with keys @return array Filtered listo of modules with duplicate keys unassigned
[ "Resolve", "conflicts", "between", "duplicate", "keys", "across", "modules" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L231-L250
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.getConflicts
protected function getConflicts($entitiesByModule) { $modules = array_keys($entitiesByModule); $allConflicts = array(); // bubble-compare each group of modules for ($i = 0; $i < count($modules) - 1; $i++) { $left = array_keys($entitiesByModule[$modules[$i]]); for ($j = $i+1; $j < count($modules); $j++) { $right = array_keys($entitiesByModule[$modules[$j]]); $conflicts = array_intersect($left, $right); $allConflicts = array_merge($allConflicts, $conflicts); } } return array_unique($allConflicts); }
php
protected function getConflicts($entitiesByModule) { $modules = array_keys($entitiesByModule); $allConflicts = array(); // bubble-compare each group of modules for ($i = 0; $i < count($modules) - 1; $i++) { $left = array_keys($entitiesByModule[$modules[$i]]); for ($j = $i+1; $j < count($modules); $j++) { $right = array_keys($entitiesByModule[$modules[$j]]); $conflicts = array_intersect($left, $right); $allConflicts = array_merge($allConflicts, $conflicts); } } return array_unique($allConflicts); }
[ "protected", "function", "getConflicts", "(", "$", "entitiesByModule", ")", "{", "$", "modules", "=", "array_keys", "(", "$", "entitiesByModule", ")", ";", "$", "allConflicts", "=", "array", "(", ")", ";", "// bubble-compare each group of modules", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "modules", ")", "-", "1", ";", "$", "i", "++", ")", "{", "$", "left", "=", "array_keys", "(", "$", "entitiesByModule", "[", "$", "modules", "[", "$", "i", "]", "]", ")", ";", "for", "(", "$", "j", "=", "$", "i", "+", "1", ";", "$", "j", "<", "count", "(", "$", "modules", ")", ";", "$", "j", "++", ")", "{", "$", "right", "=", "array_keys", "(", "$", "entitiesByModule", "[", "$", "modules", "[", "$", "j", "]", "]", ")", ";", "$", "conflicts", "=", "array_intersect", "(", "$", "left", ",", "$", "right", ")", ";", "$", "allConflicts", "=", "array_merge", "(", "$", "allConflicts", ",", "$", "conflicts", ")", ";", "}", "}", "return", "array_unique", "(", "$", "allConflicts", ")", ";", "}" ]
Find all keys in the entity list that are duplicated across modules @param array $entitiesByModule @return array List of keys
[ "Find", "all", "keys", "in", "the", "entity", "list", "that", "are", "duplicated", "across", "modules" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L258-L272
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.getBestModuleForKey
protected function getBestModuleForKey($entitiesByModule, $key) { // Check classes $class = current(explode('.', $key)); if (array_key_exists($class, $this->classModuleCache)) { return $this->classModuleCache[$class]; } $owner = $this->findModuleForClass($class); if ($owner) { $this->classModuleCache[$class] = $owner; return $owner; } // @todo - How to determine ownership of templates? Templates can // exist in multiple locations with the same name. // Display notice if not found Debug::message( "Duplicate key {$key} detected in no / multiple modules with no obvious owner", false ); // Fall back to framework then cms modules foreach (array('framework', 'cms') as $module) { if (isset($entitiesByModule[$module][$key])) { $this->classModuleCache[$class] = $module; return $module; } } // Do nothing $this->classModuleCache[$class] = null; return null; }
php
protected function getBestModuleForKey($entitiesByModule, $key) { // Check classes $class = current(explode('.', $key)); if (array_key_exists($class, $this->classModuleCache)) { return $this->classModuleCache[$class]; } $owner = $this->findModuleForClass($class); if ($owner) { $this->classModuleCache[$class] = $owner; return $owner; } // @todo - How to determine ownership of templates? Templates can // exist in multiple locations with the same name. // Display notice if not found Debug::message( "Duplicate key {$key} detected in no / multiple modules with no obvious owner", false ); // Fall back to framework then cms modules foreach (array('framework', 'cms') as $module) { if (isset($entitiesByModule[$module][$key])) { $this->classModuleCache[$class] = $module; return $module; } } // Do nothing $this->classModuleCache[$class] = null; return null; }
[ "protected", "function", "getBestModuleForKey", "(", "$", "entitiesByModule", ",", "$", "key", ")", "{", "// Check classes", "$", "class", "=", "current", "(", "explode", "(", "'.'", ",", "$", "key", ")", ")", ";", "if", "(", "array_key_exists", "(", "$", "class", ",", "$", "this", "->", "classModuleCache", ")", ")", "{", "return", "$", "this", "->", "classModuleCache", "[", "$", "class", "]", ";", "}", "$", "owner", "=", "$", "this", "->", "findModuleForClass", "(", "$", "class", ")", ";", "if", "(", "$", "owner", ")", "{", "$", "this", "->", "classModuleCache", "[", "$", "class", "]", "=", "$", "owner", ";", "return", "$", "owner", ";", "}", "// @todo - How to determine ownership of templates? Templates can", "// exist in multiple locations with the same name.", "// Display notice if not found", "Debug", "::", "message", "(", "\"Duplicate key {$key} detected in no / multiple modules with no obvious owner\"", ",", "false", ")", ";", "// Fall back to framework then cms modules", "foreach", "(", "array", "(", "'framework'", ",", "'cms'", ")", "as", "$", "module", ")", "{", "if", "(", "isset", "(", "$", "entitiesByModule", "[", "$", "module", "]", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "classModuleCache", "[", "$", "class", "]", "=", "$", "module", ";", "return", "$", "module", ";", "}", "}", "// Do nothing", "$", "this", "->", "classModuleCache", "[", "$", "class", "]", "=", "null", ";", "return", "null", ";", "}" ]
Determine the best module to be given ownership over this key @param array $entitiesByModule @param string $key @return string Best module, if found
[ "Determine", "the", "best", "module", "to", "be", "given", "ownership", "over", "this", "key" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L287-L320
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.findModuleForClass
protected function findModuleForClass($class) { if (ClassInfo::exists($class)) { $module = ClassLoader::inst() ->getManifest() ->getOwnerModule($class); if ($module) { return $module->getName(); } } // If we can't find a class, see if it needs to be fully qualified if (strpos($class, '\\') !== false) { return null; } // Find FQN that ends with $class $classes = preg_grep( '/' . preg_quote("\\{$class}", '\/') . '$/i', ClassLoader::inst()->getManifest()->getClassNames() ); // Find all modules for candidate classes $modules = array_unique(array_map(function ($class) { $module = ClassLoader::inst()->getManifest()->getOwnerModule($class); return $module ? $module->getName() : null; }, $classes)); if (count($modules) === 1) { return reset($modules); } // Couldn't find it! Exists in none, or multiple modules. return null; }
php
protected function findModuleForClass($class) { if (ClassInfo::exists($class)) { $module = ClassLoader::inst() ->getManifest() ->getOwnerModule($class); if ($module) { return $module->getName(); } } // If we can't find a class, see if it needs to be fully qualified if (strpos($class, '\\') !== false) { return null; } // Find FQN that ends with $class $classes = preg_grep( '/' . preg_quote("\\{$class}", '\/') . '$/i', ClassLoader::inst()->getManifest()->getClassNames() ); // Find all modules for candidate classes $modules = array_unique(array_map(function ($class) { $module = ClassLoader::inst()->getManifest()->getOwnerModule($class); return $module ? $module->getName() : null; }, $classes)); if (count($modules) === 1) { return reset($modules); } // Couldn't find it! Exists in none, or multiple modules. return null; }
[ "protected", "function", "findModuleForClass", "(", "$", "class", ")", "{", "if", "(", "ClassInfo", "::", "exists", "(", "$", "class", ")", ")", "{", "$", "module", "=", "ClassLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getOwnerModule", "(", "$", "class", ")", ";", "if", "(", "$", "module", ")", "{", "return", "$", "module", "->", "getName", "(", ")", ";", "}", "}", "// If we can't find a class, see if it needs to be fully qualified", "if", "(", "strpos", "(", "$", "class", ",", "'\\\\'", ")", "!==", "false", ")", "{", "return", "null", ";", "}", "// Find FQN that ends with $class", "$", "classes", "=", "preg_grep", "(", "'/'", ".", "preg_quote", "(", "\"\\\\{$class}\"", ",", "'\\/'", ")", ".", "'$/i'", ",", "ClassLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getClassNames", "(", ")", ")", ";", "// Find all modules for candidate classes", "$", "modules", "=", "array_unique", "(", "array_map", "(", "function", "(", "$", "class", ")", "{", "$", "module", "=", "ClassLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getOwnerModule", "(", "$", "class", ")", ";", "return", "$", "module", "?", "$", "module", "->", "getName", "(", ")", ":", "null", ";", "}", ",", "$", "classes", ")", ")", ";", "if", "(", "count", "(", "$", "modules", ")", "===", "1", ")", "{", "return", "reset", "(", "$", "modules", ")", ";", "}", "// Couldn't find it! Exists in none, or multiple modules.", "return", "null", ";", "}" ]
Given a partial class name, attempt to determine the best module to assign strings to. @param string $class Either a FQN class name, or a non-qualified class name. @return string Name of module
[ "Given", "a", "partial", "class", "name", "attempt", "to", "determine", "the", "best", "module", "to", "assign", "strings", "to", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L328-L362
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.mergeWithExisting
protected function mergeWithExisting($entitiesByModule) { // For each module do a simple merge of the default yml with these strings foreach ($entitiesByModule as $module => $messages) { // Load existing localisations $masterFile = "{$this->basePath}/{$module}/lang/{$this->defaultLocale}.yml"; $existingMessages = $this->getReader()->read($this->defaultLocale, $masterFile); // Merge if ($existingMessages) { $entitiesByModule[$module] = array_merge( $existingMessages, $messages ); } } return $entitiesByModule; }
php
protected function mergeWithExisting($entitiesByModule) { // For each module do a simple merge of the default yml with these strings foreach ($entitiesByModule as $module => $messages) { // Load existing localisations $masterFile = "{$this->basePath}/{$module}/lang/{$this->defaultLocale}.yml"; $existingMessages = $this->getReader()->read($this->defaultLocale, $masterFile); // Merge if ($existingMessages) { $entitiesByModule[$module] = array_merge( $existingMessages, $messages ); } } return $entitiesByModule; }
[ "protected", "function", "mergeWithExisting", "(", "$", "entitiesByModule", ")", "{", "// For each module do a simple merge of the default yml with these strings", "foreach", "(", "$", "entitiesByModule", "as", "$", "module", "=>", "$", "messages", ")", "{", "// Load existing localisations", "$", "masterFile", "=", "\"{$this->basePath}/{$module}/lang/{$this->defaultLocale}.yml\"", ";", "$", "existingMessages", "=", "$", "this", "->", "getReader", "(", ")", "->", "read", "(", "$", "this", "->", "defaultLocale", ",", "$", "masterFile", ")", ";", "// Merge", "if", "(", "$", "existingMessages", ")", "{", "$", "entitiesByModule", "[", "$", "module", "]", "=", "array_merge", "(", "$", "existingMessages", ",", "$", "messages", ")", ";", "}", "}", "return", "$", "entitiesByModule", ";", "}" ]
Merge all entities with existing strings @param array $entitiesByModule @return array
[ "Merge", "all", "entities", "with", "existing", "strings" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L370-L387
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.getEntitiesByModule
protected function getEntitiesByModule() { // A master string tables array (one mst per module) $entitiesByModule = array(); $modules = ModuleLoader::inst()->getManifest()->getModules(); foreach ($modules as $module) { // we store the master string tables $processedEntities = $this->processModule($module); $moduleName = $module->getName(); if (isset($entitiesByModule[$moduleName])) { $entitiesByModule[$moduleName] = array_merge_recursive( $entitiesByModule[$moduleName], $processedEntities ); } else { $entitiesByModule[$moduleName] = $processedEntities; } // Extract all entities for "foreign" modules ('module' key in array form) // @see CMSMenu::provideI18nEntities for an example usage foreach ($entitiesByModule[$moduleName] as $fullName => $spec) { $specModuleName = $moduleName; // Rewrite spec if module is specified if (is_array($spec) && isset($spec['module'])) { // Normalise name (in case non-composer name is specified) $specModule = ModuleLoader::inst()->getManifest()->getModule($spec['module']); if ($specModule) { $specModuleName = $specModule->getName(); } unset($spec['module']); // If only element is defalt, simplify if (count($spec) === 1 && !empty($spec['default'])) { $spec = $spec['default']; } } // Remove from source module if ($specModuleName !== $moduleName) { unset($entitiesByModule[$moduleName][$fullName]); } // Write to target module if (!isset($entitiesByModule[$specModuleName])) { $entitiesByModule[$specModuleName] = []; } $entitiesByModule[$specModuleName][$fullName] = $spec; } } return $entitiesByModule; }
php
protected function getEntitiesByModule() { // A master string tables array (one mst per module) $entitiesByModule = array(); $modules = ModuleLoader::inst()->getManifest()->getModules(); foreach ($modules as $module) { // we store the master string tables $processedEntities = $this->processModule($module); $moduleName = $module->getName(); if (isset($entitiesByModule[$moduleName])) { $entitiesByModule[$moduleName] = array_merge_recursive( $entitiesByModule[$moduleName], $processedEntities ); } else { $entitiesByModule[$moduleName] = $processedEntities; } // Extract all entities for "foreign" modules ('module' key in array form) // @see CMSMenu::provideI18nEntities for an example usage foreach ($entitiesByModule[$moduleName] as $fullName => $spec) { $specModuleName = $moduleName; // Rewrite spec if module is specified if (is_array($spec) && isset($spec['module'])) { // Normalise name (in case non-composer name is specified) $specModule = ModuleLoader::inst()->getManifest()->getModule($spec['module']); if ($specModule) { $specModuleName = $specModule->getName(); } unset($spec['module']); // If only element is defalt, simplify if (count($spec) === 1 && !empty($spec['default'])) { $spec = $spec['default']; } } // Remove from source module if ($specModuleName !== $moduleName) { unset($entitiesByModule[$moduleName][$fullName]); } // Write to target module if (!isset($entitiesByModule[$specModuleName])) { $entitiesByModule[$specModuleName] = []; } $entitiesByModule[$specModuleName][$fullName] = $spec; } } return $entitiesByModule; }
[ "protected", "function", "getEntitiesByModule", "(", ")", "{", "// A master string tables array (one mst per module)", "$", "entitiesByModule", "=", "array", "(", ")", ";", "$", "modules", "=", "ModuleLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getModules", "(", ")", ";", "foreach", "(", "$", "modules", "as", "$", "module", ")", "{", "// we store the master string tables", "$", "processedEntities", "=", "$", "this", "->", "processModule", "(", "$", "module", ")", ";", "$", "moduleName", "=", "$", "module", "->", "getName", "(", ")", ";", "if", "(", "isset", "(", "$", "entitiesByModule", "[", "$", "moduleName", "]", ")", ")", "{", "$", "entitiesByModule", "[", "$", "moduleName", "]", "=", "array_merge_recursive", "(", "$", "entitiesByModule", "[", "$", "moduleName", "]", ",", "$", "processedEntities", ")", ";", "}", "else", "{", "$", "entitiesByModule", "[", "$", "moduleName", "]", "=", "$", "processedEntities", ";", "}", "// Extract all entities for \"foreign\" modules ('module' key in array form)", "// @see CMSMenu::provideI18nEntities for an example usage", "foreach", "(", "$", "entitiesByModule", "[", "$", "moduleName", "]", "as", "$", "fullName", "=>", "$", "spec", ")", "{", "$", "specModuleName", "=", "$", "moduleName", ";", "// Rewrite spec if module is specified", "if", "(", "is_array", "(", "$", "spec", ")", "&&", "isset", "(", "$", "spec", "[", "'module'", "]", ")", ")", "{", "// Normalise name (in case non-composer name is specified)", "$", "specModule", "=", "ModuleLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getModule", "(", "$", "spec", "[", "'module'", "]", ")", ";", "if", "(", "$", "specModule", ")", "{", "$", "specModuleName", "=", "$", "specModule", "->", "getName", "(", ")", ";", "}", "unset", "(", "$", "spec", "[", "'module'", "]", ")", ";", "// If only element is defalt, simplify", "if", "(", "count", "(", "$", "spec", ")", "===", "1", "&&", "!", "empty", "(", "$", "spec", "[", "'default'", "]", ")", ")", "{", "$", "spec", "=", "$", "spec", "[", "'default'", "]", ";", "}", "}", "// Remove from source module", "if", "(", "$", "specModuleName", "!==", "$", "moduleName", ")", "{", "unset", "(", "$", "entitiesByModule", "[", "$", "moduleName", "]", "[", "$", "fullName", "]", ")", ";", "}", "// Write to target module", "if", "(", "!", "isset", "(", "$", "entitiesByModule", "[", "$", "specModuleName", "]", ")", ")", "{", "$", "entitiesByModule", "[", "$", "specModuleName", "]", "=", "[", "]", ";", "}", "$", "entitiesByModule", "[", "$", "specModuleName", "]", "[", "$", "fullName", "]", "=", "$", "spec", ";", "}", "}", "return", "$", "entitiesByModule", ";", "}" ]
Collect all entities grouped by module @return array
[ "Collect", "all", "entities", "grouped", "by", "module" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L394-L445
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.write
public function write(Module $module, $entities) { $this->getWriter()->write( $entities, $this->defaultLocale, $this->baseSavePath . '/' . $module->getRelativePath() ); return $this; }
php
public function write(Module $module, $entities) { $this->getWriter()->write( $entities, $this->defaultLocale, $this->baseSavePath . '/' . $module->getRelativePath() ); return $this; }
[ "public", "function", "write", "(", "Module", "$", "module", ",", "$", "entities", ")", "{", "$", "this", "->", "getWriter", "(", ")", "->", "write", "(", "$", "entities", ",", "$", "this", "->", "defaultLocale", ",", "$", "this", "->", "baseSavePath", ".", "'/'", ".", "$", "module", "->", "getRelativePath", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Write entities to a module @param Module $module @param array $entities @return $this
[ "Write", "entities", "to", "a", "module" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L454-L462
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.getFileListForModule
protected function getFileListForModule(Module $module) { $modulePath = $module->getPath(); // Search all .ss files in themes if (stripos($module->getRelativePath(), 'themes/') === 0) { return $this->getFilesRecursive($modulePath, null, 'ss'); } // If non-standard module structure, search all root files if (!is_dir("{$modulePath}/code") && !is_dir("{$modulePath}/src")) { return $this->getFilesRecursive($modulePath); } // Get code files if (is_dir("{$modulePath}/src")) { $files = $this->getFilesRecursive("{$modulePath}/src", null, 'php'); } else { $files = $this->getFilesRecursive("{$modulePath}/code", null, 'php'); } // Search for templates in this module if (is_dir("{$modulePath}/templates")) { $templateFiles = $this->getFilesRecursive("{$modulePath}/templates", null, 'ss'); } else { $templateFiles = $this->getFilesRecursive($modulePath, null, 'ss'); } return array_merge($files, $templateFiles); }
php
protected function getFileListForModule(Module $module) { $modulePath = $module->getPath(); // Search all .ss files in themes if (stripos($module->getRelativePath(), 'themes/') === 0) { return $this->getFilesRecursive($modulePath, null, 'ss'); } // If non-standard module structure, search all root files if (!is_dir("{$modulePath}/code") && !is_dir("{$modulePath}/src")) { return $this->getFilesRecursive($modulePath); } // Get code files if (is_dir("{$modulePath}/src")) { $files = $this->getFilesRecursive("{$modulePath}/src", null, 'php'); } else { $files = $this->getFilesRecursive("{$modulePath}/code", null, 'php'); } // Search for templates in this module if (is_dir("{$modulePath}/templates")) { $templateFiles = $this->getFilesRecursive("{$modulePath}/templates", null, 'ss'); } else { $templateFiles = $this->getFilesRecursive($modulePath, null, 'ss'); } return array_merge($files, $templateFiles); }
[ "protected", "function", "getFileListForModule", "(", "Module", "$", "module", ")", "{", "$", "modulePath", "=", "$", "module", "->", "getPath", "(", ")", ";", "// Search all .ss files in themes", "if", "(", "stripos", "(", "$", "module", "->", "getRelativePath", "(", ")", ",", "'themes/'", ")", "===", "0", ")", "{", "return", "$", "this", "->", "getFilesRecursive", "(", "$", "modulePath", ",", "null", ",", "'ss'", ")", ";", "}", "// If non-standard module structure, search all root files", "if", "(", "!", "is_dir", "(", "\"{$modulePath}/code\"", ")", "&&", "!", "is_dir", "(", "\"{$modulePath}/src\"", ")", ")", "{", "return", "$", "this", "->", "getFilesRecursive", "(", "$", "modulePath", ")", ";", "}", "// Get code files", "if", "(", "is_dir", "(", "\"{$modulePath}/src\"", ")", ")", "{", "$", "files", "=", "$", "this", "->", "getFilesRecursive", "(", "\"{$modulePath}/src\"", ",", "null", ",", "'php'", ")", ";", "}", "else", "{", "$", "files", "=", "$", "this", "->", "getFilesRecursive", "(", "\"{$modulePath}/code\"", ",", "null", ",", "'php'", ")", ";", "}", "// Search for templates in this module", "if", "(", "is_dir", "(", "\"{$modulePath}/templates\"", ")", ")", "{", "$", "templateFiles", "=", "$", "this", "->", "getFilesRecursive", "(", "\"{$modulePath}/templates\"", ",", "null", ",", "'ss'", ")", ";", "}", "else", "{", "$", "templateFiles", "=", "$", "this", "->", "getFilesRecursive", "(", "$", "modulePath", ",", "null", ",", "'ss'", ")", ";", "}", "return", "array_merge", "(", "$", "files", ",", "$", "templateFiles", ")", ";", "}" ]
Retrieves the list of files for this module @param Module $module Module instance @return array List of files to parse
[ "Retrieves", "the", "list", "of", "files", "for", "this", "module" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L508-L537
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.collectFromEntityProviders
public function collectFromEntityProviders($filePath, Module $module = null) { $entities = array(); $classes = ClassInfo::classes_for_file($filePath); foreach ($classes as $class) { // Skip non-implementing classes if (!class_exists($class) || !is_a($class, i18nEntityProvider::class, true)) { continue; } // Skip abstract classes $reflectionClass = new ReflectionClass($class); if ($reflectionClass->isAbstract()) { continue; } /** @var i18nEntityProvider $obj */ $obj = singleton($class); $provided = $obj->provideI18nEntities(); // Handle deprecated return syntax foreach ($provided as $key => $value) { // Detect non-associative result for any key if (is_array($value) && $value === array_values($value)) { Deprecation::notice('5.0', 'Non-associative translations from providei18nEntities is deprecated'); $entity = array_filter([ 'default' => $value[0], 'comment' => isset($value[1]) ? $value[1] : null, 'module' => isset($value[2]) ? $value[2] : null, ]); if (count($entity) === 1) { $provided[$key] = $value[0]; } elseif ($entity) { $provided[$key] = $entity; } else { unset($provided[$key]); } } } $entities = array_merge($entities, $provided); } ksort($entities); return $entities; }
php
public function collectFromEntityProviders($filePath, Module $module = null) { $entities = array(); $classes = ClassInfo::classes_for_file($filePath); foreach ($classes as $class) { // Skip non-implementing classes if (!class_exists($class) || !is_a($class, i18nEntityProvider::class, true)) { continue; } // Skip abstract classes $reflectionClass = new ReflectionClass($class); if ($reflectionClass->isAbstract()) { continue; } /** @var i18nEntityProvider $obj */ $obj = singleton($class); $provided = $obj->provideI18nEntities(); // Handle deprecated return syntax foreach ($provided as $key => $value) { // Detect non-associative result for any key if (is_array($value) && $value === array_values($value)) { Deprecation::notice('5.0', 'Non-associative translations from providei18nEntities is deprecated'); $entity = array_filter([ 'default' => $value[0], 'comment' => isset($value[1]) ? $value[1] : null, 'module' => isset($value[2]) ? $value[2] : null, ]); if (count($entity) === 1) { $provided[$key] = $value[0]; } elseif ($entity) { $provided[$key] = $entity; } else { unset($provided[$key]); } } } $entities = array_merge($entities, $provided); } ksort($entities); return $entities; }
[ "public", "function", "collectFromEntityProviders", "(", "$", "filePath", ",", "Module", "$", "module", "=", "null", ")", "{", "$", "entities", "=", "array", "(", ")", ";", "$", "classes", "=", "ClassInfo", "::", "classes_for_file", "(", "$", "filePath", ")", ";", "foreach", "(", "$", "classes", "as", "$", "class", ")", "{", "// Skip non-implementing classes", "if", "(", "!", "class_exists", "(", "$", "class", ")", "||", "!", "is_a", "(", "$", "class", ",", "i18nEntityProvider", "::", "class", ",", "true", ")", ")", "{", "continue", ";", "}", "// Skip abstract classes", "$", "reflectionClass", "=", "new", "ReflectionClass", "(", "$", "class", ")", ";", "if", "(", "$", "reflectionClass", "->", "isAbstract", "(", ")", ")", "{", "continue", ";", "}", "/** @var i18nEntityProvider $obj */", "$", "obj", "=", "singleton", "(", "$", "class", ")", ";", "$", "provided", "=", "$", "obj", "->", "provideI18nEntities", "(", ")", ";", "// Handle deprecated return syntax", "foreach", "(", "$", "provided", "as", "$", "key", "=>", "$", "value", ")", "{", "// Detect non-associative result for any key", "if", "(", "is_array", "(", "$", "value", ")", "&&", "$", "value", "===", "array_values", "(", "$", "value", ")", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Non-associative translations from providei18nEntities is deprecated'", ")", ";", "$", "entity", "=", "array_filter", "(", "[", "'default'", "=>", "$", "value", "[", "0", "]", ",", "'comment'", "=>", "isset", "(", "$", "value", "[", "1", "]", ")", "?", "$", "value", "[", "1", "]", ":", "null", ",", "'module'", "=>", "isset", "(", "$", "value", "[", "2", "]", ")", "?", "$", "value", "[", "2", "]", ":", "null", ",", "]", ")", ";", "if", "(", "count", "(", "$", "entity", ")", "===", "1", ")", "{", "$", "provided", "[", "$", "key", "]", "=", "$", "value", "[", "0", "]", ";", "}", "elseif", "(", "$", "entity", ")", "{", "$", "provided", "[", "$", "key", "]", "=", "$", "entity", ";", "}", "else", "{", "unset", "(", "$", "provided", "[", "$", "key", "]", ")", ";", "}", "}", "}", "$", "entities", "=", "array_merge", "(", "$", "entities", ",", "$", "provided", ")", ";", "}", "ksort", "(", "$", "entities", ")", ";", "return", "$", "entities", ";", "}" ]
Allows classes which implement i18nEntityProvider to provide additional translation strings. Not all classes can be instanciated without mandatory arguments, so entity collection doesn't work for all SilverStripe classes currently @uses i18nEntityProvider @param string $filePath @param Module $module @return array
[ "Allows", "classes", "which", "implement", "i18nEntityProvider", "to", "provide", "additional", "translation", "strings", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L811-L854
train
silverstripe/silverstripe-framework
src/i18n/TextCollection/i18nTextCollector.php
i18nTextCollector.normalizeEntity
protected function normalizeEntity($fullName, $_namespace = null) { // split fullname into entity parts $entityParts = explode('.', $fullName); if (count($entityParts) > 1) { // templates don't have a custom namespace $entity = array_pop($entityParts); // namespace might contain dots, so we explode $namespace = implode('.', $entityParts); } else { $entity = array_pop($entityParts); $namespace = $_namespace; } // If a dollar sign is used in the entity name, // we can't resolve without running the method, // and skip the processing. This is mostly used for // dynamically translating static properties, e.g. looping // through $db, which are detected by {@link collectFromEntityProviders}. if ($entity && strpos('$', $entity) !== false) { return false; } return "{$namespace}.{$entity}"; }
php
protected function normalizeEntity($fullName, $_namespace = null) { // split fullname into entity parts $entityParts = explode('.', $fullName); if (count($entityParts) > 1) { // templates don't have a custom namespace $entity = array_pop($entityParts); // namespace might contain dots, so we explode $namespace = implode('.', $entityParts); } else { $entity = array_pop($entityParts); $namespace = $_namespace; } // If a dollar sign is used in the entity name, // we can't resolve without running the method, // and skip the processing. This is mostly used for // dynamically translating static properties, e.g. looping // through $db, which are detected by {@link collectFromEntityProviders}. if ($entity && strpos('$', $entity) !== false) { return false; } return "{$namespace}.{$entity}"; }
[ "protected", "function", "normalizeEntity", "(", "$", "fullName", ",", "$", "_namespace", "=", "null", ")", "{", "// split fullname into entity parts", "$", "entityParts", "=", "explode", "(", "'.'", ",", "$", "fullName", ")", ";", "if", "(", "count", "(", "$", "entityParts", ")", ">", "1", ")", "{", "// templates don't have a custom namespace", "$", "entity", "=", "array_pop", "(", "$", "entityParts", ")", ";", "// namespace might contain dots, so we explode", "$", "namespace", "=", "implode", "(", "'.'", ",", "$", "entityParts", ")", ";", "}", "else", "{", "$", "entity", "=", "array_pop", "(", "$", "entityParts", ")", ";", "$", "namespace", "=", "$", "_namespace", ";", "}", "// If a dollar sign is used in the entity name,", "// we can't resolve without running the method,", "// and skip the processing. This is mostly used for", "// dynamically translating static properties, e.g. looping", "// through $db, which are detected by {@link collectFromEntityProviders}.", "if", "(", "$", "entity", "&&", "strpos", "(", "'$'", ",", "$", "entity", ")", "!==", "false", ")", "{", "return", "false", ";", "}", "return", "\"{$namespace}.{$entity}\"", ";", "}" ]
Normalizes enitities with namespaces. @param string $fullName @param string $_namespace @return string|boolean FALSE
[ "Normalizes", "enitities", "with", "namespaces", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/TextCollection/i18nTextCollector.php#L863-L887
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.getValidSubClasses
public static function getValidSubClasses($class = SiteTree::class, $includeUnbacked = false) { if (is_string($class) && !class_exists($class)) { return array(); } $class = self::class_name($class); if ($includeUnbacked) { $table = DataObject::getSchema()->tableName($class); $classes = DB::get_schema()->enumValuesForField($table, 'ClassName'); } else { $classes = static::subclassesFor($class); } return $classes; }
php
public static function getValidSubClasses($class = SiteTree::class, $includeUnbacked = false) { if (is_string($class) && !class_exists($class)) { return array(); } $class = self::class_name($class); if ($includeUnbacked) { $table = DataObject::getSchema()->tableName($class); $classes = DB::get_schema()->enumValuesForField($table, 'ClassName'); } else { $classes = static::subclassesFor($class); } return $classes; }
[ "public", "static", "function", "getValidSubClasses", "(", "$", "class", "=", "SiteTree", "::", "class", ",", "$", "includeUnbacked", "=", "false", ")", "{", "if", "(", "is_string", "(", "$", "class", ")", "&&", "!", "class_exists", "(", "$", "class", ")", ")", "{", "return", "array", "(", ")", ";", "}", "$", "class", "=", "self", "::", "class_name", "(", "$", "class", ")", ";", "if", "(", "$", "includeUnbacked", ")", "{", "$", "table", "=", "DataObject", "::", "getSchema", "(", ")", "->", "tableName", "(", "$", "class", ")", ";", "$", "classes", "=", "DB", "::", "get_schema", "(", ")", "->", "enumValuesForField", "(", "$", "table", ",", "'ClassName'", ")", ";", "}", "else", "{", "$", "classes", "=", "static", "::", "subclassesFor", "(", "$", "class", ")", ";", "}", "return", "$", "classes", ";", "}" ]
Returns the manifest of all classes which are present in the database. @param string $class Class name to check enum values for ClassName field @param boolean $includeUnbacked Flag indicating whether or not to include types that don't exist as implemented classes. By default these are excluded. @return array List of subclasses
[ "Returns", "the", "manifest", "of", "all", "classes", "which", "are", "present", "in", "the", "database", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L113-L127
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.dataClassesFor
public static function dataClassesFor($nameOrObject) { if (is_string($nameOrObject) && !class_exists($nameOrObject)) { return []; } // Get all classes $class = self::class_name($nameOrObject); $classes = array_merge( self::ancestry($class), self::subclassesFor($class) ); // Filter by table return array_filter($classes, function ($next) { return DataObject::getSchema()->classHasTable($next); }); }
php
public static function dataClassesFor($nameOrObject) { if (is_string($nameOrObject) && !class_exists($nameOrObject)) { return []; } // Get all classes $class = self::class_name($nameOrObject); $classes = array_merge( self::ancestry($class), self::subclassesFor($class) ); // Filter by table return array_filter($classes, function ($next) { return DataObject::getSchema()->classHasTable($next); }); }
[ "public", "static", "function", "dataClassesFor", "(", "$", "nameOrObject", ")", "{", "if", "(", "is_string", "(", "$", "nameOrObject", ")", "&&", "!", "class_exists", "(", "$", "nameOrObject", ")", ")", "{", "return", "[", "]", ";", "}", "// Get all classes", "$", "class", "=", "self", "::", "class_name", "(", "$", "nameOrObject", ")", ";", "$", "classes", "=", "array_merge", "(", "self", "::", "ancestry", "(", "$", "class", ")", ",", "self", "::", "subclassesFor", "(", "$", "class", ")", ")", ";", "// Filter by table", "return", "array_filter", "(", "$", "classes", ",", "function", "(", "$", "next", ")", "{", "return", "DataObject", "::", "getSchema", "(", ")", "->", "classHasTable", "(", "$", "next", ")", ";", "}", ")", ";", "}" ]
Returns an array of the current class and all its ancestors and children which require a DB table. @todo Move this into {@see DataObjectSchema} @param string|object $nameOrObject Class or object instance @return array
[ "Returns", "an", "array", "of", "the", "current", "class", "and", "all", "its", "ancestors", "and", "children", "which", "require", "a", "DB", "table", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L138-L155
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.class_name
public static function class_name($nameOrObject) { if (is_object($nameOrObject)) { return get_class($nameOrObject); } $key = strtolower($nameOrObject); if (!isset(static::$_cache_class_names[$key])) { // Get manifest name $name = ClassLoader::inst()->getManifest()->getItemName($nameOrObject); // Use reflection for non-manifest classes if (!$name) { $reflection = new ReflectionClass($nameOrObject); $name = $reflection->getName(); } static::$_cache_class_names[$key] = $name; } return static::$_cache_class_names[$key]; }
php
public static function class_name($nameOrObject) { if (is_object($nameOrObject)) { return get_class($nameOrObject); } $key = strtolower($nameOrObject); if (!isset(static::$_cache_class_names[$key])) { // Get manifest name $name = ClassLoader::inst()->getManifest()->getItemName($nameOrObject); // Use reflection for non-manifest classes if (!$name) { $reflection = new ReflectionClass($nameOrObject); $name = $reflection->getName(); } static::$_cache_class_names[$key] = $name; } return static::$_cache_class_names[$key]; }
[ "public", "static", "function", "class_name", "(", "$", "nameOrObject", ")", "{", "if", "(", "is_object", "(", "$", "nameOrObject", ")", ")", "{", "return", "get_class", "(", "$", "nameOrObject", ")", ";", "}", "$", "key", "=", "strtolower", "(", "$", "nameOrObject", ")", ";", "if", "(", "!", "isset", "(", "static", "::", "$", "_cache_class_names", "[", "$", "key", "]", ")", ")", "{", "// Get manifest name", "$", "name", "=", "ClassLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", "->", "getItemName", "(", "$", "nameOrObject", ")", ";", "// Use reflection for non-manifest classes", "if", "(", "!", "$", "name", ")", "{", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "nameOrObject", ")", ";", "$", "name", "=", "$", "reflection", "->", "getName", "(", ")", ";", "}", "static", "::", "$", "_cache_class_names", "[", "$", "key", "]", "=", "$", "name", ";", "}", "return", "static", "::", "$", "_cache_class_names", "[", "$", "key", "]", ";", "}" ]
Convert a class name in any case and return it as it was defined in PHP eg: self::class_name('dataobJEct'); //returns 'DataObject' @param string|object $nameOrObject The classname or object you want to normalise @throws \ReflectionException @return string The normalised class name
[ "Convert", "a", "class", "name", "in", "any", "case", "and", "return", "it", "as", "it", "was", "defined", "in", "PHP" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L216-L236
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.ancestry
public static function ancestry($nameOrObject, $tablesOnly = false) { if (is_string($nameOrObject) && !class_exists($nameOrObject)) { return []; } $class = self::class_name($nameOrObject); $lowerClass = strtolower($class); $cacheKey = $lowerClass . '_' . (string)$tablesOnly; $parent = $class; if (!isset(self::$_cache_ancestry[$cacheKey])) { $ancestry = []; do { if (!$tablesOnly || DataObject::getSchema()->classHasTable($parent)) { $ancestry[strtolower($parent)] = $parent; } } while ($parent = get_parent_class($parent)); self::$_cache_ancestry[$cacheKey] = array_reverse($ancestry); } return self::$_cache_ancestry[$cacheKey]; }
php
public static function ancestry($nameOrObject, $tablesOnly = false) { if (is_string($nameOrObject) && !class_exists($nameOrObject)) { return []; } $class = self::class_name($nameOrObject); $lowerClass = strtolower($class); $cacheKey = $lowerClass . '_' . (string)$tablesOnly; $parent = $class; if (!isset(self::$_cache_ancestry[$cacheKey])) { $ancestry = []; do { if (!$tablesOnly || DataObject::getSchema()->classHasTable($parent)) { $ancestry[strtolower($parent)] = $parent; } } while ($parent = get_parent_class($parent)); self::$_cache_ancestry[$cacheKey] = array_reverse($ancestry); } return self::$_cache_ancestry[$cacheKey]; }
[ "public", "static", "function", "ancestry", "(", "$", "nameOrObject", ",", "$", "tablesOnly", "=", "false", ")", "{", "if", "(", "is_string", "(", "$", "nameOrObject", ")", "&&", "!", "class_exists", "(", "$", "nameOrObject", ")", ")", "{", "return", "[", "]", ";", "}", "$", "class", "=", "self", "::", "class_name", "(", "$", "nameOrObject", ")", ";", "$", "lowerClass", "=", "strtolower", "(", "$", "class", ")", ";", "$", "cacheKey", "=", "$", "lowerClass", ".", "'_'", ".", "(", "string", ")", "$", "tablesOnly", ";", "$", "parent", "=", "$", "class", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "_cache_ancestry", "[", "$", "cacheKey", "]", ")", ")", "{", "$", "ancestry", "=", "[", "]", ";", "do", "{", "if", "(", "!", "$", "tablesOnly", "||", "DataObject", "::", "getSchema", "(", ")", "->", "classHasTable", "(", "$", "parent", ")", ")", "{", "$", "ancestry", "[", "strtolower", "(", "$", "parent", ")", "]", "=", "$", "parent", ";", "}", "}", "while", "(", "$", "parent", "=", "get_parent_class", "(", "$", "parent", ")", ")", ";", "self", "::", "$", "_cache_ancestry", "[", "$", "cacheKey", "]", "=", "array_reverse", "(", "$", "ancestry", ")", ";", "}", "return", "self", "::", "$", "_cache_ancestry", "[", "$", "cacheKey", "]", ";", "}" ]
Returns the passed class name along with all its parent class names in an array, sorted with the root class first. @param string|object $nameOrObject Class or object instance @param bool $tablesOnly Only return classes that have a table in the db. @return array List of class names with lowercase keys and correct-case values
[ "Returns", "the", "passed", "class", "name", "along", "with", "all", "its", "parent", "class", "names", "in", "an", "array", "sorted", "with", "the", "root", "class", "first", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L246-L269
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.classImplements
public static function classImplements($className, $interfaceName) { $lowerClassName = strtolower($className); $implementors = self::implementorsOf($interfaceName); return isset($implementors[$lowerClassName]); }
php
public static function classImplements($className, $interfaceName) { $lowerClassName = strtolower($className); $implementors = self::implementorsOf($interfaceName); return isset($implementors[$lowerClassName]); }
[ "public", "static", "function", "classImplements", "(", "$", "className", ",", "$", "interfaceName", ")", "{", "$", "lowerClassName", "=", "strtolower", "(", "$", "className", ")", ";", "$", "implementors", "=", "self", "::", "implementorsOf", "(", "$", "interfaceName", ")", ";", "return", "isset", "(", "$", "implementors", "[", "$", "lowerClassName", "]", ")", ";", "}" ]
Returns true if the given class implements the given interface @param string $className @param string $interfaceName @return bool
[ "Returns", "true", "if", "the", "given", "class", "implements", "the", "given", "interface" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L288-L293
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.classes_for_file
public static function classes_for_file($filePath) { $absFilePath = Director::getAbsFile($filePath); $classManifest = ClassLoader::inst()->getManifest(); $classes = $classManifest->getClasses(); $classNames = $classManifest->getClassNames(); $matchedClasses = []; foreach ($classes as $lowerClass => $compareFilePath) { if (strcasecmp($absFilePath, $compareFilePath) === 0) { $matchedClasses[$lowerClass] = $classNames[$lowerClass]; } } return $matchedClasses; }
php
public static function classes_for_file($filePath) { $absFilePath = Director::getAbsFile($filePath); $classManifest = ClassLoader::inst()->getManifest(); $classes = $classManifest->getClasses(); $classNames = $classManifest->getClassNames(); $matchedClasses = []; foreach ($classes as $lowerClass => $compareFilePath) { if (strcasecmp($absFilePath, $compareFilePath) === 0) { $matchedClasses[$lowerClass] = $classNames[$lowerClass]; } } return $matchedClasses; }
[ "public", "static", "function", "classes_for_file", "(", "$", "filePath", ")", "{", "$", "absFilePath", "=", "Director", "::", "getAbsFile", "(", "$", "filePath", ")", ";", "$", "classManifest", "=", "ClassLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", ";", "$", "classes", "=", "$", "classManifest", "->", "getClasses", "(", ")", ";", "$", "classNames", "=", "$", "classManifest", "->", "getClassNames", "(", ")", ";", "$", "matchedClasses", "=", "[", "]", ";", "foreach", "(", "$", "classes", "as", "$", "lowerClass", "=>", "$", "compareFilePath", ")", "{", "if", "(", "strcasecmp", "(", "$", "absFilePath", ",", "$", "compareFilePath", ")", "===", "0", ")", "{", "$", "matchedClasses", "[", "$", "lowerClass", "]", "=", "$", "classNames", "[", "$", "lowerClass", "]", ";", "}", "}", "return", "$", "matchedClasses", ";", "}" ]
Get all classes contained in a file. @param string $filePath Path to a PHP file (absolute or relative to webroot) @return array Map of lowercase class names to correct class name
[ "Get", "all", "classes", "contained", "in", "a", "file", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L301-L316
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.classes_for_folder
public static function classes_for_folder($folderPath) { $absFolderPath = Director::getAbsFile($folderPath); $classManifest = ClassLoader::inst()->getManifest(); $classes = $classManifest->getClasses(); $classNames = $classManifest->getClassNames(); $matchedClasses = []; foreach ($classes as $lowerClass => $compareFilePath) { if (stripos($compareFilePath, $absFolderPath) === 0) { $matchedClasses[$lowerClass] = $classNames[$lowerClass]; } } return $matchedClasses; }
php
public static function classes_for_folder($folderPath) { $absFolderPath = Director::getAbsFile($folderPath); $classManifest = ClassLoader::inst()->getManifest(); $classes = $classManifest->getClasses(); $classNames = $classManifest->getClassNames(); $matchedClasses = []; foreach ($classes as $lowerClass => $compareFilePath) { if (stripos($compareFilePath, $absFolderPath) === 0) { $matchedClasses[$lowerClass] = $classNames[$lowerClass]; } } return $matchedClasses; }
[ "public", "static", "function", "classes_for_folder", "(", "$", "folderPath", ")", "{", "$", "absFolderPath", "=", "Director", "::", "getAbsFile", "(", "$", "folderPath", ")", ";", "$", "classManifest", "=", "ClassLoader", "::", "inst", "(", ")", "->", "getManifest", "(", ")", ";", "$", "classes", "=", "$", "classManifest", "->", "getClasses", "(", ")", ";", "$", "classNames", "=", "$", "classManifest", "->", "getClassNames", "(", ")", ";", "$", "matchedClasses", "=", "[", "]", ";", "foreach", "(", "$", "classes", "as", "$", "lowerClass", "=>", "$", "compareFilePath", ")", "{", "if", "(", "stripos", "(", "$", "compareFilePath", ",", "$", "absFolderPath", ")", "===", "0", ")", "{", "$", "matchedClasses", "[", "$", "lowerClass", "]", "=", "$", "classNames", "[", "$", "lowerClass", "]", ";", "}", "}", "return", "$", "matchedClasses", ";", "}" ]
Returns all classes contained in a certain folder. @param string $folderPath Relative or absolute folder path @return array Map of lowercase class names to correct class name
[ "Returns", "all", "classes", "contained", "in", "a", "certain", "folder", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L324-L339
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.has_method_from
public static function has_method_from($class, $method, $compclass) { $lClass = strtolower($class); $lMethod = strtolower($method); $lCompclass = strtolower($compclass); if (!isset(self::$_cache_methods[$lClass])) { self::$_cache_methods[$lClass] = array(); } if (!array_key_exists($lMethod, self::$_cache_methods[$lClass])) { self::$_cache_methods[$lClass][$lMethod] = false; $classRef = new ReflectionClass($class); if ($classRef->hasMethod($method)) { $methodRef = $classRef->getMethod($method); self::$_cache_methods[$lClass][$lMethod] = $methodRef->getDeclaringClass()->getName(); } } return strtolower(self::$_cache_methods[$lClass][$lMethod]) === $lCompclass; }
php
public static function has_method_from($class, $method, $compclass) { $lClass = strtolower($class); $lMethod = strtolower($method); $lCompclass = strtolower($compclass); if (!isset(self::$_cache_methods[$lClass])) { self::$_cache_methods[$lClass] = array(); } if (!array_key_exists($lMethod, self::$_cache_methods[$lClass])) { self::$_cache_methods[$lClass][$lMethod] = false; $classRef = new ReflectionClass($class); if ($classRef->hasMethod($method)) { $methodRef = $classRef->getMethod($method); self::$_cache_methods[$lClass][$lMethod] = $methodRef->getDeclaringClass()->getName(); } } return strtolower(self::$_cache_methods[$lClass][$lMethod]) === $lCompclass; }
[ "public", "static", "function", "has_method_from", "(", "$", "class", ",", "$", "method", ",", "$", "compclass", ")", "{", "$", "lClass", "=", "strtolower", "(", "$", "class", ")", ";", "$", "lMethod", "=", "strtolower", "(", "$", "method", ")", ";", "$", "lCompclass", "=", "strtolower", "(", "$", "compclass", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "_cache_methods", "[", "$", "lClass", "]", ")", ")", "{", "self", "::", "$", "_cache_methods", "[", "$", "lClass", "]", "=", "array", "(", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "lMethod", ",", "self", "::", "$", "_cache_methods", "[", "$", "lClass", "]", ")", ")", "{", "self", "::", "$", "_cache_methods", "[", "$", "lClass", "]", "[", "$", "lMethod", "]", "=", "false", ";", "$", "classRef", "=", "new", "ReflectionClass", "(", "$", "class", ")", ";", "if", "(", "$", "classRef", "->", "hasMethod", "(", "$", "method", ")", ")", "{", "$", "methodRef", "=", "$", "classRef", "->", "getMethod", "(", "$", "method", ")", ";", "self", "::", "$", "_cache_methods", "[", "$", "lClass", "]", "[", "$", "lMethod", "]", "=", "$", "methodRef", "->", "getDeclaringClass", "(", ")", "->", "getName", "(", ")", ";", "}", "}", "return", "strtolower", "(", "self", "::", "$", "_cache_methods", "[", "$", "lClass", "]", "[", "$", "lMethod", "]", ")", "===", "$", "lCompclass", ";", "}" ]
Determine if the given class method is implemented at the given comparison class @param string $class Class to get methods from @param string $method Method name to lookup @param string $compclass Parent class to test if this is the implementor @return bool True if $class::$method is declared in $compclass
[ "Determine", "if", "the", "given", "class", "method", "is", "implemented", "at", "the", "given", "comparison", "class" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L349-L370
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.shortName
public static function shortName($nameOrObject) { $name = static::class_name($nameOrObject); $parts = explode('\\', $name); return end($parts); }
php
public static function shortName($nameOrObject) { $name = static::class_name($nameOrObject); $parts = explode('\\', $name); return end($parts); }
[ "public", "static", "function", "shortName", "(", "$", "nameOrObject", ")", "{", "$", "name", "=", "static", "::", "class_name", "(", "$", "nameOrObject", ")", ";", "$", "parts", "=", "explode", "(", "'\\\\'", ",", "$", "name", ")", ";", "return", "end", "(", "$", "parts", ")", ";", "}" ]
Strip namespace from class @param string|object $nameOrObject Name of class, or instance @return string Name of class without namespace
[ "Strip", "namespace", "from", "class" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L387-L392
train
silverstripe/silverstripe-framework
src/Core/ClassInfo.php
ClassInfo.hasMethod
public static function hasMethod($object, $method) { if (empty($object)) { return false; } if (method_exists($object, $method)) { return true; } return method_exists($object, 'hasMethod') && $object->hasMethod($method); }
php
public static function hasMethod($object, $method) { if (empty($object)) { return false; } if (method_exists($object, $method)) { return true; } return method_exists($object, 'hasMethod') && $object->hasMethod($method); }
[ "public", "static", "function", "hasMethod", "(", "$", "object", ",", "$", "method", ")", "{", "if", "(", "empty", "(", "$", "object", ")", ")", "{", "return", "false", ";", "}", "if", "(", "method_exists", "(", "$", "object", ",", "$", "method", ")", ")", "{", "return", "true", ";", "}", "return", "method_exists", "(", "$", "object", ",", "'hasMethod'", ")", "&&", "$", "object", "->", "hasMethod", "(", "$", "method", ")", ";", "}" ]
Helper to determine if the given object has a method @param object $object @param string $method @return bool
[ "Helper", "to", "determine", "if", "the", "given", "object", "has", "a", "method" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/ClassInfo.php#L401-L410
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.isLockedOut
public function isLockedOut() { /** @var DBDatetime $lockedOutUntilObj */ $lockedOutUntilObj = $this->dbObject('LockedOutUntil'); if ($lockedOutUntilObj->InFuture()) { return true; } $maxAttempts = $this->config()->get('lock_out_after_incorrect_logins'); if ($maxAttempts <= 0) { return false; } $idField = static::config()->get('unique_identifier_field'); $attempts = LoginAttempt::getByEmail($this->{$idField}) ->sort('Created', 'DESC') ->limit($maxAttempts); if ($attempts->count() < $maxAttempts) { return false; } foreach ($attempts as $attempt) { if ($attempt->Status === 'Success') { return false; } } // Calculate effective LockedOutUntil /** @var DBDatetime $firstFailureDate */ $firstFailureDate = $attempts->first()->dbObject('Created'); $maxAgeSeconds = $this->config()->get('lock_out_delay_mins') * 60; $lockedOutUntil = $firstFailureDate->getTimestamp() + $maxAgeSeconds; $now = DBDatetime::now()->getTimestamp(); if ($now < $lockedOutUntil) { return true; } return false; }
php
public function isLockedOut() { /** @var DBDatetime $lockedOutUntilObj */ $lockedOutUntilObj = $this->dbObject('LockedOutUntil'); if ($lockedOutUntilObj->InFuture()) { return true; } $maxAttempts = $this->config()->get('lock_out_after_incorrect_logins'); if ($maxAttempts <= 0) { return false; } $idField = static::config()->get('unique_identifier_field'); $attempts = LoginAttempt::getByEmail($this->{$idField}) ->sort('Created', 'DESC') ->limit($maxAttempts); if ($attempts->count() < $maxAttempts) { return false; } foreach ($attempts as $attempt) { if ($attempt->Status === 'Success') { return false; } } // Calculate effective LockedOutUntil /** @var DBDatetime $firstFailureDate */ $firstFailureDate = $attempts->first()->dbObject('Created'); $maxAgeSeconds = $this->config()->get('lock_out_delay_mins') * 60; $lockedOutUntil = $firstFailureDate->getTimestamp() + $maxAgeSeconds; $now = DBDatetime::now()->getTimestamp(); if ($now < $lockedOutUntil) { return true; } return false; }
[ "public", "function", "isLockedOut", "(", ")", "{", "/** @var DBDatetime $lockedOutUntilObj */", "$", "lockedOutUntilObj", "=", "$", "this", "->", "dbObject", "(", "'LockedOutUntil'", ")", ";", "if", "(", "$", "lockedOutUntilObj", "->", "InFuture", "(", ")", ")", "{", "return", "true", ";", "}", "$", "maxAttempts", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'lock_out_after_incorrect_logins'", ")", ";", "if", "(", "$", "maxAttempts", "<=", "0", ")", "{", "return", "false", ";", "}", "$", "idField", "=", "static", "::", "config", "(", ")", "->", "get", "(", "'unique_identifier_field'", ")", ";", "$", "attempts", "=", "LoginAttempt", "::", "getByEmail", "(", "$", "this", "->", "{", "$", "idField", "}", ")", "->", "sort", "(", "'Created'", ",", "'DESC'", ")", "->", "limit", "(", "$", "maxAttempts", ")", ";", "if", "(", "$", "attempts", "->", "count", "(", ")", "<", "$", "maxAttempts", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "attempts", "as", "$", "attempt", ")", "{", "if", "(", "$", "attempt", "->", "Status", "===", "'Success'", ")", "{", "return", "false", ";", "}", "}", "// Calculate effective LockedOutUntil", "/** @var DBDatetime $firstFailureDate */", "$", "firstFailureDate", "=", "$", "attempts", "->", "first", "(", ")", "->", "dbObject", "(", "'Created'", ")", ";", "$", "maxAgeSeconds", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'lock_out_delay_mins'", ")", "*", "60", ";", "$", "lockedOutUntil", "=", "$", "firstFailureDate", "->", "getTimestamp", "(", ")", "+", "$", "maxAgeSeconds", ";", "$", "now", "=", "DBDatetime", "::", "now", "(", ")", "->", "getTimestamp", "(", ")", ";", "if", "(", "$", "now", "<", "$", "lockedOutUntil", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Returns true if this user is locked out @skipUpgrade @return bool
[ "Returns", "true", "if", "this", "user", "is", "locked", "out" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L372-L411
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.regenerateTempID
public function regenerateTempID() { $generator = new RandomGenerator(); $lifetime = self::config()->get('temp_id_lifetime'); $this->TempIDHash = $generator->randomToken('sha1'); $this->TempIDExpired = $lifetime ? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + $lifetime) : null; $this->write(); }
php
public function regenerateTempID() { $generator = new RandomGenerator(); $lifetime = self::config()->get('temp_id_lifetime'); $this->TempIDHash = $generator->randomToken('sha1'); $this->TempIDExpired = $lifetime ? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + $lifetime) : null; $this->write(); }
[ "public", "function", "regenerateTempID", "(", ")", "{", "$", "generator", "=", "new", "RandomGenerator", "(", ")", ";", "$", "lifetime", "=", "self", "::", "config", "(", ")", "->", "get", "(", "'temp_id_lifetime'", ")", ";", "$", "this", "->", "TempIDHash", "=", "$", "generator", "->", "randomToken", "(", "'sha1'", ")", ";", "$", "this", "->", "TempIDExpired", "=", "$", "lifetime", "?", "date", "(", "'Y-m-d H:i:s'", ",", "strtotime", "(", "DBDatetime", "::", "now", "(", ")", "->", "getValue", "(", ")", ")", "+", "$", "lifetime", ")", ":", "null", ";", "$", "this", "->", "write", "(", ")", ";", "}" ]
Trigger regeneration of TempID. This should be performed any time the user presents their normal identification (normally Email) and is successfully authenticated.
[ "Trigger", "regeneration", "of", "TempID", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L497-L506
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.logged_in_session_exists
public static function logged_in_session_exists() { Deprecation::notice( '5.0.0', 'This method is deprecated and now does not add value. Please use Security::getCurrentUser()' ); $member = Security::getCurrentUser(); if ($member && $member->exists()) { return true; } return false; }
php
public static function logged_in_session_exists() { Deprecation::notice( '5.0.0', 'This method is deprecated and now does not add value. Please use Security::getCurrentUser()' ); $member = Security::getCurrentUser(); if ($member && $member->exists()) { return true; } return false; }
[ "public", "static", "function", "logged_in_session_exists", "(", ")", "{", "Deprecation", "::", "notice", "(", "'5.0.0'", ",", "'This method is deprecated and now does not add value. Please use Security::getCurrentUser()'", ")", ";", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "if", "(", "$", "member", "&&", "$", "member", "->", "exists", "(", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check if the member ID logged in session actually has a database record of the same ID. If there is no logged in user, FALSE is returned anyway. @deprecated Not needed anymore, as it returns Security::getCurrentUser(); @return boolean TRUE record found FALSE no record found
[ "Check", "if", "the", "member", "ID", "logged", "in", "session", "actually", "has", "a", "database", "record", "of", "the", "same", "ID", ".", "If", "there", "is", "no", "logged", "in", "user", "FALSE", "is", "returned", "anyway", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L517-L530
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.encryptWithUserSettings
public function encryptWithUserSettings($string) { if (!$string) { return null; } // If the algorithm or salt is not available, it means we are operating // on legacy account with unhashed password. Do not hash the string. if (!$this->PasswordEncryption) { return $string; } // We assume we have PasswordEncryption and Salt available here. $e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption); return $e->encrypt($string, $this->Salt); }
php
public function encryptWithUserSettings($string) { if (!$string) { return null; } // If the algorithm or salt is not available, it means we are operating // on legacy account with unhashed password. Do not hash the string. if (!$this->PasswordEncryption) { return $string; } // We assume we have PasswordEncryption and Salt available here. $e = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption); return $e->encrypt($string, $this->Salt); }
[ "public", "function", "encryptWithUserSettings", "(", "$", "string", ")", "{", "if", "(", "!", "$", "string", ")", "{", "return", "null", ";", "}", "// If the algorithm or salt is not available, it means we are operating", "// on legacy account with unhashed password. Do not hash the string.", "if", "(", "!", "$", "this", "->", "PasswordEncryption", ")", "{", "return", "$", "string", ";", "}", "// We assume we have PasswordEncryption and Salt available here.", "$", "e", "=", "PasswordEncryptor", "::", "create_for_algorithm", "(", "$", "this", "->", "PasswordEncryption", ")", ";", "return", "$", "e", "->", "encrypt", "(", "$", "string", ",", "$", "this", "->", "Salt", ")", ";", "}" ]
Utility for generating secure password hashes for this member. @param string $string @return string @throws PasswordEncryptor_NotFoundException
[ "Utility", "for", "generating", "secure", "password", "hashes", "for", "this", "member", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L573-L589
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.generateAutologinTokenAndStoreHash
public function generateAutologinTokenAndStoreHash($lifetime = null) { if ($lifetime !== null) { Deprecation::notice( '5.0', 'Passing a $lifetime to Member::generateAutologinTokenAndStoreHash() is deprecated, use the Member.auto_login_token_lifetime config setting instead', Deprecation::SCOPE_GLOBAL ); $lifetime = (86400 * $lifetime); // Method argument is days, convert to seconds } else { $lifetime = $this->config()->auto_login_token_lifetime; } do { $generator = new RandomGenerator(); $token = $generator->randomToken(); $hash = $this->encryptWithUserSettings($token); } while (DataObject::get_one(Member::class, array( '"Member"."AutoLoginHash"' => $hash ))); $this->AutoLoginHash = $hash; $this->AutoLoginExpired = date('Y-m-d H:i:s', time() + $lifetime); $this->write(); return $token; }
php
public function generateAutologinTokenAndStoreHash($lifetime = null) { if ($lifetime !== null) { Deprecation::notice( '5.0', 'Passing a $lifetime to Member::generateAutologinTokenAndStoreHash() is deprecated, use the Member.auto_login_token_lifetime config setting instead', Deprecation::SCOPE_GLOBAL ); $lifetime = (86400 * $lifetime); // Method argument is days, convert to seconds } else { $lifetime = $this->config()->auto_login_token_lifetime; } do { $generator = new RandomGenerator(); $token = $generator->randomToken(); $hash = $this->encryptWithUserSettings($token); } while (DataObject::get_one(Member::class, array( '"Member"."AutoLoginHash"' => $hash ))); $this->AutoLoginHash = $hash; $this->AutoLoginExpired = date('Y-m-d H:i:s', time() + $lifetime); $this->write(); return $token; }
[ "public", "function", "generateAutologinTokenAndStoreHash", "(", "$", "lifetime", "=", "null", ")", "{", "if", "(", "$", "lifetime", "!==", "null", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Passing a $lifetime to Member::generateAutologinTokenAndStoreHash() is deprecated,\n use the Member.auto_login_token_lifetime config setting instead'", ",", "Deprecation", "::", "SCOPE_GLOBAL", ")", ";", "$", "lifetime", "=", "(", "86400", "*", "$", "lifetime", ")", ";", "// Method argument is days, convert to seconds", "}", "else", "{", "$", "lifetime", "=", "$", "this", "->", "config", "(", ")", "->", "auto_login_token_lifetime", ";", "}", "do", "{", "$", "generator", "=", "new", "RandomGenerator", "(", ")", ";", "$", "token", "=", "$", "generator", "->", "randomToken", "(", ")", ";", "$", "hash", "=", "$", "this", "->", "encryptWithUserSettings", "(", "$", "token", ")", ";", "}", "while", "(", "DataObject", "::", "get_one", "(", "Member", "::", "class", ",", "array", "(", "'\"Member\".\"AutoLoginHash\"'", "=>", "$", "hash", ")", ")", ")", ";", "$", "this", "->", "AutoLoginHash", "=", "$", "hash", ";", "$", "this", "->", "AutoLoginExpired", "=", "date", "(", "'Y-m-d H:i:s'", ",", "time", "(", ")", "+", "$", "lifetime", ")", ";", "$", "this", "->", "write", "(", ")", ";", "return", "$", "token", ";", "}" ]
Generate an auto login token which can be used to reset the password, at the same time hashing it and storing in the database. @param int|null $lifetime DEPRECATED: The lifetime of the auto login hash in days. Overrides the Member.auto_login_token_lifetime config value @return string Token that should be passed to the client (but NOT persisted).
[ "Generate", "an", "auto", "login", "token", "which", "can", "be", "used", "to", "reset", "the", "password", "at", "the", "same", "time", "hashing", "it", "and", "storing", "in", "the", "database", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L599-L627
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.validateAutoLoginToken
public function validateAutoLoginToken($autologinToken) { $hash = $this->encryptWithUserSettings($autologinToken); $member = self::member_from_autologinhash($hash, false); return (bool)$member; }
php
public function validateAutoLoginToken($autologinToken) { $hash = $this->encryptWithUserSettings($autologinToken); $member = self::member_from_autologinhash($hash, false); return (bool)$member; }
[ "public", "function", "validateAutoLoginToken", "(", "$", "autologinToken", ")", "{", "$", "hash", "=", "$", "this", "->", "encryptWithUserSettings", "(", "$", "autologinToken", ")", ";", "$", "member", "=", "self", "::", "member_from_autologinhash", "(", "$", "hash", ",", "false", ")", ";", "return", "(", "bool", ")", "$", "member", ";", "}" ]
Check the token against the member. @param string $autologinToken @returns bool Is token valid?
[ "Check", "the", "token", "against", "the", "member", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L636-L642
train
silverstripe/silverstripe-framework
src/Security/Member.php
Member.member_from_autologinhash
public static function member_from_autologinhash($hash, $login = false) { /** @var Member $member */ $member = static::get()->filter([ 'AutoLoginHash' => $hash, 'AutoLoginExpired:GreaterThan' => DBDatetime::now()->getValue(), ])->first(); if ($login && $member) { Injector::inst()->get(IdentityStore::class)->logIn($member); } return $member; }
php
public static function member_from_autologinhash($hash, $login = false) { /** @var Member $member */ $member = static::get()->filter([ 'AutoLoginHash' => $hash, 'AutoLoginExpired:GreaterThan' => DBDatetime::now()->getValue(), ])->first(); if ($login && $member) { Injector::inst()->get(IdentityStore::class)->logIn($member); } return $member; }
[ "public", "static", "function", "member_from_autologinhash", "(", "$", "hash", ",", "$", "login", "=", "false", ")", "{", "/** @var Member $member */", "$", "member", "=", "static", "::", "get", "(", ")", "->", "filter", "(", "[", "'AutoLoginHash'", "=>", "$", "hash", ",", "'AutoLoginExpired:GreaterThan'", "=>", "DBDatetime", "::", "now", "(", ")", "->", "getValue", "(", ")", ",", "]", ")", "->", "first", "(", ")", ";", "if", "(", "$", "login", "&&", "$", "member", ")", "{", "Injector", "::", "inst", "(", ")", "->", "get", "(", "IdentityStore", "::", "class", ")", "->", "logIn", "(", "$", "member", ")", ";", "}", "return", "$", "member", ";", "}" ]
Return the member for the auto login hash @param string $hash The hash key @param bool $login Should the member be logged in? @return Member the matching member, if valid @return Member
[ "Return", "the", "member", "for", "the", "auto", "login", "hash" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Member.php#L653-L666
train