Skip to content

Object Assertions

Object assertions validate objects, classes, interfaces, and their properties/methods.

Assert that a value is an instance of a given class.

use Cline\Assert\Assertions\Assertion;
Assertion::isInstanceOf($user, User::class);
Assertion::isInstanceOf($model, Model::class, 'Expected Model instance');

Assert that a value is NOT an instance of a given class.

Assertion::notIsInstanceOf($value, LegacyUser::class);

Assert that a class exists.

Assertion::classExists(User::class);
Assertion::classExists($className, 'Class does not exist');

Assert that an interface exists.

Assertion::interfaceExists(UserInterface::class);

Assert that a class is a subclass of another.

Assertion::subclassOf(AdminUser::class, User::class);

Assert that a class implements an interface.

Assertion::implementsInterface(User::class, UserInterface::class);

Assert that a method exists on an object.

Assertion::methodExists('save', $model);
Assertion::methodExists('handle', $handler, 'Handler must have handle method');

Assert that a property exists on an object or class.

Assertion::propertyExists($user, 'email');

Assert that multiple properties exist.

$required = ['id', 'name', 'email'];
Assertion::propertiesExist($user, $required);
use Cline\Assert\Assert;
Assert::that($user)
->isObject()
->isInstanceOf(User::class);
Assert::that(User::class)
->classExists()
->implementsInterface(UserInterface::class);
Assert::that($logger)
->isObject()
->implementsInterface(LoggerInterface::class);
Assert::that($model)
->isObject()
->isInstanceOf(Model::class)
->propertyExists('id')
->propertyExists('created_at');
Assert::that($plugin)
->isObject()
->implementsInterface(PluginInterface::class)
->methodExists('register')
->methodExists('boot');
public function make(string $class)
{
Assertion::classExists($class);
Assertion::subclassOf($class, BaseService::class);
return new $class();
}
Assertion::implementsInterface(JsonSerializer::class, Serializer::class);
Assert::that($serializer)
->isObject()
->isInstanceOf(Serializer::class);
// Tightly coupled
Assert::that($logger)->isInstanceOf(MonologLogger::class);
// Depends on interface
Assert::that($logger)->isInstanceOf(LoggerInterface::class);
Assert::that($handler)
->isObject()
->isInstanceOf(HandlerInterface::class)
->methodExists('handle');