Compare commits

..

2 Commits

Author SHA1 Message Date
Guy Sartorelli
034619622a
Merge 25126267af into ba97de9458 2024-10-22 05:30:41 +13:00
Guy Sartorelli
25126267af
API Refactor template layer into its own module
Includes the following large-scale changes:
- Impoved barrier between model and view layers
- Improved casting of scalar to relevant DBField types
- Improved capabilities for rendering arbitrary data in templates
2024-10-14 15:56:44 +13:00
16 changed files with 54 additions and 56 deletions

View File

@ -8,11 +8,12 @@ use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injectable; use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\View\Requirements; use SilverStripe\View\Requirements;
use Stringable;
/** /**
* Represents a response returned by a controller. * Represents a response returned by a controller.
*/ */
class HTTPResponse class HTTPResponse implements Stringable
{ {
use Injectable; use Injectable;
@ -445,7 +446,7 @@ EOT
/** /**
* The HTTP response represented as a raw string * The HTTP response represented as a raw string
*/ */
public function __toString() public function __toString(): string
{ {
$headers = []; $headers = [];
foreach ($this->getHeaders() as $header => $values) { foreach ($this->getHeaders() as $header => $values) {

View File

@ -511,7 +511,7 @@ trait Extensible
// Setup all extension instances for this instance // Setup all extension instances for this instance
$this->extension_instances = []; $this->extension_instances = [];
foreach (ClassInfo::ancestry(static::class) as $class) { foreach (ClassInfo::ancestry(static::class) as $class) {
if (in_array($class, self::class::$unextendable_classes)) { if (in_array($class, self::$unextendable_classes)) {
continue; continue;
} }
$extensions = Config::inst()->get($class, 'extensions', Config::UNINHERITED | Config::EXCLUDE_EXTRA_SOURCES); $extensions = Config::inst()->get($class, 'extensions', Config::UNINHERITED | Config::EXCLUDE_EXTRA_SOURCES);

View File

@ -5,12 +5,13 @@ namespace SilverStripe\Core\Manifest;
use InvalidArgumentException; use InvalidArgumentException;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Path; use SilverStripe\Core\Path;
use Stringable;
/** /**
* This object represents a single resource file attached to a module, and can be used * This object represents a single resource file attached to a module, and can be used
* as a reference to this to be later turned into either a URL or file path. * as a reference to this to be later turned into either a URL or file path.
*/ */
class ModuleResource class ModuleResource implements Stringable
{ {
/** /**
* @var Module * @var Module
@ -115,7 +116,7 @@ class ModuleResource
/** /**
* Get relative path * Get relative path
*/ */
public function __toString() public function __toString(): string
{ {
return $this->getRelativePath(); return $this->getRelativePath();
} }

View File

@ -391,7 +391,7 @@ class Deprecation
} }
// Getting a backtrace is slow, so we only do it if we need it // Getting a backtrace is slow, so we only do it if we need it
$backtrace = []; $backtrace = null;
// Get the calling scope // Get the calling scope
if ($scope == Deprecation::SCOPE_METHOD) { if ($scope == Deprecation::SCOPE_METHOD) {

View File

@ -6,7 +6,6 @@ use SilverStripe\Core\Convert;
use InvalidArgumentException; use InvalidArgumentException;
use LogicException; use LogicException;
use SilverStripe\Model\ModelData; use SilverStripe\Model\ModelData;
use SilverStripe\Dev\Deprecation;
/** /**
* @see GridField * @see GridField

View File

@ -5,6 +5,7 @@ namespace SilverStripe\Forms\GridField;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\HiddenField;
use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataList;
use Stringable;
/** /**
* This class is a snapshot of the current status of a {@link GridField}. * This class is a snapshot of the current status of a {@link GridField}.
@ -14,7 +15,7 @@ use SilverStripe\ORM\DataList;
* *
* @see GridField * @see GridField
*/ */
class GridState extends HiddenField class GridState extends HiddenField implements Stringable
{ {
/** /**
@ -129,7 +130,7 @@ class GridState extends HiddenField
return Convert::raw2att($this->Value()); return Convert::raw2att($this->Value());
} }
public function __toString() public function __toString(): string
{ {
return $this->Value(); return $this->Value();
} }

View File

@ -2,13 +2,15 @@
namespace SilverStripe\Forms\GridField; namespace SilverStripe\Forms\GridField;
use Stringable;
/** /**
* Simple set of data, similar to stdClass, but without the notice-level * Simple set of data, similar to stdClass, but without the notice-level
* errors. * errors.
* *
* @see GridState * @see GridState
*/ */
class GridState_Data class GridState_Data implements Stringable
{ {
/** /**
@ -94,7 +96,7 @@ class GridState_Data
unset($this->data[$name]); unset($this->data[$name]);
} }
public function __toString() public function __toString(): string
{ {
if (!$this->data) { if (!$this->data) {
return ""; return "";

View File

@ -18,6 +18,7 @@ use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\Model\ArrayData; use SilverStripe\Model\ArrayData;
use SilverStripe\View\CastingService; use SilverStripe\View\CastingService;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use Stringable;
use UnexpectedValueException; use UnexpectedValueException;
/** /**
@ -27,7 +28,7 @@ use UnexpectedValueException;
* is provided and automatically escaped by ModelData. Any class that needs to be available to a view (controllers, * is provided and automatically escaped by ModelData. Any class that needs to be available to a view (controllers,
* {@link DataObject}s, page controls) should inherit from this class. * {@link DataObject}s, page controls) should inherit from this class.
*/ */
class ModelData class ModelData implements Stringable
{ {
use Extensible { use Extensible {
defineMethods as extensibleDefineMethods; defineMethods as extensibleDefineMethods;
@ -305,12 +306,9 @@ class ModelData
return true; return true;
} }
/**
* Return the class name (though subclasses may return something else)
*/
public function __toString(): string public function __toString(): string
{ {
return static::class; return $this->forTemplate();
} }
/** /**
@ -550,9 +548,8 @@ class ModelData
*/ */
private function objCacheName(string $fieldName, array $arguments = []): string private function objCacheName(string $fieldName, array $arguments = []): string
{ {
$name = empty($arguments) return empty($arguments)
? $fieldName ? $fieldName
: $fieldName . ":" . var_export($arguments, true); : $fieldName . ":" . var_export($arguments, true);
return md5($name);
} }
} }

View File

@ -521,11 +521,6 @@ abstract class DBField extends ModelData implements DBIndexable
DBG; DBG;
} }
public function __toString(): string
{
return (string)$this->forTemplate();
}
public function getArrayValue() public function getArrayValue()
{ {
return $this->arrayValue; return $this->arrayValue;

View File

@ -6,12 +6,13 @@ use SilverStripe\Core\Convert;
use SilverStripe\ORM\Connect\Query; use SilverStripe\ORM\Connect\Query;
use SilverStripe\ORM\DB; use SilverStripe\ORM\DB;
use Exception; use Exception;
use Stringable;
/** /**
* Abstract base class for an object representing an SQL query. * Abstract base class for an object representing an SQL query.
* The various parts of the SQL query can be manipulated individually. * The various parts of the SQL query can be manipulated individually.
*/ */
abstract class SQLExpression abstract class SQLExpression implements Stringable
{ {
/** /**
@ -45,7 +46,7 @@ abstract class SQLExpression
/** /**
* Return the generated SQL string for this query * Return the generated SQL string for this query
*/ */
public function __toString() public function __toString(): string
{ {
try { try {
$sql = $this->sql($parameters); $sql = $this->sql($parameters);

View File

@ -21,33 +21,33 @@ class CastingService
/** /**
* Cast a value to the relevant object (usually a DBField instance) for use in the view layer. * Cast a value to the relevant object (usually a DBField instance) for use in the view layer.
* *
* @param ModelData|array|null $source Where the data originates from. This is used both to check for casting helpers * @param null|array|ModelData $source Where the data originates from. This is used both to check for casting helpers
* and to help set the value in cast DBField instances. * and to help set the value in cast DBField instances.
* @param bool $strict If true, an object will be returned even if $data is null. * @param bool $strict If true, an object will be returned even if $data is null.
*/ */
public function cast(mixed $data, ModelData|array|null $source = null, string $fieldName = '', bool $strict = false): ?object public function cast(mixed $data, null|array|ModelData $source = null, string $fieldName = '', bool $strict = false): ?object
{ {
// Assume anything that's an object is intentionally using whatever class it's using
// and don't cast it.
if (is_object($data)) {
return $data;
}
// null is null - we shouldn't cast it to an object, because that makes it harder // null is null - we shouldn't cast it to an object, because that makes it harder
// for downstream checks to know there's "no value". // for downstream checks to know there's "no value".
if (!$strict && $data === null) { if (!$strict && $data === null) {
return null; return null;
} }
$serviceKey = null; // Assume anything that's an object is intentionally using whatever class it's using
// and don't cast it.
if (is_object($data)) {
return $data;
}
$service = null;
if ($source instanceof ModelData) { if ($source instanceof ModelData) {
$serviceKey = $source->castingHelper($fieldName); $service = $source->castingHelper($fieldName);
} }
// Cast to object if there's an explicit casting for this field // Cast to object if there's an explicit casting for this field
// Explicit casts take precedence over array casting // Explicit casts take precedence over array casting
if ($serviceKey) { if ($service) {
$castObject = Injector::inst()->create($serviceKey, $fieldName); $castObject = Injector::inst()->create($service, $fieldName);
if (!ClassInfo::hasMethod($castObject, 'setValue')) { if (!ClassInfo::hasMethod($castObject, 'setValue')) {
throw new LogicException('Explicit casting service must have a setValue method.'); throw new LogicException('Explicit casting service must have a setValue method.');
} }
@ -61,8 +61,8 @@ class CastingService
} }
// Fall back to default casting // Fall back to default casting
$serviceKey = $this->getDefaultServiceKey($data, $source, $fieldName); $service = $this->defaultService($data, $source, $fieldName);
$castObject = Injector::inst()->create($serviceKey, $fieldName); $castObject = Injector::inst()->create($service, $fieldName);
if (!ClassInfo::hasMethod($castObject, 'setValue')) { if (!ClassInfo::hasMethod($castObject, 'setValue')) {
throw new LogicException('Default service must have a setValue method.'); throw new LogicException('Default service must have a setValue method.');
} }
@ -73,7 +73,7 @@ class CastingService
/** /**
* Get the default service to use if no explicit service is declared for this field on the source model. * Get the default service to use if no explicit service is declared for this field on the source model.
*/ */
private function getDefaultServiceKey(mixed $data, mixed $source = null, string $fieldName = ''): ?string private function defaultService(mixed $data, mixed $source = null, string $fieldName = ''): ?string
{ {
$default = null; $default = null;
if ($source instanceof ModelData) { if ($source instanceof ModelData) {
@ -81,7 +81,7 @@ class CastingService
if ($default === null) { if ($default === null) {
$failover = $source->getFailover(); $failover = $source->getFailover();
if ($failover) { if ($failover) {
$default = $this->getDefaultServiceKey($data, $failover, $fieldName); $default = $this->defaultService($data, $failover, $fieldName);
} }
} }
} }

View File

@ -1189,7 +1189,7 @@ class SSTemplateParser extends Parser implements TemplateParser
$matchrule = "QuotedString"; $result = $this->construct($matchrule, $matchrule, null); $matchrule = "QuotedString"; $result = $this->construct($matchrule, $matchrule, null);
$_154 = NULL; $_154 = NULL;
do { do {
$stack[] = $result; $result = $this->construct( $matchrule, "q" ); $stack[] = $result; $result = $this->construct( $matchrule, "q" );
if (( $subres = $this->rx( '/[\'"]/' ) ) !== FALSE) { if (( $subres = $this->rx( '/[\'"]/' ) ) !== FALSE) {
$result["text"] .= $subres; $result["text"] .= $subres;
$subres = $result; $result = array_pop($stack); $subres = $result; $result = array_pop($stack);
@ -1199,7 +1199,7 @@ class SSTemplateParser extends Parser implements TemplateParser
$result = array_pop($stack); $result = array_pop($stack);
$_154 = FALSE; break; $_154 = FALSE; break;
} }
$stack[] = $result; $result = $this->construct( $matchrule, "String" ); $stack[] = $result; $result = $this->construct( $matchrule, "String" );
if (( $subres = $this->rx( '/ (\\\\\\\\ | \\\\. | [^'.$this->expression($result, $stack, 'q').'\\\\])* /' ) ) !== FALSE) { if (( $subres = $this->rx( '/ (\\\\\\\\ | \\\\. | [^'.$this->expression($result, $stack, 'q').'\\\\])* /' ) ) !== FALSE) {
$result["text"] .= $subres; $result["text"] .= $subres;
$subres = $result; $result = array_pop($stack); $subres = $result; $result = array_pop($stack);
@ -1842,7 +1842,7 @@ class SSTemplateParser extends Parser implements TemplateParser
$pos_255 = $this->pos; $pos_255 = $this->pos;
$_254 = NULL; $_254 = NULL;
do { do {
$stack[] = $result; $result = $this->construct( $matchrule, "Not" ); $stack[] = $result; $result = $this->construct( $matchrule, "Not" );
if (( $subres = $this->literal( 'not' ) ) !== FALSE) { if (( $subres = $this->literal( 'not' ) ) !== FALSE) {
$result["text"] .= $subres; $result["text"] .= $subres;
$subres = $result; $result = array_pop($stack); $subres = $result; $result = array_pop($stack);
@ -2235,7 +2235,7 @@ class SSTemplateParser extends Parser implements TemplateParser
else { $_330 = FALSE; break; } else { $_330 = FALSE; break; }
if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; }
else { $_330 = FALSE; break; } else { $_330 = FALSE; break; }
$stack[] = $result; $result = $this->construct( $matchrule, "Call" ); $stack[] = $result; $result = $this->construct( $matchrule, "Call" );
$_326 = NULL; $_326 = NULL;
do { do {
$matcher = 'match_'.'Word'; $key = $matcher; $pos = $this->pos; $matcher = 'match_'.'Word'; $key = $matcher; $pos = $this->pos;
@ -2740,7 +2740,7 @@ class SSTemplateParser extends Parser implements TemplateParser
$_423 = NULL; $_423 = NULL;
do { do {
if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; }
$stack[] = $result; $result = $this->construct( $matchrule, "Conditional" ); $stack[] = $result; $result = $this->construct( $matchrule, "Conditional" );
$_419 = NULL; $_419 = NULL;
do { do {
$_417 = NULL; $_417 = NULL;
@ -3166,7 +3166,7 @@ class SSTemplateParser extends Parser implements TemplateParser
if (( $subres = $this->literal( '<%' ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->literal( '<%' ) ) !== FALSE) { $result["text"] .= $subres; }
else { $_555 = FALSE; break; } else { $_555 = FALSE; break; }
if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; }
$stack[] = $result; $result = $this->construct( $matchrule, "CacheTag" ); $stack[] = $result; $result = $this->construct( $matchrule, "CacheTag" );
$_508 = NULL; $_508 = NULL;
do { do {
$_506 = NULL; $_506 = NULL;
@ -3225,7 +3225,7 @@ class SSTemplateParser extends Parser implements TemplateParser
$_524 = NULL; $_524 = NULL;
do { do {
if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; }
$stack[] = $result; $result = $this->construct( $matchrule, "Conditional" ); $stack[] = $result; $result = $this->construct( $matchrule, "Conditional" );
$_520 = NULL; $_520 = NULL;
do { do {
$_518 = NULL; $_518 = NULL;
@ -4165,7 +4165,7 @@ class SSTemplateParser extends Parser implements TemplateParser
unset( $pos_685 ); unset( $pos_685 );
} }
if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; }
$stack[] = $result; $result = $this->construct( $matchrule, "Zap" ); $stack[] = $result; $result = $this->construct( $matchrule, "Zap" );
if (( $subres = $this->literal( '%>' ) ) !== FALSE) { if (( $subres = $this->literal( '%>' ) ) !== FALSE) {
$result["text"] .= $subres; $result["text"] .= $subres;
$subres = $result; $result = array_pop($stack); $subres = $result; $result = array_pop($stack);
@ -4556,7 +4556,7 @@ class SSTemplateParser extends Parser implements TemplateParser
if (( $subres = $this->literal( '<%' ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->literal( '<%' ) ) !== FALSE) { $result["text"] .= $subres; }
else { $_743 = FALSE; break; } else { $_743 = FALSE; break; }
if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->whitespace( ) ) !== FALSE) { $result["text"] .= $subres; }
$stack[] = $result; $result = $this->construct( $matchrule, "Tag" ); $stack[] = $result; $result = $this->construct( $matchrule, "Tag" );
$_737 = NULL; $_737 = NULL;
do { do {
if (( $subres = $this->literal( 'end_' ) ) !== FALSE) { $result["text"] .= $subres; } if (( $subres = $this->literal( 'end_' ) ) !== FALSE) { $result["text"] .= $subres; }

View File

@ -372,8 +372,9 @@ PHP;
if ($isXhtml) { if ($isXhtml) {
return "<base href=\"$base\" />"; return "<base href=\"$base\" />";
} else {
return "<base href=\"$base\">";
} }
return "<base href=\"$base\">";
} }
/** /**

View File

@ -9,7 +9,6 @@ use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Manifest\ModuleResourceLoader; use SilverStripe\Core\Manifest\ModuleResourceLoader;
use SilverStripe\Core\Path; use SilverStripe\Core\Path;
use SilverStripe\Dev\Deprecation;
/** /**
* Handles finding templates from a stack of template manifest objects. * Handles finding templates from a stack of template manifest objects.

View File

@ -3,6 +3,7 @@
namespace SilverStripe\i18n\Messages\Symfony; namespace SilverStripe\i18n\Messages\Symfony;
use SilverStripe\Core\Flushable; use SilverStripe\Core\Flushable;
use Stringable;
use Symfony\Component\Config\Resource\SelfCheckingResourceInterface; use Symfony\Component\Config\Resource\SelfCheckingResourceInterface;
/** /**
@ -12,9 +13,9 @@ use Symfony\Component\Config\Resource\SelfCheckingResourceInterface;
* @link https://media.giphy.com/media/fRRD3T37DeY6Y/giphy.gif for use case * @link https://media.giphy.com/media/fRRD3T37DeY6Y/giphy.gif for use case
* @see DirectoryResource * @see DirectoryResource
*/ */
class FlushInvalidatedResource implements SelfCheckingResourceInterface, Flushable class FlushInvalidatedResource implements SelfCheckingResourceInterface, Flushable, Stringable
{ {
public function __toString() public function __toString(): string
{ {
return md5(__CLASS__); return md5(__CLASS__);
} }

View File

@ -111,8 +111,8 @@ class DeprecationTest extends SapphireTest
'Will be removed without equivalent functionality to replace it.', 'Will be removed without equivalent functionality to replace it.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testNoticeNoReplacement.' 'Called from SilverStripe\Dev\Tests\DeprecationTest->testNoticeNoReplacement.'
]); ]);
$this->expectException(DeprecationTestException::class); $this->expectDeprecation();
$this->expectExceptionMessage($message); $this->expectDeprecationMessage($message);
$this->enableDeprecationNotices(true); $this->enableDeprecationNotices(true);
$ret = $this->myDeprecatedMethodNoReplacement(); $ret = $this->myDeprecatedMethodNoReplacement();
$this->assertSame('abc', $ret); $this->assertSame('abc', $ret);