createMyValidator(true); } protected function createMyValidator(bool $allowEdit) { $auth = $this->createMock(Security::class); $auth->method('getUser')->willReturn(new User()); $auth->method('isGranted')->willReturnCallback( function ($attributes, $subject = null) use ($allowEdit) { switch ($attributes) { case 'edit_export': return $allowEdit; } return false; } ); return new TimesheetExportedValidator($auth); } public function testConstraintIsInvalid() { $this->expectException(UnexpectedTypeException::class); $this->validator->validate(new Timesheet(), new NotBlank()); } public function testInvalidValueThrowsException() { $this->expectException(UnexpectedTypeException::class); $this->validator->validate(new NotBlank(), new TimesheetExported(['message' => 'myMessage'])); } public function testTriggersOnMissingPermission() { $this->validator = $this->createMyValidator(false); $this->validator->initialize($this->context); $timesheet = $this->createMock(Timesheet::class); $timesheet->method('isExported')->willReturn(true); $timesheet->method('getId')->willReturn(1); $this->validator->validate($timesheet, new TimesheetExported()); $this->buildViolation('This timesheet is already exported.') ->atPath('property.path.exported') ->setCode(TimesheetExported::TIMESHEET_EXPORTED) ->assertRaised(); } public function testNotTriggersOnNewTimesheet() { $this->validator = $this->createMyValidator(false); $this->validator->initialize($this->context); $timesheet = $this->createMock(Timesheet::class); $timesheet->method('isExported')->willReturn(true); $timesheet->method('getId')->willReturn(null); $this->validator->validate($timesheet, new TimesheetExported()); $this->assertNoViolation(); } public function testDoesNotTriggerWithPermission() { $this->validator = $this->createMyValidator(true); $this->validator->initialize($this->context); $timesheet = new Timesheet(); $timesheet->setExported(true); $this->validator->validate($timesheet, new TimesheetExported()); $this->assertNoViolation(); } public function testDoesNotTriggerIfNotExported() { $this->validator = $this->createMyValidator(false); $this->validator->initialize($this->context); $timesheet = new Timesheet(); $timesheet->setExported(false); $this->validator->validate($timesheet, new TimesheetExported()); $this->assertNoViolation(); } public function testGetTargets() { $constraint = new TimesheetExported(); self::assertEquals('class', $constraint->getTargets()); } }