Constraint handling for @DataType (Typed Data API) I am creating a new data type, 'duration'. The value will be a duration string that is used by a DateIntervale object.

The value is a string, but with a specified format. I'm assuming that due to it being a string, for my @DataType I should either extend StringData, or PrimitiveData. And I would like to add required validation to this data to ensure that the value contained is in the correct format.

I've been reading through documentation, and reverse engineering other @DataType objects, but I've not been able to find what I'm looking for. So what I want to specifically ask:


Should I extend StringData, or is it better to extend PrimitiveData?
How/where can I add a constraint onto this data. By this I mean, what method should I use to ensure that when someone calls setValue() using this data, the string can be validated using a regex to ensure it's the proper format.
If the value is not the proper format, how is this handled? Is there a way to call an error? Should I throw an Exception? Or should I set a default value instead of the value that was supposed to be submitted?
Am I looking at this the right way?


Thank you.
In abstract class PrimitiveBase that uses PrimitiveInterface... which StringData entends you can see the PrimitiveInterface use of PrimitiveInterface methods:

getValue(); , setValue($value);, getCastedValue();

so you can safely do ether however ... Personally as your data is realy a string  I would go with the extend StringData option 

and call 
parent functions like 

 public function getValue() {
   return parent::getValue();
   or 
   $this-&gt;parent-&gt;getValue();
 }

 public function setValue($value) {
    // CRAZY REGX HERE 
   $new_value = $this-&gt;getREGXCRAXY($value);

   return $this-&gt;parent-&gt;setValue($new_value);
 }

 public function  getREGXCRAXY($value) {
    do the things.
  if value !== valid 
 throw new \Exception('Invalid data dude must be in format xyz');
  return $new_formated_value; 
 }


no i think it is proper to throw the exception because then the person can catch it in an event subscriber .. or learn the right way to set the data.