doctrine boolean unique

Schema

    is_default:
      type: boolean
      unique: true

 

Model



  /**
   * (non-PHPdoc)
   * @see plugins/ullCorePlugin/lib/model/doctrine/PluginUllRecord::preSave()
   */
  public function preSave($event)
  {
    // Set is_default to null instead of false to allow usage of doctrine "unique"
    if ($this->is_default !== true)
    {
      $this->is_default = null;
    }
  }



 

Test

 



$t->diag('preSave() / "is_default" unique handling');

  $list = new UllNewsletterMailingList;
  $list->name = 'foo';
  $list->save();
 
  $t->same($list->is_default, null, 'is_default is null per default');
 
  $list->is_default = true;
  $list->save();
 
  $t->same($list->is_default, true, 'is_default is true now');
 
  $list->is_default = false;
  $list->save();
 
  $t->same($list->is_default, null, 'is_default is again null even we set it to false'); 
 
  $list2 = new UllNewsletterMailingList;
  $list2->name = 'bar';
  $list2->is_default = true;
  $list2->save();
  $t->pass('We can create a second list which is default, because the first is not the default one');
 
  try
  {
    $list->is_default = true;
    $list->save();
    $t->fail('No exception is thrown although we already have a default list');
  }
  catch (Exception $e)
  {
    $t->pass('An exception is thrown because we already have a default list');
  }