/** * Build an entity from an properties array. * * @param array $input * * @return BaseEntity */ public function makeFromArray(array $input) { $product = new SearchProduct(); $product->setCatalog(Arr::dotGet($input, 'catalog')); $product->setAsin(Arr::dotGet($input, 'productId')); $product->setEan(Arr::dotGet($input, 'ean')); $product->setName(Arr::dotGet($input, 'title')); $product->setImageUrl(Arr::dotGet($input, 'image')); $product->setType(Arr::dotGet($input, 'type')); $product->setWeight(Arr::dotGet($input, 'weight')); if (Arr::has($input, 'rank')) { $rank = $input['rank']; if (Arr::has($rank, 'Rank')) { $product->setRank($rank['Rank']); if (Arr::has($rank, 'rankings')) { // Populate rankings $product->setRankings(array_map(function ($ranking) { return new Ranking($ranking); }, $rank['rankings'])); } } else { $product->setRank(null); } if (Arr::has($rank, 'ProductCategoryId')) { $product->setCategoryId($rank['ProductCategoryId']); } else { $product->setCategoryId(null); } if (Arr::has($input, 'relationships')) { $relationships = new RelationshipBag($input['relationships']); $product->setRelationships($relationships); } } 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 items out of a body * * @param array $body * * @return array */ protected function parseItems($body) { $items = Arr::dotGet($body, 'ItemSearchResponse.Items.Item', []); return array_map(function ($item) { return new Item($item); }, $items); }
/** * 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); }
/** * @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; }
/** * 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); }
/** * 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'; }
/** * Parse and build a rich response object from an HTTP response. * * @param ResponseInterface $response * * @return TokenResponse * @throws CoreException */ public function makeFromResponse(ResponseInterface $response) { $body = $this->parse($response); $tokenResponse = new TokenResponse(); $tokenResponse->setAccessToken(Arr::dotGet($body, 'access_token')); $tokenResponse->setRefreshToken(Arr::dotGet($body, 'refresh_token')); $tokenResponse->setExpiresIn(Arr::dotGet($body, 'expires_in')); $tokenResponse->setTokenType(Arr::dotGet($body, 'token_type')); $tokenResponse->setScope(Arr::dotGet($body, 'scope')); return $tokenResponse; }
/** * 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); }); }
/** * RelationshipBag constructor. * * @param array $relationships */ public function __construct(array $relationships) { $parents = Arr::dotGet($relationships, 'parents', []); $children = Arr::dotGet($relationships, 'children', []); if (is_array($parents) && !$this->isAssoc($parents)) { $this->setParents($parents); } if (is_array($children) && !$this->isAssoc($children)) { $this->setChildren($children); } }
/** * Parse and build a rich response object from an HTTP response. * * @param ResponseInterface $response * * @return BaseResponse * @throws WhoamiResponse */ public function makeFromResponse(ResponseInterface $response) { $body = $this->parse($response); $whoamiResponse = new WhoamiResponse(); $user = new User(); $user->fill(Arr::dotGet($body, 'user')); $whoamiResponse->setUser($user); $organization = new Organization(); $organization->fill(Arr::dotGet($body, 'organization')); $whoamiResponse->setOrganization($organization); return $whoamiResponse; }
/** * 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; }
/** * 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); }
/** * 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; }
/** * 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); } }
/** * 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; }
public function testExchangeWithInvalid() { $input = [10, 30, 20]; $this->setExpectedException(IndexOutOfBoundsException::class); Arr::exchange($input, 1, 99); }
/** * 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); }
/** * 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; }
/** * Get a method in this module by its name. * * @param string $methodName * * @return mixed */ public function getMethod($methodName) { return Arr::dotGet($this->getMethods(), $methodName); }
/** * 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()); }
/** * 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]; }
/** * 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); }
/** * Get an arbitrary attribute from this item attributes set. * * @param string $key * * @return mixed */ public function attr($key) { return Arr::dotGet($this->attributes, ucfirst($key)); }
/** * @param string $key * @param mixed|null $default * * @return mixed */ public function get($key, $default = null) { return Arr::dotGet($this->content, $key, $default); }
/** * 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.'); } }
/** * Safely get a key from the raw response * * @param string $key * @param mixed $default * * @return mixed */ protected function get($key, $default = null) { return Arr::dotGet($this->raw, $key, $default); }
/** * 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]; }