/**
  * Parse each product in the response and add it to the rich response.
  *
  * @param SearchResponse $searchResponse
  * @param array $body
  */
 protected function parseProducts(SearchResponse $searchResponse, array $body)
 {
     $factory = new SearchProductFactory();
     $searchResponse->setSearchProducts(Std::map(function ($rawProduct) use($factory) {
         return $factory->makeFromArray($rawProduct);
     }, Arr::dotGet($body, 'searchCatalogs.result', [])));
 }
 /**
  * Combine all the elements in the traversable using a combining operation.
  *
  * @param callable|Closure $closure
  * @param mixed $initial
  *
  * @return mixed
  */
 public function foldlWithKey(callable $closure, $initial)
 {
     $accumulator = $initial;
     foreach ($this->value as $key => $value) {
         $accumulator = Std::call($closure, $accumulator, $value, $key);
     }
     return $accumulator;
 }
 /**
  * @param string $text
  *
  * @return ListItem
  */
 protected function renderNextButton($text = null)
 {
     $content = Std::coalesce($text, Html::safe('»'));
     if (!$this->paginator->hasMorePages()) {
         return $this->getDisabledPageWrapper($content);
     }
     return $this->getPageWrapper($content, $this->paginator->url($this->paginator->currentPage() + 1));
 }
Example #4
0
 public function testCoalesce()
 {
     $this->assertEquals('doge', Std::coalesce('doge'));
     $this->assertEquals('doge', Std::coalesce(null, 'doge'));
     $this->assertEquals('doge', Std::coalesce(null, null, 'doge'));
     $this->assertEquals('doge', Std::coalesce(null, null, 'doge', 'dolan'));
     $this->assertEquals('gopher', Std::coalesce('gopher', null, 'doge'));
     $this->assertNull(Std::coalesce());
 }
Example #5
0
 /**
  * Render the object into a string.
  *
  * @return mixed
  */
 public function render()
 {
     return (new Table(['class' => 'table'], [new TableHeader([], new TableRow([], Std::map(function ($columnLabel) {
         return new TableHeaderCell([], $columnLabel);
     }, $this->headerLabels))), new TableBody([], Std::map(function ($row) {
         return new TableRow([], Std::map(function ($cell) {
             return new TableCell([], $cell);
         }, $row));
     }, $this->rows))]))->render();
 }
 /**
  * Generate a URL for a path inside the dashboard.
  *
  * @param string $path
  * @param array $parameters
  * @param null|bool $secure
  *
  * @return string
  */
 public function url($path = '', $parameters = [], $secure = null)
 {
     $queryString = '';
     if (count($parameters)) {
         $queryString = '?' . implode('&', Std::map(function ($value, $name) {
             return urlencode($name) . '=' . urlencode($value);
         }, $parameters));
     }
     return url($this->basePath . $path, [], $secure) . $queryString;
 }
 /**
  * Parse category mappings.
  *
  * @param GetAsinCategoriesResponse $categoriesResponse
  * @param array $body
  */
 protected function parseMappings(GetAsinCategoriesResponse $categoriesResponse, array $body)
 {
     $factory = new CategoryMappingFactory();
     $categoriesResponse->setCategoryMappings(Std::map(function ($rawMapping) use($factory, $categoriesResponse) {
         $mapping = $factory->makeFromArray($rawMapping);
         if ($mapping->isMainCategory()) {
             $categoriesResponse->setMainCategory($mapping);
         }
         return $mapping;
     }, $body['categoryMappings']));
 }
 /**
  * Build an instance of an Impersonator included common dependencies
  * defined in the map returned by getCommonProvisions().
  *
  * @return Impersonator
  * @throws LackOfCoffeeException
  */
 public function impersonatorWithCommon()
 {
     $impersonator = $this->impersonator();
     Std::map(function ($value, $key) use($impersonator) {
         if (is_array($value) || $value instanceof Closure) {
             $impersonator->mock($key, $value);
             return;
         }
         $impersonator->provide($value);
     }, $this->getCommonProvisions());
     return $impersonator;
 }
 /**
  * Get all migrations.
  *
  * @param StructuredStatusInterface $status
  *
  * @return Card
  */
 public function getAll(StructuredStatusInterface $status)
 {
     $report = $status->generateReport();
     $idle = $report->getIdle();
     $unknown = $report->getUnknown();
     $ran = $report->getRan();
     return new Card([], [new CardHeader([], 'All Migrations'), new SimpleTable(['-', 'Status', 'Name'], Std::map(function ($name) use($idle, $unknown, $ran) {
         if (in_array($name, $idle)) {
             return [new Italic(['class' => ['fa', 'fa-circle-o', 'text-warning']]), 'Pending', $name];
         } elseif (in_array($name, $unknown)) {
             return [new Italic(['class' => ['fa', 'fa-times-circle', 'text-danger']]), 'Exotic', $name];
         } elseif (in_array($name, $ran)) {
             return [new Italic(['class' => ['fa', 'fa-check-circle', 'text-success']]), 'Ran', $name];
         }
         return [new Italic(['class' => ['fa', 'fa-circle-o']]), '???', $name];
     }, Std::concat($report->getMigrations(), $report->getUnknown())))]);
 }
Example #10
0
 /**
  * Determine if some value fits inside a database column.
  *
  * Right now this check is limited to string values. Future versions might
  * support binary data and numbers as well.
  *
  * @param mixed $content
  * @param string $type
  * @param null $length
  *
  * @throws \Chromabits\Nucleus\Exceptions\LackOfCoffeeException
  * @return bool
  */
 public static function fits($content, $type, $length = null)
 {
     switch ($type) {
         case static::TYPE_CHAR:
         case static::TYPE_VARCHAR:
             return Std::within(0, Std::coalesce($length, 255), strlen($content));
         case static::TYPE_TINYTEXT:
             return Std::within(0, Std::coalesce($length, 2 ** 8), strlen($content));
         case static::TYPE_TEXT:
             return Std::within(0, Std::coalesce($length, 2 ** 16), strlen($content));
         case static::TYPE_MEDIUMTEXT:
             return Std::within(0, Std::coalesce($length, 2 ** 24), strlen($content));
         case static::TYPE_LONGTEXT:
             return Std::within(0, Std::coalesce($length, 2 ** 32), strlen($content));
     }
     throw new LackOfCoffeeException('Not implemented.');
 }
Example #11
0
 /**
  * Multibyte version of ucwords().
  *
  * @param string $str
  * @param string $delimiters
  * @param null|string $encoding
  *
  * @return mixed|string
  */
 function mb_ucwords($str, $delimiters = " \t\r\n\f\v", $encoding = null)
 {
     $encoding = Std::coalesce($encoding, mb_internal_encoding());
     $delimitersArray = mb_str_split($delimiters, 1, $encoding);
     $upper = true;
     $result = '';
     for ($ii = 0; $ii < mb_strlen($str, $encoding); $ii++) {
         $char = mb_substr($str, $ii, 1, $encoding);
         if ($upper) {
             $char = mb_convert_case($char, MB_CASE_UPPER, $encoding);
             $upper = false;
         } elseif (ArrayList::of($delimitersArray)->includes($char)) {
             $upper = true;
         }
         $result .= $char;
     }
     return $result;
 }
Example #12
0
 /**
  * Render the object into a string.
  *
  * @return mixed
  */
 public function render()
 {
     return new Div([], Std::map(function (Alert $alert) {
         $classes = ['alert'];
         switch ($alert->getType()) {
             case Alert::TYPE_SUCCESS:
                 $classes[] = 'alert-success';
                 break;
             case Alert::TYPE_WARNING:
                 $classes[] = 'alert-warning';
                 break;
             case Alert::TYPE_INFO:
                 $classes[] = 'alert-info';
                 break;
             case Alert::TYPE_ERROR:
                 $classes[] = 'alert-danger';
                 break;
         }
         return new Div(['class' => $classes], $alert->getContent());
     }, $this->alerts));
 }
Example #13
0
 public function benchMap()
 {
     Std::map(function ($value, $key) {
         return $value . ' ' . $key;
     }, $this->keyValueArray);
 }
Example #14
0
 public function testGetSpec()
 {
     $spec = $this->makeTaskSafely()->getSpec();
     $this->assertTrue(Std::truthy($spec === null, $spec instanceof Spec));
 }
Example #15
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);
 }
 /**
  * Render a table showing jobs.
  *
  * @param Paginator $jobs
  *
  * @return mixed
  */
 protected function renderJobsTable(Paginator $jobs)
 {
     return Std::firstBias(count($jobs->items()) > 0, function () use($jobs) {
         return new SimpleTable(['ID', 'Task', 'State', 'Runs', 'Created At', 'Duration'], Std::map(function (Job $job) {
             return [$job->id, $job->state, $job->task, $job->attempts, $job->created_at->toDayDateTimeString(), $job->getExecutionTime()];
         }, $jobs->items()));
     }, function () {
         return new CardBlock(['class' => 'card-block text-center'], [new Paragraph([], [new Italic(['class' => 'fa fa-4x fa-search text-light'])]), 'No jobs found matching the specified criteria.']);
     });
 }
Example #17
0
 /**
  * Turn request examples to a RAML message body.
  *
  * @param Request[] $requests
  *
  * @return RamlMessageBody
  */
 protected function requestsToBody($requests)
 {
     return Std::foldl(function (RamlMessageBody $messageBody, Request $request) {
         return $messageBody->addType($request->headers->get('content-type'), (new RamlBody())->setExample($request->getContent()));
     }, new RamlMessageBody(), $requests);
 }
Example #18
0
 /**
  * Get an array representation of this object.
  *
  * @return array
  */
 public function toArray()
 {
     return RamlUtils::filterEmptyValues(['example' => $this->example, 'schema' => $this->schema, 'formParameters' => Std::map(function (RamlParameter $parameter) {
         return $parameter->toArray();
     }, $this->formParameters)]);
 }
 /**
  * Get list of services provided.
  *
  * @throws LackOfCoffeeException
  * @return array
  */
 public function provides()
 {
     return Std::concat(Arr::keys($this->getServiceMap()), Arr::keys($this->getSingletons()));
 }
Example #20
0
 /**
  * Generate an authorization code for the Research API server.
  *
  * @param null|integer $timestamp
  *
  * @return string
  */
 public function generateCode($timestamp = null)
 {
     Arguments::contain(Boa::either(Boa::null(), Boa::integer()))->check($timestamp);
     $timestamp = Std::coalesce($timestamp, time() + 3600 * 3);
     $signature = md5(implode('', [$timestamp, $this->clientId, $this->secret]));
     return vsprintf('%s|%s|%s', [$timestamp, $this->clientId, $signature]);
 }
Example #21
0
 /**
  * Construct an instance of a ClosureConstraint.
  *
  * @param Closure $closure
  * @param string|null $description
  */
 public function __construct(Closure $closure, $description = null)
 {
     parent::__construct();
     $this->closure = $closure;
     $this->description = Std::coalesce($description, 'The value is expected to meet the constraint.');
 }
 /**
  * Get problematic modules.
  *
  * @param DashboardInterface $dashboard
  *
  * @return Div
  */
 public function getIssues(DashboardInterface $dashboard)
 {
     $exceptions = Std::map(function (Exception $exception, $moduleName) {
         return new Div([], [new Div(['class' => 'card card-inverted'], [new CardBlock([], [new HeaderSix(['class' => 'text-muted'], $moduleName), new Bold([], get_class($exception) . ': '), $exception->getMessage(), new Div(['class' => 'collapse p-t', 'id' => 'stack'], new PreformattedText(['class' => 'pre-scrollable'], $exception->getTraceAsString()))]), new Div(['class' => 'card-footer text-muted'], [new Row([], [new Column(['medium' => 6], [basename($exception->getFile()) . ':' . $exception->getLine()]), new Column(['medium' => 6, 'class' => 'text-xs-right'], new Button(['href' => '#', 'class' => ['btn', 'btn-sm', 'btn-primary-outline'], 'data-toggle' => 'collapse', 'data-target' => '#stack', 'aria-expanded' => 'false', 'aria-controls' => '#stack'], 'Toggle stacktrace'))])])])]);
     }, $dashboard->getFailedModules());
     return new Div([], [new Div(['class' => 'card'], [new Div(['class' => 'card-header'], 'Module issues'), new Div(['class' => 'card-block'], ['Below you will find a list of all the modules that ', 'failed to load. If one or more failed to load, it is ', 'not necessarily a bad thing. If you do not intend to ', 'use the component covered by the module, you may ', 'safely ignore it.'])]), new HorizontalLine([]), new Div([], Std::firstBias(count($dashboard->getFailedModules()) > 0, $exceptions, function () {
         return new Card(['class' => 'card card-block text-center'], ['All modules seem fine!']);
     }))]);
 }
Example #23
0
 /**
  * Generate the model.
  *
  * @throws LackOfCoffeeException
  * @return Model
  */
 public function make()
 {
     // Make model instance
     $model = $this->getModelInstance(true);
     $filling = TransformPipeline::define()->inline(function ($input) {
         return array_merge($input, $this->overrides);
     })->inline(function ($input) {
         return Std::map(function ($value) {
             return Std::value($value);
         }, $input);
     })->run($this->getMapping());
     Std::each(function ($value, $key) use(&$model) {
         $model->{$key} = $value;
     }, $filling);
     Std::each(function ($relation, $name) use(&$model) {
         if (!$this->isBelongsTo($name)) {
             return;
         }
         $model->{$name}()->associate($this->generateRelation($name));
     }, $this->relations);
     $model->save();
     Std::each(function ($relation, $name) use(&$model) {
         if ($this->isBelongsTo($name)) {
             return;
         }
         $related = $this->generateRelation($name);
         if (is_array($related)) {
             $model->{$name}()->saveMany($related);
         } else {
             $model->{$name}()->save($related);
         }
     }, $this->relations);
     return $model;
 }
 /**
  * Check the given plain value against a hash.
  *
  * @param string $value
  * @param string $hashedValue
  * @param array $options
  *
  * @return bool
  */
 public function check($value, $hashedValue, array $options = [])
 {
     // First, we are optimistic and try to use the target hasher.
     if ($this->targetHasher->check($value, $hashedValue, $options)) {
         return true;
     }
     // Otherwise, we attempt to check if it passes any supported hasher.
     $match = false;
     Std::each(function (Hasher $hasher) use($value, $hashedValue, $options, &$match) {
         if ($hasher->check($value, $hashedValue, $options)) {
             $match = true;
         }
     }, $this->supportedHashers);
     return $match;
 }
Example #25
0
 /**
  * Check that a certain input passes the spec.
  *
  * @param mixed $input
  *
  * @return SpecResult
  */
 public function check(array $input)
 {
     $missing = [];
     $invalid = [];
     $check = function ($constraint, $key, $value, $input) use(&$missing, &$invalid) {
         if ($constraint instanceof AbstractConstraint) {
             if (!$constraint->check($value, $input)) {
                 $invalid[$key][] = $constraint;
             }
         } elseif ($constraint instanceof CheckableInterface) {
             $result = $constraint->check($value);
             $missing = Std::concat($missing, array_map(function ($subKey) use($key) {
                 return vsprintf('%s.%s', [$key, $subKey]);
             }, $result->getMissing()));
             foreach ($result->getFailed() as $failedField => $constraints) {
                 $fullPath = vsprintf('%s.%s', [$key, $failedField]);
                 if (array_key_exists($fullPath, $invalid)) {
                     $invalid[$fullPath] = array_merge($invalid[$fullPath], $constraints);
                 } else {
                     $invalid[$fullPath] = $constraints;
                 }
             }
         } else {
             throw new CoreException(vsprintf('Unexpected constraint type: %s.', [TypeHound::fetch($constraint)]));
         }
     };
     $inputMap = ArrayMap::of($input);
     $this->annotations->each(function ($value, $key) use($check, $input, $inputMap, &$missing) {
         // If a field is required but not present, we should report it.
         if (Maybe::fromMaybe(false, $value->lookup(static::ANNOTATION_REQUIRED)) && $inputMap->member($key) === false) {
             $missing[] = $key;
             // There's no point on checking constraints on the field
             // since it is missing.
             return;
         } elseif ($inputMap->member($key) === false) {
             // There's no point on checking constraints on the field
             // since it is missing.
             return;
         }
         $fieldValue = Maybe::fromJust($inputMap->lookup($key));
         $this->getInternalFieldConstraints($key)->each(function ($constraint) use($check, $key, $fieldValue, $input) {
             $check($constraint, $key, $fieldValue, $input);
         });
     });
     if (count($missing) === 0 && count($invalid) === 0) {
         return new SpecResult($missing, $invalid, SpecResult::STATUS_PASS);
     }
     return new SpecResult($missing, $invalid, SpecResult::STATUS_FAIL);
 }
 /**
  * Render the object into a string.
  *
  * @return mixed
  */
 public function render()
 {
     return Std::firstBias($this->paginator->hasPages(), function () {
         return new CardBlock(['class' => 'card-block text-center'], new BootstrapFourPaginatorPresenter($this->paginator));
     }, '');
 }
 /**
  * Render all router patterns.
  *
  * @param Router $router
  *
  * @return Table
  */
 protected function renderPatterns(Router $router)
 {
     return new Table(['class' => 'table'], [new TableHeader([], new TableRow([], [new TableHeaderCell([], 'Key'), new TableHeaderCell([], 'Pattern')])), new TableBody([], Std::map(function ($pattern, $key) {
         return new TableRow([], [new TableCell([], $key), new TableCell([], new PreformattedText(['class' => 'pre-scrollable'], $pattern))]);
     }, $router->getPatterns()))]);
 }
Example #28
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 #29
0
 /**
  * @param ApplyInterface $other
  *
  * @return ApplyInterface
  */
 public function ap(ApplyInterface $other)
 {
     $this->assertSameType($other);
     $result = [];
     Std::poll(function ($ii) use(&$result, &$other) {
         Std::poll(function ($jj) use(&$result, &$other, $ii) {
             $result[] = Std::call($this->value[$ii], $other->value[$jj]);
         }, count($other->value));
     }, count($this->value));
     return $result;
 }
Example #30
0
 /**
  * A shortcut for fast-and-easy API calls: If the provided Spec result is
  * invalid, then a validation response is sent, otherwise the result of
  * the provided callback is sent.
  *
  * @param SpecResult $result
  * @param Closure $onSuccess
  *
  * @deprecated Use ApiCheckableRequests
  * @return mixed
  */
 public static function flow(SpecResult $result, Closure $onSuccess)
 {
     return Std::firstBias($result->failed(), function () use($result) {
         return self::makeFromSpec($result)->toResponse();
     }, $onSuccess);
 }