code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function synchronize($data = false, $code = false, $rebase = false) { if (!$data && !$code) { throw new \InvalidArgumentException('Nothing to synchronize: you must specify $data or $code'); } $body = [ 'synchronize_data' => $data, 'synchronize_code' => $code, ]; if ($rebase) { // @todo always add this (when the rebase option is GA) $body['rebase'] = $rebase; } return $this->runLongOperation('synchronize', 'post', $body); }
Synchronize an environment with its parent. @param bool $code Synchronize code. @param bool $data Synchronize data. @param bool $rebase Synchronize code by rebasing instead of merging. @throws \InvalidArgumentException @return Activity
public function setVariable( $name, $value, $json = false, $enabled = true, $sensitive = false ) { if (!is_scalar($value)) { $value = json_encode($value); $json = true; } $values = ['value' => $value, 'is_json' => $json, 'is_enabled' => $enabled]; if ($sensitive) { $values['is_sensitive'] = $sensitive; } $existing = $this->getVariable($name); if ($existing) { return $existing->update($values); } $values['name'] = $name; return Variable::create($values, $this->getLink('#manage-variables'), $this->client); }
Set a variable @param string $name @param mixed $value @param bool $json @param bool $enabled @param bool $sensitive @return Result
public function getRouteUrls() { $routes = []; if (isset($this->data['_links']['pf:routes'])) { foreach ($this->data['_links']['pf:routes'] as $route) { $routes[] = $route['href']; } } return $routes; }
Get the resolved URLs for the environment's routes. @return string[]
public function addUser($user, $role, $byUuid = true) { $property = $byUuid ? 'user' : 'email'; $body = [$property => $user, 'role' => $role]; return EnvironmentAccess::create($body, $this->getLink('#manage-access'), $this->client); }
Add a new user to the environment. @param string $user The user's UUID or email address (see $byUuid). @param string $role One of EnvironmentAccess::$roles. @param bool $byUuid Set true (default) if $user is a UUID, or false if $user is an email address. Note that for legacy reasons, the default for $byUuid is false for Project::addUser(), but true for Environment::addUser(). @return Result
public function addBackupPolicy(Policy $policy) { $backups = isset($this->data['backups']) ? $this->data['backups'] : []; $backups['schedule'][] = [ 'interval' => $policy->getInterval(), 'count' => $policy->getCount(), ]; if (!isset($backups['manual_count'])) { $backups['manual_count'] = 3; } return $this->update(['backups' => $backups]); }
Add a scheduled backup policy. @param \Platformsh\Client\Model\Backups\Policy $policy @return \Platformsh\Client\Model\Result
public function render(Request $request, array $options = array()) { return $this->doRender( $options + array( 'shortname' => $this->shortName, 'identifier' => $request->getPathInfo(), 'count' => $this->count, ) ); }
Renders the comments list. Comment form might also be included. @param \Symfony\Component\HttpFoundation\Request $request @param array $options @return string
public function renderForContent(ContentInfo $contentInfo, Request $request, array $options = array()) { return $this->doRender( $options + array( 'shortname' => $this->shortName, 'identifier' => $contentInfo->id, // TODO: Use translated name 'title' => $contentInfo->name, 'count' => $this->count, ) ); }
Renders the comments list for a given content. Comment form might also be included. @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo @param \Symfony\Component\HttpFoundation\Request $request @param array $options @return mixed
public function getLink($rel, $absolute = true) { // @todo double-check whether the resource does contain the #edit link if ($rel === "#edit" && !$this->hasLink($rel)) { return $this->getUri($absolute); } return parent::getLink($rel, $absolute); }
{@inheritdoc}
public static function parameterize($string, $sep = '-'){ # replace accented chars with their ascii equivalents $parameterized_string = static::transliterate($string); # Turn unwanted chars into the separator $parameterized_string = preg_replace('/[^a-z0-9\-_]+/i', $sep, $parameterized_string); if(!(is_null($sep) || empty($sep))){ $re_sep = preg_quote($sep); # CoreExt\Regexp::escape # No more than one of the separator in a row. $parameterized_string = preg_replace("/{$re_sep}{2,}/", $sep, $parameterized_string); # Remove leading/trailing separator. $parameterized_string = preg_replace("/^{$re_sep}|{$re_sep}$/i", '', $parameterized_string); } return strtolower($parameterized_string); }
Replaces special characters in a string so that it may be used as part of a 'pretty' URL. ==== Examples parameterize("Donald E. Knuth") # => "donald-e-knuth" @param string $string @param string $sep @return string $string with special characters replaced @author Koen Punt
public function getProject($id, $hostname = null, $https = true) { // Search for a project in the user's project list. foreach ($this->getProjects() as $project) { if ($project->id === $id) { return $project; } } // Look for a project directly if the hostname is known. if ($hostname !== null) { return $this->getProjectDirect($id, $hostname, $https); } // Use the project locator. if ($url = $this->locateProject($id)) { return Project::get($url, null, $this->connector->getClient()); } return false; }
Get a single project by its ID. @param string $id @param string $hostname @param bool $https @return Project|false
public function getProjects($reset = false) { $data = $this->getAccountInfo($reset); $client = $this->connector->getClient(); $projects = []; foreach ($data['projects'] as $project) { // Each project has its own endpoint on a Platform.sh region. $projects[] = new Project($project, $project['endpoint'], $client); } return $projects; }
Get the logged-in user's projects. @param bool $reset @return Project[]
public function getAccountInfo($reset = false) { if (!isset($this->accountInfo) || $reset) { $url = $this->accountsEndpoint . 'me'; try { $this->accountInfo = $this->simpleGet($url); } catch (BadResponseException $e) { throw ApiResponseException::create($e->getRequest(), $e->getResponse(), $e->getPrevious()); } } return $this->accountInfo; }
Get account information for the logged-in user. @param bool $reset @return array
private function simpleGet($url, array $options = []) { return (array) \GuzzleHttp\json_decode( $this->getConnector() ->getClient() ->request('get', $url, $options) ->getBody() ->getContents(), true ); }
Get a URL and return the JSON-decoded response. @param string $url @param array $options @return array
public function getProjectDirect($id, $hostname, $https = true) { $scheme = $https ? 'https' : 'http'; $collection = "$scheme://$hostname/api/projects"; return Project::get($id, $collection, $this->connector->getClient()); }
Get a single project at a known location. @param string $id The project ID. @param string $hostname The hostname of the Platform.sh regional API, e.g. 'eu.platform.sh' or 'us.platform.sh'. @param bool $https Whether to use HTTPS (default: true). @internal It's now better to use getProject(). This method will be made private in a future release. @return Project|false
protected function locateProject($id) { $url = $this->accountsEndpoint . 'projects/' . rawurlencode($id); try { $result = $this->simpleGet($url); } catch (BadResponseException $e) { $response = $e->getResponse(); // @todo Remove 400 from this array when the API is more liberal in validating project IDs. $ignoredErrorCodes = [400, 403, 404]; if ($response && in_array($response->getStatusCode(), $ignoredErrorCodes)) { return false; } throw ApiResponseException::create($e->getRequest(), $e->getResponse(), $e->getPrevious()); } return isset($result['endpoint']) ? $result['endpoint'] : false; }
Locate a project by ID. @param string $id The project ID. @return string The project's API endpoint.
public function getSshKeys($reset = false) { $data = $this->getAccountInfo($reset); return SshKey::wrapCollection($data['ssh_keys'], $this->accountsEndpoint, $this->connector->getClient()); }
Get the logged-in user's SSH keys. @param bool $reset @return SshKey[]
public function getSshKey($id) { $url = $this->accountsEndpoint . 'ssh_keys'; return SshKey::get($id, $url, $this->connector->getClient()); }
Get a single SSH key by its ID. @param string|int $id @return SshKey|false
public function addSshKey($value, $title = null) { $values = $this->cleanRequest(['value' => $value, 'title' => $title]); $url = $this->accountsEndpoint . 'ssh_keys'; return SshKey::create($values, $url, $this->connector->getClient()); }
Add an SSH public key to the logged-in user's account. @param string $value The SSH key value. @param string $title A title for the key (optional). @return Result
public function createSubscription($region, $plan = 'development', $title = null, $storage = null, $environments = null, array $activationCallback = null) { $url = $this->accountsEndpoint . 'subscriptions'; $values = $this->cleanRequest([ 'project_region' => $region, 'plan' => $plan, 'project_title' => $title, 'storage' => $storage, 'environments' => $environments, 'activation_callback' => $activationCallback, ]); return Subscription::create($values, $url, $this->connector->getClient()); }
Create a new Platform.sh subscription. @param string $region The region ID. See getRegions(). @param string $plan The plan. See Subscription::$availablePlans. @param string $title The project title. @param int $storage The storage of each environment, in MiB. @param int $environments The number of available environments. @param array $activationCallback An activation callback for the subscription. @see PlatformClient::getRegions() @see Subscription::wait() @return Subscription A subscription, representing a project. Use Subscription::wait() or similar code to wait for the subscription's project to be provisioned and activated.
public function getSubscriptions() { $url = $this->accountsEndpoint . 'subscriptions'; return Subscription::getCollection($url, 0, [], $this->connector->getClient()); }
Get a list of your Platform.sh subscriptions. @return Subscription[]
public function getSubscription($id) { $url = $this->accountsEndpoint . 'subscriptions'; return Subscription::get($id, $url, $this->connector->getClient()); }
Get a subscription by its ID. @param string|int $id @return Subscription|false
public function getSubscriptionEstimate($plan, $storage, $environments, $users) { $options = []; $options['query'] = [ 'plan' => $plan, 'storage' => $storage, 'environments' => $environments, 'user_licenses' => $users, ]; try { return $this->simpleGet($this->accountsEndpoint . 'estimate', $options); } catch (BadResponseException $e) { throw ApiResponseException::create($e->getRequest(), $e->getResponse(), $e->getPrevious()); } }
Estimate the cost of a subscription. @param string $plan The plan (see Subscription::$availablePlans). @param int $storage The allowed storage per environment (in GiB). @param int $environments The number of environments. @param int $users The number of users. @return array An array containing at least 'total' (a formatted price).
public function getPlanRecords(PlanRecordQuery $query = null) { $url = $this->accountsEndpoint . 'records/plan'; $options = []; if ($query) { $options['query'] = $query->getParams(); } return PlanRecord::getCollection($url, 0, $options, $this->connector->getClient()); }
Get plan records. @param PlanRecordQuery|null $query A query to restrict the returned plans. @return PlanRecord[]
public function plural($rule, $replacement){ if(is_string($rule)){ Utils::array_delete($this->uncountables, $rule); } Utils::array_delete($this->uncountables, $replacement); array_unshift($this->plurals, array($rule, $replacement)); }
Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. The replacement should always be a string that may include references to the matched data from the rule. @param string $rule @param string $replacement @return void @author Koen Punt
public function singular($rule, $replacement){ if(is_string($rule)){ Utils::array_delete($this->uncountables, $rule); } Utils::array_delete($this->uncountables, $replacement); array_unshift($this->singulars, array($rule, $replacement)); }
Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression. The replacement should always be a string that may include references to the matched data from the rule. @param string $rule @param string $replacement @return void @author Koen Punt
public function uncountable(/* *$words */){ $words = func_get_args(); array_push($this->uncountables, $words); $this->uncountables = Utils::array_flatten($this->uncountables); return $this->uncountables; }
Add uncountable words that shouldn't be attempted inflected. Examples: uncountable("money") uncountable("money", "information") uncountable(array('money', 'information', 'rice')) @param array $words @return array $uncountables @author Koen Punt
public function human($rule, $replacement){ $this->humans = array_merge(array($rule => $replacement), $this->humans); return $this->humans; }
Specifies a humanized form of a string by a regular expression rule or by a string mapping. When using a regular expression based replacement, the normal humanize formatting is called after the replacement. When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name') Examples: human('/_cnt$/i', '\1_count') human("legacy_col_person_name", "Name") @param string $rule @param string $replacement @return array $humans @author Koen Punt
public function clear($scope = 'all'){ switch($scope){ case 'all': $this->plurals = array(); $this->singulars = array(); $this->uncountables = array(); $this->humans = array(); break; default: $this->{$scope} = array(); } }
Clears the loaded inflections within a given scope (default is <tt>all</tt>). Give the scope as a symbol of the inflection type, the options are: <tt>plurals</tt>, <tt>singulars</tt>, <tt>uncountables</tt>, <tt>humans</tt>. Examples: clear('all') clear('plurals') @param string $scope @return void @author Koen Punt
public static function create( RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null, array $ctx = [] ) { $e = parent::create($request, $response, $previous); if ($response === null) { return $e; } // Re-create the exception to alter the message. $details = self::getErrorDetails($response); if (!empty($details)) { $className = get_class($e); $e = new $className($e->getMessage() . $details, $e->getRequest(), $e->getResponse()); } return $e; }
@inheritdoc Modifies Guzzle error messages to add more detail, based on the response body.
public static function getErrorDetails(ResponseInterface $response) { $responseInfoProperties = [ // Platform.sh API errors. 'message', 'detail', // RESTful module errors. 'title', 'type', // OAuth2 errors. 'error', 'error_description', ]; $details = ''; $response->getBody()->seek(0); $contents = $response->getBody()->getContents(); try { $json = \GuzzleHttp\json_decode($contents, true); foreach ($responseInfoProperties as $property) { if (!empty($json[$property])) { $value = $json[$property]; $details .= " [$property] " . (is_scalar($value) ? $value : json_encode($value)); } } } catch (\InvalidArgumentException $parseException) { // Occasionally the response body may not be JSON. if ($contents) { $details .= " [extra] Non-JSON response body"; $details .= " [body] " . $contents; } else { $details .= " [extra] Empty response body"; } } return $details; }
Get more details from the response body, to add to error messages. @param ResponseInterface $response @return string
public static function fromName($refName, Project $project, ClientInterface $client) { $url = $project->getUri() . '/git/refs'; return static::get($refName, $url, $client); }
Get a Ref object in a project. @param string $refName @param Project $project @param ClientInterface $client @return static|false
public function getCommit() { $data = $this->object; if ($data['type'] !== 'commit') { throw new \RuntimeException('This ref is not a commit'); } $url = Project::getProjectBaseFromUrl($this->getUri()) . '/git/commits'; return Commit::get($data['sha'], $url, $this->client); }
Get the commit for this ref. @return Commit|false
public static function create(array $body, $collectionUrl, ClientInterface $client) { $result = parent::create($body, $collectionUrl, $client); return new Subscription($result->getData(), $collectionUrl, $client); }
{@inheritdoc} @internal Use PlatformClient::createSubscription() to create a new subscription. @see \Platformsh\Client\PlatformClient::createSubscription() @return static
public function wait(callable $onPoll = null, $interval = 2) { while ($this->isPending()) { sleep($interval > 1 ? $interval : 1); $this->refresh(); if ($onPoll !== null) { $onPoll($this); } } }
Wait for the subscription's project to be provisioned. @param callable $onPoll A function that will be called every time the subscription is refreshed. It will be passed one argument: the Subscription object. @param int $interval The polling interval, in seconds.
public function isPending() { $status = $this->getStatus(); return $status === self::STATUS_PROVISIONING || $status === self::STATUS_REQUESTED; }
Check whether the subscription is pending (requested or provisioning). @return bool
public function getOwner() { $uuid = $this->getProperty('owner'); $url = $this->makeAbsoluteUrl('/api/users', $this->getLink('project')); return Account::get($uuid, $url, $this->client); }
Get the account for the project's owner. @return Account|false
public function getProject() { if (!$this->hasLink('project') && !$this->isActive()) { throw new \BadMethodCallException('Inactive subscriptions do not have projects.'); } $url = $this->getLink('project'); return Project::get($url, null, $this->client); }
Get the project associated with this subscription. @return Project|false
public function wait(callable $onPoll = null, callable $onLog = null, $pollInterval = 1) { $log = $this->getProperty('log'); if ($onLog !== null && strlen(trim($log))) { $onLog(trim($log) . "\n"); } $length = strlen($log); $retries = 0; while (!$this->isComplete()) { usleep($pollInterval * 1000000); try { $this->refresh(['timeout' => $pollInterval + 5]); if ($onPoll !== null) { $onPoll($this); } if ($onLog !== null && ($new = substr($this->getProperty('log'), $length))) { $onLog(trim($new) . "\n"); $length += strlen($new); } } catch (ConnectException $e) { // Retry on timeout. if (strpos($e->getMessage(), 'cURL error 28') !== false && $retries <= 5) { $retries++; continue; } throw $e; } } }
Wait for the activity to complete. @todo use the FutureInterface @param callable $onPoll A function that will be called every time the activity is polled for updates. It will be passed one argument: the Activity object. @param callable $onLog A function that will print new activity log messages as they are received. It will be passed one argument: the message as a string. @param int|float $pollInterval The polling interval, in seconds.
public function restore($target = null, $branchFrom = null) { if ($this->getProperty('type') !== 'environment.backup') { throw new \BadMethodCallException('Cannot restore activity (wrong type)'); } if (!$this->isComplete()) { throw new \BadMethodCallException('Cannot restore backup (not complete)'); } $options = []; if ($target !== null) { $options['environment_name'] = $target; } if ($branchFrom !== null) { $options['branch_from'] = $branchFrom; } return $this->runLongOperation('restore', 'post', $options); }
Restore the backup associated with this activity. @param string|null $target The name of the target environment to which the backup should be restored (this could be the name of an existing environment, or a new environment). Leave this null to restore to the backup's original environment. @param string|null $branchFrom If a new environment will be created (depending on $target), this specifies the name of the parent branch. @return Activity
public function getDescription($html = false) { $description = $this->getProperty('description'); if ($html) { return $description; } return html_entity_decode(strip_tags($description), ENT_QUOTES, 'utf-8'); }
Get a human-readable description of the activity. The "description" property contains the HTML-formatted description. This method just provides another way to access it, and a way to remove HTML easily. @param bool $html Whether to return HTML. @return string
public static function formatStartsAt($timestamp) { $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $date = date('c', $timestamp); date_default_timezone_set($tz); if (!$date) { throw new \RuntimeException(sprintf('Failed to format timestamp: %d', $timestamp)); } return $date; }
@param int $timestamp @return false|string
public static function inflections($block = false){ if($block){ return call_user_func($block, Inflections::instance()); }else{ return Inflections::instance(); } }
Yields a singleton instance of Inflections so you can specify additional inflector rules. Example: Inflector::inflections(function($inflect){ $inflect->uncountable("rails"); }); @param callable $block @return Inflections @author Koen Punt
private static function stringToSeconds($duration) { if (isset(self::$suffixes[substr($duration, -1)])) { $amount = substr($duration, 0, strlen($duration) - 1); $unit = self::$suffixes[substr($duration, -1)]; } else { $unit = 1; $amount = $duration; } if (!is_numeric($amount)) { throw new \InvalidArgumentException('Invalid duration: ' . $duration); } return $unit * $amount; }
Converts a duration string to seconds. @param string $duration @return int|float
public function getAccount() { $uuid = $this->getProperty('id'); $url = $this->makeAbsoluteUrl('/api/users'); $account = Account::get($uuid, $url, $this->client); if (!$account) { throw new \Exception("Account not found for user: " . $uuid); } return $account; }
Get the account information for this user. @throws \Exception @return Account
public function getEnvironmentRole(Environment $environment) { $access = $environment->getUser($this->id); return $access ? $access->role : false; }
Get the user's role on an environment. @param Environment $environment @deprecated use Environment::getUser() instead @return string|false The user's environment role, or false if not found.
public function changeEnvironmentRole(Environment $environment, $newRole) { $access = $environment->getUser($this->id); if ($access) { if ($access->role === $newRole) { throw new \InvalidArgumentException("There is nothing to change"); } return $access->update(['role' => $newRole]); } return $environment->addUser($this->id, $newRole); }
Change the user's environment-level role. @param Environment $environment @param string $newRole The new role (see EnvironmentAccess::$roles). @return Result
public function signData($data, PrivateKey $privateKey, $algorithm = OPENSSL_ALGO_SHA256, $format = self::FORMAT_DER) { Assert::oneOf($format, [self::FORMAT_ECDSA, self::FORMAT_DER], 'The format %s to sign request does not exists. Available format: %s'); $resource = $privateKey->getResource(); if (!openssl_sign($data, $signature, $resource, $algorithm)) { throw new DataSigningException( sprintf('OpenSSL data signing failed with error: %s', openssl_error_string()) ); } openssl_free_key($resource); switch ($format) { case self::FORMAT_DER: return $signature; case self::FORMAT_ECDSA: switch ($algorithm) { case OPENSSL_ALGO_SHA256: return $this->DERtoECDSA($signature, 64); case OPENSSL_ALGO_SHA384: return $this->DERtoECDSA($signature, 96); case OPENSSL_ALGO_SHA512: return $this->DERtoECDSA($signature, 132); } throw new DataSigningException('Unable to generate a ECDSA signature with the given algorithm'); default: throw new DataSigningException('The given format does exists'); } }
Generate a signature of the given data using a private key and an algorithm. @param string $data Data to sign @param PrivateKey $privateKey Key used to sign @param int $algorithm Signature algorithm defined by constants OPENSSL_ALGO_* @param string $format Format of the output @return string
private function DERtoECDSA($der, $partLength) { $hex = unpack('H*', $der)[1]; if ('30' !== mb_substr($hex, 0, 2, '8bit')) { // SEQUENCE throw new DataSigningException('Invalid signature provided'); } if ('81' === mb_substr($hex, 2, 2, '8bit')) { // LENGTH > 128 $hex = mb_substr($hex, 6, null, '8bit'); } else { $hex = mb_substr($hex, 4, null, '8bit'); } if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER throw new DataSigningException('Invalid signature provided'); } $Rl = hexdec(mb_substr($hex, 2, 2, '8bit')); $R = $this->retrievePositiveInteger(mb_substr($hex, 4, $Rl * 2, '8bit')); $R = str_pad($R, $partLength, '0', STR_PAD_LEFT); $hex = mb_substr($hex, 4 + $Rl * 2, null, '8bit'); if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER throw new DataSigningException('Invalid signature provided'); } $Sl = hexdec(mb_substr($hex, 2, 2, '8bit')); $S = $this->retrievePositiveInteger(mb_substr($hex, 4, $Sl * 2, '8bit')); $S = str_pad($S, $partLength, '0', STR_PAD_LEFT); return pack('H*', $R.$S); }
Convert a DER signature into ECDSA. The code is a copy/paste from another lib (web-token/jwt-core) which is not compatible with php <= 7.0 @see https://github.com/web-token/jwt-core/blob/master/Util/ECSignature.php
public function calculate(string $buffer): int { $bufferLength = \strlen($buffer); $mask = (((1 << ($this->bitLength - 1)) - 1) << 1) | 1; $highBit = 1 << ($this->bitLength - 1); $crc = $this->init; for ($iterator = 0; $iterator < $bufferLength; ++$iterator) { $character = \ord($buffer[$iterator]); if ($this->reverseIn) { $character = $this->binaryReverse($character, 8); } for ($j = 0x80; $j; $j >>= 1) { $bit = $crc & $highBit; $crc <<= 1; if ($character & $j) { $bit ^= $highBit; } if ($bit) { $crc ^= $this->poly; } } } if ($this->reverseOut) { $crc = $this->binaryReverse($crc, $this->bitLength); } $crc ^= $this->xorOut; return $crc & $mask; }
@param string $buffer @return int
protected function generateTable(int $polynomial): array { $tableSize = 256; $mask = (((1 << ($this->bitLength - 1)) - 1) << 1) | 1; $highBit = 1 << ($this->bitLength - 1); $crctab = []; for ($i = 0; $i < $tableSize; ++$i) { $crc = $i; if ($this->reverseIn) { $crc = $this->binaryReverse($crc, 8); } $crc <<= $this->bitLength - 8; for ($j = 0; $j < 8; ++$j) { $bit = $crc & $highBit; $crc <<= 1; if ($bit) { $crc ^= $polynomial; } } if ($this->reverseOut) { $crc = $this->binaryReverse($crc, $this->bitLength); } $crc &= $mask; $crctab[] = $crc; } return $crctab; }
@param int $polynomial @return array
protected function binaryReverse(int $binaryInput, int $bitlen): int { $cloneBits = $binaryInput; $binaryInput = 0; $count = 0; while ($count < $bitlen) { ++$count; $binaryInput <<= 1; $binaryInput |= ($cloneBits & 0x1); $cloneBits >>= 1; } return $binaryInput; }
@param int $binaryInput @param int $bitlen @return int
public function signCertificateRequest(CertificateRequest $certificateRequest) { $csrObject = $this->createCsrWithSANsObject($certificateRequest); if (!$csrObject || !openssl_csr_export($csrObject, $csrExport)) { throw new CSRSigningException(sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string())); } return $csrExport; }
Generate a CSR from the given distinguishedName and keyPair. @param CertificateRequest $certificateRequest @return string
protected function createCsrWithSANsObject(CertificateRequest $certificateRequest) { $sslConfigTemplate = <<<'EOL' [ req ] distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @req_subject_alt_name [ req_subject_alt_name ] %s EOL; $sslConfigDomains = []; $distinguishedName = $certificateRequest->getDistinguishedName(); $domains = array_merge( [$distinguishedName->getCommonName()], $distinguishedName->getSubjectAlternativeNames() ); foreach (array_values($domains) as $index => $domain) { $sslConfigDomains[] = 'DNS.'.($index + 1).' = '.$domain; } $sslConfigContent = sprintf($sslConfigTemplate, implode("\n", $sslConfigDomains)); $sslConfigFile = tempnam(sys_get_temp_dir(), 'acmephp_'); try { file_put_contents($sslConfigFile, $sslConfigContent); $resource = $certificateRequest->getKeyPair()->getPrivateKey()->getResource(); $csr = openssl_csr_new( $this->getCSRPayload($distinguishedName), $resource, [ 'digest_alg' => 'sha256', 'config' => $sslConfigFile, ] ); openssl_free_key($resource); if (!$csr) { throw new CSRSigningException( sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string()) ); } return $csr; } finally { unlink($sslConfigFile); } }
Generate a CSR object with SANs from the given distinguishedName and keyPair. @param CertificateRequest $certificateRequest @return mixed
private function getCSRPayload(DistinguishedName $distinguishedName) { $payload = []; if (null !== $countryName = $distinguishedName->getCountryName()) { $payload['countryName'] = $countryName; } if (null !== $stateOrProvinceName = $distinguishedName->getStateOrProvinceName()) { $payload['stateOrProvinceName'] = $stateOrProvinceName; } if (null !== $localityName = $distinguishedName->getLocalityName()) { $payload['localityName'] = $localityName; } if (null !== $OrganizationName = $distinguishedName->getOrganizationName()) { $payload['organizationName'] = $OrganizationName; } if (null !== $organizationUnitName = $distinguishedName->getOrganizationalUnitName()) { $payload['organizationalUnitName'] = $organizationUnitName; } if (null !== $commonName = $distinguishedName->getCommonName()) { $payload['commonName'] = $commonName; } if (null !== $emailAddress = $distinguishedName->getEmailAddress()) { $payload['emailAddress'] = $emailAddress; } return $payload; }
Retrieves a CSR payload from the given distinguished name. @param DistinguishedName $distinguishedName @return array
public function generateKeyPair($keyOption = null) { if (null === $keyOption) { $keyOption = new RsaKeyOption(); } if (\is_int($keyOption)) { @trigger_error('Passing a keySize to "generateKeyPair" is deprecated since version 1.1 and will be removed in 2.0. Pass an instance of KeyOption instead', E_USER_DEPRECATED); $keyOption = new RsaKeyOption($keyOption); } Assert::isInstanceOf($keyOption, KeyOption::class); try { $privateKey = $this->generator->generatePrivateKey($keyOption); } catch (KeyGenerationException $e) { throw new KeyPairGenerationException('Fail to generate a KeyPair with the given options', 0, $e); } return new KeyPair( $privateKey->getPublicKey(), $privateKey ); }
Generate KeyPair. @param KeyOption $keyOption configuration of the key to generate @throws KeyPairGenerationException when OpenSSL failed to generate keys @return KeyPair
public function parse(Key $key) { try { $resource = $key->getResource(); } catch (KeyFormatException $e) { throw new KeyParsingException('Fail to load resource for key', 0, $e); } $rawData = openssl_pkey_get_details($resource); openssl_free_key($resource); if (!\is_array($rawData)) { throw new KeyParsingException(sprintf('Fail to parse key with error: %s', openssl_error_string())); } foreach (['type', 'key', 'bits'] as $requiredKey) { if (!isset($rawData[$requiredKey])) { throw new KeyParsingException(sprintf('Missing expected key "%s" in OpenSSL key', $requiredKey)); } } $details = []; if (OPENSSL_KEYTYPE_RSA === $rawData['type']) { $details = $rawData['rsa']; } elseif (OPENSSL_KEYTYPE_DSA === $rawData['type']) { $details = $rawData['dsa']; } elseif (OPENSSL_KEYTYPE_DH === $rawData['type']) { $details = $rawData['dh']; } elseif (OPENSSL_KEYTYPE_EC === $rawData['type']) { $details = $rawData['ec']; } return new ParsedKey($key, $rawData['key'], $rawData['bits'], $rawData['type'], $details); }
Parse the key. @param Key $key @return ParsedKey
public function parse(Certificate $certificate) { $rawData = openssl_x509_parse($certificate->getPEM()); if (!\is_array($rawData)) { throw new CertificateParsingException( sprintf('Fail to parse certificate with error: %s', openssl_error_string()) ); } if (!isset($rawData['subject']['CN'])) { throw new CertificateParsingException('Missing expected key "subject.cn" in certificate'); } if (!isset($rawData['serialNumber'])) { throw new CertificateParsingException('Missing expected key "serialNumber" in certificate'); } if (!isset($rawData['validFrom_time_t'])) { throw new CertificateParsingException('Missing expected key "validFrom_time_t" in certificate'); } if (!isset($rawData['validTo_time_t'])) { throw new CertificateParsingException('Missing expected key "validTo_time_t" in certificate'); } $subjectAlternativeName = []; if (isset($rawData['extensions']['subjectAltName'])) { $subjectAlternativeName = array_map( function ($item) { return explode(':', trim($item), 2)[1]; }, array_filter( explode( ',', $rawData['extensions']['subjectAltName'] ), function ($item) { return false !== strpos($item, ':'); } ) ); } return new ParsedCertificate( $certificate, $rawData['subject']['CN'], isset($rawData['issuer']['CN']) ? $rawData['issuer']['CN'] : null, $rawData['subject'] === $rawData['issuer'], new \DateTime('@'.$rawData['validFrom_time_t']), new \DateTime('@'.$rawData['validTo_time_t']), $rawData['serialNumber'], $subjectAlternativeName ); }
Parse the certificate. @param Certificate $certificate @return ParsedCertificate
public static function fromDER($keyDER) { Assert::stringNotEmpty($keyDER, __METHOD__.'::$keyDER should be a non-empty string. Got %s'); $der = base64_encode($keyDER); $lines = str_split($der, 65); array_unshift($lines, '-----BEGIN PRIVATE KEY-----'); $lines[] = '-----END PRIVATE KEY-----'; $lines[] = ''; return new self(implode("\n", $lines)); }
@param $keyDER @return PrivateKey
public function onWsdlResponse(WsdlResponseEvent $event) { $xpath = new \DOMXPath($event->getWsdl()); $xpath->registerNamespace('wsaw', self::NS_WSAW); // This is a pretty dumb check. Just see if a wsaw:Addressing or wsaw:UsingAddressing tag exists if ($xpath->query('//wsaw:Addressing')->length || $xpath->query('//wsaw:UsingAddressing')->length) { $this->wsaEnabled = true; } }
Parse the WSDL to check if WS-Addressing should be enabled @param WsdlResponseEvent $event @return void
public function getDetail($name) { Assert::oneOf($name, array_keys($this->details), 'ParsedKey::getDetail() expected one of: %2$s. Got: %s'); return $this->details[$name]; }
@param string $name @return mixed
private function getOption(string $name) { return $this->input->hasOption($name) ? $this->input->getOption($name) : null; }
@param string $name @return mixed|null
public function handle(EventInterface $event) { $events = array_filter($this->listener, function (string $eventName) use ($event): bool { return fnmatch($eventName, $event->getName()); }, ARRAY_FILTER_USE_KEY); $events = array_reduce($events, 'array_merge', []); array_walk( $events, /** * @param mixed $item * @return void */ function ($item) use ($event) { if ($item instanceof ListenerInterface) { $item->handle($event); return; } if (\is_callable($item)) { $item($event); } } ); }
Handle an event. @param EventInterface $event @return void
private function recursiveCall(string $name) { foreach ($this->options as $option) { $value = $option->{$name}(); if ($value !== null) { return $value; } } return null; }
@param string $name @return mixed|null
public function accept() { $path = $this->getInnerIterator()->key(); $result = $this->visitor->isAccepted($path); if ($result === PathVisitor::PATH_ACCEPTED) { return true; } if ($result === PathVisitor::FAKE_CONTENT) { $this->toFake[] = $path; } return false; }
Check whether the current element of the iterator is acceptable @link https://php.net/manual/en/filteriterator.accept.php @return bool true if the current element is acceptable, otherwise false. @since 5.1.0
private function getData(string $path) { if (empty($this->configurations)) { return null; } return $this->configurations[$path] ?? null; }
@param string $path @return mixed|null
protected function getPsrPath(array $autoloads): array { $allPath = []; foreach ($autoloads as $name => $autoload) { $prefix = $name; // PSR-0 and PSR-4 are the same if the namespace doesn't matter // And for us, it's the case $psrPath = array_merge($autoload['psr-4'] ?? [], $autoload['psr-0'] ?? []); // Only need the path (remove the namespace) $psrPath = array_values($psrPath); // Flatten path, as you can specify multiple path for one namespace $psrPath = array_reduce( $psrPath, /** * @param string[] $carry * @param string[]|string $item * * @return string[] */ function ($carry, $item): array { if (\is_array($item)) { return array_merge($carry, $item); } $carry[] = $item; return $carry; }, [] ); if (!is_int($prefix)) { // Add the package name (<=> path in vendor dir) $psrPath = array_map(function (string $path) use ($prefix): string { return $prefix . DIRECTORY_SEPARATOR . $path; }, $psrPath); } $allPath = array_merge($allPath, $psrPath); } return $allPath; }
@param array $autoloads @return string[]
protected function getFilesPath(array $autoloads, bool $withClassmap): array { $allPath = []; foreach ($autoloads as $name => $autoload) { $prefix = $name; $filePath = $autoload['files'] ?? []; // "files" and "classmap" have a very similar behavior if ($withClassmap) { $filePath = array_merge($filePath, $autoload['classmap'] ?? []); } // Flatten path, as you can specify multiple path for one namespace $filePath = array_reduce( $filePath, /** * @param string[] $carry * @param string[]|string $item * * @return string[] */ function (array $carry, $item): array { if (\is_array($item)) { return array_merge($carry, $item); } $carry[] = $item; return $carry; }, [] ); if (!is_int($prefix)) { // Add the package name (<=> path in vendor dir) $filePath = array_map(function (string $path) use ($prefix): string { return $prefix . DIRECTORY_SEPARATOR . $path; }, $filePath); } $allPath = array_merge($allPath, $filePath); } return $allPath; }
@param array $autoloads @param bool $withClassmap @return string[]
public function handle(EventInterface $event) { if ($event instanceof StatsEvent) { $this->writeProgressionLine(''); $this->style->success('Phar creation successful'); $this->style->table([], [ ['Path', '<info>' . $event->getStats()->getFinalPath() . '</info>'], ['File size', '<info>' . $event->getSize() . '</info>'], ['Process duration', '<info>' . $event->getDuration() . '</info>'] ]); } if ($event instanceof BuilderAddEvent) { $this->writeProgressionLine('Adding <comment>' . $event->getPath() . '</comment>'); } if ($event instanceof CompressorEvent) { $this->writeProgressionLine('<info>Compressing...</info>'); } if (0 === strpos($event->getName(), 'options.')) { $this->writeProgressionLine( '<comment>Read options...</comment> (' . ucfirst(substr($event->getName(), \strlen('options.'))) . ')', true ); } }
Handle an event. @param EventInterface $event @return void
private function getOnePathData($data, string $root, bool $allowFiles, bool $allowDirs): ?string { if ($data === null) { return null; } if (!\is_array($data)) { $data = [$data]; } $result = $this->existingPaths($data, $root, $allowFiles, $allowDirs); if ($result === null || \count($result) !== 1) { return null; } return reset($result); }
@param string|string[]|null $data @param string $root @param bool $allowFiles @param bool $allowDirs @return string|null
private function getPathsData($data, string $root): ?array { if ($data === null || !\is_array($data) || \count($data) === 0) { return null; } return $this->existingPaths($data, $root); }
@param string|string[]|null $data @param string $root @return array|null
private function getOptionalOption(string $functionName, string $message) { if (!array_key_exists($functionName, $this->optionsCache)) { $option = $this->parentOptions->{$functionName}(); if ($option === null) { throw new MissingConfigurationException($message); } $this->optionsCache[$functionName] = $option; } return $this->optionsCache[$functionName]; }
@param string $functionName @param string $message @return mixed
private function getOption(string $functionName) { if (!array_key_exists($functionName, $this->optionsCache)) { $this->optionsCache[$functionName] = $this->parentOptions->{$functionName}(); } return $this->optionsCache[$functionName]; }
@param string $functionName @return mixed
public function up() { Schema::create(config('cortex.auth.tables.permissions'), function (Blueprint $table) { // Columns $table->integer('ability_id')->unsigned(); $table->integer('entity_id')->unsigned(); $table->string('entity_type', 150); $table->boolean('forbidden')->default(false); $table->integer('scope')->nullable(); // Indexes $table->index(['scope']); $table->index(['ability_id']); $table->index(['entity_id', 'entity_type', 'scope'], 'permissions_entity_index'); $table->foreign('ability_id')->references('id')->on(config('cortex.auth.tables.abilities')) ->onDelete('cascade')->onUpdate('cascade'); }); }
Run the migrations. @return void
public function ajax() { return datatables($this->query()) ->setTransformer(app($this->transformer)) ->orderColumn('title', 'title->"$.'.app()->getLocale().'" $1') ->make(true); }
Display ajax response. @return \Illuminate\Http\JsonResponse
public function register($name, Closure $callback): void { if ($this->has($name)) { $this->callbacks = $this->callbacks->put($name, $this->callbacks->get($name, collect())->push($callback)); } else { $builder = new MenuGenerator(); $builder->setViewFactory($this->viewFactory); $this->menus->put($name, $builder); $this->callbacks = $this->callbacks->put($name, $this->callbacks->get($name, collect())->push($callback)); } }
Register a menu. @param string $name @param \Closure $callback @return void
public function render(string $name, string $presenter = null, array $bindings = [], bool $specialSidebar = false): ?string { if ($this->has($name)) { $instance = $this->instance($name); $this->callbacks->get($name)->each(function ($callback) use ($instance) { $reflectionParams = collect((new ReflectionFunction($callback))->getParameters()); $reflectionParams->shift(); collect($reflectionParams)->each(function ($param) use (&$params) { $params[] = Route::current()->hasParameter($param->getName()) ? Route::current()->parameter($param->getName()) : (class_exists($param->getClass()->getName()) ? app($param->getClass()->getName()) : null); }); $params ? $callback($instance, ...$params) : $callback($instance); }); return $instance->setBindings($bindings)->render($presenter, $specialSidebar); } return null; }
Render the menu tag by given name. @param string $name @param string $presenter @param array $bindings @param bool $specialSidebar @return string|null
public function handle($request, Closure $next, string $type = 'password', string $sessionName = null, int $timeout = null, bool $renew = false) { $timeout = $timeout ?? config('cortex.auth.reauthentication.timeout'); $sessionName = $sessionName ? 'cortex.auth.reauthentication.'.$sessionName : 'cortex.auth.reauthentication.'.$request->route()->getName(); if (is_null(session($sessionName)) || time() - session($sessionName) >= $timeout) { session()->forget($sessionName); session()->put('cortex.auth.reauthentication.intended', $request->url()); session()->put('cortex.auth.reauthentication.session_name', $sessionName); return view('cortex/auth::'.$request->route('accessarea').'.pages.reauthentication-'.$type); } ! $renew || session()->put($sessionName, time()); return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @param string $type @param string $sessionName @param int $timeout @param bool $renew @return mixed
public function authorize(): bool { $twoFactor = $this->user($this->route('guard'))->getTwoFactor(); if (! $twoFactor['totp']['enabled']) { throw new GenericException(trans('cortex/auth::messages.verification.twofactor.totp.cant_backup'), route('adminarea.account.settings')); } return true; }
Determine if the user is authorized to make this request. @throws \Cortex\Foundation\Exceptions\GenericException @return bool
public function toMail($notifiable): MailMessage { return (new MailMessage()) ->subject(trans('cortex/auth::emails.register.welcome.subject')) ->line(config('cortex.auth.registration.moderated') ? trans('cortex/auth::emails.register.welcome.intro_moderation') : trans('cortex/auth::emails.register.welcome.intro_default') ); }
Build the mail representation of the notification. @param mixed $notifiable @return \Illuminate\Notifications\Messages\MailMessage
protected function prepareForValidation(): void { $data = $this->all(); $country = $data['country_code'] ?? null; $email = $data['email'] ?? null; $phone = $data['phone'] ?? null; $user = $this->user($this->route('guard')); $twoFactor = $user->getTwoFactor(); if ($email !== $user->email) { $data['email_verified_at'] = null; } if ($phone !== $user->phone || $country !== $user->country_code) { $data['phone_verified_at'] = null; } if ($twoFactor || is_null($data['phone_verified_at'])) { array_set($twoFactor, 'phone.enabled', false); $data['two_factor'] = $twoFactor; } $this->replace($data); }
Prepare the data for validation. @return void
public function rules(): array { $user = $this->user($this->route('guard')); $user->updateRulesUniques(); return $user->getRules(); }
Get the validation rules that apply to the request. @return array
public function enableTotp(Request $request, Google2FA $totpProvider) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); if (! $secret = array_get($twoFactor, 'totp.secret')) { $twoFactor['totp'] = [ 'enabled' => false, 'secret' => $secret = $totpProvider->generateSecretKey(), ]; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); } $qrCode = $totpProvider->getQRCodeInline(config('app.name'), $currentUser->email, $secret); return view('cortex/auth::adminarea.pages.account-twofactor-totp', compact('secret', 'qrCode', 'twoFactor')); }
Enable TwoFactor TOTP authentication. @param \Illuminate\Http\Request $request @param \PragmaRX\Google2FA\Google2FA $totpProvider @return \Illuminate\View\View
public function updateTotp(AccountTwoFactorTotpProcessRequest $request, Google2FA $totpProvider) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $secret = array_get($twoFactor, 'totp.secret'); $backup = array_get($twoFactor, 'totp.backup'); $backupAt = array_get($twoFactor, 'totp.backup_at'); if ($totpProvider->verifyKey($secret, $request->get('token'))) { $twoFactor['totp'] = [ 'enabled' => true, 'secret' => $secret, 'backup' => $backup ?? $this->generateTotpBackups(), 'backup_at' => $backupAt ?? now()->toDateTimeString(), ]; // Update TwoFactor settings $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.totp.enabled')], ]); } return intend([ 'back' => true, 'withErrors' => ['token' => trans('cortex/auth::messages.verification.twofactor.totp.invalid_token')], ]); }
Process the TwoFactor TOTP enable form. @param \Cortex\Auth\Http\Requests\Adminarea\AccountTwoFactorTotpProcessRequest $request @param \PragmaRX\Google2FA\Google2FA $totpProvider @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function backupTotp(AccountTwoFactorTotpBackupRequest $request) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['totp']['backup'] = $this->generateTotpBackups(); $twoFactor['totp']['backup_at'] = now()->toDateTimeString(); $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.totp.rebackup')], ]); }
Process the TwoFactor OTP backup. @param \Cortex\Auth\Http\Requests\Adminarea\AccountTwoFactorTotpBackupRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function enablePhone(AccountTwoFactorPhoneRequest $request) { $currentUser = $request->user($this->getGuard()); $currentUser->routeNotificationForAuthy(); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['phone']['enabled'] = true; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.phone.enabled')], ]); }
Enable TwoFactor Phone authentication. @param \Cortex\Auth\Http\Requests\Adminarea\AccountTwoFactorPhoneRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function disablePhone(Request $request) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['phone']['enabled'] = false; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.phone.disabled')], ]); }
Disable TwoFactor Phone authentication. @param \Illuminate\Http\Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
protected function generateTotpBackups(): array { $backup = []; for ($x = 0; $x <= 9; $x++) { $backup[] = str_pad((string) random_int(0, 9999999999), 10, '0', STR_PAD_BOTH); } return $backup; }
Generate TwoFactor OTP backup codes. @return array
public function encodeDecimal($integer, $options) { if ($integer === 1 << (\PHP_INT_SIZE * 8 - 1)) { return sprintf('(int)%s%d', $options['whitespace'] ? ' ' : '', $integer); } return var_export($integer, true); }
Encodes an integer into decimal representation. @param int $integer The integer to encode @param array $options The integer encoding options @return string The PHP code representation for the integer
public function encodeHexadecimal($integer, $options) { if ($options['hex.capitalize']) { return sprintf('%s0x%X', $this->sign($integer), abs($integer)); } return sprintf('%s0x%x', $this->sign($integer), abs($integer)); }
Encodes an integer into hexadecimal representation. @param int $integer The integer to encode @param array $options The integer encoding options @return string The PHP code representation for the integer
public function getCulture($culture = null): ?array { return $this->getCultures()[$culture] ?? (! empty($this->getCultures()) ? current($this->getCultures()) : null); }
Get the given culture. @param string|null $culture @return array|null
public function findBy(string $key, string $value, callable $callback = null): ?MenuItem { $item = $this->items->filter(function ($item) use ($key, $value) { return $item->{$key} === $value; })->first(); (! is_callable($callback) || ! $item) || call_user_func($callback, $item); return $item; }
Find menu item by given key and value. @param string $key @param string $value @param callable $callback @return \Rinvex\Menus\Models\MenuItem|null
public function findByTitleOrAdd(string $title, int $order = null, string $icon = null, array $attributes = [], callable $callback = null): ?MenuItem { if (! ($item = $this->findBy('title', $title, $callback))) { $item = $this->add(compact('title', 'order', 'icon', 'attributes')); ! is_callable($callback) || call_user_func($callback, $item); } return $item; }
Find menu item by given key and value. @param string $title @param int $order @param string $icon @param array $attributes @param callable $callback @return \Rinvex\Menus\Models\MenuItem|null
protected function resolveItems(Collection &$items): void { $resolver = function ($property) { return $this->resolve($property) ?: $property; }; $items->each(function (MenuItem $item) use ($resolver) { $item->fill(array_map($resolver, $item->properties)); }); }
Resolves an array of menu items properties. @param \Illuminate\Support\Collection &$items @return void
protected function add(array $properties = []): MenuItem { $properties['attributes']['id'] = $properties['attributes']['id'] ?? md5(json_encode($properties)); $this->items->push($item = new MenuItem($properties)); return $item; }
Add new child menu. @param array $properties @return \Rinvex\Menus\Models\MenuItem
public function dropdown(callable $callback, string $title, int $order = null, string $icon = null, array $attributes = []): MenuItem { call_user_func($callback, $item = $this->add(compact('title', 'order', 'icon', 'attributes'))); return $item; }
Create new menu with dropdown. @param callable $callback @param string $title @param int $order @param string $icon @param array $attributes @return \Rinvex\Menus\Models\MenuItem
public function url(string $url, string $title, int $order = null, string $icon = null, array $attributes = []): MenuItem { ! $this->urlPrefix || $url = $this->formatUrl($url); return $this->add(compact('url', 'title', 'order', 'icon', 'attributes')); }
Register new menu item using url. @param string $url @param string $title @param int $order @param string $icon @param array $attributes @return \Rinvex\Menus\Models\MenuItem
public function divider(int $order = null, array $attributes = []): MenuItem { return $this->add(['type' => 'divider', 'order' => $order, 'attributes' => $attributes]); }
Add new divider item. @param int $order @param array $attributes @return \Rinvex\Menus\Models\MenuItem
public function render(string $presenter = null, bool $specialSidebar = false): string { $this->resolveItems($this->items); if (! is_null($this->view)) { return $this->renderView($presenter, $specialSidebar)->render(); } (! $presenter || ! $this->presenterExists($presenter)) || $this->setPresenter($presenter); return $this->renderMenu($specialSidebar); }
Render the menu to HTML tag. @param string $presenter @param bool $specialSidebar @return string
protected function renderView(string $view, bool $specialSidebar = false): ViewContract { return $this->views->make($view, ['items' => $this->getOrderedItems(), 'specialSidebar' => $specialSidebar]); }
Render menu via view presenter. @param string $view @param bool $specialSidebar @return \Illuminate\Contracts\View\View
protected function renderMenu(bool $specialSidebar = false): string { $presenter = $this->getPresenter(); $menu = $presenter->getOpenTagWrapper(); foreach ($this->getOrderedItems() as $item) { if ($item->isHidden()) { continue; } if ($item->hasChilds()) { $menu .= $presenter->getMenuWithDropDownWrapper($item, $specialSidebar); } elseif ($item->isHeader()) { $menu .= $presenter->getHeaderWrapper($item); } elseif ($item->isDivider()) { $menu .= $presenter->getDividerWrapper(); } else { $menu .= $presenter->getMenuWithoutDropdownWrapper($item); } } $menu .= $presenter->getCloseTagWrapper(); return $menu; }
Render the menu. @param bool $specialSidebar @return string