Tweaked the blank plugin and removed out of date random option

This commit is contained in:
Andy Miller
2016-03-31 18:14:14 -06:00
parent ab23b52416
commit e839fccc2e
14 changed files with 538 additions and 825 deletions

View File

@@ -1,107 +1,107 @@
<?php
namespace Grav\Console\Cli\DevTools;
use Grav\Common\Grav;
use Grav\Common\Data;
use Grav\Common\Filesystem\Folder;
use Grav\Common\GPM\GPM;
use Grav\Common\Inflector;
use Grav\Common\Twig\Twig;
use Grav\Common\Utils;
use RocketTheme\Toolbox\File\File;
use Grav\Console\ConsoleCommand;
/**
* Class DevToolsCommand
* @package Grav\Console\Cli\
*/
class DevToolsCommand extends ConsoleCommand
{
/**
* @var array
*/
protected $component = [];
/**
* @var Grav
*/
protected $grav;
/**
* @var Inflector
*/
protected $inflector;
/**
* @var Locator
*/
protected $locator;
/**
* @var Twig
*/
protected $twig;
protected $data;
/**
* @var gpm
*/
protected $gpm;
/**
* Initializes the basic requirements for the developer tools
*/
protected function init()
{
$autoload = require_once GRAV_ROOT . '/vendor/autoload.php';
if (!function_exists('curl_version')) {
exit('FATAL: DEVTOOLS requires PHP Curl module to be installed');
}
$this->grav = Grav::instance(array('loader' => $autoload));
$this->grav['config']->init();
$this->grav['uri']->init();
$this->grav['streams'];
$this->inflector = $this->grav['inflector'];
$this->locator = $this->grav['locator'];
$this->twig = new Twig($this->grav);
$this->gpm = new GPM(true);
//Add `theme://` to prevent fail
$this->locator->addPath('theme', '', []);
}
/**
* Copies the component type and renames accordingly
*/
protected function createComponent()
{
$name = $this->component['name'];
$folderName = strtolower($this->inflector->hyphenize($name));
$type = $this->component['type'];
$template = $this->component['template'];
$templateFolder = __DIR__ . '/components/' . $type . DS . $template;
$componentFolder = $this->locator->findResource($type . 's://') . DS . $folderName;
//Copy All files to component folder
<?php
namespace Grav\Console\Cli\DevTools;
use Grav\Common\Grav;
use Grav\Common\Data;
use Grav\Common\Filesystem\Folder;
use Grav\Common\GPM\GPM;
use Grav\Common\Inflector;
use Grav\Common\Twig\Twig;
use Grav\Common\Utils;
use RocketTheme\Toolbox\File\File;
use Grav\Console\ConsoleCommand;
/**
* Class DevToolsCommand
* @package Grav\Console\Cli\
*/
class DevToolsCommand extends ConsoleCommand
{
/**
* @var array
*/
protected $component = [];
/**
* @var Grav
*/
protected $grav;
/**
* @var Inflector
*/
protected $inflector;
/**
* @var Locator
*/
protected $locator;
/**
* @var Twig
*/
protected $twig;
protected $data;
/**
* @var gpm
*/
protected $gpm;
/**
* Initializes the basic requirements for the developer tools
*/
protected function init()
{
$autoload = require_once GRAV_ROOT . '/vendor/autoload.php';
if (!function_exists('curl_version')) {
exit('FATAL: DEVTOOLS requires PHP Curl module to be installed');
}
$this->grav = Grav::instance(array('loader' => $autoload));
$this->grav['config']->init();
$this->grav['uri']->init();
$this->grav['streams'];
$this->inflector = $this->grav['inflector'];
$this->locator = $this->grav['locator'];
$this->twig = new Twig($this->grav);
$this->gpm = new GPM(true);
//Add `theme://` to prevent fail
$this->locator->addPath('theme', '', []);
}
/**
* Copies the component type and renames accordingly
*/
protected function createComponent()
{
$name = $this->component['name'];
$folderName = strtolower($this->inflector->hyphenize($name));
$type = $this->component['type'];
$template = $this->component['template'];
$templateFolder = __DIR__ . '/components/' . $type . DS . $template;
$componentFolder = $this->locator->findResource($type . 's://') . DS . $folderName;
//Copy All files to component folder
try {
Folder::copy($templateFolder, $componentFolder);
} catch (\Exception $e) {
$this->output->writeln("<red>" . $e->getMessage() . "</red>");
return false;
}
//Add Twig vars and templates then initialize
$this->twig->twig_vars['component'] = $this->component;
$this->twig->twig_paths[] = $templateFolder;
$this->twig->init();
//Get all templates of component then process each with twig and save
$templates = Folder::all($componentFolder);
//Add Twig vars and templates then initialize
$this->twig->twig_vars['component'] = $this->component;
$this->twig->twig_paths[] = $templateFolder;
$this->twig->init();
//Get all templates of component then process each with twig and save
$templates = Folder::all($componentFolder);
try {
foreach($templates as $templateFile) {
@@ -115,76 +115,78 @@ class DevToolsCommand extends ConsoleCommand
$file = File::instance($componentFolder . DS . $templateFile);
$file->delete();
}
}
}
} catch (\Exception $e) {
$this->output->writeln("<red>" . $e->getMessage() . "</red>");
$this->output->writeln("Rolling back...");
Folder::delete($componentFolder);
$this->output->writeln($type . "creation failed!");
return false;
}
rename($componentFolder . DS . $type . '.php', $componentFolder . DS . $this->inflector->hyphenize($name) . '.php');
rename($componentFolder . DS . $type . '.yaml', $componentFolder . DS . $this->inflector->hyphenize($name) . '.yaml');
}
rename($componentFolder . DS . $type . '.php', $componentFolder . DS . $this->inflector->hyphenize($name) . '.php');
rename($componentFolder . DS . $type . '.yaml', $componentFolder . DS . $this->inflector->hyphenize($name) . '.yaml');
$this->output->writeln('');
$this->output->writeln('<green>SUCCESS</green> ' . $type . ' <magenta>' . $name . '</magenta> -> Created Successfully');
$this->output->writeln('');
$this->output->writeln('Path: <cyan>' . $componentFolder . '</cyan>');
$this->output->writeln('');
}
/**
* Iterate through all options and validate
*/
protected function validateOptions()
{
foreach (array_filter($this->options) as $type => $value) {
$this->validate($type, $value);
}
}
/**
* @param $type
* @param $value
* @param string $extra
*
* @return mixed
*/
protected function validate($type, $value, $extra = '')
{
switch ($type) {
case 'name':
//Check If name
if ($value == null || trim($value) == '') {
throw new \RuntimeException('Name cannot be empty');
}
if (false != $this->gpm->findPackage($value)) {
throw new \RuntimeException('Package name exists in GPM');
}
break;
case 'description':
if($value == null || trim($value) == '') {
throw new \RuntimeException('Description cannot be empty');
}
break;
case 'developer':
if ($value === null || trim($value) == '') {
throw new \RuntimeException('Developer\'s Name cannot be empty');
}
break;
case 'email':
if (!preg_match('/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/', $value)) {
throw new \RuntimeException('Not a valid email address');
}
break;
}
return $value;
}
}
}
/**
* Iterate through all options and validate
*/
protected function validateOptions()
{
foreach (array_filter($this->options) as $type => $value) {
$this->validate($type, $value);
}
}
/**
* @param $type
* @param $value
* @param string $extra
*
* @return mixed
*/
protected function validate($type, $value, $extra = '')
{
switch ($type) {
case 'name':
//Check If name
if ($value == null || trim($value) == '') {
throw new \RuntimeException('Name cannot be empty');
}
if (false != $this->gpm->findPackage($value)) {
throw new \RuntimeException('Package name exists in GPM');
}
break;
case 'description':
if($value == null || trim($value) == '') {
throw new \RuntimeException('Description cannot be empty');
}
break;
case 'developer':
if ($value === null || trim($value) == '') {
throw new \RuntimeException('Developer\'s Name cannot be empty');
}
break;
case 'email':
if (!preg_match('/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/', $value)) {
throw new \RuntimeException('Not a valid email address');
}
break;
}
return $value;
}
}

View File

@@ -1,135 +1,129 @@
<?php
namespace Grav\Console\Cli\DevTools;
use Grav\Common\Inflector;
use Grav\Console\ConsoleCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
/**
* Class NewPluginCommand
* @package Grav\Console\Cli\DevTools
*/
class NewPluginCommand extends DevToolsCommand
{
/**
* @var array
*/
protected $options = [];
/**
*
*/
protected function configure()
{
$this
->setName('new-plugin')
->setAliases(['newplugin'])
->addOption(
'name',
'pn',
InputOption::VALUE_OPTIONAL,
'The name of your new Grav plugin'
)
->addOption(
'description',
'd',
InputOption::VALUE_OPTIONAL,
'A description of your new Grav plugin'
)
->addOption(
'developer',
'dv',
InputOption::VALUE_OPTIONAL,
'The name/username of the developer'
)
->addOption(
'email',
'e',
InputOption::VALUE_OPTIONAL,
'The developer\'s email'
)
->setDescription('Creates a new Grav plugin with the basic required files')
->setHelp('The <info>new-plugin</info> command creates a new Grav instance and performs the creation of a plugin.');
}
/**
* @return int|null|void
*/
protected function serve()
{
$this->init();
/**
* @var array DevToolsCommand $component
*/
$this->component['type'] = 'plugin';
$this->component['template'] = 'blank';
$this->component['version'] = '0.1.0'; // @todo add optional non prompting version argument
$this->options = [
'name' => $this->input->getOption('name'),
'description' => $this->input->getOption('description'),
'author' => [
'name' => $this->input->getOption('developer'),
'email' => $this->input->getOption('email')
]
];
$this->validateOptions();
$this->component = array_replace($this->component, $this->options);
$helper = $this->getHelper('question');
if (!$this->options['name']) {
$question = new Question('Enter <yellow>Plugin Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('name', $value);
});
$this->component['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['description']) {
$question = new Question('Enter <yellow>Plugin Description</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('description', $value);
});
$this->component['description'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['name']) {
$question = new Question('Enter <yellow>Developer Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('developer', $value);
});
$this->component['author']['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['email']) {
$question = new Question('Enter <yellow>Developer Email</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('email', $value);
});
$this->component['author']['email'] = $helper->ask($this->input, $this->output, $question);
}
$question = new ChoiceQuestion(
'Please choose a base plugin: ',
array('blank', 'random')
);
$this->component['template'] = $helper->ask($this->input, $this->output, $question);
$this->createComponent();
}
}
<?php
namespace Grav\Console\Cli\DevTools;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
/**
* Class NewPluginCommand
* @package Grav\Console\Cli\DevTools
*/
class NewPluginCommand extends DevToolsCommand
{
/**
* @var array
*/
protected $options = [];
/**
*
*/
protected function configure()
{
$this
->setName('new-plugin')
->setAliases(['newplugin'])
->addOption(
'name',
'pn',
InputOption::VALUE_OPTIONAL,
'The name of your new Grav plugin'
)
->addOption(
'description',
'd',
InputOption::VALUE_OPTIONAL,
'A description of your new Grav plugin'
)
->addOption(
'developer',
'dv',
InputOption::VALUE_OPTIONAL,
'The name/username of the developer'
)
->addOption(
'email',
'e',
InputOption::VALUE_OPTIONAL,
'The developer\'s email'
)
->setDescription('Creates a new Grav plugin with the basic required files')
->setHelp('The <info>new-plugin</info> command creates a new Grav instance and performs the creation of a plugin.');
}
/**
* @return int|null|void
*/
protected function serve()
{
$this->init();
/**
* @var array DevToolsCommand $component
*/
$this->component['type'] = 'plugin';
$this->component['template'] = 'blank';
$this->component['version'] = '0.1.0'; // @todo add optional non prompting version argument
$this->options = [
'name' => $this->input->getOption('name'),
'description' => $this->input->getOption('description'),
'author' => [
'name' => $this->input->getOption('developer'),
'email' => $this->input->getOption('email')
]
];
$this->validateOptions();
$this->component = array_replace($this->component, $this->options);
$helper = $this->getHelper('question');
if (!$this->options['name']) {
$question = new Question('Enter <yellow>Plugin Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('name', $value);
});
$this->component['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['description']) {
$question = new Question('Enter <yellow>Plugin Description</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('description', $value);
});
$this->component['description'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['name']) {
$question = new Question('Enter <yellow>Developer Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('developer', $value);
});
$this->component['author']['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['email']) {
$question = new Question('Enter <yellow>Developer Email</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('email', $value);
});
$this->component['author']['email'] = $helper->ask($this->input, $this->output, $question);
}
$this->component['template'] = 'blank';
$this->createComponent();
}
}

View File

@@ -1,147 +1,145 @@
<?php
namespace Grav\Console\Cli\DevTools;
use Grav\Common\Inflector;
use Grav\Console\ConsoleCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
/**
* Class NewThemeCommand
* @package Grav\Console\Cli\DevTools
*/
class NewThemeCommand extends DevToolsCommand
{
/**
* @var array
*/
protected $options = [];
/**
*
*/
protected function configure()
{
$this
->setName('new-theme')
->setAliases(['newtheme'])
->addOption(
'name',
'pn',
InputOption::VALUE_OPTIONAL,
'The name of your new Grav theme'
)
->addOption(
'description',
'd',
InputOption::VALUE_OPTIONAL,
'A description of your new Grav theme'
)
->addOption(
'developer',
'dv',
InputOption::VALUE_OPTIONAL,
'The name/username of the developer'
)
->addOption(
'email',
'e',
InputOption::VALUE_OPTIONAL,
'The developer\'s email'
)
->setDescription('Creates a new Grav theme with the basic required files')
->setHelp('The <info>new-theme</info> command creates a new Grav instance and performs the creation of a theme.');
}
/**
* @return int|null|void
*/
protected function serve()
{
$this->init();
/**
* @var array DevToolsCommand $component
*/
$this->component['type'] = 'theme';
$this->component['template'] = 'blank';
$this->component['version'] = '0.1.0'; // @todo add optional non prompting version argument
$this->options = [
'name' => $this->input->getOption('name'),
'description' => $this->input->getOption('description'),
'author' => [
'name' => $this->input->getOption('developer'),
'email' => $this->input->getOption('email')
]
];
$this->validateOptions();
$this->component = array_replace($this->component, $this->options);
$helper = $this->getHelper('question');
if (!$this->options['name']) {
$question = new Question('Enter <yellow>Theme Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('name', $value);
});
$this->component['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['description']) {
$question = new Question('Enter <yellow>Theme Description</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('description', $value);
});
$this->component['description'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['name']) {
$question = new Question('Enter <yellow>Developer Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('developer', $value);
});
$this->component['author']['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['email']) {
$question = new Question('Enter <yellow>Developer Email</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('email', $value);
});
$this->component['author']['email'] = $helper->ask($this->input, $this->output, $question);
}
$question = new ChoiceQuestion(
'Please choose a template type',
array('bootstrap', 'inheritence')
);
$this->component['template'] = $helper->ask($this->input, $this->output, $question);
if ($this->component['template'] == 'inheritence') {
$themes = $this->gpm->getInstalledThemes();
$installedThemes = [];
foreach($themes as $key => $theme) {
array_push($installedThemes, $key);
}
$question = new ChoiceQuestion(
'Please choose a theme to extend: ',
$installedThemes
);
$this->component['extends'] = $helper->ask($this->input, $this->output, $question);
}
$this->createComponent();
}
}
<?php
namespace Grav\Console\Cli\DevTools;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
/**
* Class NewThemeCommand
* @package Grav\Console\Cli\DevTools
*/
class NewThemeCommand extends DevToolsCommand
{
/**
* @var array
*/
protected $options = [];
/**
*
*/
protected function configure()
{
$this
->setName('new-theme')
->setAliases(['newtheme'])
->addOption(
'name',
'pn',
InputOption::VALUE_OPTIONAL,
'The name of your new Grav theme'
)
->addOption(
'description',
'd',
InputOption::VALUE_OPTIONAL,
'A description of your new Grav theme'
)
->addOption(
'developer',
'dv',
InputOption::VALUE_OPTIONAL,
'The name/username of the developer'
)
->addOption(
'email',
'e',
InputOption::VALUE_OPTIONAL,
'The developer\'s email'
)
->setDescription('Creates a new Grav theme with the basic required files')
->setHelp('The <info>new-theme</info> command creates a new Grav instance and performs the creation of a theme.');
}
/**
* @return int|null|void
*/
protected function serve()
{
$this->init();
/**
* @var array DevToolsCommand $component
*/
$this->component['type'] = 'theme';
$this->component['template'] = 'blank';
$this->component['version'] = '0.1.0'; // @todo add optional non prompting version argument
$this->options = [
'name' => $this->input->getOption('name'),
'description' => $this->input->getOption('description'),
'author' => [
'name' => $this->input->getOption('developer'),
'email' => $this->input->getOption('email')
]
];
$this->validateOptions();
$this->component = array_replace($this->component, $this->options);
$helper = $this->getHelper('question');
if (!$this->options['name']) {
$question = new Question('Enter <yellow>Theme Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('name', $value);
});
$this->component['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['description']) {
$question = new Question('Enter <yellow>Theme Description</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('description', $value);
});
$this->component['description'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['name']) {
$question = new Question('Enter <yellow>Developer Name</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('developer', $value);
});
$this->component['author']['name'] = $helper->ask($this->input, $this->output, $question);
}
if (!$this->options['author']['email']) {
$question = new Question('Enter <yellow>Developer Email</yellow>: ');
$question->setValidator(function ($value) {
return $this->validate('email', $value);
});
$this->component['author']['email'] = $helper->ask($this->input, $this->output, $question);
}
$question = new ChoiceQuestion(
'Please choose a template type',
array('bootstrap', 'inheritence')
);
$this->component['template'] = $helper->ask($this->input, $this->output, $question);
if ($this->component['template'] == 'inheritence') {
$themes = $this->gpm->getInstalledThemes();
$installedThemes = [];
foreach($themes as $key => $theme) {
array_push($installedThemes, $key);
}
$question = new ChoiceQuestion(
'Please choose a theme to extend: ',
$installedThemes
);
$this->component['extends'] = $helper->ask($this->input, $this->output, $question);
}
$this->createComponent();
}
}

View File

@@ -1,5 +1,7 @@
# {{ component.name|titleize }}
The **{{ component.name|titleize }}** Plugin is for [Grav](http://github.com/getgrav/grav)
{{ component.description }}
# {{ component.name|titleize }} Plugin
The **{{ component.name|titleize }}** Plugin is for [Grav CMS](http://github.com/getgrav/grav). This README.md file should be modified to describe the features, installation, configuration, and general usage of this plugin.
## Description
{{ component.description }}

View File

@@ -1,23 +1,31 @@
name: {{ component.name|titleize }}
version: 0.1.0
description: {{ component.description }}
icon: sign-in
author:
name: {{ component.author.name }}
email: {{ component.author.email }}
license: MIT
form:
validation: strict
fields:
enabled:
type: toggle
label: Plugin status
highlight: 1
default: 0
options:
1: Enabled
0: Disabled
validate:
type: bool
name: {{ component.name|titleize }}
version: 0.1.0
description: {{ component.description }}
icon: plug
author:
name: {{ component.author.name }}
email: {{ component.author.email }}
homepage: https://github.com/{{ component.author.name|hyphenize }}/grav-plugin-{{ component.name|hyphenize }}
demo: http://demo.yoursite.com
keywords: grav, plugin, etc
bugs: https://github.com/{{ component.author.name|hyphenize }}/grav-plugin-{{ component.name|hyphenize }}/issues
readme: https://github.com/{{ component.author.name|hyphenize }}/grav-plugin-{{ component.name|hyphenize }}/blob/develop/README.md
license: MIT
form:
validation: strict
fields:
enabled:
type: toggle
label: Plugin status
highlight: 1
default: 0
options:
1: Enabled
0: Disabled
validate:
type: bool
text_var:
type: text
label: Text Variable
help: Text to add to the top of a page

View File

@@ -1,90 +1,61 @@
<?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
/**
* Class {{ component.name|camelize }}Plugin
* @package Grav\Plugin
*/
class {{ component.name|camelize }}Plugin extends Plugin
{
/**
* @var bool
*
* Often used to preven unecessary code from running if
* certain criteria are not met (such as a matching
* URI).
*/
protected $active = false;
/**
* @return array
*
* The getSubscribedEvents() gives the core a list of events
* that the plugin wants to listen to. The key of each
* array section is the event that the plugin listens to
* and the value (in the form of an array) contains the
* callable (or function) as well as the priority. The
* higher the number the higher the priority.
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0]
];
}
/**
* Initialize the plugin
*/
public function onPluginsInitialized()
{
if ($this->grav['config']->get('plugins.{{ component.name|hyphenize }}.enabled')) { // Check if enabled in configuration.
$this->active = true; // Set's the plugin state to active.
$this->enable([
'onPageInitialized' => ['onPageInitialized', 0] // Adds the onPageInitialized event listener
]);
}
}
/**
* Does something with pages
*/
public function onPageInitialized()
{
// Exit the function if plugin is not active
if (!$this->active){
return;
}
// Do things with the page
$somevariable = $this->returnTrue(); // Call a protected function and set a variable to it's value
$this->doSomeProcesses(); // Call a protected function that runs some processes
}
protected function returnTrue()
{
return true;
}
protected function doSomeProcesses()
{
// Generate a random 10 letter string
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz";
$charArray = str_split($chars);
for($i = 0; $i < 10; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
// Do some math
$two = 8*4;
$twentyone = 7*3; // anyone up for poker?
}
}
<?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
use RocketTheme\Toolbox\Event\Event;
/**
* Class {{ component.name|camelize }}Plugin
* @package Grav\Plugin
*/
class {{ component.name|camelize }}Plugin extends Plugin
{
/**
* @return array
*
* The getSubscribedEvents() gives the core a list of events
* that the plugin wants to listen to. The key of each
* array section is the event that the plugin listens to
* and the value (in the form of an array) contains the
* callable (or function) as well as the priority. The
* higher the number the higher the priority.
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0]
];
}
/**
* Initialize the plugin
*/
public function onPluginsInitialized()
{
// Don't proceed if we are in the admin plugin
if ($this->isAdmin()) {
return;
}
// Enable the main event we are interested in
$this->enable([
'onPageContentRaw' => ['onPageContentRaw', 0]
]);
}
/**
* Do some work for this event, full details of events can be found
* on the learn site: http://learn.getgrav.org/plugins/event-hooks
*/
public function onPageContentRaw(Event $e)
{
// Get a variable from the plugin configuration
$text = $this->grav['config']->get('plugins.{{ component.name|hyphenize }}.text_var');
// Get the current raw content
$content = $e['page']->getRawContent();
// Prepend the output with the custom text and set back on the page
$e['page']->setRawContent($text . "\n\n" . $content);
}
}

View File

@@ -1 +1,2 @@
enabled: true
enabled: true
text_var: Custom Text from **{{ component.name|titleize }}**

View File

@@ -1,5 +0,0 @@
# v0.1.0
## {{ "now"|date("m/d/Y") }}
1. [](#new)
* ChangeLog started...

View File

@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) {{ "now"|date("Y") }} {{ component.author.name }}
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,100 +0,0 @@
# Grav {{ component.name|camelize }} Plugin
`{{ component.name|camelize }}` is a [Grav][grav] Plugin which allows a random article to load based on its taxonomy filters.
# Installation
Installing the Random plugin can be done in one of two ways. Our GPM (Grav Package Manager) installation method enables you to quickly and easily install the plugin with a simple terminal command, while the manual method enables you to do so via a zip file.
## GPM Installation (Preferred)
The simplest way to install this plugin is via the [Grav Package Manager (GPM)](http://learn.getgrav.org/advanced/grav-gpm) through your system's Terminal (also called the command line). From the root of your Grav install type:
bin/gpm install random
This will install the Random plugin into your `/user/plugins` directory within Grav. Its files can be found under `/your/site/grav/user/plugins/random`.
## Manual Installation
To install this plugin, just download the zip version of this repository and unzip it under `/your/site/grav/user/plugins`. Then, rename the folder to `random`. You can find these files either on [GitHub](https://github.com/getgrav/grav-plugin-random) or via [GetGrav.org](http://getgrav.org/downloads/plugins#extras).
You should now have all the plugin files under
/your/site/grav/user/plugins/random
>> NOTE: This plugin is a modular component for Grav which requires [Grav](http://github.com/getgrav/grav), the [Error](https://github.com/getgrav/grav-plugin-error) and [Problems](https://github.com/getgrav/grav-plugin-problems) plugins, and a theme to be installed in order to operate.
# Usage
`Random` creates a **route** that you define. Based on the **taxonomy** filters, it picks a random item.
By default `Random` looks for all page that are have taxonomy that match those in the plugin's `filter` settings. For this content to find _anything_ you need to define at
least one page with a matching taxonomy. As the default value of the filter is `category: blog` you must have at least one page with this taxonomy. For example:
---
title: Home
taxonomy:
category: blog
---
# Grav is Running!
## You have installed **Grav** successfully
Congratulations! You have installed the **Base Grav Package** that provides a **simple page** and the default **antimatter** theme to get you started.
# Settings Defaults
route: /random
filters:
category: blog
# Customizing the Settings
To customize the plugin, you first need to create an override config. To do so, create the folder `user/config/plugins` (if it doesn't exist already) and copy the [random.yaml](random.yaml) config file in there.
Now you can edit it and tweak it however you prefer.
For further help with the `filters` settings, please refer to our [Taxonomy][taxonomy] and [Headers][headers] documentation.
# Creating a "Random Article" Button
![Random](assets/readme_1.png)
In our [Blog Skeleton](http://demo.getgrav.org/blog-skeleton/) we placed a button in the sidebar that pulls up a random blog post. Here is the code we used in the `sidebar.html.twig` template file to create this button.
<a class="button" href="{{ base_url_relative }}/random"><i class="fa fa-retweet"></i> I'm Feeling Lucky!</a>
This button forwards the user to `/random` which is configured as the route for the random plugin. The `random.yaml` configuration file contains the following:
enabled: true
route: /random
filters: { category: blog}
filter_combinator: and
# Updating
As development for the Random plugin continues, new versions may become available that add additional features and functionality, improve compatibility with newer Grav releases, and generally provide a better user experience. Updating Random is easy, and can be done through Grav's GPM system, as well as manually.
## GPM Update (Preferred)
The simplest way to update this plugin is via the [Grav Package Manager (GPM)](http://learn.getgrav.org/advanced/grav-gpm). You can do this with this by navigating to the root directory of your Grav install using your system's Terminal (also called command line) and typing the following:
bin/gpm update random
This command will check your Grav install to see if your Random plugin is due for an update. If a newer release is found, you will be asked whether or not you wish to update. To continue, type `y` and hit enter. The plugin will automatically update and clear Grav's cache.
## Manual Update
Manually updating Random is pretty simple. Here is what you will need to do to get this done:
* Delete the `your/site/user/plugins/random` directory.
* Download the new version of the Random plugin from either [GitHub](https://github.com/getgrav/grav-plugin-random) or [GetGrav.org](http://getgrav.org/downloads/plugins#extras).
* Unzip the zip file in `your/site/user/plugins` and rename the resulting folder to `random`.
* Clear the Grav cache. The simplest way to do this is by going to the root Grav directory in terminal and typing `bin/grav clear-cache`.
> Note: Any changes you have made to any of the files listed under this directory will also be removed and replaced by the new set. Any files located elsewhere (for example a YAML settings file placed in `user/config/plugins`) will remain intact.
[taxonomy]: http://learn.getgrav.org/content/taxonomy
[headers]: http://learn.getgrav.org/content/headers
[grav]: http://github.com/getgrav/grav

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

View File

@@ -1,57 +0,0 @@
name: {{ component.name|titleize }}
version: 0.1.0
description: {{ component.description }}
icon: refresh
author:
name: {{ component.author.name }}
email: {{ component.author.email }}
license: MIT
form:
validation: strict
fields:
enabled:
type: toggle
label: Plugin status
highlight: 1
default: 0
options:
1: Enabled
0: Disabled
validate:
type: bool
route:
type: text
size: medium
label: Route
default: /random
help: Default route of the random plugin
redirect:
type: toggle
label: Redirect
highlight: 1
default: 1
options:
1: Enabled
0: Disabled
validate:
type: bool
filters.category:
type: selectize
label: Category filter
help: Comma separated list of category names
validate:
type: commalist
filter_combinator:
type: select
size: medium
classes: fancy
label: Filter Combinator
default: and
options:
and: And - Boolean &&
or: Or - Boolean ||

View File

@@ -1,75 +0,0 @@
<?php
namespace Grav\Plugin;
use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Uri;
use Grav\Common\Taxonomy;
class {{ component.name|camelize }}Plugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0],
];
}
/**
* Activate plugin if path matches to the configured one.
*/
public function onPluginsInitialized()
{
if ($this->isAdmin()) {
$this->active = false;
return;
}
/** @var Uri $uri */
$uri = $this->grav['uri'];
$route = $this->config->get('plugins.{{ component.name|hyphenize }}.route');
if ($route && $route == $uri->path()) {
$this->enable([
'onPageInitialized' => ['onPageInitialized', 0]
]);
}
}
/**
* Display random page.
*/
public function onPageInitialized()
{
/** @var Taxonomy $taxonomy_map */
$taxonomy_map = $this->grav['taxonomy'];
$filters = (array) $this->config->get('plugins.{{ component.name|hyphenize }}.filters');
$operator = $this->config->get('plugins.{{ component.name|hyphenize }}.filter_combinator', 'and');
if (count($filters)) {
$collection = new Collection();
$collection->append($taxonomy_map->findTaxonomy($filters, $operator)->toArray());
if (count($collection)) {
unset($this->grav['page']);
$page = $collection->random()->current();
if ($this->config->get('plugins.{{ component.name|hyphenize }}.redirect', true)) {
$this->grav->redirect($page->url(true));
} else {
// override the modified time
$page->modified(time());
$this->grav['page'] = $page;
// Convince the URI object that it is this random page...
$uri = $this->grav['uri'];
$uri->url = $uri->base().$page->url();
$uri->init();
}
}
}
}
}

View File

@@ -1,5 +0,0 @@
enabled: true
route: /random
redirect: true
filters: { category: blog}
filter_combinator: and