API: Move DBField subclasses into SilverStripe\Model\FieldType namespace

API: Deprecate SS_Datetime.

The DBField subclasses are have all been renamed to start with “DB” and
be in the SilverStripe\Model\FieldType namespace. To keep DataObject
definitions concise, the original short variations of their names are
preserved as service definitions. Most of the field generation code
doesn’t need to change, but where field classes are referenced directly,
changes will be needed.

SS_Datetime, which is commonly referenced outside the model system
itself, has been preserved as a subclass of DBDatetime. This has been
marked as deprecated and can be removed in SilverStripe 5.

A few places that referred to $db and $casting values weren’t using
the Injector to instantiate the relevant classes. This meant that the
remapping we have created as part of moving classes into a namespace
didn’t work.
This commit is contained in:
Sam Minnee 2015-08-30 17:02:55 +12:00
parent 262f487053
commit aeccb8b8e0
84 changed files with 856 additions and 559 deletions

View File

@ -1,5 +1,53 @@
Injector:
Int:
class: SilverStripe\Model\FieldType\DBInt
Boolean:
class: SilverStripe\Model\FieldType\DBBoolean
Currency:
class: SilverStripe\Model\FieldType\DBCurrency
DBClassName:
class: SilverStripe\Model\FieldType\DBClassName
Date:
class: SilverStripe\Model\FieldType\DBDate
Datetime:
class: SilverStripe\Model\FieldType\DBDatetime
SS_Datetime:
class: SilverStripe\Model\FieldType\DBDatetime
Decimal:
class: SilverStripe\Model\FieldType\DBDecimal
Double:
class: SilverStripe\Model\FieldType\DBDouble
Enum:
class: SilverStripe\Model\FieldType\DBEnum
DBFile:
class: SilverStripe\Filesystem\Storage\DBFile
Float:
class: SilverStripe\Model\FieldType\DBFloat
ForeignKey:
class: SilverStripe\Model\FieldType\DBForeignKey
HTMLText:
class: SilverStripe\Model\FieldType\DBHTMLText
HTMLVarchar:
class: SilverStripe\Model\FieldType\DBHTMLVarchar
Int:
class: SilverStripe\Model\FieldType\DBInt
Locale:
class: SilverStripe\Model\FieldType\DBLocale
DBLocale:
class: SilverStripe\Model\FieldType\DBLocale
Money:
class: SilverStripe\Model\FieldType\DBMoney
MultiEnum:
class: SilverStripe\Model\FieldType\DBMultiEnum
Percentage:
class: SilverStripe\Model\FieldType\DBPercentage
PolymorphicForeignKey:
class: SilverStripe\Model\FieldType\DBPolymorphicForeignKey
PrimaryKey:
class: SilverStripe\Model\FieldType\DBPrimaryKey
Text:
class: SilverStripe\Model\FieldType\DBText
Time:
class: SilverStripe\Model\FieldType\DBTime
Varchar:
class: SilverStripe\Model\FieldType\DBVarchar
Year:
class: SilverStripe\Model\FieldType\DBYear

View File

@ -6,6 +6,7 @@
*/
use SilverStripe\Forms\Schema\FormSchema;
use SilverStripe\Model\FieldType\DBField;
/**
* LeftAndMain is the parent class of all the two-pane views in the CMS.
@ -1824,7 +1825,7 @@ class LeftAndMain extends Controller implements PermissionProvider {
* @return String
*/
public function Locale() {
return DBField::create_field('DBLocale', i18n::get_locale());
return DBField::create_field('Locale', i18n::get_locale());
}
public function providePermissions() {

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* RSSFeed class
*
@ -320,9 +323,7 @@ class RSSFeed_Entry extends ViewableData {
$obj->setValue($value);
return $obj;
} else {
$obj = new $defaultClass($fieldName);
$obj->setValue($this->failover->XML_val($fieldName));
return $obj;
return DBField::create_field($defaultClass, $this->failover->XML_val($fieldName), $fieldName);
}
}
}

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBDatetime;
/**
* A default backend for the setting and getting of cookies
*
@ -76,7 +78,7 @@ class CookieJar implements Cookie_Backend {
//expiry === 0 is a special case where we set a cookie for the current user session
if ($expiry !== 0) {
//don't do the maths if we are clearing
$expiry = $clear ? -1 : SS_Datetime::now()->Format('U') + (86400 * $expiry);
$expiry = $clear ? -1 : DBDatetime::now()->Format('U') + (86400 * $expiry);
}
//set the path up
$path = $path ? $path : Director::baseURL();

View File

@ -1,4 +1,8 @@
<?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBDatetime;
/**
* Test case class for the Sapphire framework.
* Sapphire unit testing is based on PHPUnit, but provides a number of hooks into our data model that make it easier
@ -512,7 +516,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
$this->originalIsRunningTest = null;
// Reset mocked datetime
SS_Datetime::clear_mock_now();
DBDatetime::clear_mock_now();
// Stop the redirection that might have been requested in the test.
// Note: Ideally a clean Controller should be created for each test.

View File

@ -133,7 +133,7 @@ You can also create your own functions by decorating the `Image` class.
Image:
extensions:
- MyImage
DBFile:
SilverStripe\Filesystem\Storage\DBFile:
extensions:
- MyImage
@ -166,7 +166,7 @@ mysite/config/config.yml file:
File:
force_resample: true
# DBFile can be configured independently
DBFile:
SilverStripe\Filesystem\Storage\DBFile:
force_resample: true
If you are intending to resample images with SilverStripe it is good practice

View File

@ -445,7 +445,7 @@ After:
// in _config.php
File::add_extension('MyImageExtension');
DBFile::add_extension('MyImageExtension');
SilverStripe\Filesystem\Storage\DBFile::add_extension('MyImageExtension');
There are a few differences in this new API:
@ -461,14 +461,14 @@ There are a few differences in this new API:
### Upgrading code that uses composite db fields.
`CompositeDBField` is now an abstract class, not an interface. In many cases, custom code that handled
saving of content into composite fields can be removed, as it is now handled by the base class.
The `CompositeDBField` interface has been replaced with an abstract class, `DBComposite`. In many cases, custom code
that handled saving of content into composite fields can be removed, as it is now handled by the base class.
The below describes the minimum amount of effort required to implement a composite DB field.
:::php
<?
class MyAddressField extends CompositeDBField {
class MyAddressField extends DBComposite {
private static $composite_db = array(
'Street' => 'Varchar(200)',
@ -712,4 +712,50 @@ Images inserted into `HTMLText` fields (through a WYSIWYG editor) need to be tra
Instead of `<img>` tags, the field will insert `[image]` shortcodes which point to the database identifier
of the `Image` record rather than its path on the filesystem. The shortcode will be automatically replaced
when the field is rendered. Newly inserted images will automatically receive the shortcode and ownership tracking,
and existing `<img>` will continue to work.
and existing `<img>` will continue to work.
### Upgrading references to DBField and subclasses
A major change in 4.0 is the introduction of namespaced DBField subclasses. Now as a standard, all DBField subclasses have a `DB` prefix, are namespaced, and have an associative alias which omits the DB prefix.
This means that for the most part, code that worked in 3.0 won't need to be changed, although if you have any hard class literals which reference the old classes, they will need to be updated to point to the new namespaced classes.
An exception to this is any classes which once had the `SS_` prefix, which will now be instead prefixed with `DB`, and have an un-aliased prefix. For example `SS_Datetime` is now `DBDateTime`, and has the alias `DateTime` which may be used in config.
For example:
class MyObject extends DataObject {
private static $db = array(
'Number' => 'Int',
'Time' => 'SS_Datetime'
);
/**
* @param Int $val
* @return Varchar
*/
public function TextNumber() {
return new Varchar('TextNumber', 'Number is ' . $this->Number);
}
}
Will become:
use SilverStripe\Model\FieldType\DBVarchar;
class MyObject extends DataObject {
private static $db = array(
'Number' => 'Int',
'Time' => 'Datetime'
);
/**
* @param Int $val
* @return Varchar
*/
public function TextNumber() {
return new DBVarchar('TextNumber', 'Number is ' . $this->Number);
}
}
Note that string references to SS_Datetime passed to injector, or used in config values, will still work, and will refer to the updated class names.

View File

@ -7,6 +7,7 @@ use Injector;
use Member;
use Versioned;
use SilverStripe\Filesystem\Storage\AssetStore;
use SilverStripe\Filesystem\Storage\DBFile;
/**
* This class provides the necessary business logic to ensure that any assets attached
@ -210,10 +211,9 @@ class AssetControlExtension extends \DataExtension
// Search for dbfile instances
$files = array();
foreach ($record->db() as $field => $db) {
// Extract assets from this database field
list($dbClass) = explode('(', $db);
if (!is_a($dbClass, 'DBFile', true)) {
continue;
$fieldObj = $record->$field;
if(!is_object($fieldObj) || !($record->$field instanceof DBFile)) {
continue;
}
// Omit variant and merge with set

View File

@ -4,8 +4,8 @@ namespace SilverStripe\Filesystem;
use Config;
use Convert;
use DBField;
use DBFile;
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Filesystem\Storage\DBFile;
use HTMLText;
use Image_Backend;
use Injector;

View File

@ -1,11 +1,20 @@
<?php
namespace SilverStripe\Filesystem\Storage;
use SilverStripe\Filesystem\ImageManipulation;
use SilverStripe\Filesystem\Storage\AssetContainer;
use SilverStripe\Filesystem\Storage\AssetStore;
use SilverStripe\Model\FieldType\DBComposite;
// Un-comment once https://github.com/silverstripe/silverstripe-framework/pull/4551/ is merged
// namespace SilverStripe\Filesystem\Storage;
use Injector;
use AssetField;
use File;
use Director;
use Permission;
use ShortcodeHandler;
use ValidationResult;
use ValidationException;
/**
* Represents a file reference stored in a database
@ -17,7 +26,7 @@ use SilverStripe\Filesystem\Storage\AssetStore;
* @package framework
* @subpackage filesystem
*/
class DBFile extends CompositeDBField implements AssetContainer {
class DBFile extends DBComposite implements AssetContainer {
use ImageManipulation;

View File

@ -2,6 +2,7 @@
use SilverStripe\Filesystem\Storage\AssetContainer;
use SilverStripe\Filesystem\Storage\AssetStore;
use SilverStripe\Filesystem\Storage\DBFile;
/**
* Field for uploading into a DBFile instance.

View File

@ -17,7 +17,7 @@ class CurrencyField extends TextField {
*/
public function setValue($val) {
if(!$val) $val = 0.00;
$this->value = Config::inst()->get('Currency','currency_symbol') . number_format((double)preg_replace('/[^0-9.\-]/', '', $val), 2);
$this->value = Config::inst()->get('SilverStripe\Model\FieldType\DBCurrency','currency_symbol') . number_format((double)preg_replace('/[^0-9.\-]/', '', $val), 2);
return $this;
}
/**
@ -44,7 +44,7 @@ class CurrencyField extends TextField {
}
public function validate($validator) {
$currencySymbol = preg_quote(Config::inst()->get('Currency','currency_symbol'));
$currencySymbol = preg_quote(Config::inst()->get('SilverStripe\Model\FieldType\DBCurrency', 'currency_symbol'));
$regex = '/^\s*(\-?'.$currencySymbol.'?|'.$currencySymbol.'\-?)?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?\s*$/';
if(!empty ($this->value)
&& !preg_match($regex, $this->value)) {

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBDate;
require_once 'Zend/Date.php';
/**
@ -481,7 +484,7 @@ class DateField_Disabled extends DateField {
$val = Convert::raw2xml($this->valueObj->toString($this->getConfig('dateformat'))
. ' ('._t('DateField.TODAY','today').')');
} else {
$df = new Date($this->name);
$df = new DBDate($this->name);
$df->setValue($this->dataValue());
$val = Convert::raw2xml($this->valueObj->toString($this->getConfig('dateformat'))
. ', ' . $df->Ago());

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* A composite field for date and time entry,
* based on {@link DateField} and {@link TimeField}.

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* Render a button that will submit the form its contained in through ajax.
* If you want to add custom behaviour, please set {@link includeDefaultJS()} to FALSE

View File

@ -1,4 +1,8 @@
<?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBMoney;
/**
* A form field that can save into a {@link Money} database field.
* See {@link CurrencyField} for a similiar implementation
@ -83,7 +87,7 @@ class MoneyField extends FormField {
if(is_array($val)) {
$this->fieldCurrency->setValue($val['Currency']);
$this->fieldAmount->setValue($val['Amount']);
} elseif($val instanceof Money) {
} elseif($val instanceof DBMoney) {
$this->fieldCurrency->setValue($val->getCurrency());
$this->fieldAmount->setValue($val->getAmount());
}

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* NullableField is a field that wraps other fields when you want to allow the user to specify
* whether the value of the field is null or not.

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* Displays a {@link SS_List} in a grid format.
*

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBDatetime;
/**
* Adds an "Print" button to the bottom or top of a GridField.
*
@ -214,7 +216,7 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
"Title" => $this->getTitle($gridField),
"Header" => $header,
"ItemRows" => $itemRows,
"Datetime" => SS_Datetime::now(),
"Datetime" => DBDatetime::now(),
"Member" => Member::currentUser(),
));

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* Utility class to render views of the differences between two data objects (or two versions of the
* same data object).

View File

@ -1,4 +1,12 @@
<?php
use SilverStripe\Model\FieldType\DBPolymorphicForeignKey;
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBDatetime;
use SilverStripe\Model\FieldType\DBPrimaryKey;
use SilverStripe\Model\FieldType\DBComposite;
use SilverStripe\Model\FieldType\DBClassName;
/**
* A single database record & abstract class for the data-access-model.
*
@ -278,7 +286,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
$db = Config::inst()->get($class, 'db', Config::UNINHERITED) ?: array();
foreach($db as $fieldName => $fieldSpec) {
$fieldClass = strtok($fieldSpec, '(');
if(is_subclass_of($fieldClass, 'CompositeDBField')) {
if(singleton($fieldClass) instanceof DBComposite) {
$compositeFields[$fieldName] = $fieldSpec;
} else {
$dbFields[$fieldName] = $fieldSpec;
@ -312,7 +320,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
/**
* Get all database columns explicitly defined on a class in {@link DataObject::$db}
* and {@link DataObject::$has_one}. Resolves instances of {@link CompositeDBField}
* and {@link DataObject::$has_one}. Resolves instances of {@link DBComposite}
* into the actual database fields, rather than the name of the field which
* might not equate a database column.
*
@ -321,7 +329,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
*
* Can be called directly on an object. E.g. Member::custom_database_fields()
*
* @uses CompositeDBField->compositeDatabaseFields()
* @uses DBComposite->compositeDatabaseFields()
*
* @param string $class Class name to query from
* @return array Map of fieldname to specification, similiar to {@link DataObject::$db}.
@ -1348,7 +1356,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* @throws ValidationException Exception that can be caught and handled by the calling function
*/
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$now = SS_Datetime::now()->Rfc2822();
$now = DBDatetime::now()->Rfc2822();
// Execute pre-write tasks
$this->preWrite();
@ -2421,7 +2429,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
// Prevents CompositeDBFields infinite looping on isChanged
// Prevents DBComposite infinite looping on isChanged
if(is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
continue;
}
@ -2504,7 +2512,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// Situation 1a: Composite fields should remain bound in case they are
// later referenced to update the parent dataobject
if($val instanceof CompositeDBField) {
if($val instanceof DBComposite) {
$val->bindTo($this);
$this->record[$fieldName] = $val;
}

View File

@ -1,11 +1,18 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use CheckboxField;
use DropdownField;
/**
* Represents a boolean field.
*
* @package framework
* @subpackage model
*/
class Boolean extends DBField {
class DBBoolean extends DBField {
public function __construct($name = null, $defaultVal = 0) {
$this->defaultVal = ($defaultVal) ? 1 : 0;

View File

@ -1,12 +1,19 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use DataObject;
use ClassInfo;
use Config;
/**
* Represents a classname selector, which respects obsolete clasess.
*
* @package framework
* @subpackage model
*/
class DBClassName extends Enum {
class DBClassName extends DBEnum {
/**
* Base classname of class to enumerate.

View File

@ -1,4 +1,11 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use Object;
use DataObject;
/**
* Apply this interface to any {@link DBField} that doesn't have a 1-1 mapping with a database field.
* This includes multi-value fields and transformed fields
@ -7,7 +14,7 @@
*
* Example with a combined street name and number:
* <code>
* class Street extends CompositeDBField {
* class Street extends DBComposite {
* private static $composite_db = return array(
* "Number" => "Int",
* "Name" => "Text"
@ -18,7 +25,7 @@
* @package framework
* @subpackage model
*/
abstract class CompositeDBField extends DBField {
abstract class DBComposite extends DBField {
/**
* Similiar to {@link DataObject::$db},
@ -145,7 +152,7 @@ abstract class CompositeDBField extends DBField {
foreach($this->compositeDatabaseFields() as $field => $spec) {
// Check value
if($value instanceof CompositeDBField) {
if($value instanceof DBComposite) {
// Check if saving from another composite field
$this->setField($field, $value->getField($field));

View File

@ -1,4 +1,9 @@
<?php
namespace SilverStripe\Model\FieldType;
use Deprecation;
/**
* Represents a decimal field containing a currency amount.
* The currency class only supports single currencies. For multi-currency support, use {@link Money}
@ -15,7 +20,7 @@
* @package framework
* @subpackage model
*/
class Currency extends Decimal {
class DBCurrency extends DBDecimal {
/**
* @config
@ -66,7 +71,7 @@ class Currency extends Decimal {
public static function setCurrencySymbol($value) {
Deprecation::notice('4.0', 'Use the "Currency.currency_symbol" config setting instead');
Currency::config()->currency_symbol = $value;
DBCurrency::config()->currency_symbol = $value;
}
}

View File

@ -1,4 +1,15 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use Member;
use Zend_Date;
use DateTime;
use DateField;
use Convert;
use Exception;
/**
* Represents a date field.
* The field currently supports New Zealand date format (DD/MM/YYYY),
@ -18,7 +29,7 @@
* @package framework
* @subpackage model
*/
class Date extends DBField {
class DBDate extends DBField {
public function setValue($value, $record = null, $markChanged = true) {
if($value === false || $value === null || (is_string($value) && !strlen($value))) {
@ -226,7 +237,7 @@ class Date extends DBField {
*/
public function Ago($includeSeconds = true, $significance = 2) {
if($this->value) {
$time = SS_Datetime::now()->Format('U');
$time = DBDatetime::now()->Format('U');
if(strtotime($this->value) == $time || $time > strtotime($this->value)) {
return _t(
'Date.TIMEDIFFAGO',
@ -253,7 +264,7 @@ class Date extends DBField {
public function TimeDiff($includeSeconds = true, $significance = 2) {
if(!$this->value) return false;
$time = SS_Datetime::now()->Format('U');
$time = DBDatetime::now()->Format('U');
$ago = abs($time - strtotime($this->value));
if($ago < 60 && !$includeSeconds) {
return _t('Date.LessThanMinuteAgo', 'less than a minute');
@ -282,7 +293,7 @@ class Date extends DBField {
public function TimeDiffIn($format) {
if(!$this->value) return false;
$time = SS_Datetime::now()->Format('U');
$time = DBDatetime::now()->Format('U');
$ago = abs($time - strtotime($this->value));
switch($format) {
@ -323,7 +334,7 @@ class Date extends DBField {
* @return boolean
*/
public function InPast() {
return strtotime($this->value) < SS_Datetime::now()->Format('U');
return strtotime($this->value) < DBDatetime::now()->Format('U');
}
/**
@ -331,7 +342,7 @@ class Date extends DBField {
* @return boolean
*/
public function InFuture() {
return strtotime($this->value) > SS_Datetime::now()->Format('U');
return strtotime($this->value) > DBDatetime::now()->Format('U');
}
/**
@ -339,7 +350,7 @@ class Date extends DBField {
* @return boolean
*/
public function IsToday() {
return (date('Y-m-d', strtotime($this->value)) == SS_Datetime::now()->Format('Y-m-d'));
return (date('Y-m-d', strtotime($this->value)) == DBDatetime::now()->Format('Y-m-d'));
}
/**

View File

@ -1,4 +1,15 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use Convert;
use Member;
use DatetimeField;
use Zend_Date;
use TemplateGlobalProvider;
use DateTime;
/**
* Represents a date-time field.
* The field currently supports New Zealand date format (DD/MM/YYYY),
@ -7,9 +18,9 @@
* PHP's built-in date() and strtotime() function according to your system locale.
*
* For all computations involving the current date and time,
* please use {@link SS_Datetime::now()} instead of PHP's built-in date() and time()
* please use {@link DBDatetime::now()} instead of PHP's built-in date() and time()
* methods. This ensures that all time-based computations are testable with mock dates
* through {@link SS_Datetime::set_mock_now()}.
* through {@link DBDatetime::set_mock_now()}.
*
* Example definition via {@link DataObject::$db}:
* <code>
@ -23,7 +34,7 @@
* @package framework
* @subpackage model
*/
class SS_Datetime extends Date implements TemplateGlobalProvider {
class DBDatetime extends DBDate implements TemplateGlobalProvider {
public function setValue($value, $record = null, $markChanged = true) {
if($value === false || $value === null || (is_string($value) && !strlen($value))) {
@ -185,7 +196,7 @@ class SS_Datetime extends Date implements TemplateGlobalProvider {
} elseif(is_string($datetime)) {
self::$mock_now = DBField::create_field('SS_Datetime', $datetime);
} else {
throw new Exception('SS_Datetime::set_mock_now(): Wrong format: ' . $datetime);
throw new Exception('DBDatetime::set_mock_now(): Wrong format: ' . $datetime);
}
}

View File

@ -1,11 +1,17 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use NumericField;
/**
* Represents a Decimal field.
*
* @package framework
* @subpackage model
*/
class Decimal extends DBField {
class DBDecimal extends DBField {
protected $wholeSize, $decimalSize, $defaultValue;

View File

@ -1,13 +1,16 @@
<?php
use SilverStripe\Model\FieldType\DBFloat;
namespace SilverStripe\Model\FieldType;
use DB;
use MySQLDatabase;
/**
*
* @package framework
* @subpackage model
*/
class Double extends DBFloat {
class DBDouble extends DBFloat {
public function requireField() {
// HACK: MSSQL does not support double so we're using float instead

View File

@ -1,4 +1,12 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use ArrayLib;
use DropdownField;
use Config;
/**
* Class Enum represents an enumeration of a set of strings.
*
@ -7,7 +15,7 @@
* @package framework
* @subpackage model
*/
class Enum extends StringField {
class DBEnum extends DBString {
/**
* List of enum values

View File

@ -1,4 +1,12 @@
<?php
namespace SilverStripe\Model\FieldType;
use ViewableData;
use Convert;
use Object;
use TextField;
/**
* Single field in the database.
*

View File

@ -3,7 +3,6 @@
namespace SilverStripe\Model\FieldType;
use DB;
use DBField;
use NumericField;
/**

View File

@ -1,6 +1,12 @@
<?php
use SilverStripe\Model\FieldType\DBInt;
namespace SilverStripe\Model\FieldType;
use DataList;
use UploadField;
use DropdownField;
use NumericField;
use DataObject;
/**
* A special type Int field used for foreign keys in has_one relationships.
@ -15,7 +21,7 @@ use SilverStripe\Model\FieldType\DBInt;
* @package framework
* @subpackage model
*/
class ForeignKey extends DBInt {
class DBForeignKey extends DBInt {
/**
* @var DataObject

View File

@ -1,4 +1,15 @@
<?php
namespace SilverStripe\Model\FieldType;
use Injector;
use HTTP;
use ShortcodeParser;
use DOMDocument;
use HtmlEditorField;
use TextField;
use Exception;
/**
* Represents a large text field that contains HTML content.
* This behaves similarly to {@link Text}, but the template processor won't escape any HTML content within it.
@ -10,7 +21,7 @@
* @package framework
* @subpackage model
*/
class HTMLText extends Text {
class DBHTMLText extends DBText {
private static $escape_type = 'xml';
private static $casting = array(

View File

@ -1,4 +1,11 @@
<?php
namespace SilverStripe\Model\FieldType;
use ShortcodeParser;
use HtmlEditorField;
use TextField;
/**
* Represents a short text field that is intended to contain HTML content.
*
@ -6,7 +13,7 @@
* @package framework
* @subpackage model
*/
class HTMLVarchar extends Varchar {
class DBHTMLVarchar extends DBVarchar {
private static $escape_type = 'xml';

View File

@ -3,7 +3,6 @@
namespace SilverStripe\Model\FieldType;
use DB;
use DBField;
use NumericField;
use ArrayList;
use ArrayData;

View File

@ -1,4 +1,9 @@
<?php
namespace SilverStripe\Model\FieldType;
use i18n;
/**
* Locale database field, mainly used in {@link Translatable} extension.
*
@ -7,7 +12,7 @@
* @package framework
* @subpackage i18n
*/
class DBLocale extends Varchar {
class DBLocale extends DBVarchar {
public function __construct($name, $size = 16) {
parent::__construct($name, $size);

View File

@ -1,4 +1,13 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use i18n;
use Zend_Currency;
use MoneyField;
use DataObject;
/**
* Partially based on Zend_Currency.
*
@ -22,7 +31,7 @@ require_once 'Zend/Currency.php';
* @package framework
* @subpackage model
*/
class Money extends CompositeDBField {
class DBMoney extends DBComposite {
/**
* @var string $locale

View File

@ -1,5 +1,10 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use CheckboxSetField;
/**
* @package framework
* @subpackage model
@ -10,7 +15,7 @@
* @package framework
* @subpackage model
*/
class MultiEnum extends Enum {
class DBMultiEnum extends DBEnum {
public function __construct($name, $enum = NULL, $default = NULL) {
// MultiEnum needs to take care of its own defaults
parent::__construct($name, $enum, null);

View File

@ -1,4 +1,7 @@
<?php
namespace SilverStripe\Model\FieldType;
/**
* Represents a decimal field from 0-1 containing a percentage value.
*
@ -13,7 +16,7 @@
* @package framework
* @subpackage model
*/
class Percentage extends Decimal {
class DBPercentage extends DBDecimal {
/**
* Create a new Decimal field.

View File

@ -1,12 +1,18 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use DataObject;
use ClassInfo;
/**
* A special ForeignKey class that handles relations with arbitrary class types
*
* @package framework
* @subpackage model
*/
class PolymorphicForeignKey extends CompositeDBField {
class DBPolymorphicForeignKey extends DBComposite {
private static $composite_db = array(
'ID' => 'Int',

View File

@ -1,6 +1,11 @@
<?php
use SilverStripe\Model\FieldType\DBInt;
namespace SilverStripe\Model\FieldType;
use DataList;
use DropdownField;
use DB;
use DataObject;
/**
* A special type Int field used for primary keys.
@ -10,7 +15,7 @@ use SilverStripe\Model\FieldType\DBInt;
* @package framework
* @subpackage model
*/
class PrimaryKey extends DBInt {
class DBPrimaryKey extends DBInt {
/**
* @var DataObject
*/

View File

@ -1,11 +1,16 @@
<?php
namespace SilverStripe\Model\FieldType;
use Convert;
/**
* An abstract base class for the string field types (i.e. Varchar and Text)
*
* @package framework
* @subpackage model
*/
abstract class StringField extends DBField {
abstract class DBString extends DBField {
/**
* @var boolean

View File

@ -1,4 +1,15 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use HTTP;
use Convert;
use NullableField;
use TextareaField;
use TextField;
use Config;
/**
* Represents a variable-length string of up to 2 megabytes, designed to store raw text
*
@ -16,7 +27,7 @@
* @package framework
* @subpackage model
*/
class Text extends StringField {
class DBText extends DBString {
private static $casting = array(
"AbsoluteLinks" => "Text",

View File

@ -1,4 +1,13 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use Convert;
use Zend_Date;
use TimeField;
/**
* Represents a column in the database with the type 'Time'.
*
@ -14,7 +23,7 @@
* @package framework
* @subpackage model
*/
class Time extends DBField {
class DBTime extends DBField {
public function setValue($value, $record = null, $markChanged = true) {
if($value) {

View File

@ -1,4 +1,12 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use NullableField;
use TextField;
use Config;
/**
* Class Varchar represents a variable-length string of up to 255 characters, designed to store raw text
*
@ -9,7 +17,7 @@
* @package framework
* @subpackage model
*/
class Varchar extends StringField {
class DBVarchar extends DBString {
private static $casting = array(
"Initial" => "Text",

View File

@ -1,4 +1,10 @@
<?php
namespace SilverStripe\Model\FieldType;
use DB;
use DropdownField;
/**
* @package framework
* @subpackage model
@ -10,7 +16,7 @@
* @package framework
* @subpackage model
*/
class Year extends DBField {
class DBYear extends DBField {
public function requireField() {
$parts=Array('datatype'=>'year', 'precision'=>4, 'arrayValue'=>$this->arrayValue);

View File

@ -0,0 +1,49 @@
<?php
/**
* Backwards-compatibility class to preserve the functioning of references to SS_Datetime::now()
* @deprecated 4.0.0:5.0.0 Use SilverStripe\Model\FieldType\DBDatetime instead.
*/
class SS_Datetime extends SilverStripe\Model\FieldType\DBDatetime
{
public function __construct($name = null) {
self::deprecation_notice();
parent::__construct($name);
}
public static function now() {
self::deprecation_notice();
return parent::now();
}
/**
* Mock the system date temporarily, which is useful for time-based unit testing.
* Use {@link clear_mock_now()} to revert to the current system date.
* Caution: This sets a fixed date that doesn't increment with time.
*
* @param SS_Datetime|string $datetime Either in object format, or as a SS_Datetime compatible string.
*/
public static function set_mock_now($datetime) {
self::deprecation_notice();
return parent::set_mock_now($datetime);
}
/**
* Clear any mocked date, which causes
* {@link Now()} to return the current system date.
*/
public static function clear_mock_now() {
self::deprecation_notice();
return parent::clear_mock_now();
}
public static function get_template_global_variables() {
self::deprecation_notice();
return parent::get_template_global_variables();
}
protected static function deprecation_notice() {
Deprecation::notice('4.0', 'SS_Datetime is deprecated. Please use SilverStripe\Model\FieldType\DBDatetime instead.');
}
}

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBComposite;
/**
* Subclass of {@link DataList} representing a many_many relation.
*
@ -88,7 +90,7 @@ class ManyManyList extends RelationList {
foreach($this->extraFields as $field => $spec) {
$obj = Object::create_from_string($spec);
if($obj instanceof CompositeDBField) {
if($obj instanceof DBComposite) {
$this->_compositeExtraFields[$field] = array();
// append the composite field names to the select

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBDatetime;
/**
* The member class which represents the users of the system
*
@ -489,7 +492,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
$generator = new RandomGenerator();
$this->TempIDHash = $generator->randomToken('sha1');
$this->TempIDExpired = self::config()->temp_id_lifetime
? date('Y-m-d H:i:s', strtotime(SS_Datetime::now()->getValue()) + self::config()->temp_id_lifetime)
? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + self::config()->temp_id_lifetime)
: null;
$this->write();
}
@ -706,7 +709,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
// Exclude expired
if(static::config()->temp_id_lifetime) {
$members = $members->filter('TempIDExpired:GreaterThan', SS_Datetime::now()->getValue());
$members = $members->filter('TempIDExpired:GreaterThan', DBDatetime::now()->getValue());
}
return $members->first();

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* Shows a categorized list of available permissions (through {@link Permission::get_codes()}).
* Permissions which are assigned to a given {@link Group} record

View File

@ -1,14 +1,16 @@
<?php
use SilverStripe\Model\FieldType\DBVarchar;
class ArrayDataTest extends SapphireTest {
public function testViewabledataItemsInsideArraydataArePreserved() {
/* ViewableData objects will be preserved, but other objects will be converted */
$arrayData = new ArrayData(array(
"A" => new Varchar("A"),
"A" => new DBVarchar("A"),
"B" => new stdClass(),
));
$this->assertEquals("Varchar", get_class($arrayData->A));
$this->assertEquals('SilverStripe\Model\FieldType\DBVarchar', get_class($arrayData->A));
$this->assertEquals("ArrayData", get_class($arrayData->B));
}

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* @package framework
* @subpackage tests

View File

@ -287,7 +287,7 @@ class FixtureBlueprintTest_SiteTree extends DataObject implements TestOnly {
class FixtureBlueprintTest_Page extends FixtureBlueprintTest_SiteTree {
private static $db = array(
'PublishDate' => 'SS_DateTime'
'PublishDate' => 'Datetime'
);
}

View File

@ -10,6 +10,7 @@ use SilverStripe\Filesystem\Flysystem\PublicAssetAdapter;
use SilverStripe\Filesystem\Storage\AssetContainer;
use SilverStripe\Filesystem\Storage\AssetStore;
use SilverStripe\Filesystem\Storage\FlysystemGeneratedAssetHandler;
use SilverStripe\Filesystem\Storage\DBFile;
class AssetStoreTest extends SapphireTest {

View File

@ -60,7 +60,7 @@ class CurrencyFieldTest extends SapphireTest {
);
//tests with updated currency symbol setting
Config::inst()->update('Currency', 'currency_symbol', '€');
Config::inst()->update('SilverStripe\Model\FieldType\DBCurrency', 'currency_symbol', '€');
$f->setValue('123.45');
$this->assertTrue(
@ -164,7 +164,7 @@ class CurrencyFieldTest extends SapphireTest {
);
//update currency symbol via config
Config::inst()->update('Currency', 'currency_symbol', '€');
Config::inst()->update('SilverStripe\Model\FieldType\DBCurrency', 'currency_symbol', '€');
$f->setValue('123.45');
$this->assertEquals(
@ -235,7 +235,7 @@ class CurrencyFieldTest extends SapphireTest {
);
//tests with updated currency symbol setting
Config::inst()->update('Currency', 'currency_symbol', '€');
Config::inst()->update('SilverStripe\Model\FieldType\DBCurrency', 'currency_symbol', '€');
$f->setValue('€123.45');
$this->assertEquals(

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBEnum;
/**
* @package framework
* @subpackage tests
@ -8,7 +11,7 @@ class EnumFieldTest extends SapphireTest {
$values = array (
'Key' => 'Value'
);
$enumField = new Enum('testField', $values);
$enumField = new DBEnum('testField', $values);
$searchField = $enumField->scaffoldSearchField();
@ -18,7 +21,7 @@ class EnumFieldTest extends SapphireTest {
}
public function testEnumParsing() {
$enum = new Enum('testField', "
$enum = new DBEnum('testField', "
Item1,
Item2,
Item 3,

View File

@ -16,7 +16,7 @@ class LookupFieldTest extends SapphireTest {
$this->assertEquals(
'<span class="readonly" id="test"><i>(none)</i></span><input type="hidden" name="test" value="" />',
$f->Field()->getValue()
trim($f->Field()->getValue())
);
}
@ -26,7 +26,7 @@ class LookupFieldTest extends SapphireTest {
$f->setValue(1);
$this->assertEquals(
'<span class="readonly" id="test">one</span><input type="hidden" name="test" value="1" />',
$f->Field()->getValue()
trim($f->Field()->getValue())
);
}
@ -37,7 +37,7 @@ class LookupFieldTest extends SapphireTest {
$f->dontEscape = true; // simulates CMSMain->compareversions()
$this->assertEquals(
'<span class="readonly" id="test"><ins>w00t</ins></span><input type="hidden" name="test" value="" />',
$f->Field()->getValue()
trim($f->Field()->getValue())
);
}
@ -48,7 +48,7 @@ class LookupFieldTest extends SapphireTest {
$f->setValue(array('one','two'));
$this->assertEquals('<span class="readonly" id="test">one val, two val</span>'
. '<input type="hidden" name="test" value="one, two" />',
$f->Field()->getValue()
trim($f->Field()->getValue())
);
}
@ -59,7 +59,7 @@ class LookupFieldTest extends SapphireTest {
$f->setValue(array(1,2));
$this->assertEquals(
'<span class="readonly" id="test">one, two</span><input type="hidden" name="test" value="1, 2" />',
$f->Field()->getValue()
trim($f->Field()->getValue())
);
}
@ -79,7 +79,7 @@ class LookupFieldTest extends SapphireTest {
$member1->ID,
$member2->ID
),
$f->Field()->getValue()
trim($f->Field()->getValue())
);
}
@ -101,7 +101,7 @@ class LookupFieldTest extends SapphireTest {
$this->assertEquals(
'<span class="readonly" id="test">Carrots</span><input type="hidden" name="test" value="3" />',
$f->Field()->getValue()
trim($f->Field()->getValue())
);
$f->setValue(array(
@ -110,7 +110,7 @@ class LookupFieldTest extends SapphireTest {
$this->assertEquals(
'<span class="readonly" id="test">Carrots, Vegan</span><input type="hidden" name="test" value="3, 9" />',
$f->Field()->getValue()
trim($f->Field()->getValue())
);
}
}

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBMoney;
/**
* @package framework
* @subpackage tests
@ -13,7 +16,7 @@ class MoneyFieldTest extends SapphireTest {
public function testSaveInto() {
$o = new MoneyFieldTest_Object();
$m = new Money();
$m = new DBMoney();
$m->setAmount(123456.78);
$m->setCurrency('EUR');
$f = new MoneyField('MyMoney', 'MyMoney', $m);
@ -28,7 +31,7 @@ class MoneyFieldTest extends SapphireTest {
$f = new MoneyField('MyMoney', 'MyMoney');
$m = new Money();
$m = new DBMoney();
$m->setAmount(123456.78);
$m->setCurrency('EUR');
$f->setValue($m);

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBClassName;
class DBClassNameTest extends SapphireTest {
protected $extraDataObjects = array(

View File

@ -1,17 +1,21 @@
<?php
use SilverStripe\Model\FieldType\DBMoney;
/**
* @package framework
* @subpackage tests
*/
class CompositeDBFieldTest extends SapphireTest {
class DBCompositeTest extends SapphireTest {
protected $extraDataObjects = array(
'CompositeDBFieldTest_DataObject',
'DBCompositeTest_DataObject',
'SubclassedDBFieldObject',
);
public function testHasDatabaseFieldOnDataObject() {
$obj = singleton('CompositeDBFieldTest_DataObject');
$obj = singleton('DBCompositeTest_DataObject');
$this->assertTrue($obj->hasDatabaseField('MyMoneyAmount'));
$this->assertTrue($obj->hasDatabaseField('MyMoneyCurrency'));
@ -22,7 +26,7 @@ class CompositeDBFieldTest extends SapphireTest {
$this->assertTrue($obj->dbObject('MyMoney')->hasField('Currency'));
// Test getField accessor
$this->assertTrue($obj->MyMoney instanceof Money);
$this->assertTrue($obj->MyMoney instanceof DBMoney);
$this->assertTrue($obj->MyMoney->hasField('Amount'));
$obj->MyMoney->Amount = 100.00;
$this->assertEquals(100.00, $obj->MyMoney->Amount);
@ -38,14 +42,14 @@ class CompositeDBFieldTest extends SapphireTest {
* Test DataObject::composite_fields() and DataObject::is_composite_field()
*/
public function testCompositeFieldMetaDataFunctions() {
$this->assertEquals('Money', DataObject::is_composite_field('CompositeDBFieldTest_DataObject', 'MyMoney'));
$this->assertFalse(DataObject::is_composite_field('CompositeDBFieldTest_DataObject', 'Title'));
$this->assertEquals('Money', DataObject::is_composite_field('DBCompositeTest_DataObject', 'MyMoney'));
$this->assertFalse(DataObject::is_composite_field('DBCompositeTest_DataObject', 'Title'));
$this->assertEquals(
array(
'MyMoney' => 'Money',
'OverriddenMoney' => 'Money'
),
DataObject::composite_fields('CompositeDBFieldTest_DataObject')
DataObject::composite_fields('DBCompositeTest_DataObject')
);
@ -67,14 +71,14 @@ class CompositeDBFieldTest extends SapphireTest {
* Tests that changes to the fields affect the underlying dataobject, and vice versa
*/
public function testFieldBinding() {
$object = new CompositeDBFieldTest_DataObject();
$object = new DBCompositeTest_DataObject();
$object->MyMoney->Currency = 'NZD';
$object->MyMoney->Amount = 100.0;
$this->assertEquals('NZD', $object->MyMoneyCurrency);
$this->assertEquals(100.0, $object->MyMoneyAmount);
$object->write();
$object2 = CompositeDBFieldTest_DataObject::get()->byID($object->ID);
$object2 = DBCompositeTest_DataObject::get()->byID($object->ID);
$this->assertEquals('NZD', $object2->MyMoney->Currency);
$this->assertEquals(100.0, $object2->MyMoney->Amount);
@ -90,18 +94,18 @@ class CompositeDBFieldTest extends SapphireTest {
* Ensures that composite fields are assigned to the correct tables
*/
public function testInheritedTables() {
$object1 = new CompositeDBFieldTest_DataObject();
$object1 = new DBCompositeTest_DataObject();
$object2 = new SubclassedDBFieldObject();
$this->assertEquals('CompositeDBFieldTest_DataObject', $object1->dbObject('MyMoney')->getTable());
$this->assertEquals('CompositeDBFieldTest_DataObject', $object1->dbObject('OverriddenMoney')->getTable());
$this->assertEquals('CompositeDBFieldTest_DataObject', $object2->dbObject('MyMoney')->getTable());
$this->assertEquals('DBCompositeTest_DataObject', $object1->dbObject('MyMoney')->getTable());
$this->assertEquals('DBCompositeTest_DataObject', $object1->dbObject('OverriddenMoney')->getTable());
$this->assertEquals('DBCompositeTest_DataObject', $object2->dbObject('MyMoney')->getTable());
$this->assertEquals('SubclassedDBFieldObject', $object2->dbObject('OtherMoney')->getTable());
$this->assertEquals('SubclassedDBFieldObject', $object2->dbObject('OverriddenMoney')->getTable());
}
}
class CompositeDBFieldTest_DataObject extends DataObject implements TestOnly {
class DBCompositeTest_DataObject extends DataObject implements TestOnly {
private static $db = array(
'Title' => 'Text',
'MyMoney' => 'Money',
@ -109,7 +113,7 @@ class CompositeDBFieldTest_DataObject extends DataObject implements TestOnly {
);
}
class SubclassedDBFieldObject extends CompositeDBFieldTest_DataObject {
class SubclassedDBFieldObject extends DBCompositeTest_DataObject {
private static $db = array(
'OtherField' => 'Text',
'OtherMoney' => 'Money',

View File

@ -1,9 +1,12 @@
<?php
use SilverStripe\Model\FieldType\DBCurrency;
/**
* @package framework
* @subpackage tests
*/
class CurrencyTest extends SapphireTest {
class DBCurrencyTest extends SapphireTest {
public function testNiceFormatting() {
// Test a bunch of different data values and results in Nice() and Whole()
$tests = array(
@ -31,7 +34,7 @@ class CurrencyTest extends SapphireTest {
);
foreach($tests as $value => $niceValues) {
$c = new Currency('MyField');
$c = new DBCurrency('MyField');
$c->setValue($value);
$this->assertEquals($niceValues[0], $c->Nice());
$this->assertEquals($niceValues[1], $c->Whole());

View File

@ -1,9 +1,13 @@
<?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBDatetime;
/**
* @package framework
* @subpackage tests
*/
class DateTest extends SapphireTest {
class DBDateTest extends SapphireTest {
protected $originalTZ;
@ -161,7 +165,7 @@ class DateTest extends SapphireTest {
}
public function testAgoInPast() {
SS_Datetime::set_mock_now('2000-12-31 12:00:00');
DBDatetime::set_mock_now('2000-12-31 12:00:00');
$this->assertEquals(
'1 month ago',
@ -211,11 +215,11 @@ class DateTest extends SapphireTest {
'Approximate past match in singular'
);
SS_Datetime::clear_mock_now();
DBDatetime::clear_mock_now();
}
public function testAgoInFuture() {
SS_Datetime::set_mock_now('2000-12-31 00:00:00');
DBDatetime::set_mock_now('2000-12-31 00:00:00');
$this->assertEquals(
'in 10 years',
@ -235,7 +239,7 @@ class DateTest extends SapphireTest {
'Approximate past match on minutes'
);
SS_Datetime::clear_mock_now();
DBDatetime::clear_mock_now();
}
public function testFormatFromSettings() {

View File

@ -1,5 +1,9 @@
<?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBVarchar;
use SilverStripe\Model\FieldType\DBText;
/**
*
* Tests for DBField objects.
@ -95,7 +99,7 @@ class DBFieldTest extends SapphireTest {
$this->assertEquals(123, singleton('Varchar')->prepValueForDB(123));
/* AllowEmpty Varchar behaviour */
$varcharField = new Varchar("testfield", 50, array("nullifyEmpty"=>false));
$varcharField = new DBVarchar("testfield", 50, array("nullifyEmpty"=>false));
$this->assertSame(0, $varcharField->prepValueForDB(0));
$this->assertSame(null, $varcharField->prepValueForDB(null));
$this->assertSame(null, $varcharField->prepValueForDB(false));
@ -125,7 +129,7 @@ class DBFieldTest extends SapphireTest {
$this->assertEquals(123, singleton('Text')->prepValueForDB(123));
/* AllowEmpty Text behaviour */
$textField = new Text("testfield", array("nullifyEmpty"=>false));
$textField = new DBText("testfield", array("nullifyEmpty"=>false));
$this->assertSame(0, $textField->prepValueForDB(0));
$this->assertSame(null, $textField->prepValueForDB(null));
$this->assertSame(null, $textField->prepValueForDB(false));
@ -163,7 +167,7 @@ class DBFieldTest extends SapphireTest {
}
public function testExists() {
$varcharField = new Varchar("testfield");
$varcharField = new DBVarchar("testfield");
$this->assertTrue($varcharField->getNullifyEmpty());
$varcharField->setValue('abc');
$this->assertTrue($varcharField->exists());
@ -172,7 +176,7 @@ class DBFieldTest extends SapphireTest {
$varcharField->setValue(null);
$this->assertFalse($varcharField->exists());
$varcharField = new Varchar("testfield", 50, array('nullifyEmpty'=>false));
$varcharField = new DBVarchar("testfield", 50, array('nullifyEmpty'=>false));
$this->assertFalse($varcharField->getNullifyEmpty());
$varcharField->setValue('abc');
$this->assertTrue($varcharField->exists());
@ -181,7 +185,7 @@ class DBFieldTest extends SapphireTest {
$varcharField->setValue(null);
$this->assertFalse($varcharField->exists());
$textField = new Text("testfield");
$textField = new DBText("testfield");
$this->assertTrue($textField->getNullifyEmpty());
$textField->setValue('abc');
$this->assertTrue($textField->exists());
@ -190,7 +194,7 @@ class DBFieldTest extends SapphireTest {
$textField->setValue(null);
$this->assertFalse($textField->exists());
$textField = new Text("testfield", array('nullifyEmpty'=>false));
$textField = new DBText("testfield", array('nullifyEmpty'=>false));
$this->assertFalse($textField->getNullifyEmpty());
$textField->setValue('abc');
$this->assertTrue($textField->exists());

View File

@ -1,9 +1,13 @@
<?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBHTMLText;
/**
* @package framework
* @subpackage tests
*/
class HTMLTextTest extends SapphireTest {
class DBHTMLTextTest extends SapphireTest {
/**
* Test {@link HTMLText->LimitCharacters()}
@ -16,7 +20,7 @@ class HTMLTextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new HTMLText('Test');
$textObj = new DBHTMLText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitCharacters());
}
@ -37,7 +41,7 @@ class HTMLTextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new HTMLText('Test');
$textObj = new DBHTMLText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->Summary());
}
@ -52,7 +56,7 @@ class HTMLTextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new HTMLText('Test');
$textObj = new DBHTMLText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->Summary(5, 3, '...'));
}
@ -67,7 +71,7 @@ class HTMLTextTest extends SapphireTest {
$match = 'Cut it off, cut';
foreach($cases as $add) {
$textObj = new HTMLText();
$textObj = new DBHTMLText();
$textObj->setValue($orig);
$this->assertEquals($match.$add, $textObj->Summary(4, 0, $add));
}
@ -77,7 +81,7 @@ class HTMLTextTest extends SapphireTest {
$orig = '<p>Cut it off, cut it off</p>';
$match = 'Cut it off, cut';
$textObj = new HTMLText();
$textObj = new DBHTMLText();
$textObj->setValue($orig);
$this->assertEquals($match, $textObj->Summary(4, 10, ''));
}
@ -90,7 +94,7 @@ class HTMLTextTest extends SapphireTest {
);
foreach($cases as $orig => $match) {
$textObj = new HTMLText();
$textObj = new DBHTMLText();
$textObj->setValue($orig);
$this->assertEquals($match, $textObj->Summary(4, 0, ''));
}
@ -109,7 +113,7 @@ class HTMLTextTest extends SapphireTest {
);
foreach($cases as $orig => $match) {
$textObj = new HTMLText();
$textObj = new DBHTMLText();
$textObj->setValue($orig);
$this->assertEquals($match, $textObj->FirstSentence());
}
@ -144,7 +148,7 @@ class HTMLTextTest extends SapphireTest {
}
function testExists() {
$h = new HTMLText;
$h = new DBHTMLText();
$h->setValue("");
$this->assertFalse($h->exists());
$h->setValue("<p></p>");
@ -178,14 +182,14 @@ class HTMLTextTest extends SapphireTest {
}
function testWhitelist() {
$textObj = new HTMLText('Test', 'meta,link');
$textObj = new DBHTMLText('Test', 'meta,link');
$this->assertEquals(
'<meta content="Keep"><link href="Also Keep">',
$textObj->whitelistContent('<meta content="Keep"><p>Remove</p><link href="Also Keep" />Remove Text'),
'Removes any elements not in whitelist excluding text elements'
);
$textObj = new HTMLText('Test', 'meta,link,text()');
$textObj = new DBHTMLText('Test', 'meta,link,text()');
$this->assertEquals(
'<meta content="Keep"><link href="Also Keep">Keep Text',
$textObj->whitelistContent('<meta content="Keep"><p>Remove</p><link href="Also Keep" />Keep Text'),

View File

@ -1,21 +1,24 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* @package framework
* @subpackage tests
*/
class DBLocaleTest extends SapphireTest {
public function testNice() {
$l = DBField::create_field('DBLocale', 'de_DE');
$l = DBField::create_field('Locale', 'de_DE');
$this->assertEquals($l->Nice(), 'German');
}
public function testNiceNative() {
$l = DBField::create_field('DBLocale', 'de_DE');
$l = DBField::create_field('Locale', 'de_DE');
$this->assertEquals($l->Nice(true), 'Deutsch');
}
public function testNativeName() {
$l = DBField::create_field('DBLocale', 'de_DE');
$l = DBField::create_field('Locale', 'de_DE');
$this->assertEquals($l->getNativeName(), 'Deutsch');
}
}

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBMoney;
/**
* Partially based on Zend_CurrencyTest.
*
@ -11,7 +14,7 @@
* @package framework
* @subpackage tests
*/
class MoneyTest extends SapphireTest {
class DBMoneyTest extends SapphireTest {
protected static $fixture_file = 'MoneyTest.yml';
@ -22,14 +25,14 @@ class MoneyTest extends SapphireTest {
public function testMoneyFieldsReturnedAsObjects() {
$obj = $this->objFromFixture('MoneyTest_DataObject', 'test1');
$this->assertInstanceOf('Money', $obj->MyMoney);
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBMoney', $obj->MyMoney);
}
public function testLoadFromFixture() {
$obj = $this->objFromFixture('MoneyTest_DataObject', 'test1');
$this->assertInstanceOf('Money', $obj->MyMoney);
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBMoney', $obj->MyMoney);
$this->assertEquals($obj->MyMoney->getCurrency(), 'EUR');
$this->assertEquals($obj->MyMoney->getAmount(), 1.23);
}
@ -43,7 +46,7 @@ class MoneyTest extends SapphireTest {
$this->assertNotContains('MyMoney', array_keys($changed));
// With changes
$this->assertInstanceOf('Money', $obj->MyMoney);
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBMoney', $obj->MyMoney);
$obj->MyMoney->setAmount(99);
$changed = $obj->getChangedFields();
$this->assertContains('MyMoney', array_keys($changed), 'Field is detected as changed');
@ -53,13 +56,13 @@ class MoneyTest extends SapphireTest {
public function testCanOverwriteSettersWithNull() {
$obj = new MoneyTest_DataObject();
$m1 = new Money();
$m1 = new DBMoney();
$m1->setAmount(987.65);
$m1->setCurrency('USD');
$obj->MyMoney = $m1;
$obj->write();
$m2 = new Money();
$m2 = new DBMoney();
$m2->setAmount(null);
$m2->setCurrency(null);
$obj->MyMoney = $m2;
@ -82,7 +85,7 @@ class MoneyTest extends SapphireTest {
$obj = new MoneyTest_DataObject();
$m = new Money();
$m = new DBMoney();
$m->setAmount(987.65);
$m->setCurrency('USD');
$obj->MyMoney = $m;
@ -104,7 +107,7 @@ class MoneyTest extends SapphireTest {
}
public function testToCurrency() {
$USD = new Money();
$USD = new DBMoney();
$USD->setLocale('en_US');
$USD->setAmount(53292.18);
$this->assertSame('$53,292.18', $USD->Nice());
@ -112,7 +115,7 @@ class MoneyTest extends SapphireTest {
}
public function testGetSign() {
$SKR = new Money();
$SKR = new DBMoney();
$SKR->setValue(array(
'Currency' => 'SKR',
'Amount' => 3.44
@ -127,7 +130,7 @@ class MoneyTest extends SapphireTest {
} catch(Exception $e) {
}
$EUR = new Money();
$EUR = new DBMoney();
$EUR->setValue(array(
'Currency' => 'EUR',
'Amount' => 3.44
@ -138,7 +141,7 @@ class MoneyTest extends SapphireTest {
public function testGetName()
{
$m = new Money();
$m = new DBMoney();
$m->setValue(array(
'Currency' => 'EUR',
'Amount' => 3.44
@ -156,7 +159,7 @@ class MoneyTest extends SapphireTest {
}
public function testGetShortName() {
$m = new Money();
$m = new DBMoney();
$m->setValue(array(
'Currency' => 'EUR',
'Amount' => 3.44
@ -176,7 +179,7 @@ class MoneyTest extends SapphireTest {
}
public function testSetValueAsArray() {
$m = new Money();
$m = new DBMoney();
$m->setValue(array(
'Currency' => 'EUR',
'Amount' => 3.44
@ -192,12 +195,12 @@ class MoneyTest extends SapphireTest {
}
public function testSetValueAsMoney() {
$m1 = new Money();
$m1 = new DBMoney();
$m1->setValue(array(
'Currency' => 'EUR',
'Amount' => 3.44
));
$m2 = new Money();
$m2 = new DBMoney();
$m2->setValue($m1);
$this->assertEquals(
$m2->getCurrency(),
@ -210,17 +213,17 @@ class MoneyTest extends SapphireTest {
}
public function testExists() {
$m1 = new Money();
$m1 = new DBMoney();
$this->assertFalse($m1->exists());
$m2 = new Money();
$m2 = new DBMoney();
$m2->setValue(array(
'Currency' => 'EUR',
'Amount' => 3.44
));
$this->assertTrue($m2->exists());
$m3 = new Money();
$m3 = new DBMoney();
$m3->setValue(array(
'Currency' => 'EUR',
'Amount' => 0
@ -231,9 +234,9 @@ class MoneyTest extends SapphireTest {
public function testLoadIntoDataObject() {
$obj = new MoneyTest_DataObject();
$this->assertInstanceOf('Money', $obj->obj('MyMoney'));
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBMoney', $obj->obj('MyMoney'));
$m = new Money();
$m = new DBMoney();
$m->setValue(array(
'Currency' => 'EUR',
'Amount' => 1.23
@ -246,7 +249,7 @@ class MoneyTest extends SapphireTest {
public function testWriteToDataObject() {
$obj = new MoneyTest_DataObject();
$m = new Money();
$m = new DBMoney();
$m->setValue(array(
'Currency' => 'EUR',
'Amount' => 1.23
@ -280,7 +283,7 @@ class MoneyTest extends SapphireTest {
public function testHasAmount() {
$obj = new MoneyTest_DataObject();
$m = new Money();
$m = new DBMoney();
$obj->MyMoney = $m;
$m->setValue(array('Amount' => 1));

View File

@ -1,9 +1,12 @@
<?php
use SilverStripe\Model\FieldType\DBPercentage;
/**
* @package framework
* @subpackage tests
*/
class PercentageTest extends SapphireTest {
class DBPercentageTest extends SapphireTest {
public function testNice() {
/* Test the default Nice() output of Percentage */
@ -19,7 +22,7 @@ class PercentageTest extends SapphireTest {
);
foreach($cases as $original => $expected) {
$percentage = new Percentage('Probability');
$percentage = new DBPercentage('Probability');
$percentage->setValue($original);
$this->assertEquals($expected, $percentage->Nice());
}
@ -37,7 +40,7 @@ class PercentageTest extends SapphireTest {
);
foreach($cases as $original => $expected) {
$percentage = new Percentage('Probability', 2);
$percentage = new DBPercentage('Probability', 2);
$percentage->setValue($original);
$this->assertEquals($expected, $percentage->Nice());
}

View File

@ -1,13 +1,17 @@
<?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBString;
/**
* @package framework
* @subpackage tests
*/
class StringFieldTest extends SapphireTest {
class DBStringTest extends SapphireTest {
/**
* @covers StringField->forTemplate()
* @covers DBString->forTemplate()
*/
public function testForTemplate() {
$this->assertEquals(
@ -17,7 +21,7 @@ class StringFieldTest extends SapphireTest {
}
/**
* @covers StringField->LowerCase()
* @covers DBString->LowerCase()
*/
public function testLowerCase() {
$this->assertEquals(
@ -27,7 +31,7 @@ class StringFieldTest extends SapphireTest {
}
/**
* @covers StringField->UpperCase()
* @covers DBString->UpperCase()
*/
public function testUpperCase() {
$this->assertEquals(
@ -54,6 +58,6 @@ class StringFieldTest extends SapphireTest {
}
class StringFieldTest_MyStringField extends StringField implements TestOnly {
class StringFieldTest_MyStringField extends DBString implements TestOnly {
public function requireField() {}
}

View File

@ -1,9 +1,13 @@
<?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBText;
/**
* @package framework
* @subpackage tests
*/
class TextTest extends SapphireTest {
class DBTextTest extends SapphireTest {
/**
* Test {@link Text->LimitCharacters()}
@ -15,7 +19,7 @@ class TextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj = new DBText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitCharacters());
}
@ -44,7 +48,7 @@ class TextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj = new DBText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitCharactersToClosestWord(24));
}
@ -71,7 +75,7 @@ class TextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj = new DBText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitWordCount(3));
}
@ -89,7 +93,7 @@ class TextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj = new DBText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitWordCountXML(3));
}
@ -111,7 +115,7 @@ class TextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj = new DBText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitSentences(2));
}
@ -132,7 +136,7 @@ class TextTest extends SapphireTest {
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj = new DBText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->FirstSentence());
}

View File

@ -1,15 +1,18 @@
<?php
use SilverStripe\Model\FieldType\DBYear;
/**
* @package framework
* @subpackage tests
*/
class YearTest extends SapphireTest {
class DBYearTest extends SapphireTest {
/**
* Test that the scaffolding form field works
*/
public function testScaffoldFormFieldFirst() {
$year = new Year();
$year = new DBYear();
$field = $year->scaffoldFormField("YearTest");
$this->assertEquals("DropdownField", get_class($field));
@ -25,7 +28,7 @@ class YearTest extends SapphireTest {
}
public function testScaffoldFormFieldLast() {
$year = new Year();
$year = new DBYear();
$field = $year->scaffoldFormField("YearTest");
$source = $field->getSource();

View File

@ -152,7 +152,7 @@ class DataExtensionTest extends SapphireTest {
public function testDbObjectOnExtendedFields() {
$member = $this->objFromFixture('DataExtensionTest_Member', 'member1');
$this->assertNotNull($member->dbObject('Website'));
$this->assertInstanceOf('Varchar', $member->dbObject('Website'));
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBVarchar', $member->dbObject('Website'));
}
public function testExtensionCanBeAppliedToDataObject() {

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBClassName;
class DataObjectSchemaGenerationTest extends SapphireTest {
protected $extraDataObjects = array(
'DataObjectSchemaGenerationTest_DO',

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* @package framework
* @subpackage tests
@ -332,7 +335,7 @@ class DataObjectTest extends SapphireTest {
// check behaviour of dbObject with polymorphic relations
$favouriteDBObject = $fan1->dbObject('Favourite');
$favouriteValue = $favouriteDBObject->getValue();
$this->assertInstanceOf('PolymorphicForeignKey', $favouriteDBObject);
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBPolymorphicForeignKey', $favouriteDBObject);
$this->assertEquals($favourite->ID, $favouriteValue->ID);
$this->assertEquals($favourite->ClassName, $favouriteValue->ClassName);
}
@ -1667,16 +1670,16 @@ class DataObjectTest extends SapphireTest {
$captain = $this->objFromFixture('DataObjectTest_Player', 'captain1');
// Test traversal of a single has_one
$this->assertInstanceOf("Varchar", $captain->relObject('FavouriteTeam.Title'));
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBVarchar', $captain->relObject('FavouriteTeam.Title'));
$this->assertEquals("Team 1", $captain->relObject('FavouriteTeam.Title')->getValue());
// Test direct field access
$this->assertInstanceOf("Boolean", $captain->relObject('IsRetired'));
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBBoolean', $captain->relObject('IsRetired'));
$this->assertEquals(1, $captain->relObject('IsRetired')->getValue());
$player = $this->objFromFixture('DataObjectTest_Player', 'player2');
// Test that we can traverse more than once, and that arbitrary methods are okay
$this->assertInstanceOf("Varchar", $player->relObject('Teams.First.Title'));
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBVarchar', $player->relObject('Teams.First.Title'));
$this->assertEquals("Team 1", $player->relObject('Teams.First.Title')->getValue());
}

View File

@ -1,220 +0,0 @@
<?php
/**
* Tests for {@link SS_Datetime} class.
*
* @todo Current date comparisons are slightly dodgy, as they only compare
* the current date (not hour, minute, second) and assume that the date
* doesn't switch throughout the test execution. This means tests might
* fail when run at 23:59:59.
*
* @package framework
* @subpackage tests
*/
class SS_DatetimeTest extends SapphireTest {
public function testNowWithSystemDate() {
$systemDatetime = DBField::create_field('SS_Datetime', date('Y-m-d H:i:s'));
$nowDatetime = SS_Datetime::now();
$this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
}
public function testNowWithMockDate() {
// Test setting
$mockDate = '2001-12-31 22:10:59';
SS_Datetime::set_mock_now($mockDate);
$systemDatetime = DBField::create_field('SS_Datetime', date('Y-m-d H:i:s'));
$nowDatetime = SS_Datetime::now();
$this->assertNotEquals($systemDatetime->Date(), $nowDatetime->Date());
$this->assertEquals($nowDatetime->getValue(), $mockDate);
// Test clearing
SS_Datetime::clear_mock_now();
$systemDatetime = DBField::create_field('SS_Datetime', date('Y-m-d H:i:s'));
$nowDatetime = SS_Datetime::now();
$this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
}
public function testSetNullAndZeroValues() {
$date = DBField::create_field('SS_Datetime', '');
$this->assertNull($date->getValue(), 'Empty string evaluates to NULL');
$date = DBField::create_field('SS_Datetime', null);
$this->assertNull($date->getValue(), 'NULL is set as NULL');
$date = DBField::create_field('SS_Datetime', false);
$this->assertNull($date->getValue(), 'Boolean FALSE evaluates to NULL');
$date = DBField::create_field('SS_Datetime', '0');
$this->assertEquals('1970-01-01 00:00:00', $date->getValue(), 'String zero is UNIX epoch time');
$date = DBField::create_field('SS_Datetime', 0);
$this->assertEquals('1970-01-01 00:00:00', $date->getValue(), 'Numeric zero is UNIX epoch time');
}
public function testExtendedDateTimes() {
$date = DBField::create_field('SS_Datetime', '1500-10-10 15:32:24');
$this->assertEquals('10 Oct 1500 15 32 24', $date->Format('d M Y H i s'));
$date = DBField::create_field('SS_Datetime', '3000-10-10 15:32:24');
$this->assertEquals('10 Oct 3000 15 32 24', $date->Format('d M Y H i s'));
}
public function testNice() {
$date = DBField::create_field('SS_Datetime', '2001-12-31 22:10:59');
$this->assertEquals('31/12/2001 10:10pm', $date->Nice());
}
public function testNice24() {
$date = DBField::create_field('SS_Datetime', '2001-12-31 22:10:59');
$this->assertEquals('31/12/2001 22:10', $date->Nice24());
}
public function testDate() {
$date = DBField::create_field('SS_Datetime', '2001-12-31 22:10:59');
$this->assertEquals('31/12/2001', $date->Date());
}
public function testTime() {
$date = DBField::create_field('SS_Datetime', '2001-12-31 22:10:59');
$this->assertEquals('10:10pm', $date->Time());
}
public function testTime24() {
$date = DBField::create_field('SS_Datetime', '2001-12-31 22:10:59');
$this->assertEquals('22:10', $date->Time24());
}
public function testURLDateTime(){
$date = DBField::create_field('SS_Datetime', '2001-12-31 22:10:59');
$this->assertEquals('2001-12-31%2022:10:59', $date->URLDateTime());
}
public function testAgoInPast() {
SS_Datetime::set_mock_now('2000-12-31 12:00:00');
$this->assertEquals(
'10 years ago',
DBField::create_field('SS_Datetime', '1990-12-31 12:00:00')->Ago(),
'Exact past match on years'
);
$this->assertEquals(
'10 years ago',
DBField::create_field('SS_Datetime', '1990-12-30 12:00:00')->Ago(),
'Approximate past match on years'
);
$this->assertEquals(
'1 year ago',
DBField::create_field('SS_Datetime', '1999-12-30 12:00:12')->Ago(true, 1),
'Approximate past match in singular, significance=1'
);
$this->assertEquals(
'12 months ago',
DBField::create_field('SS_Datetime', '1999-12-30 12:00:12')->Ago(),
'Approximate past match in singular'
);
$this->assertEquals(
'50 mins ago',
DBField::create_field('SS_Datetime', '2000-12-31 11:10:11')->Ago(),
'Approximate past match on minutes'
);
$this->assertEquals(
'59 secs ago',
DBField::create_field('SS_Datetime', '2000-12-31 11:59:01')->Ago(),
'Approximate past match on seconds'
);
$this->assertEquals(
'less than a minute ago',
DBField::create_field('SS_Datetime', '2000-12-31 11:59:01')->Ago(false),
'Approximate past match on seconds with $includeSeconds=false'
);
$this->assertEquals(
'1 min ago',
DBField::create_field('SS_Datetime', '2000-12-31 11:58:50')->Ago(false),
'Test between 1 and 2 minutes with includeSeconds=false'
);
$this->assertEquals(
'70 secs ago',
DBField::create_field('SS_Datetime', '2000-12-31 11:58:50')->Ago(true),
'Test between 1 and 2 minutes with includeSeconds=true'
);
$this->assertEquals(
'4 mins ago',
DBField::create_field('SS_Datetime', '2000-12-31 11:55:50')->Ago(),
'Past match on minutes'
);
$this->assertEquals(
'1 hour ago',
DBField::create_field('SS_Datetime', '2000-12-31 10:50:58')->Ago(true, 1),
'Past match on hours, significance=1'
);
$this->assertEquals(
'3 hours ago',
DBField::create_field('SS_Datetime', '2000-12-31 08:50:58')->Ago(),
'Past match on hours'
);
SS_Datetime::clear_mock_now();
}
public function testAgoInFuture() {
SS_Datetime::set_mock_now('2000-12-31 00:00:00');
$this->assertEquals(
'in 10 years',
DBField::create_field('SS_Datetime', '2010-12-31 12:00:00')->Ago(),
'Exact past match on years'
);
$this->assertEquals(
'in 1 hour',
DBField::create_field('SS_Datetime', '2000-12-31 1:01:05')->Ago(true, 1),
'Approximate past match on minutes, significance=1'
);
$this->assertEquals(
'in 61 mins',
DBField::create_field('SS_Datetime', '2000-12-31 1:01:05')->Ago(),
'Approximate past match on minutes'
);
SS_Datetime::clear_mock_now();
}
public function testFormatFromSettings() {
$memberID = $this->logInWithPermission();
$member = DataObject::get_by_id('Member', $memberID);
$member->DateFormat = 'dd/MM/YYYY';
$member->TimeFormat = 'hh:mm:ss';
$member->write();
$fixtures = array(
'2000-12-31 10:11:01' => '31/12/2000 10:11:01',
'2000-12-31 1:11:01' => '31/12/2000 01:11:01',
'12/12/2000 1:11:01' => '12/12/2000 01:11:01',
'2000-12-31' => '31/12/2000 12:00:00',
'2014-04-01 10:11:01' => '01/04/2014 10:11:01',
'10:11:01' => date('d/m/Y').' 10:11:01'
);
foreach($fixtures as $from => $to) {
$date = DBField::create_field('SS_Datetime', $from);
// With member
$this->assertEquals($to, $date->FormatFromSettings($member));
// Without member
$this->assertEquals($to, $date->FormatFromSettings());
}
}
}

View File

@ -1,145 +1,224 @@
<?php
<?php
class DbDatetimeTest extends FunctionalTest {
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBDatetime;
protected static $fixture_file = 'DbDatetimeTest.yml';
/**
* Tests for {@link Datetime} class.
*
* @todo Current date comparisons are slightly dodgy, as they only compare
* the current date (not hour, minute, second) and assume that the date
* doesn't switch throughout the test execution. This means tests might
* fail when run at 23:59:59.
*
* @package framework
* @subpackage tests
*/
class DBDatetimeTest extends SapphireTest {
public function testNowWithSystemDate() {
$systemDatetime = DBField::create_field('Datetime', date('Y-m-d H:i:s'));
$nowDatetime = DBDatetime::now();
protected $extraDataObjects = array('DbDatetimeTest_Team');
protected $offset;
protected $adapter;
/**
* Check if dates match more or less. This takes into the account the db query
* can overflow to the next second giving offset readings.
*/
private function matchesRoughly($date1, $date2, $comment = '', $offset) {
$allowedDifference = 5 + abs($offset); // seconds
$time1 = is_numeric($date1) ? $date1 : strtotime($date1);
$time2 = is_numeric($date2) ? $date2 : strtotime($date2);
$this->assertTrue(abs($time1-$time2)<$allowedDifference,
$comment . " (times differ by " . abs($time1-$time2) . " seconds)");
$this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
}
private function getDbNow() {
$query = 'SELECT ' . $this->adapter->formattedDatetimeClause('now', '%U');
return DB::query($query)->value();
public function testNowWithMockDate() {
// Test setting
$mockDate = '2001-12-31 22:10:59';
DBDatetime::set_mock_now($mockDate);
$systemDatetime = DBField::create_field('Datetime', date('Y-m-d H:i:s'));
$nowDatetime = DBDatetime::now();
$this->assertNotEquals($systemDatetime->Date(), $nowDatetime->Date());
$this->assertEquals($nowDatetime->getValue(), $mockDate);
// Test clearing
DBDatetime::clear_mock_now();
$systemDatetime = DBField::create_field('Datetime', date('Y-m-d H:i:s'));
$nowDatetime = DBDatetime::now();
$this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
}
/**
* Needs to be run within a test*() context.
*
* @return Int Offset in seconds
*/
private function checkPreconditions() {
// number of seconds of php and db time are out of sync
$offset = time() - strtotime(DB::query('SELECT ' . DB::get_conn()->now())->value());
$threshold = 5; // seconds
public function testSetNullAndZeroValues() {
$date = DBField::create_field('Datetime', '');
$this->assertNull($date->getValue(), 'Empty string evaluates to NULL');
if($offset > 5) {
$this->markTestSkipped('The time of the database is out of sync with the webserver by '
. abs($offset) . ' seconds.');
$date = DBField::create_field('Datetime', null);
$this->assertNull($date->getValue(), 'NULL is set as NULL');
$date = DBField::create_field('Datetime', false);
$this->assertNull($date->getValue(), 'Boolean FALSE evaluates to NULL');
$date = DBField::create_field('Datetime', '0');
$this->assertEquals('1970-01-01 00:00:00', $date->getValue(), 'String zero is UNIX epoch time');
$date = DBField::create_field('Datetime', 0);
$this->assertEquals('1970-01-01 00:00:00', $date->getValue(), 'Numeric zero is UNIX epoch time');
}
public function testExtendedDateTimes() {
$date = DBField::create_field('Datetime', '1500-10-10 15:32:24');
$this->assertEquals('10 Oct 1500 15 32 24', $date->Format('d M Y H i s'));
$date = DBField::create_field('Datetime', '3000-10-10 15:32:24');
$this->assertEquals('10 Oct 3000 15 32 24', $date->Format('d M Y H i s'));
}
public function testNice() {
$date = DBField::create_field('Datetime', '2001-12-31 22:10:59');
$this->assertEquals('31/12/2001 10:10pm', $date->Nice());
}
public function testNice24() {
$date = DBField::create_field('Datetime', '2001-12-31 22:10:59');
$this->assertEquals('31/12/2001 22:10', $date->Nice24());
}
public function testDate() {
$date = DBField::create_field('Datetime', '2001-12-31 22:10:59');
$this->assertEquals('31/12/2001', $date->Date());
}
public function testTime() {
$date = DBField::create_field('Datetime', '2001-12-31 22:10:59');
$this->assertEquals('10:10pm', $date->Time());
}
public function testTime24() {
$date = DBField::create_field('Datetime', '2001-12-31 22:10:59');
$this->assertEquals('22:10', $date->Time24());
}
public function testURLDateTime(){
$date = DBField::create_field('Datetime', '2001-12-31 22:10:59');
$this->assertEquals('2001-12-31%2022:10:59', $date->URLDateTime());
}
public function testAgoInPast() {
DBDatetime::set_mock_now('2000-12-31 12:00:00');
$this->assertEquals(
'10 years ago',
DBField::create_field('Datetime', '1990-12-31 12:00:00')->Ago(),
'Exact past match on years'
);
$this->assertEquals(
'10 years ago',
DBField::create_field('Datetime', '1990-12-30 12:00:00')->Ago(),
'Approximate past match on years'
);
$this->assertEquals(
'1 year ago',
DBField::create_field('Datetime', '1999-12-30 12:00:12')->Ago(true, 1),
'Approximate past match in singular, significance=1'
);
$this->assertEquals(
'12 months ago',
DBField::create_field('Datetime', '1999-12-30 12:00:12')->Ago(),
'Approximate past match in singular'
);
$this->assertEquals(
'50 mins ago',
DBField::create_field('Datetime', '2000-12-31 11:10:11')->Ago(),
'Approximate past match on minutes'
);
$this->assertEquals(
'59 secs ago',
DBField::create_field('Datetime', '2000-12-31 11:59:01')->Ago(),
'Approximate past match on seconds'
);
$this->assertEquals(
'less than a minute ago',
DBField::create_field('Datetime', '2000-12-31 11:59:01')->Ago(false),
'Approximate past match on seconds with $includeSeconds=false'
);
$this->assertEquals(
'1 min ago',
DBField::create_field('Datetime', '2000-12-31 11:58:50')->Ago(false),
'Test between 1 and 2 minutes with includeSeconds=false'
);
$this->assertEquals(
'70 secs ago',
DBField::create_field('Datetime', '2000-12-31 11:58:50')->Ago(true),
'Test between 1 and 2 minutes with includeSeconds=true'
);
$this->assertEquals(
'4 mins ago',
DBField::create_field('Datetime', '2000-12-31 11:55:50')->Ago(),
'Past match on minutes'
);
$this->assertEquals(
'1 hour ago',
DBField::create_field('Datetime', '2000-12-31 10:50:58')->Ago(true, 1),
'Past match on hours, significance=1'
);
$this->assertEquals(
'3 hours ago',
DBField::create_field('Datetime', '2000-12-31 08:50:58')->Ago(),
'Past match on hours'
);
DBDatetime::clear_mock_now();
}
public function testAgoInFuture() {
DBDatetime::set_mock_now('2000-12-31 00:00:00');
$this->assertEquals(
'in 10 years',
DBField::create_field('Datetime', '2010-12-31 12:00:00')->Ago(),
'Exact past match on years'
);
$this->assertEquals(
'in 1 hour',
DBField::create_field('Datetime', '2000-12-31 1:01:05')->Ago(true, 1),
'Approximate past match on minutes, significance=1'
);
$this->assertEquals(
'in 61 mins',
DBField::create_field('Datetime', '2000-12-31 1:01:05')->Ago(),
'Approximate past match on minutes'
);
DBDatetime::clear_mock_now();
}
public function testFormatFromSettings() {
$memberID = $this->logInWithPermission();
$member = DataObject::get_by_id('Member', $memberID);
$member->DateFormat = 'dd/MM/YYYY';
$member->TimeFormat = 'hh:mm:ss';
$member->write();
$fixtures = array(
'2000-12-31 10:11:01' => '31/12/2000 10:11:01',
'2000-12-31 1:11:01' => '31/12/2000 01:11:01',
'12/12/2000 1:11:01' => '12/12/2000 01:11:01',
'2000-12-31' => '31/12/2000 12:00:00',
'2014-04-01 10:11:01' => '01/04/2014 10:11:01',
'10:11:01' => date('d/m/Y').' 10:11:01'
);
foreach($fixtures as $from => $to) {
$date = DBField::create_field('Datetime', $from);
// With member
$this->assertEquals($to, $date->FormatFromSettings($member));
// Without member
$this->assertEquals($to, $date->FormatFromSettings());
}
if(method_exists($this->adapter, 'supportsTimezoneOverride') && !$this->adapter->supportsTimezoneOverride()) {
$this->markTestSkipped("Database doesn't support timezone overrides");
}
return $offset;
}
public function setUp() {
parent::setUp();
$this->adapter = DB::get_conn();
}
public function testCorrectNow() {
$offset = $this->checkPreconditions();
$clause = $this->adapter->formattedDatetimeClause('now', '%U');
$result = DB::query('SELECT ' . $clause)->value();
$this->assertRegExp('/^\d*$/', (string) $result);
$this->assertTrue($result>0);
}
public function testDbDatetimeFormat() {
$offset = $this->checkPreconditions();
$clause = $this->adapter->formattedDatetimeClause('1973-10-14 10:30:00', '%H:%i, %d/%m/%Y');
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result, date('H:i, d/m/Y', strtotime('1973-10-14 10:30:00')), 'nice literal time',
$offset);
$clause = $this->adapter->formattedDatetimeClause('now', '%d');
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result, date('d', $this->getDbNow()), 'todays day', $offset);
$clause = $this->adapter->formattedDatetimeClause('"Created"', '%U') . ' AS test FROM "DbDateTimeTest_Team"';
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result, strtotime(DataObject::get_one('DbDateTimeTest_Team')->Created),
'fixture ->Created as timestamp', $offset);
}
public function testDbDatetimeInterval() {
$offset = $this->checkPreconditions();
$clause = $this->adapter->datetimeIntervalClause('1973-10-14 10:30:00', '+18 Years');
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result, '1991-10-14 10:30:00', 'add 18 years', $offset);
$clause = $this->adapter->datetimeIntervalClause('now', '+1 Day');
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result, date('Y-m-d H:i:s', strtotime('+1 Day', $this->getDbNow())), 'tomorrow',
$offset);
$query = new SQLSelect();
$query->setSelect(array());
$query->selectField($this->adapter->datetimeIntervalClause('"Created"', '-15 Minutes'), 'test')
->setFrom('"DbDateTimeTest_Team"')
->setLimit(1);
$result = $query->execute()->value();
$this->matchesRoughly($result,
date('Y-m-d H:i:s', strtotime(DataObject::get_one('DbDateTimeTest_Team')->Created) - 900),
'15 Minutes before creating fixture', $offset);
}
public function testDbDatetimeDifference() {
$offset = $this->checkPreconditions();
$clause = $this->adapter->datetimeDifferenceClause('1974-10-14 10:30:00', '1973-10-14 10:30:00');
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result/86400, 365, '1974 - 1973 = 365 * 86400 sec', $offset);
$clause = $this->adapter->datetimeDifferenceClause(date('Y-m-d H:i:s', strtotime('-15 seconds')), 'now');
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result, -15, '15 seconds ago - now', $offset);
$clause = $this->adapter->datetimeDifferenceClause('now',
$this->adapter->datetimeIntervalClause('now', '+45 Minutes'));
$result = DB::query('SELECT ' . $clause)->value();
$this->matchesRoughly($result, -45 * 60, 'now - 45 minutes ahead', $offset);
$query = new SQLSelect();
$query->setSelect(array());
$query->selectField($this->adapter->datetimeDifferenceClause('"LastEdited"', '"Created"'), 'test')
->setFrom('"DbDateTimeTest_Team"')
->setLimit(1);
$result = $query->execute()->value();
$lastedited = Dataobject::get_one('DbDateTimeTest_Team')->LastEdited;
$created = Dataobject::get_one('DbDateTimeTest_Team')->Created;
$this->matchesRoughly($result, strtotime($lastedited) - strtotime($created),
'age of HomePage record in seconds since unix epoc', $offset);
}
}
class DbDateTimeTest_Team extends DataObject implements TestOnly {
private static $db = array(
'Title' => 'Varchar'
);
}

View File

@ -46,7 +46,7 @@ class ImageTest extends SapphireTest {
}
public function testGetTagWithTitle() {
Config::inst()->update('DBFile', 'force_resample', false);
Config::inst()->update('SilverStripe\Filesystem\Storage\DBFile', 'force_resample', false);
$image = $this->objFromFixture('Image', 'imageWithTitle');
$expected = '<img src="/assets/ImageTest/folder/444065542b/test-image.png" alt="This is a image Title" />';
@ -56,7 +56,7 @@ class ImageTest extends SapphireTest {
}
public function testGetTagWithoutTitle() {
Config::inst()->update('DBFile', 'force_resample', false);
Config::inst()->update('SilverStripe\Filesystem\Storage\DBFile', 'force_resample', false);
$image = $this->objFromFixture('Image', 'imageWithoutTitle');
$expected = '<img src="/assets/ImageTest/folder/444065542b/test-image.png" alt="test image" />';
@ -66,7 +66,7 @@ class ImageTest extends SapphireTest {
}
public function testGetTagWithoutTitleContainingDots() {
Config::inst()->update('DBFile', 'force_resample', false);
Config::inst()->update('SilverStripe\Filesystem\Storage\DBFile', 'force_resample', false);
$image = $this->objFromFixture('Image', 'imageWithoutTitleContainingDots');
$expected = '<img src="/assets/ImageTest/folder/46affab704/test.image.with.dots.png" alt="test.image.with.dots" />';
@ -156,7 +156,7 @@ class ImageTest extends SapphireTest {
$imageLQR = $imageLQ->Resampled();
// Test resampled file is served when force_resample = true
Config::inst()->update('DBFile', 'force_resample', true);
Config::inst()->update('SilverStripe\Filesystem\Storage\DBFile', 'force_resample', true);
$this->assertLessThan($imageHQ->getAbsoluteSize(), $imageHQR->getAbsoluteSize(), 'Resampled image is smaller than original');
$this->assertEquals($imageHQ->getURL(), $imageHQR->getSourceURL(), 'Path to a resampled image was returned by getURL()');
@ -165,7 +165,7 @@ class ImageTest extends SapphireTest {
$this->assertNotEquals($imageLQ->getURL(), $imageLQR->getSourceURL(), 'Path to the original image file was returned by getURL()');
// Test original file is served when force_resample = false
Config::inst()->update('DBFile', 'force_resample', false);
Config::inst()->update('SilverStripe\Filesystem\Storage\DBFile', 'force_resample', false);
$this->assertNotEquals($imageHQ->getURL(), $imageHQR->getSourceURL(), 'Path to the original image file was returned by getURL()');
}

View File

@ -8,6 +8,6 @@ class LabelFieldTest extends SapphireTest {
public function testFieldHasNoNameAttribute() {
$field = new LabelField('MyName', 'MyTitle');
$this->assertEquals($field->Field(), '<label id="MyName" class="readonly">MyTitle</label>');
$this->assertEquals(trim($field->Field()), '<label id="MyName" class="readonly">MyTitle</label>');
}
}

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBMoney;
/**
* @package framework
* @subpackage tests
@ -40,7 +42,7 @@ class ManyManyListTest extends SapphireTest {
$obj = new ManyManyListTest_ExtraFields();
$obj->write();
$money = new Money();
$money = new DBMoney();
$money->setAmount(100);
$money->setCurrency('USD');
@ -53,7 +55,7 @@ class ManyManyListTest extends SapphireTest {
$check = $obj->Clients()->First();
$this->assertEquals('Foo', $check->Reference, 'Basic scalar fields should exist');
$this->assertInstanceOf('Money', $check->Worth, 'Composite fields should exist on the record');
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBMoney', $check->Worth, 'Composite fields should exist on the record');
$this->assertEquals(100, $check->Worth->getAmount());
}

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBDatetime;
/**
* @package framework
* @subpackage tests
@ -532,7 +534,7 @@ class VersionedTest extends SapphireTest {
public function testArchiveVersion() {
// In 2005 this file was created
SS_Datetime::set_mock_now('2005-01-01 00:00:00');
DBDatetime::set_mock_now('2005-01-01 00:00:00');
$testPage = new VersionedTest_Subclass();
$testPage->Title = 'Archived page';
$testPage->Content = 'This is the content from 2005';
@ -540,19 +542,19 @@ class VersionedTest extends SapphireTest {
$testPage->write();
// In 2007 we updated it
SS_Datetime::set_mock_now('2007-01-01 00:00:00');
DBDatetime::set_mock_now('2007-01-01 00:00:00');
$testPage->Content = "It's 2007 already!";
$testPage->ExtraField = '2007';
$testPage->write();
// In 2009 we updated it again
SS_Datetime::set_mock_now('2009-01-01 00:00:00');
DBDatetime::set_mock_now('2009-01-01 00:00:00');
$testPage->Content = "I'm enjoying 2009";
$testPage->ExtraField = '2009';
$testPage->write();
// End mock, back to the present day:)
SS_Datetime::clear_mock_now();
DBDatetime::clear_mock_now();
// Test 1 - 2006 Content
singleton('VersionedTest_Subclass')->flushCache(true);
@ -583,7 +585,7 @@ class VersionedTest extends SapphireTest {
public function testAllVersions()
{
// In 2005 this file was created
SS_Datetime::set_mock_now('2005-01-01 00:00:00');
DBDatetime::set_mock_now('2005-01-01 00:00:00');
$testPage = new VersionedTest_Subclass();
$testPage->Title = 'Archived page';
$testPage->Content = 'This is the content from 2005';
@ -591,7 +593,7 @@ class VersionedTest extends SapphireTest {
$testPage->write();
// In 2007 we updated it
SS_Datetime::set_mock_now('2007-01-01 00:00:00');
DBDatetime::set_mock_now('2007-01-01 00:00:00');
$testPage->Content = "It's 2007 already!";
$testPage->ExtraField = '2007';
$testPage->write();
@ -612,13 +614,13 @@ class VersionedTest extends SapphireTest {
$this->assertEquals($extraFields, array('2005', '2007'), 'Version fields returned');
// In 2009 we updated it again
SS_Datetime::set_mock_now('2009-01-01 00:00:00');
DBDatetime::set_mock_now('2009-01-01 00:00:00');
$testPage->Content = "I'm enjoying 2009";
$testPage->ExtraField = '2009';
$testPage->write();
// End mock, back to the present day:)
SS_Datetime::clear_mock_now();
DBDatetime::clear_mock_now();
$versions = Versioned::get_all_versions('VersionedTest_Subclass', $testPage->ID);
$content = array();
@ -637,7 +639,7 @@ class VersionedTest extends SapphireTest {
}
public function testArchiveRelatedDataWithoutVersioned() {
SS_Datetime::set_mock_now('2009-01-01 00:00:00');
DBDatetime::set_mock_now('2009-01-01 00:00:00');
$relatedData = new VersionedTest_RelatedWithoutVersion();
$relatedData->Name = 'Related Data';
@ -649,7 +651,7 @@ class VersionedTest extends SapphireTest {
$testData->Related()->add($relatedData);
$id = $testData->write();
SS_Datetime::set_mock_now('2010-01-01 00:00:00');
DBDatetime::set_mock_now('2010-01-01 00:00:00');
$testData->Content = 'After Content';
$testData->write();

View File

@ -1,4 +1,8 @@
<?php
use SilverStripe\Model\FieldType\DBDatetime;
use SilverStripe\Model\FieldType\DBClassName;
/**
* Test the security class, including log-in form, change password form, etc
*
@ -361,7 +365,7 @@ class SecurityTest extends FunctionalTest {
public function testChangePasswordFromLostPassword() {
$admin = $this->objFromFixture('Member', 'test');
$admin->FailedLoginCount = 99;
$admin->LockedOutUntil = SS_Datetime::now()->Format('Y-m-d H:i:s');
$admin->LockedOutUntil = DBDatetime::now()->Format('Y-m-d H:i:s');
$admin->write();
$this->assertNull($admin->AutoLoginHash, 'Hash is empty before lost password');

View File

@ -153,7 +153,7 @@ class ViewableDataTest extends SapphireTest {
// Casted data should be the string wrapped in a DBField-object.
$this->assertNotEmpty($castedData, 'Casted data was empty.');
$this->assertInstanceOf('DBField', $castedData, 'Casted data should be instance of DBField.');
$this->assertInstanceOf('SilverStripe\Model\FieldType\DBField', $castedData, 'Casted data should be instance of DBField.');
$this->assertEquals($uncastedData, $castedData->getValue(), 'Casted and uncasted strings are not equal.');
}

View File

@ -1,5 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBField;
/**
* This tracks the current scope for an SSViewer instance. It has three goals:
* - Handle entering & leaving sub-scopes in loops and withs
@ -507,7 +509,7 @@ class SSViewer_DataPresenter extends SSViewer_Scope {
// If not provided, use default
if (!$casting) $casting = Config::inst()->get('ViewableData', 'default_cast', Config::FIRST_SET);
$obj = new $casting($property);
$obj = Injector::inst()->get($casting, false, array($property));
$obj->setValue($res['value']);
$res['obj'] = $obj;

View File

@ -1,4 +1,7 @@
<?php
use SilverStripe\Model\FieldType\DBVarchar;
/**
* A ViewableData object is any object that can be rendered into a template/view.
*
@ -64,7 +67,7 @@ class ViewableData extends Object implements IteratorAggregate {
/**
* Converts a field spec into an object creator. For example: "Int" becomes "new Int($fieldName);" and "Varchar(50)"
* becomes "new Varchar($fieldName, 50);".
* becomes "new DBVarchar($fieldName, 50);".
*
* @param string $fieldSchema The field spec
* @return string
@ -317,7 +320,9 @@ class ViewableData extends Object implements IteratorAggregate {
public function escapeTypeForField($field) {
$class = $this->castingClass($field) ?: $this->config()->default_cast;
return Config::inst()->get($class, 'escape_type', Config::FIRST_SET);
// TODO: It would be quicker not to instantiate the object, but to merely
// get its class from the Injector
return Injector::inst()->get($class, true)->config()->escape_type;
}
/**