Permalink
Browse files

ENHANCEMENT: Allow Object::create() to be called with late static bin…

…ding.

This allows DataList::create('SiteTree') as equivalent to Object::create('DataList', 'SiteTree'), without
having to have a create() function on DataList. Required for E_STRICT compliance.
  • Loading branch information...
1 parent 06a4e1a commit de2832e65f104c1833a1d32143998d47087d3456 @andrewandante andrewandante committed Mar 27, 2012
@@ -467,7 +467,7 @@ public function MainMenu() {
$menu->push(new ArrayData(array(
"MenuItem" => $menuItem,
"Title" => Convert::raw2xml($title),
- "Code" => DBField::create('Text', $code),
+ "Code" => DBField::create_field('Text', $code),
"Link" => $menuItem->url,
"LinkingMode" => $linkingmode
)));
@@ -1256,7 +1256,7 @@ function IsPreviewExpanded() {
* @return String
*/
function Locale() {
- return DBField::create('DBLocale', i18n::get_locale());
+ return DBField::create_field('DBLocale', i18n::get_locale());
}
function providePermissions() {
View
@@ -83,13 +83,27 @@ public function config() {
* overload is found, an instance of this is returned rather than the original class. To overload a class, use
* {@link Object::useCustomClass()}
*
+ * This can be called in one of two ways - either calling via the class directly,
+ * or calling on Object and passing the class name as the first parameter. The following
+ * are equivalent:
+ * $list = DataList::create('SiteTree');
+ * $list = Object::create('DataList', 'SiteTree');
+ *
* @param string $class the class name
* @param mixed $arguments,... arguments to pass to the constructor
* @return Object
*/
public static function create() {
$args = func_get_args();
- $class = self::getCustomClass(array_shift($args));
+
+ // Class to create should be the calling class if not Object,
+ // otherwise the first parameter
+ $class = get_called_class();
+ if($class == 'Object')
+ $class = array_shift($args);
+
+ $class = self::getCustomClass($class);
+
$reflector = new ReflectionClass($class);
if($reflector->getConstructor()) {
return $reflector->newInstanceArgs($args);
@@ -45,10 +45,6 @@ function __construct($action, $title = "", $form = null) {
parent::__construct($this->action, $title, null, $form);
}
- static function create($action, $title = "") {
- return new FormAction($action, $title);
- }
-
function actionName() {
return substr($this->name, 7);
}
@@ -28,9 +28,4 @@ function getAttributes() {
array('type' => 'hidden')
);
}
-
- static function create($name) {
- return new HiddenField($name);
- }
-
}
@@ -103,7 +103,7 @@ function setValue($val) {
function saveInto($dataObject) {
$fieldName = $this->name;
if($dataObject->hasMethod("set$fieldName")) {
- $dataObject->$fieldName = DBField::create('Money', array(
+ $dataObject->$fieldName = DBField::create_field('Money', array(
"Currency" => $this->fieldCurrency->Value(),
"Amount" => $this->fieldAmount->Value()
));
@@ -637,8 +637,8 @@ function SummaryFields($items = null) {
$summaryFields[] = new ArrayData(array(
'Function' => $function,
'SummaryValue' => $summaryValue,
- 'Name' => DBField::create('Varchar', $fieldName),
- 'Title' => DBField::create('Varchar', $fieldTitle),
+ 'Name' => DBField::create_field('Varchar', $fieldName),
+ 'Title' => DBField::create_field('Varchar', $fieldTitle),
));
}
return new ArrayList($summaryFields);
@@ -1234,13 +1234,13 @@ function getCastedValue($value, $castingDefinition) {
}
if(strpos($castingDefinition,'->') === false) {
$castingFieldType = $castingDefinition;
- $castingField = DBField::create($castingFieldType, $value);
+ $castingField = DBField::create_field($castingFieldType, $value);
$value = call_user_func_array(array($castingField,'XML'),$castingParams);
} else {
$fieldTypeParts = explode('->', $castingDefinition);
$castingFieldType = $fieldTypeParts[0];
$castingMethod = $fieldTypeParts[1];
- $castingField = DBField::create($castingFieldType, $value);
+ $castingField = DBField::create_field($castingFieldType, $value);
$value = call_user_func_array(array($castingField,$castingMethod),$castingParams);
}
@@ -59,7 +59,7 @@ function Field() {
$rawInput = Convert::html2raw($valforInput);
if($this->charNum) $reducedVal = substr($rawInput,0,$this->charNum);
- else $reducedVal = DBField::create('Text',$rawInput)->{$this->truncateMethod}();
+ else $reducedVal = DBField::create_field('Text',$rawInput)->{$this->truncateMethod}();
// only create togglefield if the truncated content is shorter
if(strlen($reducedVal) < strlen($rawInput)) {
@@ -239,13 +239,13 @@ public function getCastedValue($value, $castingDefinition) {
if(strpos($castingDefinition,'->') === false) {
$castingFieldType = $castingDefinition;
- $castingField = DBField::create($castingFieldType, $value);
+ $castingField = DBField::create_field($castingFieldType, $value);
$value = call_user_func_array(array($castingField,'XML'),$castingParams);
} else {
$fieldTypeParts = explode('->', $castingDefinition);
$castingFieldType = $fieldTypeParts[0];
$castingMethod = $fieldTypeParts[1];
- $castingField = DBField::create($castingFieldType, $value);
+ $castingField = DBField::create_field($castingFieldType, $value);
$value = call_user_func_array(array($castingField,$castingMethod),$castingParams);
}
View
@@ -14,18 +14,6 @@ class ArrayList extends ViewableData implements SS_List, SS_Filterable, SS_Sorta
*/
protected $items;
-
- /**
- * Synonym of the constructor. Can be chained with literate methods.
- * ArrayList::create("SiteTree")->sort("Title") is legal, but
- * new ArrayList("SiteTree")->sort("Title") is not.
- *
- * @param array $items - an initial array to fill this object with
- */
- public static function create(array $items = array()) {
- return new ArrayList($items);
- }
-
/**
*
* @param array $items - an initial array to fill this object with
View
@@ -27,17 +27,6 @@ class DataList extends ViewableData implements SS_List, SS_Filterable, SS_Sortab
* @var DataModel
*/
protected $model;
-
- /**
- * Synonym of the constructor. Can be chained with literate methods.
- * DataList::create("SiteTree")->sort("Title") is legal, but
- * new DataList("SiteTree")->sort("Title") is not.
- *
- * @param string $dataClass - The DataObject class to query.
- */
- public static function create($dataClass) {
- return new DataList($dataClass);
- }
/**
* Create a new DataList.
@@ -1092,7 +1092,7 @@ public function write($showDebug = false, $forceInsert = false, $forceWrite = fa
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
- $fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
+ $fieldObj = DBField::create_field('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
@@ -2380,12 +2380,12 @@ public function dbObject($fieldName) {
// Special case for has_one relationships
} else if(preg_match('/ID$/', $fieldName) && $this->has_one(substr($fieldName,0,-2))) {
$val = (isset($this->record[$fieldName])) ? $this->record[$fieldName] : null;
- return DBField::create('ForeignKey', $val, $fieldName, $this);
+ return DBField::create_field('ForeignKey', $val, $fieldName, $this);
// Special case for ClassName
} else if($fieldName == 'ClassName') {
$val = get_class($this);
- return DBField::create('Varchar', $val, $fieldName, $this);
+ return DBField::create_field('Varchar', $val, $fieldName, $this);
}
}
@@ -12,24 +12,6 @@ class ManyManyList extends RelationList {
protected $foreignKey, $foreignID;
protected $extraFields;
-
- /**
- * Synonym of the constructor. Can be chained with literate methods.
- * ManyManyList::create("Group","Member","ID", "GroupID")->sort("Title") is legal, but
- * new ManyManyList("Group","Member","ID", "GroupID")->sort("Title") is not.
- *
- * @param string $dataClass The class of the DataObjects that this will list.
- * @param string $joinTable The name of the table whose entries define the content of this many_many relation.
- * @param string $localKey The key in the join table that maps to the dataClass' PK.
- * @param string $foreignKey The key in the join table that maps to joined class' PK.
- * @param string $extraFields A map of field => fieldtype of extra fields on the join table.
- *
- * @see ManyManyList::__construct();
- * @example ManyManyList::create('Group','Group_Members', 'GroupID', 'MemberID');
- */
- public static function create($dataClass, $joinTable, $localKey, $foreignKey, $extraFields = array()) {
- return new ManyManyList($dataClass, $joinTable, $localKey, $foreignKey, $extraFields = array());
- }
/**
* Create a new ManyManyList object.
@@ -25,13 +25,13 @@
* if($this->getStreetName()) {
* $manipulation['fields']["{$this->name}Name"] = $this->prepValueForDB($this->getStreetName());
* } else {
-* $manipulation['fields']["{$this->name}Name"] = DBField::create('Varchar', $this->getStreetName())->nullValue();
+* $manipulation['fields']["{$this->name}Name"] = DBField::create_field('Varchar', $this->getStreetName())->nullValue();
* }
*
* if($this->getStreetNumber()) {
* $manipulation['fields']["{$this->name}Number"] = $this->prepValueForDB($this->getStreetNumber());
* } else {
-* $manipulation['fields']["{$this->name}Number"] = DBField::create('Int', $this->getStreetNumber())->nullValue();
+* $manipulation['fields']["{$this->name}Number"] = DBField::create_field('Int', $this->getStreetNumber())->nullValue();
* }
* }
*
@@ -63,11 +63,18 @@ function __construct($name = null) {
parent::__construct();
}
+
+ static function create() {
+ Deprecation::notice('3.0', 'DBField::create_field() is deprecated as it clashes with Object::create(). Use DBField::create_field() instead.');
+
+ return call_user_func_array(array('DBField', 'create_field'), func_get_args());
+ }
+
/**
* Create a DBField object that's not bound to any particular field.
* Useful for accessing the classes behaviour for other parts of your code.
*/
- static function create($className, $value, $name = null, $object = null) {
+ static function create_field($className, $value, $name = null, $object = null) {
$dbField = Object::create($className, $name, $object);
$dbField->setValue($value, null, false);
return $dbField;
@@ -96,7 +96,7 @@ static function now() {
if(self::$mock_now) {
return self::$mock_now;
} else {
- return DBField::create('SS_Datetime', date('Y-m-d H:i:s'));
+ return DBField::create_field('SS_Datetime', date('Y-m-d H:i:s'));
}
}
@@ -111,7 +111,7 @@ static function set_mock_now($datetime) {
if($datetime instanceof SS_Datetime) {
self::$mock_now = $datetime;
} elseif(is_string($datetime)) {
- self::$mock_now = DBField::create('SS_Datetime', $datetime);
+ self::$mock_now = DBField::create_field('SS_Datetime', $datetime);
} else {
throw new Exception('SS_Datetime::set_mock_now(): Wrong format: ' . $datetime);
}
@@ -84,13 +84,13 @@ function writeToManipulation(&$manipulation) {
if($this->getCurrency()) {
$manipulation['fields'][$this->name.'Currency'] = $this->prepValueForDB($this->getCurrency());
} else {
- $manipulation['fields'][$this->name.'Currency'] = DBField::create('Varchar', $this->getCurrency())->nullValue();
+ $manipulation['fields'][$this->name.'Currency'] = DBField::create_field('Varchar', $this->getCurrency())->nullValue();
}
if($this->getAmount()) {
$manipulation['fields'][$this->name.'Amount'] = $this->getAmount();
} else {
- $manipulation['fields'][$this->name.'Amount'] = DBField::create('Decimal', $this->getAmount())->nullValue();
+ $manipulation['fields'][$this->name.'Amount'] = DBField::create_field('Decimal', $this->getAmount())->nullValue();
}
}
@@ -544,7 +544,7 @@ class RestfulServerTest_AuthorRating extends DataObject implements TestOnly {
static $db = array(
'Rating' => 'Int',
'SecretField' => 'Text',
- 'WriteProtectedField' => 'Text'
+ 'WriteProtectedField' => 'Text',
);
static $has_one = array(
@@ -119,6 +119,11 @@ public function testCreateWithArgs() {
$strongObj = Object::strong_create('ObjectTest_CreateTest', 'arg1', 'arg2', array(), null, 'arg5');
$this->assertEquals($strongObj->constructArguments, array('arg1', 'arg2', array(), null, 'arg5'));
}
+
+ public function testCreateLateStaticBinding() {
+ $createdObj = ObjectTest_CreateTest::create('arg1', 'arg2', array(), null, 'arg5');
+ $this->assertEquals($createdObj->constructArguments, array('arg1', 'arg2', array(), null, 'arg5'));
+ }
/**
* Tests that {@link Object::useCustomClass()} correnctly replaces normal and strong objects
@@ -131,7 +131,7 @@ function testLoadWithCustomHeaderAndRelation() {
$this->assertEquals($testPlayer->ContractID, $testContract->ID, 'Creating new has_one relation works');
// Test nested setting of relation properties
- $contractAmount = DBField::create('Currency', $compareRow[5])->RAW();
+ $contractAmount = DBField::create_field('Currency', $compareRow[5])->RAW();
$this->assertEquals($testPlayer->Contract()->Amount, $contractAmount, 'Setting nested values in a relation works');
fclose($file);
@@ -202,7 +202,7 @@ function testStringFieldsWithMultibyteData() {
$value = 'üåäöÜÅÄÖ';
foreach ($allFields as $stringField) {
- $stringField = DBField::create($stringField, $value);
+ $stringField = DBField::create_field($stringField, $value);
for ($i = 1; $i < mb_strlen($value); $i++) {
$expected = mb_substr($value, 0, $i) . '...';
$this->assertEquals($expected, $stringField->LimitCharacters($i));
@@ -211,12 +211,12 @@ function testStringFieldsWithMultibyteData() {
$value = '<p>üåäö&amp;ÜÅÄÖ</p>';
foreach ($htmlFields as $stringField) {
- $stringField = DBField::create($stringField, $value);
+ $stringField = DBField::create_field($stringField, $value);
$this->assertEquals('üåäö&amp;ÜÅÄ...', $stringField->LimitCharacters(8));
}
- $this->assertEquals('ÅÄÖ', DBField::create('Text', 'åäö')->UpperCase());
- $this->assertEquals('åäö', DBField::create('Text', 'ÅÄÖ')->LowerCase());
+ $this->assertEquals('ÅÄÖ', DBField::create_field('Text', 'åäö')->UpperCase());
+ $this->assertEquals('åäö', DBField::create_field('Text', 'ÅÄÖ')->LowerCase());
}
}
@@ -5,17 +5,17 @@
*/
class DBLocaleTest extends SapphireTest {
function testNice() {
- $l = DBField::create('DBLocale', 'de_DE');
+ $l = DBField::create_field('DBLocale', 'de_DE');
$this->assertEquals($l->Nice(), 'German');
}
function testNiceNative() {
- $l = DBField::create('DBLocale', 'de_DE');
+ $l = DBField::create_field('DBLocale', 'de_DE');
$this->assertEquals($l->Nice(true), 'Deutsch');
}
function testNativeName() {
- $l = DBField::create('DBLocale', 'de_DE');
+ $l = DBField::create_field('DBLocale', 'de_DE');
$this->assertEquals($l->getNativeName(), 'Deutsch');
}
}
Oops, something went wrong.

0 comments on commit de2832e

Please sign in to comment.