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::define(Boa::string(), Boa::string(), Boa::string())->check($method, $verb, $path); $this->method = $method; $this->verb = $verb; $this->path = $path; }
/** * Register a module with this dashboard. * * @param string $moduleClassName * * @throws CoreException * @throws InvalidArgumentException */ public function register($moduleClassName) { Arguments::define(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; }
/** * 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(); }
/** * 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'); }
/** * 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; } } }
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()]]); }
/** * @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]); }
public function testRenderFieldWithOther() { $spec = (new FormSpec())->withFieldType('expire_at', Boa::instance(Carbon::class)); $presenter = new FormSpecPresenter($spec); $this->assertEquals((new Input(['id' => 'expire_at', 'class' => 'form-control', 'type' => 'text']))->render(), $presenter->renderField('expire_at')->render()); }
/** * 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; }
/** * 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'); }
/** * @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; }
/** * Set the HTTP method using the request. * * @param $method * * @throws InvalidArgumentException * @return $this */ public function usingMethod($method) { Arguments::define(Boa::in(HttpMethods::getValues()))->check($method); $this->method = $method; return $this; }
/** * 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); }
public function testAccessors() { $strings = Boa::string(); $spec = new Spec(['name' => $strings], ['name' => 'Bobby'], ['name']); $this->assertEqualsMatrix([[['name' => $strings], $spec->getConstraints()], [['name' => 'Bobby'], $spec->getDefaults()], [['name'], $spec->getRequired()]]); }
/** * A shortcut for building mocks. * * @param string $type * @param Closure|CallExpectation[] $definition * * @return $this */ public function mock($type, $definition) { Arguments::define(Boa::string(), Boa::either(Boa::func(), Boa::arrOf(Boa::instance(CallExpectation::class))))->check($type, $definition); if (is_array($definition)) { $this->provide(static::expectationsToMock($type, $definition)); return $this; } $this->provide(Mockery::mock($type, $definition)); return $this; }
/** * 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)); }
/** * @return PrimitiveTypeConstraint */ public function getKeyType() { return Boa::integer(); }
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 = m::mock(BaseTask::class); $handler->shouldReceive('fire')->with($job, m::type(JobSchedulerInterface::class))->atLeast()->once(); $handler->shouldReceive('getSpec')->andReturn(Spec::define(['omg' => Boa::boolean()], ['yes' => 'please'], ['why_not'])); $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]); }
/** * Set the new status for this response. * * @param string $newStatus * * @throws InvalidArgumentException */ public function setStatus($newStatus) { Arguments::define(Boa::in($this->getValidStatuses()))->check($newStatus); $this->status = $newStatus; }
/** * 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]))); }
/** * 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::define(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; }
/** * 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)); }
/** * 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; }
/** * 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; }
/** * @param string $prefix * * @return $this */ public function withPrefix($prefix) { Arguments::define(Boa::string())->check($prefix); $this->prefix = $prefix; return $this; }
/** * Get a model by its id. * * @param int $id * @param array $columns * @param array $with * * @throws InvalidArgumentException * @throws LackOfCoffeeException * @return Model */ public function getById($id, array $columns = ['*'], array $with = []) { Arguments::define(Boa::integer(), Boa::arrOf(Boa::string()), Boa::arrOf(Boa::string()))->check($id, $columns, $with); $query = $this->makeModelInstance()->query()->where('id', $id); $this->applyWith($query, $with); return $query->firstOrFail($columns); }
/** * @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; }
/** * @return AbstractTypeConstraint */ public function getValueType() { // TODO: Figure out how to make this nicer. return Boa::any(); }