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_URL, $call, $params); return $response; }
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': return json_encode($response); case 'jsonp': $response = json_encode($response); return $this->callback . '(' . $response . ')'; default: return $response; } }
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, got ' . $chunkSize); } else { $this->chunkSize = $chunkSize; } }
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); } return false; }
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']); $this->storage->set($token, 'request_token'); }
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' => $this->callback, ); // Build the URL and redirect the user $query = '?' . http_build_query($params, '', '&'); $url = self::WEB_URL . self::AUTHORISE_METHOD . $query; return $url; }
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; } } return $token; }
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 standard request parameters $params = array( 'oauth_consumer_key' => $this->consumerKey, 'oauth_token' => $token->oauth_token, 'oauth_signature_method' => $this->sigMethod, 'oauth_version' => '1.0', // Generate nonce and timestamp if signature method is HMAC-SHA1 'oauth_timestamp' => ($this->sigMethod == 'HMAC-SHA1') ? time() : null, 'oauth_nonce' => ($this->sigMethod == 'HMAC-SHA1') ? $nonce : null, ); // Merge with the additional request parameters $params = array_merge($params, $additional); ksort($params); // URL encode each parameter to RFC3986 for use in the base string $encoded = array(); foreach($params as $param => $value) { if ($value !== null) { // If the value is a file upload (prefixed with @), replace it with // the destination filename, the file path will be sent in POSTFIELDS if (isset($value[0]) && $value[0] === '@') $value = $params['filename']; $encoded[] = $this->encode($param) . '=' . $this->encode($value); } else { unset($params[$param]); } } // Build the first part of the string $base = $method . '&' . $this->encode($url . $call) . '&'; // Re-encode the encoded parameter string and append to $base $base .= $this->encode(implode('&', $encoded)); // Concatenate the secrets with an ampersand $key = $this->consumerSecret . '&' . $token->oauth_token_secret; // Get the signature string based on signature method $signature = $this->getSignature($base, $key); $params['oauth_signature'] = $signature; // Build the signed request URL $query = '?' . http_build_query($params, '', '&'); return array( 'url' => $url . $call . $query, 'postfields' => $params, ); }
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 array @return array
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; } return $signature; }
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('Unsupported signature method ' . $method); } }
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)) . ' given: ' . print_r($breadcrumbs, true) ); } foreach ($breadcrumbs as $key => $breadcrumb) { if (!static::isValidCrumb($breadcrumb)) { throw new \InvalidArgumentException( 'Breadcrumbs::setBreadcrumbs() only accepts correctly formatted arrays, but at least one of the ' . 'values was misformed: $breadcrumbs[' . $key . '] = ' . print_r($breadcrumb, true) ); } else { $this->addCrumb( $breadcrumb['name'] ?: '', $breadcrumb['href'] ?: '', isset($breadcrumb['hrefIsFullUrl']) ? (bool) $breadcrumb['hrefIsFullUrl'] : false ); } } return $this; }
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://') && !$hrefIsFullUrl) { $this->addCrumb($name, $href, true); } elseif ((mb_substr($href, 0, 8) === 'https://') && !$hrefIsFullUrl) { $this->addCrumb($name, $href, true); } else { $crumb = array( 'name' => $name, 'href' => $href, 'hrefIsFullUrl' => $hrefIsFullUrl, ); $this->breadcrumbs[] = $crumb; } return $this; }
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 value. @param boolean $hrefIsFullUrl Whether the `$href` argument is a full URL or just a segment. The difference is that segments will be built upon previous breadcrumbs, while full URLs will be returned as they are inputted. This can be automatically forced to `true`, depending on the `$href` argument - read its description for details. @return $this
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 will be forced to `true`, regardless of its value. @param boolean $hrefIsFullUrl Whether the `$href` argument is a full URL or just a segment. The difference is that segments will be built upon previous breadcrumbs, while full URLs will be returned as they are inputted. This can be automatically forced to `true`, depending on the `$href` argument - read its description for details. @return $this
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; } if (empty($crumb['name']) || empty($crumb['href'])) { return false; } return true; }
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 ' . (is_object($cssClasses) ? get_class($cssClasses) : gettype($cssClasses)) . ' given: ' . print_r($cssClasses, true) ); } foreach ($cssClasses as $key => $cssClass) { if (!is_string($cssClass)) { throw new \InvalidArgumentException( 'Breadcrumbs::setCssClasses() was passed an array, but at least one of the values was not a ' . 'string: $cssClasses[' . $key . '] = ' . print_r($cssClass, true) ); } } $this->breadcrumbsCssClasses = array_unique($cssClasses); return $this; }
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)) . ' given: ' . print_r($divider, true) ); } $this->divider = $divider; return $this; }
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: ' . print_r($element, true) ); } $this->listElement = $element; return $this; }
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: ' . print_r($class, true) ); } $this->listItemCssClass = $class; return $this; }
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 itemprop=\"position\" content=\"{$position}\" />"; } else { $positionMeta = ""; } if (!$isLast) { return '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" ' . "class=\"{$this->listItemCssClass}\" >" . "<a itemprop=\"item\" href=\"{$href}\"><span itemprop=\"name\">{$name}</span></a>" . "{$positionMeta}{$divider}</li>"; } else { return '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" ' . "class=\"{$this->listItemCssClass} active\"><span itemprop=\"name\">{$name}</span>" . "{$positionMeta}</li>"; } }
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 ($crumb['hrefIsFullUrl']) { $hrefSegments = array(); } if ($crumb['href']) { $hrefSegments[] = $crumb['href']; } $href = implode('/', $hrefSegments); if (!preg_match('#^https?://.*#', $href)) { $href = "/{$href}"; } $output .= $this->renderCrumb($crumb['name'], $href, $isLast, $position); $position++; } return $output; }
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 .'">' . $this->renderCrumbs() . '</'. $this->listElement .'>'; }
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('voice'); break; default: throw new Exception('Invalid registration type'); } return $registration; }
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 specified @return Registration @throws Exception @internal param string $nickname Your nickname, it will appear in push notifications @internal param bool $log Enables log file, this is set to false if not specified
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(Property::AUDIO_SECURE_URL, $this->secureUrl); } if ($this->type !== null) { $properties[] = new Property(Property::AUDIO_TYPE, $this->type); } return $properties; }
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($this->_config['cookie']['name']); if (empty($cookies)) { return false; } extract($this->_config['fields']); if (empty($cookies[$username]) || empty($cookies[$password])) { return false; } $user = $this->_findUser($cookies[$username], $cookies[$password]); if ($user) { return $user; } return false; }
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(Property::IMAGE_HEIGHT, $this->height); } if ($this->secureUrl !== null) { $properties[] = new Property(Property::IMAGE_SECURE_URL, $this->secureUrl); } if ($this->type !== null) { $properties[] = new Property(Property::IMAGE_TYPE, $this->type); } if ($this->width !== null) { $properties[] = new Property(Property::IMAGE_WIDTH, $this->width); } if ($this->userGenerated !== null) { $properties[] = new Property(Property::IMAGE_USER_GENERATED, $this->userGenerated); } return $properties; }
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: $this->audios[] = new Audio($value); break; case Property::AUDIO_SECURE_URL: case Property::AUDIO_TYPE: if (count($this->audios) > 0) { $this->handleAudioAttribute($this->audios[count($this->audios) - 1], $name, $value); } elseif ($debug) { throw new \UnexpectedValueException( sprintf( "Found '%s' property but no audio was found before.", $name ) ); } break; case Property::DESCRIPTION: if ($this->description === null) { $this->description = $value; } break; case Property::DETERMINER: if ($this->determiner === null) { $this->determiner = $value; } break; case Property::IMAGE: case Property::IMAGE_URL: $this->images[] = new Image($value); break; case Property::IMAGE_HEIGHT: case Property::IMAGE_SECURE_URL: case Property::IMAGE_TYPE: case Property::IMAGE_WIDTH: case Property::IMAGE_USER_GENERATED: if (count($this->images) > 0) { $this->handleImageAttribute($this->images[count($this->images) - 1], $name, $value); } elseif ($debug) { throw new \UnexpectedValueException( sprintf( "Found '%s' property but no image was found before.", $name ) ); } break; case Property::LOCALE: if ($this->locale === null) { $this->locale = $value; } break; case Property::LOCALE_ALTERNATE: $this->localeAlternate[] = $value; break; case Property::RICH_ATTACHMENT: $this->richAttachment = $this->convertToBoolean($value); break; case Property::SEE_ALSO: $this->seeAlso[] = $value; break; case Property::SITE_NAME: if ($this->siteName === null) { $this->siteName = $value; } break; case Property::TITLE: if ($this->title === null) { $this->title = $value; } break; case Property::UPDATED_TIME: if ($this->updatedTime === null && strtotime($value) !== false) { $this->updatedTime = $this->convertToDateTime($value); } break; case Property::URL: if ($this->url === null) { $this->url = $value; } break; case Property::VIDEO: case Property::VIDEO_URL: $this->videos[] = new Video($value); break; case Property::VIDEO_HEIGHT: case Property::VIDEO_SECURE_URL: case Property::VIDEO_TYPE: case Property::VIDEO_WIDTH: if (count($this->videos) > 0) { $this->handleVideoAttribute($this->videos[count($this->videos) - 1], $name, $value); } elseif ($debug) { throw new \UnexpectedValueException( sprintf( "Found '%s' property but no video was found before.", $name ) ); } } } }
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); } if ($this->description !== null) { $properties[] = new Property(Property::DESCRIPTION, $this->description); } if ($this->determiner !== null) { $properties[] = new Property(Property::DETERMINER, $this->determiner); } foreach ($this->images as $image) { $properties = array_merge($properties, $image->getProperties()); } if ($this->locale !== null) { $properties[] = new Property(Property::LOCALE, $this->locale); } foreach ($this->localeAlternate as $locale) { $properties[] = new Property(Property::LOCALE_ALTERNATE, $locale); } if ($this->richAttachment !== null) { $properties[] = new Property(Property::RICH_ATTACHMENT, (int)$this->richAttachment); } foreach ($this->seeAlso as $seeAlso) { $properties[] = new Property(Property::SEE_ALSO, $seeAlso); } if ($this->siteName !== null) { $properties[] = new Property(Property::SITE_NAME, $this->siteName); } if ($this->type !== null) { $properties[] = new Property(Property::TYPE, $this->type); } if ($this->updatedTime !== null) { $properties[] = new Property(Property::UPDATED_TIME, $this->updatedTime->format("c")); } if ($this->url !== null) { $properties[] = new Property(Property::URL, $this->url); } foreach ($this->videos as $video) { $properties = array_merge($properties, $video->getProperties()); } return $properties; }
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(Property::VIDEO_HEIGHT, $this->height); } if ($this->secureUrl !== null) { $properties[] = new Property(Property::VIDEO_SECURE_URL, $this->secureUrl); } if ($this->type !== null) { $properties[] = new Property(Property::VIDEO_TYPE, $this->type); } if ($this->width !== null) { $properties[] = new Property(Property::VIDEO_WIDTH, $this->width); } return $properties; }
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; } // Return result return $page; }
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()->translate($lang)->{$name}) ? $this->boundData->data()->translate($lang)->{$name} : ''; return $value; } return $this->boundData->get($name, $default); }
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 ($this->options as $key => $option) { $mpdf->$key = $option; } if ($this->beforeRender instanceof \Closure) { call_user_func($this->beforeRender, $mpdf, $response->data); } $mpdf->WriteHTML($response->data); return $mpdf->Output('', 'S'); }
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 is requested. if ($count = func_num_args()) { $args = ($count == 1 ? head(func_get_args()) : func_get_args()); $locales = array_intersect($locales, (array) $args); } foreach ($locales as $locale) { $this->arguments($originalArguments); $this->methods($originalMethods); $name = str_contains($originalArguments['name'], '%locale') ? $originalArguments['name'] : '%locale[' . $originalArguments['name'] . ']'; $this->overwriteArgument('name', str_replace('%locale', $locale, $name)); if ($this->translatableIndicator()) { $this->setTranslatableLabelIndicator($locale); } if (!empty($this->config['form-group-class'])) { $this->addMethod('addGroupClass', str_replace('%locale', $locale, $this->config['form-group-class'])); } if (!empty($this->config['input-locale-attribute'])) { $this->addMethod('attribute', [$this->config['input-locale-attribute'], $locale]); } $elements[] = $this->createInput($locale); } } else { $elements[] = $this->createInput(); } $this->reset(); return implode('', $elements); }
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' => $currentLocale]; if ($name = array_get($this->arguments(), 'name')) { array_set($replacements, 'name', $name); } return str_replace(array_keys($replacements), array_values($replacements), $parameter); }
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('adamwathan.form', function ($app) { $formBuilder = new Form\FormBuilder(); $formBuilder->setLocales($this->getLocales()); $formBuilder->setErrorStore($app['adamwathan.form.errorstore']); $formBuilder->setOldInputProvider($app['adamwathan.form.oldinput']); $token = version_compare(Application::VERSION, '5.4', '<') ? $app['session.store']->getToken() : $app['session.store']->token(); $formBuilder->setToken($token); return $formBuilder; }); // Define TranslatableBootForm. $this->app->singleton('translatable-bootform', function ($app) { $form = new TranslatableBootForm($app['bootform']); $form->locales($this->getLocales()); return $form; }); }
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('Authorization', $all['Authorization']); } } }
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['config']->get('slack::unfurl_media'); return new Client( $app['config']->get('slack::endpoint'), [ 'channel' => $app['config']->get('slack::channel'), 'username' => $app['config']->get('slack::username'), 'icon' => $app['config']->get('slack::icon'), 'link_names' => $app['config']->get('slack::link_names'), 'unfurl_links' => $app['config']->get('slack::unfurl_links'), 'unfurl_media' => is_bool($unfurl_media) ? $unfurl_media : true, 'allow_markdown' => is_bool($allow_markdown) ? $allow_markdown : true, 'markdown_in_attachments' => is_array($markdown_in_attachments) ? $markdown_in_attachments : [], ], new Guzzle() ); }); $this->app->bind('jeremykenedy\Slack\Client', 'jeremykenedy.slack'); }
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' => $app['config']->get('slack.channel'), 'username' => $app['config']->get('slack.username'), 'icon' => $app['config']->get('slack.icon'), 'link_names' => $app['config']->get('slack.link_names'), 'unfurl_links' => $app['config']->get('slack.unfurl_links'), 'unfurl_media' => $app['config']->get('slack.unfurl_media'), 'allow_markdown' => $app['config']->get('slack.allow_markdown'), 'markdown_in_attachments' => $app['config']->get('slack.markdown_in_attachments'), ], new Guzzle() ); }); $this->app->bind('jeremykenedy\Slack\Client', 'jeremykenedy.slack'); }
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); if ($this->hasAttribute($itemPathName)) { $previousAttributes = $this->getAttribute($itemPathName); } $newAttributes = array_merge($previousAttributes, $attributes); $this->setAttribute($itemPathName, $newAttributes); $this->setAttribute('page', $newAttributes); if ($collectionName === 'posts') { $postAttributes = $this->postAttributesResolver->resolve($attributes); foreach ($postAttributes['categories'] as $category) { $this->setAttribute(sprintf('site.categories.%s.%s', $category, $id), $newAttributes); } foreach ($postAttributes['tags'] as $tag) { $this->setAttribute(sprintf('site.tags.%s.%s', $tag, $id), $newAttributes); } } }
{@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'] = []; $site['page'] = []; $this->arrayWrapper->setArray($site); }
{@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, $themeName, $options['prefer-lock'], $options['prefer-source'], $options['no-scripts'] ); } catch (\Exception $e) { $this->fs->remove($path); throw $e; } }
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' @param array $options @throws LogicException If there is an attemp of create a non-blank template without the PackageManager
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; } if ($this->packageManager->existPackage($themeName) === false) { throw new \RuntimeException(sprintf('The theme: "%s" does not exist at registered repositories.', $themeName)); } if ($this->packageManager->isThemePackage($themeName) === false) { throw new \RuntimeException(sprintf('The theme: "%s" is not a Spress theme.', $themeName)); } if ($this->packageManager->isPackageDependOn($themeName, $this->spressInstallerPackage) === false) { throw new \RuntimeException(sprintf( sprintf('This version of Spress requires a theme with "%s".', $this->spressInstallerPackage), $themeName )); } $this->updateDependencies($preferLock, $preferSource, $noScripts); $relativeThemePath = 'src/themes/'.$themePair->getName(); $this->copyContentFromThemeToSite($path, $relativeThemePath); $this->setUpSiteConfigFile($path, $relativeThemePath, $themePair->getName()); }
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 theme's name is invalid
entailment
protected function updateDependencies($preferLock, $preferSource, $noScripts) { $pmOptions = [ 'prefer-source' => $preferSource, 'prefer-dist' => !$preferSource, 'no-scripts' => $noScripts, ]; if ($preferLock === true) { $this->packageManager->install($pmOptions); } else { $this->packageManager->update($pmOptions); } }
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)); } $existsPath ? $this->clearDir($path) : $this->fs->mkdir($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); } $orgDir = getcwd(); chdir($path); $this->fs->mkdir([ 'build', 'src/layouts', 'src/content', 'src/content/posts', 'src/content/assets', 'src/includes', 'src/plugins', ]); $this->renderFile('site/config.yml.twig', 'config.yml', [ 'theme_name' => $themeName, ]); $this->renderFile('site/composer.json.twig', 'composer.json', [ 'requires' => $this->generateRequirePackages($packagePairs), ]); $this->fs->dumpFile('src/content/index.html', ''); chdir($orgDir); }
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.'/'.$relativeThemePath.'/src/content') ->exclude(['assets']) ->files(); foreach ($finder as $file) { $this->fs->copy($file->getRealpath(), $sitePath.'/src/content/'.$file->getRelativePathname(), true); } }
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); $configValues = Yaml::parse($configContent); $configValues['themes'] = ['name' => $themeName]; $configParsed = Yaml::dump($configValues); $this->fs->dumpFile($destination, $configParsed); }
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 true; }
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) { $this->fs->remove($items); } }
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 with id: "%s" has been registered previously with another collection.', $id)); } if (isset($this->itemCollections[$collectionName]) === false) { $this->itemCollections[$collectionName] = []; } $this->itemCollections[$collectionName][$id] = $item; $this->idCollections[$id] = $collectionName; }
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 ($collections as $collection) { if (isset($this->itemCollections[$collection]) === false) { continue; } if ($groupByCollection === false) { $result = array_merge($result, $this->itemCollections[$collection]); continue; } $result[$collection] = $this->itemCollections[$collection]; } return $result; }
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[$attribute]) === true ? $attributes[$attribute] : null; }; foreach ($itemCollections as $collection => $items) { $arr = new ArrayWrapper($items); $itemsSorted = $arr->sortBy($callback, null, SORT_REGULAR, $descending); $this->itemCollections[$collection] = $itemsSorted; } $this->items = []; foreach ($this->itemCollections as $collection => $items) { $this->items = array_merge($this->items, $items); } return $this; }
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 belong to Collections will be affected @return Yosymfony\Spress\Core\Support\ItemCollection An intance of itself
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); $this->checkThemeName($themeName); $this->processPath($path, $force); $this->checkRequirements($themeName); $this->packageManager->createThemeProject( $path, $themeName, $options['repository'], $options['prefer-source'] ); }
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 package, which will be used instead of packagist @param bool $force Force to clear destination if exists and it's not empty' @param array $options Options: "prefer-source", "prefer-lock" or "repository" @throws LogicException If there is an attemp of create a non-blank template without the PackageManager
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) { throw new \RuntimeException(sprintf( 'An error has been occurred with code: %s while resolving dependencies.', $status )); } }
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->run(); if ($status !== 0) { throw new \RuntimeException(sprintf( 'An error has been occurred with code: %s while resolving dependencies.', $status )); } }
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) { $fs->dumpFile($file, "{\n}\n"); } $json = new JsonFile($file); $requirements = $this->formatPackageNames($packageNames); $versionParser = new VersionParser(); foreach ($requirements as $constraint) { $versionParser->parseConstraints($constraint); } $composerDefinition = $json->read(); $requireKey = $areDevPackages ? 'require-dev' : 'require'; foreach ($requirements as $package => $version) { $composerDefinition[$requireKey][$package] = $version; } $json->write($composerDefinition); return $composerDefinition[$requireKey]; }
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); $composerDefinition = $jsonFile->read(); $type = $areDevPackages ? 'require-dev' : 'require'; foreach ($packages as $name => $version) { if (isset($composerDefinition[$type][$name])) { $json->removeLink($type, $name); unset($composerDefinition[$type][$name]); continue; } $this->io->writeError(sprintf( 'Package: "%s" is not required and has not been removed.', $name )); } return $composerDefinition[$type]; }
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(RepositoryFactory::defaultRepos($this->io, $config)); } else { $sourceRepo = RepositoryFactory::fromString($this->io, $config, $repository, true); } $pool = new Pool($packagePair->getStability()); $pool->addRepository($sourceRepo); $platformOverrides = $config->get('platform') ?: []; $platform = new PlatformRepository([], $platformOverrides); $phpPackage = $platform->findPackage('php', '*'); $phpVersion = $phpPackage->getVersion(); $prettyPhpVersion = $phpPackage->getPrettyVersion(); $versionSelector = new VersionSelector($pool); $package = $versionSelector->findBestCandidate( $packagePair->getName(), $packagePair->getVersion(), $phpVersion, $packagePair->getStability() ); if (is_null($package)) { $errorMessage = sprintf( 'Could not find the theme "%s"', $packagePair->getName() ); $versionWithoutPHP = $versionSelector->findBestCandidate( $packagePair->getName(), $packagePair->getVersion(), null, $packagePair->getStability() ); if ($phpVersion && $versionWithoutPHP) { throw new \InvalidArgumentException( sprintf( '%s in a version installable using your PHP version %s.', $errorMessage, $prettyPhpVersion ) ); } throw new \InvalidArgumentException($errorMessage.'.'); } if ($package->getType() != self::PACKAGE_TYPE_THEME) { throw new \InvalidArgumentException(sprintf( 'The package "%s" is not a Spress theme.', $packageName )); } if (strpos($package->getPrettyVersion(), 'dev-') === 0 && in_array($package->getSourceType(), array('git', 'hg'))) { $package->setSourceReference(substr($package->getPrettyVersion(), 4)); } $dm = $this->createDownloadManager($config); $dm->setPreferSource($preferSource) ->setPreferDist(!$preferSource); $projectInstaller = new ProjectInstaller($siteDir, $dm); $im = new InstallationManager(); $im->addInstaller($projectInstaller); $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package)); $im->notifyInstalls($this->io); if (is_null($repository)) { $this->removeVcsMetadata($siteDir); } }
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 source when available @throws InvalidArgumentException If the package is not a Spress theme or or the host doesn't meet the requirements
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) { foreach ($package->{'get'.$meta['method']}() as $link) { if ($link->getPrettyConstraint() === 'self.version') { $configSource->addLink( $type, $link->getTarget(), $package->getPrettyVersion() ); } } } }
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() == self::PACKAGE_TYPE_THEME; }
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)); } $requires = $composerPackageA->getRequires(); $pairPackageB = new PackageNameVersion($packageNameB); foreach ($requires as $link) { if ($link->getTarget() == $pairPackageB->getName()) { if ($link->getConstraint()->matches($pairPackageB->getComposerVersionConstraint())) { return true; } return false; } } return false; }
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 = $this->embeddedComposer->createComposer($this->io); $repoManager = $composer->getRepositoryManager(); $name = $packagePair->getName(); $version = $packagePair->getVersion(); $composerPackage = $this->packageCache[$packageName] = $repoManager->findPackage($name, $version); return $composerPackage; }
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 $vcsName) { $finder->name($vcsName); } try { foreach ($finder as $dir) { $fs->remove($dir); } } catch (\Exception $e) { $this->io->writeError(sprintf( 'An error occurred while removing the VCS metadata: %s.', $e->getMessage() )); } }
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; if ($this->extension === '') { $this->hasPredefinedExt = false; $this->extension = parent::getExtension(); } } return $this->extension; }
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']['env']; $drafts = $spress['spress.config.values']['drafts']; $safe = $spress['spress.config.values']['safe']; $debug = $spress['spress.config.values']['debug']; $host = $spress['spress.config.values']['host']; $port = $spress['spress.config.values']['port']; $serverWatchExtension = $spress['spress.config.values']['server_watch_ext']; if ($debug === true) { $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); } $this->startingMessage($io, $env, $drafts, $safe); $resultData = $spress->parse(); $this->resultMessage($io, $resultData); $sourceDir = $spress['spress.config.site_dir']; $destinationDir = $spress['spress.config.build_dir']; $rw = $this->buildResourceWatcher($sourceDir, $destinationDir); if ($server === true) { $documentroot = $destinationDir; $serverroot = __DIR__.'/../../app/httpServer'; $server = new HttpServer($io, $serverroot, $documentroot, $port, $host); if ($watch === true) { $io->labelValue('Auto-regeneration', 'enabled'); $server->onBeforeRequest(function (ServerRequest $request) use ($io, $input, $rw, $serverWatchExtension) { $resourceExtension = pathinfo($request->getPathFilename(), PATHINFO_EXTENSION); if (in_array($resourceExtension, $serverWatchExtension)) { $this->reParse($io, $input, $rw); } }); } $server->start(); } elseif ($watch) { $io->labelValue('Auto-regeneration', 'enabled'); $io->write('<comment>Press ctrl-c to stop.</comment>'); $io->newLine(); do { sleep(2); $this->reParse($io, $input, $rw); } while (true); } }
{@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 (is_null($sourceDir) === true) { $sourceDir = './'; } if (($realDir = realpath($sourceDir)) === false) { throw new \RuntimeException(sprintf('Invalid source path: "%s".', $sourceDir)); } $spress = $this->getSpress($realDir); $spress['spress.config.env'] = $env; $spress['spress.config.safe'] = $safe; $spress['spress.config.drafts'] = $drafts; $spress['spress.config.timezone'] = $timezone; $resolver = $this->getConfigResolver(); $resolver->resolve($spress['spress.config.values']); if ($spress['spress.config.values']['parsedown_activated'] === true) { $this->enableParsedown($spress); $io->labelValue('Parsedown converter', 'enabled'); } $spress['spress.io'] = $io; return $spress; }
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()); $spress = $this->buildSpress($io, $input); $resultData = $spress->parse(); $this->resultMessage($io, $resultData); }
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); if (false === strpos($relativeDestination, '..')) { $finder->exclude($relativeDestination); } $rc = new ResourceCacheMemory(); $rw = new ResourceWatcher($rc); $rw->setFinder($finder); return $rw; }
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) ->setValidator('port', function ($value) { return $value >= 0; }) ->setDefault('server_watch_ext', ['html'], 'array', true) ->setDefault('parsedown_activated', false, 'bool', true); $this->configResolver = $resolver; return $this->configResolver; }
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']; $predefinedConverters['ParsedownConverter'] = new ParsedownConverter($markdownExts); return $predefinedConverters; }); }
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 ($draft === true) { $io->labelValue('Draft posts', 'enabled'); } if ($safe === true) { $io->labelValue('Plugins', 'disabled'); } }
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($updatedResources), count($deletedResources) )); $io->newLine(); }
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 = $symfonyConsoleApp->find($commandName); $arguments['command'] = $commandName; $arrayInput = new ArrayInput($arguments); return $commandToRun->run($arrayInput, $this->output); }
{@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 Console application does not support Spress.'); }
{@inheritdoc}
entailment
public function buildCommands() { $result = []; $pluginsCollection = $this->pluginManager->getPluginCollection(); foreach ($pluginsCollection as $plugin) { if ($this->isValidCommandPlugin($plugin) === true) { $result[] = $this->buildCommand($plugin); } } return $result; }
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()); $consoleComand->setHelp($definition->getHelp()); foreach ($definition->getArguments() as list($name, $mode, $description, $defaultValue)) { $argumentsAndOptions[] = new InputArgument($name, $mode, $description, $defaultValue); } foreach ($definition->getOptions() as list($name, $shortcut, $mode, $description, $defaultValue)) { $argumentsAndOptions[] = new InputOption($name, $shortcut, $mode, $description, $defaultValue); } $consoleComand->setDefinition($argumentsAndOptions); $consoleComand->setCode(function (InputInterface $input, OutputInterface $output) use ($commandPlugin, $consoleComand) { $io = new ConsoleIO($input, $output); $arguments = $input->getArguments(); $options = $input->getOptions(); $commandPlugin->setCommandEnvironment(new SymfonyCommandEnvironment($consoleComand, $output)); $commandPlugin->executeCommand($io, $arguments, $options); }); return $consoleComand; }
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['_calendar']['month']; $data = $this->dataContainer; $currentYear = (int)date('Y'); $currentMonth = (int)date('n'); if ($year === $currentYear && $month === $currentMonth) { $today = (int)date('j'); } $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year)); $firstDayInMonth = date('D', mktime(0, 0, 0, $month, 1, $year)); $firstDayInMonth = strtolower($firstDayInMonth); $str .= '<table class="calendar">'; $str .= '<thead>'; $str .= '<tr><th class="cell-prev">'; $str .= $this->previousLink(); $str .= '</th><th colspan="5" class="cell-month">' . __(ucfirst($this->monthName($month))) . ' ' . $year . '</th><th class="cell-next">'; $str .= $this->nextLink(); $str .= '</th></tr>'; $str .= '<tr>'; for ($i = 0; $i < 7;$i++) { $str .= '<th class="cell-header">' . __(ucfirst($this->dayList[$i])) . '</th>'; //TODO: i18n! } $str .= '</tr>'; $str .= '</thead>'; $str .= '<tbody>'; while ($day <= $daysInMonth) { $str .= '<tr>'; for ($i = 0; $i < 7; $i++) { $cell = '&nbsp;'; if (isset($data[$day])) { $cell = '<ul>' . implode(PHP_EOL, $data[$day]) . '</ul>'; } $class = ''; if ($i > 4) { $class = ' class="cell-weekend" '; } if ($day === $today && ($firstDayInMonth == $this->dayList[$i] || $day > 1) && ($day <= $daysInMonth)) { $class = ' class="cell-today" '; } if (($firstDayInMonth == $this->dayList[$i] || $day > 1) && ($day <= $daysInMonth)) { $str .= '<td ' . $class . '><div class="cell-number">' . $day . '</div><div class="cell-data">' . $cell . '</div></td>'; $day++; } else { $str .= '<td class="cell-disabled">&nbsp;</td>'; } } $str .= '</tr>'; } $str .= '</tbody>'; $str .= '</table>'; return $str; }
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) { return $url; } $url[] = $year; $url[] = $this->formatMonth($month); return $url; }
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)); } $content = file_get_contents($filename); if ($content === false) { throw new IOException(sprintf('Error reading the content of the file "%s".', $filename)); } return $content; }
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