I have an application which is built on top of another framework. Said framework has a number of value objects, which I need to extend in various ways using the decorator pattern. Lets call the base object Entity and the decorator classes Wrappers. Entities of the same class can have different "types", and a different Wrapper class is required for each of these types to expose functionality specific to that type. This application is not the final layer and does not control what types exist or which classes to use for them (done higher up the chain), so assignment needs to be dynamic.
I have created a factory class that receives an entity and determines the correct wrapper for it. The factory can be assigned a Wrapper class to be used when the entity is of a given type.
<?php
class WrapperFactory
{
protected $default_wrapper = null;
protected $typed_wrappers = [];
public function __construct($default){
$this->setDefaultWrapper($default);
}
public function setDefaultWrapper($class){
if ($this->validateWrapperClass($class)){
$default_wrapper = $class;
}
}
public function getDefaultWrapper(){
return $this->$default_wrapper;
}
public function setWrapperForType($class, $type){
if($this->validateWrapperClass($class)){
$this->$typed_wrappers[$type] = $class;
}
}
public function hasWrapperForType($type){
return array_key_exists($type, $this->typed_wrappers);
}
public function getWrapperForType($type){
if($this->hasWrapperForType($type)){
return $this->typed_wrappers[$type];
}
else{
return $this->getDefaultWrapper();
}
}
public function wrap($entity)
{
$class = $this->getWrapperForType($entity->type);
return new $class($entity);
}
protected function validateWrapperClass($class){
if(class_exists($class) && class_implements($class, WrapperInterface::class)){
return true;
}else{
throw new BadMethodCallException("Wrapper must implement ". WrapperInterface::class . ".");
}
}
}
I'm not entirely sure how to properly Unit Test this class. Is there a way I can mock a class that implements the interface, rather than an object? how can I test that an class assigned to a type is working properly? Do I need to explicitly declare a dummy class or two in my test files or is there a way to mock them?
Aucun commentaire:
Enregistrer un commentaire