code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function actionView($name) { $formModel = new AddAuthItemForm(); /* @var $am CAuthManager|AuthBehavior */ $am = Yii::app()->getAuthManager(); if (isset($_POST['AddAuthItemForm'])) { $formModel->attributes = $_POST['AddAuthItemForm']; if ($formModel->validate()) { if (!$am->hasItemChild($name, $formModel->items)) { $am->addItemChild($name, $formModel->items); if ($am instanceof CPhpAuthManager) { $am->save(); } } } } $item = $am->getAuthItem($name); $dpConfig = array( 'pagination' => false, 'sort' => array('defaultOrder' => 'depth asc'), ); $ancestors = $am->getAncestors($name); $ancestorDp = new PermissionDataProvider(array_values($ancestors), $dpConfig); $descendants = $am->getDescendants($name); $descendantDp = new PermissionDataProvider(array_values($descendants), $dpConfig); $childOptions = $this->getItemChildOptions($item->name); if (!empty($childOptions)) { $childOptions = array_merge(array('' => Yii::t('AuthModule.main', 'Select item') . ' ...'), $childOptions); } $this->render( 'view', array( 'item' => $item, 'ancestorDp' => $ancestorDp, 'descendantDp' => $descendantDp, 'formModel' => $formModel, 'childOptions' => $childOptions, ) ); }
Displays the item with the given name. @param string $name name of the item.
public function actionDelete() { if (isset($_GET['name'])) { $name = $_GET['name']; /* @var $am CAuthManager|AuthBehavior */ $am = Yii::app()->getAuthManager(); $item = $am->getAuthItem($name); if ($item instanceof CAuthItem) { $am->removeAuthItem($name); if ($am instanceof CPhpAuthManager) { $am->save(); } if (!isset($_POST['ajax'])) { $this->redirect(array('index')); } } else { throw new CHttpException(404, Yii::t('AuthModule.main', 'Item does not exist.')); } } else { throw new CHttpException(400, Yii::t('AuthModule.main', 'Invalid request.')); } }
Deletes the item with the given name. @throws CHttpException if the item does not exist or if the request is invalid.
public function actionRemoveParent($itemName, $parentName) { /* @var $am CAuthManager|AuthBehavior */ $am = Yii::app()->getAuthManager(); if ($am->hasItemChild($parentName, $itemName)) { $am->removeItemChild($parentName, $itemName); if ($am instanceof CPhpAuthManager) { $am->save(); } } $this->redirect(array('view', 'name' => $itemName)); }
Removes the parent from the item with the given name. @param string $itemName name of the item. @param string $parentName name of the parent.
public function actionRemoveChild($itemName, $childName) { /* @var $am CAuthManager|AuthBehavior */ $am = Yii::app()->getAuthManager(); if ($am->hasItemChild($itemName, $childName)) { $am->removeItemChild($itemName, $childName); if ($am instanceof CPhpAuthManager) { $am->save(); } } $this->redirect(array('view', 'name' => $itemName)); }
Removes the child from the item with the given name. @param string $itemName name of the item. @param string $childName name of the child.
protected function getItemChildOptions($itemName) { $options = array(); /* @var $am CAuthManager|AuthBehavior */ $am = Yii::app()->getAuthManager(); $item = $am->getAuthItem($itemName); if ($item instanceof CAuthItem) { $exclude = $am->getAncestors($itemName); $exclude[$itemName] = $item; $exclude = array_merge($exclude, $item->getChildren()); $authItems = $am->getAuthItems(); $validChildTypes = $this->getValidChildTypes(); foreach ($authItems as $childName => $childItem) { if (in_array($childItem->type, $validChildTypes) && !isset($exclude[$childName])) { $options[$this->capitalize( $this->getItemTypeText($childItem->type, true) )][$childName] = $childItem->description; } } } return $options; }
Returns a list of possible children for the item with the given name. @param string $itemName name of the item. @return array the child options.
protected function getValidChildTypes() { $validTypes = array(); switch ($this->type) { case CAuthItem::TYPE_OPERATION: break; case CAuthItem::TYPE_TASK: $validTypes[] = CAuthItem::TYPE_OPERATION; break; case CAuthItem::TYPE_ROLE: $validTypes[] = CAuthItem::TYPE_OPERATION; $validTypes[] = CAuthItem::TYPE_TASK; break; } if (!$this->module->strictMode) { $validTypes[] = $this->type; } return $validTypes; }
Returns a list of the valid child types for the given type. @return array the valid types.
public function checkAccess($itemName, $userId, $params = array(), $allowCaching = true) { $cacheKey = $this->resolveCacheKey($itemName, $userId); $key = serialize($params); if ($allowCaching && ($cache = $this->getCache()) !== null) { if (($data = $cache->get($cacheKey)) !== false) { $data = unserialize($data); if (isset($data[$key])) { return $data[$key]; } } } else { $data = array(); } $result = $data[$key] = parent::checkAccess($itemName, $userId, $params); if (isset($cache)) { $cache->set($cacheKey, serialize($data), $this->cachingDuration); } return $result; }
Performs access check for the specified user. @param string $itemName the name of the operation that need access check. @param integer $userId the user id. @param array $params name-value pairs that would be passed to biz rules associated with the tasks and roles assigned to the user. @param boolean $allowCaching whether to allow caching the result of access check. @return boolean whether the operations can be performed by the user.
public function flushAccess($itemName, $userId) { if (($cache = $this->getCache()) !== null) { $cacheKey = $this->resolveCacheKey($itemName, $userId); return $cache->delete($cacheKey); } return false; }
Flushes the access cache for the specified user. @param string $itemName the name of the operation that need access check. @param integer $userId the user id. @return boolean whether access was flushed.
protected function getCache() { return $this->cachingDuration > 0 && $this->cacheID !== false ? Yii::app()->getComponent($this->cacheID) : null; }
Returns the caching component for this component. @return CCache|null the caching component.
public function getClassMetadata($class) { $class = ltrim($class, '\\'); //Already parsed if ($this->isParsed($class)) { return $this->getParsedClass($class); } //Check Cache for it if ($this->cache !== null && $this->cache->contains($class)) { $this->setParsedClass($class, $this->cache->fetch($class)); return $this->getParsedClass($class); } //Parse unloaded and uncached class return $this->parseClassMetadata($class); }
{@inheritDoc}
private function parseClassMetadata($class) { $metadata = new ClassMetadata($class); //Load up parent and interfaces $this->loadParentMetadata($metadata); $this->loadInterfaceMetadata($metadata); //Load Annotations from Reader $this->loader->loadClassMetadata($metadata); //Store internally $this->setParsedClass($class, $metadata); if ($this->cache !== null) { $this->cache->save($class, $metadata); } return $metadata; }
Reads class metadata for a new and unparsed class @param string $class @return ClassMetadataInterface
protected function loadParentMetadata(ClassMetadataInterface $metadata) { $parent = $metadata->getReflectionClass()->getParentClass(); if ($parent) { $metadata->mergeRules($this->getClassMetadata($parent->getName())); } }
Checks if the class being parsed has a parent and cascades parsing to its parent @param ClassMetadataInterface $metadata
protected function preFilter($filterChain) { $itemName = ''; $controller = $filterChain->controller; /* @var $user CWebUser */ $user = Yii::app()->getUser(); if (($module = $controller->getModule()) !== null) { $itemName .= $module->getId() . '.'; if ($user->checkAccess($itemName . '*')) { return true; } } $itemName .= $controller->getId(); if ($user->checkAccess($itemName . '.*')) { return true; } $itemName .= '.' . $controller->action->getId(); if ($user->checkAccess($itemName, $this->params)) { return true; } if ($user->isGuest) { $user->loginRequired(); } throw new CHttpException(401, Yii::t('yii', 'You are not authorized to perform this action.')); }
Performs the pre-action filtering. @param CFilterChain $filterChain the filter chain that the filter is on. @return boolean whether the filtering process should continue and the action should be executed. @throws CHttpException if the user is denied access.
protected function renderDataCellContent($row, $data) { if ($this->userId !== null) { echo TbHtml::linkButton( TbHtml::icon(TbHtml::ICON_REMOVE), array( 'color' => TbHtml::BUTTON_COLOR_LINK, 'size' => TbHtml::BUTTON_SIZE_MINI, 'url' => array('revoke', 'itemName' => $data['name'], 'userId' => $this->userId), 'rel' => 'tooltip', 'title' => Yii::t('AuthModule.main', 'Revoke'), ) ); } }
Renders the data cell content. @param integer $row the row number (zero-based). @param mixed $data the data associated with the row.
public function getLoginUrl(string $redirectUrl, array $permissions = ['public_profile'], ?string $stateParam = null): string { // Create redirect URL with econea return URL $helper = $this->facebook->getRedirectLoginHelper(); // Set our own state param if (isset($stateParam)) { $helper->getPersistentDataHandler()->set('state', $stateParam); } $url = $helper->getLoginUrl($redirectUrl, $permissions); return $url; }
Creates Response that redirects person to FB for authorization and back @param string[] $permissions
public function getAccessToken(): AccessToken { $helper = $this->facebook->getRedirectLoginHelper(); try { // Get accessToken from $_GET $accessToken = $helper->getAccessToken(); // Failed to get accessToken if (!isset($accessToken)) { if ($helper->getError() !== null) { throw new FacebookLoginException($helper->getError()); } else { throw new FacebookLoginException('Facebook: Bad request.'); } } $accessToken = $this->getLongLifeValidatedToken($accessToken); } catch (FacebookResponseException | FacebookSDKException $e) { throw new FacebookLoginException($e->getMessage()); } return $accessToken; }
Gets access token from fb for queried user @throws FacebookLoginException
public static function fromSha($sha, $baseUrl, ClientInterface $client) { $url = Project::getProjectBaseFromUrl($baseUrl) . '/git/trees'; return static::get($sha, $url, $client); }
Get the Tree object for an SHA hash. @param string $sha @param string $baseUrl @param ClientInterface $client @return static|false
public function getObject($path) { if ($path === '' || $path === '.') { return $this; } $data = $this->getObjectData($path); if ($data === false) { return false; } if ($data['type'] === 'blob') { return Blob::fromSha($data['sha'], $this->getUri(), $this->client); } elseif ($data['type'] === 'tree') { return Tree::fromSha($data['sha'], $this->getUri(), $this->client); } throw new \RuntimeException('Unrecognised object type: ' . $data['type']); }
Get an object in this tree. @param string $path The path to an object in the tree. @return Blob|Tree|false A Blob or Tree object, or false if the object does not exist.
private function getObjectData($path) { foreach ($this->tree as $objectData) { if ($objectData['path'] === $path) { return $objectData; } } return false; }
Find an object definition by its path. @param string $path @return array|false
private function getObjectRecursive($path) { $tree = $object = $this; foreach ($this->splitPath($path) as $part) { $object = $tree->getObject($part); if (!$object instanceof Tree) { return $object; } $tree = $object; } return $object; }
Get an object recursively in this tree. @param string $path @return Blob|Tree|false
public function getBlob($path) { $object = $this->getObjectRecursive($path); if ($object === false) { return false; } if ($object instanceof Blob) { return $object; } if ($object instanceof Tree) { throw new GitObjectTypeException('The requested file is a directory', $path); } return false; }
Get a Blob (file) inside this tree. @param string $path @throws GitObjectTypeException if the path is a directory. @return Blob|false A Blob object, or false if the blob is not found.
public function getTree($path) { $object = $this->getObjectRecursive($path); if ($object === false) { return false; } if ($object instanceof Tree) { return $object; } throw new GitObjectTypeException('Not a directory', $path); }
Get a Tree (directory) inside this tree. @param string $path @throws GitObjectTypeException if the path is not a directory. @return Tree|false A Tree object or false if the tree is not found.
public function triggerHook() { $hookUrl = $this->getLink('#hook'); $options = []; // The API needs us to send an empty JSON object. $options['json'] = new \stdClass(); // Switch off authentication for this request (none is required). $options['auth'] = null; $this->sendRequest($hookUrl, 'post', $options); }
Trigger the integration's web hook. Normally the external service should do this in response to events, but it may be useful to trigger the hook manually in certain cases.
public static function listValidationErrors(BadResponseException $exception) { $response = $exception->getResponse(); if ($response && $response->getStatusCode() === 400) { $response->getBody()->seek(0); $data = $response->json(); if (isset($data['detail']) && is_array($data['detail'])) { return $data['detail']; } } throw $exception; }
Process an API exception to list integration validation errors. @param \GuzzleHttp\Exception\BadResponseException $exception An exception received during integration create, update, or validate. @see \Platformsh\Client\Model\Integration::validate() @throws \GuzzleHttp\Exception\BadResponseException The original exception is re-thrown if specific validation errors cannot be found. @return string[] A list of errors.
public function renderForContentAction($contentId, Request $request) { return new Response( $this->commentsRenderer->renderForContent( $this->contentService->loadContentInfo($contentId), $request ) ); }
Renders the comments list for content with id $contentId Comment form might also be included. @param mixed $contentId @return Response
public function getActivities() { if (!isset($this->data['_embedded']['activities'])) { return []; } $activities = []; foreach ($this->data['_embedded']['activities'] as $data) { $activities[] = new Activity($data, $this->baseUrl, $this->client); } return $activities; }
Get activities embedded in the result. A result could embed 0, 1, or many activities. @return Activity[]
public function getEntity() { if (!isset($this->data['_embedded']['entity']) || !isset($this->resourceClass)) { throw new \Exception("No entity found in result"); } $data = $this->data['_embedded']['entity']; $resourceClass = $this->resourceClass; return new $resourceClass($data, $this->baseUrl, $this->client); }
Get the entity embedded in the result. @throws \Exception If no entity was embedded. @return ApiResourceBase An instance of ApiResourceBase - the implementing class name was set when this Result was instantiated.
public function getRawContent() { if ($this->size == 0) { return ''; } if ($this->encoding === 'base64') { $raw = base64_decode($this->content, true); if ($raw === false) { throw new \RuntimeException('Failed to decode content'); } return $raw; } throw new \RuntimeException('Unrecognised blob encoding: ' . $this->encoding); }
Get the raw content of the file. @return string
public static function camelize($term, $uppercase_first_letter = true){ $string = (string)$term; if( $uppercase_first_letter ){ $string = preg_replace_callback('/^[a-z\d]*/', function($matches){ return isset(static::inflections()->acronyms[$matches[0]]) ? static::inflections()->acronyms[$matches[0]] : ucfirst($matches[0]); }, $string, 1); }else{ $acronym_regex = static::inflections()->acronym_regex; $string = preg_replace_callback("/^(?:{$acronym_regex}(?=\b|[A-Z_])|\w)/", function($matches) { return strtolower($matches[0]); }, $string); } return preg_replace_callback('/(?:_|(\/))([a-z\d]*)/i', function($matches){ return str_replace('/', '\\', "{$matches[1]}" . (isset(static::inflections()->acronyms[$matches[2]]) ? static::inflections()->acronyms[$matches[2]] : ucfirst($matches[2]))); }, $string); }
By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+ is set to <tt>lower</tt> then +camelize+ produces lowerCamelCase. +camelize+ will also convert '/' to '\' which is useful for converting paths to namespaces. Examples: camelize("active_model" # => "ActiveModel" camelize("active_model", false) # => "activeModel" camelize("active_model/errors") # => "ActiveModel::Errors" camelize("active_model/errors", false) # => "activeModel::Errors" As a rule of thumb you can think of +camelize+ as the inverse of +underscore+, though there are cases where that does not hold: camelize(underscore("SSLError")) # => "SslError" @param string $term @param boolean $uppercase_first_letter @return string Camelized $term @author Koen Punt
public static function underscore($camel_cased_word){ $word = $camel_cased_word; $word = preg_replace('/\\\/', '/', $word); $acronym_regex = static::inflections()->acronym_regex; $word = preg_replace_callback("/(?:([A-Za-z\d])|^)({$acronym_regex})(?=\b|[^a-z])/", function($matches){ return "{$matches[1]}" . ($matches[1] ? '_' : '') . strtolower($matches[2]); }, $word); $word = preg_replace('/([A-Z\d]+)([A-Z][a-z])/','$1_$2', $word); $word = preg_replace('/([a-z\d])([A-Z])/','$1_$2', $word); $word = strtr($word, '-', '_'); $word = strtolower($word); return $word; }
Makes an underscored, lowercase form from the expression in the string. Changes '\' to '/' to convert namespaces to paths. Examples: underscore("ActiveRecord") # => "active_record" underscore("ActiveRecord\Errors") # => "active_record/errors" As a rule of thumb you can think of +underscore+ as the inverse of +camelize+, though there are cases where that does not hold: camelize(underscore("SSLError")) # => "SslError" @param string $camel_cased_word @return string Underscored $camel_cased_word @author Koen Punt
public static function humanize($lower_case_and_underscored_word){ $result = $lower_case_and_underscored_word; foreach(static::inflections()->humans as $rule => $replacement){ if(($result = preg_replace($rule, $replacement, $result, 1)))break; }; $result = preg_replace('/_id$/', "", $result); $result = strtr($result, '_', ' '); return ucfirst(preg_replace_callback('/([a-z\d]*)/i', function($matches){ return isset(static::inflections()->acronyms[$matches[0]]) ? static::inflections()->acronyms[$matches[0]] : strtolower($matches[0]); }, $result)); }
Capitalizes the first word and turns underscores into spaces and strips a trailing "_id", if any. Like +titleize+, this is meant for creating pretty output. Examples: titleize("employee_salary") # => "Employee salary" titleize("author_id") # => "Author" @param string $lower_case_and_underscored_word @return string Humanized $lower_case_and_underscored_word @author Koen Punt
public static function titleize($word){ return preg_replace_callback("/\b(?<!['’`])[a-z]/", function($r1) use ($word){ return ucfirst($r1[0]); }, static::humanize(static::underscore($word))); }
Capitalizes all the words and replaces some characters in the string to create a nicer looking title. +titleize+ is meant for creating pretty output. It is not used in the Rails internals. +titleize+ is also aliased as as +titlecase+. Examples: titleize("man from the boondocks") # => "Man From The Boondocks" titleize("x-men: the last stand") # => "X Men: The Last Stand" titleize("TheManWithoutAPast") # => "The Man Without A Past" titleize("raiders_of_the_lost_ark") # => "Raiders Of The Lost Ark" @param string $word @return string Titleized $word @author Koen Punt
private static function apply_inflections($word, $rules){ $result = $word; preg_match('/\b\w+\Z/', strtolower($result), $matches); if( empty($word) || array_search($matches[0], static::inflections()->uncountables) !== false ){ return $result; }else{ foreach($rules as $rule_replacement){ list($rule, $replacement) = $rule_replacement; $result = preg_replace($rule, $replacement, $result, -1, $count); if($count){ break; } } return $result; } }
Applies inflection rules for +singularize+ and +pluralize+. Examples: apply_inflections("post", inflections()->plurals) # => "posts" apply_inflections("posts", inflections()->singulars) # => "post" @param string $word @param array $rules @return string inflected $word @author Koen Punt
private function load() { if (!$this->loaded && isset($this->storage)) { $this->data = $this->storage->load($this->id); $this->original = $this->data; $this->loaded = true; } }
Load session data, if storage is defined.
public function MetaTags(&$tags) { // Only attempt to replace <title> tag if it has been included, as it won't // be included if called via $MetaTags(false) if (preg_match("/<title>(.+)<\/title>/i", $tags)) { $format = Config::inst()->get(static::class, 'title_format'); $data = ArrayData::create([ 'MetaTitle' => $this->owner->MetaTitle ? $this->owner->obj('MetaTitle') : $this->owner->obj('Title') ]); $newTitleTag = HTML::createTag('title', [], SSViewer::execute_string($format, $data)); $tags = preg_replace("/<title>(.+)<\/title>/i", $newTitleTag, $tags); } }
Replace the <title> tag (if present) with the format provided in the title_format config setting. Will fall back to 'Title' if 'MetaTitle' is empty @param string &$tags
public static function validatePublicKey($value) { $value = preg_replace('/\s+/', ' ', $value); if (!strpos($value, ' ')) { return false; } list($type, $key) = explode(' ', $value, 3); if (!in_array($type, static::$allowedAlgorithms) || base64_decode($key, true) === false) { return false; } return true; }
Validate an SSH public key. @param string $value @return bool
public function buildDisqus($disqusProviderClass) { /** @var \EzSystems\CommentsBundle\Comments\Provider\DisqusProvider $disqusProvider */ $disqusProvider = new $disqusProviderClass(); $disqusProvider->setTemplateEngine($this->templateEngine); $disqusProvider->setDefaultTemplate( $this->configResolver->getParameter('disqus.default_template', 'ez_comments') ); $disqusProvider->setShortName($this->configResolver->getParameter('disqus.shortname', 'ez_comments')); $disqusProvider->setCount($this->configResolver->getParameter('disqus.count', 'ez_comments')); return $disqusProvider; }
@param string $disqusProviderClass @return \EzSystems\CommentsBundle\Comments\ProviderInterface
public function buildFacebook(LocationService $locationService, RouterInterface $router) { $facebookProvider = new FacebookProvider( $this->configResolver->getParameter('facebook.app_id', 'ez_comments'), array( 'width' => $this->configResolver->getParameter('facebook.width', 'ez_comments'), 'num_posts' => $this->configResolver->getParameter('facebook.num_posts', 'ez_comments'), 'color_scheme' => $this->configResolver->getParameter('facebook.color_scheme', 'ez_comments'), 'include_sdk' => $this->configResolver->getParameter('facebook.include_sdk', 'ez_comments'), ), $locationService, $router, $this->templateEngine, $this->configResolver->getParameter('facebook.default_template', 'ez_comments') ); return $facebookProvider; }
@param LocationService $locationService @param RouterInterface $router @return \EzSystems\CommentsBundle\Comments\ProviderInterface
public static function get($id, $collectionUrl = null, ClientInterface $client) { try { $url = $collectionUrl ? rtrim($collectionUrl, '/') . '/' . urlencode($id) : $id; $request = new Request('get', $url); $data = self::send($request, $client); return new static($data, $url, $client, true); } catch (BadResponseException $e) { $response = $e->getResponse(); if ($response && $response->getStatusCode() === 404) { return false; } throw $e; } }
Get a resource by its ID. @param string $id The ID of the resource, or the full URL. @param string $collectionUrl The URL of the collection. @param ClientInterface $client A suitably configured Guzzle client. @return static|false The resource object, or false if the resource is not found.
public static function create(array $body, $collectionUrl, ClientInterface $client) { if ($errors = static::checkNew($body)) { $message = "Cannot create resource due to validation error(s): " . implode('; ', $errors); throw new \InvalidArgumentException($message); } $request = new Request('post', $collectionUrl, [], \GuzzleHttp\json_encode($body)); $data = self::send($request, $client); return new Result($data, $collectionUrl, $client, get_called_class()); }
Create a resource. @param array $body @param string $collectionUrl @param ClientInterface $client @return Result
public static function send(RequestInterface $request, ClientInterface $client, array $options = []) { $response = null; try { $response = $client->send($request, $options); $body = $response->getBody()->getContents(); $data = []; if ($body) { $response->getBody()->seek(0); $body = $response->getBody()->getContents(); $data = \GuzzleHttp\json_decode($body, true); } return (array) $data; } catch (BadResponseException $e) { throw ApiResponseException::create($e->getRequest(), $e->getResponse()); } catch (\InvalidArgumentException $e) { throw ApiResponseException::create($request, $response); } }
Send a Guzzle request. Using this method allows exceptions to be standardized. @param RequestInterface $request @param ClientInterface $client @param array $options @internal @return array
protected function sendRequest($url, $method = 'get', array $options = []) { return $this->send( new Request($method, $url), $this->client, $options ); }
A simple helper function to send an HTTP request. @param string $url @param string $method @param array $options @return array
protected static function checkNew(array $data) { $errors = []; if ($missing = array_diff(static::getRequired(), array_keys($data))) { $errors[] = 'Missing: ' . implode(', ', $missing); } foreach ($data as $key => $value) { $errors += static::checkProperty($key, $value); } return $errors; }
Validate a new resource. @param array $data @return string[] An array of validation errors.
public static function getCollection($url, $limit = 0, array $options = [], ClientInterface $client) { // @todo uncomment this when the API implements a 'count' parameter // if ($limit) { // $options['query']['count'] = $limit; // } $request = new Request('get', $url); $data = self::send($request, $client, $options); // @todo remove this when the API implements a 'count' parameter if ($limit) { $data = array_slice($data, 0, $limit); } return static::wrapCollection($data, $url, $client); }
Get a collection of resources. @param string $url The collection URL. @param int $limit A limit on the number of resources to return. @param array $options An array of additional Guzzle request options. @param ClientInterface $client A suitably configured Guzzle client. @return static[]
public static function wrapCollection(array $data, $baseUrl, ClientInterface $client) { $resources = []; foreach ($data as $item) { $resources[] = new static($item, $baseUrl, $client); } return $resources; }
Create an array of resource instances from a collection's JSON data. @param array $data The deserialized JSON from the collection (i.e. a list of resources, each of which is an array of data). @param string $baseUrl The URL to the collection. @param ClientInterface $client A suitably configured Guzzle client. @return static[]
protected function runOperation($op, $method = 'post', array $body = []) { if (!$this->operationAvailable($op, true)) { throw new OperationUnavailableException("Operation not available: $op"); } $options = []; if (!empty($body)) { $options['json'] = $body; } $request= new Request($method, $this->getLink("#$op")); $data = $this->send($request, $this->client, $options); return new Result($data, $this->baseUrl, $this->client, get_called_class()); }
Execute an operation on the resource. @param string $op @param string $method @param array $body @return Result
protected function runLongOperation($op, $method = 'post', array $body = []) { $result = $this->runOperation($op, $method, $body); $activities = $result->getActivities(); if (count($activities) !== 1) { trigger_error(sprintf("Expected one activity, found %d", count($activities)), E_USER_WARNING); } return reset($activities); }
Run a long-running operation. @param string $op @param string $method @param array $body @return Activity
public function hasProperty($property, $lazyLoad = true) { if (!$this->isProperty($property)) { return false; } if (!array_key_exists($property, $this->data) && $lazyLoad) { $this->ensureFull(); } return array_key_exists($property, $this->data); }
Check whether a property exists in the resource. @param string $property @param bool $lazyLoad @return bool
public function getProperty($property, $required = true, $lazyLoad = true) { if (!$this->hasProperty($property, $lazyLoad)) { if ($required) { throw new \InvalidArgumentException("Property not found: $property"); } return null; } return $this->data[$property]; }
Get a property of the resource. @param string $property @param bool $required @param bool $lazyLoad @throws \InvalidArgumentException If $required is true and the property is not found. @return mixed|null The property value, or null if the property does not exist (and $required is false).
public function delete() { $data = $this->sendRequest($this->getUri(), 'delete'); return new Result($data, $this->getUri(), $this->client, get_called_class()); }
Delete the resource. @return Result
public function update(array $values) { if ($errors = $this->checkUpdate($values)) { $message = "Cannot update resource due to validation error(s): " . implode('; ', $errors); throw new \InvalidArgumentException($message); } $data = $this->runOperation('edit', 'patch', $values)->getData(); if (isset($data['_embedded']['entity'])) { $this->setData($data['_embedded']['entity']); $this->isFull = true; } return new Result($data, $this->baseUrl, $this->client, get_called_class()); }
Update the resource. This updates the resource's internal data with the API response. @param array $values @return Result
protected static function checkUpdate(array $values) { $errors = []; foreach ($values as $key => $value) { $errors += static::checkProperty($key, $value); } return $errors; }
Validate values for update. @param array $values @return string[] An array of validation errors.
public function refresh(array $options = []) { $request = new Request('get', $this->getUri()); $this->setData(self::send($request, $this->client, $options)); $this->isFull = true; }
Refresh the resource. @param array $options
public function operationAvailable($op, $refreshDuringCheck = false) { // Ensure this resource is a full representation. if (!$this->isFull) { $this->refresh(); $refreshDuringCheck = false; } // Check if the operation is available in the HAL links. $available = $this->isOperationAvailable($op); if ($available) { return true; } // If not, and $refreshDuringCheck is on, then refresh the resource. if ($refreshDuringCheck) { $this->refresh(); $available = $this->isOperationAvailable($op); } return $available; }
Check whether an operation is available on the resource. @param string $op @param bool $refreshDuringCheck @return bool
public function getLink($rel, $absolute = true) { if (!$this->hasLink($rel)) { throw new \InvalidArgumentException("Link not found: $rel"); } $url = $this->data['_links'][$rel]['href']; if ($absolute && strpos($url, '//') === false) { $url = $this->makeAbsoluteUrl($url); } return $url; }
Get a link for a given resource relation. @param string $rel @param bool $absolute @return string
protected function makeAbsoluteUrl($relativeUrl, $baseUrl = null) { $baseUrl = $baseUrl ?: $this->baseUrl; if (empty($baseUrl)) { throw new \RuntimeException('No base URL'); } $base = \GuzzleHttp\Psr7\uri_for($baseUrl); return $base->withPath($relativeUrl)->__toString(); }
Make a URL absolute, based on the base URL. @param string $relativeUrl @param string $baseUrl @return string
public function getProperties($lazyLoad = true) { if ($lazyLoad) { $this->ensureFull(); } $keys = $this->getPropertyNames(); return array_intersect_key($this->data, array_flip($keys)); }
Get an array of this resource's properties and their values. @param bool $lazyLoad @return array
public function disable() { if (!$this->getProperty('is_enabled')) { return new Result([], $this->baseUrl, $this->client, get_called_class()); } return $this->update(['is_enabled' => false]); }
Disable the variable. This is only useful if the variable is both inherited and enabled. Non-inherited variables can be deleted. @return Result
protected function getDefaultDirectory() { // Default to ~/.platformsh/.session, but if it's not writable, fall // back to the temporary directory. $default = $this->getHomeDirectory() . '/.platformsh/.session'; if ($this->canWrite($default)) { return $default; } $temp = sys_get_temp_dir() . '/.platformsh-client/.session'; if ($this->canWrite($temp)) { return $temp; } throw new \RuntimeException('Unable to find a writable session storage directory'); }
Get the default directory for session files. @return string
protected function canWrite($path) { if (is_writable($path)) { return true; } $current = $path; while (!file_exists($current) && ($parent = dirname($current)) && $parent !== $current) { if (is_writable($parent)) { return true; } $current = $parent; } return false; }
Tests whether a file path is writable (even if it doesn't exist). @param string $path @return bool
protected function getHomeDirectory() { $home = getenv('HOME'); if (!$home && ($userProfile = getenv('USERPROFILE'))) { $home = $userProfile; } if (!$home || !is_dir($home)) { throw new \RuntimeException('Could not determine home directory'); } return $home; }
Finds the user's home directory. @return string
protected function mkDir($dir) { if (!file_exists($dir)) { mkdir($dir, self::DIR_MODE, true); chmod($dir, self::DIR_MODE); } if (!is_dir($dir)) { throw new \Exception("Failed to create directory: $dir"); } }
Create a directory. @throws \Exception @param string $dir
public function getSubscriptionId() { if ($this->hasProperty('subscription_id', false)) { return $this->getProperty('subscription_id'); } if (isset($this->data['subscription']['license_uri'])) { return basename($this->data['subscription']['license_uri']); } throw new \RuntimeException('Subscription ID not found'); }
Get the subscription ID for the project. @todo when APIs are unified, this can be a property @return int
public function getGitUrl() { // The collection doesn't provide a Git URL, but it does provide the // right host, so the URL can be calculated. if (!$this->hasProperty('repository', false)) { $host = parse_url($this->getUri(), PHP_URL_HOST); return "{$this->id}@git.{$host}:{$this->id}.git"; } $repository = $this->getProperty('repository'); return $repository['url']; }
Get the Git URL for the project. @return string
public function addUser($user, $role, $byUuid = false) { $property = $byUuid ? 'user' : 'email'; $body = [$property => $user, 'role' => $role]; return ProjectAccess::create($body, $this->getLink('access'), $this->client); }
Add a new user to a project. @param string $user The user's UUID or email address (see $byUuid). @param string $role One of ProjectAccess::$roles. @param bool $byUuid Set true if $user is a UUID, or false (default) 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 getLink($rel, $absolute = true) { if ($this->hasLink($rel)) { return parent::getLink($rel, $absolute); } if ($rel === 'self') { return $this->getProperty('endpoint'); } if ($rel === '#ui') { return $this->getProperty('uri'); } if ($rel === '#manage-variables') { return $this->getUri() . '/variables'; } return $this->getUri() . '/' . ltrim($rel, '#'); }
@inheritdoc The accounts API does not (yet) return HAL links. This is a collection of workarounds for that issue.
public function addDomain($name, array $ssl = []) { $body = ['name' => $name]; if (!empty($ssl)) { $body['ssl'] = $ssl; } return Domain::create($body, $this->getLink('domains'), $this->client); }
Add a domain to the project. @param string $name @param array $ssl @return Result
public function addIntegration($type, array $data = []) { $body = ['type' => $type] + $data; return Integration::create($body, $this->getLink('integrations'), $this->client); }
Add an integration to the project. @param string $type @param array $data @return Result
public function getActivities($limit = 0, $type = null, $startsAt = null) { $options = []; if ($type !== null) { $options['query']['type'] = $type; } if ($startsAt !== null) { $options['query']['starts_at'] = Activity::formatStartsAt($startsAt); } $activities = Activity::getCollection($this->getUri() . '/activities', $limit, $options, $this->client); // Guarantee the type filter (works around a temporary bug). if ($type !== null) { $activities = array_filter($activities, function (Activity $activity) use ($type) { return $activity->type === $type; }); } return $activities; }
Get a list of project activities. @param int $limit Limit the number of activities to return. @param string $type Filter activities by type. @param int $startsAt A UNIX timestamp for the maximum created date of activities to return. @return Activity[]
public function setVariable( $name, $value, $json = false, $visibleBuild = true, $visibleRuntime = true, $sensitive = false ) { // If $value isn't a scalar, assume it's supposed to be JSON. if (!is_scalar($value)) { $value = json_encode($value); $json = true; } $values = [ 'value' => $value, 'is_json' => $json, 'visible_build' => $visibleBuild, 'visible_runtime' => $visibleRuntime]; if ($sensitive) { $values['is_sensitive'] = $sensitive; } $existing = $this->getVariable($name); if ($existing) { return $existing->update($values); } $values['name'] = $name; return ProjectLevelVariable::create($values, $this->getLink('#manage-variables'), $this->client); }
Set a variable. @param string $name The name of the variable to set. @param mixed $value The value of the variable to set. If non-scalar it will be JSON-encoded automatically. @param bool $json Whether this variable's value is JSON-encoded. @param bool $visibleBuild Whether this this variable should be exposed during the build phase. @param bool $visibleRuntime Whether this variable should be exposed during deploy and runtime. @param bool $sensitive Whether this variable's value should be readable via the API. @return Result
public function addCertificate($certificate, $key, array $chain = []) { $options = ['key' => $key, 'certificate' => $certificate, 'chain' => $chain]; return Certificate::create($options, $this->getUri() . '/certificates', $this->client); }
Add a certificate to the project. @param string $certificate @param string $key @param array $chain @return Result
public static function getProjectBaseFromUrl($url) { if (preg_match('#/api/projects/([^/]+)#', $url, $matches)) { return uri_for($url)->withPath('/api/projects/' . $matches[1])->__toString(); } throw new \RuntimeException('Failed to find project ID from URL: ' . $url); }
Find the project base URL from another project resource's URL. @param string $url @return string
public function render(Request $request, array $options = array()) { return $this->doRender( $options + array( 'app_id' => $this->appId, 'width' => $this->defaultWidth, 'num_posts' => $this->defaultNumPosts, 'color_scheme' => $this->defaultColorScheme, 'include_sdk' => $this->defaultIncludeSDK, 'url' => $request->getSchemeAndHttpHost() . $request->attributes->get('semanticPathinfo', $request->getPathInfo()), ) ); }
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()) { $foo = $this->locationService->loadLocation($contentInfo->mainLocationId); return $this->doRender( $options + array( 'app_id' => $this->appId, 'width' => $this->defaultWidth, 'num_posts' => $this->defaultNumPosts, 'color_scheme' => $this->defaultColorScheme, 'include_sdk' => $this->defaultIncludeSDK, 'url' => $this->router->generate($foo, array(), true), ) ); }
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 string
public function setPeriod(\DateTime $start = null, \DateTime $end = null) { $this->filters['start'] = $start !== null? $start->format('c') : null; $this->filters['end'] = $end !== null ? $end->format('c') : null; }
Restrict the query to a date/time period. @param \DateTime|null $start @param \DateTime|null $end
public function getParams() { $filters = array_filter($this->filters, function ($value) { return $value !== null; }); $filters = array_map(function ($value) { return is_array($value) ? ['value' => $value, 'operator' => 'IN'] : $value; }, $filters); return count($filters) ? ['filter' => $filters] : []; }
Get the URL query parameters. @return array
public function getDefaultProvider() { if (isset($this->defaultProvider)) { return $this->getProvider($this->defaultProvider); } $providerLabels = array_keys($this->providers); return $this->providers[$providerLabels[0]]; }
Returns the default provider. If no default provider is set, the first one will be returned. @return ProviderInterface
public function render(Request $request, array $options = array()) { $provider = isset($options['provider']) ? $this->getProvider($options['provider']) : $this->getDefaultProvider(); unset($options['provider']); return $provider->render($request, $options); }
Renders the comments list. Comment form might also be included. The default provider will be used unless one is specified in $options (with key 'provider') @param \Symfony\Component\HttpFoundation\Request $request @param array $options @return string
public function renderForContent(ContentInfo $contentInfo, Request $request, array $options = array()) { $commentsConfig = $this->getCommentsConfig($contentInfo); if (isset($commentsConfig['enabled']) && $commentsConfig['enabled'] === false) { if ($this->logger) { $this->logger->debug("Commenting is specifically disabled for content #$contentInfo->id"); } return; } /* * Order of precedence for provider is: * 1. $options['provider'] => specified directly. * 2. $commentConfig['provider'] => configured provider for given content. * 3. Defaut provider. */ $providerLabel = $this->defaultProvider; if (isset($options['provider'])) { $providerLabel = $options['provider']; } elseif (isset($commentsConfig['provider'])) { $providerLabel = $commentsConfig['provider']; } $provider = $this->getProvider($providerLabel); unset($options['provider']); // Merge configured options with explicitly passed options. // Explicit options always have precedence. $options = isset($commentsConfig['options']) ? $options + $commentsConfig['options'] : $options; return $provider->renderForContent($contentInfo, $request, $options); }
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
private function getCommentsConfig(ContentInfo $contentInfo) { $view = new ContentView(null, [], 'comments'); $view->setContent($this->contentService->loadContentByContentInfo($contentInfo)); return $this->matcherFactory->match($view); }
@param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo @note Matched config is cached in memory by underlying matcher factory. @return array|null
public function render(array $options = array(), $provider = null) { if (isset($provider)) { $options['provider'] = $provider; } $request = $this->getCurrentRequest(); if (!isset($request)) { throw new RuntimeException('Comments rendering needs the Request.'); } return $this->commentsRenderer->render($request, $options); }
Triggers comments rendering. @param array $options @param string|null $provider Label of the provider to use. If null, the default provider will be used. @throws \RuntimeException @return string
public function renderForContent(ContentInfo $contentInfo, array $options = array(), $provider = null) { if (isset($provider)) { $options['provider'] = $provider; } $request = $this->getCurrentRequest(); if (!isset($request)) { throw new RuntimeException('Comments rendering needs the Request.'); } return $this->commentsRenderer->renderForContent($contentInfo, $request, $options); }
Triggers comments rendering for a given ContentInfo object. @param ContentInfo $contentInfo @param array $options @param string|null $provider Label of the provider to use. If null, the default provider will be used. @return mixed @throws \RuntimeException
public function logOut() { try { $this->revokeTokens(); } catch (BadResponseException $e) { // Retry the request once. if ($e->getResponse() && $e->getResponse()->getStatusCode() < 500) { $this->revokeTokens(); } } finally { $this->session->clear(); $this->session->save(); } }
@inheritdoc @throws \GuzzleHttp\Exception\GuzzleException if tokens cannot be revoked.
private function revokeTokens() { $revocations = array_filter([ 'refresh_token' => $this->session->get('refreshToken'), 'access_token' => $this->session->get('accessToken'), ]); $url = uri_for($this->config['accounts']) ->withPath($this->config['revoke_url']) ->__toString(); foreach ($revocations as $type => $token) { $this->getClient()->request('post', $url, [ 'form_params' => [ 'token' => $token, 'token_type_hint' => $type, ], ]); } }
Revokes the access and refresh tokens saved in the session. @see Connector::logOut() @throws \GuzzleHttp\Exception\GuzzleException
public function logIn($username, $password, $force = false, $totp = null) { if (!$force && $this->isLoggedIn() && $this->session->get('username') === $username) { return; } if ($this->isLoggedIn()) { $this->logOut(); } $token = $this->getProvider()->getAccessToken(new Password(), [ 'username' => $username, 'password' => $password, 'totp' => $totp, ]); $this->session->set('username', $username); $this->saveToken($token); }
{@inheritdoc}
protected function saveToken(AccessToken $token) { if ($this->config['api_token'] && $this->config['api_token_type'] === 'access') { return; } foreach ($token->jsonSerialize() as $name => $value) { if (isset($this->storageKeys[$name])) { $this->session->set($this->storageKeys[$name], $value); } } $this->session->save(); }
Save an access token to the session. @param AccessToken $token
protected function loadToken() { if ($this->config['api_token'] && $this->config['api_token_type'] === 'access') { return new AccessToken([ 'access_token' => $this->config['api_token'], // Skip local expiry checking. 'expires' => 2147483647, ]); } if (!$this->session->get($this->storageKeys['access_token'])) { return null; } // These keys are used for saving in the session for backwards // compatibility with the commerceguys/guzzle-oauth2-plugin package. $values = []; foreach ($this->storageKeys as $tokenKey => $sessionKey) { $value = $this->session->get($sessionKey); if ($value !== null) { $values[$tokenKey] = $value; } } return new AccessToken($values); }
Load the current access token. @return AccessToken|null
protected function getOauthMiddleware() { if (!$this->oauthMiddleware) { if (!$this->isLoggedIn()) { throw new \RuntimeException('Not logged in'); } $grant = new ClientCredentials(); $grantOptions = []; // Set up the "exchange" (normal) API token type. if ($this->config['api_token'] && $this->config['api_token_type'] !== 'access') { $grant = new ApiToken(); $grantOptions['api_token'] = $this->config['api_token']; } $this->oauthMiddleware = new GuzzleMiddleware($this->getProvider(), $grant, $grantOptions); $this->oauthMiddleware->setTokenSaveCallback(function (AccessToken $token) { $this->saveToken($token); }); // If an access token is already available (via an API token or via // the session) then set it in the middleware in advance. if ($accessToken = $this->loadToken()) { $this->oauthMiddleware->setAccessToken($accessToken); } } return $this->oauthMiddleware; }
Get an OAuth2 middleware to add to Guzzle clients. @throws \RuntimeException @return GuzzleMiddleware
protected function doRender(array $options) { $template = isset($options['template']) ? $options['template'] : $this->getDefaultTemplate(); unset($options['template']); return $this->templateEngine->render($template, $options); }
Renders the template with provided options. "template" option allows to override the default template for rendering. @param array $options @return string
public static function fromData(array $data) { $policies = []; foreach (isset($data['schedule']) ? $data['schedule'] : [] as $policyData) { $policies[] = new Policy($policyData['interval'], $policyData['count']); } return new static($policies, isset($data['manual_count']) ? $data['manual_count'] : 1); }
Instantiates a backup configuration object from config data. @param array $data @return static
public static function array_flatten(array $array){ $index = 0; $count = count($array); while ($index < $count) { if (is_array($array[$index])) { array_splice($array, $index, 1, $array[$index]); } else { ++$index; } $count = count($array); } return $array; }
Make multidimensional array flat @param array $array @return array @author Koen Punt
public static function array_delete(array &$data, $key){ if(array_key_exists($key, $data)){ $value = $data[$key]; unset($data[$key]); return $value; } }
Deletes entry from array and return its value @param array $data @param string $key @return mixed @author Koen Punt
public function getCurrentDeployment() { $deployment = EnvironmentDeployment::get('current', $this->getUri() . '/deployments', $this->client); if (!$deployment) { throw new EnvironmentStateException('Current deployment not found', $this); } return $deployment; }
Get the current deployment of this environment. @throws \RuntimeException if no current deployment is found. @return EnvironmentDeployment
public function getHeadCommit() { $base = Project::getProjectBaseFromUrl($this->getUri()) . '/git/commits'; return Commit::get($this->head_commit, $base, $this->client); }
Get the Git commit for the HEAD of this environment. @return Commit|false
public function getSshUrl($app = '') { $urls = $this->getSshUrls(); if (isset($urls[$app])) { return $urls[$app]; } return $this->constructLegacySshUrl($app); }
Get the SSH URL for the environment. @param string $app An application name. @throws EnvironmentStateException @throws OperationUnavailableException @return string
private function constructLegacySshUrl() { if (!$this->hasLink('ssh')) { $id = $this->data['id']; if (!$this->isActive()) { throw new EnvironmentStateException("No SSH URL found for environment '$id'. It is not currently active.", $this); } throw new OperationUnavailableException("No SSH URL found for environment '$id'. You may not have permission to SSH."); } return $this->convertSshUrl($this->getLink('ssh')); }
Get the SSH URL via the legacy 'ssh' link. @return string
private function convertSshUrl($url, $username_suffix = '') { $parsed = parse_url($url); if (!$parsed) { throw new \InvalidArgumentException('Invalid URL: ' . $url); } return $parsed['user'] . $username_suffix . '@' . $parsed['host']; }
Convert a full SSH URL (with schema) into a normal SSH connection string. @param string $url The URL (starting with ssh://). @param string $username_suffix A suffix to append to the username. @return string
public function getSshUrls() { $prefix = 'pf:ssh:'; $prefixLength = strlen($prefix); $sshUrls = []; foreach ($this->data['_links'] as $rel => $link) { if (strpos($rel, $prefix) === 0 && isset($link['href'])) { $sshUrls[substr($rel, $prefixLength)] = $this->convertSshUrl($link['href']); } } if (empty($sshUrls) && $this->hasLink('ssh')) { $sshUrls[''] = $this->convertSshUrl($this->getLink('ssh')); } return $sshUrls; }
Returns a list of SSH URLs, keyed by app name. @return string[]
public function getPublicUrl() { if (!$this->hasLink('public-url')) { $id = $this->data['id']; if (!$this->isActive()) { throw new EnvironmentStateException("No public URL found for environment '$id'. It is not currently active.", $this); } throw new OperationUnavailableException("No public URL found for environment '$id'."); } return $this->getLink('public-url'); }
Get the public URL for the environment. @throws EnvironmentStateException @deprecated You should use routes to get the correct URL(s) @see self::getRouteUrls() @return string
public function branch($title, $id = null, $cloneParent = true) { $id = $id ?: $this->sanitizeId($title); $body = ['name' => $id, 'title' => $title]; if (!$cloneParent) { $body['clone_parent'] = false; } return $this->runLongOperation('branch', 'post', $body); }
Branch (create a new environment). @param string $title The title of the new environment. @param string $id The ID of the new environment. This will be the Git branch name. Leave blank to generate automatically from the title. @param bool $cloneParent Whether to clone data from the parent environment while branching. @return Activity