Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- abstract class AbstractBuilder
- {
- protected $data;
- public function __construct()
- {
- $this->data = $this->configureParameters();
- }
- public function build()
- {
- $reflector = new \ReflectionClass($this->getObjectFqcn());
- return $reflector->newInstanceArgs(array_values($this->data));
- }
- public function setValues(array $values)
- {
- foreach ($values as $key => $value) {
- $this->{$key} = $value;
- }
- return $this;
- }
- public function __set($name, $value)
- {
- if (!array_key_exists($name, $this->data)) {
- throw new \InvalidArgumentException(sprintf('Unknown property "%s" in "%s".', $name, get_class($this)));
- }
- $this->data[$name] = $value;
- }
- public function __get($name)
- {
- if (!array_key_exists($name, $this->data)) {
- throw new \InvalidArgumentException(sprintf('Unknown property "%s" in "%s".', $name, get_class($this)));
- }
- return $this->data[$name];
- }
- public function __isset($name)
- {
- return array_key_exists($name, $this->data);
- }
- public function __call($name, array $arguments)
- {
- $property = lcfirst(substr($name, 3));
- if (strpos($name, 'set') !== 0 || !array_key_exists($property, $this->data)) {
- throw new \BadMethodCallException(sprintf('Unknown method "%s" in "%s".', $name, get_class($this)));
- }
- if (count($arguments) !== 1) {
- throw new \BadMethodCallException(sprintf('Method "%s" in "%s" expects exactly one parameter.', $name, get_class($this)));
- }
- $this->data[$property] = $arguments[0];
- return $this;
- }
- public static function createBuilder()
- {
- return new static();
- }
- /**
- * Configure builder parameters that will be passed to building class constructor.
- *
- * @return array
- */
- protected abstract function configureParameters();
- /**
- * Get full qualified class name of class that instance ought to be constructed.
- *
- * @return string
- */
- protected abstract function getObjectFqcn();
- }
- // EXAMPLE - creating a builder that builds instance of "Response" class
- /**
- * Class ResponseBuilder
- *
- * @method setId($id)
- * @method setToken($token)
- * @method setResponseCode($responseCode)
- * @method setResponseAction($responseAction)
- * @method setErrorReason($errorReason)
- * @method setTimestamp($timestamp)
- *
- * @package Syntech\Swarm\Handler\Apns\Builder
- */
- final class ResponseBuilder extends AbstractBuilder
- {
- /**
- * Get builded response.
- *
- * @return Response
- */
- public function getResponse()
- {
- return $this->build();
- }
- /**
- * {@inheritdoc}
- */
- protected function configureParameters()
- {
- return array(
- 'id' => null,
- 'token' => null,
- 'responseCode' => null,
- 'responseAction' => null,
- 'errorReason' => null,
- 'timestamp' => null
- );
- }
- /**
- * {@inheritdoc}
- */
- protected function getObjectFqcn()
- {
- return Response::class;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment