2007-07-19 12:40:28 +02:00
|
|
|
<?php
|
2015-08-30 07:02:55 +02:00
|
|
|
|
2016-06-15 06:03:16 +02:00
|
|
|
namespace SilverStripe\ORM\FieldType;
|
2015-08-30 07:02:55 +02:00
|
|
|
|
2008-02-25 03:10:37 +01:00
|
|
|
/**
|
|
|
|
* Represents a decimal field from 0-1 containing a percentage value.
|
2014-08-15 08:53:05 +02:00
|
|
|
*
|
2010-10-15 01:58:09 +02:00
|
|
|
* Example instantiation in {@link DataObject::$db}:
|
|
|
|
* <code>
|
|
|
|
* static $db = array(
|
|
|
|
* "SuccessRatio" => "Percentage",
|
|
|
|
* "ReallyAccurate" => "Percentage(6)",
|
|
|
|
* );
|
|
|
|
* </code>
|
2008-02-25 03:10:37 +01:00
|
|
|
*/
|
2015-08-30 07:02:55 +02:00
|
|
|
class DBPercentage extends DBDecimal {
|
2014-08-15 08:53:05 +02:00
|
|
|
|
2007-07-19 12:40:28 +02:00
|
|
|
/**
|
|
|
|
* Create a new Decimal field.
|
2016-07-01 04:26:18 +02:00
|
|
|
*
|
|
|
|
* @param string $name
|
|
|
|
* @param int $precision
|
2007-07-19 12:40:28 +02:00
|
|
|
*/
|
2012-09-19 12:07:39 +02:00
|
|
|
public function __construct($name = null, $precision = 4) {
|
2009-02-03 21:29:21 +01:00
|
|
|
if(!$precision) $precision = 4;
|
2014-08-15 08:53:05 +02:00
|
|
|
|
2009-07-30 01:58:27 +02:00
|
|
|
parent::__construct($name, $precision + 1, $precision);
|
2007-07-19 12:40:28 +02:00
|
|
|
}
|
2014-08-15 08:53:05 +02:00
|
|
|
|
2010-10-15 01:58:09 +02:00
|
|
|
/**
|
|
|
|
* Returns the number, expressed as a percentage. For example, “36.30%”
|
|
|
|
*/
|
2012-09-19 12:07:39 +02:00
|
|
|
public function Nice() {
|
2007-07-19 12:40:28 +02:00
|
|
|
return number_format($this->value * 100, $this->decimalSize - 2) . '%';
|
|
|
|
}
|
2014-08-15 08:53:05 +02:00
|
|
|
|
2012-09-19 12:07:39 +02:00
|
|
|
public function saveInto($dataObject) {
|
2009-07-30 01:58:27 +02:00
|
|
|
parent::saveInto($dataObject);
|
2014-08-15 08:53:05 +02:00
|
|
|
|
2009-07-30 01:58:27 +02:00
|
|
|
$fieldName = $this->name;
|
|
|
|
if($fieldName && $dataObject->$fieldName > 1.0) {
|
|
|
|
$dataObject->$fieldName = 1.0;
|
|
|
|
}
|
|
|
|
}
|
2007-07-19 12:40:28 +02:00
|
|
|
}
|
|
|
|
|
2012-02-12 21:22:11 +01:00
|
|
|
|