/** * Build an entity from an properties array. * * @param array $input * * @return BaseEntity */ public function makeFromArray(array $input) { $product = new SearchProduct(); $product->setCatalog($input['catalog']); $product->setAsin($input['productId']); $product->setEan($input['ean']); $product->setName($input['title']); $product->setImageUrl($input['image']); $product->setType($input['type']); $product->setWeight($input['weight']); if (Arr::has($input, 'rank')) { $rank = $input['rank']; if (Arr::has($rank, 'Rank')) { $product->setRank($rank['Rank']); } else { $product->setRank(null); } if (Arr::has($rank, 'ProductCategoryId')) { $product->setCategoryId($rank['ProductCategoryId']); } else { $product->setCategoryId(null); } } return $product; }
/** * Construct an instance of a Container. * * @param array $attributes * @param string|RenderableInterface|string[]|RenderableInterface[] $content */ public function __construct(array $attributes, $content) { $classes = []; $this->extraSmall = (int) Arr::dotGet($attributes, 'extraSmall', 0); $this->small = (int) Arr::dotGet($attributes, 'small', 0); $this->medium = (int) Arr::dotGet($attributes, 'medium', 0); $this->large = (int) Arr::dotGet($attributes, 'large', 0); if ($this->extraSmall > 0) { $classes[] = 'col-xs-' . $this->extraSmall; } if ($this->small > 0) { $classes[] = 'col-sm-' . $this->small; } if ($this->medium > 0) { $classes[] = 'col-md-' . $this->medium; } if ($this->large > 0) { $classes[] = 'col-lg-' . $this->large; } if (Arr::has($attributes, 'class')) { $classes[] = $attributes['class']; } $attributes['class'] = implode(' ', $classes); parent::__construct('div', $attributes, $content, false); }
/** * 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', []))); }
/** * Construct an instance of a Row. * * @param array $attributes * @param \string[] $content * @param bool|false $fluid */ public function __construct(array $attributes, $content, $fluid = false) { if (Arr::has($attributes, 'class')) { $attributes['class'] = implode(' ', ['row', $attributes['class']]); } else { $attributes['class'] = 'row'; } parent::__construct('div', $attributes, $content, false); }
/** * Construct an instance of a Container. * * @param array $attributes * @param \string[] $content * @param bool|false $fluid */ public function __construct(array $attributes, $content, $fluid = false) { $this->fluid = $fluid; if (Arr::has($attributes, 'class')) { $attributes['class'] = implode(' ', [$this->fluid ? 'container-fluid' : 'container', $attributes['class']]); } else { $attributes['class'] = $this->fluid ? 'container-fluid' : 'container'; } parent::__construct('div', $attributes, $content, false); }
/** * @param int $code * @param RamlResponse $response * * @return RamlResponseGroup */ public function addResponse($code, RamlResponse $response) { $new = clone $this; if (Arr::has($this->responses, $code)) { $new->responses[$code] = $this->responses[$code]->append($response); return $new; } $new->responses[$code] = $response; return $new; }
/** * Get the display name of a method. * * @param string $methodName * * @return string */ public function getMethodName($methodName) { $propertyName = vsprintf('%sName', [$methodName]); if (property_exists($this, $propertyName)) { return $this->{$propertyName}; } if (property_exists($this, 'methodNames') && Arr::has($this->methodNames, $methodName)) { return $this->methodNames[$methodName]; } return 'Unknown'; }
/** * Only return non-null and non-empty values in an array. * * @param array $properties * @param array|null $allowed * * @return array */ public static function filterEmptyValues($properties, array $allowed = null) { // If provided, only use allowed properties $properties = Arr::only($properties, $allowed); return array_filter($properties, function ($value) { if (is_array($value) && count($value) === 0) { return false; } return !is_null($value); }); }
/** * Build an entity from an properties array. * * @param array $input * * @return CategoryMapping */ public function makeFromArray(array $input) { $mapping = new CategoryMapping(); if (Arr::has($input, 'main')) { $mapping->setMainCategory($input['main']); } if (Arr::has($input, 'categoryId')) { $mapping->setCategoryId($input['categoryId']); } if (Arr::has($input, 'category')) { $mapping->setCategory($input['category']); } return $mapping; }
/** * Attempt to encode a Spec into a JSON schema. * * @param Spec $spec * @param string $title * * @throws CoreException * @return string */ public function encode(Spec $spec, $title = 'root') { $schema = ['$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => $title, 'type' => CompoundTypes::COMPOUND_OBJECT, 'required' => $spec->getRequired()]; $properties = []; foreach ($spec->getConstraints() as $key => $constraints) { $properties[$key] = $this->encodeConstraints($spec, $constraints, $key); } foreach ($spec->getDefaults() as $key => $default) { if (!Arr::has($properties, $key)) { $properties[$key] = []; } $properties[$key]['default'] = $default; } $schema['properties'] = $properties; return json_encode($schema, JSON_PRETTY_PRINT); }
/** * Parse most properties from the response. * * @param FeesResponse $feesResponse * @param array $body * * @throws InvalidFormatException */ protected function parseProperties(FeesResponse $feesResponse, array $body) { if (!Arr::has($body, 'data')) { throw new InvalidFormatException('The `data` property is missing from the response object.'); } $data = $body['data']; $factory = new FeesSetFactory(); if (Arr::has($data, 'sizeTier')) { $feesResponse->setSizeTier($data['sizeTier']); } if (Arr::has($data, 'fbaFees')) { $set = $factory->makeFromArray($data['fbaFees']); $set->setType(FeesSetType::TYPE_FBA); $feesResponse->setFbaFees($set); } if (Arr::has($data, 'mfnFees')) { $set = $factory->makeFromArray($data['mfnFees']); $set->setType(FeesSetType::TYPE_MERCHANT_FULFILLED); $feesResponse->setMerchantFees($set); } }
/** * Build an entity from an properties array. * * @param array $input * * @return FeesSet */ public function makeFromArray(array $input) { $set = new FeesSet(); $set->setPrice((double) $input['price']); $set->setRevenue((double) $input['revenue']); $set->setAmazonCommission((double) $input['azComm']); $set->setAmazonVar((double) $input['azVar']); $set->setFeesTotal((double) $input['feesTotal']); $set->setNetIncome((double) $input['netIncome']); $set->setCategory($input['category']); if (Arr::has($input, 'fbaWeight')) { $set->setFbaWeight((double) $input['fbaWeight']); } if (Arr::has($input, 'fbaPick')) { $set->setFbaPick((double) $input['fbaPick']); } if (Arr::has($input, 'fbaOrder')) { $set->setFbaOrder((double) $input['fbaOrder']); } return $set; }
/** * Get list of services provided. * * @throws LackOfCoffeeException * @return array */ public function provides() { return Std::concat(Arr::keys($this->getServiceMap()), Arr::keys($this->getSingletons())); }
/** * Get a specific relationship by its name. * * @param string $name * * @throws LackOfCoffeeException * @return Relation */ public function getRelation($name) { $relations = $this->discoverRelations(); if (!Arr::has($relations, $name)) { throw new LackOfCoffeeException(vsprintf('The model does not declare a dependency named "%s".', [$name])); } return $relations[$name]; }
/** * Parse extras array provided by the API. * * @param OffersResponse $offersResponse * @param array $body */ protected function parseExtras(OffersResponse $offersResponse, array $body) { if (Arr::has($body, 'extras')) { $offersResponse->setExtras($body['extras']); } }
/** * Build out the models for a relation. * * @param string $name * * @return Model|Collection */ protected function generateRelation($name) { $count = Arr::dotGet($this->relationsCount, $name, 1); if (!$this->relationsGenerators[$name] instanceof ModelGenerator) { return $this->relationsGenerators[$name]; } if ($count === 1) { return $this->relationsGenerators[$name]->make(); } return $this->relationsGenerators[$name]->makeMany($count); }
/** * Check that the spec matches and overlay help messaged. * * The resulting SpecResult instance should have more user-friendly * messages. This allows one to use Specs for validation on a website or * even an API. * * @param array $input * * @return SpecResult */ public function check(array $input) { $result = $this->spec->check($input); return new SpecResult($result->getMissing(), Arr::walkCopy($result->getFailed(), function ($key, $value, &$array, $path) { $array[$key] = Std::coalesce(Std::firstBias(Arr::dotGet($this->messages, Std::nonempty($path, $key)) !== null, [Arr::dotGet($this->messages, Std::nonempty($path, $key))], null), Std::firstBias($value instanceof AbstractConstraint, function () use($value) { return $value->getDescription(); }, null), Std::firstBias(is_array($value), function () use($value) { return array_map(function (AbstractConstraint $item) { return $item->getDescription(); }, $value); }, $value)); }, true, '', false), $result->getStatus()); }
/** * Assert that the response is valid and successful. * * @param array $body * * @throws InvalidFormatException */ protected function assertIsSuccessful(array $body) { if (!Arr::has($body, 'categoryMappings')) { throw new InvalidFormatException('The `categoryMappings` property is missing from the response.'); } }
public function testExchangeWithInvalid() { $input = [10, 30, 20]; $this->setExpectedException(IndexOutOfBoundsException::class); Arr::exchange($input, 1, 99); }
/** * @param string $key * @param mixed|null $default * * @return mixed */ public function get($key, $default = null) { return Arr::dotGet($this->content, $key, $default); }
/** * Get a RAML parameter definition from a Spec field. * * @param Spec $spec * @param string $field * * @return array */ protected function specFieldToParameter(Spec $spec, $field) { $constraints = $spec->getConstraints(); $defaults = $spec->getDefaults(); $required = $spec->getRequired(); $parameter = []; if (Arr::has($constraints, $field)) { $input = $constraints[$field]; if (is_array($input) || $input instanceof Spec) { if ($input instanceof Spec) { $input = [$input]; } foreach ($input as $constraint) { if ($constraint instanceof PrimitiveTypeConstraint) { switch ($constraint->toString()) { case ScalarTypes::SCALAR_STRING: $parameter['type'] = 'string'; break; case ScalarTypes::SCALAR_FLOAT: case ScalarTypes::SCALAR_INTEGER: $parameter['type'] = 'number'; break; case ScalarTypes::SCALAR_BOOLEAN: $parameter['type'] = 'boolean'; break; } } } } } if (Arr::has($defaults, $field)) { $parameter['default'] = $defaults[$field]; } $parameter['required'] = in_array($field, $required); return $parameter; }
/** * 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; }
/** * Attempt to automatically mock the arguments of a function. * * @param ReflectionParameter[] $parameters * @param array $overrides * * @return array * @throws ResolutionException */ protected function mockArguments(array $parameters, $overrides = []) { $resolved = []; foreach ($parameters as $parameter) { $hint = $parameter->getClass(); $name = $parameter->getName(); if (Arr::has($overrides, $name)) { $resolved[] = $overrides[$name]; continue; } if (is_null($hint)) { throw new ResolutionException(); } $mock = $this->resolveMock($hint); $resolved[] = $mock; } return $resolved; }
/** * @param string $key * * @return mixed */ public function getProperty($key) { return Arr::dotGet($this->getProperties(), $key); }
public function getReferenceSingle(HandlerResolverInterface $resolver, ConferenceContext $context, Request $request) { $taskName = $request->query->get('id'); $handler = $resolver->instantiate($taskName); $defaults = $handler->getDefaults(); $types = $handler->getTypes(); return new Card([], [new CardHeader([], 'Reference for task:'), new CardBlock([], [new HeaderOne(['class' => 'display-one'], $taskName), new Paragraph(['class' => 'lead'], $handler->getDescription())]), new SimpleTable(['Field Name', 'Type', 'Default', 'Description'], Std::map(function ($description, $field) use($types, $defaults) { return [$field, Arr::dotGet($types, $field, '-'), (string) Arr::dotGet($defaults, $field, '-'), $description]; }, $handler->getReference())), new CardBlock([], [new HeaderSix([], 'Example usage:'), new PreformattedText([], json_encode($defaults, JSON_PRETTY_PRINT))])]); }
/** * Get the failed constrains for a specific field. * * Dot notation is supported. * * @param string $fieldName * * @return AbstractConstraint[] */ public function getFailedForField($fieldName) { return Arr::dotGet($this->failed, $fieldName); }
/** * Check an input array against the SpecGraph. * * @param array $input * * @throws CoreException * @throws Exceptions\InvalidArgumentException * @return SpecResult */ public function check(array $input) { // Automatic reset if (count($this->pending) === 0) { foreach (Arr::keys($this->nodes) as $name) { if (count($this->incomingEdges[$name]) === 0) { $this->pending[] = $name; } } $this->checked = []; $this->results = []; $this->failed = false; } // Actual process while (count($this->checked) < count($this->nodes)) { if (count($this->pending) === 0) { throw new CoreException('Unable to resolve constraint graph.'); } $this->iterate($input); if ($this->failed) { $this->pending = []; break; } } // Aggregate results $missing = []; $failed = []; array_map(function (SpecResult $result) use(&$missing, &$failed) { $missing[] = $result->getMissing(); $failed[] = $result->getFailed(); }, $this->checked); return new SpecResult(Arr::mergev($missing), Arr::mergev($failed), $this->failed ? SpecResult::STATUS_FAIL : SpecResult::STATUS_PASS); }
/** * Resolve a module by name. * * @param null $moduleName * * @throws ModuleNotFoundException * @return Module */ protected function resolveModule($moduleName = null) { $selected = $moduleName; if ($moduleName === null) { $selected = static::DEFAULT_MODULE; } if (!Arr::has($this->modules, $selected)) { throw new ModuleNotFoundException($selected); } return $this->modules[$selected]; }
/** * Get a method in this module by its name. * * @param string $methodName * * @return mixed */ public function getMethod($methodName) { return Arr::dotGet($this->getMethods(), $methodName); }