Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 13 | class PartialFieldSubmissionTest extends SapphireTest |
||
| 14 | { |
||
| 15 | /** |
||
| 16 | * @var bool |
||
| 17 | */ |
||
| 18 | protected $usesDatabase = true; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * @var PartialFieldSubmission |
||
| 22 | */ |
||
| 23 | protected $field; |
||
| 24 | |||
| 25 | public function testCanView() |
||
| 26 | { |
||
| 27 | $this->assertTrue($this->field->canView()); |
||
| 28 | |||
| 29 | $member = DefaultAdminService::singleton()->findOrCreateAdmin('[email protected]'); |
||
| 30 | Security::setCurrentUser($member); |
||
| 31 | |||
| 32 | $this->assertTrue($this->field->canView($member)); |
||
| 33 | } |
||
| 34 | |||
| 35 | public function testCanCreate() |
||
| 36 | { |
||
| 37 | Security::setCurrentUser(null); |
||
| 38 | $this->assertFalse($this->field->canCreate()); |
||
| 39 | |||
| 40 | $member = DefaultAdminService::singleton()->findOrCreateAdmin('[email protected]'); |
||
| 41 | Security::setCurrentUser($member); |
||
| 42 | |||
| 43 | $this->assertFalse($this->field->canCreate($member)); |
||
| 44 | } |
||
| 45 | |||
| 46 | public function testCanEdit() |
||
| 47 | { |
||
| 48 | Security::setCurrentUser(null); |
||
| 49 | $this->assertFalse($this->field->canEdit()); |
||
| 50 | |||
| 51 | $member = DefaultAdminService::singleton()->findOrCreateAdmin('[email protected]'); |
||
| 52 | Security::setCurrentUser($member); |
||
| 53 | |||
| 54 | $this->assertTrue($this->field->canEdit($member)); |
||
| 55 | } |
||
| 56 | |||
| 57 | public function testCanDelete() |
||
| 58 | { |
||
| 59 | Security::setCurrentUser(null); |
||
| 60 | $this->assertFalse($this->field->canDelete()); |
||
| 61 | |||
| 62 | $member = DefaultAdminService::singleton()->findOrCreateAdmin('[email protected]'); |
||
| 63 | Security::setCurrentUser($member); |
||
| 64 | |||
| 65 | $this->assertTrue($this->field->canDelete($member)); |
||
| 66 | } |
||
| 67 | |||
| 68 | protected function setUp() |
||
| 69 | { |
||
| 70 | parent::setUp(); |
||
| 71 | |||
| 72 | $this->field = PartialFieldSubmission::create(); |
||
| 73 | $partialForm = PartialFormSubmission::create(); |
||
| 74 | $udf = UserDefinedForm::create(['Title' => 'Test'])->write(); |
||
| 75 | $partialForm->UserDefinedFormID = $udf; |
||
| 76 | $partialForm->UserDefinedFormClass = UserDefinedForm::class; |
||
| 77 | $partialFormID = $partialForm->write(); |
||
| 78 | $this->field->SubmittedFormID = $partialFormID; |
||
| 79 | // testCanCreate() will most likely be an error due to SubmittedForm returning a parent's permission |
||
| 80 | // without checking if Parent exists, so have to set the SubmittedForm parent |
||
| 81 | $this->field->SubmittedForm()->ParentID = $udf; |
||
| 82 | } |
||
| 83 | } |
||
| 84 |