/**
  * 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));
 }
Exemplo n.º 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());
 }
Exemplo n.º 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();
 }
 /**
  * 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']));
 }
Exemplo n.º 7
0
 /**
  * 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;
 }
 /**
  * Parse and build a rich response object from an HTTP response.
  *
  * @param ResponseInterface $response
  *
  * @return SubscriptionResponse
  * @throws CoreException
  */
 public function makeFromResponse(ResponseInterface $response)
 {
     $body = $this->parse($response);
     $subscriptionsResponse = new SubscriptionResponse();
     $subscriptionsResponse->setSubscriptions(Std::map(function ($s) {
         $subscription = new Subscription();
         // Maps from the new subscription format from SLAPP
         // to the legacy format.
         $subscription->fill(['id' => Arr::dotGet($s, 'stripe_plan.id'), 'plan_id' => $s['stripe_plan_id'], 'cycle_length' => sprintf('%s %s', Arr::dotGet($s, 'stripe_plan.interval_count'), Arr::dotGet($s, 'stripe_plan.interval')), 'created_at' => $s['current_period_start'], 'expires_at' => $s['current_period_end'], 'autorenew' => !$s['cancel_at_period_end'], 'cancelled_at' => $s['canceled_at'], 'status' => $s['status']]);
         return $subscription;
     }, Arr::dotGet($body, 'subscriptions', [])));
     return $subscriptionsResponse;
 }
Exemplo n.º 9
0
 /**
  * Get an environment variable or return the default if it is not defined.
  *
  * This avoid any post-processing, such as automatic casting.
  *
  * @param string $key
  * @param null|mixed|callable $default
  *
  * @return mixed|string
  */
 public static function getRaw($key, $default = null)
 {
     $env = ArrayMap::of($_ENV);
     $server = ArrayMap::of($_SERVER);
     if ($env->member($key)) {
         return Maybe::fromJust($env->lookup($key));
     } elseif ($server->member($key)) {
         return Maybe::fromJust($server->lookup($key));
     }
     $value = getenv($key);
     if ($value === false) {
         return Std::thunk($default);
     }
     return $value;
 }
Exemplo n.º 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 \SellerLabs\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.');
 }
 /**
  * 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())))]);
 }
Exemplo n.º 12
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;
 }
 /**
  * Report errors to the alerts manager and redirect to a page.
  *
  * @param CheckableInterface $check
  * @param CheckResultInterface $result
  */
 public function handleFailure(CheckableInterface $check, CheckResultInterface $result)
 {
     $response = $this->redirector->to($this->getRedirectUrl())->withInput($this->request->except($this->dontFlash));
     if (count($result->getFailed())) {
         if ($check instanceof Validator) {
             $messages = Std::map(function ($value) {
                 return implode(', ', $value);
             }, $result->getFailed());
             $this->pushValidationAlert($messages);
         } else {
             $this->pushValidationSpecAlert($result);
         }
     }
     if (count($result->getMissing())) {
         $this->pushMissingAlert($result->getMissing());
     }
     throw new HttpResponseException($response);
 }
Exemplo n.º 14
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:
             case Alert::TYPE_VALIDATION:
                 $classes[] = 'alert-danger';
                 break;
         }
         return new Div(['class' => $classes], $alert->getContent());
     }, $this->alerts));
 }
Exemplo n.º 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);
 }
 /**
  * @param Spec $spec
  * @param string $field
  *
  * @return TableRow
  */
 protected function renderConstraint(Spec $spec, $field)
 {
     $constraints = $spec->getConstraints();
     $defaults = $spec->getDefaults();
     $default = '';
     if (array_key_exists($field, $defaults)) {
         $default = $defaults[$field];
     }
     $constraint = $constraints[$field];
     if ($constraint instanceof AbstractConstraint) {
         return new TableRow([], [new TableCell([], $field), new TableCell([], $constraint->toString()), new TableCell([], (string) $default)]);
     }
     return new TableRow([], [new TableCell([], $field), new TableCell([], Std::map(function (AbstractConstraint $constraint) {
         return $constraint->toString() . ', ';
     }, $constraint)), new TableCell([], (string) $default)]);
 }
Exemplo n.º 17
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)]);
 }
Exemplo n.º 18
0
 /**
  * Map all the routes contained in every resource factory.
  *
  * @param Router $router
  *
  * @return Router
  */
 public function map(Router $router)
 {
     return Std::reduce(function (Router $router, ResourceFactory $factory) {
         return $factory->inject($router);
     }, $router, $this->getResources());
 }
Exemplo n.º 19
0
 /**
  * Check if the constraint is met.
  *
  * @param mixed $value
  * @param array $context
  *
  * @return bool
  */
 public function check($value, array $context = [])
 {
     return Std::truthy($this->one->check($value), $this->other->check($value));
 }
Exemplo n.º 20
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::thunk($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;
 }
Exemplo n.º 21
0
 /**
  * Execute the transform.
  *
  * @param array $input
  *
  * @return array
  */
 public function run(array $input)
 {
     return Std::call($this->inner, $input);
 }
Exemplo n.º 22
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);
 }
Exemplo n.º 23
0
 /**
  * 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));
     }, '');
 }
Exemplo n.º 24
0
 /**
  * Inject routes into the provided router.
  *
  * @param Router $router
  * @return Router
  */
 public function inject(Router $router)
 {
     $router->group(Arr::filterNullValues(['middleware' => $this->middleware, 'prefix' => $this->prefix]), function (Router $router) {
         Std::each(function (ResourceMethod $method) use($router) {
             $handler = vsprintf('%s@%s', [$this->controller, $method->getMethod()]);
             $router->match([$method->getVerb()], $method->getPath(), $handler);
         }, $this->methods);
     });
     return $router;
 }
Exemplo n.º 25
0
 /**
  * Run the input through the pipeline.
  *
  * @param array $input
  *
  * @return array
  */
 public function run(array $input)
 {
     return Std::foldl(function ($current, TransformInterface $input) {
         return $input->run($current);
     }, $input, $this->transforms);
 }
Exemplo n.º 26
0
 /**
  * Get an array representation of this object.
  *
  * @return array
  */
 public function toArray()
 {
     return Std::map(function (RamlBody $body) {
         return $body->toArray();
     }, $this->bodyTypes);
 }
Exemplo n.º 27
0
 /**
  * Validate and discover all the relationships on a model.
  *
  * @return Relation[]
  */
 protected function discoverRelations()
 {
     if ($this->relations === null) {
         $this->relations = [];
         Std::each(function ($name) {
             // Check that the relationship method is there.
             if (!method_exists($this->model, $name)) {
                 throw new LackOfCoffeeException(vsprintf('The model declares a relationship named "%s" but' . ' there is no method with that name.', [$name]));
             }
             $relationReflector = new ReflectionMethod($this->model, $name);
             if (!$relationReflector->isPublic()) {
                 throw new LackOfCoffeeException(vsprintf('The method for the relationship named "%s" should' . ' be public.', [$name]));
             }
             $argumentCount = $relationReflector->getNumberOfParameters();
             if ($argumentCount > 0) {
                 throw new LackOfCoffeeException(vsprintf('The method for the relationship named "%s" should' . ' take 0 arguments. However, it requires %d.', [$name, $argumentCount]));
             }
             $relation = $this->model->{$name}();
             if (!$relation instanceof Relation) {
                 throw new LackOfCoffeeException(vsprintf('The method for the relationship named "%s" should' . ' return an instance of %s. Got %s.', [$name, Relation::class, TypeHound::fetch($relation)]));
             }
             $this->relations[$name] = $relation;
         }, $this->model->getRelated());
     }
     return $this->relations;
 }
Exemplo n.º 28
0
 /**
  * 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()))]);
 }
Exemplo n.º 29
0
 /**
  * Get the type of each field.
  *
  * @return array
  */
 public function getTypes()
 {
     if ($this->spec instanceof Spec) {
         return Std::map(function ($field) {
             if ($field instanceof AbstractConstraint) {
                 return $field->toString();
             }
             return implode(' ^ ', Std::map(function ($innerField) {
                 if ($innerField instanceof Spec) {
                     return '{spec}';
                 } elseif ($innerField instanceof AbstractConstraint) {
                     return $innerField->toString();
                 }
                 return '{???}';
             }, $field));
         }, $this->spec->getConstraints());
     }
     return [];
 }
Exemplo n.º 30
0
 /**
  * Render the object into a string.
  *
  * @return mixed
  */
 public function render()
 {
     $title = 'Illuminated';
     $dashboardUrl = $this->context->url();
     $modulesUrl = $this->context->method('illuminated.conference.front', 'modules');
     $modulesDropdown = Std::foldr(function (NavbarDropdownFactory $factory, Module $module) {
         return $factory->addOption($this->context->module($module->getName()), $module->getLabel());
     }, new NavbarDropdownFactory(), $this->dashboard->getModules())->setContent([new Italic(['class' => 'fa fa-rocket']), ' Launchpad'])->make();
     $innerPage = new Page([new Container(['class' => 'p-t p-b'], [new Navigation(['class' => 'navbar navbar-dark bg-inverse'], [new Anchor(['class' => 'navbar-brand', 'href' => $dashboardUrl], 'Illuminated'), new UnorderedList(['class' => 'nav navbar-nav'], [new ListItem(['class' => 'nav-item'], new Anchor(['href' => $dashboardUrl, 'class' => 'nav-link'], 'Home')), $modulesDropdown, new ListItem(['class' => 'nav-item'], new Anchor(['href' => $modulesUrl, 'class' => 'nav-link'], [new Italic(['class' => 'fa fa-asterisk']), ' Meta']))])])]), $this->renderContent(), new Container(['class' => 'p-t p-b'], [new Paragraph([], [new Small([], 'Keep building awesome stuff. 👍 ')])]), new Script(['src' => 'https://ajax.googleapis.com/ajax/libs/jquery/' . '2.1.4/jquery.min.js']), new Script(['src' => 'https://cdn.rawgit.com/twbs/bootstrap/v4-dev/' . 'dist/js/bootstrap.js'])], [new Meta(['charset' => 'utf-8']), new Meta(['name' => 'viewport', 'content' => 'width=device-width, initial-scale=1']), new Meta(['http-equiv' => 'x-ua-compatible', 'content' => 'ie=edge']), new Title([], 'Illuminated - Conference'), new Link(['rel' => 'stylesheet', 'href' => 'https://maxcdn.bootstrapcdn.com/bootstrap' . '/4.0.0-alpha.2/css/bootstrap.min.css']), new Link(['rel' => 'stylesheet', 'href' => 'https://maxcdn.bootstrapcdn.com/font-awesome' . '/4.5.0/css/font-awesome.min.css']), new Link(['rel' => 'stylesheet', 'href' => $dashboardUrl . '/css/main.css'])]);
     return $innerPage->render();
 }