Merge pull request #4551 from sminnee/php7-support

PHP7 support
This commit is contained in:
Damian Mooyman 2016-03-23 09:21:51 +13:00
commit 633eb0163e
99 changed files with 1302 additions and 974 deletions

View File

@ -28,6 +28,8 @@ matrix:
env: DB=MYSQL PDO=1 env: DB=MYSQL PDO=1
- php: 5.6 - php: 5.6
env: DB=MYSQL BEHAT_TEST=1 JS_SANITY_CHECK=1 env: DB=MYSQL BEHAT_TEST=1 JS_SANITY_CHECK=1
- php: 7.0
env: DB=MYSQL PDO=1
before_script: before_script:
# Until http://pecl.php.net/package/imagick is working again # Until http://pecl.php.net/package/imagick is working again

53
_config/model.yml Normal file
View File

@ -0,0 +1,53 @@
Injector:
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\Forms\Schema\FormSchema;
use SilverStripe\Model\FieldType\DBField;
/** /**
* LeftAndMain is the parent class of all the two-pane views in the CMS. * 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 * @return String
*/ */
public function Locale() { public function Locale() {
return DBField::create_field('DBLocale', i18n::get_locale()); return DBField::create_field('Locale', i18n::get_locale());
} }
public function providePermissions() { public function providePermissions() {

View File

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

View File

@ -1,5 +1,7 @@
<?php <?php
use SilverStripe\Model\FieldType\DBDatetime;
/** /**
* A default backend for the setting and getting of cookies * 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 //expiry === 0 is a special case where we set a cookie for the current user session
if ($expiry !== 0) { if ($expiry !== 0) {
//don't do the maths if we are clearing //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 //set the path up
$path = $path ? $path : Director::baseURL(); $path = $path ? $path : Director::baseURL();

View File

@ -703,8 +703,8 @@ class Config_LRU {
public function __construct() { public function __construct() {
Deprecation::notice('4.0', 'Please use Config_MemCache instead', Deprecation::SCOPE_CLASS); Deprecation::notice('4.0', 'Please use Config_MemCache instead', Deprecation::SCOPE_CLASS);
if (version_compare(PHP_VERSION, '5.3.7', '<')) { if (version_compare(PHP_VERSION, '5.3.7', '<') || version_compare(PHP_VERSION, '6.99.99', '>')) {
// SplFixedArray causes seg faults before PHP 5.3.7 // SplFixedArray causes seg faults before PHP 5.3.7, and also in 7.0.0-RC1
$this->cache = array(); $this->cache = array();
} }
else { else {
@ -796,6 +796,13 @@ class Config_LRU {
$this->indexing = array(); $this->indexing = array();
} }
} }
/**
* Return the numbers of items in the index
*/
public function getIndexCount() {
return count($this->indexing);
}
} }
/** /**

View File

@ -14,12 +14,7 @@
// You may copy this code freely under the conditions of the GPL. // You may copy this code freely under the conditions of the GPL.
// //
// FIXME: possibly remove assert()'s for production version? define('USE_ASSERTS', true);
// PHP3 does not have assert()
/**
*/
define('USE_ASSERTS', function_exists('assert'));
/** /**
* @package framework * @package framework
@ -52,7 +47,7 @@ class _DiffOp {
class _DiffOp_Copy extends _DiffOp { class _DiffOp_Copy extends _DiffOp {
var $type = 'copy'; var $type = 'copy';
public function _DiffOp_Copy ($orig, $final = false) { public function __construct ($orig, $final = false) {
if (!is_array($final)) if (!is_array($final))
$final = $orig; $final = $orig;
$this->orig = $orig; $this->orig = $orig;
@ -72,7 +67,7 @@ class _DiffOp_Copy extends _DiffOp {
class _DiffOp_Delete extends _DiffOp { class _DiffOp_Delete extends _DiffOp {
var $type = 'delete'; var $type = 'delete';
public function _DiffOp_Delete ($lines) { public function __construct ($lines) {
$this->orig = $lines; $this->orig = $lines;
$this->final = false; $this->final = false;
} }
@ -90,7 +85,7 @@ class _DiffOp_Delete extends _DiffOp {
class _DiffOp_Add extends _DiffOp { class _DiffOp_Add extends _DiffOp {
var $type = 'add'; var $type = 'add';
public function _DiffOp_Add ($lines) { public function __construct ($lines) {
$this->final = $lines; $this->final = $lines;
$this->orig = false; $this->orig = false;
} }
@ -108,7 +103,7 @@ class _DiffOp_Add extends _DiffOp {
class _DiffOp_Change extends _DiffOp { class _DiffOp_Change extends _DiffOp {
var $type = 'change'; var $type = 'change';
public function _DiffOp_Change ($orig, $final) { public function __construct ($orig, $final) {
$this->orig = $orig; $this->orig = $orig;
$this->final = $final; $this->final = $final;
} }
@ -541,7 +536,7 @@ class Diff
* (Typically these are lines from a file.) * (Typically these are lines from a file.)
* @param $to_lines array An array of strings. * @param $to_lines array An array of strings.
*/ */
public function Diff($from_lines, $to_lines) { public function __construct($from_lines, $to_lines) {
$eng = new _DiffEngine; $eng = new _DiffEngine;
$this->edits = $eng->diff($from_lines, $to_lines); $this->edits = $eng->diff($from_lines, $to_lines);
//$this->_check($from_lines, $to_lines); //$this->_check($from_lines, $to_lines);
@ -853,13 +848,13 @@ extends Diff
* @param $mapped_to_lines array This array should * @param $mapped_to_lines array This array should
* have the same number of elements as $to_lines. * have the same number of elements as $to_lines.
*/ */
public function MappedDiff($from_lines, $to_lines, public function __construct($from_lines, $to_lines,
$mapped_from_lines, $mapped_to_lines) { $mapped_from_lines, $mapped_to_lines) {
assert(sizeof($from_lines) == sizeof($mapped_from_lines)); assert(sizeof($from_lines) == sizeof($mapped_from_lines));
assert(sizeof($to_lines) == sizeof($mapped_to_lines)); assert(sizeof($to_lines) == sizeof($mapped_to_lines));
$this->Diff($mapped_from_lines, $mapped_to_lines); parent::__construct($mapped_from_lines, $mapped_to_lines);
$xi = $yi = 0; $xi = $yi = 0;
// Optimizing loop invariants: // Optimizing loop invariants:

View File

@ -1,4 +1,8 @@
<?php <?php
use SilverStripe\Model\FieldType\DBField;
use SilverStripe\Model\FieldType\DBDatetime;
/** /**
* Test case class for the Sapphire framework. * 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 * 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; $this->originalIsRunningTest = null;
// Reset mocked datetime // Reset mocked datetime
SS_Datetime::clear_mock_now(); DBDatetime::clear_mock_now();
// Stop the redirection that might have been requested in the test. // Stop the redirection that might have been requested in the test.
// Note: Ideally a clean Controller should be created for each 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: Image:
extensions: extensions:
- MyImage - MyImage
DBFile: SilverStripe\Filesystem\Storage\DBFile:
extensions: extensions:
- MyImage - MyImage
@ -166,7 +166,7 @@ mysite/config/config.yml file:
File: File:
force_resample: true force_resample: true
# DBFile can be configured independently # DBFile can be configured independently
DBFile: SilverStripe\Filesystem\Storage\DBFile:
force_resample: true force_resample: true
If you are intending to resample images with SilverStripe it is good practice If you are intending to resample images with SilverStripe it is good practice

View File

@ -445,7 +445,7 @@ After:
// in _config.php // in _config.php
File::add_extension('MyImageExtension'); File::add_extension('MyImageExtension');
DBFile::add_extension('MyImageExtension'); SilverStripe\Filesystem\Storage\DBFile::add_extension('MyImageExtension');
There are a few differences in this new API: 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. ### Upgrading code that uses composite db fields.
`CompositeDBField` is now an abstract class, not an interface. In many cases, custom code that handled The `CompositeDBField` interface has been replaced with an abstract class, `DBComposite`. In many cases, custom code
saving of content into composite fields can be removed, as it is now handled by the base class. 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. The below describes the minimum amount of effort required to implement a composite DB field.
:::php :::php
<? <?
class MyAddressField extends CompositeDBField { class MyAddressField extends DBComposite {
private static $composite_db = array( private static $composite_db = array(
'Street' => 'Varchar(200)', '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 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 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, 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 Member;
use Versioned; use Versioned;
use SilverStripe\Filesystem\Storage\AssetStore; use SilverStripe\Filesystem\Storage\AssetStore;
use SilverStripe\Filesystem\Storage\DBFile;
/** /**
* This class provides the necessary business logic to ensure that any assets attached * 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 // Search for dbfile instances
$files = array(); $files = array();
foreach ($record->db() as $field => $db) { foreach ($record->db() as $field => $db) {
// Extract assets from this database field $fieldObj = $record->$field;
list($dbClass) = explode('(', $db); if(!is_object($fieldObj) || !($record->$field instanceof DBFile)) {
if (!is_a($dbClass, 'DBFile', true)) { continue;
continue;
} }
// Omit variant and merge with set // Omit variant and merge with set

View File

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

View File

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

View File

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

View File

@ -17,7 +17,7 @@ class CurrencyField extends TextField {
*/ */
public function setValue($val) { public function setValue($val) {
if(!$val) $val = 0.00; 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; return $this;
} }
/** /**
@ -44,7 +44,7 @@ class CurrencyField extends TextField {
} }
public function validate($validator) { 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*$/'; $regex = '/^\s*(\-?'.$currencySymbol.'?|'.$currencySymbol.'\-?)?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?\s*$/';
if(!empty ($this->value) if(!empty ($this->value)
&& !preg_match($regex, $this->value)) { && !preg_match($regex, $this->value)) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,12 @@
<?php <?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. * 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(); $db = Config::inst()->get($class, 'db', Config::UNINHERITED) ?: array();
foreach($db as $fieldName => $fieldSpec) { foreach($db as $fieldName => $fieldSpec) {
$fieldClass = strtok($fieldSpec, '('); $fieldClass = strtok($fieldSpec, '(');
if(is_subclass_of($fieldClass, 'CompositeDBField')) { if(singleton($fieldClass) instanceof DBComposite) {
$compositeFields[$fieldName] = $fieldSpec; $compositeFields[$fieldName] = $fieldSpec;
} else { } else {
$dbFields[$fieldName] = $fieldSpec; $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} * 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 * into the actual database fields, rather than the name of the field which
* might not equate a database column. * 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() * 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 * @param string $class Class name to query from
* @return array Map of fieldname to specification, similiar to {@link DataObject::$db}. * @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 * @throws ValidationException Exception that can be caught and handled by the calling function
*/ */
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) { public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$now = SS_Datetime::now()->Rfc2822(); $now = DBDatetime::now()->Rfc2822();
// Execute pre-write tasks // Execute pre-write tasks
$this->preWrite(); $this->preWrite();
@ -2421,7 +2429,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// Update the changed array with references to changed obj-fields // Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) { 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)) { if(is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
continue; continue;
} }
@ -2504,7 +2512,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// Situation 1a: Composite fields should remain bound in case they are // Situation 1a: Composite fields should remain bound in case they are
// later referenced to update the parent dataobject // later referenced to update the parent dataobject
if($val instanceof CompositeDBField) { if($val instanceof DBComposite) {
$val->bindTo($this); $val->bindTo($this);
$this->record[$fieldName] = $val; $this->record[$fieldName] = $val;
} }

View File

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

View File

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

View File

@ -1,4 +1,11 @@
<?php <?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. * 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 * This includes multi-value fields and transformed fields
@ -7,7 +14,7 @@
* *
* Example with a combined street name and number: * Example with a combined street name and number:
* <code> * <code>
* class Street extends CompositeDBField { * class Street extends DBComposite {
* private static $composite_db = return array( * private static $composite_db = return array(
* "Number" => "Int", * "Number" => "Int",
* "Name" => "Text" * "Name" => "Text"
@ -18,7 +25,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
abstract class CompositeDBField extends DBField { abstract class DBComposite extends DBField {
/** /**
* Similiar to {@link DataObject::$db}, * Similiar to {@link DataObject::$db},
@ -145,7 +152,7 @@ abstract class CompositeDBField extends DBField {
foreach($this->compositeDatabaseFields() as $field => $spec) { foreach($this->compositeDatabaseFields() as $field => $spec) {
// Check value // Check value
if($value instanceof CompositeDBField) { if($value instanceof DBComposite) {
// Check if saving from another composite field // Check if saving from another composite field
$this->setField($field, $value->getField($field)); $this->setField($field, $value->getField($field));

View File

@ -1,4 +1,9 @@
<?php <?php
namespace SilverStripe\Model\FieldType;
use Deprecation;
/** /**
* Represents a decimal field containing a currency amount. * Represents a decimal field containing a currency amount.
* The currency class only supports single currencies. For multi-currency support, use {@link Money} * The currency class only supports single currencies. For multi-currency support, use {@link Money}
@ -15,7 +20,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Currency extends Decimal { class DBCurrency extends DBDecimal {
/** /**
* @config * @config
@ -66,7 +71,7 @@ class Currency extends Decimal {
public static function setCurrencySymbol($value) { public static function setCurrencySymbol($value) {
Deprecation::notice('4.0', 'Use the "Currency.currency_symbol" config setting instead'); 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 <?php
namespace SilverStripe\Model\FieldType;
use DB;
use Member;
use Zend_Date;
use DateTime;
use DateField;
use Convert;
use Exception;
/** /**
* Represents a date field. * Represents a date field.
* The field currently supports New Zealand date format (DD/MM/YYYY), * The field currently supports New Zealand date format (DD/MM/YYYY),
@ -18,7 +29,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Date extends DBField { class DBDate extends DBField {
public function setValue($value, $record = null, $markChanged = true) { public function setValue($value, $record = null, $markChanged = true) {
if($value === false || $value === null || (is_string($value) && !strlen($value))) { 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) { public function Ago($includeSeconds = true, $significance = 2) {
if($this->value) { if($this->value) {
$time = SS_Datetime::now()->Format('U'); $time = DBDatetime::now()->Format('U');
if(strtotime($this->value) == $time || $time > strtotime($this->value)) { if(strtotime($this->value) == $time || $time > strtotime($this->value)) {
return _t( return _t(
'Date.TIMEDIFFAGO', 'Date.TIMEDIFFAGO',
@ -253,7 +264,7 @@ class Date extends DBField {
public function TimeDiff($includeSeconds = true, $significance = 2) { public function TimeDiff($includeSeconds = true, $significance = 2) {
if(!$this->value) return false; if(!$this->value) return false;
$time = SS_Datetime::now()->Format('U'); $time = DBDatetime::now()->Format('U');
$ago = abs($time - strtotime($this->value)); $ago = abs($time - strtotime($this->value));
if($ago < 60 && !$includeSeconds) { if($ago < 60 && !$includeSeconds) {
return _t('Date.LessThanMinuteAgo', 'less than a minute'); return _t('Date.LessThanMinuteAgo', 'less than a minute');
@ -282,7 +293,7 @@ class Date extends DBField {
public function TimeDiffIn($format) { public function TimeDiffIn($format) {
if(!$this->value) return false; if(!$this->value) return false;
$time = SS_Datetime::now()->Format('U'); $time = DBDatetime::now()->Format('U');
$ago = abs($time - strtotime($this->value)); $ago = abs($time - strtotime($this->value));
switch($format) { switch($format) {
@ -323,7 +334,7 @@ class Date extends DBField {
* @return boolean * @return boolean
*/ */
public function InPast() { 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 * @return boolean
*/ */
public function InFuture() { 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 * @return boolean
*/ */
public function IsToday() { 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 <?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. * Represents a date-time field.
* The field currently supports New Zealand date format (DD/MM/YYYY), * 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. * PHP's built-in date() and strtotime() function according to your system locale.
* *
* For all computations involving the current date and time, * 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 * 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}: * Example definition via {@link DataObject::$db}:
* <code> * <code>
@ -23,7 +34,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class SS_Datetime extends Date implements TemplateGlobalProvider { class DBDatetime extends DBDate implements TemplateGlobalProvider {
public function setValue($value, $record = null, $markChanged = true) { public function setValue($value, $record = null, $markChanged = true) {
if($value === false || $value === null || (is_string($value) && !strlen($value))) { 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)) { } elseif(is_string($datetime)) {
self::$mock_now = DBField::create_field('SS_Datetime', $datetime); self::$mock_now = DBField::create_field('SS_Datetime', $datetime);
} else { } 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 <?php
namespace SilverStripe\Model\FieldType;
use DB;
use NumericField;
/** /**
* Represents a Decimal field. * Represents a Decimal field.
* *
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Decimal extends DBField { class DBDecimal extends DBField {
protected $wholeSize, $decimalSize, $defaultValue; protected $wholeSize, $decimalSize, $defaultValue;

View File

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

View File

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

View File

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

View File

@ -1,11 +1,17 @@
<?php <?php
namespace SilverStripe\Model\FieldType;
use DB;
use NumericField;
/** /**
* Represents a floating point field. * Represents a floating point field.
* *
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Float extends DBField { class DBFloat extends DBField {
public function __construct($name = null, $defaultVal = 0) { public function __construct($name = null, $defaultVal = 0) {
$this->defaultVal = is_float($defaultVal) ? $defaultVal : (float) 0; $this->defaultVal = is_float($defaultVal) ? $defaultVal : (float) 0;

View File

@ -1,4 +1,13 @@
<?php <?php
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. * A special type Int field used for foreign keys in has_one relationships.
* @uses ImageField * @uses ImageField
@ -12,7 +21,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class ForeignKey extends Int { class DBForeignKey extends DBInt {
/** /**
* @var DataObject * @var DataObject

View File

@ -1,4 +1,15 @@
<?php <?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. * 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. * This behaves similarly to {@link Text}, but the template processor won't escape any HTML content within it.
@ -10,7 +21,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class HTMLText extends Text { class DBHTMLText extends DBText {
private static $escape_type = 'xml'; private static $escape_type = 'xml';
private static $casting = array( private static $casting = array(

View File

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

View File

@ -1,11 +1,19 @@
<?php <?php
namespace SilverStripe\Model\FieldType;
use DB;
use NumericField;
use ArrayList;
use ArrayData;
/** /**
* Represents a signed 32 bit integer field. * Represents a signed 32 bit integer field.
* *
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Int extends DBField { class DBInt extends DBField {
public function __construct($name = null, $defaultVal = 0) { public function __construct($name = null, $defaultVal = 0) {
$this->defaultVal = is_int($defaultVal) ? $defaultVal : 0; $this->defaultVal = is_int($defaultVal) ? $defaultVal : 0;
@ -64,3 +72,4 @@ class Int extends DBField {
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,15 @@
<?php <?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 * Represents a variable-length string of up to 2 megabytes, designed to store raw text
* *
@ -16,7 +27,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Text extends StringField { class DBText extends DBString {
private static $casting = array( private static $casting = array(
"AbsoluteLinks" => "Text", "AbsoluteLinks" => "Text",

View File

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

View File

@ -1,4 +1,12 @@
<?php <?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 * Class Varchar represents a variable-length string of up to 255 characters, designed to store raw text
* *
@ -9,7 +17,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Varchar extends StringField { class DBVarchar extends DBString {
private static $casting = array( private static $casting = array(
"Initial" => "Text", "Initial" => "Text",

View File

@ -1,4 +1,10 @@
<?php <?php
namespace SilverStripe\Model\FieldType;
use DB;
use DropdownField;
/** /**
* @package framework * @package framework
* @subpackage model * @subpackage model
@ -10,7 +16,7 @@
* @package framework * @package framework
* @subpackage model * @subpackage model
*/ */
class Year extends DBField { class DBYear extends DBField {
public function requireField() { public function requireField() {
$parts=Array('datatype'=>'year', 'precision'=>4, 'arrayValue'=>$this->arrayValue); $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 <?php
use SilverStripe\Model\FieldType\DBComposite;
/** /**
* Subclass of {@link DataList} representing a many_many relation. * Subclass of {@link DataList} representing a many_many relation.
* *
@ -88,7 +90,7 @@ class ManyManyList extends RelationList {
foreach($this->extraFields as $field => $spec) { foreach($this->extraFields as $field => $spec) {
$obj = Object::create_from_string($spec); $obj = Object::create_from_string($spec);
if($obj instanceof CompositeDBField) { if($obj instanceof DBComposite) {
$this->_compositeExtraFields[$field] = array(); $this->_compositeExtraFields[$field] = array();
// append the composite field names to the select // append the composite field names to the select

View File

@ -586,7 +586,7 @@ abstract class DBSchemaManager {
$spec['parts']['name'] = $field; $spec['parts']['name'] = $field;
$spec_orig['parts']['name'] = $field; $spec_orig['parts']['name'] = $field;
//Convert the $spec array into a database-specific string //Convert the $spec array into a database-specific string
$spec = $this->$spec['type']($spec['parts'], true); $spec = $this->{$spec['type']}($spec['parts'], true);
} }
// Collations didn't come in until MySQL 4.1. Anything earlier will throw a syntax error if you try and use // Collations didn't come in until MySQL 4.1. Anything earlier will throw a syntax error if you try and use
@ -623,7 +623,7 @@ abstract class DBSchemaManager {
// Get the version of the field as we would create it. This is used for comparison purposes to see if the // Get the version of the field as we would create it. This is used for comparison purposes to see if the
// existing field is different to what we now want // existing field is different to what we now want
if (is_array($spec_orig)) { if (is_array($spec_orig)) {
$spec_orig = $this->$spec_orig['type']($spec_orig['parts']); $spec_orig = $this->{$spec_orig['type']}($spec_orig['parts']);
} }
if ($newTable || $fieldValue == '') { if ($newTable || $fieldValue == '') {

View File

@ -1,4 +1,7 @@
<?php <?php
use SilverStripe\Model\FieldType\DBDatetime;
/** /**
* The member class which represents the users of the system * The member class which represents the users of the system
* *
@ -489,7 +492,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
$generator = new RandomGenerator(); $generator = new RandomGenerator();
$this->TempIDHash = $generator->randomToken('sha1'); $this->TempIDHash = $generator->randomToken('sha1');
$this->TempIDExpired = self::config()->temp_id_lifetime $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; : null;
$this->write(); $this->write();
} }
@ -706,7 +709,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
// Exclude expired // Exclude expired
if(static::config()->temp_id_lifetime) { 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(); return $members->first();

View File

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

View File

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

View File

@ -295,46 +295,42 @@ class ConfigTest extends SapphireTest {
} }
public function testLRUDiscarding() { public function testLRUDiscarding() {
$cache = new ConfigTest_Config_LRU(); $cache = new Config_LRU();
for ($i = 0; $i < Config_LRU::SIZE*2; $i++) $cache->set($i, $i); for ($i = 0; $i < Config_LRU::SIZE*2; $i++) $cache->set($i, $i);
$this->assertEquals( $this->assertEquals(
Config_LRU::SIZE, count($cache->indexing), Config_LRU::SIZE, $cache->getIndexCount(),
'Homogenous usage gives exact discarding' 'Homogenous usage gives exact discarding'
); );
$cache = new ConfigTest_Config_LRU(); $cache = new Config_LRU();
for ($i = 0; $i < Config_LRU::SIZE; $i++) $cache->set($i, $i); for ($i = 0; $i < Config_LRU::SIZE; $i++) $cache->set($i, $i);
for ($i = 0; $i < Config_LRU::SIZE; $i++) $cache->set(-1, -1); for ($i = 0; $i < Config_LRU::SIZE; $i++) $cache->set(-1, -1);
$this->assertLessThan( $this->assertLessThan(
Config_LRU::SIZE, count($cache->indexing), Config_LRU::SIZE, $cache->getIndexCount(),
'Heterogenous usage gives sufficient discarding' 'Heterogenous usage gives sufficient discarding'
); );
} }
public function testLRUCleaning() { public function testLRUCleaning() {
$cache = new ConfigTest_Config_LRU(); $cache = new Config_LRU();
for ($i = 0; $i < Config_LRU::SIZE; $i++) $cache->set($i, $i); for ($i = 0; $i < Config_LRU::SIZE; $i++) $cache->set($i, $i);
$this->assertEquals(Config_LRU::SIZE, count($cache->indexing)); $this->assertEquals(Config_LRU::SIZE, $cache->getIndexCount());
$cache->clean(); $cache->clean();
$this->assertEquals(0, count($cache->indexing), 'Clean clears all items'); $this->assertEquals(0, $cache->getIndexCount(), 'Clean clears all items');
$this->assertFalse($cache->get(1), 'Clean clears all items'); $this->assertFalse($cache->get(1), 'Clean clears all items');
$cache->set(1, 1, array('Foo')); $cache->set(1, 1, array('Foo'));
$this->assertEquals(1, count($cache->indexing)); $this->assertEquals(1, $cache->getIndexCount());
$cache->clean('Foo'); $cache->clean('Foo');
$this->assertEquals(0, count($cache->indexing), 'Clean items with matching tag'); $this->assertEquals(0, $cache->getIndexCount(), 'Clean items with matching tag');
$this->assertFalse($cache->get(1), 'Clean items with matching tag'); $this->assertFalse($cache->get(1), 'Clean items with matching tag');
$cache->set(1, 1, array('Foo', 'Bar')); $cache->set(1, 1, array('Foo', 'Bar'));
$this->assertEquals(1, count($cache->indexing)); $this->assertEquals(1, $cache->getIndexCount());
$cache->clean('Bar'); $cache->clean('Bar');
$this->assertEquals(0, count($cache->indexing), 'Clean items with any single matching tag'); $this->assertEquals(0, $cache->getIndexCount(), 'Clean items with any single matching tag');
$this->assertFalse($cache->get(1), 'Clean items with any single matching tag'); $this->assertFalse($cache->get(1), 'Clean items with any single matching tag');
} }
} }
class ConfigTest_Config_LRU extends Config_LRU implements TestOnly {
public $cache;
public $indexing;
}
class ConfigTest_Config_MemCache extends Config_MemCache implements TestOnly { class ConfigTest_Config_MemCache extends Config_MemCache implements TestOnly {
public $cache; public $cache;

View File

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

View File

@ -287,7 +287,7 @@ class FixtureBlueprintTest_SiteTree extends DataObject implements TestOnly {
class FixtureBlueprintTest_Page extends FixtureBlueprintTest_SiteTree { class FixtureBlueprintTest_Page extends FixtureBlueprintTest_SiteTree {
private static $db = array( 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\AssetContainer;
use SilverStripe\Filesystem\Storage\AssetStore; use SilverStripe\Filesystem\Storage\AssetStore;
use SilverStripe\Filesystem\Storage\FlysystemGeneratedAssetHandler; use SilverStripe\Filesystem\Storage\FlysystemGeneratedAssetHandler;
use SilverStripe\Filesystem\Storage\DBFile;
class AssetStoreTest extends SapphireTest { class AssetStoreTest extends SapphireTest {

View File

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

View File

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

View File

@ -16,7 +16,7 @@ class LookupFieldTest extends SapphireTest {
$this->assertEquals( $this->assertEquals(
'<span class="readonly" id="test"><i>(none)</i></span><input type="hidden" name="test" value="" />', '<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); $f->setValue(1);
$this->assertEquals( $this->assertEquals(
'<span class="readonly" id="test">one</span><input type="hidden" name="test" value="1" />', '<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() $f->dontEscape = true; // simulates CMSMain->compareversions()
$this->assertEquals( $this->assertEquals(
'<span class="readonly" id="test"><ins>w00t</ins></span><input type="hidden" name="test" value="" />', '<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')); $f->setValue(array('one','two'));
$this->assertEquals('<span class="readonly" id="test">one val, two val</span>' $this->assertEquals('<span class="readonly" id="test">one val, two val</span>'
. '<input type="hidden" name="test" value="one, two" />', . '<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)); $f->setValue(array(1,2));
$this->assertEquals( $this->assertEquals(
'<span class="readonly" id="test">one, two</span><input type="hidden" name="test" value="1, 2" />', '<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, $member1->ID,
$member2->ID $member2->ID
), ),
$f->Field()->getValue() trim($f->Field()->getValue())
); );
} }
@ -101,7 +101,7 @@ class LookupFieldTest extends SapphireTest {
$this->assertEquals( $this->assertEquals(
'<span class="readonly" id="test">Carrots</span><input type="hidden" name="test" value="3" />', '<span class="readonly" id="test">Carrots</span><input type="hidden" name="test" value="3" />',
$f->Field()->getValue() trim($f->Field()->getValue())
); );
$f->setValue(array( $f->setValue(array(
@ -110,7 +110,7 @@ class LookupFieldTest extends SapphireTest {
$this->assertEquals( $this->assertEquals(
'<span class="readonly" id="test">Carrots, Vegan</span><input type="hidden" name="test" value="3, 9" />', '<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 <?php
use SilverStripe\Model\FieldType\DBMoney;
/** /**
* @package framework * @package framework
* @subpackage tests * @subpackage tests
@ -13,7 +16,7 @@ class MoneyFieldTest extends SapphireTest {
public function testSaveInto() { public function testSaveInto() {
$o = new MoneyFieldTest_Object(); $o = new MoneyFieldTest_Object();
$m = new Money(); $m = new DBMoney();
$m->setAmount(123456.78); $m->setAmount(123456.78);
$m->setCurrency('EUR'); $m->setCurrency('EUR');
$f = new MoneyField('MyMoney', 'MyMoney', $m); $f = new MoneyField('MyMoney', 'MyMoney', $m);
@ -28,7 +31,7 @@ class MoneyFieldTest extends SapphireTest {
$f = new MoneyField('MyMoney', 'MyMoney'); $f = new MoneyField('MyMoney', 'MyMoney');
$m = new Money(); $m = new DBMoney();
$m->setAmount(123456.78); $m->setAmount(123456.78);
$m->setCurrency('EUR'); $m->setCurrency('EUR');
$f->setValue($m); $f->setValue($m);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,7 @@
<?php <?php
use SilverStripe\Model\FieldType\DBField;
/** /**
* @package framework * @package framework
* @subpackage tests * @subpackage tests
@ -332,7 +335,7 @@ class DataObjectTest extends SapphireTest {
// check behaviour of dbObject with polymorphic relations // check behaviour of dbObject with polymorphic relations
$favouriteDBObject = $fan1->dbObject('Favourite'); $favouriteDBObject = $fan1->dbObject('Favourite');
$favouriteValue = $favouriteDBObject->getValue(); $favouriteValue = $favouriteDBObject->getValue();
$this->assertInstanceOf('PolymorphicForeignKey', $favouriteDBObject); $this->assertInstanceOf('SilverStripe\Model\FieldType\DBPolymorphicForeignKey', $favouriteDBObject);
$this->assertEquals($favourite->ID, $favouriteValue->ID); $this->assertEquals($favourite->ID, $favouriteValue->ID);
$this->assertEquals($favourite->ClassName, $favouriteValue->ClassName); $this->assertEquals($favourite->ClassName, $favouriteValue->ClassName);
} }
@ -1667,16 +1670,16 @@ class DataObjectTest extends SapphireTest {
$captain = $this->objFromFixture('DataObjectTest_Player', 'captain1'); $captain = $this->objFromFixture('DataObjectTest_Player', 'captain1');
// Test traversal of a single has_one // 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()); $this->assertEquals("Team 1", $captain->relObject('FavouriteTeam.Title')->getValue());
// Test direct field access // 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()); $this->assertEquals(1, $captain->relObject('IsRetired')->getValue());
$player = $this->objFromFixture('DataObjectTest_Player', 'player2'); $player = $this->objFromFixture('DataObjectTest_Player', 'player2');
// Test that we can traverse more than once, and that arbitrary methods are okay // 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()); $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'); $this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
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)");
} }
private function getDbNow() { public function testNowWithMockDate() {
$query = 'SELECT ' . $this->adapter->formattedDatetimeClause('now', '%U'); // Test setting
return DB::query($query)->value(); $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());
} }
/** public function testSetNullAndZeroValues() {
* Needs to be run within a test*() context. $date = DBField::create_field('Datetime', '');
* $this->assertNull($date->getValue(), 'Empty string evaluates to NULL');
* @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
if($offset > 5) { $date = DBField::create_field('Datetime', null);
$this->markTestSkipped('The time of the database is out of sync with the webserver by ' $this->assertNull($date->getValue(), 'NULL is set as NULL');
. abs($offset) . ' seconds.');
$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() { 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'); $image = $this->objFromFixture('Image', 'imageWithTitle');
$expected = '<img src="/assets/ImageTest/folder/444065542b/test-image.png" alt="This is a image Title" />'; $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() { 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'); $image = $this->objFromFixture('Image', 'imageWithoutTitle');
$expected = '<img src="/assets/ImageTest/folder/444065542b/test-image.png" alt="test image" />'; $expected = '<img src="/assets/ImageTest/folder/444065542b/test-image.png" alt="test image" />';
@ -66,7 +66,7 @@ class ImageTest extends SapphireTest {
} }
public function testGetTagWithoutTitleContainingDots() { 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'); $image = $this->objFromFixture('Image', 'imageWithoutTitleContainingDots');
$expected = '<img src="/assets/ImageTest/folder/46affab704/test.image.with.dots.png" alt="test.image.with.dots" />'; $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(); $imageLQR = $imageLQ->Resampled();
// Test resampled file is served when force_resample = true // 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->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()'); $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()'); $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 // 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()'); $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() { public function testFieldHasNoNameAttribute() {
$field = new LabelField('MyName', 'MyTitle'); $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 <?php
use SilverStripe\Model\FieldType\DBMoney;
/** /**
* @package framework * @package framework
* @subpackage tests * @subpackage tests
@ -40,7 +42,7 @@ class ManyManyListTest extends SapphireTest {
$obj = new ManyManyListTest_ExtraFields(); $obj = new ManyManyListTest_ExtraFields();
$obj->write(); $obj->write();
$money = new Money(); $money = new DBMoney();
$money->setAmount(100); $money->setAmount(100);
$money->setCurrency('USD'); $money->setCurrency('USD');
@ -53,7 +55,7 @@ class ManyManyListTest extends SapphireTest {
$check = $obj->Clients()->First(); $check = $obj->Clients()->First();
$this->assertEquals('Foo', $check->Reference, 'Basic scalar fields should exist'); $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()); $this->assertEquals(100, $check->Worth->getAmount());
} }

View File

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

View File

@ -1,4 +1,8 @@
<?php <?php
use SilverStripe\Model\FieldType\DBDatetime;
use SilverStripe\Model\FieldType\DBClassName;
/** /**
* Test the security class, including log-in form, change password form, etc * Test the security class, including log-in form, change password form, etc
* *
@ -361,7 +365,7 @@ class SecurityTest extends FunctionalTest {
public function testChangePasswordFromLostPassword() { public function testChangePasswordFromLostPassword() {
$admin = $this->objFromFixture('Member', 'test'); $admin = $this->objFromFixture('Member', 'test');
$admin->FailedLoginCount = 99; $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(); $admin->write();
$this->assertNull($admin->AutoLoginHash, 'Hash is empty before lost password'); $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. // Casted data should be the string wrapped in a DBField-object.
$this->assertNotEmpty($castedData, 'Casted data was empty.'); $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.'); $this->assertEquals($uncastedData, $castedData->getValue(), 'Casted and uncasted strings are not equal.');
} }

View File

@ -27,7 +27,7 @@ class SimpleCookie {
var $_path; var $_path;
var $_expiry; var $_expiry;
var $_is_secure; var $_is_secure;
/** /**
* Constructor. Sets the stored values. * Constructor. Sets the stored values.
* @param string $name Cookie key. * @param string $name Cookie key.
@ -36,7 +36,7 @@ class SimpleCookie {
* @param string $expiry Expiry date as string. * @param string $expiry Expiry date as string.
* @param boolean $is_secure Currently ignored. * @param boolean $is_secure Currently ignored.
*/ */
function SimpleCookie($name, $value = false, $path = false, $expiry = false, $is_secure = false) { function __construct($name, $value = false, $path = false, $expiry = false, $is_secure = false) {
$this->_host = false; $this->_host = false;
$this->_name = $name; $this->_name = $name;
$this->_value = $value; $this->_value = $value;
@ -49,7 +49,7 @@ class SimpleCookie {
} }
$this->_is_secure = $is_secure; $this->_is_secure = $is_secure;
} }
/** /**
* Sets the host. The cookie rules determine * Sets the host. The cookie rules determine
* that the first two parts are taken for * that the first two parts are taken for
@ -67,7 +67,7 @@ class SimpleCookie {
} }
return false; return false;
} }
/** /**
* Accessor for the truncated host to which this * Accessor for the truncated host to which this
* cookie applies. * cookie applies.
@ -77,7 +77,7 @@ class SimpleCookie {
function getHost() { function getHost() {
return $this->_host; return $this->_host;
} }
/** /**
* Test for a cookie being valid for a host name. * Test for a cookie being valid for a host name.
* @param string $host Host to test against. * @param string $host Host to test against.
@ -87,7 +87,7 @@ class SimpleCookie {
function isValidHost($host) { function isValidHost($host) {
return ($this->_truncateHost($host) === $this->getHost()); return ($this->_truncateHost($host) === $this->getHost());
} }
/** /**
* Extracts just the domain part that determines a * Extracts just the domain part that determines a
* cookie's host validity. * cookie's host validity.
@ -104,7 +104,7 @@ class SimpleCookie {
} }
return false; return false;
} }
/** /**
* Accessor for name. * Accessor for name.
* @return string Cookie key. * @return string Cookie key.
@ -113,7 +113,7 @@ class SimpleCookie {
function getName() { function getName() {
return $this->_name; return $this->_name;
} }
/** /**
* Accessor for value. A deleted cookie will * Accessor for value. A deleted cookie will
* have an empty string for this. * have an empty string for this.
@ -123,7 +123,7 @@ class SimpleCookie {
function getValue() { function getValue() {
return $this->_value; return $this->_value;
} }
/** /**
* Accessor for path. * Accessor for path.
* @return string Valid cookie path. * @return string Valid cookie path.
@ -132,7 +132,7 @@ class SimpleCookie {
function getPath() { function getPath() {
return $this->_path; return $this->_path;
} }
/** /**
* Tests a path to see if the cookie applies * Tests a path to see if the cookie applies
* there. The test path must be longer or * there. The test path must be longer or
@ -147,7 +147,7 @@ class SimpleCookie {
$this->getPath(), $this->getPath(),
strlen($this->getPath())) == 0); strlen($this->getPath())) == 0);
} }
/** /**
* Accessor for expiry. * Accessor for expiry.
* @return string Expiry string. * @return string Expiry string.
@ -159,7 +159,7 @@ class SimpleCookie {
} }
return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT"; return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT";
} }
/** /**
* Test to see if cookie is expired against * Test to see if cookie is expired against
* the cookie format time or timestamp. * the cookie format time or timestamp.
@ -180,7 +180,7 @@ class SimpleCookie {
} }
return ($this->_expiry < $now); return ($this->_expiry < $now);
} }
/** /**
* Ages the cookie by the specified number of * Ages the cookie by the specified number of
* seconds. * seconds.
@ -192,7 +192,7 @@ class SimpleCookie {
$this->_expiry -= $interval; $this->_expiry -= $interval;
} }
} }
/** /**
* Accessor for the secure flag. * Accessor for the secure flag.
* @return boolean True if cookie needs SSL. * @return boolean True if cookie needs SSL.
@ -201,7 +201,7 @@ class SimpleCookie {
function isSecure() { function isSecure() {
return $this->_is_secure; return $this->_is_secure;
} }
/** /**
* Adds a trailing and leading slash to the path * Adds a trailing and leading slash to the path
* if missing. * if missing.
@ -227,15 +227,15 @@ class SimpleCookie {
*/ */
class SimpleCookieJar { class SimpleCookieJar {
var $_cookies; var $_cookies;
/** /**
* Constructor. Jar starts empty. * Constructor. Jar starts empty.
* @access public * @access public
*/ */
function SimpleCookieJar() { function __construct() {
$this->_cookies = array(); $this->_cookies = array();
} }
/** /**
* Removes expired and temporary cookies as if * Removes expired and temporary cookies as if
* the browser was closed and re-opened. * the browser was closed and re-opened.
@ -258,7 +258,7 @@ class SimpleCookieJar {
} }
$this->_cookies = $surviving_cookies; $this->_cookies = $surviving_cookies;
} }
/** /**
* Ages all cookies in the cookie jar. * Ages all cookies in the cookie jar.
* @param integer $interval The old session is moved * @param integer $interval The old session is moved
@ -272,7 +272,7 @@ class SimpleCookieJar {
$this->_cookies[$i]->agePrematurely($interval); $this->_cookies[$i]->agePrematurely($interval);
} }
} }
/** /**
* Sets an additional cookie. If a cookie has * Sets an additional cookie. If a cookie has
* the same name and path it is replaced. * the same name and path it is replaced.
@ -290,7 +290,7 @@ class SimpleCookieJar {
} }
$this->_cookies[$this->_findFirstMatch($cookie)] = $cookie; $this->_cookies[$this->_findFirstMatch($cookie)] = $cookie;
} }
/** /**
* Finds a matching cookie to write over or the * Finds a matching cookie to write over or the
* first empty slot if none. * first empty slot if none.
@ -311,7 +311,7 @@ class SimpleCookieJar {
} }
return count($this->_cookies); return count($this->_cookies);
} }
/** /**
* Reads the most specific cookie value from the * Reads the most specific cookie value from the
* browser cookies. Looks for the longest path that * browser cookies. Looks for the longest path that
@ -335,7 +335,7 @@ class SimpleCookieJar {
} }
return (isset($value) ? $value : false); return (isset($value) ? $value : false);
} }
/** /**
* Tests cookie for matching against search * Tests cookie for matching against search
* criteria. * criteria.
@ -359,7 +359,7 @@ class SimpleCookieJar {
} }
return true; return true;
} }
/** /**
* Uses a URL to sift relevant cookies by host and * Uses a URL to sift relevant cookies by host and
* path. Results are list of strings of form "name=value". * path. Results are list of strings of form "name=value".

View File

@ -5,7 +5,7 @@
* @subpackage WebTester * @subpackage WebTester
* @version $Id: encoding.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: encoding.php 1723 2008-04-08 00:34:10Z lastcraft $
*/ */
/**#@+ /**#@+
* include other SimpleTest class files * include other SimpleTest class files
*/ */
@ -20,17 +20,17 @@ require_once(dirname(__FILE__) . '/socket.php');
class SimpleEncodedPair { class SimpleEncodedPair {
var $_key; var $_key;
var $_value; var $_value;
/** /**
* Stashes the data for rendering later. * Stashes the data for rendering later.
* @param string $key Form element name. * @param string $key Form element name.
* @param string $value Data to send. * @param string $value Data to send.
*/ */
function SimpleEncodedPair($key, $value) { function __construct($key, $value) {
$this->_key = $key; $this->_key = $key;
$this->_value = $value; $this->_value = $value;
} }
/** /**
* The pair as a single string. * The pair as a single string.
* @return string Encoded pair. * @return string Encoded pair.
@ -39,7 +39,7 @@ class SimpleEncodedPair {
function asRequest() { function asRequest() {
return urlencode($this->_key) . '=' . urlencode($this->_value); return urlencode($this->_key) . '=' . urlencode($this->_value);
} }
/** /**
* The MIME part as a string. * The MIME part as a string.
* @return string MIME part encoding. * @return string MIME part encoding.
@ -51,7 +51,7 @@ class SimpleEncodedPair {
$part .= "\r\n" . $this->_value; $part .= "\r\n" . $this->_value;
return $part; return $part;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @param string $key Identifier. * @param string $key Identifier.
@ -61,7 +61,7 @@ class SimpleEncodedPair {
function isKey($key) { function isKey($key) {
return $key == $this->_key; return $key == $this->_key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Identifier. * @return string Identifier.
@ -70,7 +70,7 @@ class SimpleEncodedPair {
function getKey() { function getKey() {
return $this->_key; return $this->_key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Content. * @return string Content.
@ -90,19 +90,19 @@ class SimpleAttachment {
var $_key; var $_key;
var $_content; var $_content;
var $_filename; var $_filename;
/** /**
* Stashes the data for rendering later. * Stashes the data for rendering later.
* @param string $key Key to add value to. * @param string $key Key to add value to.
* @param string $content Raw data. * @param string $content Raw data.
* @param hash $filename Original filename. * @param hash $filename Original filename.
*/ */
function SimpleAttachment($key, $content, $filename) { function __construct($key, $content, $filename) {
$this->_key = $key; $this->_key = $key;
$this->_content = $content; $this->_content = $content;
$this->_filename = $filename; $this->_filename = $filename;
} }
/** /**
* The pair as a single string. * The pair as a single string.
* @return string Encoded pair. * @return string Encoded pair.
@ -111,7 +111,7 @@ class SimpleAttachment {
function asRequest() { function asRequest() {
return ''; return '';
} }
/** /**
* The MIME part as a string. * The MIME part as a string.
* @return string MIME part encoding. * @return string MIME part encoding.
@ -125,7 +125,7 @@ class SimpleAttachment {
$part .= "\r\n\r\n" . $this->_content; $part .= "\r\n\r\n" . $this->_content;
return $part; return $part;
} }
/** /**
* Attempts to figure out the MIME type from the * Attempts to figure out the MIME type from the
* file extension and the content. * file extension and the content.
@ -138,7 +138,7 @@ class SimpleAttachment {
} }
return 'application/octet-stream'; return 'application/octet-stream';
} }
/** /**
* Tests each character is in the range 0-127. * Tests each character is in the range 0-127.
* @param string $ascii String to test. * @param string $ascii String to test.
@ -152,7 +152,7 @@ class SimpleAttachment {
} }
return true; return true;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @param string $key Identifier. * @param string $key Identifier.
@ -162,7 +162,7 @@ class SimpleAttachment {
function isKey($key) { function isKey($key) {
return $key == $this->_key; return $key == $this->_key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Identifier. * @return string Identifier.
@ -171,7 +171,7 @@ class SimpleAttachment {
function getKey() { function getKey() {
return $this->_key; return $this->_key;
} }
/** /**
* Is this the value we are looking for? * Is this the value we are looking for?
* @return string Content. * @return string Content.
@ -190,7 +190,7 @@ class SimpleAttachment {
*/ */
class SimpleEncoding { class SimpleEncoding {
var $_request; var $_request;
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -198,14 +198,14 @@ class SimpleEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleEncoding($query = false) { function __construct($query = false) {
if (! $query) { if (! $query) {
$query = array(); $query = array();
} }
$this->clear(); $this->clear();
$this->merge($query); $this->merge($query);
} }
/** /**
* Empties the request of parameters. * Empties the request of parameters.
* @access public * @access public
@ -213,7 +213,7 @@ class SimpleEncoding {
function clear() { function clear() {
$this->_request = array(); $this->_request = array();
} }
/** /**
* Adds a parameter to the query. * Adds a parameter to the query.
* @param string $key Key to add value to. * @param string $key Key to add value to.
@ -232,7 +232,7 @@ class SimpleEncoding {
$this->_addPair($key, $value); $this->_addPair($key, $value);
} }
} }
/** /**
* Adds a new value into the request. * Adds a new value into the request.
* @param string $key Key to add value to. * @param string $key Key to add value to.
@ -242,7 +242,7 @@ class SimpleEncoding {
function _addPair($key, $value) { function _addPair($key, $value) {
$this->_request[] = new SimpleEncodedPair($key, $value); $this->_request[] = new SimpleEncodedPair($key, $value);
} }
/** /**
* Adds a MIME part to the query. Does nothing for a * Adds a MIME part to the query. Does nothing for a
* form encoded packet. * form encoded packet.
@ -254,7 +254,7 @@ class SimpleEncoding {
function attach($key, $content, $filename) { function attach($key, $content, $filename) {
$this->_request[] = new SimpleAttachment($key, $content, $filename); $this->_request[] = new SimpleAttachment($key, $content, $filename);
} }
/** /**
* Adds a set of parameters to this query. * Adds a set of parameters to this query.
* @param array/SimpleQueryString $query Multiple values are * @param array/SimpleQueryString $query Multiple values are
@ -270,7 +270,7 @@ class SimpleEncoding {
} }
} }
} }
/** /**
* Accessor for single value. * Accessor for single value.
* @return string/array False if missing, string * @return string/array False if missing, string
@ -293,7 +293,7 @@ class SimpleEncoding {
return $values; return $values;
} }
} }
/** /**
* Accessor for listing of pairs. * Accessor for listing of pairs.
* @return array All pair objects. * @return array All pair objects.
@ -302,7 +302,7 @@ class SimpleEncoding {
function getAll() { function getAll() {
return $this->_request; return $this->_request;
} }
/** /**
* Renders the query string as a URL encoded * Renders the query string as a URL encoded
* request part. * request part.
@ -327,7 +327,7 @@ class SimpleEncoding {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleGetEncoding extends SimpleEncoding { class SimpleGetEncoding extends SimpleEncoding {
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -335,10 +335,10 @@ class SimpleGetEncoding extends SimpleEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleGetEncoding($query = false) { function __construct($query = false) {
$this->SimpleEncoding($query); parent::__construct($query);
} }
/** /**
* HTTP request method. * HTTP request method.
* @return string Always GET. * @return string Always GET.
@ -347,7 +347,7 @@ class SimpleGetEncoding extends SimpleEncoding {
function getMethod() { function getMethod() {
return 'GET'; return 'GET';
} }
/** /**
* Writes no extra headers. * Writes no extra headers.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
@ -355,7 +355,7 @@ class SimpleGetEncoding extends SimpleEncoding {
*/ */
function writeHeadersTo(&$socket) { function writeHeadersTo(&$socket) {
} }
/** /**
* No data is sent to the socket as the data is encoded into * No data is sent to the socket as the data is encoded into
* the URL. * the URL.
@ -364,7 +364,7 @@ class SimpleGetEncoding extends SimpleEncoding {
*/ */
function writeTo(&$socket) { function writeTo(&$socket) {
} }
/** /**
* Renders the query string as a URL encoded * Renders the query string as a URL encoded
* request part for attaching to a URL. * request part for attaching to a URL.
@ -382,7 +382,7 @@ class SimpleGetEncoding extends SimpleEncoding {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleHeadEncoding extends SimpleGetEncoding { class SimpleHeadEncoding extends SimpleGetEncoding {
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -390,10 +390,10 @@ class SimpleHeadEncoding extends SimpleGetEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleHeadEncoding($query = false) { function __construct($query = false) {
$this->SimpleGetEncoding($query); parent::__construct($query);
} }
/** /**
* HTTP request method. * HTTP request method.
* @return string Always HEAD. * @return string Always HEAD.
@ -411,7 +411,7 @@ class SimpleHeadEncoding extends SimpleGetEncoding {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimplePostEncoding extends SimpleEncoding { class SimplePostEncoding extends SimpleEncoding {
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -419,13 +419,13 @@ class SimplePostEncoding extends SimpleEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimplePostEncoding($query = false) { function __construct($query = false) {
if (is_array($query) and $this->hasMoreThanOneLevel($query)) { if (is_array($query) and $this->hasMoreThanOneLevel($query)) {
$query = $this->rewriteArrayWithMultipleLevels($query); $query = $this->rewriteArrayWithMultipleLevels($query);
} }
$this->SimpleEncoding($query); parent::__construct($query);
} }
function hasMoreThanOneLevel($query) { function hasMoreThanOneLevel($query) {
foreach ($query as $key => $value) { foreach ($query as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
@ -449,11 +449,11 @@ class SimplePostEncoding extends SimpleEncoding {
if ($this->hasMoreThanOneLevel($query_)) { if ($this->hasMoreThanOneLevel($query_)) {
$query_ = $this->rewriteArrayWithMultipleLevels($query_); $query_ = $this->rewriteArrayWithMultipleLevels($query_);
} }
return $query_; return $query_;
} }
/** /**
* HTTP request method. * HTTP request method.
* @return string Always POST. * @return string Always POST.
@ -462,7 +462,7 @@ class SimplePostEncoding extends SimpleEncoding {
function getMethod() { function getMethod() {
return 'POST'; return 'POST';
} }
/** /**
* Dispatches the form headers down the socket. * Dispatches the form headers down the socket.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
@ -472,7 +472,7 @@ class SimplePostEncoding extends SimpleEncoding {
$socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n");
$socket->write("Content-Type: application/x-www-form-urlencoded\r\n"); $socket->write("Content-Type: application/x-www-form-urlencoded\r\n");
} }
/** /**
* Dispatches the form data down the socket. * Dispatches the form data down the socket.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
@ -481,7 +481,7 @@ class SimplePostEncoding extends SimpleEncoding {
function writeTo(&$socket) { function writeTo(&$socket) {
$socket->write($this->_encode()); $socket->write($this->_encode());
} }
/** /**
* Renders the query string as a URL encoded * Renders the query string as a URL encoded
* request part for attaching to a URL. * request part for attaching to a URL.
@ -501,7 +501,7 @@ class SimplePostEncoding extends SimpleEncoding {
*/ */
class SimpleMultipartEncoding extends SimplePostEncoding { class SimpleMultipartEncoding extends SimplePostEncoding {
var $_boundary; var $_boundary;
/** /**
* Starts empty. * Starts empty.
* @param array $query Hash of parameters. * @param array $query Hash of parameters.
@ -509,11 +509,11 @@ class SimpleMultipartEncoding extends SimplePostEncoding {
* as lists on a single key. * as lists on a single key.
* @access public * @access public
*/ */
function SimpleMultipartEncoding($query = false, $boundary = false) { function __construct($query = false, $boundary = false) {
$this->SimplePostEncoding($query); parent::__construct($query);
$this->_boundary = ($boundary === false ? uniqid('st') : $boundary); $this->_boundary = ($boundary === false ? uniqid('st') : $boundary);
} }
/** /**
* Dispatches the form headers down the socket. * Dispatches the form headers down the socket.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
@ -523,7 +523,7 @@ class SimpleMultipartEncoding extends SimplePostEncoding {
$socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n"); $socket->write("Content-Length: " . (integer)strlen($this->_encode()) . "\r\n");
$socket->write("Content-Type: multipart/form-data, boundary=" . $this->_boundary . "\r\n"); $socket->write("Content-Type: multipart/form-data, boundary=" . $this->_boundary . "\r\n");
} }
/** /**
* Dispatches the form data down the socket. * Dispatches the form data down the socket.
* @param SimpleSocket $socket Socket to write to. * @param SimpleSocket $socket Socket to write to.
@ -532,7 +532,7 @@ class SimpleMultipartEncoding extends SimplePostEncoding {
function writeTo(&$socket) { function writeTo(&$socket) {
$socket->write($this->_encode()); $socket->write($this->_encode());
} }
/** /**
* Renders the query string as a URL encoded * Renders the query string as a URL encoded
* request part. * request part.

View File

@ -5,7 +5,7 @@
* @subpackage WebTester * @subpackage WebTester
* @version $Id: form.php 1672 2008-03-02 04:47:34Z edwardzyang $ * @version $Id: form.php 1672 2008-03-02 04:47:34Z edwardzyang $
*/ */
/**#@+ /**#@+
* include SimpleTest files * include SimpleTest files
*/ */
@ -30,13 +30,13 @@ class SimpleForm {
var $_widgets; var $_widgets;
var $_radios; var $_radios;
var $_checkboxes; var $_checkboxes;
/** /**
* Starts with no held controls/widgets. * Starts with no held controls/widgets.
* @param SimpleTag $tag Form tag to read. * @param SimpleTag $tag Form tag to read.
* @param SimplePage $page Holding page. * @param SimplePage $page Holding page.
*/ */
function SimpleForm($tag, &$page) { function __construct($tag, &$page) {
$this->_method = $tag->getAttribute('method'); $this->_method = $tag->getAttribute('method');
$this->_action = $this->_createAction($tag->getAttribute('action'), $page); $this->_action = $this->_createAction($tag->getAttribute('action'), $page);
$this->_encoding = $this->_setEncodingClass($tag); $this->_encoding = $this->_setEncodingClass($tag);
@ -48,7 +48,7 @@ class SimpleForm {
$this->_radios = array(); $this->_radios = array();
$this->_checkboxes = array(); $this->_checkboxes = array();
} }
/** /**
* Creates the request packet to be sent by the form. * Creates the request packet to be sent by the form.
* @param SimpleTag $tag Form tag to read. * @param SimpleTag $tag Form tag to read.
@ -64,7 +64,7 @@ class SimpleForm {
} }
return 'SimpleGetEncoding'; return 'SimpleGetEncoding';
} }
/** /**
* Sets the frame target within a frameset. * Sets the frame target within a frameset.
* @param string $frame Name of frame. * @param string $frame Name of frame.
@ -73,7 +73,7 @@ class SimpleForm {
function setDefaultTarget($frame) { function setDefaultTarget($frame) {
$this->_default_target = $frame; $this->_default_target = $frame;
} }
/** /**
* Accessor for method of form submission. * Accessor for method of form submission.
* @return string Either get or post. * @return string Either get or post.
@ -82,7 +82,7 @@ class SimpleForm {
function getMethod() { function getMethod() {
return ($this->_method ? strtolower($this->_method) : 'get'); return ($this->_method ? strtolower($this->_method) : 'get');
} }
/** /**
* Combined action attribute with current location * Combined action attribute with current location
* to get an absolute form target. * to get an absolute form target.
@ -96,7 +96,7 @@ class SimpleForm {
} }
return $page->expandUrl(new SimpleUrl($action));; return $page->expandUrl(new SimpleUrl($action));;
} }
/** /**
* Absolute URL of the target. * Absolute URL of the target.
* @return SimpleUrl URL target. * @return SimpleUrl URL target.
@ -109,7 +109,7 @@ class SimpleForm {
} }
return $url; return $url;
} }
/** /**
* Creates the encoding for the current values in the * Creates the encoding for the current values in the
* form. * form.
@ -124,7 +124,7 @@ class SimpleForm {
} }
return $encoding; return $encoding;
} }
/** /**
* ID field of form for unique identification. * ID field of form for unique identification.
* @return string Unique tag ID. * @return string Unique tag ID.
@ -133,7 +133,7 @@ class SimpleForm {
function getId() { function getId() {
return $this->_id; return $this->_id;
} }
/** /**
* Adds a tag contents to the form. * Adds a tag contents to the form.
* @param SimpleWidget $tag Input tag to add. * @param SimpleWidget $tag Input tag to add.
@ -148,7 +148,7 @@ class SimpleForm {
$this->_setWidget($tag); $this->_setWidget($tag);
} }
} }
/** /**
* Sets the widget into the form, grouping radio * Sets the widget into the form, grouping radio
* buttons if any. * buttons if any.
@ -164,7 +164,7 @@ class SimpleForm {
$this->_widgets[] = &$tag; $this->_widgets[] = &$tag;
} }
} }
/** /**
* Adds a radio button, building a group if necessary. * Adds a radio button, building a group if necessary.
* @param SimpleRadioButtonTag $tag Incoming form control. * @param SimpleRadioButtonTag $tag Incoming form control.
@ -177,7 +177,7 @@ class SimpleForm {
} }
$this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag); $this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag);
} }
/** /**
* Adds a checkbox, making it a group on a repeated name. * Adds a checkbox, making it a group on a repeated name.
* @param SimpleCheckboxTag $tag Incoming form control. * @param SimpleCheckboxTag $tag Incoming form control.
@ -197,7 +197,7 @@ class SimpleForm {
$this->_widgets[$index]->addWidget($tag); $this->_widgets[$index]->addWidget($tag);
} }
} }
/** /**
* Extracts current value from form. * Extracts current value from form.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -218,7 +218,7 @@ class SimpleForm {
} }
return null; return null;
} }
/** /**
* Sets a widget value within the form. * Sets a widget value within the form.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -243,7 +243,7 @@ class SimpleForm {
} }
return $success; return $success;
} }
/** /**
* Used by the page object to set widgets labels to * Used by the page object to set widgets labels to
* external label tags. * external label tags.
@ -260,7 +260,7 @@ class SimpleForm {
} }
} }
} }
/** /**
* Test to see if a form has a submit button. * Test to see if a form has a submit button.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -275,7 +275,7 @@ class SimpleForm {
} }
return false; return false;
} }
/** /**
* Test to see if a form has an image control. * Test to see if a form has an image control.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -290,7 +290,7 @@ class SimpleForm {
} }
return false; return false;
} }
/** /**
* Gets the submit values for a selected button. * Gets the submit values for a selected button.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -309,12 +309,12 @@ class SimpleForm {
if ($additional) { if ($additional) {
$encoding->merge($additional); $encoding->merge($additional);
} }
return $encoding; return $encoding;
} }
} }
return false; return false;
} }
/** /**
* Gets the submit values for an image. * Gets the submit values for an image.
* @param SimpleSelector $selector Criteria to apply. * @param SimpleSelector $selector Criteria to apply.
@ -335,12 +335,12 @@ class SimpleForm {
if ($additional) { if ($additional) {
$encoding->merge($additional); $encoding->merge($additional);
} }
return $encoding; return $encoding;
} }
} }
return false; return false;
} }
/** /**
* Simply submits the form without the submit button * Simply submits the form without the submit button
* value. Used when there is only one button or it * value. Used when there is only one button or it

View File

@ -22,16 +22,16 @@ require_once(dirname(__FILE__) . '/url.php');
*/ */
class SimpleRoute { class SimpleRoute {
var $_url; var $_url;
/** /**
* Sets the target URL. * Sets the target URL.
* @param SimpleUrl $url URL as object. * @param SimpleUrl $url URL as object.
* @access public * @access public
*/ */
function SimpleRoute($url) { function __construct($url) {
$this->_url = $url; $this->_url = $url;
} }
/** /**
* Resource name. * Resource name.
* @return SimpleUrl Current url. * @return SimpleUrl Current url.
@ -40,7 +40,7 @@ class SimpleRoute {
function getUrl() { function getUrl() {
return $this->_url; return $this->_url;
} }
/** /**
* Creates the first line which is the actual request. * Creates the first line which is the actual request.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
@ -51,7 +51,7 @@ class SimpleRoute {
return $method . ' ' . $this->_url->getPath() . return $method . ' ' . $this->_url->getPath() .
$this->_url->getEncodedRequest() . ' HTTP/1.0'; $this->_url->getEncodedRequest() . ' HTTP/1.0';
} }
/** /**
* Creates the host part of the request. * Creates the host part of the request.
* @return string Host line content. * @return string Host line content.
@ -64,7 +64,7 @@ class SimpleRoute {
} }
return $line; return $line;
} }
/** /**
* Opens a socket to the route. * Opens a socket to the route.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
@ -86,7 +86,7 @@ class SimpleRoute {
} }
return $socket; return $socket;
} }
/** /**
* Factory for socket. * Factory for socket.
* @param string $scheme Protocol to use. * @param string $scheme Protocol to use.
@ -116,7 +116,7 @@ class SimpleProxyRoute extends SimpleRoute {
var $_proxy; var $_proxy;
var $_username; var $_username;
var $_password; var $_password;
/** /**
* Stashes the proxy address. * Stashes the proxy address.
* @param SimpleUrl $url URL as object. * @param SimpleUrl $url URL as object.
@ -125,13 +125,13 @@ class SimpleProxyRoute extends SimpleRoute {
* @param string $password Password for autentication. * @param string $password Password for autentication.
* @access public * @access public
*/ */
function SimpleProxyRoute($url, $proxy, $username = false, $password = false) { function __construct($url, $proxy, $username = false, $password = false) {
$this->SimpleRoute($url); parent::__construct($url);
$this->_proxy = $proxy; $this->_proxy = $proxy;
$this->_username = $username; $this->_username = $username;
$this->_password = $password; $this->_password = $password;
} }
/** /**
* Creates the first line which is the actual request. * Creates the first line which is the actual request.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
@ -146,7 +146,7 @@ class SimpleProxyRoute extends SimpleRoute {
return $method . ' ' . $scheme . '://' . $url->getHost() . $port . return $method . ' ' . $scheme . '://' . $url->getHost() . $port .
$url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0'; $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0';
} }
/** /**
* Creates the host part of the request. * Creates the host part of the request.
* @param SimpleUrl $url URL as object. * @param SimpleUrl $url URL as object.
@ -158,7 +158,7 @@ class SimpleProxyRoute extends SimpleRoute {
$port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080; $port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080;
return "$host:$port"; return "$host:$port";
} }
/** /**
* Opens a socket to the route. * Opens a socket to the route.
* @param string $method HTTP request method, usually GET. * @param string $method HTTP request method, usually GET.
@ -198,7 +198,7 @@ class SimpleHttpRequest {
var $_encoding; var $_encoding;
var $_headers; var $_headers;
var $_cookies; var $_cookies;
/** /**
* Builds the socket request from the different pieces. * Builds the socket request from the different pieces.
* These include proxy information, URL, cookies, headers, * These include proxy information, URL, cookies, headers,
@ -208,13 +208,13 @@ class SimpleHttpRequest {
* request. * request.
* @access public * @access public
*/ */
function SimpleHttpRequest(&$route, $encoding) { function __construct(&$route, $encoding) {
$this->_route = &$route; $this->_route = &$route;
$this->_encoding = $encoding; $this->_encoding = $encoding;
$this->_headers = array(); $this->_headers = array();
$this->_cookies = array(); $this->_cookies = array();
} }
/** /**
* Dispatches the content to the route's socket. * Dispatches the content to the route's socket.
* @param integer $timeout Connection timeout. * @param integer $timeout Connection timeout.
@ -231,7 +231,7 @@ class SimpleHttpRequest {
$response = &$this->_createResponse($socket); $response = &$this->_createResponse($socket);
return $response; return $response;
} }
/** /**
* Sends the headers. * Sends the headers.
* @param SimpleSocket $socket Open socket. * @param SimpleSocket $socket Open socket.
@ -251,7 +251,7 @@ class SimpleHttpRequest {
$socket->write("\r\n"); $socket->write("\r\n");
$encoding->writeTo($socket); $encoding->writeTo($socket);
} }
/** /**
* Adds a header line to the request. * Adds a header line to the request.
* @param string $header_line Text of full header line. * @param string $header_line Text of full header line.
@ -260,7 +260,7 @@ class SimpleHttpRequest {
function addHeaderLine($header_line) { function addHeaderLine($header_line) {
$this->_headers[] = $header_line; $this->_headers[] = $header_line;
} }
/** /**
* Reads all the relevant cookies from the * Reads all the relevant cookies from the
* cookie jar. * cookie jar.
@ -271,7 +271,7 @@ class SimpleHttpRequest {
function readCookiesFromJar($jar, $url) { function readCookiesFromJar($jar, $url) {
$this->_cookies = $jar->selectAsPairs($url); $this->_cookies = $jar->selectAsPairs($url);
} }
/** /**
* Wraps the socket in a response parser. * Wraps the socket in a response parser.
* @param SimpleSocket $socket Responding socket. * @param SimpleSocket $socket Responding socket.
@ -301,13 +301,13 @@ class SimpleHttpHeaders {
var $_cookies; var $_cookies;
var $_authentication; var $_authentication;
var $_realm; var $_realm;
/** /**
* Parses the incoming header block. * Parses the incoming header block.
* @param string $headers Header block. * @param string $headers Header block.
* @access public * @access public
*/ */
function SimpleHttpHeaders($headers) { function __construct($headers) {
$this->_raw_headers = $headers; $this->_raw_headers = $headers;
$this->_response_code = false; $this->_response_code = false;
$this->_http_version = false; $this->_http_version = false;
@ -320,7 +320,7 @@ class SimpleHttpHeaders {
$this->_parseHeaderLine($header_line); $this->_parseHeaderLine($header_line);
} }
} }
/** /**
* Accessor for parsed HTTP protocol version. * Accessor for parsed HTTP protocol version.
* @return integer HTTP error code. * @return integer HTTP error code.
@ -329,7 +329,7 @@ class SimpleHttpHeaders {
function getHttpVersion() { function getHttpVersion() {
return $this->_http_version; return $this->_http_version;
} }
/** /**
* Accessor for raw header block. * Accessor for raw header block.
* @return string All headers as raw string. * @return string All headers as raw string.
@ -338,7 +338,7 @@ class SimpleHttpHeaders {
function getRaw() { function getRaw() {
return $this->_raw_headers; return $this->_raw_headers;
} }
/** /**
* Accessor for parsed HTTP error code. * Accessor for parsed HTTP error code.
* @return integer HTTP error code. * @return integer HTTP error code.
@ -347,7 +347,7 @@ class SimpleHttpHeaders {
function getResponseCode() { function getResponseCode() {
return (integer)$this->_response_code; return (integer)$this->_response_code;
} }
/** /**
* Returns the redirected URL or false if * Returns the redirected URL or false if
* no redirection. * no redirection.
@ -357,7 +357,7 @@ class SimpleHttpHeaders {
function getLocation() { function getLocation() {
return $this->_location; return $this->_location;
} }
/** /**
* Test to see if the response is a valid redirect. * Test to see if the response is a valid redirect.
* @return boolean True if valid redirect. * @return boolean True if valid redirect.
@ -367,7 +367,7 @@ class SimpleHttpHeaders {
return in_array($this->_response_code, array(301, 302, 303, 307)) && return in_array($this->_response_code, array(301, 302, 303, 307)) &&
(boolean)$this->getLocation(); (boolean)$this->getLocation();
} }
/** /**
* Test to see if the response is an authentication * Test to see if the response is an authentication
* challenge. * challenge.
@ -379,7 +379,7 @@ class SimpleHttpHeaders {
(boolean)$this->_authentication && (boolean)$this->_authentication &&
(boolean)$this->_realm; (boolean)$this->_realm;
} }
/** /**
* Accessor for MIME type header information. * Accessor for MIME type header information.
* @return string MIME type. * @return string MIME type.
@ -388,7 +388,7 @@ class SimpleHttpHeaders {
function getMimeType() { function getMimeType() {
return $this->_mime_type; return $this->_mime_type;
} }
/** /**
* Accessor for authentication type. * Accessor for authentication type.
* @return string Type. * @return string Type.
@ -397,7 +397,7 @@ class SimpleHttpHeaders {
function getAuthentication() { function getAuthentication() {
return $this->_authentication; return $this->_authentication;
} }
/** /**
* Accessor for security realm. * Accessor for security realm.
* @return string Realm. * @return string Realm.
@ -406,7 +406,7 @@ class SimpleHttpHeaders {
function getRealm() { function getRealm() {
return $this->_realm; return $this->_realm;
} }
/** /**
* Writes new cookies to the cookie jar. * Writes new cookies to the cookie jar.
* @param SimpleCookieJar $jar Jar to write to. * @param SimpleCookieJar $jar Jar to write to.
@ -449,7 +449,7 @@ class SimpleHttpHeaders {
$this->_realm = trim($matches[2]); $this->_realm = trim($matches[2]);
} }
} }
/** /**
* Parse the Set-cookie content. * Parse the Set-cookie content.
* @param string $cookie_line Text after "Set-cookie:" * @param string $cookie_line Text after "Set-cookie:"
@ -484,7 +484,7 @@ class SimpleHttpResponse extends SimpleStickyError {
var $_sent; var $_sent;
var $_content; var $_content;
var $_headers; var $_headers;
/** /**
* Constructor. Reads and parses the incoming * Constructor. Reads and parses the incoming
* content and headers. * content and headers.
@ -494,8 +494,8 @@ class SimpleHttpResponse extends SimpleStickyError {
* @param mixed $encoding Record of content sent. * @param mixed $encoding Record of content sent.
* @access public * @access public
*/ */
function SimpleHttpResponse(&$socket, $url, $encoding) { function __construct(&$socket, $url, $encoding) {
$this->SimpleStickyError(); parent::__construct();
$this->_url = $url; $this->_url = $url;
$this->_encoding = $encoding; $this->_encoding = $encoding;
$this->_sent = $socket->getSent(); $this->_sent = $socket->getSent();
@ -507,7 +507,7 @@ class SimpleHttpResponse extends SimpleStickyError {
} }
$this->_parse($raw); $this->_parse($raw);
} }
/** /**
* Splits up the headers and the rest of the content. * Splits up the headers and the rest of the content.
* @param string $raw Content to parse. * @param string $raw Content to parse.
@ -525,7 +525,7 @@ class SimpleHttpResponse extends SimpleStickyError {
$this->_headers = new SimpleHttpHeaders($headers); $this->_headers = new SimpleHttpHeaders($headers);
} }
} }
/** /**
* Original request method. * Original request method.
* @return string GET, POST or HEAD. * @return string GET, POST or HEAD.
@ -534,7 +534,7 @@ class SimpleHttpResponse extends SimpleStickyError {
function getMethod() { function getMethod() {
return $this->_encoding->getMethod(); return $this->_encoding->getMethod();
} }
/** /**
* Resource name. * Resource name.
* @return SimpleUrl Current url. * @return SimpleUrl Current url.
@ -543,7 +543,7 @@ class SimpleHttpResponse extends SimpleStickyError {
function getUrl() { function getUrl() {
return $this->_url; return $this->_url;
} }
/** /**
* Original request data. * Original request data.
* @return mixed Sent content. * @return mixed Sent content.
@ -552,7 +552,7 @@ class SimpleHttpResponse extends SimpleStickyError {
function getRequestData() { function getRequestData() {
return $this->_encoding; return $this->_encoding;
} }
/** /**
* Raw request that was sent down the wire. * Raw request that was sent down the wire.
* @return string Bytes actually sent. * @return string Bytes actually sent.
@ -561,7 +561,7 @@ class SimpleHttpResponse extends SimpleStickyError {
function getSent() { function getSent() {
return $this->_sent; return $this->_sent;
} }
/** /**
* Accessor for the content after the last * Accessor for the content after the last
* header line. * header line.
@ -571,7 +571,7 @@ class SimpleHttpResponse extends SimpleStickyError {
function getContent() { function getContent() {
return $this->_content; return $this->_content;
} }
/** /**
* Accessor for header block. The response is the * Accessor for header block. The response is the
* combination of this and the content. * combination of this and the content.
@ -581,7 +581,7 @@ class SimpleHttpResponse extends SimpleStickyError {
function getHeaders() { function getHeaders() {
return $this->_headers; return $this->_headers;
} }
/** /**
* Accessor for any new cookies. * Accessor for any new cookies.
* @return array List of new cookies. * @return array List of new cookies.
@ -590,7 +590,7 @@ class SimpleHttpResponse extends SimpleStickyError {
function getNewCookies() { function getNewCookies() {
return $this->_headers->getNewCookies(); return $this->_headers->getNewCookies();
} }
/** /**
* Reads the whole of the socket output into a * Reads the whole of the socket output into a
* single string. * single string.
@ -606,7 +606,7 @@ class SimpleHttpResponse extends SimpleStickyError {
} }
return $all; return $all;
} }
/** /**
* Test to see if the packet from the socket is the * Test to see if the packet from the socket is the
* last one. * last one.

View File

@ -127,10 +127,10 @@ class SimplePageBuilder extends SimpleSaxListener {
* Sets the builder up empty. * Sets the builder up empty.
* @access public * @access public
*/ */
function SimplePageBuilder() { function __construct() {
$this->SimpleSaxListener(); parent::__construct();
} }
/** /**
* Frees up any references so as to allow the PHP garbage * Frees up any references so as to allow the PHP garbage
* collection from unset() to work. * collection from unset() to work.
@ -179,7 +179,7 @@ class SimplePageBuilder extends SimpleSaxListener {
$parser = new SimpleHtmlSaxParser($listener); $parser = new SimpleHtmlSaxParser($listener);
return $parser; return $parser;
} }
/** /**
* Start of element event. Opens a new tag. * Start of element event. Opens a new tag.
* @param string $name Element name. * @param string $name Element name.
@ -358,7 +358,7 @@ class SimplePage {
* @param SimpleHttpResponse $response Result of HTTP fetch. * @param SimpleHttpResponse $response Result of HTTP fetch.
* @access public * @access public
*/ */
function SimplePage($response = false) { function __construct($response = false) {
$this->_links = array(); $this->_links = array();
$this->_title = false; $this->_title = false;
$this->_left_over_labels = array(); $this->_left_over_labels = array();

View File

@ -30,20 +30,20 @@ class ParallelRegex {
var $_labels; var $_labels;
var $_regex; var $_regex;
var $_case; var $_case;
/** /**
* Constructor. Starts with no patterns. * Constructor. Starts with no patterns.
* @param boolean $case True for case sensitive, false * @param boolean $case True for case sensitive, false
* for insensitive. * for insensitive.
* @access public * @access public
*/ */
function ParallelRegex($case) { function __construct($case) {
$this->_case = $case; $this->_case = $case;
$this->_patterns = array(); $this->_patterns = array();
$this->_labels = array(); $this->_labels = array();
$this->_regex = null; $this->_regex = null;
} }
/** /**
* Adds a pattern with an optional label. * Adds a pattern with an optional label.
* @param string $pattern Perl style regex, but ( and ) * @param string $pattern Perl style regex, but ( and )
@ -58,7 +58,7 @@ class ParallelRegex {
$this->_labels[$count] = $label; $this->_labels[$count] = $label;
$this->_regex = null; $this->_regex = null;
} }
/** /**
* Attempts to match all patterns at once against * Attempts to match all patterns at once against
* a string. * a string.
@ -84,7 +84,7 @@ class ParallelRegex {
} }
return true; return true;
} }
/** /**
* Compounds the patterns into a single * Compounds the patterns into a single
* regular expression separated with the * regular expression separated with the
@ -105,7 +105,7 @@ class ParallelRegex {
} }
return $this->_regex; return $this->_regex;
} }
/** /**
* Accessor for perl regex mode flags to use. * Accessor for perl regex mode flags to use.
* @return string Perl regex flags. * @return string Perl regex flags.
@ -123,16 +123,16 @@ class ParallelRegex {
*/ */
class SimpleStateStack { class SimpleStateStack {
var $_stack; var $_stack;
/** /**
* Constructor. Starts in named state. * Constructor. Starts in named state.
* @param string $start Starting state name. * @param string $start Starting state name.
* @access public * @access public
*/ */
function SimpleStateStack($start) { function __construct($start) {
$this->_stack = array($start); $this->_stack = array($start);
} }
/** /**
* Accessor for current state. * Accessor for current state.
* @return string State. * @return string State.
@ -141,7 +141,7 @@ class SimpleStateStack {
function getCurrent() { function getCurrent() {
return $this->_stack[count($this->_stack) - 1]; return $this->_stack[count($this->_stack) - 1];
} }
/** /**
* Adds a state to the stack and sets it * Adds a state to the stack and sets it
* to be the current state. * to be the current state.
@ -151,7 +151,7 @@ class SimpleStateStack {
function enter($state) { function enter($state) {
array_push($this->_stack, $state); array_push($this->_stack, $state);
} }
/** /**
* Leaves the current state and reverts * Leaves the current state and reverts
* to the previous one. * to the previous one.
@ -183,7 +183,7 @@ class SimpleLexer {
var $_mode; var $_mode;
var $_mode_handlers; var $_mode_handlers;
var $_case; var $_case;
/** /**
* Sets up the lexer in case insensitive matching * Sets up the lexer in case insensitive matching
* by default. * by default.
@ -193,14 +193,14 @@ class SimpleLexer {
* @param boolean $case True for case sensitive. * @param boolean $case True for case sensitive.
* @access public * @access public
*/ */
function SimpleLexer(&$parser, $start = "accept", $case = false) { function __construct(&$parser, $start = "accept", $case = false) {
$this->_case = $case; $this->_case = $case;
$this->_regexes = array(); $this->_regexes = array();
$this->_parser = &$parser; $this->_parser = &$parser;
$this->_mode = new SimpleStateStack($start); $this->_mode = new SimpleStateStack($start);
$this->_mode_handlers = array($start => $start); $this->_mode_handlers = array($start => $start);
} }
/** /**
* Adds a token search pattern for a particular * Adds a token search pattern for a particular
* parsing mode. The pattern does not change the * parsing mode. The pattern does not change the
@ -221,7 +221,7 @@ class SimpleLexer {
$this->_mode_handlers[$mode] = $mode; $this->_mode_handlers[$mode] = $mode;
} }
} }
/** /**
* Adds a pattern that will enter a new parsing * Adds a pattern that will enter a new parsing
* mode. Useful for entering parenthesis, strings, * mode. Useful for entering parenthesis, strings,
@ -244,7 +244,7 @@ class SimpleLexer {
$this->_mode_handlers[$new_mode] = $new_mode; $this->_mode_handlers[$new_mode] = $new_mode;
} }
} }
/** /**
* Adds a pattern that will exit the current mode * Adds a pattern that will exit the current mode
* and re-enter the previous one. * and re-enter the previous one.
@ -262,7 +262,7 @@ class SimpleLexer {
$this->_mode_handlers[$mode] = $mode; $this->_mode_handlers[$mode] = $mode;
} }
} }
/** /**
* Adds a pattern that has a special mode. Acts as an entry * Adds a pattern that has a special mode. Acts as an entry
* and exit pattern in one go, effectively calling a special * and exit pattern in one go, effectively calling a special
@ -284,7 +284,7 @@ class SimpleLexer {
$this->_mode_handlers[$special] = $special; $this->_mode_handlers[$special] = $special;
} }
} }
/** /**
* Adds a mapping from a mode to another handler. * Adds a mapping from a mode to another handler.
* @param string $mode Mode to be remapped. * @param string $mode Mode to be remapped.
@ -294,7 +294,7 @@ class SimpleLexer {
function mapHandler($mode, $handler) { function mapHandler($mode, $handler) {
$this->_mode_handlers[$mode] = $handler; $this->_mode_handlers[$mode] = $handler;
} }
/** /**
* Splits the page text into tokens. Will fail * Splits the page text into tokens. Will fail
* if the handlers report an error or if no * if the handlers report an error or if no
@ -328,7 +328,7 @@ class SimpleLexer {
} }
return $this->_invokeParser($raw, LEXER_UNMATCHED); return $this->_invokeParser($raw, LEXER_UNMATCHED);
} }
/** /**
* Sends the matched token and any leading unmatched * Sends the matched token and any leading unmatched
* text to the parser changing the lexer to a new * text to the parser changing the lexer to a new
@ -364,7 +364,7 @@ class SimpleLexer {
$this->_mode->enter($mode); $this->_mode->enter($mode);
return $this->_invokeParser($matched, LEXER_ENTER); return $this->_invokeParser($matched, LEXER_ENTER);
} }
/** /**
* Tests to see if the new mode is actually to leave * Tests to see if the new mode is actually to leave
* the current mode and pop an item from the matching * the current mode and pop an item from the matching
@ -376,7 +376,7 @@ class SimpleLexer {
function _isModeEnd($mode) { function _isModeEnd($mode) {
return ($mode === "__exit"); return ($mode === "__exit");
} }
/** /**
* Test to see if the mode is one where this mode * Test to see if the mode is one where this mode
* is entered for this token only and automatically * is entered for this token only and automatically
@ -388,7 +388,7 @@ class SimpleLexer {
function _isSpecialMode($mode) { function _isSpecialMode($mode) {
return (strncmp($mode, "_", 1) == 0); return (strncmp($mode, "_", 1) == 0);
} }
/** /**
* Strips the magic underscore marking single token * Strips the magic underscore marking single token
* modes. * modes.
@ -399,7 +399,7 @@ class SimpleLexer {
function _decodeSpecial($mode) { function _decodeSpecial($mode) {
return substr($mode, 1); return substr($mode, 1);
} }
/** /**
* Calls the parser method named after the current * Calls the parser method named after the current
* mode. Empty content will be ignored. The lexer * mode. Empty content will be ignored. The lexer
@ -416,7 +416,7 @@ class SimpleLexer {
$handler = $this->_mode_handlers[$this->_mode->getCurrent()]; $handler = $this->_mode_handlers[$this->_mode->getCurrent()];
return $this->_parser->$handler($content, $is_match); return $this->_parser->$handler($content, $is_match);
} }
/** /**
* Tries to match a chunk of text and if successful * Tries to match a chunk of text and if successful
* removes the recognised chunk and any leading * removes the recognised chunk and any leading
@ -448,7 +448,7 @@ class SimpleLexer {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleHtmlLexer extends SimpleLexer { class SimpleHtmlLexer extends SimpleLexer {
/** /**
* Sets up the lexer with case insensitive matching * Sets up the lexer with case insensitive matching
* and adds the HTML handlers. * and adds the HTML handlers.
@ -456,8 +456,8 @@ class SimpleHtmlLexer extends SimpleLexer {
* reference. * reference.
* @access public * @access public
*/ */
function SimpleHtmlLexer(&$parser) { function __construct(&$parser) {
$this->SimpleLexer($parser, 'text'); parent::__construct($parser, 'text');
$this->mapHandler('text', 'acceptTextToken'); $this->mapHandler('text', 'acceptTextToken');
$this->_addSkipping(); $this->_addSkipping();
foreach ($this->_getParsedTags() as $tag) { foreach ($this->_getParsedTags() as $tag) {
@ -465,7 +465,7 @@ class SimpleHtmlLexer extends SimpleLexer {
} }
$this->_addInTagTokens(); $this->_addInTagTokens();
} }
/** /**
* List of parsed tags. Others are ignored. * List of parsed tags. Others are ignored.
* @return array List of searched for tags. * @return array List of searched for tags.
@ -475,7 +475,7 @@ class SimpleHtmlLexer extends SimpleLexer {
return array('a', 'base', 'title', 'form', 'input', 'button', 'textarea', 'select', return array('a', 'base', 'title', 'form', 'input', 'button', 'textarea', 'select',
'option', 'frameset', 'frame', 'label'); 'option', 'frameset', 'frame', 'label');
} }
/** /**
* The lexer has to skip certain sections such * The lexer has to skip certain sections such
* as server code, client code and styles. * as server code, client code and styles.
@ -492,7 +492,7 @@ class SimpleHtmlLexer extends SimpleLexer {
$this->addEntryPattern('<!--', 'text', 'comment'); $this->addEntryPattern('<!--', 'text', 'comment');
$this->addExitPattern('-->', 'comment'); $this->addExitPattern('-->', 'comment');
} }
/** /**
* Pattern matches to start and end a tag. * Pattern matches to start and end a tag.
* @param string $tag Name of tag to scan for. * @param string $tag Name of tag to scan for.
@ -502,7 +502,7 @@ class SimpleHtmlLexer extends SimpleLexer {
$this->addSpecialPattern("</$tag>", 'text', 'acceptEndToken'); $this->addSpecialPattern("</$tag>", 'text', 'acceptEndToken');
$this->addEntryPattern("<$tag", 'text', 'tag'); $this->addEntryPattern("<$tag", 'text', 'tag');
} }
/** /**
* Pattern matches to parse the inside of a tag * Pattern matches to parse the inside of a tag
* including the attributes and their quoting. * including the attributes and their quoting.
@ -515,7 +515,7 @@ class SimpleHtmlLexer extends SimpleLexer {
$this->addExitPattern('/>', 'tag'); $this->addExitPattern('/>', 'tag');
$this->addExitPattern('>', 'tag'); $this->addExitPattern('>', 'tag');
} }
/** /**
* Matches attributes that are either single quoted, * Matches attributes that are either single quoted,
* double quoted or unquoted. * double quoted or unquoted.
@ -546,20 +546,20 @@ class SimpleHtmlSaxParser {
var $_tag; var $_tag;
var $_attributes; var $_attributes;
var $_current_attribute; var $_current_attribute;
/** /**
* Sets the listener. * Sets the listener.
* @param SimpleSaxListener $listener SAX event handler. * @param SimpleSaxListener $listener SAX event handler.
* @access public * @access public
*/ */
function SimpleHtmlSaxParser(&$listener) { function __construct(&$listener) {
$this->_listener = &$listener; $this->_listener = &$listener;
$this->_lexer = &$this->createLexer($this); $this->_lexer = &$this->createLexer($this);
$this->_tag = ''; $this->_tag = '';
$this->_attributes = array(); $this->_attributes = array();
$this->_current_attribute = ''; $this->_current_attribute = '';
} }
/** /**
* Runs the content through the lexer which * Runs the content through the lexer which
* should call back to the acceptors. * should call back to the acceptors.
@ -570,7 +570,7 @@ class SimpleHtmlSaxParser {
function parse($raw) { function parse($raw) {
return $this->_lexer->parse($raw); return $this->_lexer->parse($raw);
} }
/** /**
* Sets up the matching lexer. Starts in 'text' mode. * Sets up the matching lexer. Starts in 'text' mode.
* @param SimpleSaxParser $parser Event generator, usually $self. * @param SimpleSaxParser $parser Event generator, usually $self.
@ -582,7 +582,7 @@ class SimpleHtmlSaxParser {
$lexer = new SimpleHtmlLexer($parser); $lexer = new SimpleHtmlLexer($parser);
return $lexer; return $lexer;
} }
/** /**
* Accepts a token from the tag mode. If the * Accepts a token from the tag mode. If the
* starting element completes then the element * starting element completes then the element
@ -613,7 +613,7 @@ class SimpleHtmlSaxParser {
} }
return true; return true;
} }
/** /**
* Accepts a token from the end tag mode. * Accepts a token from the end tag mode.
* The element name is converted to lower case. * The element name is converted to lower case.
@ -628,7 +628,7 @@ class SimpleHtmlSaxParser {
} }
return $this->_listener->endElement(strtolower($matches[1])); return $this->_listener->endElement(strtolower($matches[1]));
} }
/** /**
* Part of the tag data. * Part of the tag data.
* @param string $token Incoming characters. * @param string $token Incoming characters.
@ -649,7 +649,7 @@ class SimpleHtmlSaxParser {
} }
return true; return true;
} }
/** /**
* A character entity. * A character entity.
* @param string $token Incoming characters. * @param string $token Incoming characters.
@ -659,7 +659,7 @@ class SimpleHtmlSaxParser {
*/ */
function acceptEntityToken($token, $event) { function acceptEntityToken($token, $event) {
} }
/** /**
* Character data between tags regarded as * Character data between tags regarded as
* important. * important.
@ -671,7 +671,7 @@ class SimpleHtmlSaxParser {
function acceptTextToken($token, $event) { function acceptTextToken($token, $event) {
return $this->_listener->addContent($token); return $this->_listener->addContent($token);
} }
/** /**
* Incoming data to be ignored. * Incoming data to be ignored.
* @param string $token Incoming characters. * @param string $token Incoming characters.
@ -682,7 +682,7 @@ class SimpleHtmlSaxParser {
function ignore($token, $event) { function ignore($token, $event) {
return true; return true;
} }
/** /**
* Decodes any HTML entities. * Decodes any HTML entities.
* @param string $html Incoming HTML. * @param string $html Incoming HTML.
@ -693,7 +693,7 @@ class SimpleHtmlSaxParser {
static function decodeHtml($html) { static function decodeHtml($html) {
return html_entity_decode($html, ENT_QUOTES); return html_entity_decode($html, ENT_QUOTES);
} }
/** /**
* Turns HTML into text browser visible text. Images * Turns HTML into text browser visible text. Images
* are converted to their alt text and tags are supressed. * are converted to their alt text and tags are supressed.
@ -723,14 +723,14 @@ class SimpleHtmlSaxParser {
* @abstract * @abstract
*/ */
class SimpleSaxListener { class SimpleSaxListener {
/** /**
* Sets the document to write to. * Sets the document to write to.
* @access public * @access public
*/ */
function SimpleSaxListener() { function __construct() {
} }
/** /**
* Start of element event. * Start of element event.
* @param string $name Element name. * @param string $name Element name.
@ -742,7 +742,7 @@ class SimpleSaxListener {
*/ */
function startElement($name, $attributes) { function startElement($name, $attributes) {
} }
/** /**
* End of element event. * End of element event.
* @param string $name Element name. * @param string $name Element name.
@ -751,7 +751,7 @@ class SimpleSaxListener {
*/ */
function endElement($name) { function endElement($name) {
} }
/** /**
* Unparsed, but relevant data. * Unparsed, but relevant data.
* @param string $text May include unparsed tags. * @param string $text May include unparsed tags.

View File

@ -26,7 +26,7 @@ class SimpleByName {
* Stashes the name for later comparison. * Stashes the name for later comparison.
* @param string $name Name attribute to match. * @param string $name Name attribute to match.
*/ */
function SimpleByName($name) { function __construct($name) {
$this->_name = $name; $this->_name = $name;
} }
@ -57,7 +57,7 @@ class SimpleByLabel {
* Stashes the name for later comparison. * Stashes the name for later comparison.
* @param string $label Visible text to match. * @param string $label Visible text to match.
*/ */
function SimpleByLabel($label) { function __construct($label) {
$this->_label = $label; $this->_label = $label;
} }
@ -88,7 +88,7 @@ class SimpleById {
* Stashes the name for later comparison. * Stashes the name for later comparison.
* @param string $id ID atribute to match. * @param string $id ID atribute to match.
*/ */
function SimpleById($id) { function __construct($id) {
$this->_id = $id; $this->_id = $id;
} }
@ -115,7 +115,7 @@ class SimpleByLabelOrName {
* Stashes the name/label for later comparison. * Stashes the name/label for later comparison.
* @param string $label Visible text to match. * @param string $label Visible text to match.
*/ */
function SimpleByLabelOrName($label) { function __construct($label) {
$this->_label = $label; $this->_label = $label;
} }

View File

@ -25,7 +25,7 @@ class SimpleStickyError {
* Sets the error to empty. * Sets the error to empty.
* @access public * @access public
*/ */
function SimpleStickyError() { function __construct() {
$this->_clearError(); $this->_clearError();
} }
@ -85,8 +85,8 @@ class SimpleSocket extends SimpleStickyError {
* @param integer $block_size Size of chunk to read. * @param integer $block_size Size of chunk to read.
* @access public * @access public
*/ */
function SimpleSocket($host, $port, $timeout, $block_size = 255) { function __construct($host, $port, $timeout, $block_size = 255) {
$this->SimpleStickyError(); parent::__construct();
if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) { if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) {
$this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds"); $this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds");
return; return;
@ -196,8 +196,8 @@ class SimpleSecureSocket extends SimpleSocket {
* @param integer $timeout Connection timeout in seconds. * @param integer $timeout Connection timeout in seconds.
* @access public * @access public
*/ */
function SimpleSecureSocket($host, $port, $timeout) { function __construct($host, $port, $timeout) {
$this->SimpleSocket($host, $port, $timeout); parent::__construct($host, $port, $timeout);
} }
/** /**

View File

@ -5,7 +5,7 @@
* @subpackage WebTester * @subpackage WebTester
* @version $Id: tag.php 1723 2008-04-08 00:34:10Z lastcraft $ * @version $Id: tag.php 1723 2008-04-08 00:34:10Z lastcraft $
*/ */
/**#@+ /**#@+
* include SimpleTest files * include SimpleTest files
*/ */
@ -22,7 +22,7 @@ class SimpleTag {
var $_name; var $_name;
var $_attributes; var $_attributes;
var $_content; var $_content;
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param string $name Tag name. * @param string $name Tag name.
@ -31,12 +31,12 @@ class SimpleTag {
* the keys must have been * the keys must have been
* converted to lower case. * converted to lower case.
*/ */
function SimpleTag($name, $attributes) { function __construct($name, $attributes) {
$this->_name = strtolower(trim($name)); $this->_name = strtolower(trim($name));
$this->_attributes = $attributes; $this->_attributes = $attributes;
$this->_content = ''; $this->_content = '';
} }
/** /**
* Check to see if the tag can have both start and * Check to see if the tag can have both start and
* end tags with content in between. * end tags with content in between.
@ -46,7 +46,7 @@ class SimpleTag {
function expectEndTag() { function expectEndTag() {
return true; return true;
} }
/** /**
* The current tag should not swallow all content for * The current tag should not swallow all content for
* itself as it's searchable page content. Private * itself as it's searchable page content. Private
@ -68,7 +68,7 @@ class SimpleTag {
function addContent($content) { function addContent($content) {
$this->_content .= (string)$content; $this->_content .= (string)$content;
} }
/** /**
* Adds an enclosed tag to the content. * Adds an enclosed tag to the content.
* @param SimpleTag $tag New tag. * @param SimpleTag $tag New tag.
@ -76,7 +76,7 @@ class SimpleTag {
*/ */
function addTag(&$tag) { function addTag(&$tag) {
} }
/** /**
* Accessor for tag name. * Accessor for tag name.
* @return string Name of tag. * @return string Name of tag.
@ -85,7 +85,7 @@ class SimpleTag {
function getTagName() { function getTagName() {
return $this->_name; return $this->_name;
} }
/** /**
* List of legal child elements. * List of legal child elements.
* @return array List of element names. * @return array List of element names.
@ -94,7 +94,7 @@ class SimpleTag {
function getChildElements() { function getChildElements() {
return array(); return array();
} }
/** /**
* Accessor for an attribute. * Accessor for an attribute.
* @param string $label Attribute name. * @param string $label Attribute name.
@ -108,7 +108,7 @@ class SimpleTag {
} }
return (string)$this->_attributes[$label]; return (string)$this->_attributes[$label];
} }
/** /**
* Sets an attribute. * Sets an attribute.
* @param string $label Attribute name. * @param string $label Attribute name.
@ -118,7 +118,7 @@ class SimpleTag {
function _setAttribute($label, $value) { function _setAttribute($label, $value) {
$this->_attributes[strtolower($label)] = $value; $this->_attributes[strtolower($label)] = $value;
} }
/** /**
* Accessor for the whole content so far. * Accessor for the whole content so far.
* @return string Content as big raw string. * @return string Content as big raw string.
@ -127,7 +127,7 @@ class SimpleTag {
function getContent() { function getContent() {
return $this->_content; return $this->_content;
} }
/** /**
* Accessor for content reduced to visible text. Acts * Accessor for content reduced to visible text. Acts
* like a text mode browser, normalising space and * like a text mode browser, normalising space and
@ -138,7 +138,7 @@ class SimpleTag {
function getText() { function getText() {
return SimpleHtmlSaxParser::normalise($this->_content); return SimpleHtmlSaxParser::normalise($this->_content);
} }
/** /**
* Test to see if id attribute matches. * Test to see if id attribute matches.
* @param string $id ID to test against. * @param string $id ID to test against.
@ -156,14 +156,14 @@ class SimpleTag {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleBaseTag extends SimpleTag { class SimpleBaseTag extends SimpleTag {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleBaseTag($attributes) { function __construct($attributes) {
$this->SimpleTag('base', $attributes); parent::__construct('base', $attributes);
} }
/** /**
@ -182,14 +182,14 @@ class SimpleBaseTag extends SimpleTag {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleTitleTag extends SimpleTag { class SimpleTitleTag extends SimpleTag {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleTitleTag($attributes) { function __construct($attributes) {
$this->SimpleTag('title', $attributes); parent::__construct('title', $attributes);
} }
} }
@ -199,16 +199,16 @@ class SimpleTitleTag extends SimpleTag {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleAnchorTag extends SimpleTag { class SimpleAnchorTag extends SimpleTag {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleAnchorTag($attributes) { function __construct($attributes) {
$this->SimpleTag('a', $attributes); parent::__construct('a', $attributes);
} }
/** /**
* Accessor for URL as string. * Accessor for URL as string.
* @return string Coerced as string. * @return string Coerced as string.
@ -232,20 +232,20 @@ class SimpleWidget extends SimpleTag {
var $_value; var $_value;
var $_label; var $_label;
var $_is_set; var $_is_set;
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param string $name Tag name. * @param string $name Tag name.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleWidget($name, $attributes) { function __construct($name, $attributes) {
$this->SimpleTag($name, $attributes); parent::__construct($name, $attributes);
$this->_value = false; $this->_value = false;
$this->_label = false; $this->_label = false;
$this->_is_set = false; $this->_is_set = false;
} }
/** /**
* Accessor for name submitted as the key in * Accessor for name submitted as the key in
* GET/POST variables hash. * GET/POST variables hash.
@ -255,7 +255,7 @@ class SimpleWidget extends SimpleTag {
function getName() { function getName() {
return $this->getAttribute('name'); return $this->getAttribute('name');
} }
/** /**
* Accessor for default value parsed with the tag. * Accessor for default value parsed with the tag.
* @return string Parsed value. * @return string Parsed value.
@ -264,7 +264,7 @@ class SimpleWidget extends SimpleTag {
function getDefault() { function getDefault() {
return $this->getAttribute('value'); return $this->getAttribute('value');
} }
/** /**
* Accessor for currently set value or default if * Accessor for currently set value or default if
* none. * none.
@ -278,7 +278,7 @@ class SimpleWidget extends SimpleTag {
} }
return $this->_value; return $this->_value;
} }
/** /**
* Sets the current form element value. * Sets the current form element value.
* @param string $value New value. * @param string $value New value.
@ -290,7 +290,7 @@ class SimpleWidget extends SimpleTag {
$this->_is_set = true; $this->_is_set = true;
return true; return true;
} }
/** /**
* Resets the form element value back to the * Resets the form element value back to the
* default. * default.
@ -299,7 +299,7 @@ class SimpleWidget extends SimpleTag {
function resetValue() { function resetValue() {
$this->_is_set = false; $this->_is_set = false;
} }
/** /**
* Allows setting of a label externally, say by a * Allows setting of a label externally, say by a
* label tag. * label tag.
@ -309,7 +309,7 @@ class SimpleWidget extends SimpleTag {
function setLabel($label) { function setLabel($label) {
$this->_label = trim($label); $this->_label = trim($label);
} }
/** /**
* Reads external or internal label. * Reads external or internal label.
* @param string $label Label to test. * @param string $label Label to test.
@ -319,7 +319,7 @@ class SimpleWidget extends SimpleTag {
function isLabel($label) { function isLabel($label) {
return $this->_label == trim($label); return $this->_label == trim($label);
} }
/** /**
* Dispatches the value into the form encoded packet. * Dispatches the value into the form encoded packet.
* @param SimpleEncoding $encoding Form packet. * @param SimpleEncoding $encoding Form packet.
@ -338,19 +338,19 @@ class SimpleWidget extends SimpleTag {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleTextTag extends SimpleWidget { class SimpleTextTag extends SimpleWidget {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleTextTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('input', $attributes); parent::__construct('input', $attributes);
if ($this->getAttribute('value') === false) { if ($this->getAttribute('value') === false) {
$this->_setAttribute('value', ''); $this->_setAttribute('value', '');
} }
} }
/** /**
* Tag contains no content. * Tag contains no content.
* @return boolean False. * @return boolean False.
@ -359,7 +359,7 @@ class SimpleTextTag extends SimpleWidget {
function expectEndTag() { function expectEndTag() {
return false; return false;
} }
/** /**
* Sets the current form element value. Cannot * Sets the current form element value. Cannot
* change the value of a hidden field. * change the value of a hidden field.
@ -381,19 +381,19 @@ class SimpleTextTag extends SimpleWidget {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleSubmitTag extends SimpleWidget { class SimpleSubmitTag extends SimpleWidget {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleSubmitTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('input', $attributes); parent::__construct('input', $attributes);
if ($this->getAttribute('value') === false) { if ($this->getAttribute('value') === false) {
$this->_setAttribute('value', 'Submit'); $this->_setAttribute('value', 'Submit');
} }
} }
/** /**
* Tag contains no end element. * Tag contains no end element.
* @return boolean False. * @return boolean False.
@ -402,7 +402,7 @@ class SimpleSubmitTag extends SimpleWidget {
function expectEndTag() { function expectEndTag() {
return false; return false;
} }
/** /**
* Disables the setting of the button value. * Disables the setting of the button value.
* @param string $value Ignored. * @param string $value Ignored.
@ -412,7 +412,7 @@ class SimpleSubmitTag extends SimpleWidget {
function setValue($value) { function setValue($value) {
return false; return false;
} }
/** /**
* Value of browser visible text. * Value of browser visible text.
* @return string Visible label. * @return string Visible label.
@ -421,7 +421,7 @@ class SimpleSubmitTag extends SimpleWidget {
function getLabel() { function getLabel() {
return $this->getValue(); return $this->getValue();
} }
/** /**
* Test for a label match when searching. * Test for a label match when searching.
* @param string $label Label to test. * @param string $label Label to test.
@ -432,23 +432,23 @@ class SimpleSubmitTag extends SimpleWidget {
return trim($label) == trim($this->getLabel()); return trim($label) == trim($this->getLabel());
} }
} }
/** /**
* Image button as input tag. * Image button as input tag.
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleImageSubmitTag extends SimpleWidget { class SimpleImageSubmitTag extends SimpleWidget {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleImageSubmitTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('input', $attributes); parent::__construct('input', $attributes);
} }
/** /**
* Tag contains no end element. * Tag contains no end element.
* @return boolean False. * @return boolean False.
@ -457,7 +457,7 @@ class SimpleImageSubmitTag extends SimpleWidget {
function expectEndTag() { function expectEndTag() {
return false; return false;
} }
/** /**
* Disables the setting of the button value. * Disables the setting of the button value.
* @param string $value Ignored. * @param string $value Ignored.
@ -467,7 +467,7 @@ class SimpleImageSubmitTag extends SimpleWidget {
function setValue($value) { function setValue($value) {
return false; return false;
} }
/** /**
* Value of browser visible text. * Value of browser visible text.
* @return string Visible label. * @return string Visible label.
@ -479,7 +479,7 @@ class SimpleImageSubmitTag extends SimpleWidget {
} }
return $this->getAttribute('alt'); return $this->getAttribute('alt');
} }
/** /**
* Test for a label match when searching. * Test for a label match when searching.
* @param string $label Label to test. * @param string $label Label to test.
@ -489,7 +489,7 @@ class SimpleImageSubmitTag extends SimpleWidget {
function isLabel($label) { function isLabel($label) {
return trim($label) == trim($this->getLabel()); return trim($label) == trim($this->getLabel());
} }
/** /**
* Dispatches the value into the form encoded packet. * Dispatches the value into the form encoded packet.
* @param SimpleEncoding $encoding Form packet. * @param SimpleEncoding $encoding Form packet.
@ -507,24 +507,24 @@ class SimpleImageSubmitTag extends SimpleWidget {
} }
} }
} }
/** /**
* Submit button as button tag. * Submit button as button tag.
* @package SimpleTest * @package SimpleTest
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleButtonTag extends SimpleWidget { class SimpleButtonTag extends SimpleWidget {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* Defaults are very browser dependent. * Defaults are very browser dependent.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleButtonTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('button', $attributes); parent::__construct('button', $attributes);
} }
/** /**
* Check to see if the tag can have both start and * Check to see if the tag can have both start and
* end tags with content in between. * end tags with content in between.
@ -534,7 +534,7 @@ class SimpleButtonTag extends SimpleWidget {
function expectEndTag() { function expectEndTag() {
return true; return true;
} }
/** /**
* Disables the setting of the button value. * Disables the setting of the button value.
* @param string $value Ignored. * @param string $value Ignored.
@ -544,7 +544,7 @@ class SimpleButtonTag extends SimpleWidget {
function setValue($value) { function setValue($value) {
return false; return false;
} }
/** /**
* Value of browser visible text. * Value of browser visible text.
* @return string Visible label. * @return string Visible label.
@ -553,7 +553,7 @@ class SimpleButtonTag extends SimpleWidget {
function getLabel() { function getLabel() {
return $this->getContent(); return $this->getContent();
} }
/** /**
* Test for a label match when searching. * Test for a label match when searching.
* @param string $label Label to test. * @param string $label Label to test.
@ -571,16 +571,16 @@ class SimpleButtonTag extends SimpleWidget {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleTextAreaTag extends SimpleWidget { class SimpleTextAreaTag extends SimpleWidget {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleTextAreaTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('textarea', $attributes); parent::__construct('textarea', $attributes);
} }
/** /**
* Accessor for starting value. * Accessor for starting value.
* @return string Parsed value. * @return string Parsed value.
@ -589,7 +589,7 @@ class SimpleTextAreaTag extends SimpleWidget {
function getDefault() { function getDefault() {
return $this->_wrap(SimpleHtmlSaxParser::decodeHtml($this->getContent())); return $this->_wrap(SimpleHtmlSaxParser::decodeHtml($this->getContent()));
} }
/** /**
* Applies word wrapping if needed. * Applies word wrapping if needed.
* @param string $value New value. * @param string $value New value.
@ -599,7 +599,7 @@ class SimpleTextAreaTag extends SimpleWidget {
function setValue($value) { function setValue($value) {
return parent::setValue($this->_wrap($value)); return parent::setValue($this->_wrap($value));
} }
/** /**
* Test to see if text should be wrapped. * Test to see if text should be wrapped.
* @return boolean True if wrapping on. * @return boolean True if wrapping on.
@ -614,7 +614,7 @@ class SimpleTextAreaTag extends SimpleWidget {
} }
return false; return false;
} }
/** /**
* Performs the formatting that is peculiar to * Performs the formatting that is peculiar to
* this tag. There is strange behaviour in this * this tag. There is strange behaviour in this
@ -639,7 +639,7 @@ class SimpleTextAreaTag extends SimpleWidget {
} }
return $text; return $text;
} }
/** /**
* The content of textarea is not part of the page. * The content of textarea is not part of the page.
* @return boolean True. * @return boolean True.
@ -656,16 +656,16 @@ class SimpleTextAreaTag extends SimpleWidget {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleUploadTag extends SimpleWidget { class SimpleUploadTag extends SimpleWidget {
/** /**
* Starts with attributes only. * Starts with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleUploadTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('input', $attributes); parent::__construct('input', $attributes);
} }
/** /**
* Tag contains no content. * Tag contains no content.
* @return boolean False. * @return boolean False.
@ -674,7 +674,7 @@ class SimpleUploadTag extends SimpleWidget {
function expectEndTag() { function expectEndTag() {
return false; return false;
} }
/** /**
* Dispatches the value into the form encoded packet. * Dispatches the value into the form encoded packet.
* @param SimpleEncoding $encoding Form packet. * @param SimpleEncoding $encoding Form packet.
@ -699,18 +699,18 @@ class SimpleUploadTag extends SimpleWidget {
class SimpleSelectionTag extends SimpleWidget { class SimpleSelectionTag extends SimpleWidget {
var $_options; var $_options;
var $_choice; var $_choice;
/** /**
* Starts with attributes only. * Starts with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleSelectionTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('select', $attributes); parent::__construct('select', $attributes);
$this->_options = array(); $this->_options = array();
$this->_choice = false; $this->_choice = false;
} }
/** /**
* Adds an option tag to a selection field. * Adds an option tag to a selection field.
* @param SimpleOptionTag $tag New option. * @param SimpleOptionTag $tag New option.
@ -721,7 +721,7 @@ class SimpleSelectionTag extends SimpleWidget {
$this->_options[] = &$tag; $this->_options[] = &$tag;
} }
} }
/** /**
* Text within the selection element is ignored. * Text within the selection element is ignored.
* @param string $content Ignored. * @param string $content Ignored.
@ -729,7 +729,7 @@ class SimpleSelectionTag extends SimpleWidget {
*/ */
function addContent($content) { function addContent($content) {
} }
/** /**
* Scans options for defaults. If none, then * Scans options for defaults. If none, then
* the first option is selected. * the first option is selected.
@ -747,7 +747,7 @@ class SimpleSelectionTag extends SimpleWidget {
} }
return ''; return '';
} }
/** /**
* Can only set allowed values. * Can only set allowed values.
* @param string $value New choice. * @param string $value New choice.
@ -763,7 +763,7 @@ class SimpleSelectionTag extends SimpleWidget {
} }
return false; return false;
} }
/** /**
* Accessor for current selection value. * Accessor for current selection value.
* @return string Value attribute or * @return string Value attribute or
@ -786,18 +786,18 @@ class SimpleSelectionTag extends SimpleWidget {
class MultipleSelectionTag extends SimpleWidget { class MultipleSelectionTag extends SimpleWidget {
var $_options; var $_options;
var $_values; var $_values;
/** /**
* Starts with attributes only. * Starts with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function MultipleSelectionTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('select', $attributes); parent::__construct('select', $attributes);
$this->_options = array(); $this->_options = array();
$this->_values = false; $this->_values = false;
} }
/** /**
* Adds an option tag to a selection field. * Adds an option tag to a selection field.
* @param SimpleOptionTag $tag New option. * @param SimpleOptionTag $tag New option.
@ -808,7 +808,7 @@ class MultipleSelectionTag extends SimpleWidget {
$this->_options[] = &$tag; $this->_options[] = &$tag;
} }
} }
/** /**
* Text within the selection element is ignored. * Text within the selection element is ignored.
* @param string $content Ignored. * @param string $content Ignored.
@ -816,7 +816,7 @@ class MultipleSelectionTag extends SimpleWidget {
*/ */
function addContent($content) { function addContent($content) {
} }
/** /**
* Scans options for defaults to populate the * Scans options for defaults to populate the
* value array(). * value array().
@ -832,7 +832,7 @@ class MultipleSelectionTag extends SimpleWidget {
} }
return $default; return $default;
} }
/** /**
* Can only set allowed values. Any illegal value * Can only set allowed values. Any illegal value
* will result in a failure, but all correct values * will result in a failure, but all correct values
@ -859,7 +859,7 @@ class MultipleSelectionTag extends SimpleWidget {
$this->_values = $achieved; $this->_values = $achieved;
return true; return true;
} }
/** /**
* Accessor for current selection value. * Accessor for current selection value.
* @return array List of currently set options. * @return array List of currently set options.
@ -879,14 +879,14 @@ class MultipleSelectionTag extends SimpleWidget {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleOptionTag extends SimpleWidget { class SimpleOptionTag extends SimpleWidget {
/** /**
* Stashes the attributes. * Stashes the attributes.
*/ */
function SimpleOptionTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('option', $attributes); parent::__construct('option', $attributes);
} }
/** /**
* Does nothing. * Does nothing.
* @param string $value Ignored. * @param string $value Ignored.
@ -896,7 +896,7 @@ class SimpleOptionTag extends SimpleWidget {
function setValue($value) { function setValue($value) {
return false; return false;
} }
/** /**
* Test to see if a value matches the option. * Test to see if a value matches the option.
* @param string $compare Value to compare with. * @param string $compare Value to compare with.
@ -910,7 +910,7 @@ class SimpleOptionTag extends SimpleWidget {
} }
return trim($this->getContent()) == $compare; return trim($this->getContent()) == $compare;
} }
/** /**
* Accessor for starting value. Will be set to * Accessor for starting value. Will be set to
* the option label if no value exists. * the option label if no value exists.
@ -923,7 +923,7 @@ class SimpleOptionTag extends SimpleWidget {
} }
return $this->getAttribute('value'); return $this->getAttribute('value');
} }
/** /**
* The content of options is not part of the page. * The content of options is not part of the page.
* @return boolean True. * @return boolean True.
@ -940,18 +940,18 @@ class SimpleOptionTag extends SimpleWidget {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleRadioButtonTag extends SimpleWidget { class SimpleRadioButtonTag extends SimpleWidget {
/** /**
* Stashes the attributes. * Stashes the attributes.
* @param array $attributes Hash of attributes. * @param array $attributes Hash of attributes.
*/ */
function SimpleRadioButtonTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('input', $attributes); parent::__construct('input', $attributes);
if ($this->getAttribute('value') === false) { if ($this->getAttribute('value') === false) {
$this->_setAttribute('value', 'on'); $this->_setAttribute('value', 'on');
} }
} }
/** /**
* Tag contains no content. * Tag contains no content.
* @return boolean False. * @return boolean False.
@ -960,7 +960,7 @@ class SimpleRadioButtonTag extends SimpleWidget {
function expectEndTag() { function expectEndTag() {
return false; return false;
} }
/** /**
* The only allowed value sn the one in the * The only allowed value sn the one in the
* "value" attribute. * "value" attribute.
@ -977,7 +977,7 @@ class SimpleRadioButtonTag extends SimpleWidget {
} }
return parent::setValue($value); return parent::setValue($value);
} }
/** /**
* Accessor for starting value. * Accessor for starting value.
* @return string Parsed value. * @return string Parsed value.
@ -997,19 +997,19 @@ class SimpleRadioButtonTag extends SimpleWidget {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleCheckboxTag extends SimpleWidget { class SimpleCheckboxTag extends SimpleWidget {
/** /**
* Starts with attributes only. * Starts with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleCheckboxTag($attributes) { function __construct($attributes) {
$this->SimpleWidget('input', $attributes); parent::__construct('input', $attributes);
if ($this->getAttribute('value') === false) { if ($this->getAttribute('value') === false) {
$this->_setAttribute('value', 'on'); $this->_setAttribute('value', 'on');
} }
} }
/** /**
* Tag contains no content. * Tag contains no content.
* @return boolean False. * @return boolean False.
@ -1018,7 +1018,7 @@ class SimpleCheckboxTag extends SimpleWidget {
function expectEndTag() { function expectEndTag() {
return false; return false;
} }
/** /**
* The only allowed value in the one in the * The only allowed value in the one in the
* "value" attribute. The default for this * "value" attribute. The default for this
@ -1040,7 +1040,7 @@ class SimpleCheckboxTag extends SimpleWidget {
} }
return parent::setValue($value); return parent::setValue($value);
} }
/** /**
* Accessor for starting value. The default * Accessor for starting value. The default
* value is "on". * value is "on".
@ -1071,7 +1071,7 @@ class SimpleTagGroup {
function addWidget(&$widget) { function addWidget(&$widget) {
$this->_widgets[] = &$widget; $this->_widgets[] = &$widget;
} }
/** /**
* Accessor to widget set. * Accessor to widget set.
* @return array All widgets. * @return array All widgets.
@ -1090,7 +1090,7 @@ class SimpleTagGroup {
function getAttribute($label) { function getAttribute($label) {
return false; return false;
} }
/** /**
* Fetches the name for the widget from the first * Fetches the name for the widget from the first
* member. * member.
@ -1102,7 +1102,7 @@ class SimpleTagGroup {
return $this->_widgets[0]->getName(); return $this->_widgets[0]->getName();
} }
} }
/** /**
* Scans the widgets for one with the appropriate * Scans the widgets for one with the appropriate
* ID field. * ID field.
@ -1118,7 +1118,7 @@ class SimpleTagGroup {
} }
return false; return false;
} }
/** /**
* Scans the widgets for one with the appropriate * Scans the widgets for one with the appropriate
* attached label. * attached label.
@ -1134,7 +1134,7 @@ class SimpleTagGroup {
} }
return false; return false;
} }
/** /**
* Dispatches the value into the form encoded packet. * Dispatches the value into the form encoded packet.
* @param SimpleEncoding $encoding Form packet. * @param SimpleEncoding $encoding Form packet.
@ -1151,7 +1151,7 @@ class SimpleTagGroup {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleCheckboxGroup extends SimpleTagGroup { class SimpleCheckboxGroup extends SimpleTagGroup {
/** /**
* Accessor for current selected widget or false * Accessor for current selected widget or false
* if none. * if none.
@ -1168,7 +1168,7 @@ class SimpleCheckboxGroup extends SimpleTagGroup {
} }
return $this->_coerceValues($values); return $this->_coerceValues($values);
} }
/** /**
* Accessor for starting value that is active. * Accessor for starting value that is active.
* @return string/array Widget values or false if none. * @return string/array Widget values or false if none.
@ -1184,7 +1184,7 @@ class SimpleCheckboxGroup extends SimpleTagGroup {
} }
return $this->_coerceValues($values); return $this->_coerceValues($values);
} }
/** /**
* Accessor for current set values. * Accessor for current set values.
* @param string/array/boolean $values Either a single string, a * @param string/array/boolean $values Either a single string, a
@ -1208,7 +1208,7 @@ class SimpleCheckboxGroup extends SimpleTagGroup {
} }
return true; return true;
} }
/** /**
* Tests to see if a possible value set is legal. * Tests to see if a possible value set is legal.
* @param string/array/boolean $values Either a single string, a * @param string/array/boolean $values Either a single string, a
@ -1228,7 +1228,7 @@ class SimpleCheckboxGroup extends SimpleTagGroup {
} }
return ($values == $matches); return ($values == $matches);
} }
/** /**
* Converts the output to an appropriate format. This means * Converts the output to an appropriate format. This means
* that no values is false, a single value is just that * that no values is false, a single value is just that
@ -1246,7 +1246,7 @@ class SimpleCheckboxGroup extends SimpleTagGroup {
return $values; return $values;
} }
} }
/** /**
* Converts false or string into array. The opposite of * Converts false or string into array. The opposite of
* the coercian method. * the coercian method.
@ -1274,7 +1274,7 @@ class SimpleCheckboxGroup extends SimpleTagGroup {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleRadioGroup extends SimpleTagGroup { class SimpleRadioGroup extends SimpleTagGroup {
/** /**
* Each tag is tried in turn until one is * Each tag is tried in turn until one is
* successfully set. The others will be * successfully set. The others will be
@ -1296,7 +1296,7 @@ class SimpleRadioGroup extends SimpleTagGroup {
} }
return true; return true;
} }
/** /**
* Tests to see if a value is allowed. * Tests to see if a value is allowed.
* @param string Attempted value. * @param string Attempted value.
@ -1312,7 +1312,7 @@ class SimpleRadioGroup extends SimpleTagGroup {
} }
return false; return false;
} }
/** /**
* Accessor for current selected widget or false * Accessor for current selected widget or false
* if none. * if none.
@ -1329,7 +1329,7 @@ class SimpleRadioGroup extends SimpleTagGroup {
} }
return false; return false;
} }
/** /**
* Accessor for starting value that is active. * Accessor for starting value that is active.
* @return string/boolean Value of first checked * @return string/boolean Value of first checked
@ -1353,16 +1353,16 @@ class SimpleRadioGroup extends SimpleTagGroup {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleLabelTag extends SimpleTag { class SimpleLabelTag extends SimpleTag {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleLabelTag($attributes) { function __construct($attributes) {
$this->SimpleTag('label', $attributes); parent::__construct('label', $attributes);
} }
/** /**
* Access for the ID to attach the label to. * Access for the ID to attach the label to.
* @return string For attribute. * @return string For attribute.
@ -1379,14 +1379,14 @@ class SimpleLabelTag extends SimpleTag {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleFormTag extends SimpleTag { class SimpleFormTag extends SimpleTag {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleFormTag($attributes) { function __construct($attributes) {
$this->SimpleTag('form', $attributes); parent::__construct('form', $attributes);
} }
} }
@ -1396,16 +1396,16 @@ class SimpleFormTag extends SimpleTag {
* @subpackage WebTester * @subpackage WebTester
*/ */
class SimpleFrameTag extends SimpleTag { class SimpleFrameTag extends SimpleTag {
/** /**
* Starts with a named tag with attributes only. * Starts with a named tag with attributes only.
* @param hash $attributes Attribute names and * @param hash $attributes Attribute names and
* string values. * string values.
*/ */
function SimpleFrameTag($attributes) { function __construct($attributes) {
$this->SimpleTag('frame', $attributes); parent::__construct('frame', $attributes);
} }
/** /**
* Tag contains no content. * Tag contains no content.
* @return boolean False. * @return boolean False.

View File

@ -35,13 +35,13 @@ class SimpleUrl {
var $_y; var $_y;
var $_target; var $_target;
var $_raw = false; var $_raw = false;
/** /**
* Constructor. Parses URL into sections. * Constructor. Parses URL into sections.
* @param string $url Incoming URL. * @param string $url Incoming URL.
* @access public * @access public
*/ */
function SimpleUrl($url = '') { function __construct($url = '') {
list($x, $y) = $this->_chompCoordinates($url); list($x, $y) = $this->_chompCoordinates($url);
$this->setCoordinates($x, $y); $this->setCoordinates($x, $y);
$this->_scheme = $this->_chompScheme($url); $this->_scheme = $this->_chompScheme($url);
@ -57,7 +57,7 @@ class SimpleUrl {
$this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); $this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false);
$this->_target = false; $this->_target = false;
} }
/** /**
* Extracts the X, Y coordinate pair from an image map. * Extracts the X, Y coordinate pair from an image map.
* @param string $url URL so far. The coordinates will be * @param string $url URL so far. The coordinates will be
@ -72,7 +72,7 @@ class SimpleUrl {
} }
return array(false, false); return array(false, false);
} }
/** /**
* Extracts the scheme part of an incoming URL. * Extracts the scheme part of an incoming URL.
* @param string $url URL so far. The scheme will be * @param string $url URL so far. The scheme will be
@ -87,7 +87,7 @@ class SimpleUrl {
} }
return false; return false;
} }
/** /**
* Extracts the username and password from the * Extracts the username and password from the
* incoming URL. The // prefix will be reattached * incoming URL. The // prefix will be reattached
@ -114,7 +114,7 @@ class SimpleUrl {
$url = $prefix . $url; $url = $prefix . $url;
return array(false, false); return array(false, false);
} }
/** /**
* Extracts the host part of an incoming URL. * Extracts the host part of an incoming URL.
* Includes the port number part. Will extract * Includes the port number part. Will extract
@ -143,7 +143,7 @@ class SimpleUrl {
} }
return false; return false;
} }
/** /**
* Extracts the path information from the incoming * Extracts the path information from the incoming
* URL. Strips this path from the URL. * URL. Strips this path from the URL.
@ -159,7 +159,7 @@ class SimpleUrl {
} }
return ''; return '';
} }
/** /**
* Strips off the request data. * Strips off the request data.
* @param string $url URL so far. The request will be * @param string $url URL so far. The request will be
@ -174,7 +174,7 @@ class SimpleUrl {
} }
return ''; return '';
} }
/** /**
* Breaks the request down into an object. * Breaks the request down into an object.
* @param string $raw Raw request. * @param string $raw Raw request.
@ -193,7 +193,7 @@ class SimpleUrl {
} }
return $request; return $request;
} }
/** /**
* Accessor for protocol part. * Accessor for protocol part.
* @param string $default Value to use if not present. * @param string $default Value to use if not present.
@ -203,7 +203,7 @@ class SimpleUrl {
function getScheme($default = false) { function getScheme($default = false) {
return $this->_scheme ? $this->_scheme : $default; return $this->_scheme ? $this->_scheme : $default;
} }
/** /**
* Accessor for user name. * Accessor for user name.
* @return string Username preceding host. * @return string Username preceding host.
@ -212,7 +212,7 @@ class SimpleUrl {
function getUsername() { function getUsername() {
return $this->_username; return $this->_username;
} }
/** /**
* Accessor for password. * Accessor for password.
* @return string Password preceding host. * @return string Password preceding host.
@ -221,7 +221,7 @@ class SimpleUrl {
function getPassword() { function getPassword() {
return $this->_password; return $this->_password;
} }
/** /**
* Accessor for hostname and port. * Accessor for hostname and port.
* @param string $default Value to use if not present. * @param string $default Value to use if not present.
@ -231,7 +231,7 @@ class SimpleUrl {
function getHost($default = false) { function getHost($default = false) {
return $this->_host ? $this->_host : $default; return $this->_host ? $this->_host : $default;
} }
/** /**
* Accessor for top level domain. * Accessor for top level domain.
* @return string Last part of host. * @return string Last part of host.
@ -241,7 +241,7 @@ class SimpleUrl {
$path_parts = pathinfo($this->getHost()); $path_parts = pathinfo($this->getHost());
return (isset($path_parts['extension']) ? $path_parts['extension'] : false); return (isset($path_parts['extension']) ? $path_parts['extension'] : false);
} }
/** /**
* Accessor for port number. * Accessor for port number.
* @return integer TCP/IP port number. * @return integer TCP/IP port number.
@ -249,8 +249,8 @@ class SimpleUrl {
*/ */
function getPort() { function getPort() {
return $this->_port; return $this->_port;
} }
/** /**
* Accessor for path. * Accessor for path.
* @return string Full path including leading slash if implied. * @return string Full path including leading slash if implied.
@ -262,7 +262,7 @@ class SimpleUrl {
} }
return $this->_path; return $this->_path;
} }
/** /**
* Accessor for page if any. This may be a * Accessor for page if any. This may be a
* directory name if ambiguious. * directory name if ambiguious.
@ -275,7 +275,7 @@ class SimpleUrl {
} }
return $matches[1]; return $matches[1];
} }
/** /**
* Gets the path to the page. * Gets the path to the page.
* @return string Path less the page. * @return string Path less the page.
@ -287,7 +287,7 @@ class SimpleUrl {
} }
return $matches[1]; return $matches[1];
} }
/** /**
* Accessor for fragment at end of URL after the "#". * Accessor for fragment at end of URL after the "#".
* @return string Part after "#". * @return string Part after "#".
@ -296,7 +296,7 @@ class SimpleUrl {
function getFragment() { function getFragment() {
return $this->_fragment; return $this->_fragment;
} }
/** /**
* Sets image coordinates. Set to false to clear * Sets image coordinates. Set to false to clear
* them. * them.
@ -312,7 +312,7 @@ class SimpleUrl {
$this->_x = (integer)$x; $this->_x = (integer)$x;
$this->_y = (integer)$y; $this->_y = (integer)$y;
} }
/** /**
* Accessor for horizontal image coordinate. * Accessor for horizontal image coordinate.
* @return integer X value. * @return integer X value.
@ -321,7 +321,7 @@ class SimpleUrl {
function getX() { function getX() {
return $this->_x; return $this->_x;
} }
/** /**
* Accessor for vertical image coordinate. * Accessor for vertical image coordinate.
* @return integer Y value. * @return integer Y value.
@ -330,7 +330,7 @@ class SimpleUrl {
function getY() { function getY() {
return $this->_y; return $this->_y;
} }
/** /**
* Accessor for current request parameters * Accessor for current request parameters
* in URL string form. Will return teh original request * in URL string form. Will return teh original request
@ -350,7 +350,7 @@ class SimpleUrl {
} }
return ''; return '';
} }
/** /**
* Adds an additional parameter to the request. * Adds an additional parameter to the request.
* @param string $key Name of parameter. * @param string $key Name of parameter.
@ -361,7 +361,7 @@ class SimpleUrl {
$this->_raw = false; $this->_raw = false;
$this->_request->add($key, $value); $this->_request->add($key, $value);
} }
/** /**
* Adds additional parameters to the request. * Adds additional parameters to the request.
* @param hash/SimpleFormEncoding $parameters Additional * @param hash/SimpleFormEncoding $parameters Additional
@ -372,7 +372,7 @@ class SimpleUrl {
$this->_raw = false; $this->_raw = false;
$this->_request->merge($parameters); $this->_request->merge($parameters);
} }
/** /**
* Clears down all parameters. * Clears down all parameters.
* @access public * @access public
@ -381,7 +381,7 @@ class SimpleUrl {
$this->_raw = false; $this->_raw = false;
$this->_request = new SimpleGetEncoding(); $this->_request = new SimpleGetEncoding();
} }
/** /**
* Gets the frame target if present. Although * Gets the frame target if present. Although
* not strictly part of the URL specification it * not strictly part of the URL specification it
@ -392,7 +392,7 @@ class SimpleUrl {
function getTarget() { function getTarget() {
return $this->_target; return $this->_target;
} }
/** /**
* Attaches a frame target. * Attaches a frame target.
* @param string $frame Name of frame. * @param string $frame Name of frame.
@ -402,7 +402,7 @@ class SimpleUrl {
$this->_raw = false; $this->_raw = false;
$this->_target = $frame; $this->_target = $frame;
} }
/** /**
* Renders the URL back into a string. * Renders the URL back into a string.
* @return string URL in canonical form. * @return string URL in canonical form.
@ -430,7 +430,7 @@ class SimpleUrl {
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return "$scheme$identity$host$port$path$encoded$fragment$coords"; return "$scheme$identity$host$port$path$encoded$fragment$coords";
} }
/** /**
* Replaces unknown sections to turn a relative * Replaces unknown sections to turn a relative
* URL into an absolute one. The base URL can * URL into an absolute one. The base URL can
@ -462,7 +462,7 @@ class SimpleUrl {
$coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY();
return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords"); return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords");
} }
/** /**
* Replaces unknown sections of the path with base parts * Replaces unknown sections of the path with base parts
* to return a complete absolute one. * to return a complete absolute one.
@ -482,7 +482,7 @@ class SimpleUrl {
} }
return $base->getPath(); return $base->getPath();
} }
/** /**
* Simple test to see if a path part is relative. * Simple test to see if a path part is relative.
* @param string $path Path to test. * @param string $path Path to test.
@ -492,7 +492,7 @@ class SimpleUrl {
function _isRelativePath($path) { function _isRelativePath($path) {
return (substr($path, 0, 1) != '/'); return (substr($path, 0, 1) != '/');
} }
/** /**
* Extracts the username and password for use in rendering * Extracts the username and password for use in rendering
* a URL. * a URL.
@ -505,7 +505,7 @@ class SimpleUrl {
} }
return false; return false;
} }
/** /**
* Replaces . and .. sections of the path. * Replaces . and .. sections of the path.
* @param string $path Unoptimised path. * @param string $path Unoptimised path.
@ -516,7 +516,7 @@ class SimpleUrl {
$path = preg_replace('|/\./|', '/', $path); $path = preg_replace('|/\./|', '/', $path);
return preg_replace('|/[^/]+/\.\./|', '/', $path); return preg_replace('|/[^/]+/\.\./|', '/', $path);
} }
/** /**
* A pipe seperated list of all TLDs that result in two part * A pipe seperated list of all TLDs that result in two part
* domain names. * domain names.

View File

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

View File

@ -1,4 +1,7 @@
<?php <?php
use SilverStripe\Model\FieldType\DBVarchar;
/** /**
* A ViewableData object is any object that can be rendered into a template/view. * 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)" * 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 * @param string $fieldSchema The field spec
* @return string * @return string
@ -317,7 +320,9 @@ class ViewableData extends Object implements IteratorAggregate {
public function escapeTypeForField($field) { public function escapeTypeForField($field) {
$class = $this->castingClass($field) ?: $this->config()->default_cast; $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;
} }
/** /**