Example #1
0
 public function testCheckWithFailedConstraints()
 {
     $spec = TypedSpec::define()->withFieldType('first_name', Boa::string())->withFieldConstraints('first_name', new StringLengthConstraint(4))->withFieldType('age', Boa::integer());
     $result = $spec->check(['first_name' => 'Ed', 'age' => 23]);
     $this->assertTrue($result->failed());
     $this->assertEquals(['first_name'], array_keys($result->getFailed()));
 }
 /**
  * Construct an instance of a ResourceMethod.
  *
  * @param string $method
  * @param string $verb
  * @param string $path
  */
 public function __construct($method, $verb, $path)
 {
     parent::__construct();
     Arguments::contain(Boa::string(), Boa::string(), Boa::string())->check($method, $verb, $path);
     $this->method = $method;
     $this->verb = $verb;
     $this->path = $path;
 }
Example #3
0
 /**
  * Register a module with this dashboard.
  *
  * @param string $moduleClassName
  *
  * @throws CoreException
  * @throws InvalidArgumentException
  */
 public function register($moduleClassName)
 {
     Arguments::contain(Boa::string())->check($moduleClassName);
     $instance = $this->application->make($moduleClassName);
     if (!$instance instanceof Module) {
         throw new InvalidArgumentException('The provided class should extend the Module class.');
     }
     try {
         $instance->boot();
         $this->modules[$instance->getName()] = $instance;
     } catch (Exception $e) {
         $this->failedModules[$instance->getName()] = $e;
     }
 }
 /**
  * Construct an instance of a StringLengthConstraint.
  *
  * @param int $min
  * @param int $max
  *
  * @throws InvalidArgumentException
  */
 public function __construct($min = 0, $max = -1)
 {
     parent::__construct();
     Arguments::define(Boa::integer(), Boa::integer())->check($min, $max);
     if ($min < 0) {
         throw new InvalidArgumentException('The minimum length is expected to be >= 0.');
     }
     if ($max != -1 && $max < $min || $max < -1) {
         throw new InvalidArgumentException('
             The maximum length is expected to be: (== -1 || >= minimum) &&' . ' >= -1.');
     }
     $this->min = $min;
     $this->max = $max;
 }
Example #5
0
 /**
  * Run the flick on input.
  *
  * @param string|int $input
  *
  * @throws UnknownKeyException
  * @return mixed
  */
 public function go($input)
 {
     Arguments::define(Boa::readMap())->define($input);
     $map = ComplexFactory::toReadMap($this->functions);
     if ($map->member($input)) {
         /** @var callable $function */
         $function = Maybe::fromJust($map->lookup($input));
         return $function();
     } elseif ($map->member($this->default)) {
         /** @var callable $function */
         $function = Maybe::fromJust($map->lookup($this->default));
         return $function();
     }
     throw new UnknownKeyException();
 }
Example #6
0
 /**
  * Escape the provided string.
  *
  * @param SafeHtmlWrapper|SafeHtmlProducerInterface|string $string
  *
  * @throws CoreException
  * @throws InvalidArgumentException
  * @return SafeHtmlWrapper|string
  */
 public static function escape($string)
 {
     Arguments::define(Boa::either(Boa::either(Boa::instance(SafeHtmlWrapper::class), Boa::instance(SafeHtmlProducerInterface::class)), Boa::string()))->check($string);
     if ($string instanceof SafeHtmlWrapper) {
         return $string;
     } elseif ($string instanceof SafeHtmlProducerInterface) {
         $result = $string->getSafeHtml();
         if ($result instanceof SafeHtmlWrapper) {
             return $result;
         } elseif ($result instanceof SafeHtmlProducerInterface) {
             return static::escape($result);
         }
         throw new CoreException(vsprintf('Object of class %s implements SafeHtmlProducerInterface' . ' but it returned an unsafe type: %s', [get_class($string), TypeHound::fetch($result)]));
     }
     return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
 }
Example #7
0
 /**
  * Add a offer to the response.
  *
  * @param string $type
  * @param string $condition
  * @param Offer $offer
  *
  * @throws InvalidArgumentException
  */
 public function addOffer($type, $condition, Offer $offer)
 {
     Arguments::contain(Boa::in(OfferType::getValues()), Boa::in(OfferCondition::getValues()), Boa::instance(Offer::class))->check($type, $condition, $offer);
     if ($type === OfferType::TYPE_FBA) {
         if ($condition === OfferCondition::CONDITION_NEW) {
             $this->fbaNewOffers[] = $offer;
         } elseif ($condition === OfferCondition::CONDITION_USED) {
             $this->fbaUsedOffers[] = $offer;
         }
     } elseif ($type === OfferType::TYPE_MERCHANT_FULFILLED) {
         if ($condition === OfferCondition::CONDITION_NEW) {
             $this->merchantNewOffers[] = $offer;
         } elseif ($condition === OfferCondition::CONDITION_USED) {
             $this->merchantUsedOffers[] = $offer;
         }
     }
 }
Example #8
0
 public function testComplexSpec()
 {
     $graph = new SpecGraph();
     $graph->add('input', [], Spec::define(['sleepy' => Boa::boolean(), 'tennis_balls' => Boa::integer(), 'message' => Boa::either(Boa::string(), Boa::integer())], [], ['message']));
     $graph->add('allowedMessage', ['input'], Spec::define(['message' => [Boa::in(['hi', 'how are you?', 'you dumb']), Boa::in(['hi', 'how are you?', 'you are smart'])]], [], ['message']));
     $graph->add('validBallCount', ['input'], Spec::define(['tennis_balls' => Boa::between(1, 10)]));
     $graph->add('additionalBallProps', ['validBallCount'], Spec::define(['ball_color' => [Boa::string(), Boa::in(['blue', 'red', 'yellow'])]], [], ['ball_color']));
     $result = $graph->check(['sleepy' => true, 'tennis_balls' => 3, 'message' => 'hi', 'ball_color' => 'blue']);
     $this->assertTrue($result->passed());
     $result2 = $graph->check(['sleepy' => 1, 'tennis_balls' => 3]);
     $this->assertEqualsMatrix([[true, $result2->failed()], [1, count($result2->getFailed())], [['message'], $result2->getMissing()]]);
     $result3 = $graph->check(['sleepy' => true, 'tennis_balls' => -30, 'message' => 'hello']);
     $this->assertEqualsMatrix([[true, $result3->failed()], [2, count($result3->getFailed())], [[], $result3->getMissing()]]);
     $result4 = $graph->check(['sleepy' => true, 'tennis_balls' => 3, 'message' => 'how are you?']);
     $this->assertEqualsMatrix([[true, $result4->failed()], [0, count($result4->getFailed())], [['ball_color'], $result4->getMissing()]]);
     $result5 = $graph->check(['sleepy' => true, 'tennis_balls' => 3, 'message' => 'how are you?', 'ball_color' => 'liquid_gold']);
     $this->assertEqualsMatrix([[true, $result5->failed()], [1, count($result5->getFailed())], [[], $result5->getMissing()]]);
 }
Example #9
0
 /**
  * Get a copy of the provided array excluding the specified values.
  *
  * @param array $input
  * @param array $excluded
  *
  * @return array
  * @throws InvalidArgumentException
  */
 public static function exceptValues(array $input, $excluded = [])
 {
     Arguments::define(Boa::arrOf(Boa::either(Boa::string(), Boa::integer())))->check($excluded);
     return Std::filter(function ($value, $_) use($excluded) {
         return !in_array($value, $excluded);
     }, $input);
 }
Example #10
0
 /**
  * Add a custom message for a field.
  *
  * @param $field
  * @param $message
  *
  * @throws InvalidArgumentException
  * @return $this
  */
 public function message($field, $message)
 {
     Arguments::define(Boa::string(), Boa::string())->check($field, $message);
     $this->messages[$field] = $message;
     return $this;
 }
Example #11
0
 /**
  * @return PrimitiveTypeConstraint
  */
 public function getKeyType()
 {
     return Boa::integer();
 }
Example #12
0
 /**
  * Set the new status for this response.
  *
  * @param string $newStatus
  *
  * @throws InvalidArgumentException
  */
 public function setStatus($newStatus)
 {
     Arguments::contain(Boa::in($this->getValidStatuses()))->check($newStatus);
     $this->status = $newStatus;
 }
Example #13
0
 /**
  * @param RamlParameter[] $formParameters
  *
  * @return RamlBody
  */
 public function setFormParameters($formParameters)
 {
     Arguments::define(Boa::arrOf(Boa::instance(RamlParameter::class)))->check($formParameters);
     $new = clone $this;
     $new->formParameters = $formParameters;
     return $new;
 }
Example #14
0
 /**
  * Wrap the provided value inside a Map.
  *
  * @param array|ArrayObject|ArrayAccess|MapInterface $input
  *
  * @return ArrayAccessMap|ArrayList
  * @throws CoreException
  * @throws InvalidArgumentException
  */
 public static function toMap($input)
 {
     Arguments::define(Boa::map())->check($input);
     if ($input instanceof MapInterface) {
         return $input;
     }
     if (is_array($input) || $input instanceof ArrayObject) {
         return new ArrayMap($input);
     }
     if ($input instanceof ArrayAccess) {
         return new ArrayAccessMap($input);
     }
     throw new CoreException('Unable to build Map');
 }
Example #15
0
 /**
  * Add one or more fields to the list of fields that are required.
  *
  * @param string|string[] $fields
  *
  * @throws InvalidArgumentException
  * @return $this
  */
 public function required($fields)
 {
     Arguments::define(Boa::either(Boa::string(), Boa::arrOf(Boa::string())))->check($fields);
     if (!is_array($fields)) {
         $fields = [$fields];
     }
     $this->required = $this->required->append(ArrayList::of($fields));
     return $this;
 }
Example #16
0
 /**
  * Set a relationship of the model explicitly.
  *
  * @param string $relationName
  * @param Model|Model[] $related
  *
  * @throws LackOfCoffeeException
  * @throws InvalidArgumentException
  * @return $this
  */
 public function withFixed($relationName, $related)
 {
     $inspector = $this->getInspector($this->getModelInstance());
     $relation = $inspector->getRelation($relationName);
     $relationModelClass = get_class($relation->getRelated());
     Arguments::contain(Boa::string(), Boa::either(Boa::instance($relationModelClass), Boa::arrOf(Boa::instance($relationModelClass))))->check($relationName, $related);
     $this->relations[$relationName] = $relation;
     $this->relationsGenerators[$relationName] = $related;
     return $this;
 }
 /**
  * Construct an instance of a AtLeastOneOfConstraint.
  *
  * @param array $fields
  */
 public function __construct(array $fields)
 {
     parent::__construct();
     Arguments::define(Boa::arrOf(Boa::string()))->check($fields);
     $this->fields = $fields;
 }
 /**
  * @param string $prefix
  *
  * @return $this
  */
 public function withPrefix($prefix)
 {
     Arguments::define(Boa::string())->check($prefix);
     $this->prefix = $prefix;
     return $this;
 }
Example #19
0
 /**
  * Generate a hash of the content using the provided private key.
  *
  * @param string $content
  * @param string $privateKey
  *
  * @return string
  */
 public function hash($content, $privateKey)
 {
     Arguments::define(Boa::string(), Boa::string())->check($content, $privateKey);
     return hash_hmac($this->algorithm, $content, $privateKey);
 }
 /**
  * @inheritDoc
  */
 public function getSpec()
 {
     return Spec::define(['days' => Boa::integer(), 'repeat_in' => Boa::integer(), 'expire_after' => Boa::integer()], ['days' => 30, 'repeat_in' => -1, 'expire_after' => 1440]);
 }
Example #21
0
 /**
  * Set the HTTP method using the request.
  *
  * @param $method
  *
  * @throws InvalidArgumentException
  * @return $this
  */
 public function usingMethod($method)
 {
     Arguments::contain(Boa::in(HttpMethods::getValues()))->check($method);
     $this->method = $method;
     return $this;
 }
Example #22
0
 /**
  * @return AbstractTypeConstraint
  */
 public function getValueType()
 {
     // TODO: Figure out how to make this nicer.
     return Boa::any();
 }
Example #23
0
 /**
  * Get a category by ID
  *
  * @param string $categoryId
  *
  * @return GetCategoryByIdResponse
  */
 public function getCategoryById($categoryId)
 {
     Arguments::contain(Boa::string())->check($categoryId);
     return (new CategoryResponseFactory())->makeFromResponse($this->client->get(vsprintf('/v1/getCategoryById/%s', [$categoryId])));
 }
Example #24
0
 /**
  * Check if the constraint is met.
  *
  * @param mixed $value
  * @param array $context
  *
  * @return mixed
  */
 public function check($value, array $context = [])
 {
     return Std::falsy(Boa::string()->check($value, $context), (new RegexConstraint('/^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/'))->check($value, $context));
 }
Example #25
0
 /**
  * Get the type annotation for a field.
  *
  * @param string $fieldName
  *
  * @return AbstractTypeConstraint
  */
 public function getFieldType($fieldName)
 {
     return Maybe::fromMaybe(Boa::any(), $this->getFieldAnnotation($fieldName, static::ANNOTATION_TYPE));
 }
Example #26
0
 /**
  * Attempt call the provided function a number of times until it no longer
  * throws an exception.
  *
  * @param callable $function
  * @param int $attempts
  *
  * @return mixed|null
  * @throws InvalidArgumentException
  */
 public static function retry(callable $function, $attempts)
 {
     Arguments::define(Boa::func(), Boa::integer())->check($function, $attempts);
     for ($ii = 0; $ii < $attempts; $ii++) {
         try {
             $result = static::call($function, $ii);
             return $result;
         } catch (Exception $e) {
             continue;
         }
     }
     return null;
 }
 public function testFireWithValidSpec()
 {
     $laravelJob = m::mock(LaravelJob::class);
     $laravelJob->shouldReceive('delete')->atLeast()->once();
     $job = new Job();
     $job->state = JobState::QUEUED;
     $job->data = json_encode(['omg' => false, 'why_not' => 'because']);
     $handler = $this->expectationsToMock(BaseTask::class, [$this->on('fire', [$job, m::type(JobSchedulerInterface::class)]), $this->on('getSpec', [], Spec::define(['omg' => Boa::boolean()], ['yes' => 'please'], ['why_not'])), $this->on('isSelfDeleting', [], false)]);
     $impersonator = new Impersonator();
     $impersonator->mock(JobRepositoryInterface::class, function (MockInterface $mock) use($job) {
         $mock->shouldReceive('find')->with(1337)->atLeast()->once()->andReturn($job);
         $mock->shouldReceive('started')->with($job, m::type('string'))->atLeast()->once();
         $mock->shouldReceive('complete')->with($job)->atLeast()->once();
     });
     $impersonator->mock(HandlerResolverInterface::class, function (MockInterface $mock) use($job, $handler) {
         $mock->shouldReceive('resolve')->with($job)->atLeast()->once()->andReturn($handler);
     });
     /** @var RunTaskCommand $command */
     $command = $impersonator->make(RunTaskCommand::class);
     $command->fire($laravelJob, ['job_id' => 1337]);
 }
Example #28
0
 /**
  * @param string $type
  *
  * @return RamlParameter
  */
 public function setType($type)
 {
     Arguments::define(Boa::in(RamlTypes::getValues()))->check($type);
     $new = clone $this;
     $new->type = $type;
     return $new;
 }
Example #29
0
 /**
  * Get an array with only the specified keys of the provided array.
  *
  * @param array|null $included
  *
  * @return static
  */
 public function only($included = [])
 {
     Arguments::define(Boa::either(Boa::arrOf(Boa::either(Boa::string(), Boa::integer())), Boa::null()))->check($included);
     if (is_null($included)) {
         return $this;
     }
     if (count($included) == 0) {
         return static::zero();
     }
     return static::of(array_intersect_key($this->value, array_flip($included)));
 }
Example #30
0
 /**
  * Construct an instance of a OnlyTransform.
  *
  * @param array $allowed
  */
 public function __construct(array $allowed)
 {
     parent::__construct();
     Arguments::define(Boa::arrOf(Boa::string()))->check($allowed);
     $this->allowed = $allowed;
 }