added example for developpers module

This commit is contained in:
Bachir Soussi Chiadmi
2018-01-06 11:28:03 +01:00
parent 5017966908
commit 5ec2f4311c
396 changed files with 26299 additions and 0 deletions
@@ -0,0 +1,4 @@
# Default form values for \Drupal\cron_example\Form\CronExampleForm.
# @see examples/cron_example/config/schema/cron_example.schema.yml
# @see \Drupal\cron_example\Form\CronExampleForm::getEditableConfigNames()
interval: 300
@@ -0,0 +1,12 @@
# Set configuration defaults. This schema describes the cron_example.settings
# config. The defaults for this config are set in
# config/install/cron_example.settings.yml and then used by
# \Drupal\cron_example\Form\CronExampleForm.
# @see https://www.drupal.org/node/1905070
cron_example.settings:
type: config_object
label: 'Cron Example settings'
mapping:
interval:
type: integer
label: 'Period between cron runs'
@@ -0,0 +1,14 @@
name: Cron Example
type: module
description: 'Demonstrates hook_cron() and related features'
package: Example modules
# core: 8.x
dependencies:
- drupal:node
- examples:examples
# Information added by Drupal.org packaging script on 2017-12-17
version: '8.x-1.x-dev'
core: '8.x'
project: 'examples'
datestamp: 1513537386
@@ -0,0 +1,3 @@
cron_example.description:
title: Cron Example
route_name: cron_example
@@ -0,0 +1,56 @@
<?php
/**
* @file
* Demonstrates use of the Cron API in Drupal - hook_cron().
*/
/**
* @defgroup cron_example Example: Cron
* @ingroup examples
* @{
* Example using Cron API, including hook_cron() and @QueueWorker plugins
*
* This example is part of the Examples for Developers Project
* which you can download and experiment with at
* http://drupal.org/project/examples
*/
/**
* Implements hook_cron().
*
* We implement hook_cron() to do "background" processing. It gets called every
* time the Drupal cron runs. We then decide what has to happen in response.
*
* In this example, we log a message after the time given in the state value
* 'cron_example.next_execution'. Then we update that variable to a time in the
* future.
*/
function cron_example_cron() {
// We access our configuration.
$cron_config = \Drupal::configFactory()->getEditable('cron_example.settings');
// Default to an hourly interval. Of course, cron has to be running at least
// hourly for this to work.
$interval = $cron_config->get('interval');
$interval = !empty($interval) ? $interval : 3600;
// We usually don't want to act every time cron runs (which could be every
// minute) so keep a time for the next run in the site state.
$next_execution = \Drupal::state()->get('cron_example.next_execution');
$next_execution = !empty($next_execution) ? $next_execution : 0;
if (REQUEST_TIME >= $next_execution) {
// This is a silly example of a cron job.
// It just makes it obvious that the job has run without
// making any changes to your database.
\Drupal::logger('cron_example')->notice('cron_example ran');
if (\Drupal::state()->get('cron_example_show_status_message')) {
drupal_set_message(t('cron_example executed at %time', ['%time' => date_iso8601(REQUEST_TIME)]));
\Drupal::state()->set('cron_example_show_status_message', FALSE);
}
\Drupal::state()->set('cron_example.next_execution', REQUEST_TIME + $interval);
}
}
/**
* @} End of "defgroup cron_example".
*/
@@ -0,0 +1,7 @@
cron_example:
path: '/examples/cron-example'
defaults:
_form: '\Drupal\cron_example\Form\CronExampleForm'
_title: 'Cron Example'
requirements:
_permission: 'access content'
@@ -0,0 +1,256 @@
<?php
namespace Drupal\cron_example\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\CronInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Queue\QueueFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\State\StateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Form with examples on how to use cron.
*/
class CronExampleForm extends ConfigFormBase {
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The cron service.
*
* @var \Drupal\Core\CronInterface
*/
protected $cron;
/**
* The queue object.
*
* @var \Drupal\Core\Queue\QueueFactory
*/
protected $queue;
/**
* The state keyvalue collection.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* {@inheritdoc}
*/
public function __construct(ConfigFactoryInterface $config_factory, AccountInterface $current_user, CronInterface $cron, QueueFactory $queue, StateInterface $state) {
parent::__construct($config_factory);
$this->currentUser = $current_user;
$this->cron = $cron;
$this->queue = $queue;
$this->state = $state;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('current_user'),
$container->get('cron'),
$container->get('queue'),
$container->get('state')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'cron_example';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->configFactory->get('cron_example.settings');
$form['status'] = [
'#type' => 'details',
'#title' => $this->t('Cron status information'),
'#open' => TRUE,
];
$form['status']['intro'] = [
'#type' => 'item',
'#markup' => $this->t('The cron example demonstrates hook_cron() and hook_queue_info() processing. If you have administrative privileges you can run cron from this page and see the results.'),
];
$next_execution = \Drupal::state()->get('cron_example.next_execution');
$next_execution = !empty($next_execution) ? $next_execution : REQUEST_TIME;
$args = [
'%time' => date_iso8601(\Drupal::state()->get('cron_example.next_execution')),
'%seconds' => $next_execution - REQUEST_TIME,
];
$form['status']['last'] = [
'#type' => 'item',
'#markup' => $this->t('cron_example_cron() will next execute the first time cron runs after %time (%seconds seconds from now)', $args),
];
if ($this->currentUser->hasPermission('administer site configuration')) {
$form['cron_run'] = [
'#type' => 'details',
'#title' => $this->t('Run cron manually'),
'#open' => TRUE,
];
$form['cron_run']['cron_reset'] = [
'#type' => 'checkbox',
'#title' => $this->t("Run cron_example's cron regardless of whether interval has expired."),
'#default_value' => FALSE,
];
$form['cron_run']['cron_trigger']['actions'] = ['#type' => 'actions'];
$form['cron_run']['cron_trigger']['actions']['sumbit'] = [
'#type' => 'submit',
'#value' => $this->t('Run cron now'),
'#submit' => [[$this, 'cronRun']],
];
}
$form['cron_queue_setup'] = [
'#type' => 'details',
'#title' => $this->t('Cron queue setup (for hook_cron_queue_info(), etc.)'),
'#open' => TRUE,
];
$queue_1 = $this->queue->get('cron_example_queue_1');
$queue_2 = $this->queue->get('cron_example_queue_2');
$args = [
'%queue_1' => $queue_1->numberOfItems(),
'%queue_2' => $queue_2->numberOfItems(),
];
$form['cron_queue_setup']['current_cron_queue_status'] = [
'#type' => 'item',
'#markup' => $this->t('There are currently %queue_1 items in queue 1 and %queue_2 items in queue 2', $args),
];
$form['cron_queue_setup']['num_items'] = [
'#type' => 'select',
'#title' => $this->t('Number of items to add to queue'),
'#options' => array_combine([1, 5, 10, 100, 1000], [1, 5, 10, 100, 1000]),
'#default_value' => 5,
];
$form['cron_queue_setup']['queue'] = [
'#type' => 'radios',
'#title' => $this->t('Queue to add items to'),
'#options' => [
'cron_example_queue_1' => $this->t('Queue 1'),
'cron_example_queue_2' => $this->t('Queue 2'),
],
'#default_value' => 'cron_example_queue_1',
];
$form['cron_queue_setup']['actions'] = ['#type' => 'actions'];
$form['cron_queue_setup']['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Add jobs to queue'),
'#submit' => [[$this, 'addItems']],
];
$form['configuration'] = [
'#type' => 'details',
'#title' => $this->t('Configuration of cron_example_cron()'),
'#open' => TRUE,
];
$form['configuration']['cron_example_interval'] = [
'#type' => 'select',
'#title' => $this->t('Cron interval'),
'#description' => $this->t('Time after which cron_example_cron will respond to a processing request.'),
'#default_value' => $config->get('interval'),
'#options' => [
60 => $this->t('1 minute'),
300 => $this->t('5 minutes'),
3600 => $this->t('1 hour'),
86400 => $this->t('1 day'),
],
];
return parent::buildForm($form, $form_state);
}
/**
* Allow user to directly execute cron, optionally forcing it.
*/
public function cronRun(array &$form, FormStateInterface &$form_state) {
$config = $this->configFactory->getEditable('cron_example.settings');
$cron_reset = $form_state->getValue('cron_reset');
if (!empty($cron_reset)) {
\Drupal::state()->set('cron_example.next_execution', 0);
}
// Use a state variable to signal that cron was run manually from this form.
$this->state->set('cron_example_show_status_message', TRUE);
if ($this->cron->run()) {
drupal_set_message($this->t('Cron ran successfully.'));
}
else {
drupal_set_message($this->t('Cron run failed.'), 'error');
}
}
/**
* Add the items to the queue when signaled by the form.
*/
public function addItems(array &$form, FormStateInterface &$form_state) {
$values = $form_state->getValues();
$queue_name = $form['cron_queue_setup']['queue'][$values['queue']]['#title'];
$num_items = $form_state->getValue('num_items');
// Queues are defined by a QueueWorker Plugin which are selected by their
// id attritbute.
// @see \Drupal\cron_example\Plugin\QueueWorker\ReportWorkerOne
$queue = $this->queue->get($values['queue']);
for ($i = 1; $i <= $num_items; $i++) {
// Create a new item, a new data object, which is passed to the
// QueueWorker's processItem() method.
$item = new \stdClass();
$item->created = REQUEST_TIME;
$item->sequence = $i;
$queue->createItem($item);
}
$args = [
'%num' => $num_items,
'%queue' => $queue_name,
];
drupal_set_message($this->t('Added %num items to %queue', $args));
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Update the interval as stored in configuration. This will be read when
// this modules hook_cron function fires and will be used to ensure that
// action is taken only after the appropiate time has elapsed.
$this->configFactory->getEditable('cron_example.settings')
->set('interval', $form_state->getValue('cron_example_interval'))
->save();
parent::submitForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['cron_example.settings'];
}
}
@@ -0,0 +1,92 @@
<?php
namespace Drupal\cron_example\Plugin\QueueWorker;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
/**
* Provides base functionality for the ReportWorkers.
*/
abstract class ReportWorkerBase extends QueueWorkerBase implements ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* The state.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* The logger.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* ReportWorkerBase constructor.
*
* @param array $configuration
* The configuration of the instance.
* @param string $plugin_id
* The plugin id.
* @param mixed $plugin_definition
* The plugin definition.
* @param \Drupal\Core\State\StateInterface $state
* The state service the instance should use.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger
* The logger service the instance should use.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, StateInterface $state, LoggerChannelFactoryInterface $logger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->state = $state;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('state'),
$container->get('logger.factory')
);
}
/**
* Simple reporter log and display information about the queue.
*
* @param int $worker
* Worker number.
* @param object $item
* The $item which was stored in the cron queue.
*/
protected function reportWork($worker, $item) {
if ($this->state->get('cron_example_show_status_message')) {
drupal_set_message(
$this->t('Queue @worker worker processed item with sequence @sequence created at @time', [
'@worker' => $worker,
'@sequence' => $item->sequence,
'@time' => date_iso8601($item->created),
])
);
}
$this->logger->get('cron_example')->info('Queue @worker worker processed item with sequence @sequence created at @time', [
'@worker' => $worker,
'@sequence' => $item->sequence,
'@time' => date_iso8601($item->created),
]);
}
}
@@ -0,0 +1,29 @@
<?php
namespace Drupal\cron_example\Plugin\QueueWorker;
/**
* A report worker.
*
* @QueueWorker(
* id = "cron_example_queue_1",
* title = @Translation("First worker in cron_example"),
* cron = {"time" = 1}
* )
*
* QueueWorkers are new in Drupal 8. They define a queue, which in this case
* is identified as cron_example_queue_1 and contain a process that operates on
* all the data given to the queue.
*
* @see queue_example.module
*/
class ReportWorkerOne extends ReportWorkerBase {
/**
* {@inheritdoc}
*/
public function processItem($data) {
$this->reportWork(1, $data);
}
}
@@ -0,0 +1,29 @@
<?php
namespace Drupal\cron_example\Plugin\QueueWorker;
/**
* A report worker.
*
* @QueueWorker(
* id = "cron_example_queue_2",
* title = @Translation("Second worker in cron_example"),
* cron = {"time" = 20}
* )
*
* QueueWorkers are new in Drupal 8. They define a queue, which in this case
* is identified as cron_example_queue_2 and contain a process that operates on
* all the data given to the queue.
*
* @see queue_example.module
*/
class ReportWorkerTwo extends ReportWorkerBase {
/**
* {@inheritdoc}
*/
public function processItem($data) {
$this->reportWork(2, $data);
}
}
@@ -0,0 +1,90 @@
<?php
namespace Drupal\Tests\cron_example\Functional;
use Drupal\Tests\examples\Functional\ExamplesBrowserTestBase;
/**
* Test the functionality for the Cron Example.
*
* @ingroup cron_example
*
* @group cron_example
* @group examples
*/
class CronExampleTest extends ExamplesBrowserTestBase {
/**
* An editable config object for access to 'cron_example.settings'.
*
* @var \Drupal\Core\Config\Config
*/
protected $cronConfig;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['cron_example', 'node'];
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
// Create user. Search content permission granted for the search block to
// be shown.
$this->drupalLogin($this->drupalCreateUser(['administer site configuration', 'access content']));
$this->cronConfig = \Drupal::configFactory()->getEditable('cron_example.settings');
}
/**
* Create an example node, test block through admin and user interfaces.
*/
public function testCronExampleBasic() {
$assert = $this->assertSession();
// Pretend that cron has never been run (even though simpletest seems to
// run it once...).
\Drupal::state()->set('cron_example.next_execution', 0);
$this->drupalGet('examples/cron-example');
// Initial run should cause cron_example_cron() to fire.
$post = [];
$this->drupalPostForm('examples/cron-example', $post, 'Run cron now');
$assert->pageTextContains('cron_example executed at');
// Forcing should also cause cron_example_cron() to fire.
$post['cron_reset'] = TRUE;
$this->drupalPostForm(NULL, $post, 'Run cron now');
$assert->pageTextContains('cron_example executed at');
// But if followed immediately and not forced, it should not fire.
$post['cron_reset'] = FALSE;
$this->drupalPostForm(NULL, $post, 'Run cron now');
$assert->statusCodeEquals(200);
$assert->pageTextNotContains('cron_example executed at');
$assert->pageTextContains('There are currently 0 items in queue 1 and 0 items in queue 2');
$post = [
'num_items' => 5,
'queue' => 'cron_example_queue_1',
];
$this->drupalPostForm(NULL, $post, 'Add jobs to queue');
$assert->pageTextContains('There are currently 5 items in queue 1 and 0 items in queue 2');
$post = [
'num_items' => 100,
'queue' => 'cron_example_queue_2',
];
$this->drupalPostForm(NULL, $post, 'Add jobs to queue');
$assert->pageTextContains('There are currently 5 items in queue 1 and 100 items in queue 2');
$this->drupalPostForm('examples/cron-example', [], 'Run cron now');
$assert->responseMatches('/Queue 1 worker processed item with sequence 5 /');
$assert->responseMatches('/Queue 2 worker processed item with sequence 100 /');
}
}