sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function create($path) { $call = 'fileops/create_folder'; $params = array('root' => $this->root, 'path' => $this->normalisePath($path)); $response = $this->fetch('POST', self::API_URL, $call, $params); return $response; }
Creates a folder @param string New folder to create relative to root @return object stdClass
entailment
public function move($from, $to) { $call = 'fileops/move'; $params = array( 'root' => $this->root, 'from_path' => $this->normalisePath($from), 'to_path' => $this->normalisePath($to), ); $response = $this->fetch('POST', self::API...
Moves a file or folder to a new location @param string $from File or folder to be moved, relative to root @param string $to Destination path, relative to root @return object stdClass
entailment
private function fetch($method, $url, $call, array $params = array()) { // Make the API call via the consumer $response = $this->OAuth->fetch($method, $url, $call, $params); // Format the response and return switch ($this->responseFormat) { case 'json': ...
Intermediate fetch function @param string $method The HTTP method @param string $url The API endpoint @param string $call The API method to call @param array $params Additional parameters @return mixed
entailment
public function setResponseFormat($format) { $format = strtolower($format); if (!in_array($format, array('php', 'json', 'jsonp'))) { throw new Exception("Expected a format of php, json or jsonp, got '$format'"); } else { $this->responseFormat = $format; ...
Set the API response format @param string $format One of php, json or jsonp @return void
entailment
public function setChunkSize($chunkSize = 4194304) { if (!is_int($chunkSize)) { throw new Exception('Expecting chunk size to be an integer, got ' . gettype($chunkSize)); } elseif ($chunkSize > 157286400) { throw new Exception('Chunk size must not exceed 157286400 bytes, ...
Set the chunk size for chunked uploads If $chunkSize is empty, set to 4194304 bytes (4 MB) @see \Dropbox\API\chunkedUpload()
entailment
private function getMimeType($data, $isFilename = false) { if (extension_loaded('fileinfo')) { $finfo = new \finfo(FILEINFO_MIME); if ($isFilename !== false) { return $finfo->file($data); } return $finfo->buffer($data); } ...
Get the mime type of downloaded file If the Fileinfo extension is not loaded, return false @param string $data File contents as a string or filename @param string $isFilename Is $data a filename? @return boolean|string Mime type and encoding of the file
entailment
private function encodePath($path) { $path = $this->normalisePath($path); $path = str_replace('%2F', '/', rawurlencode($path)); return $path; }
Encode the path, then replace encoded slashes with literal forward slash characters @param string $path The path to encode @return string
entailment
protected function authenticate() { if ((!$this->storage->get('access_token'))) { try { $this->getAccessToken(); } catch(\Dropbox\Exception $e) { $this->getRequestToken(); $this->authorise(); } } }
Authenticate using 3-legged OAuth flow, firstly checking we don't already have tokens to use @return void
entailment
public function getRequestToken() { // Nullify any request token we already have $this->storage->set(null, 'request_token'); $url = API::API_URL . self::REQUEST_TOKEN_METHOD; $response = $this->fetch('POST', $url, ''); $token = $this->parseTokenString($response['body']); ...
Acquire an unauthorised request token @link http://tools.ietf.org/html/rfc5849#section-2.1 @return void
entailment
public function getAuthoriseUrl() { // Get the request token $token = $this->getToken(); // Prepare request parameters $params = array( 'oauth_token' => $token->oauth_token, 'oauth_token_secret' => $token->oauth_token_secret, 'oauth_callback' ...
Build the user authorisation URL @return string
entailment
public function getAccessToken() { // Get the signed request URL $response = $this->fetch('POST', API::API_URL, self::ACCESS_TOKEN_METHOD); $token = $this->parseTokenString($response['body']); $this->storage->set($token, 'access_token'); }
Acquire an access token Tokens acquired at this point should be stored to prevent having to request new tokens for each API call @link http://tools.ietf.org/html/rfc5849#section-2.3
entailment
private function getToken() { if (!$token = $this->storage->get('access_token')) { if (!$token = $this->storage->get('request_token')) { $token = new \stdClass(); $token->oauth_token = null; $token->oauth_token_secret = null; } ...
Get the request/access token This will return the access/request token depending on which stage we are at in the OAuth flow, or a dummy object if we have not yet started the authentication process @return object stdClass
entailment
protected function getSignedRequest($method, $url, $call, array $additional = array()) { // Get the request/access token $token = $this->getToken(); // Generate a random string for the request $nonce = md5(microtime(true) . uniqid('', true)); // Prepare the ...
Generate signed request URL See inline comments for description @link http://tools.ietf.org/html/rfc5849#section-3.4 @param string $method HTTP request method @param string $url API endpoint to send the request to @param string $call API call to send @param array $additional Additional parameters as an associative arra...
entailment
private function getSignature($base, $key) { switch ($this->sigMethod) { case 'PLAINTEXT': $signature = $key; break; case 'HMAC-SHA1': $signature = base64_encode(hash_hmac('sha1', $base, $key, true)); break; } ...
Generate the oauth_signature for a request @param string $base Signature base string, used by HMAC-SHA1 @param string $key Concatenated consumer and token secrets
entailment
public function setSignatureMethod($method) { $method = strtoupper($method); switch ($method) { case 'PLAINTEXT': case 'HMAC-SHA1': $this->sigMethod = $method; break; default: throw new \Dropbox\Exception('U...
Set the OAuth signature method @param string $method Either PLAINTEXT or HMAC-SHA1 @return void
entailment
public function setOutFile($handle) { if (!is_resource($handle) || get_resource_type($handle) != 'stream') { throw new \Dropbox\Exception('Outfile must be a stream resource'); } $this->outFile = $handle; }
Set the output file @param resource Resource to stream response data to @return void
entailment
public function setInFile($handle) { if (!is_resource($handle) || get_resource_type($handle) != 'stream') { throw new \Dropbox\Exception('Infile must be a stream resource'); } fseek($handle, 0); $this->inFile = $handle; }
Set the input file @param resource Resource to read data from @return void
entailment
private function parseTokenString($response) { $parts = explode('&', $response); $token = new \stdClass(); foreach ($parts as $part) { list($k, $v) = explode('=', $part, 2); $k = strtolower($k); $token->$k = $v; } return $token; }
Parse response parameters for a token into an object Dropbox returns tokens in the response parameters, and not a JSON encoded object as per other API requests @link http://oauth.net/core/1.0/#response_parameters @param string $response @return object stdClass
entailment
public function setBreadcrumbs($breadcrumbs) { if (!is_array($breadcrumbs)) { throw new \InvalidArgumentException( 'Breadcrumbs::setBreadcrumbs() only accepts arrays, but ' . (is_object($breadcrumbs) ? get_class($breadcrumbs) : gettype($breadcrumbs)) ...
Sets all the breadcrumbs. Useful for quickly configuring the instance. @param array $breadcrumbs @return $this
entailment
public function addCrumb($name = '', $href = '', $hrefIsFullUrl = false) { if (mb_substr($href, 0, 1) === '/') { $length = mb_strlen($href); $href = mb_substr($href, 1, $length - 1); $this->addCrumb($name, $href, true); } elseif ((mb_substr($href, 0, 7) === 'http:...
Adds a crumb to the internal array. @param string $name The name of this breadcrumb, which will be seen by the users. @param string $href If this parameter begins with a forward slash, it will be treated as a full URL, and the `$hrefIsFullUrl` parameter will be forced to `true`, regardless of its v...
entailment
public function add($name = '', $href = '', $hrefIsFullUrl = false) { return $this->addCrumb($name, $href, $hrefIsFullUrl); }
Adds a crumb to the internal array. Alias for `Breadcrumbs::addCrumb` method. @param string $name The name of this breadcrumb, which will be seen by the users. @param string $href If this parameter begins with a forward slash, it will be treated as a full URL, and the `$hrefIsFullUrl` parameter wi...
entailment
public static function isValidCrumb($crumb) { if (!is_array($crumb)) { return false; } if (!isset($crumb['name'], $crumb['href'])) { return false; } if (!is_string($crumb['name']) || !is_string($crumb['href'])) { return false; } ...
Checks whether a crumb is valid, so that it can safely be added to the internal breadcrumbs array. @param array $crumb @return boolean
entailment
public function setCssClasses($cssClasses) { if (is_string($cssClasses)) { $cssClasses = explode(' ', $cssClasses); } if (!is_array($cssClasses)) { throw new \InvalidArgumentException( 'Breadcrumbs::setCssClasses() only accepts strings or arrays, but ...
Sets the CSS classes to be applied to the containing `<ul>` element. Can be passed a string or an array. If passed a string, separate CSS classes should be separated with spaces. @param string|array $cssClasses @return $this
entailment
public function setDivider($divider) { if (!is_string($divider) && !is_null($divider)) { throw new \InvalidArgumentException( 'Breadcrumbs::setDivider() only accepts strings or NULL, but ' . (is_object($divider) ? get_class($divider) : gettype($divider)) ...
Sets the divider which will be printed between the breadcrumbs. If set to `null`, the divider won't be printed at all. @param string $divider @return $this
entailment
public function setListElement($element) { if (!is_string($element)) { throw new \InvalidArgumentException( 'Breadcrumbs::setListElement() only accepts strings, but ' . (is_object($element) ? get_class($element) : gettype($element)) . ' given: ' . ...
Set the containing list DOM element @param string $element @return $this
entailment
public function setListItemCssClass($class) { if (!is_string($class)) { throw new \InvalidArgumentException( 'Breadcrumbs::setListItemCssClass() only accepts strings, but ' . (is_object($class) ? get_class($class) : gettype($class)) . ' given: ' . ...
Set the list item CSS class. This CSS class will be added to all list items. @param string $class @return $this
entailment
protected function renderCrumb($name, $href, $isLast = false, $position = null) { if ($this->divider) { $divider = " <span class=\"divider\">{$this->divider}</span>"; } else { $divider = ''; } if ($position != null) { $positionMeta = "<meta itempr...
Renders a single breadcrumb, Twitter Bootstrap-style. @param string $name @param string $href @param boolean $isLast @param number $position @return string
entailment
protected function renderCrumbs() { end($this->breadcrumbs); $lastKey = key($this->breadcrumbs); $output = ''; $hrefSegments = array(); $position = 1; foreach ($this->breadcrumbs as $key => $crumb) { $isLast = ($lastKey === $key); if ($cru...
Renders the crumbs one by one, and returns them concatenated. @return string
entailment
public function render() { if (empty($this->breadcrumbs)) { return ''; } $cssClasses = implode(' ', $this->breadcrumbsCssClasses); return '<'. $this->listElement . ' itemscope itemtype="http://schema.org/BreadcrumbList"' .' class="' . $cssClasses .'">' ...
Renders the complete breadcrumbs into Twitter Bootstrap-compatible HTML. @return string
entailment
protected function startListening() { foreach ($this->eventsToListenFor as $event) { if (is_callable([$this, $event])) { $this->connection->eventManager()->bind($event, [$this, $event]); } } return $this; }
Binds the requested events to the event manager. @return $this
entailment
public function requestCode($username, $type = 'sms', $debug = false) { // Create a instance of Registration class. $registration = new Registration($username, $debug); switch ($type) { case 'sms': $registration->codeRequest('sms'); break; case 'voice': $registration->codeRequest('vo...
When requesting the code, you can do it via SMS or voice call, in both cases you will receive a code like 123-456, that we will use for register the number. @param string $username Your phone number with country code, ie: 34123456789 @param string $type @param bool $debug Shows debug log, this is set to false if not s...
entailment
public function getProperties() { $properties = []; // URL must precede all other properties if ($this->url !== null) { $properties[] = new Property(Property::AUDIO_URL, $this->url); } if ($this->secureUrl !== null) { $properties[] = new Property(Pro...
Gets all properties set on this element. @return array|Property[]
entailment
public function authenticate(Request $request, Response $response) { if (!isset($this->_registry->Cookie) || !$this->_registry->Cookie instanceof CookieComponent) { throw new \RuntimeException('You need to load the CookieComponent.'); } $cookies = $this->_registry->Cookie->read(...
Authenticate a user based on the cookies information. @param \Cake\Network\Request $request The request instance. @param \Cake\Network\Response $response The response instance. @return mixed @throws \RuntimeException When the CookieComponent is not loaded.
entailment
public function getProperties() { $properties = []; // URL must precede all other properties if ($this->url !== null) { $properties[] = new Property(Property::IMAGE_URL, $this->url); } if ($this->height !== null) { $properties[] = new Property(Proper...
Gets all properties set on this element. @return array|Property[]
entailment
public function assignProperties(array $properties, $debug = false) { foreach ($properties as $property) { $name = $property->key; $value = $property->value; switch($name) { case Property::AUDIO: case Property::AUDIO_URL: ...
Assigns all properties given to the this Object instance. @param array|Property[] $properties Array of all properties to assign. @param bool $debug Throw exceptions when parsing or not. @throws \UnexpectedValueException
entailment
public function getProperties() { $properties = []; foreach ($this->audios as $audio) { $properties = array_merge($properties, $audio->getProperties()); } if ($this->title !== null) { $properties[] = new Property(Property::TITLE, $this->title); ...
Gets all properties set on this object. @return array|Property[]
entailment
public function getProperties() { $properties = []; // URL must precede all other properties if ($this->url !== null) { $properties[] = new Property(Property::VIDEO_URL, $this->url); } if ($this->height !== null) { $properties[] = new Property(Proper...
Gets all properties set on this element. @return array|Property[]
entailment
public function loadUrl($url) { // Fetch HTTP content using Guzzle $response = $this->client->get($url); return $this->loadHtml($response->getBody()->__toString(), $url); }
Fetches HTML content from the given URL and then crawls it for Open Graph data. @param string $url URL to be crawled. @return Website
entailment
public function loadHtml($html, $fallbackUrl = null) { // Extract all data that can be found $page = $this->extractOpenGraphData($html); // Use the user's URL as fallback if ($this->useFallbackMode && $page->url === null) { $page->url = $fallbackUrl; } /...
Crawls the given HTML string for OpenGraph data. @param string $html HTML string, usually whole content of crawled web resource. @param string $fallbackUrl URL to use when fallback mode is enabled. @return ObjectBase
entailment
protected function getBoundValue($name, $default) { $inputName = preg_split('/[\[\]]+/', $name, - 1, PREG_SPLIT_NO_EMPTY); if (count($inputName) == 2 && in_array($inputName[0], $this->locales)) { list($lang, $name) = $inputName; $value = isset($this->boundData->data()->transl...
Getting value from Model or ModelTranslation to populate form. Courtesy of TypiCMS/TranslatableBootForms (https://github.com/TypiCMS/TranslatableBootForms/blob/master/src/TranslatableFormBuilder.php) @param string $name key @return string value
entailment
public function format($response) { $response->getHeaders()->set('Content-Type', 'application/pdf'); $response->content = $this->formatPdf($response); }
Formats the specified response. @param Response $response the response to be formatted.
entailment
protected function formatPdf($response) { $mpdf = new \mPDF($this->mode, $this->format, $this->defaultFontSize, $this->defaultFont, $this->marginLeft, $this->marginRight, $this->marginTop, $this->marginBottom, $this->marginHeader, $this->marginFooter, $this->orientation ); foreach ...
Formats response HTML in PDF @param Response $response
entailment
public function render() { $this->applyElementBehavior(); $elements = []; if ($this->cloneElement()) { $originalArguments = $this->arguments(); $originalMethods = $this->methods(); $locales = $this->locales(); // Check if a custom locale set...
Renders the current translatable form element. @return string
entailment
protected function replacePlaceholdersRecursively($parameter, $currentLocale) { if (is_array($parameter)) { foreach ($parameter as $param) { $this->replacePlaceholdersRecursively($param, $currentLocale); } } $replacements = ['locale' => $curre...
Replaces %name recursively with the proper input name. @param mixed $parameter @param string $currentLocale @return mixed
entailment
public function register() { $this->mergeConfigFrom( __DIR__ . '/../config/config.php', 'translatable-bootforms' ); // Override BootForm's form builder in order to get model binding // between BootForm & TranslatableBootForm working. $this->app->singleton('adamwa...
Register the service provider. @return void
entailment
protected static function fixAuthHeader(\Symfony\Component\HttpFoundation\HeaderBag $headers) { if (!$headers->has('Authorization') && function_exists('apache_request_headers')) { $all = apache_request_headers(); if (isset($all['Authorization'])) { $headers->set('Auth...
PHP does not include HTTP_AUTHORIZATION in the $_SERVER array, so this header is missing. We retrieve it from apache_request_headers() @see https://github.com/symfony/symfony/issues/7170 @param HeaderBag $headers
entailment
public function register() { $this->app['jeremykenedy.slack'] = $this->app->share(function ($app) { $allow_markdown = $app['config']->get('slack::allow_markdown'); $markdown_in_attachments = $app['config']->get('slack::markdown_in_attachments'); $unfurl_media = $app['co...
Register the service provider. @return void
entailment
public function findUnitByStart(Token $token) { foreach ($this->collection as $unit) { if ($unit->start === $token) { return $unit; } } return null; }
Searches for blocks that start with a given token and returns it or null, if none is found @param Token $token @return Unit the found block or null
entailment
public function register() { $this->mergeConfigFrom(__DIR__.'/config/config.php', 'slack'); $this->app->singleton('jeremykenedy.slack', function ($app) { return new Client( $app['config']->get('slack.endpoint'), [ 'channel' ...
Register the service provider. @return void
entailment
public function setItem(ItemInterface $item) { $previousAttributes = []; $attributes = $this->getItemAttributes($item); $id = str_replace('.', '[.]', $item->getId()); $collectionName = $item->getCollection(); $itemPathName = sprintf('site.%s.%s', $collectionName, $id); ...
{@inheritdoc}
entailment
public function initialize(array $attributes = []) { $site = []; $site['spress'] = []; $site['site'] = $attributes; $site['site']['time'] = new \DateTime('now'); $site['site']['collections'] = []; $site['site']['categories'] = []; $site['site']['tags'] = []; ...
{@inheritdoc}
entailment
public function generate($path, $themeName, $force = false, array $options = []) { $options = $this->createOptionsResolver()->resolve($options); $this->checkThemeName($themeName); $this->processPath($path, $force); try { $this->createSite( $path, ...
Scaffold a new site. In case of exception, the new-site directory will be removed. @param string $path Destination path @param string $themeName Theme name. Pattern <theme_name>:<theme_version> can be used. "blank" is a special theme @param bool $force Force to clear destination if exists and it's not empty...
entailment
protected function createSite($path, $themeName, $preferLock, $preferSource, $noScripts) { $this->checkRequirements($themeName); $themePair = new PackageNameVersion($themeName); $this->createBlankSite($path, $themePair); if ($themeName === self::BLANK_THEME) { return; ...
Create a site. @param string $path Where the site will be located @param string $themeName The name of the theme the site based on @throws LogicException If the packageManager is null @throws RuntimeException If an error occurs while installing the theme @throws InvalidArgumentException If the ...
entailment
protected function updateDependencies($preferLock, $preferSource, $noScripts) { $pmOptions = [ 'prefer-source' => $preferSource, 'prefer-dist' => !$preferSource, 'no-scripts' => $noScripts, ]; if ($preferLock === true) { $this->packageManager-...
Updates the site dependencies. @param bool $preferLock @param bool $preferSource @param bool $noScripts
entailment
protected function processPath($path, $force) { $existsPath = $this->fs->exists($path); $isEmpty = $this->isEmptyDir($path); if ($existsPath === true && $force === false && $isEmpty === false) { throw new \RuntimeException(sprintf('Path "%s" exists and is not empty.', $path)); ...
Process the path of the future site. @param string $path @param bool $force @throws RuntimeException If the argument force is set to true and the path exists and is not empty
entailment
protected function createBlankSite($path, PackageNameVersion $themePair) { $themeName = ''; $packagePairs = $this->getInitialPackagePairs(); if ($themePair->getName() !== self::BLANK_THEME) { $themeName = $themePair->getName(); array_push($packagePairs, $themePair); ...
Creates a blank site. @param string $path Where the site will be located @param PackageNameVersion $themePair Theme pair
entailment
protected function copyContentFromThemeToSite($sitePath, $relativeThemePath) { if ($this->fs->exists($sitePath.'/'.$relativeThemePath) === false) { throw new \RuntimeException('The theme has not been installed correctly.'); } $finder = new Finder(); $finder->in($sitePath...
Copies content files from the theme to "src/content" folder. @param string $sitePath @param string $relativeThemePath
entailment
protected function setUpSiteConfigFile($sitePath, $relativeThemePath, $themeName) { $source = $sitePath.'/'.$relativeThemePath.'/config.yml'; $destination = $sitePath.'/config.yml'; $this->fs->copy($source, $destination, true); $configContent = file_get_contents($destination); ...
Sets up the configuration file. @param string $sitePath @param string $relativeThemePath @param string $themeName
entailment
protected function isEmptyDir($path) { if ($this->fs->exists($path) === true) { $finder = new Finder(); $finder->in($path); $iterator = $finder->getIterator(); $iterator->next(); return iterator_count($iterator) === 0; } return t...
Is the path empty? @param string $path @return bool
entailment
protected function clearDir($path) { $items = []; $finder = new Finder(); $finder->in($path) ->ignoreVCS(false) ->ignoreDotFiles(false); foreach ($finder as $item) { $items[] = $item->getRealpath(); } if (count($items) > 0) { ...
Clears the directory. @param string $path
entailment
protected function generateRequirePackages(array $packagePairs) { $requires = []; foreach ($packagePairs as $packagePair) { $requires[$packagePair->getName()] = $packagePair->getVersion(); } return $requires; }
Generates the list of required packages. @param PackageNameVersion[] $packagePairs @return array List of packages in which the key is the package's name and the value is the package's version
entailment
protected function createOptionsResolver() { $resolver = new AttributesResolver(); $resolver->setDefault('prefer-lock', false, 'bool') ->setDefault('prefer-source', false, 'bool') ->setDefault('no-scripts', false, 'bool'); return $resolver; }
Returns the resolver for generating options. @return AttributesResolver
entailment
public function add(ItemInterface $item) { if ($this->has($item->getId()) === true) { throw new \RuntimeException(sprintf('A previous item exists with the same id: "%s".', $item->getId())); } $this->set($item); }
Adds an new item. @param Yosymfony\Spress\Core\DataSource\ItemInterface $item @throws \RuntimeException If the item has been registered previously with the same id
entailment
public function set(ItemInterface $item) { $id = $item->getId(); $collectionName = $item->getCollection(); $this->items[$id] = $item; if (isset($this->idCollections[$id]) && $this->idCollections[$id] !== $collectionName) { throw new \RuntimeException(sprintf('The item w...
Sets an item. @param Yosymfony\Spress\Core\DataSource\ItemInterface @throws \RuntimeException If the item has been registered previously in another collection
entailment
public function get($id) { if (false === $this->has($id)) { throw new \RuntimeException(sprintf('Item with id: "%s" not found.', $id)); } return $this->items[$id]; }
Gets an item. @param string $id The identifier of the item @return Yosymfony\Spress\Core\DataSource\ItemInterface @throws \RuntimeException If the item was not found
entailment
public function all(array $collections = [], $groupByCollection = false) { if (count($collections) === 0) { if ($groupByCollection === false) { return $this->items; } return $this->itemCollections; } $result = []; foreach ($colle...
Returns all items in this collection. @param string[] $collections The name of the item collections affected. Array empty means all @param bool $groupByCollection First level of array is the collection name @return array
entailment
public function sortItems($attribute, $descending = true, array $collections = []) { $itemCollections = $this->all($collections, true); $callback = function ($key, ItemInterface $item) use ($attribute) { $attributes = $item->getAttributes(); return isset($attributes[$attrib...
Sorts items in this collection. e.g:. ``` $itemCollection = new ItemCollection(); // warm-up... $items = $itemCollection->sortItems('date', true)->all(); ``` @param string $attribute The name of the attribute used to sort @param bool $descending Is descending sort? @param string[] $collections Only the items...
entailment
public function remove($id) { if ($this->has($id) === false) { return; } $collection = $this->idCollections[$id]; unset($this->idCollections[$id]); unset($this->itemCollections[$collection]); unset($this->items[$id]); }
Removes an item. @param string $id The identifier of the item
entailment
public function generate($path, $themeName, $force = false, array $options = []) { if ($themeName === self::BLANK_THEME) { parent::generate($path, $themeName, $force, $options); return; } $options = $this->getGenerateOptionsResolver()->resolve($options); $t...
Scaffolds a new theme. In case of exception, the new-site directory will be removed. @param string $path Destination path @param string $themeName Theme name. Pattern <theme_name>:<theme_version> can be used. "blank" is a special theme @param string $repository Provide a custom repository to search for the pack...
entailment
protected function getGenerateOptionsResolver() { $resolver = parent::createOptionsResolver(); $resolver->setDefault('repository', null, 'string', false, true); return $resolver; }
{@inheritdoc}
entailment
public function install(array $options = [], array $packageNames = []) { $options = $this->getInstallResolver()->resolve($options); $installer = $this->buildInstaller($options); $installer->setUpdateWhitelist($packageNames); $status = $installer->run(); if ($status !== 0) { ...
Installs plugins and themes. @param array $options Options for installing packages @param string[] $packageNames List of packages @throws RuntimeException If any problem occurs while resolving dependencies
entailment
public function update(array $options = [], array $packageNames = []) { $options = $this->getInstallResolver()->resolve($options); $installer = $this->buildInstaller($options); $installer->setUpdate(true); $installer->setUpdateWhitelist($packageNames); $status = $installer->r...
Update plugins and themes installed previously. @param array $options Options for updating packages @param string[] $packageNames List of packages @throws RuntimeException If any problem occurs while resolving dependencies
entailment
public function addPackage(array $packageNames, $areDevPackages = false) { $fs = new Filesystem(); $file = $this->embeddedComposer->getExternalComposerFilename(); if ($fs->exists($file) === false) { $fs->dumpFile($file, "{\n}\n"); } if (filesize($file) === 0) { ...
Adds a new set of packages to the current Composer file. @param array $packageNames @param bool $areDevPackages @return array List of package's name as a key and the package's version as value
entailment
public function removePackage(array $packageNames, $areDevPackages = false) { $packages = $this->formatPackageNames($packageNames); $file = $this->embeddedComposer->getExternalComposerFilename(); $jsonFile = new JsonFile($file); $json = new JsonConfigSource($jsonFile); $compo...
Remove a set of packages of the current Composer file. @param array $packageNames @param bool $areDevPackages @return array List of package's name as a key and the package's version as value
entailment
public function createThemeProject($siteDir, $packageName, $repository = null, $preferSource = false) { $packagePair = new PackageNameVersion($packageName); $config = Factory::createConfig(); if (is_null($repository) === true) { $sourceRepo = new CompositeRepository(RepositoryFa...
Create a new theme project. This is equivalent to perform a "git clone". @param string $siteDir Site directory @param string $packageName Package's name. e.g: "vendory/foo 2.0.0" @param string $repository Provide a custom repository to search for the package @param bool $preferSource Install packages from so...
entailment
public function rewritingSelfVersionDependencies() { $composer = $this->embeddedComposer->createComposer($this->io); $package = $composer->getPackage(); $configSource = new JsonConfigSource(new JsonFile('composer.json')); foreach (BasePackage::$supportedLinkTypes as $type => $meta) ...
Rewriting "self.version" dependencies with explicit version numbers of the current composer.json file. Useful if the package's vcs metadata is gone.
entailment
public function isThemePackage($packageName) { $composerPackage = $this->findPackageGlobal($packageName); if (is_null($composerPackage) === true) { throw new \RuntimeException(sprintf('The theme: "%s" does not exist.', $packageName)); } return $composerPackage->getType(...
Determines if package is a Spress theme. @return bool @throws RuntimeException If the package doesn't exist
entailment
public function isPackageDependOn($packageNameA, $packageNameB) { $composerPackageA = $this->findPackageGlobal($packageNameA); if (is_null($composerPackageA) === true) { throw new \RuntimeException(sprintf('The package: "%s" does not exist.', $packageNameA)); } $require...
Determines if a package A depends on package B. Only scan with first deep level. @param string $packageNameA Packagae A. e.g: "vendor/foo *" @param string $packageNameB Package B. e.g: "vendor/foo-b" or "vendor/foo-b >=2.0" @return bool @throws RuntimeException If the package doesn't exist
entailment
protected function findPackageGlobal($packageName) { $packagePair = new PackageNameVersion($packageName); if (isset($this->packageCache[$packagePair->getNormalizedNameVersion()])) { return $this->packageCache[$packagePair->getNormalizedNameVersion()]; } $composer = $thi...
Recovers the data of a package registered in repositories such as packagist.org. @param string $packageName Package's name @return Composer\Package\PackageInterface|null Null if the package not found
entailment
protected function formatPackageNames(array $packageNames) { $requires = []; foreach ($packageNames as $packageName) { $packagePair = new PackageNameVersion($packageName); $requires[$packagePair->getName()] = $packagePair->getVersion(); } return $requires; ...
Formats the packages names. @return array List in which the key is the name and the value is the version
entailment
protected function removeVcsMetadata($directory) { $fs = new Filesystem(); $finder = new Finder(); $finder ->in($directory) ->depth(0) ->directories() ->ignoreVCS(false) ->ignoreDotFiles(false); foreach ($this->vcsNames as ...
Clear the VCS metadata. e.g: .git folder. If an error occurred while removing VCS metadata, then its details will be dump using IO. @param string $directory Directory in which find VCS metadata
entailment
public function convert($input) { if (is_string($input) === false) { throw new \InvalidArgumentException('Expected a string value at Parsedown converter.'); } $converter = new \ParsedownExtra(); return $converter->text($input); }
Convert the input data. @param string $input The raw content without Front-matter @return string
entailment
public function getFilename() { if (is_null($this->filename) === true) { $str = new StringWrapper(parent::getFilename()); $this->filename = $str->deleteSufix('.'.$this->getExtension()); } return $this->filename; }
Gets the filename without extension. @return string
entailment
public function getExtension() { if (is_null($this->extension) === true) { $filename = parent::getFilename(); $str = new StringWrapper($filename); $this->extension = $str->getFirstEndMatch($this->predefinedExtensions); $this->hasPredefinedExt = true; ...
Gets the extension of the file. @return string
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $server = $input->getOption('server'); $watch = $input->getOption('watch'); $io = new ConsoleIO($input, $output); $spress = $this->buildSpress($io, $input); $env = $spress['spress.config.values'][...
{@inheritdoc}
entailment
protected function buildSpress(IOInterface $io, InputInterface $input) { $timezone = $input->getOption('timezone'); $drafts = $input->getOption('drafts'); $safe = $input->getOption('safe'); $env = $input->getOption('env'); $sourceDir = $input->getOption('source'); if...
Builds a Spress instance. @param IOInterface $io The Spress IO @param InputInterface $input The Symfony Console input @return Spress The Spress instance
entailment
protected function reParse(IOInterface $io, InputInterface $input, ResourceWatcher $rw) { $rw->findChanges(); if ($rw->hasChanges() === false) { return; } $this->rebuildingSiteMessage($io, $rw->getNewResources(), $rw->getUpdatedResources(), $rw->getDeletedResources()); ...
Reparses a site. @param IOInterface $io The Spress IO @param InputInterface $input The Symfony Console input @param ResourceWatcher $rw The ResourceWatcher
entailment
protected function buildResourceWatcher($sourceDir, $destinationDir) { $fs = new Filesystem(); $relativeDestination = rtrim($fs->makePathRelative($destinationDir, $sourceDir), '/'); $finder = new Finder(); $finder->files() ->name('*.*') ->in($sourceDir); ...
Builds a ResourceWatcher instance. @param string $sourceDir Source path @param string $destinationDir Destination path @return ResourceWatcher The ResourceWatcher instance
entailment
protected function getConfigResolver() { if (is_null($this->configResolver) === false) { return $this->configResolver; } $resolver = new AttributesResolver(); $resolver->setDefault('host', '0.0.0.0', 'string', true) ->setDefault('port', 4000, 'integer', true)...
Returns the attributes or options resolver for configuration values. @return AttributesResolver
entailment
protected function enableParsedown(Spress $spress) { $spress->extend('spress.cms.converterManager.converters', function ($predefinedConverters, $c) { unset($predefinedConverters['MichelfMarkdownConverter']); $markdownExts = $c['spress.config.values']['markdown_ext']; $pr...
Enables Parsedown converter. @param Spress $spress The Spress instance
entailment
protected function startingMessage(ConsoleIO $io, $env, $draft, $safe) { $io->newLine(); $io->write('<comment>Starting...</comment>'); $io->labelValue('Environment', $env); if ($io->isDebug() === true) { $io->labelValue('Debug mode', 'enabled'); } if ($d...
Writes the staring messages. @param ConsoleIO $io Spress IO @param string $env The enviroment name @param bool $draft Is draft mode enabled? @param bool $safe Is safe mode enabled?
entailment
protected function resultMessage(ConsoleIO $io, array $items) { $io->newLine(); $io->labelValue('Total items', count($items)); $io->newLine(); $io->success('Success!'); }
Writes the result of a parsing a site. @param ConsoleIO $io The Spress IO @param ItemInterface[] $items Item affected
entailment
protected function rebuildingSiteMessage(ConsoleIO $io, array $newResources, array $updatedResources, array $deletedResources) { $io->write(sprintf( '<comment>Rebuilding site... (%s new, %s updated and %s deleted resources)</comment>', count($newResources), count($updated...
Write the result of rebuilding a site. @param ConsoleIO $io The Spress IO @param array $newResources @param array $updatedResources @param array $deletedResources
entailment
public function runCommand($commandName, array $arguments) { if ($this->hasCommand($commandName) === false) { throw new CommandNotFoundException(sprintf('Command "%s" not found.', $commandName)); } $symfonyConsoleApp = $this->getSymfonyConsoleApplication(); $commandToRun...
{@inheritdoc}
entailment
public function getSpress($siteDir = null) { $symfonyConsoleApp = $this->getSymfonyConsoleApplication(); if ($symfonyConsoleApp instanceof Application) { return $symfonyConsoleApp->getSpress($siteDir); } throw new \RuntimeException('This implementation of the Symfony Co...
{@inheritdoc}
entailment
public function buildCommands() { $result = []; $pluginsCollection = $this->pluginManager->getPluginCollection(); foreach ($pluginsCollection as $plugin) { if ($this->isValidCommandPlugin($plugin) === true) { $result[] = $this->buildCommand($plugin); ...
Gets a list of Symfony Console command. @return Symfony\Component\Console\Command\Command[] Symfony Console commands
entailment
protected function buildCommand(CommandPluginInterface $commandPlugin) { $definition = $commandPlugin->getCommandDefinition(); $argumentsAndOptions = []; $consoleComand = new Command($definition->getName()); $consoleComand->setDescription($definition->getDescription()); $con...
Build a Symfony Console commands. @param \Yosymfony\Spress\Plugin\CommandPluginInterface $commandPlugin @return \Symfony\Component\Console\Command\Command Symfony Console command
entailment
public function render() { $str = ''; $day = 1; $today = 0; if (empty($this->_View->viewVars['_calendar'])) { throw new RuntimeException('You need to load Calendar.Calendar component for this helper to work.'); } $year = $this->_View->viewVars['_calendar']['year']; $month = $this->_View->viewVars['_...
Generates a calendar for the specified by the month and year params and populates it with the content of the data container array @return string HTML code to display calendar in view
entailment
public function calendarUrlArray(array $url, ChronosInterface $dateTime) { $year = $this->retrieveYearFromDate($dateTime); $month = $this->retrieveMonthFromDate($dateTime); $currentYear = (int)date('Y'); $currentMonth = (int)date('n'); if ($year === (int)$currentYear && $month === (int)$currentMonth) { r...
Generates a link back to the calendar from any view page. Specify action and if necessary controller, plugin, and prefix. @param array $url @param \Cake\Chronos\ChronosInterface $dateTime @return array
entailment
public function readFile($filename) { if (is_file($filename) === false) { throw new FileNotFoundException(sprintf('File "%s" does not exist.', $filename)); } if (is_readable($filename) === false) { throw new IOException(sprintf('File "%s" cannot be read.', $filename))...
Reads the content of a filename. @param string The file to which to read the content. @return string The content of the filename. @throws FileNotFoundException When the filename does not exist. @throws IOException When the filename cannot be read or there is another problem.
entailment