sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function addConverter(ConverterInterface $converter) { $priority = $converter->getPriority(); if (false === (is_int($priority) && $priority >= 0 && $priority <= 10)) { throw new \InvalidArgumentException(sprintf('Invalid priority at the converter: "%s".', get_class($converter))); } $this->queue->insert($converter, $priority); }
Adds a converter. @param Yosymfony\Spress\Core\ContentManager\Converter\ConverterInterface $converter The converter @throws RuntimeException If invalid priority at the converter
entailment
public function convertContent($content, $inputExtension) { $converter = $this->getConverter($inputExtension); $content = $converter->convert($content); $outputExtension = $converter->getOutExtension($inputExtension); return new ConverterResult( $content, $inputExtension, $outputExtension ); }
Converts the content. @param string $content The content @param string $inputExtension The filename extension. e.g: 'html' @return Yosymfony\Spress\Core\ContentManager\Converter\ConverterResult @throws RuntimeException If there's no converter for the extension passed
entailment
public function convertItem(ItemInterface $item) { $path = $item->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE); $str = new StringWrapper($path); $extension = $str->getFirstEndMatch($this->textExtensions); if ($extension === '') { $extension = pathinfo($path, PATHINFO_EXTENSION); } return $this->convertContent($item->getContent(), $extension); }
Converts an item. This method uses the SNAPSHOT_PATH_RELATIVE of Item path. @param Yosymfony\Spress\Core\DataSource\ItemInterface $item The item @return Yosymfony\Spress\Core\ContentManager\Converter\ConverterResult @throws RuntimeException If there's no converter for the extension passed
entailment
public function buildFromConfigArray(array $config) { $cm = new CollectionManager(); $collectionItemCollection = $cm->getCollectionItemCollection(); foreach ($config as $collectionName => $attributes) { $path = $collectionName === 'pages' ? '' : $collectionName; if (is_array($attributes) === false) { throw new \RuntimeException(sprintf('Expected array at the collection: "%s".', $collectionName)); } $collectionItemCollection->set($collectionName, new Collection($collectionName, $path, $attributes)); } return $cm; }
Build a collection manager with collections loaded from config array. A config array has the following sign: .Array ( [collection_name_1] => Array ( [attribute_1] => 'value' ) [collection_name_2] => Array ( ) ) @param array $config Configuration array with data about collections @return Yosymfony\Spress\Core\ContentManager\Collection\CollectionManager @throws RuntimeException If unexpected type of data
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $title = Validators::validatePostTitle($input->getOption('title')); $layout = $input->getOption('layout'); $date = $input->getOption('date') ?: $this->getDateFormated(); $tags = array_map('trim', explode(',', $input->getOption('tags') ?: '')); $categories = array_map('trim', explode(',', $input->getOption('categories') ?: '')); $postsDir = './src/content/posts'; $generator = new PostGenerator(); $generator->setSkeletonDirs([$this->getSkeletonsDir()]); $files = $generator->generate($postsDir, new \DateTime($date), $title, $layout, $tags, $categories); $this->resultMessage($io, $files); }
{@inheritdoc}
entailment
protected function interact(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $this->welcomeMessage($io); $title = $io->askAndValidate( 'Post title', function ($answer) { return Validators::validatePostTitle($answer); }, false, $input->getOption('title') ); $input->setOption('title', $title); $layout = $io->ask('Post layout', $input->getOption('layout')); $input->setOption('layout', $layout); $defaultDate = $input->getOption('date'); if (empty($defaultDate) === true) { $defaultDate = $this->getDateFormated(); } $date = $io->ask('Post date', $defaultDate); $input->setOption('date', $date); if ($io->askConfirmation('Do you want to use tags?', empty($input->getOption('tags')) === false)) { $tags = $io->ask('Comma separated list of post tags', $input->getOption('tags')); $input->setOption('tags', $tags); } if ($io->askConfirmation('Do you want to use categories?', empty($input->getOption('categories')) === false)) { $categories = $io->ask('Comma separated list of post categories', $input->getOption('categories')); $input->setOption('categories', $categories); } }
{@inheritdoc}
entailment
public function generateItems(ItemInterface $templateItem, array $collections) { $result = []; $taxonomyCollection = []; $termCollection = []; $templateAttributes = $templateItem->getAttributes(); $options = $this->buildAttributesResolver($templateItem); $taxonomyAttribute = $options['taxonomy_attribute']; $permalink = $options['permalink']; $templateAttributes['permalink'] = $options['pagination_permalink']; $templatePath = dirname($templateItem->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE)); $items = (new ArrayWrapper($collections))->flatten(); foreach ($items as $item) { $attributes = $item->getAttributes(); if (isset($attributes[$taxonomyAttribute]) === false) { continue; } $terms = (array) $attributes[$taxonomyAttribute]; foreach ($terms as $term) { if (empty(trim($term)) === true) { continue; } $term = $this->normalizeTerm($term); $slugedTerm = (new StringWrapper($term))->slug(); if (isset($taxonomyCollection[$slugedTerm]) === false) { $taxonomyCollection[$slugedTerm] = []; } if (isset($termCollection[$slugedTerm]) === false) { $termCollection[$slugedTerm] = []; } if (in_array($item, $taxonomyCollection[$slugedTerm]) === false) { $taxonomyCollection[$slugedTerm][] = $item; } if (in_array($term, $termCollection[$slugedTerm]) === false) { $termCollection[$slugedTerm][] = $term; } } } ksort($taxonomyCollection); foreach ($taxonomyCollection as $slugedTerm => $items) { $templateAttributes['provider'] = 'site.'.$slugedTerm; $templateAttributes['term'] = $termCollection[$slugedTerm][0]; $templateItem->setAttributes($templateAttributes); $slugedTermPath = $this->getTermRelativePath($templatePath, $permalink, $slugedTerm); $templateItem->setPath($slugedTermPath, ItemInterface::SNAPSHOT_PATH_RELATIVE); $paginationGenerator = new PaginationGenerator(); $itemsGenerated = $paginationGenerator->generateItems($templateItem, [$slugedTerm => $items]); $this->setTermsPermalink($items, $taxonomyAttribute, $termCollection[$slugedTerm], $slugedTermPath); $result = array_merge($result, $itemsGenerated); } return $result; }
{@inheritdoc} @throws Yosymfony\Spress\Core\ContentManager\Exception\AttributeValueException if bad attribute value
entailment
protected function setTermsPermalink(array $items, $taxonomyAttribute, array $terms, $termRelativePath) { foreach ($items as $item) { $attributes = $item->getAttributes(); if (isset($attributes['term_urls'])) { $attributes['term_urls'] = []; } if (isset($attributes['term_urls'][$taxonomyAttribute])) { $attributes['term_urls'][$taxonomyAttribute] = []; } $slugedTermPermalink = $this->getTermPermalink($termRelativePath); foreach ($terms as $term) { $attributes['terms_url'][$taxonomyAttribute][$term] = $slugedTermPermalink; } $item->setAttributes($attributes); } }
Sets the permalink's term to a list of items associated with that term. @param array $items List of items associated with a the term @param string $taxonomyAttribute The item's attribute used for grouping by @param array $terms Term or set of sluged equivalent terms @param string $termRelativePath Relative path to the term. Used for generating the permalink
entailment
protected function getTermRelativePath($basePath, $permalinkTemplate, $term) { $result = $basePath; $slugedTerm = (new StringWrapper($term))->slug(); $result .= '/'.str_replace(':name', $slugedTerm, $permalinkTemplate).'/index.html'; return ltrim(preg_replace('/\/\/+/', '/', $result), '/'); }
Returns the relative path of a term. @param string $basePath The base path @param string $permalinkTemplate The template of the permalink that will be applied @param string $term The term @return string
entailment
protected function getTermPermalink($TermRelativePath) { if (is_null($TermRelativePath)) { return; } $result = $TermRelativePath; $basename = basename($TermRelativePath); if ($basename === 'index.html') { $result = dirname($TermRelativePath); if ($result === '.') { $result = ''; } } return '/'.$result; }
Returns the permalink of a term relative-path-based. @param string $TermRelativePath The relative path of the term @return string
entailment
protected function buildAttributesResolver(ItemInterface $templateItem) { $resolver = new AttributesResolver(); $resolver->setDefault('taxonomy_attribute', 'categories', 'string') ->setDefault('permalink', '/:name') ->setDefault('pagination_permalink', '/page:num', 'string'); $attributes = $templateItem->getAttributes(); return $resolver->resolve($attributes); }
Build the attribute resolver. @param ItemInterface $templateItem The item used as template @return AttributesResolver
entailment
public function addUse() { if (false === $this->isConfigured) { $this->configure(); $this->isConfigured = true; } if ($this->referenceCounter < 0) { $this->referenceCounter = 0; } if ($this->referenceCounter === 0) { $this->setUp(); } ++$this->referenceCounter; }
Marks as used the data source. This method increases the internal reference count. When the internal reference count goes from 0 to 1 setUp method is invoked.
entailment
public function retrieveMonth($month) { if (!$month) { return 0; } $month = mb_strtolower($month); if (in_array($month, $this->monthList)) { $keys = array_keys($this->monthList, $month); return $keys[0] + 1; } return 0; }
Month as integer value 1..12 or 0 on error february => 2 @param string $month @return int
entailment
public function retrieveDay($day, $month = null) { $day = (int)$day; if ($day < 1 || $day > 31) { return 0; } // TODO check on month days! return $day; }
Day as integer value 1..31 or 0 on error february => 2 @param string $day @param int|null $month @return int
entailment
protected function asString($number, $digits = 2) { $number = (string)$number; $count = mb_strlen($number); while ($count < $digits) { $number = '0' . $number; $count++; } return $number; }
Converts integer to x-digit string 1 => 01, 12 => 12 @param int $number @param int $digits @return string
entailment
public function getStability() { if (is_null($this->stability) === false) { return $this->stability; } if (preg_match('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $this->getVersion(), $match)) { $stability = $match[1]; } else { $stability = VersionParser::parseStability($this->getVersion()); } $this->stability = VersionParser::normalizeStability($stability); return $this->stability; }
Returns the package's version stability. @return string
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $theme = $input->getArgument('theme'); $io = new ConsoleIO($input, $output); if ($theme === self::SPRESSO_THEME) { $theme = 'spress/spress-theme-spresso'; } $this->startingMessage($io, $theme); if ($input->getOption('all') === true) { $io->warning('You are using a deprecated option "--all"'); } $packageManager = $this->getPackageManager($input->getArgument('path'), $io); $generator = new SiteGenerator($packageManager); $generator->setSkeletonDirs([$this->getSkeletonsDir()]); $generator->generate( $input->getArgument('path'), $theme, $input->getOption('force'), [ 'prefer-source' => $input->getOption('prefer-source'), 'prefer-lock' => $input->getOption('prefer-lock'), 'no-scripts' => $input->getOption('no-scripts'), ] ); $this->successMessage($io, $theme, $input->getArgument('path')); }
{@inheritdoc}
entailment
protected function startingMessage(ConsoleIO $io, $theme) { $io->newLine(); $io->write(sprintf('<comment>Generating a site using the theme: "%s"...</comment>', $theme)); }
Writes the staring messages. @param ConsoleIO $io Spress IO @param string $theme The theme
entailment
protected function successMessage(ConsoleIO $io, $theme, $path) { $io->success(sprintf('New site with theme "%s" created at "%s" folder', $theme, $path)); }
Writes the success messages. @param ConsoleIO $io Spress IO @param string $theme The theme @param string $path The path
entailment
public function write($messages, $newline = true, $verbosity = self::VERBOSITY_NORMAL) { $sfVerbosity = $this->verbosityMap[$verbosity]; if ($sfVerbosity > $this->sStyle->getVerbosity()) { return; } $this->sStyle->write($messages, $newline); $this->isFirstMessage = false; }
{@inheritdoc}
entailment
public function overwrite($messages, $newline = true, $verbosity = self::VERBOSITY_NORMAL) { if ($this->hasSupportAnsiCommands() === false || $this->isFirstMessage === true) { $this->write($messages, $newline, $verbosity); return; } $messages = implode($newline ? PHP_EOL : '', (array) $messages); $numNewLines = substr_count($messages, PHP_EOL); $this->write("\x0D", false, $verbosity); $this->write("\x1B[2K", false, $verbosity); if ($numNewLines > 0) { $this->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount), false, $verbosity); } $this->write($messages, false, $verbosity); if ($newline) { $this->write('', true, $verbosity); } }
{@inheritdoc} Based on ProgressBar helper of Symfony Console component. @see https://github.com/symfony/console/blob/master/Helper/ProgressBar.php#L470
entailment
public function askAndValidate($question, callable $validator, $attempts = false, $default = null) { $attempts = is_int($attempts) ? $attempts : null; $question = new Question($question, $default); $question->setValidator($validator); $question->setMaxAttempts($attempts); return $this->sStyle->askQuestion($question); }
{@inheritdoc}
entailment
public function askAndHideAnswer($question, $fallback = true) { $question = new Question($question); $question->setHidden(true); $question->setHiddenFallback($fallback); return $this->sStyle->askQuestion($question); }
{@inheritdoc}
entailment
public function askHiddenResponseAndValidate($question, callable $validator, $attempts = false, $fallback = true) { $attempts = is_int($attempts) ?: null; $question = new Question($question); $question->setHidden(true); $question->setValidator($validator); $question->setMaxAttempts($attempts); $question->setHiddenFallback($fallback); return $this->sStyle->askQuestion($question); }
{@inheritdoc}
entailment
public function askChoice($question, array $choices, $default = null, $attempts = null, $errorMessage = 'Value "%s" is invalid', $multiselect = false) { $attempts = is_int($attempts) ?: null; $question = new ChoiceQuestion($question, $choices, $default); $question->setErrorMessage($errorMessage); $question->setMultiselect($multiselect); $question->setMaxAttempts($attempts); return $this->sStyle->askQuestion($question); }
{@inheritdoc}
entailment
public function getAttributes() { $attributes = parent::getAttributes(); if (isset($attributes['pagination']) === false) { return $attributes; } $attributes['pagination']['items'] = []; foreach ($this->pageItems as $item) { $attributes['pagination']['items'][$item->getId()] = $this->getItemAttributes($item); } return $attributes; }
{@inheritdoc}
entailment
protected function getItemAttributes(ItemInterface $item) { $result = $item->getAttributes(); $result['id'] = $item->getId(); $result['content'] = $item->getContent(); $result['collection'] = $item->getCollection(); $result['path'] = $item->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE); return $result; }
Gets the attributes of an item. @param ItemInterface $item @return array
entailment
public function parse() { $attributes = $this['spress.config.values']; $spressAttributes = $this->getSpressAttributes(); $siteMetadata = $this['spress.siteMetadata']; $siteMetadata->set('generator', 'version', self::VERSION); $result = $this['spress.cms.contentManager']->parseSite( $attributes, $spressAttributes, $attributes['drafts'], $attributes['safe'], $attributes['timezone'] ); $dependencyResolver = $this['spress.DependencyResolver']; $siteMetadata->set('site', 'dependencies', $dependencyResolver->getAllDependencies()); $siteMetadata->save(); return $result; }
Parse a site. Example: $spress['spress.config.site_dir'] = '/my-site-folder'; $spress['spress.config.drafts'] = true; $spress['spress.config.safe'] = false; $spress['spress.config.timezone'] = 'UTC'; $spress['spress.config.url'] = 'http://your-domain.local:4000'; $spress->parse(); @return Yosymfony\Spress\Core\DataSource\ItemInterface[] Items of the site
entailment
public function write(ItemInterface $item) { if ($this->isWritable($item) === false) { return; } if ($item->isBinary()) { $this->items[$item->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE_AFTER_CONVERT)] = $item; } else { $this->items[$item->getPath(ItemInterface::SNAPSHOT_PATH_PERMALINK)] = $item; } }
{@inheritdoc}
entailment
public function configure() { $this->items = []; $this->layouts = []; $this->includes = []; $resolver = $this->createResolver(); $this->params = $resolver->resolve($this->params); switch ($this->params['attribute_syntax']) { case 'yaml': $this->attributeParser = new AttributeParser(AttributeParser::PARSER_YAML); break; case 'json': $this->attributeParser = new AttributeParser(AttributeParser::PARSER_JSON); break; } }
{@inheritdoc} @throws AttributeValueException If attributes do not validate all the rules. @throws MissingAttributeException If missing attribute.
entailment
public function getPathFilename() { $path = $this->getPath(); if ($this->isInternal()) { return $this->serverRoot.$path; } $path = $this->documentRoot.$path; if (is_dir($path) === true) { $path .= '/index.html'; } return preg_replace('/\/\/+/', '/', $path); }
Gets the path with "index.html" append. @return string Absolute path using either document root or server root (iternal requests)
entailment
public function getMimeType() { $mimetypeRepo = new PhpRepository(); $path = $this->getPathFilename(); return $mimetypeRepo->findType(pathinfo($path, PATHINFO_EXTENSION)) ?: 'application/octet-stream'; }
Gets the Mime Type. @return string. Myme type. "application/octet-stream" by default
entailment
public function generate($targetDir, \DateTime $date, $title, $layout, array $tags = [], array $categories = []) { if (0 === strlen(trim($title))) { throw new \RuntimeException('Unable to generate the post as the title is empty.'); } if (file_exists($targetDir)) { if (false === is_dir($targetDir)) { throw new \RuntimeException(sprintf('Unable to generate the post as the target directory "%s" exists but is a file.', $targetDir)); } if (false === is_writable($targetDir)) { throw new \RuntimeException(sprintf('Unable to generate the post as the target directory "%s" is not writable.', $targetDir)); } } $model = [ 'layout' => $layout, 'title' => $title, 'categories' => $categories, 'tags' => $tags, ]; $this->cleanFilesAffected(); $this->renderFile('post/post.md.twig', $targetDir.'/'.$this->getPostFilename($date, $title), $model); return $this->getFilesAffected(); }
Generates a post. @param $targetDir string @param $tdate DateTime @param $title string @param $layout string @param $categories array @param $tags array @return array
entailment
public function add($key, $element) { if ($this->has($key) === false) { $this->set($key, $element); } }
Adds a new element in this collection. @param mixed $key The key associated to the element @param mixed $element The element
entailment
public function get($key) { if ($this->has($key) === false) { throw new \RuntimeException(sprintf('Element with key: "%s" not found.', $key)); } return $this->elements[$key]; }
Gets a element from the collection. @param string $key The element identifier @return mixed The element @throws RuntimeException If the key is not defined
entailment
public function loadConfiguration($sitePath, $envName = null) { if ($this->isSpressSite($sitePath) === false) { throw new \RuntimeException(sprintf('Not a Spress site at "%s".', $sitePath)); } $default = $this->loadDefaultConfiguration(); $dev = $this->loadEnvironmentConfiguration($sitePath, 'dev'); $result = $this->resolver->resolve(array_merge($default, $dev)); if (is_null($envName)) { $envName = $result['env']; } if ($envName !== 'dev') { $environment = $this->loadEnvironmentConfiguration($sitePath, $envName); $environment['env'] = $envName; $result = $this->resolver->resolve(array_merge($result, $environment)); } return $result; }
{@inheritdoc}
entailment
public function setCommandData($name, $description = '', $help = '') { $this->commandName = $name; $this->commandDescription = $description; $this->commandHelp = $help; }
Sets the command's data in case of command plugin. @param string $name The name of the command @param string $description The description of the command
entailment
public function generate() { $this->dirctoryName = $this->getPluginDir($this->name); $pluginDir = $this->targetDir.'/'.$this->dirctoryName; if (file_exists($pluginDir)) { throw new \RuntimeException(sprintf('Unable to generate the plugin as the plugin directory "%s" exists.', $pluginDir)); } $model = [ 'name' => $this->name, 'classname' => $this->getClassname($this->name), 'namespace' => $this->namespace, 'namespace_psr4' => $this->getNamespacePsr4($this->namespace), 'author' => $this->author, 'email' => $this->email, 'description' => $this->description, 'license' => $this->license, ]; $this->cleanFilesAffected(); $pluginTemplateFile = 'plugin/plugin.php.twig'; if (empty($this->commandName) === false) { $pluginTemplateFile = 'plugin/commandPlugin.php.twig'; $model['command_name'] = $this->commandName; $model['command_description'] = $this->commandDescription; $model['command_help'] = $this->commandHelp; } $this->renderFile($pluginTemplateFile, $pluginDir.'/'.$this->getPluginFilename($this->name), $model); $this->renderFile('plugin/composer.json.twig', $pluginDir.'/composer.json', $model); $licenseFile = $this->getLicenseFile($this->license); if ($licenseFile) { $model = [ 'author' => $this->author, ]; $this->renderFile($licenseFile, $pluginDir.'/LICENSE', $model); } return $this->getFilesAffected(); }
Generates a plugin. @return array
entailment
protected function getClassname($name) { $result = implode(' ', explode('/', $name)); $result = implode(' ', explode('-', $result)); $result = ucwords($result); // replace non letter or digits by empty string $result = preg_replace('/[^\\pL\d]+/u', '', $result); // trim $result = trim($result, '-'); // transliterate $result = iconv('UTF-8', 'US-ASCII//TRANSLIT', $result); // remove unwanted characters $result = preg_replace('/[^-\w]+/', '', $result); return $result; }
Gets the classname. @param string $name @return string
entailment
protected function getLicenseFile($licenseName) { return isset($this->licenses[strtoupper($licenseName)]) ? $this->licenses[strtoupper($licenseName)] : ''; }
Gets the license filename. @param string $licenseName @return string Filename or empty-string if not exists
entailment
public function addGenerator($name, GeneratorInterface $generator) { if ($this->hasGenerator($name) === true) { throw new \RuntimeException(sprintf('A previous generator exists with the same name: "%s".', $name)); } $this->setGenerator($name, $generator); }
Adds a new generator. @param string $name The generator name @param \Yosymfony\Spress\Core\ContentManager\Generator\GeneratorInterface $generator @throws RuntimeException If a previous generator exists with the same name
entailment
public function getGenerator($name) { if ($this->hasGenerator($name) === false) { throw new \RuntimeException(sprintf('Generator not found: "%s".', $name)); } return $this->generators[$name]; }
Gets a generator. @param string $name The generator name @return \Yosymfony\Spress\Core\ContentManager\Generator\GeneratorInterface @throws RuntimeException If the generator is not defined
entailment
public function getContent($snapshotName = '') { if ($snapshotName) { if (isset($this->snapshot[$snapshotName]) === false) { return ''; } return $this->snapshot[$snapshotName]; } return isset($this->snapshot[self::SNAPSHOT_LAST]) === true ? $this->snapshot[self::SNAPSHOT_LAST] : ''; }
{@inheritdoc}
entailment
public function setContent($content, $snapshotName) { $this->snapshot[$snapshotName] = $content; $this->snapshot[self::SNAPSHOT_LAST] = $content; }
{@inheritdoc}
entailment
public function getPath($snapshotName = '') { if ($snapshotName) { if (isset($this->pathSnapshot[$snapshotName]) === false) { return ''; } return $this->pathSnapshot[$snapshotName]; } return isset($this->pathSnapshot[self::SNAPSHOT_PATH_LAST]) === true ? $this->pathSnapshot[self::SNAPSHOT_PATH_LAST] : ''; }
{@inheritdoc}
entailment
public function setPath($value, $snapshotName) { $this->pathSnapshot[$snapshotName] = $value; $this->pathSnapshot[self::SNAPSHOT_PATH_LAST] = $value; }
{@inheritdoc}
entailment
public function setDefault($attribute, $value, $type = null, $required = false, $nullable = false) { $this->defaults[$attribute] = $value; if (empty($type) === false) { $this->types[$attribute] = $type; } if ($required === true) { $this->requires[] = $attribute; } if ($nullable === false) { $this->notNullables[] = $attribute; } return $this; }
Sets the default value of a given attribute. @param string $attribute The name of the attribute @param mixed $value The default value of the attribute @param string $type The accepted type. Any type for which a corresponding is_<type>() function exists is acceptable @param bool $required Is that attribute required? @param bool $nullable Is that attribute nullable? @return \Yosymfony\Spress\Core\Support\AttributesResolver This instance
entailment
public function resolve(array $attributes) { $clone = clone $this; $clone->resolved = array_replace($clone->defaults, $attributes); foreach ($clone->types as $attribute => $type) { if (function_exists($isFunction = 'is_'.$type) === true) { if (is_null($clone->resolved[$attribute]) === false && $isFunction($clone->resolved[$attribute]) === false) { throw new AttributeValueException( sprintf('Invalid type of value. Expected "%s".', $type), $attribute ); } } } foreach ($clone->notNullables as $attribute) { if (is_null($clone->resolved[$attribute]) === true) { throw new AttributeValueException('Unexpected null value.', $attribute); } } foreach ($clone->validators as $attribute => $validator) { if (is_null($clone->resolved[$attribute]) === false && $validator($clone->resolved[$attribute]) === false) { throw new AttributeValueException( sprintf('Invalid value.', $attribute), $attribute ); } } foreach ($clone->requires as $attribute) { if (array_key_exists($attribute, $attributes) === false) { throw new MissingAttributeException(sprintf('Missing attribute or option "%s".', $attribute)); } } return $clone->resolved; }
Merges options with the default values and validates them. If an attribute is marked as nullable the validate function never will be invoked. @param array $attributes @return array The merged and validated options @throws \Yosymfony\Spress\Core\ContentManager\Exception\AttributeValueException If the attributes don't validate the rules @throws \Yosymfony\Spress\Core\ContentManager\Exception\MissingAttributeException If a required values is missing
entailment
public function clear() { $this->defaults = []; $this->types = []; $this->requires = []; $this->notNullables = []; return $this; }
Remove all attributes.
entailment
public function remove($attributes) { foreach ((array) $attributes as $attribute) { unset($this->defaults[$attribute], $this->types[$attribute], $this->requires[$attribute], $this->notNullables[$attribute]); } return $this; }
Removes the attributes with the given name. @param string|string[] One or more attributes @return \Yosymfony\Spress\Core\Support\AttributesResolver This instance
entailment
public static function validateCommandName($name) { $name = trim($name); if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) { throw new \InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name)); } return $name; }
Validator for the name of a command (command plugins). @param string $name @return string
entailment
public static function validateEmail($email) { $email = trim($email); if (false === filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new \InvalidArgumentException(sprintf('The Email "%s" is invalid.', $email)); } return $email; }
Validator for a Email. @param string $email @return string
entailment
public function load() { $this->initialize(); foreach ($this->dataSources as $name => $dataSource) { $dataSource->load(); $this->processItems($dataSource->getItems(), $name); $this->processLayouts($dataSource->getLayouts(), $name); $this->processIncludes($dataSource->getIncludes(), $name); } }
Load the items from the registered data sources. @throws RuntimeException If a previous data sources exists with the same id
entailment
public function addDataSource($name, AbstractDataSource $dataSource) { if ($this->hasDataSource($name)) { throw new \RuntimeException(sprintf('A previous data source exists with the same name: "%s".', $name)); } $this->dataSources[$name] = $dataSource; }
Adds a new data source. @param string $name The name of the data source @param AbstractDataSource $dataSource @throws \RuntimeException If a previous data sources exists with the same name
entailment
public function getDataSource($name) { if (false === $this->hasDataSource($name)) { throw new \RuntimeException(sprintf('Data source: "%s" not found.', $name)); } return $this->dataSources[$name]; }
Gets a data source. @return \Yosymfony\Spress\Core\DataSource\AbstractDataSource @throws \RuntimeException If data source not found
entailment
public function getPackageManager($siteDir, IOInterface $io) { $embeddedComposer = $this->getEmbeddedComposer($siteDir, 'composer.json', 'vendor'); $embeddedComposer->processAdditionalAutoloads(); return new PackageManager($embeddedComposer, $io); }
Returns an instance of PackageManager. It is configured to read a composer.json file. @param string $siteDir Root directory of an Spress site @return PackageManager
entailment
protected function getEmbeddedComposer($siteDir, $composerFilename, $vendorDir) { $classloader = $this->getApplication()->getClassloader(); $builder = new EmbeddedComposerBuilder($classloader, $siteDir); return $builder ->setComposerFilename($composerFilename) ->setVendorDirectory($vendorDir) ->build(); }
Returns an EmbeddedComposer instance. @return Dflydev\EmbeddedComposer\Core\EmbeddedComposer
entailment
public function setRelativeUrl($url) { $url = $this->prepareUrl($url); $attributes = $this->getAttributes(); $attributes['url'] = $url; $urlPath = $this->getPathFromUrl($url); $this->item->setPath($urlPath, ItemInterface::SNAPSHOT_PATH_PERMALINK); $this->setAttributes($attributes); }
Sets the relative URL (only path component) of the item. @param string $url The relative URL. e.g: /about/me/index.html
entailment
protected function prepareUrl($url) { if (empty($url)) { throw new \RuntimeException(sprintf('Empty URL at item with id: "%s"', $this->getId())); } if (stripos($url, '://') !== false) { throw new \RuntimeException(sprintf('Malformed relative URL at item with id: "%s"', $this->getId())); } if (stripos($url, '/') !== 0) { throw new \RuntimeException(sprintf('Relative URL must start with "/" at item with id: "%s"', $this->getId())); } return $url; }
Prepare a URL. @param string $url The relative URL @return string @throws \RuntimeException If empty or malformed relative URL
entailment
public function build() { $pm = new PluginManager($this->eventDispatcher); $pluginCollection = $pm->getPluginCollection(); if (file_exists($this->path) === false) { return $pm; } $classnamesFromComposerFile = []; $finder = $this->buildFinder(); foreach ($finder as $file) { if ($file->getFilename() === $this->composerFilename) { $classes = $this->getClassnamesFromComposerFile($file); $classnamesFromComposerFile = array_merge($classnamesFromComposerFile, $classes); continue; } $classname = $this->getClassnameFromPHPFilename($file); include_once $file->getRealPath(); if ($this->hasImplementedPluginInterface($classname) === false) { continue; } $this->addPluginToCollection($classname, $pluginCollection); } foreach ($classnamesFromComposerFile as $classname) { if ($this->hasImplementedPluginInterface($classname) === true) { $this->addPluginToCollection($classname, $pluginCollection); } } return $pm; }
Builds the PluginManager with the plugins of a site. Each plugin is added to PluginManager using "name" meta or its classname if that meta does not exists. @return PluginManager PluginManager filled with the valid plugins
entailment
protected function addPluginToCollection($classname, Collection $pluginCollection) { $plugin = new $classname(); $metas = $this->getPluginMetas($plugin); $pluginCollection->add($metas['name'], $plugin); }
Adds a new valid list of plugins (they must implements PluginInterface) to a collections of plugins. It performs a new operation for each valid plugin. @param string $classname @param Collection $pluginCollection
entailment
protected function getClassnamesFromComposerFile(SplFileInfo $file) { $composerData = $this->readComposerFile($file); if (isset($composerData['extra']['spress_class']) === false) { return []; } if ( is_string($composerData['extra']['spress_class']) === false && is_array($composerData['extra']['spress_class']) === false ) { return []; } return (array) $composerData['extra']['spress_class']; }
Extracts the class names from a composer.json file A composer.json file could defines several classes in spress_class property from extra section. @param SplFileInfo $file A composer.json file @return array List of class names
entailment
protected function getPluginMetas(PluginInterface $plugin) { $metas = $plugin->getMetas(); if (is_array($metas) === false) { $classname = get_class($plugin); throw new \RuntimeException(sprintf('Expected an array at method "getMetas" of the plugin: "%s".', $classname)); } $metas = $this->resolver->resolve($metas); if (empty($metas['name']) === true) { $metas['name'] = get_class($plugin); } return $metas; }
Gets metas of a plugin. @param string $filename The plugin filename @param PluginInterface $plugin The plugin @return array @throws RuntimeException If bad metas
entailment
protected function hasImplementedPluginInterface($name) { $result = false; if (class_exists($name)) { $implements = class_implements($name); if (isset($implements['Yosymfony\\Spress\\Core\\Plugin\\PluginInterface'])) { $result = true; } } return $result; }
Checks if the class implements the PluginInterface. @param string $name Class's name @return bool
entailment
protected function readComposerFile(SplFileInfo $file) { $json = $file->getContents(); $data = json_decode($json, true); return $data; }
Reads a "composer.json" file. @param SplFileInfo $file The file @return array The parsed JSON filename
entailment
protected function buildFinder() { $finder = new Finder(); $finder->files() ->name('/(\.php|composer\.json)$/') ->in($this->path) ->exclude($this->excludeDirs); return $finder; }
Returns a Finder set up for finding both composer.json and php files. @return Finder A Symfony Finder instance
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $name = Validators::validatePluginName($input->getOption('name')); $commandName = $input->getOption('command-name'); if (empty($commandName) === false) { $commandName = Validators::validateCommandName($commandName); } $commandDescription = $input->getOption('command-description'); $commandHelp = $input->getOption('command-help'); $author = $input->getOption('author'); $email = $input->getOption('email'); if (empty($email) === false) { $email = Validators::validateEmail($email); } $description = $input->getOption('description'); $license = $input->getOption('license') ?: 'MIT'; $generator = new PluginGenerator('./src/plugins', $name); $generator->setSkeletonDirs([$this->getSkeletonsDir()]); $generator->setCommandData($commandName, $commandDescription, $commandHelp); $generator->setAuthor($author, $email); $generator->setDescription($description); $generator->setLicense($license); $files = $generator->generate(); $this->resultMessage($io, $files); }
{@inheritdoc}
entailment
protected function interact(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $this->welcomeMessage($io); $name = $io->askAndValidate( 'Plugin name (follow the pattern <comment>"vendor-name/plugin-name"</comment>)', function ($answer) { return Validators::validatePluginName($answer); }, false, $input->getOption('name') ); $input->setOption('name', $name); if ($io->askConfirmation('Is it a command plugin?', empty($input->getOption('name')) === false)) { $commandName = $io->askAndValidate( 'Name of the command', function ($answer) { return Validators::validateCommandName($answer); }, false, $input->getOption('command-name') ); $input->setOption('command-name', $commandName); $commandDescription = $io->ask('Description for the command', $input->getOption('command-description')); $input->setOption('command-description', $commandDescription); $commandHelp = $io->ask('Help for the command', $input->getOption('command-help')); $input->setOption('command-help', $commandHelp); } $author = $io->ask('Plugin author', $input->getOption('author')); $input->setOption('author', $author); $email = $io->askAndValidate( 'Email author', function ($answer) { return Validators::validateEmail($answer); }, false, $input->getOption('email') ); $input->setOption('email', $email); $description = $io->ask('Plugin description', $input->getOption('description')); $input->setOption('description', $description); $this->licenseMessage($io); $defaultLicense = $input->getOption('license'); if (is_null($defaultLicense) === true) { $defaultLicense = 'MIT'; } $license = $io->ask('Plugin license', $defaultLicense); $input->setOption('license', $license); }
{@inheritdoc}
entailment
public function registerDependency($idA, $idDependentOnA) { if (isset($this->dependencies[$idA]) === false) { $this->dependencies[$idA] = []; } if (isset($this->dependencies[$idDependentOnA]) === false) { $this->dependencies[$idDependentOnA] = []; } if (in_array($idDependentOnA, $this->dependencies[$idA]) === false) { $this->dependencies[$idA][] = $idDependentOnA; } }
{@inheritdoc}
entailment
public function getIdsDependingOn($id) { $resolved = []; $unresolved = []; $this->dependencyResolve($id, $resolved, $unresolved); return array_keys($resolved); }
{@inheritdoc} @throws RuntimeException If a circular reference is detected.
entailment
public function start() { $this->initialMessage(); $server = new \Yosymfony\HttpServer\HttpServer($this->requestHandler); $server->start(); }
Run the built-in server.
entailment
protected function render($template, $model) { $twig = $this->getTwig(); return $twig->render($template, $model); }
Render a content using Twig template engine. @param string $template The Twig template @param array $model List of key-value properties @return string The redered template
entailment
protected function getTwig() { $options = [ 'cache' => false, 'strict_variables' => true, ]; $loader = new \Twig_Loader_Filesystem(); $loader->setPaths($this->skeletonDirs); return new \Twig_Environment($loader, $options); }
Return an instance of Twig. @return Twig_Environment The Twig instance
entailment
protected function renderFile($template, $target, $model) { if (!is_dir(dirname($target))) { mkdir(dirname($target), 0777, true); } $this->files[] = $target; return file_put_contents($target, $this->render($template, $model)); }
Render a template and result is dumped to a file. @param string $template Path to the template file @param string $target Filename result @param array $model key-value array that acts as model @return int|bool Numer of byte that were written or false if error
entailment
public function getAttributesFromString($value) { if (empty($value) === true) { return []; } $repository = $this->config->load($value, $this->type); return $repository->getArray(); }
Get the attributes of an item from string. @param string $value Attributes represented as string. e.g: JSON or YAML @return array
entailment
public function getAttributesFromFrontmatter($value) { $found = preg_match($this->pattern, $value, $matches); if (1 === $found) { return $this->getAttributesFromString($matches[1]); } return []; }
Get the attributes from the fronmatter of an item. Front-matter block let you specify certain attributes of the page and define new variables that will be available in the content. e.g: (YAML syntax) --- name: "Victor" --- @param string $value Frontmatter @return array Array with two elements: "attributes" and "content"
entailment
public function findCalendar(Query $query, array $options) { $field = $this->getConfig('field'); $year = $options[static::YEAR]; $month = $options[static::MONTH]; $from = new Time($year . '-' . $month . '-01'); $lastDayOfMonth = $from->daysInMonth; $to = new Time($year . '-' . $month . '-' . $lastDayOfMonth . ' 23:59:59'); $conditions = [ $field . ' >=' => $from, $field . ' <=' => $to ]; if ($this->getConfig('endField')) { $endField = $this->getConfig('endField'); $conditions = [ 'OR' => [ [ $field . ' <=' => $to, $endField . ' >' => $from, ], $conditions ] ]; } $query->where($conditions); if ($this->getConfig('scope')) { $query->andWhere($this->getConfig('scope')); } return $query; }
Custom finder for Calendars field. Options: - year (required), best to use CalendarBehavior::YEAR constant - month (required), best to use CalendarBehavior::MONTH constant @param \Cake\ORM\Query $query Query. @param array $options Array of options as described above @return \Cake\ORM\Query
entailment
public function setUp() { if ($this->filesystem->exists($this->outputDir) === false) { return; } $finder = new Finder(); $finder->in($this->outputDir) ->depth('== 0'); $this->filesystem->remove($finder); }
{@inheritdoc} Removes the whole content of the output dir but VCS files.
entailment
public function write(ItemInterface $item) { if ($this->isWritable($item) === false) { return; } if ($item->isBinary() === true) { $sourcePath = $item->getPath(ItemInterface::SNAPSHOT_PATH_SOURCE); $outputPath = $item->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE_AFTER_CONVERT); if (strlen($sourcePath) > 0) { $this->filesystem->copy($sourcePath, $this->composeOutputPath($outputPath)); return; } else { $this->filesystem->dumpFile($this->composeOutputPath($outputPath), $item->getContent()); } } $outputPath = $item->getPath(ItemInterface::SNAPSHOT_PATH_PERMALINK); if (strlen($outputPath) == 0) { return; } $this->filesystem->dumpFile($this->composeOutputPath($outputPath), $item->getContent()); }
{@inheritdoc}
entailment
public function load() { if ($this->fs->exists($this->filename) === false) { return; } try { $data = $this->fs->readFile($this->filename); } catch (\Exception $e) { $message = sprintf('Error loading the site metadata: %s', $e->getMessage()); throw new LoadSiteMetadataException($message, 0, $e, $this->filename); } $this->metadata = json_decode($data, true); if (0 < $errorCode = json_last_error()) { $this->throwInvalidMetadataException($errorCode); } }
{@inheritdoc} @throws LoadSiteMetadataException In case of error loading a site metadata file. @throws InvalidSiteMetadataException In case of invalid site metadata format.
entailment
public function save() { $data = json_encode($this->metadata, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); if ($data === false) { $this->throwInvalidMetadataException(json_last_error()); } try { $this->fs->dumpFile($this->filename, $data); } catch (\Exception $e) { $message = sprintf('Error saving the site metadata: %s', $e->getMessage()); throw new SaveSiteMetadataException($message, 0, $e, $this->filename); } }
{@inheritdoc} @throws SaveMetadataException In case of error saving site metadata in a file @throws InvalidSiteMetadataException In case of invalid site metadata format.
entailment
public function write($messages, $newline = true, $verbosity = self::NORMAL) { $this->io->write($messages, $newline, $verbosity); }
{@inheritdoc}
entailment
public function overwrite($messages, $newline = true, $size = null, $verbosity = self::NORMAL) { $this->io->overwrite($messages, $newline, $verbosity); }
{@inheritdoc} The Composer's verbosity levels match with the Spress's verbosity levels. In this implementation, the param `size` is unused.
entailment
public function askAndValidate($question, $validator, $attempts = false, $default = null) { return $this->io->askAndValidate($question, $validator, $attempts, $default); }
{@inheritdoc}
entailment
public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false) { if (is_array($question)) { $question = implode('', $question); } return $this->io->askChoice( $question, $choices, $default, $attempts, $errorMessage, $multiselect ); }
{@inheritdoc}
entailment
public function parseSite(array $attributes, array $spressAttributes, $draft = false, $safe = false, $timezone = 'UTC') { $this->attributes = $attributes; $this->spressAttributes = $spressAttributes; $this->safe = $safe; $this->timezone = $timezone; $this->processDraft = $draft; $this->reset(); $this->setUp(); $this->initializePlugins(); $this->process(); $this->finish(); return $this->itemCollection->all(); }
Parses a site. @param array $attributes The site attributes @param array $spressAttributes @param bool $draft Include draft posts @param bool $safe True for disabling custom plugins @param string $timezone Sets the time zone. @see http://php.net/manual/en/timezones.php More time zones @return ItemInterface[] Items of the site
entailment
public function setDependencyResolver(DependencyResolver $dependencyResolver) { if ($this->dependencyResolver != null) { throw new \LogicException('There is an instance of DependencyManager class in class ContentManager.'); } $this->dependencyResolver = $dependencyResolver; }
Sets the dependency resolver. @param DependencyResolver $dependencyResolver @throws LogicException If there is a previous instance the dependency resolver.
entailment
public function getOutExtension($extension) { if (isset($this->extensionMap[$extension])) { return $this->extensionMap[$extension]; } return $extension; }
The extension of filename result (without dot). E.g: 'html'. @param string $extension File's extension @return string
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $io->write([ '', $this->getSpressAsciiArt(), '', 'Hola user and welcome!', '', 'More information at <comment>http://spress.yosymfony.com</comment> or <comment>@spress_cms</comment> on Twitter', '', ]); if ($this->isUnstableVersion()) { $io->warning('This is an unstable version'); } $command = $this->getApplication()->find('list'); $arguments = new ArrayInput([ 'command' => 'list', ]); $command->run($arguments, $output); }
{@inheritdoc}
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); if ($this->isInstalledAsPhar() === false) { $io->error('Self-update is available only for PHAR version'); return 1; } $manifest = $this->getManifestFile(); $remoteVersion = $manifest['version']; $localVersion = $this->getApplication()->getVersion(); if ($localVersion === $remoteVersion) { $io->success('Spress is already up to date'); return; } $remoteFilename = $manifest['url']; $localFilename = $_SERVER['argv'][0]; $tempFilename = basename($localFilename, '.phar').'-tmp.phar'; $io->newLine(); $io->write('Downloading Spress...'); $io->newLine(); $this->downloadRemoteFilename($remoteFilename); try { copy($remoteFilename, $tempFilename); chmod($tempFilename, 0777 & ~umask()); $phar = new \Phar($tempFilename); unset($phar); if (@rename($tempFilename, $localFilename) !== true) { $io->error(sprintf('Cannot rename "%s" to "%s" probably because permission denied.', $tempFilename, $localFilename)); return 1; } $io->success(sprintf('Spress updated from %s to %s.', $localVersion, $remoteVersion)); if (isset($manifest['changelog_url']) === true) { $io->write(sprintf('<comment>Go to <info>%s</info> for more details.</comment>', $manifest['changelog_url'])); } } catch (\Exception $e) { if ($e instanceof \UnexpectedValueException === false && $e instanceof \PharException === false) { throw $e; } unlink($tempFilename); $io->error([ sprintf('The download is corrupt (%s).', $e->getMessage()), 'Please re-run the self-update command to try again.', ]); return 1; } }
{@inheritdoc}
entailment
public function addLayout($id, $content, array $attributes = []) { $namespaceLayoutId = $this->getLayoutNameWithNamespace($id); $this->layouts[$namespaceLayoutId] = [$id, $content, $attributes]; }
Adds a new layout. @param string $id The identifier of the layout. e.g: default @param string $content The content of the layout @param array $attributes The attributes of the layout. "layout" attribute has a special meaning.
entailment
public function renderBlocks($id, $content, array $attributes) { try { $this->arrayLoader->setTemplate('@dynamic/content', $content); return $this->twig->render('@dynamic/content', $attributes); } catch (\Twig_Error_Syntax $e) { throw new RenderException('Error during lexing or parsing a template.', $id, $e); } }
Renders the content blocks (layout NOT included). @param string $id The identifier of the item. @param string $content The content. @param array $attributes The attributes for using inside the content. @return string The block rendered. @throws RenderException If an error occurred during rendering the content.
entailment
public function renderPage($id, $content, $layoutName, array $siteAttributes) { if ($this->isLayoutsProcessed === false) { $this->processLayouts(); } if ($layoutName) { $namespaceLayoutId = $this->getLayoutNameWithNamespace($layoutName); if (isset($this->layouts[$namespaceLayoutId]) === false) { throw new AttributeValueException(sprintf('Layout "%s" not found.', $layoutName), 'layout', $id); } if (isset($siteAttributes['page']) === false) { $siteAttributes['page'] = []; } $siteAttributes['page']['content'] = $content; $content = sprintf('{%% extends "%s" %%}', $namespaceLayoutId); } return $this->renderBlocks($id, $content, $siteAttributes); }
Renders a page completely (layout included). The value of param $content will be placed at "page.content" attribute. @param string $id The identifier of the item. @param string $content The page content. @param string $layoutName The layout name. @param array $siteAttributes The attributes for using inside the content. "layout" attribute has a special meaning. @return string The page rendered @throws AttributeValueException If "layout" attribute has an invalid value or layout not found. @throws RenderException If an error occurred during rendering the content.
entailment
public function addTwigFilter($name, callable $filter, array $options = []) { $twigFilter = new \Twig_SimpleFilter($name, $filter, $options); $this->twig->addFilter($twigFilter); }
Adds a new Twig filter. @see http://twig.sensiolabs.org/doc/advanced.html#filters Twig documentation @param string $name Name of filter @param callable $filter Filter implementation @param array $options
entailment
public function addTwigFunction($name, callable $function, array $options = []) { $twigfunction = new \Twig_SimpleFunction($name, $function, $options); $this->twig->addFunction($twigfunction); }
Adds a new Twig function. @see http://twig.sensiolabs.org/doc/advanced.html#functions Twig documentation @param string $name Name of filter @param callable $function Filter implementation @param array $options
entailment
protected function getLayoutAttributeWithNamespace(array $attributes, $contentName) { if (isset($attributes['layout']) === false) { return ''; } if (is_string($attributes['layout']) === false) { throw new AttributeValueException('Invalid value. Expected string.', 'layout', $contentName); } if (strlen($attributes['layout']) == 0) { throw new AttributeValueException('Invalid value. Expected a non-empty string.', 'layout', $contentName); } return $this->getLayoutNameWithNamespace($attributes['layout']); }
Returns the value of layout attribute. @param array $attributes List of attributes @param string $contentName The identifier of the content @return string
entailment
public function getSpress($siteDir = null) { $spress = new Spress(); $spress['spress.config.default_filename'] = __DIR__.'/../../app/config/config.yml'; if (is_null($siteDir) === false) { $spress['spress.config.site_dir'] = $siteDir; } $spress['spress.plugin.classLoader'] = $this->getClassloader(); return $spress; }
Returns an Spress instance with the minimum configuration: - Classloader. - Site directory. @return Spress A Spress instance
entailment
public function registerCommandPlugins() { $spress = $this->getSpress(); try { $pm = $spress['spress.plugin.pluginManager']; $commandBuilder = new ConsoleCommandBuilder($pm); $consoleCommandFromPlugins = $commandBuilder->buildCommands(); foreach ($consoleCommandFromPlugins as $consoleCommand) { $this->add($consoleCommand); } } catch (\Exception $e) { } }
Registers the command plugins present in the current directory.
entailment
public function registerStandardCommands() { $welcomeCommand = new WelcomeCommand(); $this->add($welcomeCommand); $this->add(new NewPluginCommand()); $this->add(new NewPostCommand()); $this->add(new NewSiteCommand()); $this->add(new NewThemeCommand()); $this->add(new SelfUpdateCommand()); $this->add(new SiteBuildCommand()); $this->add(new UpdatePluginCommand()); $this->add(new AddPluginCommand()); $this->add(new RemovePluginCommand()); $this->setDefaultCommand($welcomeCommand->getName()); }
Registers the standard commands of Spress.
entailment
public function addArgument($name, $mode = null, $description = '', $default = null) { if (null === $mode) { $mode = self::OPTIONAL; } elseif (!is_int($mode) || $mode > 7 || $mode < 1) { throw new \InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode)); } $this->arguments[] = [$name, $mode, $description, $default]; }
Adds a new command argument. @param string $name The argument name @param int $mode The argument mode: self::REQUIRED or self::OPTIONAL @param string $description A description text @param mixed $default The default value (for self::OPTIONAL mode only) @throws \InvalidArgumentException When argument mode is not valid
entailment