7c4ebf40b11162d1513be64d7763ccfb974fc248
[yaffs-website] / web / core / core.api.php
1 <?php
2
3 /**
4  * @file
5  * Documentation landing page and topics, plus core library hooks.
6  */
7
8 /**
9  * @mainpage
10  * Welcome to the Drupal API Documentation!
11  *
12  * This site is an API reference for Drupal, generated from comments embedded
13  * in the source code. More in-depth documentation can be found at
14  * https://www.drupal.org/developing/api.
15  *
16  * Here are some topics to help you get started developing with Drupal.
17  *
18  * @section essentials Essential background concepts
19  *
20  * - @link oo_conventions Object-oriented conventions used in Drupal @endlink
21  * - @link extending Extending and altering Drupal @endlink
22  * - @link best_practices Security and best practices @endlink
23  * - @link info_types Types of information in Drupal @endlink
24  *
25  * @section interface User interface
26  *
27  * - @link menu Menu entries, local tasks, and other links @endlink
28  * - @link routing Routing API and page controllers @endlink
29  * - @link form_api Forms @endlink
30  * - @link block_api Blocks @endlink
31  * - @link ajax Ajax @endlink
32  *
33  * @section store_retrieve Storing and retrieving data
34  *
35  * - @link entity_api Entities @endlink
36  * - @link field Fields @endlink
37  * - @link config_api Configuration API @endlink
38  * - @link state_api State API @endlink
39  * - @link views_overview Views @endlink
40  * - @link database Database abstraction layer @endlink
41  *
42  * @section other_essentials Other essential APIs
43  *
44  * - @link plugin_api Plugins @endlink
45  * - @link container Services and the Dependency Injection Container @endlink
46  * - @link events Events @endlink
47  * - @link i18n Internationalization @endlink
48  * - @link cache Caching @endlink
49  * - @link utility Utility classes and functions @endlink
50  * - @link user_api User accounts, permissions, and roles @endlink
51  * - @link theme_render Render API @endlink
52  * - @link themeable Theme system @endlink
53  * - @link update_api Update API @endlink
54  * - @link migration Migration @endlink
55  *
56  * @section additional Additional topics
57  *
58  * - @link batch Batch API @endlink
59  * - @link queue Queue API @endlink
60  * - @link typed_data Typed Data @endlink
61  * - @link testing Automated tests @endlink
62  * - @link php_assert PHP Runtime Assert Statements @endlink
63  * - @link third_party Integrating third-party applications @endlink
64  *
65  * @section more_info Further information
66  *
67  * - @link https://api.drupal.org/api/drupal/groups/8 All topics @endlink
68  * - @link https://www.drupal.org/project/examples Examples project (sample modules) @endlink
69  * - @link https://www.drupal.org/list-changes API change notices @endlink
70  * - @link https://www.drupal.org/developing/api/8 Drupal 8 API longer references @endlink
71  */
72
73 /**
74  * @defgroup third_party REST and Application Integration
75  * @{
76  * Integrating third-party applications using REST and related operations.
77  *
78  * @section sec_overview Overview of web services
79  * Web services make it possible for applications and web sites to read and
80  * update information from other web sites. There are several standard
81  * techniques for providing web services, including:
82  * - SOAP: http://wikipedia.org/wiki/SOAP
83  * - XML-RPC: http://wikipedia.org/wiki/XML-RPC
84  * - REST: http://wikipedia.org/wiki/Representational_state_transfer
85  * Drupal sites can both provide web services and integrate third-party web
86  * services.
87  *
88  * @section sec_rest_overview Overview of REST
89  * The REST technique uses basic HTTP requests to obtain and update data, where
90  * each web service defines a specific API (HTTP GET and/or POST parameters and
91  * returned response) for its HTTP requests. REST requests are separated into
92  * several types, known as methods, including:
93  * - GET: Requests to obtain data.
94  * - POST: Requests to update or create data.
95  * - PUT: Requests to update or create data (limited support, currently unused
96  *   by entity resources).
97  * - PATCH: Requests to update a subset of data, such as one field.
98  * - DELETE: Requests to delete data.
99  * The Drupal Core REST module provides support for GET, POST, PATCH, and DELETE
100  * quests on entities, GET requests on the database log from the Database
101  * Logging module, and a plugin framework for providing REST support for other
102  * data and other methods.
103  *
104  * REST requests can be authenticated. The Drupal Core Basic Auth module
105  * provides authentication using the HTTP Basic protocol; the contributed module
106  * OAuth (https://www.drupal.org/project/oauth) implements the OAuth
107  * authentication protocol. You can also use cookie-based authentication, which
108  * would require users to be logged into the Drupal site while using the
109  * application on the third-party site that is using the REST service.
110  *
111  * @section sec_rest Enabling REST for entities and the log
112  * Here are the steps to take to use the REST operations provided by Drupal
113  * Core:
114  * - Enable the REST module, plus Basic Auth (or another authentication method)
115  *   and HAL.
116  * - Node entity support is configured by default. If you would like to support
117  *   other types of entities, you can copy
118  *   core/modules/rest/config/install/rest.settings.yml to your sync
119  *   configuration directory, appropriately modified for other entity types,
120  *   and import it. Support for GET on the log from the Database Logging module
121  *   can also be enabled in this way; in this case, the 'entity:node' line
122  *   in the configuration would be replaced by the appropriate plugin ID,
123  *   'dblog'.
124  * - Set up permissions to allow the desired REST operations for a role, and set
125  *   up one or more user accounts to perform the operations.
126  * - To perform a REST operation, send a request to either the canonical URL
127  *   for an entity (such as node/12345 for a node), or if the entity does not
128  *   have a canonical URL, a URL like entity/(type)/(ID). The URL for a log
129  *   entry is dblog/(ID). The request must have the following properties:
130  *   - The request method must be set to the REST method you are using (POST,
131  *     GET, PATCH, etc.).
132  *   - The content type for the data you send, or the accept type for the
133  *     data you are receiving, must be set to 'application/hal+json'.
134  *   - If you are sending data, it must be JSON-encoded.
135  *   - You'll also need to make sure the authentication information is sent
136  *     with the request, unless you have allowed access to anonymous users.
137  *
138  * For more detailed information on setting up REST, see
139  * https://www.drupal.org/documentation/modules/rest.
140  *
141  * @section sec_plugins Defining new REST plugins
142  * The REST framework in the REST module has support built in for entities, but
143  * it is also an extensible plugin-based system. REST plugins implement
144  * interface \Drupal\rest\Plugin\ResourceInterface, and generally extend base
145  * class \Drupal\rest\Plugin\ResourceBase. They are annotated with
146  * \Drupal\rest\Annotation\RestResource annotation, and must be in plugin
147  * namespace subdirectory Plugin\rest\resource. For more information on how to
148  * create plugins, see the @link plugin_api Plugin API topic. @endlink
149  *
150  * If you create a new REST plugin, you will also need to enable it by
151  * providing default configuration or configuration import, as outlined in
152  * @ref sec_rest above.
153  *
154  * @section sec_integrate Integrating data from other sites into Drupal
155  * If you want to integrate data from other web sites into Drupal, here are
156  * some notes:
157  * - There are contributed modules available for integrating many third-party
158  *   sites into Drupal. Search on https://www.drupal.org/project/project_module
159  * - If there is not an existing module, you will need to find documentation on
160  *   the specific web services API for the site you are trying to integrate.
161  * - There are several classes and functions that are useful for interacting
162  *   with web services:
163  *   - You should make requests using the 'http_client' service, which
164  *     implements \GuzzleHttp\ClientInterface. See the
165  *     @link container Services topic @endlink for more information on
166  *     services. If you cannot use dependency injection to retrieve this
167  *     service, the \Drupal::httpClient() method is available. A good example
168  *     of how to use this service can be found in
169  *     \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher
170  *   - \Drupal\Component\Serialization\Json (JSON encoding and decoding).
171  *   - PHP has functions and classes for parsing XML; see
172  *     http://php.net/manual/refs.xml.php
173  * @}
174  */
175
176 /**
177  * @defgroup state_api State API
178  * @{
179  * Information about the State API.
180  *
181  * The State API is one of several methods in Drupal for storing information.
182  * See the @link info_types Information types topic @endlink for an
183  * overview of the different types of information.
184  *
185  * The basic entry point into the State API is \Drupal::state(), which returns
186  * an object of class \Drupal\Core\State\StateInterface. This class has
187  * methods for storing and retrieving state information; each piece of state
188  * information is associated with a string-valued key. Example:
189  * @code
190  * // Get the state class.
191  * $state = \Drupal::state();
192  * // Find out when cron was last run; the key is 'system.cron_last'.
193  * $time = $state->get('system.cron_last');
194  * // Set the cron run time to the current request time.
195  * $state->set('system.cron_last', REQUEST_TIME);
196  * @endcode
197  *
198  * For more on the State API, see https://www.drupal.org/developing/api/8/state
199  * @}
200  */
201
202 /**
203  * @defgroup config_api Configuration API
204  * @{
205  * Information about the Configuration API.
206  *
207  * The Configuration API is one of several methods in Drupal for storing
208  * information. See the @link info_types Information types topic @endlink for
209  * an overview of the different types of information. The sections below have
210  * more information about the configuration API; see
211  * https://www.drupal.org/developing/api/8/configuration for more details.
212  *
213  * @section sec_storage Configuration storage
214  * In Drupal, there is a concept of the "active" configuration, which is the
215  * configuration that is currently in use for a site. The storage used for the
216  * active configuration is configurable: it could be in the database, in files
217  * in a particular directory, or in other storage backends; the default storage
218  * is in the database. Module developers must use the configuration API to
219  * access the active configuration, rather than being concerned about the
220  * details of where and how it is stored.
221  *
222  * Configuration is divided into individual objects, each of which has a
223  * unique name or key. Some modules will have only one configuration object,
224  * typically called 'mymodule.settings'; some modules will have many. Within
225  * a configuration object, configuration settings have data types (integer,
226  * string, Boolean, etc.) and settings can also exist in a nested hierarchy,
227  * known as a "mapping".
228  *
229  * Configuration can also be overridden on a global, per-language, or
230  * per-module basis. See https://www.drupal.org/node/1928898 for more
231  * information.
232  *
233  * @section sec_yaml Configuration YAML files
234  * Whether or not configuration files are being used for the active
235  * configuration storage on a particular site, configuration files are always
236  * used for:
237  * - Defining the default configuration for an extension (module, theme, or
238  *   profile), which is imported to the active storage when the extension is
239  *   enabled. These configuration items are located in the config/install
240  *   sub-directory of the extension. Note that changes to this configuration
241  *   after a module or theme is already enabled have no effect; to make a
242  *   configuration change after a module or theme is enabled, you would need to
243  *   uninstall/reinstall or use a hook_update_N() function.
244  * - Defining optional configuration for a module or theme. Optional
245  *   configuration items are located in the config/optional sub-directory of the
246  *   extension. These configuration items have dependencies that are not
247  *   explicit dependencies of the extension, so they are only installed if all
248  *   dependencies are met. For example, in the scenario that module A defines a
249  *   dependency which requires module B, but module A is installed first and
250  *   module B some time later, then module A's config/optional directory will be
251  *   scanned at that time for newly met dependencies, and the configuration will
252  *   be installed then. If module B is never installed, the configuration item
253  *   will not be installed either.
254  * - Exporting and importing configuration.
255  *
256  * The file storage format for configuration information in Drupal is
257  * @link http://wikipedia.org/wiki/YAML YAML files. @endlink Configuration is
258  * divided into files, each containing one configuration object. The file name
259  * for a configuration object is equal to the unique name of the configuration,
260  * with a '.yml' extension. The default configuration files for each module are
261  * placed in the config/install directory under the top-level module directory,
262  * so look there in most Core modules for examples.
263  *
264  * @section sec_schema Configuration schema and translation
265  * Each configuration file has a specific structure, which is expressed as a
266  * YAML-based configuration schema. The configuration schema details the
267  * structure of the configuration, its data types, and which of its values need
268  * to be translatable. Each module needs to define its configuration schema in
269  * files in the config/schema directory under the top-level module directory, so
270  * look there in most Core modules for examples.
271  *
272  * Configuration can be internationalized; see the
273  * @link i18n Internationalization topic @endlink for more information. Data
274  * types label, text, and date_format in configuration schema are translatable;
275  * string is non-translatable text (the 'translatable' property on a schema
276  * data type definition indicates that it is translatable).
277  *
278  * @section sec_simple Simple configuration
279  * The simple configuration API should be used for information that will always
280  * have exactly one copy or version. For instance, if your module has a
281  * setting that is either on or off, then this is only defined once, and it
282  * would be a Boolean-valued simple configuration setting.
283  *
284  * The first task in using the simple configuration API is to define the
285  * configuration file structure, file name, and schema of your settings (see
286  * @ref sec_yaml above). Once you have done that, you can retrieve the active
287  * configuration object that corresponds to configuration file mymodule.foo.yml
288  * with a call to:
289  * @code
290  * $config = \Drupal::config('mymodule.foo');
291  * @endcode
292  *
293  * This will be an object of class \Drupal\Core\Config\Config, which has methods
294  * for getting configuration information. For instance, if your YAML file
295  * structure looks like this:
296  * @code
297  * enabled: '0'
298  * bar:
299  *   baz: 'string1'
300  *   boo: 34
301  * @endcode
302  * you can make calls such as:
303  * @code
304  * // Get a single value.
305  * $enabled = $config->get('enabled');
306  * // Get an associative array.
307  * $bar = $config->get('bar');
308  * // Get one element of the array.
309  * $bar_baz = $config->get('bar.baz');
310  * @endcode
311  *
312  * The Config object that was obtained and used in the previous examples does
313  * not allow you to change configuration. If you want to change configuration,
314  * you will instead need to get the Config object by making a call to
315  * getEditable() on the config factory:
316  * @code
317  * $config =\Drupal::service('config.factory')->getEditable('mymodule.foo');
318  * @endcode
319  *
320  * Individual configuration values can be changed or added using the set()
321  * method and saved using the save() method:
322  * @code
323  * // Set a scalar value.
324  * $config->set('enabled', 1);
325  * // Save the configuration.
326  * $config->save();
327  * @endcode
328  *
329  * Configuration values can also be unset using the clear() method, which is
330  * also chainable:
331  * @code
332  * $config->clear('bar.boo')->save();
333  * $config_data = $config->get('bar');
334  * @endcode
335  * In this example $config_data would return an array with one key - 'baz' -
336  * because 'boo' was unset.
337  *
338  * @section sec_entity Configuration entities
339  * In contrast to the simple configuration settings described in the previous
340  * section, if your module allows users to create zero or more items (where
341  * "items" are things like content type definitions, view definitions, and the
342  * like), then you need to define a configuration entity type to store your
343  * configuration. Creating an entity type, loading entities, and querying them
344  * are outlined in the @link entity_api Entity API topic. @endlink Here are a
345  * few additional steps and notes specific to configuration entities:
346  * - For examples, look for classes that implement
347  *   \Drupal\Core\Config\Entity\ConfigEntityInterface -- one good example is
348  *   the \Drupal\user\Entity\Role entity type.
349  * - In the entity type annotation, you will need to define a 'config_prefix'
350  *   string. When Drupal stores a configuration item, it will be given a name
351  *   composed of your module name, your chosen config prefix, and the ID of
352  *   the individual item, separated by '.'. For example, in the Role entity,
353  *   the config prefix is 'role', so one configuration item might be named
354  *   user.role.anonymous, with configuration file user.role.anonymous.yml.
355  * - You will need to define the schema for your configuration in your
356  *   modulename.schema.yml file, with an entry for 'modulename.config_prefix.*'.
357  *   For example, for the Role entity, the file user.schema.yml has an entry
358  *   user.role.*; see @ref sec_yaml above for more information.
359  * - Your module can provide default/optional configuration entities in YAML
360  *   files; see @ref sec_yaml above for more information.
361  * - Some configuration entities have dependencies on other configuration
362  *   entities, and module developers need to consider this so that configuration
363  *   can be imported, uninstalled, and synchronized in the right order. For
364  *   example, a field display configuration entity would need to depend on
365  *   field configuration, which depends on field and bundle configuration.
366  *   Configuration entity classes expose dependencies by overriding the
367  *   \Drupal\Core\Config\Entity\ConfigEntityInterface::calculateDependencies()
368  *   method.
369  * - On routes for paths starting with '/admin' or otherwise designated as
370  *   administration paths (such as node editing when it is set as an admin
371  *   operation), if they have configuration entity placeholders, configuration
372  *   entities are normally loaded in their original language, without
373  *   translations or other overrides. This is usually desirable, because most
374  *   admin paths are for editing configuration, and you need that to be in the
375  *   source language and to lack possibly dynamic overrides. If for some reason
376  *   you need to have your configuration entity loaded in the currently-selected
377  *   language on an admin path (for instance, if you go to
378  *   example.com/es/admin/your_path and you need the entity to be in Spanish),
379  *   then you can add a 'with_config_overrides' parameter option to your route.
380  *   The same applies if you need to load the entity with overrides (or
381  *   translated) on an admin path like '/node/add/article' (when configured to
382  *   be an admin path). Here's an example using the configurable_language config
383  *   entity:
384  *   @code
385  *   mymodule.myroute:
386  *     path: '/admin/mypath/{configurable_language}'
387  *     defaults:
388  *       _controller: '\Drupal\mymodule\MyController::myMethod'
389  *     options:
390  *       parameters:
391  *         configurable_language:
392  *           type: entity:configurable_language
393  *           with_config_overrides: TRUE
394  *   @endcode
395  *   With the route defined this way, the $configurable_language parameter to
396  *   your controller method will come in translated to the current language.
397  *   Without the parameter options section, it would be in the original
398  *   language, untranslated.
399  *
400  * @see i18n
401  *
402  * @}
403  */
404
405 /**
406  * @defgroup cache Cache API
407  * @{
408  * Information about the Drupal Cache API
409  *
410  * @section basics Basics
411  *
412  * Note: If not specified, all of the methods mentioned here belong to
413  * \Drupal\Core\Cache\CacheBackendInterface.
414  *
415  * The Cache API is used to store data that takes a long time to compute.
416  * Caching can either be permanent or valid only for a certain timespan, and
417  * the cache can contain any type of data.
418  *
419  * To use the Cache API:
420  * - Request a cache object through \Drupal::cache() or by injecting a cache
421  *   service.
422  * - Define a Cache ID (cid) value for your data. A cid is a string, which must
423  *   contain enough information to uniquely identify the data. For example, if
424  *   your data contains translated strings, then your cid value must include the
425  *   interface text language selected for page.
426  * - Call the get() method to attempt a cache read, to see if the cache already
427  *   contains your data.
428  * - If your data is not already in the cache, compute it and add it to the
429  *   cache using the set() method. The third argument of set() can be used to
430  *   control the lifetime of your cache item.
431  *
432  * Example:
433  * @code
434  * $cid = 'mymodule_example:' . \Drupal::languageManager()->getCurrentLanguage()->getId();
435  *
436  * $data = NULL;
437  * if ($cache = \Drupal::cache()->get($cid)) {
438  *   $data = $cache->data;
439  * }
440  * else {
441  *   $data = my_module_complicated_calculation();
442  *   \Drupal::cache()->set($cid, $data);
443  * }
444  * @endcode
445  *
446  * Note the use of $data and $cache->data in the above example. Calls to
447  * \Drupal::cache()->get() return a record that contains the information stored
448  * by \Drupal::cache()->set() in the data property as well as additional meta
449  * information about the cached data. In order to make use of the cached data
450  * you can access it via $cache->data.
451  *
452  * @section bins Cache bins
453  *
454  * Cache storage is separated into "bins", each containing various cache items.
455  * Each bin can be configured separately; see @ref configuration.
456  *
457  * When you request a cache object, you can specify the bin name in your call to
458  * \Drupal::cache(). Alternatively, you can request a bin by getting service
459  * "cache.nameofbin" from the container. The default bin is called "default", with
460  * service name "cache.default", it is used to store common and frequently used
461  * caches.
462  *
463  * Other common cache bins are the following:
464  *   - bootstrap: Data needed from the beginning to the end of most requests,
465  *     that has a very strict limit on variations and is invalidated rarely.
466  *   - render: Contains cached HTML strings like cached pages and blocks, can
467  *     grow to large size.
468  *   - data: Contains data that can vary by path or similar context.
469  *   - discovery: Contains cached discovery data for things such as plugins,
470  *     views_data, or YAML discovered data such as library info.
471  *
472  * A module can define a cache bin by defining a service in its
473  * modulename.services.yml file as follows (substituting the desired name for
474  * "nameofbin"):
475  * @code
476  * cache.nameofbin:
477  *   class: Drupal\Core\Cache\CacheBackendInterface
478  *   tags:
479  *     - { name: cache.bin }
480  *   factory: cache_factory:get
481  *   arguments: [nameofbin]
482  * @endcode
483  * See the @link container Services topic @endlink for more on defining
484  * services.
485  *
486  * @section delete Deletion
487  *
488  * There are two ways to remove an item from the cache:
489  * - Deletion (using delete(), deleteMultiple() or deleteAll()) permanently
490  *   removes the item from the cache.
491  * - Invalidation (using invalidate(), invalidateMultiple() or invalidateAll())
492  *   is a "soft" delete that only marks items as "invalid", meaning "not fresh"
493  *   or "not fresh enough". Invalid items are not usually returned from the
494  *   cache, so in most ways they behave as if they have been deleted. However,
495  *   it is possible to retrieve invalid items, if they have not yet been
496  *   permanently removed by the garbage collector, by passing TRUE as the second
497  *   argument for get($cid, $allow_invalid).
498  *
499  * Use deletion if a cache item is no longer useful; for instance, if the item
500  * contains references to data that has been deleted. Use invalidation if the
501  * cached item may still be useful to some callers until it has been updated
502  * with fresh data. The fact that it was fresh a short while ago may often be
503  * sufficient.
504  *
505  * Invalidation is particularly useful to protect against stampedes. Rather than
506  * having multiple concurrent requests updating the same cache item when it
507  * expires or is deleted, there can be one request updating the cache, while the
508  * other requests can proceed using the stale value. As soon as the cache item
509  * has been updated, all future requests will use the updated value.
510  *
511  * @section tags Cache Tags
512  *
513  * The fourth argument of the set() method can be used to specify cache tags,
514  * which are used to identify which data is included in each cache item. A cache
515  * item can have multiple cache tags (an array of cache tags), and each cache
516  * tag is a string. The convention is to generate cache tags of the form
517  * [prefix]:[suffix]. Usually, you'll want to associate the cache tags of
518  * entities, or entity listings. You won't have to manually construct cache tags
519  * for them â€” just get their cache tags via
520  * \Drupal\Core\Cache\CacheableDependencyInterface::getCacheTags() and
521  * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags().
522  * Data that has been tagged can be invalidated as a group: no matter the Cache
523  * ID (cid) of the cache item, no matter in which cache bin a cache item lives;
524  * as long as it is tagged with a certain cache tag, it will be invalidated.
525  *
526  * Because of that, cache tags are a solution to the cache invalidation problem:
527  * - For caching to be effective, each cache item must only be invalidated when
528  *   absolutely necessary. (i.e. maximizing the cache hit ratio.)
529  * - For caching to be correct, each cache item that depends on a certain thing
530  *   must be invalidated whenever that certain thing is modified.
531  *
532  * A typical scenario: a user has modified a node that appears in two views,
533  * three blocks and on twelve pages. Without cache tags, we couldn't possibly
534  * know which cache items to invalidate, so we'd have to invalidate everything:
535  * we had to sacrifice effectiveness to achieve correctness. With cache tags, we
536  * can have both.
537  *
538  * Example:
539  * @code
540  * // A cache item with nodes, users, and some custom module data.
541  * $tags = array(
542  *   'my_custom_tag',
543  *   'node:1',
544  *   'node:3',
545  *   'user:7',
546  * );
547  * \Drupal::cache()->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT, $tags);
548  *
549  * // Invalidate all cache items with certain tags.
550  * \Drupal\Core\Cache\Cache::invalidateTags(array('user:1'));
551  * @endcode
552  *
553  * Drupal is a content management system, so naturally you want changes to your
554  * content to be reflected everywhere, immediately. That's why we made sure that
555  * every entity type in Drupal 8 automatically has support for cache tags: when
556  * you save an entity, you can be sure that the cache items that have the
557  * corresponding cache tags will be invalidated.
558  * This also is the case when you define your own entity types: you'll get the
559  * exact same cache tag invalidation as any of the built-in entity types, with
560  * the ability to override any of the default behavior if needed.
561  * See \Drupal\Core\Cache\CacheableDepenencyInterface::getCacheTags(),
562  * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags(),
563  * \Drupal\Core\Entity\Entity::invalidateTagsOnSave() and
564  * \Drupal\Core\Entity\Entity::invalidateTagsOnDelete().
565  *
566  * @section context Cache contexts
567  *
568  * Some computed data depends on contextual data, such as the user roles of the
569  * logged-in user who is viewing a page, the language the page is being rendered
570  * in, the theme being used, etc. When caching the output of such a calculation,
571  * you must cache each variation separately, along with information about which
572  * variation of the contextual data was used in the calculatation. The next time
573  * the computed data is needed, if the context matches that for an existing
574  * cached data set, the cached data can be reused; if no context matches, a new
575  * data set can be calculated and cached for later use.
576  *
577  * Cache contexts are services tagged with 'cache.context', whose classes
578  * implement \Drupal\Core\Cache\Context\CacheContextInterface. See
579  * https://www.drupal.org/developing/api/8/cache/contexts for more information
580  * on cache contexts, including a list of the contexts that exist in Drupal
581  * core, and information on how to define your own contexts. See the
582  * @link container Services and the Dependency Injection Container @endlink
583  * topic for more information about services.
584  *
585  * Typically, the cache context is specified as part of the #cache property
586  * of a render array; see the Caching section of the
587  * @link theme_render Render API overview topic @endlink for details.
588  *
589  * @section configuration Configuration
590  *
591  * By default cached data is stored in the database. This can be configured
592  * though so that all cached data, or that of an individual cache bin, uses a
593  * different cache backend, such as APCu or Memcache, for storage.
594  *
595  * In a settings.php file, you can override the service used for a particular
596  * cache bin. For example, if your service implementation of
597  * \Drupal\Core\Cache\CacheBackendInterface was called cache.custom, the
598  * following line would make Drupal use it for the 'cache_render' bin:
599  * @code
600  *  $settings['cache']['bins']['render'] = 'cache.custom';
601  * @endcode
602  *
603  * Additionally, you can register your cache implementation to be used by
604  * default for all cache bins with:
605  * @code
606  *  $settings['cache']['default'] = 'cache.custom';
607  * @endcode
608  *
609  * Finally, you can chain multiple cache backends together, see
610  * \Drupal\Core\Cache\ChainedFastBackend and \Drupal\Core\Cache\BackendChain.
611  *
612  * @see https://www.drupal.org/node/1884796
613  * @}
614  */
615
616 /**
617  * @defgroup user_api User accounts, permissions, and roles
618  * @{
619  * API for user accounts, access checking, roles, and permissions.
620  *
621  * @section sec_overview Overview and terminology
622  * Drupal's permission system is based on the concepts of accounts, roles,
623  * and permissions.
624  *
625  * Users (site visitors) have accounts, which include a user name, an email
626  * address, a password (or some other means of authentication), and possibly
627  * other fields (if defined on the site). Anonymous users have an implicit
628  * account that does not have a real user name or any account information.
629  *
630  * Each user account is assigned one or more roles. The anonymous user account
631  * automatically has the anonymous user role; real user accounts
632  * automatically have the authenticated user role, plus any roles defined on
633  * the site that they have been assigned.
634  *
635  * Each role, including the special anonymous and authenticated user roles, is
636  * granted one or more named permissions, which allow them to perform certain
637  * tasks or view certain content on the site. It is possible to designate a
638  * role to be the "administrator" role; if this is set up, this role is
639  * automatically granted all available permissions whenever a module is
640  * enabled that defines permissions.
641  *
642  * All code in Drupal that allows users to perform tasks or view content must
643  * check that the current user has the correct permission before allowing the
644  * action. In the standard case, access checking consists of answering the
645  * question "Does the current user have permission 'foo'?", and allowing or
646  * denying access based on the answer. Note that access checking should nearly
647  * always be done at the permission level, not by checking for a particular role
648  * or user ID, so that site administrators can set up user accounts and roles
649  * appropriately for their particular sites.
650  *
651  * @section sec_define Defining permissions
652  * Modules define permissions via a $module.permissions.yml file. See
653  * \Drupal\user\PermissionHandler for documentation of permissions.yml files.
654  *
655  * @section sec_access Access permission checking
656  * Depending on the situation, there are several methods for ensuring that
657  * access checks are done properly in Drupal:
658  * - Routes: When you register a route, include a 'requirements' section that
659  *   either gives the machine name of the permission that is needed to visit the
660  *   URL of the route, or tells Drupal to use an access check method or service
661  *   to check access. See the @link menu Routing topic @endlink for more
662  *   information.
663  * - Entities: Access for various entity operations is designated either with
664  *   simple permissions or access control handler classes in the entity
665  *   annotation. See the @link entity_api Entity API topic @endlink for more
666  *   information.
667  * - Other code: There is a 'current_user' service, which can be injected into
668  *   classes to provide access to the current user account (see the
669  *   @link container Services and Dependency Injection topic @endlink for more
670  *   information on dependency injection). In code that cannot use dependency
671  *   injection, you can access this service and retrieve the current user
672  *   account object by calling \Drupal::currentUser(). Once you have a user
673  *   object for the current user (implementing \Drupal\user\UserInterface), you
674  *   can call inherited method
675  *   \Drupal\Core\Session\AccountInterface::hasPermission() to check
676  *   permissions, or pass this object into other functions/methods.
677  * - Forms: Each element of a form array can have a Boolean '#access' property,
678  *   which determines whether that element is visible and/or usable. This is a
679  *   common need in forms, so the current user service (described above) is
680  *   injected into the form base class as method
681  *   \Drupal\Core\Form\FormBase::currentUser().
682  *
683  * @section sec_entities User and role objects
684  * User objects in Drupal are entity items, implementing
685  * \Drupal\user\UserInterface. Role objects in Drupal are also entity items,
686  * implementing \Drupal\user\RoleInterface. See the
687  * @link entity_api Entity API topic @endlink for more information about
688  * entities in general (including how to load, create, modify, and query them).
689  *
690  * Roles often need to be manipulated in automated test code, such as to add
691  * permissions to them. Here's an example:
692  * @code
693  * $role = \Drupal\user\Entity\Role::load('authenticated');
694  * $role->grantPermission('access comments');
695  * $role->save();
696  * @endcode
697  *
698  * Other important interfaces:
699  * - \Drupal\Core\Session\AccountInterface: The part of UserInterface that
700  *   deals with access checking. In writing code that checks access, your
701  *   method parameters should use this interface, not UserInterface.
702  * - \Drupal\Core\Session\AccountProxyInterface: The interface for the
703  *   current_user service (described above).
704  * @}
705  */
706
707 /**
708  * @defgroup container Services and Dependency Injection Container
709  * @{
710  * Overview of the Dependency Injection Container and Services.
711  *
712  * @section sec_overview Overview of container, injection, and services
713  * The Services and Dependency Injection Container concepts have been adopted by
714  * Drupal from the @link http://symfony.com/ Symfony framework. @endlink A
715  * "service" (such as accessing the database, sending email, or translating user
716  * interface text) is defined (given a name and an interface or at least a
717  * class that defines the methods that may be called), and a default class is
718  * designated to provide the service. These two steps must be done together, and
719  * can be done by Drupal Core or a module. Other modules can then define
720  * alternative classes to provide the same services, overriding the default
721  * classes. Classes and functions that need to use the service should always
722  * instantiate the class via the dependency injection container (also known
723  * simply as the "container"), rather than instantiating a particular service
724  * provider class directly, so that they get the correct class (default or
725  * overridden).
726  *
727  * See https://www.drupal.org/node/2133171 for more detailed information on
728  * services and the dependency injection container.
729  *
730  * @section sec_discover Discovering existing services
731  * Drupal core defines many core services in the core.services.yml file (in the
732  * top-level core directory). Some Drupal Core modules and contributed modules
733  * also define services in modulename.services.yml files. API reference sites
734  * (such as https://api.drupal.org) generate lists of all existing services from
735  * these files. Look for the Services link in the API Navigation block.
736  * Alternatively you can look through the individual files manually.
737  *
738  * A typical service definition in a *.services.yml file looks like this:
739  * @code
740  * path.alias_manager:
741  *   class: Drupal\Core\Path\AliasManager
742  *   arguments: ['@path.crud', '@path.alias_whitelist', '@language_manager']
743  * @endcode
744  * Some services use other services as factories; a typical service definition
745  * is:
746  * @code
747  *   cache.entity:
748  *     class: Drupal\Core\Cache\CacheBackendInterface
749  *     tags:
750  *       - { name: cache.bin }
751  *     factory: cache_factory:get
752  *     arguments: [entity]
753  * @endcode
754  *
755  * The first line of a service definition gives the unique machine name of the
756  * service. This is often prefixed by the module name if provided by a module;
757  * however, by convention some service names are prefixed by a group name
758  * instead, such as cache.* for cache bins and plugin.manager.* for plugin
759  * managers.
760  *
761  * The class line either gives the default class that provides the service, or
762  * if the service uses a factory class, the interface for the service. If the
763  * class depends on other services, the arguments line lists the machine
764  * names of the dependencies (preceded by '@'); objects for each of these
765  * services are instantiated from the container and passed to the class
766  * constructor when the service class is instantiated. Other arguments can also
767  * be passed in; see the section at https://www.drupal.org/node/2133171 for more
768  * detailed information.
769  *
770  * Services using factories can be defined as shown in the above example, if the
771  * factory is itself a service. The factory can also be a class; details of how
772  * to use service factories can be found in the section at
773  * https://www.drupal.org/node/2133171.
774  *
775  * @section sec_container Accessing a service through the container
776  * As noted above, if you need to use a service in your code, you should always
777  * instantiate the service class via a call to the container, using the machine
778  * name of the service, so that the default class can be overridden. There are
779  * several ways to make sure this happens:
780  * - For service-providing classes, see other sections of this documentation
781  *   describing how to pass services as arguments to the constructor.
782  * - Plugin classes, controllers, and similar classes have create() or
783  *   createInstance() methods that are used to create an instance of the class.
784  *   These methods come from different interfaces, and have different
785  *   arguments, but they all include an argument $container of type
786  *   \Symfony\Component\DependencyInjection\ContainerInterface.
787  *   If you are defining one of these classes, in the create() or
788  *   createInstance() method, call $container->get('myservice.name') to
789  *   instantiate a service. The results of these calls are generally passed to
790  *   the class constructor and saved as member variables in the class.
791  * - For functions and class methods that do not have access to either of
792  *   the above methods of dependency injection, you can use service location to
793  *   access services, via a call to the global \Drupal class. This class has
794  *   special methods for accessing commonly-used services, or you can call a
795  *   generic method to access any service. Examples:
796  *   @code
797  *   // Retrieve the entity.manager service object (special method exists).
798  *   $manager = \Drupal::entityManager();
799  *   // Retrieve the service object for machine name 'foo.bar'.
800  *   $foobar = \Drupal::service('foo.bar');
801  *   @endcode
802  *
803  * As a note, you should always use dependency injection (via service arguments
804  * or create()/createInstance() methods) if possible to instantiate services,
805  * rather than service location (via the \Drupal class), because:
806  * - Dependency injection facilitates writing unit tests, since the container
807  *   argument can be mocked and the create() method can be bypassed by using
808  *   the class constructor. If you use the \Drupal class, unit tests are much
809  *   harder to write and your code has more dependencies.
810  * - Having the service interfaces on the class constructor and member variables
811  *   is useful for IDE auto-complete and self-documentation.
812  *
813  * @section sec_define Defining a service
814  * If your module needs to define a new service, here are the steps:
815  * - Choose a unique machine name for your service. Typically, this should
816  *   start with your module name. Example: mymodule.myservice.
817  * - Create a PHP interface to define what your service does.
818  * - Create a default class implementing your interface that provides your
819  *   service. If your class needs to use existing services (such as database
820  *   access), be sure to make these services arguments to your class
821  *   constructor, and save them in member variables. Also, if the needed
822  *   services are provided by other modules and not Drupal Core, you'll want
823  *   these modules to be dependencies of your module.
824  * - Add an entry to a modulename.services.yml file for the service. See
825  *   @ref sec_discover above, or existing *.services.yml files in Core, for the
826  *   syntax; it will start with your machine name, refer to your default class,
827  *   and list the services that need to be passed into your constructor.
828  *
829  * Services can also be defined dynamically, as in the
830  * \Drupal\Core\CoreServiceProvider class, but this is less common for modules.
831  *
832  * @section sec_tags Service tags
833  * Some services have tags, which are defined in the service definition. See
834  * @link service_tag Service Tags @endlink for usage.
835  *
836  * @section sec_injection Overriding the default service class
837  * Modules can override the default classes used for services. Here are the
838  * steps:
839  * - Define a class in the top-level namespace for your module
840  *   (Drupal\my_module), whose name is the camel-case version of your module's
841  *   machine name followed by "ServiceProvider" (for example, if your module
842  *   machine name is my_module, the class must be named
843  *   MyModuleServiceProvider).
844  * - The class needs to implement
845  *   \Drupal\Core\DependencyInjection\ServiceModifierInterface, which is
846  *   typically done by extending
847  *   \Drupal\Core\DependencyInjection\ServiceProviderBase.
848  * - The class needs to contain one method: alter(). This method does the
849  *   actual work of telling Drupal to use your class instead of the default.
850  *   Here's an example:
851  *   @code
852  *   public function alter(ContainerBuilder $container) {
853  *     // Override the language_manager class with a new class.
854  *     $definition = $container->getDefinition('language_manager');
855  *     $definition->setClass('Drupal\my_module\MyLanguageManager');
856  *   }
857  *   @endcode
858  *   Note that $container here is an instance of
859  *   \Drupal\Core\DependencyInjection\ContainerBuilder.
860  *
861  * @see https://www.drupal.org/node/2133171
862  * @see core.services.yml
863  * @see \Drupal
864  * @see \Symfony\Component\DependencyInjection\ContainerInterface
865  * @see plugin_api
866  * @see menu
867  * @}
868  */
869
870 /**
871  * @defgroup listing_page_service Page header for Services page
872  * @{
873  * Introduction to services
874  *
875  * A "service" (such as accessing the database, sending email, or translating
876  * user interface text) can be defined by a module or Drupal core. Defining a
877  * service means giving it a name and designating a default class to provide the
878  * service; ideally, there should also be an interface that defines the methods
879  * that may be called. Services are collected into the Dependency Injection
880  * Container, and can be overridden to use different classes or different
881  * instantiation by modules. See the
882  * @link container Services and Dependency Injection Container topic @endlink
883  * for details.
884  *
885  * Some services have tags, which are defined in the service definition. Tags
886  * are used to define a group of related services, or to specify some aspect of
887  * how the service behaves. See the
888  * @link service_tag Service Tags topic @endlink for more information.
889  *
890  * @see container
891  * @see service_tag
892  *
893  * @}
894  */
895
896 /**
897  * @defgroup typed_data Typed Data API
898  * @{
899  * API for describing data based on a set of available data types.
900  *
901  * PHP has data types, such as int, string, float, array, etc., and it is an
902  * object-oriented language that lets you define classes and interfaces.
903  * However, in some cases, it is useful to be able to define an abstract
904  * type (as in an interface, free of implementation details), that still has
905  * properties (which an interface cannot) as well as meta-data. The Typed Data
906  * API provides this abstraction.
907  *
908  * @section sec_overview Overview
909  * Each data type in the Typed Data API is a plugin class (annotation class
910  * example: \Drupal\Core\TypedData\Annotation\DataType); these plugins are
911  * managed by the typed_data_manager service (by default
912  * \Drupal\Core\TypedData\TypedDataManager). Each data object encapsulates a
913  * single piece of data, provides access to the metadata, and provides
914  * validation capability. Also, the typed data plugins have a shorthand
915  * for easily accessing data values, described in @ref sec_tree.
916  *
917  * The metadata of a data object is defined by an object based on a class called
918  * the definition class (see \Drupal\Core\TypedData\DataDefinitionInterface).
919  * The class used can vary by data type and can be specified in the data type's
920  * plugin definition, while the default is set in the $definition_class property
921  * of the annotation class. The default class is
922  * \Drupal\Core\TypedData\DataDefinition. For data types provided by a plugin
923  * deriver, the plugin deriver can set the definition_class property too.
924  * The metadata object provides information about the data, such as the data
925  * type, whether it is translatable, the names of its properties (for complex
926  * types), and who can access it.
927  *
928  * See https://www.drupal.org/node/1794140 for more information about the Typed
929  * Data API.
930  *
931  * @section sec_varieties Varieties of typed data
932  * There are three kinds of typed data: primitive, complex, and list.
933  *
934  * @subsection sub_primitive Primitive data types
935  * Primitive data types wrap PHP data types and also serve as building blocks
936  * for complex and list typed data. Each primitive data type has an interface
937  * that extends \Drupal\Core\TypedData\PrimitiveInterface, with getValue()
938  * and setValue() methods for accessing the data value, and a default plugin
939  * implementation. Here's a list:
940  * - \Drupal\Core\TypedData\Type\IntegerInterface: Plugin ID integer,
941  *   corresponds to PHP type int.
942  * - \Drupal\Core\TypedData\Type\StringInterface: Plugin ID string,
943  *   corresponds to PHP type string.
944  * - \Drupal\Core\TypedData\Type\FloatInterface: Plugin ID float,
945  *   corresponds to PHP type float.
946  * - \Drupal\Core\TypedData\Type\BooleanInterface: Plugin ID bool,
947  *   corresponds to PHP type bool.
948  * - \Drupal\Core\TypedData\Type\BinaryInterface: Plugin ID binary,
949  *   corresponds to a PHP file resource.
950  * - \Drupal\Core\TypedData\Type\UriInterface: Plugin ID uri.
951  *
952  * @subsection sec_complex Complex data
953  * Complex data types, with interface
954  * \Drupal\Core\TypedData\ComplexDataInterface, represent data with named
955  * properties; the properties can be accessed with get() and set() methods.
956  * The value of each property is itself a typed data object, which can be
957  * primitive, complex, or list data.
958  *
959  * The base type for most complex data is the
960  * \Drupal\Core\TypedData\Plugin\DataType\Map class, which represents an
961  * associative array. Map provides its own definition class in the annotation,
962  * \Drupal\Core\TypedData\MapDataDefinition, and most complex data classes
963  * extend this class. The getValue() and setValue() methods on the Map class
964  * enforce the data definition and its property structure.
965  *
966  * The Drupal Field API uses complex typed data for its field items, with
967  * definition class \Drupal\Core\Field\TypedData\FieldItemDataDefinition.
968  *
969  * @section sec_list Lists
970  * List data types, with interface \Drupal\Core\TypedData\ListInterface,
971  * represent data that is an ordered list of typed data, all of the same type.
972  * More precisely, the plugins in the list must have the same base plugin ID;
973  * however, some types (for example field items and entities) are provided by
974  * plugin derivatives and the sub IDs can be different.
975  *
976  * @section sec_tree Tree handling
977  * Typed data allows you to use shorthand to get data values nested in the
978  * implicit tree structure of the data. For example, to get the value from
979  * an entity field item, the Entity Field API allows you to call:
980  * @code
981  * $value = $entity->fieldName->propertyName;
982  * @endcode
983  * This is really shorthand for:
984  * @code
985  * $field_item_list = $entity->get('fieldName');
986  * $field_item = $field_item_list->get(0);
987  * $property = $field_item->get('propertyName');
988  * $value = $property->getValue();
989  * @endcode
990  * Some notes:
991  * - $property, $field_item, and $field_item_list are all typed data objects,
992  *   while $value is a raw PHP value.
993  * - You can call $property->getParent() to get $field_item,
994  *   $field_item->getParent() to get $field_item_list, or
995  *   $field_item_list->getParent() to get $typed_entity ($entity wrapped in a
996  *   typed data object). $typed_entity->getParent() is NULL.
997  * - For all of these ->getRoot() returns $typed_entity.
998  * - The langcode property is on $field_item_list, but you can access it
999  *   on $property as well, so that all items will report the same langcode.
1000  * - When the value of $property is changed by calling $property->setValue(),
1001  *   $property->onChange() will fire, which in turn calls the parent object's
1002  *   onChange() method and so on. This allows parent objects to react upon
1003  *   changes of contained properties or list items.
1004  *
1005  * @section sec_defining Defining data types
1006  * To define a new data type:
1007  * - Create a class that implements one of the Typed Data interfaces.
1008  *   Typically, you will want to extend one of the classes listed in the
1009  *   sections above as a starting point.
1010  * - Make your class into a DataType plugin. To do that, put it in namespace
1011  *   \Drupal\yourmodule\Plugin\DataType (where "yourmodule" is your module's
1012  *   short name), and add annotation of type
1013  *   \Drupal\Core\TypedData\Annotation\DataType to the documentation header.
1014  *   See the @link plugin_api Plugin API topic @endlink and the
1015  *   @link annotation Annotations topic @endlink for more information.
1016  *
1017  * @section sec_using Using data types
1018  * The data types of the Typed Data API can be used in several ways, once they
1019  * have been defined:
1020  * - In the Field API, data types can be used as the class in the property
1021  *   definition of the field. See the @link field Field API topic @endlink for
1022  *   more information.
1023  * - In configuration schema files, you can use the unique ID ('id' annotation)
1024  *   from any DataType plugin class as the 'type' value for an entry. See the
1025  *   @link config_api Confuration API topic @endlink for more information.
1026  * - If you need to create a typed data object in code, first get the
1027  *   typed_data_manager service from the container or by calling
1028  *   \Drupal::typedDataManager(). Then pass the plugin ID to
1029  *   $manager::createDataDefinition() to create an appropriate data definition
1030  *   object. Then pass the data definition object and the value of the data to
1031  *   $manager::create() to create a typed data object.
1032  *
1033  * @see plugin_api
1034  * @see container
1035  * @}
1036  */
1037
1038 /**
1039  * @defgroup testing Automated tests
1040  * @{
1041  * Overview of PHPUnit tests and Simpletest tests.
1042  *
1043  * The Drupal project has embraced a philosophy of using automated tests,
1044  * consisting of both unit tests (which test the functionality of classes at a
1045  * low level) and functional tests (which test the functionality of Drupal
1046  * systems at a higher level, usually involving web output). The goal is to
1047  * have test coverage for all or most of the components and features, and to
1048  * run the automated tests before any code is changed or added, to make sure
1049  * it doesn't break any existing functionality (regression testing).
1050  *
1051  * In order to implement this philosophy, developers need to do the following:
1052  * - When making a patch to fix a bug, make sure that the bug fix patch includes
1053  *   a test that fails without the code change and passes with the code change.
1054  *   This helps reviewers understand what the bug is, demonstrates that the code
1055  *   actually fixes the bug, and ensures the bug will not reappear due to later
1056  *   code changes.
1057  * - When making a patch to implement a new feature, include new unit and/or
1058  *   functional tests in the patch. This serves to both demonstrate that the
1059  *   code actually works, and ensure that later changes do not break the new
1060  *   functionality.
1061  *
1062  * @section write_unit Writing PHPUnit tests for classes
1063  * PHPUnit tests for classes are written using the industry-standard PHPUnit
1064  * framework. Use a PHPUnit test to test functionality of a class if the Drupal
1065  * environment (database, settings, etc.) and web browser are not needed for the
1066  * test, or if the Drupal environment can be replaced by a "mock" object. To
1067  * write a PHPUnit test:
1068  * - Define a class that extends \Drupal\Tests\UnitTestCase.
1069  * - The class name needs to end in the word Test.
1070  * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests,
1071  *   where yourmodule is your module's machine name.
1072  * - The test class file must be named and placed under the
1073  *   yourmodule/tests/src/Unit directory, according to the PSR-4 standard.
1074  * - Your test class needs a phpDoc comment block with a description and
1075  *   a @group annotation, which gives information about the test.
1076  * - Add test cases by adding method names that start with 'test' and have no
1077  *   arguments, for example testYourTestCase(). Each one should test a logical
1078  *   subset of the functionality.
1079  * For more details, see:
1080  * - https://www.drupal.org/phpunit for full documentation on how to write
1081  *   PHPUnit tests for Drupal.
1082  * - http://phpunit.de for general information on the PHPUnit framework.
1083  * - @link oo_conventions Object-oriented programming topic @endlink for more
1084  *   on PSR-4, namespaces, and where to place classes.
1085  *
1086  * @section write_functional Writing functional tests
1087  * Functional tests are written using a Drupal-specific framework that is, for
1088  * historical reasons, known as "Simpletest". Use a Simpletest test to test the
1089  * functionality of sub-system of Drupal, if the functionality depends on the
1090  * Drupal database and settings, or to test the web output of Drupal. To
1091  * write a Simpletest test:
1092  * - For functional tests of the web output of Drupal, define a class that
1093  *   extends \Drupal\simpletest\WebTestBase, which contains an internal web
1094  *   browser and defines many helpful test assertion methods that you can use
1095  *   in your tests. You can specify modules to be enabled by defining a
1096  *   $modules member variable -- keep in mind that by default, WebTestBase uses
1097  *   a "testing" install profile, with a minimal set of modules enabled.
1098  * - For functional tests that do not test web output, define a class that
1099  *   extends \Drupal\KernelTests\KernelTestBase. This class is much faster
1100  *   than WebTestBase, because instead of making a full install of Drupal, it
1101  *   uses an in-memory pseudo-installation (similar to what the installer and
1102  *   update scripts use). To use this test class, you will need to create the
1103  *   database tables you need and install needed modules manually.
1104  * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests,
1105  *   where yourmodule is your module's machine name.
1106  * - The test class file must be named and placed under the yourmodule/src/Tests
1107  *   directory, according to the PSR-4 standard.
1108  * - Your test class needs a phpDoc comment block with a description and
1109  *   a @group annotation, which gives information about the test.
1110  * - You may also override the default setUp() method, which can set be used to
1111  *   set up content types and similar procedures.
1112  * - In some cases, you may need to write a test module to support your test;
1113  *   put such modules under the yourmodule/tests/modules directory.
1114  * - Add test cases by adding method names that start with 'test' and have no
1115  *   arguments, for example testYourTestCase(). Each one should test a logical
1116  *   subset of the functionality. Each method runs in a new, isolated test
1117  *   environment, so it can only rely on the setUp() method, not what has
1118  *   been set up by other test methods.
1119  * For more details, see:
1120  * - https://www.drupal.org/simpletest for full documentation on how to write
1121  *   functional tests for Drupal.
1122  * - @link oo_conventions Object-oriented programming topic @endlink for more
1123  *   on PSR-4, namespaces, and where to place classes.
1124  *
1125  * @section write_functional_phpunit Write functional PHP tests (phpunit)
1126  * Functional tests extend the BrowserTestBase base class, and use PHPUnit as
1127  * their underlying framework. They use a simulated browser, in which the test
1128  * can click links, visit URLs, post to forms, etc. To write a functional test:
1129  * - Extend \Drupal\Tests\BrowserTestBase.
1130  * - Place the test in the yourmodule/tests/src/Functional/ directory and use
1131  *   the \Drupal\Tests\yourmodule\Functional namespace.
1132  * - Add a @group annotation. For example, if the test is for a Drupal 6
1133  *   migration process, the group core uses is migrate_drupal_6. Use yourmodule
1134  *   as the group name if the test does not belong to another larger group.
1135  * - You may also override the default setUp() method, which can be used to set
1136  *   up content types and similar procedures. Don't forget to call the parent
1137  *   method.
1138  * - In some cases, you may need to write a test module to support your test;
1139  *   put such modules under the yourmodule/tests/modules directory.
1140  * - Add test cases by adding method names that start with 'test' and have no
1141  *   arguments, for example testYourTestCase(). Each one should test a logical
1142  *   subset of the functionality. Each method runs in a new, isolated test
1143  *   environment, so it can only rely on the setUp() method, not what has
1144  *   been set up by other test methods.
1145  * For more details, see:
1146  * - https://www.drupal.org/docs/8/phpunit/phpunit-browser-test-tutorial for
1147  *   a full tutorial on how to write functional PHPUnit tests for Drupal.
1148  * - https://www.drupal.org/phpunit for the full documentation on how to write
1149  *   PHPUnit tests for Drupal.
1150  *
1151  * @section write_jsfunctional_phpunit Write functional JavaScript tests (phpunit)
1152  * To write a functional test that relies on JavaScript:
1153  * - Extend \Drupal\FunctionalJavaScriptTests\JavascriptTestBase.
1154  * - Place the test into the yourmodule/tests/src/FunctionalJavascript/
1155  *   directory and use the \Drupal\Tests\yourmodule\FunctionalJavascript
1156  *   namespace.
1157  * - Add a @group annotation. Use yourmodule as the group name if the test does
1158  *   not belong to another larger group.
1159  * - Set up PhantomJS; see http://phantomjs.org/download.html.
1160  * - To run tests, see core/tests/README.md.
1161  * - When clicking a link/button with Ajax behavior attached, keep in mind that
1162  *   the underlying browser might take time to deliver changes to the HTML. Use
1163  *   $this->assertSession()->assertWaitOnAjaxRequest() to wait for the Ajax
1164  *   request to finish.
1165  * For more details, see:
1166  * - https://www.drupal.org/docs/8/phpunit/phpunit-javascript-testing-tutorial
1167  *   for a full tutorial on how to write PHPUnit JavaScript tests for Drupal.
1168  * - https://www.drupal.org/phpunit for the full documentation on how to write
1169  *   PHPUnit tests for Drupal.
1170  *
1171  * @section running Running tests
1172  * You can run both Simpletest and PHPUnit tests by enabling the core Testing
1173  * module (core/modules/simpletest). Once that module is enabled, tests can be
1174  * run using the core/scripts/run-tests.sh script, using
1175  * @link https://www.drupal.org/project/drush Drush @endlink, or from the
1176  *   Testing module user interface.
1177  *
1178  * PHPUnit tests can also be run from the command line, using the PHPUnit
1179  * framework. See https://www.drupal.org/node/2116263 for more information.
1180  * @}
1181  */
1182
1183 /**
1184  * @defgroup php_assert PHP Runtime Assert Statements
1185  * @{
1186  * Use of the assert() statement in Drupal.
1187  *
1188  * Unit tests also use the term "assertion" to refer to test conditions, so to
1189  * avoid confusion the term "runtime assertion" will be used for the assert()
1190  * statement throughout the documentation.
1191  *
1192  * A runtime assertion is a statement that is expected to always be true at
1193  * the point in the code it appears at. They are tested using PHP's internal
1194  * @link http://php.net/assert assert() @endlink statement. If an
1195  * assertion is ever FALSE it indicates an error in the code or in module or
1196  * theme configuration files. User-provided configuration files should be
1197  * verified with standard control structures at all times, not just checked in
1198  * development environments with assert() statements on.
1199  *
1200  * When runtime assertions fail in PHP 7 an \AssertionError is thrown.
1201  * Drupal uses an assertion callback to do the same in PHP 5.x so that unit
1202  * tests involving runtime assertions will work uniformly across both versions.
1203  *
1204  * The Drupal project primarily uses runtime assertions to enforce the
1205  * expectations of the API by failing when incorrect calls are made by code
1206  * under development. While PHP type hinting does this for objects and arrays,
1207  * runtime assertions do this for scalars (strings, integers, floats, etc.) and
1208  * complex data structures such as cache and render arrays. They ensure that
1209  * methods' return values are the documented datatypes. They also verify that
1210  * objects have been properly configured and set up by the service container.
1211  * Runtime assertions are checked throughout development. They supplement unit
1212  * tests by checking scenarios that do not have unit tests written for them,
1213  * and by testing the API calls made by all the code in the system.
1214  *
1215  * When using assert() keep the following in mind:
1216  * - Runtime assertions are disabled by default in production and enabled in
1217  *   development, so they can't be used as control structures. Use exceptions
1218  *   for errors that can occur in production no matter how unlikely they are.
1219  * - Assert() functions in a buggy manner prior to PHP 7. If you do not use a
1220  *   string for the first argument of the statement but instead use a function
1221  *   call or expression then that code will be evaluated even when runtime
1222  *   assertions are turned off. To avoid this you must use a string as the
1223  *   first argument, and assert will pass this string to the eval() statement.
1224  * - Since runtime assertion strings are parsed by eval() use caution when
1225  *   using them to work with data that may be unsanitized.
1226  *
1227  * See https://www.drupal.org/node/2492225 for more information on runtime
1228  * assertions.
1229  * @}
1230  */
1231
1232 /**
1233  * @defgroup info_types Information types
1234  * @{
1235  * Types of information in Drupal.
1236  *
1237  * Drupal has several distinct types of information, each with its own methods
1238  * for storage and retrieval:
1239  * - Content: Information meant to be displayed on your site: articles, basic
1240  *   pages, images, files, custom blocks, etc. Content is stored and accessed
1241  *   using @link entity_api Entities @endlink.
1242  * - Session: Information about individual users' interactions with the site,
1243  *   such as whether they are logged in. This is really "state" information, but
1244  *   it is not stored the same way so it's a separate type here. Session
1245  *   information is available from the Request object. The session implements
1246  *   \Symfony\Component\HttpFoundation\Session\SessionInterface.
1247  * - State: Information of a temporary nature, generally machine-generated and
1248  *   not human-edited, about the current state of your site. Examples: the time
1249  *   when Cron was last run, whether node access permissions need rebuilding,
1250  *   etc. See @link state_api the State API topic @endlink for more information.
1251  * - Configuration: Information about your site that is generally (or at least
1252  *   can be) human-edited, but is not Content, and is meant to be relatively
1253  *   permanent. Examples: the name of your site, the content types and views
1254  *   you have defined, etc. See
1255  *   @link config_api the Configuration API topic @endlink for more information.
1256  *
1257  * @see cache
1258  * @see i18n
1259  * @}
1260  */
1261
1262 /**
1263  * @defgroup extending Extending and altering Drupal
1264  * @{
1265  * Overview of extensions and alteration methods for Drupal.
1266  *
1267  * @section sec_types Types of extensions
1268  * Drupal's core behavior can be extended and altered via these three basic
1269  * types of extensions:
1270  * - Themes: Themes alter the appearance of Drupal sites. They can include
1271  *   template files, which alter the HTML markup and other raw output of the
1272  *   site; CSS files, which alter the styling applied to the HTML; and
1273  *   JavaScript, Flash, images, and other files. For more information, see the
1274  *   @link theme_render Theme system and render API topic @endlink and
1275  *   https://www.drupal.org/docs/8/theming
1276  * - Modules: Modules add to or alter the behavior and functionality of Drupal,
1277  *   by using one or more of the methods listed below. For more information
1278  *   about creating modules, see https://www.drupal.org/developing/modules/8
1279  * - Installation profiles: Installation profiles can be used to
1280  *   create distributions, which are complete specific-purpose packages of
1281  *   Drupal including additional modules, themes, and data. For more
1282  *   information, see https://www.drupal.org/developing/distributions.
1283  *
1284  * @section sec_alter Alteration methods for modules
1285  * Here is a list of the ways that modules can alter or extend Drupal's core
1286  * behavior, or the behavior of other modules:
1287  * - Hooks: Specially-named functions that a module defines, which are
1288  *   discovered and called at specific times, usually to alter behavior or data.
1289  *   See the @link hooks Hooks topic @endlink for more information.
1290  * - Plugins: Classes that a module defines, which are discovered and
1291  *   instantiated at specific times to add functionality. See the
1292  *   @link plugin_api Plugin API topic @endlink for more information.
1293  * - Entities: Special plugins that define entity types for storing new types
1294  *   of content or configuration in Drupal. See the
1295  *   @link entity_api Entity API topic @endlink for more information.
1296  * - Services: Classes that perform basic operations within Drupal, such as
1297  *   accessing the database and sending email. See the
1298  *   @link container Dependency Injection Container and Services topic @endlink
1299  *   for more information.
1300  * - Routing: Providing or altering "routes", which are URLs that Drupal
1301  *   responds to, or altering routing behavior with event listener classes.
1302  *   See the @link menu Routing and menu topic @endlink for more information.
1303  * - Events: Modules can register as event subscribers; when an event is
1304  *   dispatched, a method is called on each registered subscriber, allowing each
1305  *   one to react. See the @link events Events topic @endlink for more
1306  *   information.
1307  *
1308  * @section sec_sample *.info.yml files
1309  * Extensions must each be located in a directory whose name matches the short
1310  * name (or machine name) of the extension, and this directory must contain a
1311  * file named machine_name.info.yml (where machine_name is the machine name of
1312  * the extension). See \Drupal\Core\Extension\InfoParserInterface::parse() for
1313  * documentation of the format of .info.yml files.
1314  * @}
1315  */
1316
1317 /**
1318  * @defgroup plugin_api Plugin API
1319  * @{
1320  * Using the Plugin API
1321  *
1322  * @section sec_overview Overview and terminology
1323  *
1324  * The basic idea of plugins is to allow a particular module or subsystem of
1325  * Drupal to provide functionality in an extensible, object-oriented way. The
1326  * controlling module or subsystem defines the basic framework (interface) for
1327  * the functionality, and other modules can create plugins (implementing the
1328  * interface) with particular behaviors. The controlling module instantiates
1329  * existing plugins as needed, and calls methods to invoke their functionality.
1330  * Examples of functionality in Drupal Core that use plugins include: the block
1331  * system (block types are plugins), the entity/field system (entity types,
1332  * field types, field formatters, and field widgets are plugins), the image
1333  * manipulation system (image effects and image toolkits are plugins), and the
1334  * search system (search page types are plugins).
1335  *
1336  * Plugins are grouped into plugin types, each generally defined by an
1337  * interface. Each plugin type is managed by a plugin manager service, which
1338  * uses a plugin discovery method to discover provided plugins of that type and
1339  * instantiate them using a plugin factory.
1340  *
1341  * Some plugin types make use of the following concepts or components:
1342  * - Plugin derivatives: Allows a single plugin class to present itself as
1343  *   multiple plugins. Example: the Menu module provides a block for each
1344  *   defined menu via a block plugin derivative.
1345  * - Plugin mapping: Allows a plugin class to map a configuration string to an
1346  *   instance, and have the plugin automatically instantiated without writing
1347  *   additional code.
1348  * - Plugin collections: Provide a way to lazily instantiate a set of plugin
1349  *   instances from a single plugin definition.
1350  *
1351  * There are several things a module developer may need to do with plugins:
1352  * - Define a completely new plugin type: see @ref sec_define below.
1353  * - Create a plugin of an existing plugin type: see @ref sec_create below.
1354  * - Perform tasks that involve plugins: see @ref sec_use below.
1355  *
1356  * See https://www.drupal.org/developing/api/8/plugins for more detailed
1357  * documentation on the plugin system. There are also topics for a few
1358  * of the many existing types of plugins:
1359  * - @link block_api Block API @endlink
1360  * - @link entity_api Entity API @endlink
1361  * - @link field Various types of field-related plugins @endlink
1362  * - @link views_plugins Views plugins @endlink (has links to topics covering
1363  *   various specific types of Views plugins).
1364  * - @link search Search page plugins @endlink
1365  *
1366  * @section sec_define Defining a new plugin type
1367  * To define a new plugin type:
1368  * - Define an interface for the plugin. This describes the common set of
1369  *   behavior, and the methods you will call on each plugin class that is
1370  *   instantiated. Usually this interface will extend one or more of the
1371  *   following interfaces:
1372  *   - \Drupal\Component\Plugin\PluginInspectionInterface
1373  *   - \Drupal\Component\Plugin\ConfigurablePluginInterface
1374  *   - \Drupal\Component\Plugin\ContextAwarePluginInterface
1375  *   - \Drupal\Core\Plugin\PluginFormInterface
1376  *   - \Drupal\Core\Executable\ExecutableInterface
1377  * - (optional) Create a base class that provides a partial implementation of
1378  *   the interface, for the convenience of developers wishing to create plugins
1379  *   of your type. The base class usually extends
1380  *   \Drupal\Core\Plugin\PluginBase, or one of the base classes that extends
1381  *   this class.
1382  * - Choose a method for plugin discovery, and define classes as necessary.
1383  *   See @ref sub_discovery below.
1384  * - Create a plugin manager/factory class and service, which will discover and
1385  *   instantiate plugins. See @ref sub_manager below.
1386  * - Use the plugin manager to instantiate plugins. Call methods on your plugin
1387  *   interface to perform the tasks of your plugin type.
1388  * - (optional) If appropriate, define a plugin collection. See @ref
1389  *    sub_collection below for more information.
1390  *
1391  * @subsection sub_discovery Plugin discovery
1392  * Plugin discovery is the process your plugin manager uses to discover the
1393  * individual plugins of your type that have been defined by your module and
1394  * other modules. Plugin discovery methods are classes that implement
1395  * \Drupal\Component\Plugin\Discovery\DiscoveryInterface. Most plugin types use
1396  * one of the following discovery mechanisms:
1397  * - Annotation: Plugin classes are annotated and placed in a defined namespace
1398  *   subdirectory. Most Drupal Core plugins use this method of discovery.
1399  * - Hook: Plugin modules need to implement a hook to tell the manager about
1400  *   their plugins.
1401  * - YAML: Plugins are listed in YAML files. Drupal Core uses this method for
1402  *   discovering local tasks and local actions. This is mainly useful if all
1403  *   plugins use the same class, so it is kind of like a global derivative.
1404  * - Static: Plugin classes are registered within the plugin manager class
1405  *   itself. Static discovery is only useful if modules cannot define new
1406  *   plugins of this type (if the list of available plugins is static).
1407  *
1408  * It is also possible to define your own custom discovery mechanism or mix
1409  * methods together. And there are many more details, such as annotation
1410  * decorators, that apply to some of the discovery methods. See
1411  * https://www.drupal.org/developing/api/8/plugins for more details.
1412  *
1413  * The remainder of this documentation will assume Annotation-based discovery,
1414  * since this is the most common method.
1415  *
1416  * @subsection sub_manager Defining a plugin manager class and service
1417  * To define an annotation-based plugin manager:
1418  * - Choose a namespace subdirectory for your plugin. For example, search page
1419  *   plugins go in directory Plugin/Search under the module namespace.
1420  * - Define an annotation class for your plugin type. This class should extend
1421  *   \Drupal\Component\Annotation\Plugin, and for most plugin types, it should
1422  *   contain member variables corresponding to the annotations plugins will
1423  *   need to provide. All plugins have at least $id: a unique string
1424  *   identifier.
1425  * - Define an alter hook for altering the discovered plugin definitions. You
1426  *   should document the hook in a *.api.php file.
1427  * - Define a plugin manager class. This class should implement
1428  *   \Drupal\Component\Plugin\PluginManagerInterface; most plugin managers do
1429  *   this by extending \Drupal\Core\Plugin\DefaultPluginManager. If you do
1430  *   extend the default plugin manager, the only method you will probably need
1431  *   to define is the class constructor, which will need to call the parent
1432  *   constructor to provide information about the annotation class and plugin
1433  *   namespace for discovery, set up the alter hook, and possibly set up
1434  *   caching. See classes that extend DefaultPluginManager for examples.
1435  * - Define a service for your plugin manager. See the
1436  *   @link container Services topic for more information. @endlink Your service
1437  *   definition should look something like this, referencing your manager
1438  *   class and the parent (default) plugin manager service to inherit
1439  *   constructor arguments:
1440  *   @code
1441  *   plugin.manager.mymodule:
1442  *     class: Drupal\mymodule\MyPluginManager
1443  *     parent: default_plugin_manager
1444  *   @endcode
1445  * - If your plugin is configurable, you will also need to define the
1446  *   configuration schema and possibly a configuration entity type. See the
1447  *   @link config_api Configuration API topic @endlink for more information.
1448  *
1449  * @subsection sub_collection Defining a plugin collection
1450  * Some configurable plugin types allow administrators to create zero or more
1451  * instances of each plugin, each with its own configuration. For example,
1452  * a single block plugin can be configured several times, to display in
1453  * different regions of a theme, with different visibility settings, a
1454  * different title, or other plugin-specific settings. To make this possible,
1455  * a plugin type can make use of what's known as a plugin collection.
1456  *
1457  * A plugin collection is a class that extends
1458  * \Drupal\Component\Plugin\LazyPluginCollection or one of its subclasses; there
1459  * are several examples in Drupal Core. If your plugin type uses a plugin
1460  * collection, it will usually also have a configuration entity, and the entity
1461  * class should implement
1462  * \Drupal\Core\Entity\EntityWithPluginCollectionInterface. Again, there are
1463  * several examples in Drupal Core; see also the @link config_api Configuration
1464  * API topic @endlink for more information about configuration entities.
1465  *
1466  * @section sec_create Creating a plugin of an existing type
1467  * Assuming the plugin type uses annotation-based discovery, in order to create
1468  * a plugin of an existing type, you will be creating a class. This class must:
1469  * - Implement the plugin interface, so that it has the required methods
1470  *   defined. Usually, you'll want to extend the plugin base class, if one has
1471  *   been provided.
1472  * - Have the right annotation in its documentation header. See the
1473  *   @link annotation Annotation topic @endlink for more information about
1474  *   annotation.
1475  * - Be in the right plugin namespace, in order to be discovered.
1476  * Often, the easiest way to make sure this happens is to find an existing
1477  * example of a working plugin class of the desired type, and copy it into your
1478  * module as a starting point.
1479  *
1480  * You can also create a plugin derivative, which allows your plugin class
1481  * to present itself to the user interface as multiple plugins. To do this,
1482  * in addition to the plugin class, you'll need to create a separate plugin
1483  * derivative class implementing
1484  * \Drupal\Component\Plugin\Derivative\DerivativeInterface. The classes
1485  * \Drupal\system\Plugin\Block\SystemMenuBlock (plugin class) and
1486  * \Drupal\system\Plugin\Derivative\SystemMenuBlock (derivative class) are a
1487  * good example to look at.
1488  *
1489  * @section sec_use Performing tasks involving plugins
1490  * Here are the steps to follow to perform a task that involves plugins:
1491  * - Locate the machine name of the plugin manager service, and instantiate the
1492  *   service. See the @link container Services topic @endlink for more
1493  *   information on how to do this.
1494  * - On the plugin manager class, use methods like getDefinition(),
1495  *   getDefinitions(), or other methods specific to particular plugin managers
1496  *   to retrieve information about either specific plugins or the entire list of
1497  *   defined plugins.
1498  * - Call the createInstance() method on the plugin manager to instantiate
1499  *   individual plugin objects.
1500  * - Call methods on the plugin objects to perform the desired tasks.
1501  *
1502  * @see annotation
1503  * @}
1504  */
1505
1506 /**
1507  * @defgroup oo_conventions Objected-oriented programming conventions
1508  * @{
1509  * PSR-4, namespaces, class naming, and other conventions.
1510  *
1511  * A lot of the PHP code in Drupal is object oriented (OO), making use of
1512  * @link http://php.net/manual/language.oop5.php PHP classes, interfaces, and traits @endlink
1513  * (which are loosely referred to as "classes" in the rest of this topic). The
1514  * following conventions and standards apply to this version of Drupal:
1515  * - Each class must be in its own file.
1516  * - Classes must be namespaced. If a module defines a class, the namespace
1517  *   must start with \Drupal\module_name. If it is defined by Drupal Core for
1518  *   use across many modules, the namespace should be \Drupal\Core or
1519  *   \Drupal\Component, with the exception of the global class \Drupal. See
1520  *   https://www.drupal.org/node/1353118 for more about namespaces.
1521  * - In order for the PSR-4-based class auto-loader to find the class, it must
1522  *   be located in a directory corresponding to the namespace. For
1523  *   module-defined classes, if the namespace is \Drupal\module_name\foo\bar,
1524  *   then the class goes under the main module directory in directory
1525  *   src/foo/bar. For Drupal-wide classes, if the namespace is
1526  *   \Drupal\Core\foo\bar, then it goes in directory
1527  *   core/lib/Drupal/Core/foo/bar. See https://www.drupal.org/node/2156625 for
1528  *   more information about PSR-4.
1529  * - Some classes have annotations added to their documentation headers. See
1530  *   the @link annotation Annotation topic @endlink for more information.
1531  * - Standard plugin discovery requires particular namespaces and annotation
1532  *   for most plugin classes. See the
1533  *   @link plugin_api Plugin API topic @endlink for more information.
1534  * - There are project-wide coding standards for OO code, including naming:
1535  *   https://www.drupal.org/node/608152
1536  * - Documentation standards for classes are covered on:
1537  *   https://www.drupal.org/coding-standards/docs#classes
1538  * @}
1539  */
1540
1541 /**
1542  * @defgroup listing_page_class Page header for Classes page
1543  * @{
1544  * Introduction to classes
1545  *
1546  * A lot of the PHP code in Drupal is object oriented (OO), making use of
1547  * @link http://php.net/manual/language.oop5.php PHP classes, interfaces, and traits. @endlink
1548  * See the
1549  * @link oo_conventions Objected-oriented programming conventions @endlink
1550  * for more information.
1551  *
1552  * @see oo_conventions
1553  *
1554  * @}
1555  */
1556
1557 /**
1558  * @defgroup listing_page_namespace Page header for Namespaces page
1559  * @{
1560  * Introduction to namespaces
1561  *
1562  * PHP classes, interfaces, and traits in Drupal are
1563  * @link http://php.net/manual/en/language.namespaces.rationale.php namespaced. @endlink
1564  * See the
1565  * @link oo_conventions Objected-oriented programming conventions @endlink
1566  * for more information.
1567  *
1568  * @see oo_conventions
1569  *
1570  * @}
1571  */
1572
1573 /**
1574  * @defgroup best_practices Best practices for developers
1575  * @{
1576  * Overview of standards and best practices for developers
1577  *
1578  * Ideally, all code that is included in Drupal Core and contributed modules,
1579  * themes, and distributions will be secure, internationalized, maintainable,
1580  * and efficient. In order to facilitate this, the Drupal community has
1581  * developed a set of guidelines and standards for developers to follow. Most of
1582  * these standards can be found under
1583  * @link https://www.drupal.org/developing/best-practices Best practices on Drupal.org @endlink
1584  *
1585  * Standards and best practices that developers should be aware of include:
1586  * - Security: https://www.drupal.org/writing-secure-code and the
1587  *   @link sanitization Sanitization functions topic @endlink
1588  * - Coding standards: https://www.drupal.org/coding-standards
1589  *   and https://www.drupal.org/coding-standards/docs
1590  * - Accessibility: https://www.drupal.org/node/1637990 (modules) and
1591  *   https://www.drupal.org/node/464472 (themes)
1592  * - Usability: https://www.drupal.org/ui-standards
1593  * - Internationalization: @link i18n Internationalization topic @endlink
1594  * - Automated testing: @link testing Automated tests topic @endlink
1595  * @}
1596  */
1597
1598 /**
1599  * @defgroup utility Utility classes and functions
1600  * @{
1601  * Overview of utility classes and functions for developers.
1602  *
1603  * Drupal provides developers with a variety of utility functions that make it
1604  * easier and more efficient to perform tasks that are either really common,
1605  * tedious, or difficult. Utility functions help to reduce code duplication and
1606  * should be used in place of one-off code whenever possible.
1607  *
1608  * @see common.inc
1609  * @see file
1610  * @see format
1611  * @see php_wrappers
1612  * @see sanitization
1613  * @see transliteration
1614  * @see validation
1615  * @}
1616  */
1617
1618 /**
1619  * @defgroup hooks Hooks
1620  * @{
1621  * Define functions that alter the behavior of Drupal core.
1622  *
1623  * One way for modules to alter the core behavior of Drupal (or another module)
1624  * is to use hooks. Hooks are specially-named functions that a module defines
1625  * (this is known as "implementing the hook"), which are discovered and called
1626  * at specific times to alter or add to the base behavior or data (this is
1627  * known as "invoking the hook"). Each hook has a name (example:
1628  * hook_batch_alter()), a defined set of parameters, and a defined return value.
1629  * Your modules can implement hooks that are defined by Drupal core or other
1630  * modules that they interact with. Your modules can also define their own
1631  * hooks, in order to let other modules interact with them.
1632  *
1633  * To implement a hook:
1634  * - Locate the documentation for the hook. Hooks are documented in *.api.php
1635  *   files, by defining functions whose name starts with "hook_" (these
1636  *   files and their functions are never loaded by Drupal -- they exist solely
1637  *   for documentation). The function should have a documentation header, as
1638  *   well as a sample function body. For example, in the core file
1639  *   system.api.php, you can find hooks such as hook_batch_alter(). Also, if
1640  *   you are viewing this documentation on an API reference site, the Core
1641  *   hooks will be listed in this topic.
1642  * - Copy the function to your module's .module file.
1643  * - Change the name of the function, substituting your module's short name
1644  *   (name of the module's directory, and .info.yml file without the extension)
1645  *   for the "hook" part of the sample function name. For instance, to implement
1646  *   hook_batch_alter(), you would rename it to my_module_batch_alter().
1647  * - Edit the documentation for the function (normally, your implementation
1648  *   should just have one line saying "Implements hook_batch_alter().").
1649  * - Edit the body of the function, substituting in what you need your module
1650  *   to do.
1651  *
1652  * To define a hook:
1653  * - Choose a unique name for your hook. It should start with "hook_", followed
1654  *   by your module's short name.
1655  * - Provide documentation in a *.api.php file in your module's main
1656  *   directory. See the "implementing" section above for details of what this
1657  *   should contain (parameters, return value, and sample function body).
1658  * - Invoke the hook in your module's code.
1659  *
1660  * To invoke a hook, use methods on
1661  * \Drupal\Core\Extension\ModuleHandlerInterface such as alter(), invoke(),
1662  * and invokeAll(). You can obtain a module handler by calling
1663  * \Drupal::moduleHandler(), or getting the 'module_handler' service on an
1664  * injected container.
1665  *
1666  * @see extending
1667  * @see themeable
1668  * @see callbacks
1669  * @see \Drupal\Core\Extension\ModuleHandlerInterface
1670  * @see \Drupal::moduleHandler()
1671  *
1672  * @}
1673  */
1674
1675 /**
1676  * @defgroup callbacks Callbacks
1677  * @{
1678  * Callback function signatures.
1679  *
1680  * Drupal's API sometimes uses callback functions to allow you to define how
1681  * some type of processing happens. A callback is a function with a defined
1682  * signature, which you define in a module. Then you pass the function name as
1683  * a parameter to a Drupal API function or return it as part of a hook
1684  * implementation return value, and your function is called at an appropriate
1685  * time. For instance, when setting up batch processing you might need to
1686  * provide a callback function for each processing step and/or a callback for
1687  * when processing is finished; you would do that by defining these functions
1688  * and passing their names into the batch setup function.
1689  *
1690  * Callback function signatures, like hook definitions, are described by
1691  * creating and documenting dummy functions in a *.api.php file; normally, the
1692  * dummy callback function's name should start with "callback_", and you should
1693  * document the parameters and return value and provide a sample function body.
1694  * Then your API documentation can refer to this callback function in its
1695  * documentation. A user of your API can usually name their callback function
1696  * anything they want, although a standard name would be to replace "callback_"
1697  * with the module name.
1698  *
1699  * @see hooks
1700  * @see themeable
1701  *
1702  * @}
1703  */
1704
1705 /**
1706  * @defgroup form_api Form generation
1707  * @{
1708  * Describes how to generate and manipulate forms and process form submissions.
1709  *
1710  * Drupal provides a Form API in order to achieve consistency in its form
1711  * processing and presentation, while simplifying code and reducing the amount
1712  * of HTML that must be explicitly generated by a module.
1713  *
1714  * @section generating_forms Creating forms
1715  * Forms are defined as classes that implement the
1716  * \Drupal\Core\Form\FormInterface and are built using the
1717  * \Drupal\Core\Form\FormBuilder class. Drupal provides a couple of utility
1718  * classes that can be extended as a starting point for most basic forms, the
1719  * most commonly used of which is \Drupal\Core\Form\FormBase. FormBuilder
1720  * handles the low level processing of forms such as rendering the necessary
1721  * HTML, initial processing of incoming $_POST data, and delegating to your
1722  * implementation of FormInterface for validation and processing of submitted
1723  * data.
1724  *
1725  * Here is an example of a Form class:
1726  * @code
1727  * namespace Drupal\mymodule\Form;
1728  *
1729  * use Drupal\Core\Form\FormBase;
1730  * use Drupal\Core\Form\FormStateInterface;
1731  *
1732  * class ExampleForm extends FormBase {
1733  *   public function getFormId() {
1734  *     // Unique ID of the form.
1735  *     return 'example_form';
1736  *   }
1737  *
1738  *   public function buildForm(array $form, FormStateInterface $form_state) {
1739  *     // Create a $form API array.
1740  *     $form['phone_number'] = array(
1741  *       '#type' => 'tel',
1742  *       '#title' => $this->t('Your phone number'),
1743  *     );
1744  *     $form['save'] = array(
1745  *       '#type' => 'submit',
1746  *       '#value' => $this->t('Save'),
1747  *     );
1748  *     return $form;
1749  *   }
1750  *
1751  *   public function validateForm(array &$form, FormStateInterface $form_state) {
1752  *     // Validate submitted form data.
1753  *   }
1754  *
1755  *   public function submitForm(array &$form, FormStateInterface $form_state) {
1756  *     // Handle submitted form data.
1757  *   }
1758  * }
1759  * @endcode
1760  *
1761  * @section retrieving_forms Retrieving and displaying forms
1762  * \Drupal::formBuilder()->getForm() should be used to handle retrieving,
1763  * processing, and displaying a rendered HTML form. Given the ExampleForm
1764  * defined above,
1765  * \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm') would
1766  * return the rendered HTML of the form defined by ExampleForm::buildForm(), or
1767  * call the validateForm() and submitForm(), methods depending on the current
1768  * processing state.
1769  *
1770  * The argument to \Drupal::formBuilder()->getForm() is the name of a class that
1771  * implements FormInterface. Any additional arguments passed to the getForm()
1772  * method will be passed along as additional arguments to the
1773  * ExampleForm::buildForm() method.
1774  *
1775  * For example:
1776  * @code
1777  * $extra = '612-123-4567';
1778  * $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm', $extra);
1779  * ...
1780  * public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL)
1781  *   $form['phone_number'] = array(
1782  *     '#type' => 'tel',
1783  *     '#title' => $this->t('Your phone number'),
1784  *     '#value' => $extra,
1785  *   );
1786  *   return $form;
1787  * }
1788  * @endcode
1789  *
1790  * Alternatively, forms can be built directly via the routing system which will
1791  * take care of calling \Drupal::formBuilder()->getForm(). The following example
1792  * demonstrates the use of a routing.yml file to display a form at the given
1793  * route.
1794  *
1795  * @code
1796  * example.form:
1797  *   path: '/example-form'
1798  *   defaults:
1799  *     _title: 'Example form'
1800  *     _form: '\Drupal\mymodule\Form\ExampleForm'
1801  * @endcode
1802  *
1803  * The $form argument to form-related functions is a specialized render array
1804  * containing the elements and properties of the form. For more about render
1805  * arrays, see the @link theme_render Render API topic. @endlink For more
1806  * detailed explanations of the Form API workflow, see the
1807  * @link https://www.drupal.org/node/2117411 Form API documentation section. @endlink
1808  * In addition, there is a set of Form API tutorials in the
1809  * @link https://www.drupal.org/project/examples Examples for Developers project. @endlink
1810  *
1811  * In the form builder, validation, submission, and other form methods,
1812  * $form_state is the primary influence on the processing of the form and is
1813  * passed to most methods, so they can use it to communicate with the form
1814  * system and each other. $form_state is an object that implements
1815  * \Drupal\Core\Form\FormStateInterface.
1816  * @}
1817  */
1818
1819 /**
1820  * @defgroup queue Queue operations
1821  * @{
1822  * Queue items to allow later processing.
1823  *
1824  * The queue system allows placing items in a queue and processing them later.
1825  * The system tries to ensure that only one consumer can process an item.
1826  *
1827  * Before a queue can be used it needs to be created by
1828  * Drupal\Core\Queue\QueueInterface::createQueue().
1829  *
1830  * Items can be added to the queue by passing an arbitrary data object to
1831  * Drupal\Core\Queue\QueueInterface::createItem().
1832  *
1833  * To process an item, call Drupal\Core\Queue\QueueInterface::claimItem() and
1834  * specify how long you want to have a lease for working on that item.
1835  * When finished processing, the item needs to be deleted by calling
1836  * Drupal\Core\Queue\QueueInterface::deleteItem(). If the consumer dies, the
1837  * item will be made available again by the Drupal\Core\Queue\QueueInterface
1838  * implementation once the lease expires. Another consumer will then be able to
1839  * receive it when calling Drupal\Core\Queue\QueueInterface::claimItem().
1840  * Due to this, the processing code should be aware that an item might be handed
1841  * over for processing more than once.
1842  *
1843  * The $item object used by the Drupal\Core\Queue\QueueInterface can contain
1844  * arbitrary metadata depending on the implementation. Systems using the
1845  * interface should only rely on the data property which will contain the
1846  * information passed to Drupal\Core\Queue\QueueInterface::createItem().
1847  * The full queue item returned by Drupal\Core\Queue\QueueInterface::claimItem()
1848  * needs to be passed to Drupal\Core\Queue\QueueInterface::deleteItem() once
1849  * processing is completed.
1850  *
1851  * There are two kinds of queue backends available: reliable, which preserves
1852  * the order of messages and guarantees that every item will be executed at
1853  * least once. The non-reliable kind only does a best effort to preserve order
1854  * in messages and to execute them at least once but there is a small chance
1855  * that some items get lost. For example, some distributed back-ends like
1856  * Amazon SQS will be managing jobs for a large set of producers and consumers
1857  * where a strict FIFO ordering will likely not be preserved. Another example
1858  * would be an in-memory queue backend which might lose items if it crashes.
1859  * However, such a backend would be able to deal with significantly more writes
1860  * than a reliable queue and for many tasks this is more important. See
1861  * aggregator_cron() for an example of how to effectively use a non-reliable
1862  * queue. Another example is doing Twitter statistics -- the small possibility
1863  * of losing a few items is insignificant next to power of the queue being able
1864  * to keep up with writes. As described in the processing section, regardless
1865  * of the queue being reliable or not, the processing code should be aware that
1866  * an item might be handed over for processing more than once (because the
1867  * processing code might time out before it finishes).
1868  * @}
1869  */
1870
1871 /**
1872  * @defgroup annotation Annotations
1873  * @{
1874  * Annotations for class discovery and metadata description.
1875  *
1876  * The Drupal plugin system has a set of reusable components that developers
1877  * can use, override, and extend in their modules. Most of the plugins use
1878  * annotations, which let classes register themselves as plugins and describe
1879  * their metadata. (Annotations can also be used for other purposes, though
1880  * at the moment, Drupal only uses them for the plugin system.)
1881  *
1882  * To annotate a class as a plugin, add code similar to the following to the
1883  * end of the documentation block immediately preceding the class declaration:
1884  * @code
1885  * * @ContentEntityType(
1886  * *   id = "comment",
1887  * *   label = @Translation("Comment"),
1888  * *   ...
1889  * *   base_table = "comment"
1890  * * )
1891  * @endcode
1892  *
1893  * Note that you must use double quotes; single quotes will not work in
1894  * annotations.
1895  *
1896  * Some annotation types, which extend the "@ PluginID" annotation class, have
1897  * only a single 'id' key in their annotation. For these, it is possible to use
1898  * a shorthand annotation. For example:
1899  * @code
1900  * * @ViewsArea("entity")
1901  * @endcode
1902  * in place of
1903  * @code
1904  * * @ViewsArea(
1905  * *   id = "entity"
1906  * *)
1907  * @endcode
1908  *
1909  * The available annotation classes are listed in this topic, and can be
1910  * identified when you are looking at the Drupal source code by having
1911  * "@ Annotation" in their documentation blocks (without the space after @). To
1912  * find examples of annotation for a particular annotation class, such as
1913  * EntityType, look for class files that have an @ annotation section using the
1914  * annotation class.
1915  *
1916  * @see plugin_translatable
1917  * @see plugin_context
1918  *
1919  * @}
1920  */
1921
1922 /**
1923  * @addtogroup hooks
1924  * @{
1925  */
1926
1927 /**
1928  * Perform periodic actions.
1929  *
1930  * Modules that require some commands to be executed periodically can
1931  * implement hook_cron(). The engine will then call the hook whenever a cron
1932  * run happens, as defined by the administrator. Typical tasks managed by
1933  * hook_cron() are database maintenance, backups, recalculation of settings
1934  * or parameters, automated mailing, and retrieving remote data.
1935  *
1936  * Short-running or non-resource-intensive tasks can be executed directly in
1937  * the hook_cron() implementation.
1938  *
1939  * Long-running tasks and tasks that could time out, such as retrieving remote
1940  * data, sending email, and intensive file tasks, should use the queue API
1941  * instead of executing the tasks directly. To do this, first define one or
1942  * more queues via a \Drupal\Core\Annotation\QueueWorker plugin. Then, add items
1943  * that need to be processed to the defined queues.
1944  */
1945 function hook_cron() {
1946   // Short-running operation example, not using a queue:
1947   // Delete all expired records since the last cron run.
1948   $expires = \Drupal::state()->get('mymodule.last_check', 0);
1949   \Drupal::database()->delete('mymodule_table')
1950     ->condition('expires', $expires, '>=')
1951     ->execute();
1952   \Drupal::state()->set('mymodule.last_check', REQUEST_TIME);
1953
1954   // Long-running operation example, leveraging a queue:
1955   // Queue news feeds for updates once their refresh interval has elapsed.
1956   $queue = \Drupal::queue('aggregator_feeds');
1957   $ids = \Drupal::entityManager()->getStorage('aggregator_feed')->getFeedIdsToRefresh();
1958   foreach (Feed::loadMultiple($ids) as $feed) {
1959     if ($queue->createItem($feed)) {
1960       // Add timestamp to avoid queueing item more than once.
1961       $feed->setQueuedTime(REQUEST_TIME);
1962       $feed->save();
1963     }
1964   }
1965   $ids = \Drupal::entityQuery('aggregator_feed')
1966     ->condition('queued', REQUEST_TIME - (3600 * 6), '<')
1967     ->execute();
1968   if ($ids) {
1969     $feeds = Feed::loadMultiple($ids);
1970     foreach ($feeds as $feed) {
1971       $feed->setQueuedTime(0);
1972       $feed->save();
1973     }
1974   }
1975 }
1976
1977 /**
1978  * Alter available data types for typed data wrappers.
1979  *
1980  * @param array $data_types
1981  *   An array of data type information.
1982  *
1983  * @see hook_data_type_info()
1984  */
1985 function hook_data_type_info_alter(&$data_types) {
1986   $data_types['email']['class'] = '\Drupal\mymodule\Type\Email';
1987 }
1988
1989 /**
1990  * Alter cron queue information before cron runs.
1991  *
1992  * Called by \Drupal\Core\Cron to allow modules to alter cron queue settings
1993  * before any jobs are processesed.
1994  *
1995  * @param array $queues
1996  *   An array of cron queue information.
1997  *
1998  * @see \Drupal\Core\QueueWorker\QueueWorkerInterface
1999  * @see \Drupal\Core\Annotation\QueueWorker
2000  * @see \Drupal\Core\Cron
2001  */
2002 function hook_queue_info_alter(&$queues) {
2003   // This site has many feeds so let's spend 90 seconds on each cron run
2004   // updating feeds instead of the default 60.
2005   $queues['aggregator_feeds']['cron']['time'] = 90;
2006 }
2007
2008 /**
2009  * Alter an email message created with MailManagerInterface->mail().
2010  *
2011  * hook_mail_alter() allows modification of email messages created and sent
2012  * with MailManagerInterface->mail(). Usage examples include adding and/or
2013  * changing message text, message fields, and message headers.
2014  *
2015  * Email messages sent using functions other than MailManagerInterface->mail()
2016  * will not invoke hook_mail_alter(). For example, a contributed module directly
2017  * calling the MailInterface->mail() or PHP mail() function will not invoke
2018  * this hook. All core modules use MailManagerInterface->mail() for messaging,
2019  * it is best practice but not mandatory in contributed modules.
2020  *
2021  * @param $message
2022  *   An array containing the message data. Keys in this array include:
2023  *   - 'id':
2024  *     The MailManagerInterface->mail() id of the message. Look at module source
2025  *     code or MailManagerInterface->mail() for possible id values.
2026  *   - 'to':
2027  *     The address or addresses the message will be sent to. The
2028  *     formatting of this string must comply with RFC 2822.
2029  *   - 'from':
2030  *     The address the message will be marked as being from, which is
2031  *     either a custom address or the site-wide default email address.
2032  *   - 'subject':
2033  *     Subject of the email to be sent. This must not contain any newline
2034  *     characters, or the email may not be sent properly.
2035  *   - 'body':
2036  *     An array of strings or objects that implement
2037  *     \Drupal\Component\Render\MarkupInterface containing the message text. The
2038  *     message body is created by concatenating the individual array strings
2039  *     into a single text string using "\n\n" as a separator.
2040  *   - 'headers':
2041  *     Associative array containing mail headers, such as From, Sender,
2042  *     MIME-Version, Content-Type, etc.
2043  *   - 'params':
2044  *     An array of optional parameters supplied by the caller of
2045  *     MailManagerInterface->mail() that is used to build the message before
2046  *     hook_mail_alter() is invoked.
2047  *   - 'language':
2048  *     The language object used to build the message before hook_mail_alter()
2049  *     is invoked.
2050  *   - 'send':
2051  *     Set to FALSE to abort sending this email message.
2052  *
2053  * @see \Drupal\Core\Mail\MailManagerInterface::mail()
2054  */
2055 function hook_mail_alter(&$message) {
2056   if ($message['id'] == 'modulename_messagekey') {
2057     if (!example_notifications_optin($message['to'], $message['id'])) {
2058       // If the recipient has opted to not receive such messages, cancel
2059       // sending.
2060       $message['send'] = FALSE;
2061       return;
2062     }
2063     $message['body'][] = "--\nMail sent out from " . \Drupal::config('system.site')->get('name');
2064   }
2065 }
2066
2067 /**
2068  * Prepares a message based on parameters;
2069  *
2070  * This hook is called from MailManagerInterface->mail(). Note that hook_mail(),
2071  * unlike hook_mail_alter(), is only called on the $module argument to
2072  * MailManagerInterface->mail(), not all modules.
2073  *
2074  * @param $key
2075  *   An identifier of the mail.
2076  * @param $message
2077  *   An array to be filled in. Elements in this array include:
2078  *   - id: An ID to identify the mail sent. Look at module source code or
2079  *     MailManagerInterface->mail() for possible id values.
2080  *   - to: The address or addresses the message will be sent to. The
2081  *     formatting of this string must comply with RFC 2822.
2082  *   - subject: Subject of the email to be sent. This must not contain any
2083  *     newline characters, or the mail may not be sent properly.
2084  *     MailManagerInterface->mail() sets this to an empty
2085  *     string when the hook is invoked.
2086  *   - body: An array of lines containing the message to be sent. Drupal will
2087  *     format the correct line endings for you. MailManagerInterface->mail()
2088  *     sets this to an empty array when the hook is invoked. The array may
2089  *     contain either strings or objects implementing
2090  *     \Drupal\Component\Render\MarkupInterface.
2091  *   - from: The address the message will be marked as being from, which is
2092  *     set by MailManagerInterface->mail() to either a custom address or the
2093  *     site-wide default email address when the hook is invoked.
2094  *   - headers: Associative array containing mail headers, such as From,
2095  *     Sender, MIME-Version, Content-Type, etc.
2096  *     MailManagerInterface->mail() pre-fills several headers in this array.
2097  * @param $params
2098  *   An array of parameters supplied by the caller of
2099  *   MailManagerInterface->mail().
2100  *
2101  * @see \Drupal\Core\Mail\MailManagerInterface::mail()
2102  */
2103 function hook_mail($key, &$message, $params) {
2104   $account = $params['account'];
2105   $context = $params['context'];
2106   $variables = [
2107     '%site_name' => \Drupal::config('system.site')->get('name'),
2108     '%username' => $account->getDisplayName(),
2109   ];
2110   if ($context['hook'] == 'taxonomy') {
2111     $entity = $params['entity'];
2112     $vocabulary = Vocabulary::load($entity->id());
2113     $variables += [
2114       '%term_name' => $entity->name,
2115       '%term_description' => $entity->description,
2116       '%term_id' => $entity->id(),
2117       '%vocabulary_name' => $vocabulary->label(),
2118       '%vocabulary_description' => $vocabulary->getDescription(),
2119       '%vocabulary_id' => $vocabulary->id(),
2120     ];
2121   }
2122
2123   // Node-based variable translation is only available if we have a node.
2124   if (isset($params['node'])) {
2125     /** @var \Drupal\node\NodeInterface $node */
2126     $node = $params['node'];
2127     $variables += [
2128       '%uid' => $node->getOwnerId(),
2129       '%url' => $node->url('canonical', ['absolute' => TRUE]),
2130       '%node_type' => node_get_type_label($node),
2131       '%title' => $node->getTitle(),
2132       '%teaser' => $node->teaser,
2133       '%body' => $node->body,
2134     ];
2135   }
2136   $subject = strtr($context['subject'], $variables);
2137   $body = strtr($context['message'], $variables);
2138   $message['subject'] .= str_replace(["\r", "\n"], '', $subject);
2139   $message['body'][] = MailFormatHelper::htmlToText($body);
2140 }
2141
2142 /**
2143  * Alter the list of mail backend plugin definitions.
2144  *
2145  * @param array $info
2146  *   The mail backend plugin definitions to be altered.
2147  *
2148  * @see \Drupal\Core\Annotation\Mail
2149  * @see \Drupal\Core\Mail\MailManager
2150  */
2151 function hook_mail_backend_info_alter(&$info) {
2152   unset($info['test_mail_collector']);
2153 }
2154
2155 /**
2156  * Alter the default country list.
2157  *
2158  * @param $countries
2159  *   The associative array of countries keyed by two-letter country code.
2160  *
2161  * @see \Drupal\Core\Locale\CountryManager::getList()
2162  */
2163 function hook_countries_alter(&$countries) {
2164   // Elbonia is now independent, so add it to the country list.
2165   $countries['EB'] = 'Elbonia';
2166 }
2167
2168 /**
2169  * Alter display variant plugin definitions.
2170  *
2171  * @param array $definitions
2172  *   The array of display variant definitions, keyed by plugin ID.
2173  *
2174  * @see \Drupal\Core\Display\VariantManager
2175  * @see \Drupal\Core\Display\Annotation\DisplayVariant
2176  */
2177 function hook_display_variant_plugin_alter(array &$definitions) {
2178   $definitions['full_page']['admin_label'] = t('Block layout');
2179 }
2180
2181 /**
2182  * Allow modules to alter layout plugin definitions.
2183  *
2184  * @param \Drupal\Core\Layout\LayoutDefinition[] $definitions
2185  *   The array of layout definitions, keyed by plugin ID.
2186  */
2187 function hook_layout_alter(&$definitions) {
2188   // Remove a layout.
2189   unset($definitions['twocol']);
2190 }
2191
2192 /**
2193  * Flush all persistent and static caches.
2194  *
2195  * This hook asks your module to clear all of its static caches,
2196  * in order to ensure a clean environment for subsequently
2197  * invoked data rebuilds.
2198  *
2199  * Do NOT use this hook for rebuilding information. Only use it to flush custom
2200  * caches.
2201  *
2202  * Static caches using drupal_static() do not need to be reset manually.
2203  * However, all other static variables that do not use drupal_static() must be
2204  * manually reset.
2205  *
2206  * This hook is invoked by drupal_flush_all_caches(). It runs before module data
2207  * is updated and before hook_rebuild().
2208  *
2209  * @see drupal_flush_all_caches()
2210  * @see hook_rebuild()
2211  */
2212 function hook_cache_flush() {
2213   if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
2214     _update_cache_clear();
2215   }
2216 }
2217
2218 /**
2219  * Rebuild data based upon refreshed caches.
2220  *
2221  * This hook allows your module to rebuild its data based on the latest/current
2222  * module data. It runs after hook_cache_flush() and after all module data has
2223  * been updated.
2224  *
2225  * This hook is only invoked after the system has been completely cleared;
2226  * i.e., all previously cached data is known to be gone and every API in the
2227  * system is known to return current information, so your module can safely rely
2228  * on all available data to rebuild its own.
2229  *
2230  * @see hook_cache_flush()
2231  * @see drupal_flush_all_caches()
2232  */
2233 function hook_rebuild() {
2234   $themes = \Drupal::service('theme_handler')->listInfo();
2235   foreach ($themes as $theme) {
2236     _block_rehash($theme->getName());
2237   }
2238 }
2239
2240 /**
2241  * Alter the configuration synchronization steps.
2242  *
2243  * @param array $sync_steps
2244  *   A one-dimensional array of \Drupal\Core\Config\ConfigImporter method names
2245  *   or callables that are invoked to complete the import, in the order that
2246  *   they will be processed. Each callable item defined in $sync_steps should
2247  *   either be a global function or a public static method. The callable should
2248  *   accept a $context array by reference. For example:
2249  *   <code>
2250  *     function _additional_configuration_step(&$context) {
2251  *       // Do stuff.
2252  *       // If finished set $context['finished'] = 1.
2253  *     }
2254  *   </code>
2255  *   For more information on creating batches, see the
2256  *   @link batch Batch operations @endlink documentation.
2257  *
2258  * @see callback_batch_operation()
2259  * @see \Drupal\Core\Config\ConfigImporter::initialize()
2260  */
2261 function hook_config_import_steps_alter(&$sync_steps, \Drupal\Core\Config\ConfigImporter $config_importer) {
2262   $deletes = $config_importer->getUnprocessedConfiguration('delete');
2263   if (isset($deletes['field.storage.node.body'])) {
2264     $sync_steps[] = '_additional_configuration_step';
2265   }
2266 }
2267
2268 /**
2269  * Alter config typed data definitions.
2270  *
2271  * For example you can alter the typed data types representing each
2272  * configuration schema type to change default labels or form element renderers
2273  * used for configuration translation.
2274  *
2275  * If implementations of this hook add or remove configuration schema a
2276  * ConfigSchemaAlterException will be thrown. Keep in mind that there are tools
2277  * that may use the configuration schema for static analysis of configuration
2278  * files, like the string extractor for the localization system. Such systems
2279  * won't work with dynamically defined configuration schemas.
2280  *
2281  * For adding new data types use configuration schema YAML files instead.
2282  *
2283  * @param $definitions
2284  *   Associative array of configuration type definitions keyed by schema type
2285  *   names. The elements are themselves array with information about the type.
2286  *
2287  * @see \Drupal\Core\Config\TypedConfigManager
2288  * @see \Drupal\Core\Config\Schema\ConfigSchemaAlterException
2289  */
2290 function hook_config_schema_info_alter(&$definitions) {
2291   // Enhance the text and date type definitions with classes to generate proper
2292   // form elements in ConfigTranslationFormBase. Other translatable types will
2293   // appear as a one line textfield.
2294   $definitions['text']['form_element_class'] = '\Drupal\config_translation\FormElement\Textarea';
2295   $definitions['date_format']['form_element_class'] = '\Drupal\config_translation\FormElement\DateFormat';
2296 }
2297
2298 /**
2299  * Alter validation constraint plugin definitions.
2300  *
2301  * @param array[] $definitions
2302  *   The array of validation constraint definitions, keyed by plugin ID.
2303  *
2304  * @see \Drupal\Core\Validation\ConstraintManager
2305  * @see \Drupal\Core\Validation\Annotation\Constraint
2306  */
2307 function hook_validation_constraint_alter(array &$definitions) {
2308   $definitions['Null']['class'] = '\Drupal\mymodule\Validator\Constraints\MyClass';
2309 }
2310
2311 /**
2312  * @} End of "addtogroup hooks".
2313  */
2314
2315 /**
2316  * @defgroup ajax Ajax API
2317  * @{
2318  * Overview for Drupal's Ajax API.
2319  *
2320  * @section sec_overview Overview of Ajax
2321  * Ajax is the process of dynamically updating parts of a page's HTML based on
2322  * data from the server. When a specified event takes place, a PHP callback is
2323  * triggered, which performs server-side logic and may return updated markup or
2324  * JavaScript commands to run. After the return, the browser runs the JavaScript
2325  * or updates the markup on the fly, with no full page refresh necessary.
2326  *
2327  * Many different events can trigger Ajax responses, including:
2328  * - Clicking a button
2329  * - Pressing a key
2330  * - Moving the mouse
2331  *
2332  * @section sec_framework Ajax responses in forms
2333  * Forms that use the Drupal Form API (see the
2334  * @link form_api Form API topic @endlink for more information about forms) can
2335  * trigger AJAX responses. Here is an outline of the steps:
2336  * - Add property '#ajax' to a form element in your form array, to trigger an
2337  *   Ajax response.
2338  * - Write an Ajax callback to process the input and respond.
2339  * See sections below for details on these two steps.
2340  *
2341  * @subsection sub_form Adding Ajax triggers to a form
2342  * As an example of adding Ajax triggers to a form, consider editing a date
2343  * format, where the user is provided with a sample of the generated date output
2344  * as they type. To accomplish this, typing in the text field should trigger an
2345  * Ajax response. This is done in the text field form array element
2346  * in \Drupal\config_translation\FormElement\DateFormat::getFormElement():
2347  * @code
2348  * '#ajax' => array(
2349  *   'callback' => 'Drupal\config_translation\FormElement\DateFormat::ajaxSample',
2350  *   'event' => 'keyup',
2351  *   'progress' => array(
2352  *     'type' => 'throbber',
2353  *     'message' => NULL,
2354  *   ),
2355  * ),
2356  * @endcode
2357  *
2358  * As you can see from this example, the #ajax property for a form element is
2359  * an array. Here are the details of its elements, all of which are optional:
2360  * - callback: The callback to invoke to handle the server side of the
2361  *   Ajax event. More information on callbacks is below in @ref sub_callback.
2362  * - wrapper: The HTML 'id' attribute of the area where the content returned by
2363  *   the callback should be placed. Note that callbacks have a choice of
2364  *   returning content or JavaScript commands; 'wrapper' is used for content
2365  *   returns.
2366  * - method: The jQuery method for placing the new content (used with
2367  *   'wrapper'). Valid options are 'replaceWith' (default), 'append', 'prepend',
2368  *   'before', 'after', or 'html'. See
2369  *   http://api.jquery.com/category/manipulation/ for more information on these
2370  *   methods.
2371  * - effect: The jQuery effect to use when placing the new HTML (used with
2372  *   'wrapper'). Valid options are 'none' (default), 'slide', or 'fade'.
2373  * - speed: The effect speed to use (used with 'effect' and 'wrapper'). Valid
2374  *   options are 'slow' (default), 'fast', or the number of milliseconds the
2375  *   effect should run.
2376  * - event: The JavaScript event to respond to. This is selected automatically
2377  *   for the type of form element; provide a value to override the default.
2378  * - prevent: A JavaScript event to prevent when the event is triggered. For
2379  *   example, if you use event 'mousedown' on a button, you might want to
2380  *   prevent 'click' events from also being triggered.
2381  * - progress: An array indicating how to show Ajax processing progress. Can
2382  *   contain one or more of these elements:
2383  *   - type: Type of indicator: 'throbber' (default) or 'bar'.
2384  *   - message: Translated message to display.
2385  *   - url: For a bar progress indicator, URL path for determining progress.
2386  *   - interval: For a bar progress indicator, how often to update it.
2387  * - url: A \Drupal\Core\Url to which to submit the Ajax request. If omitted,
2388  *   defaults to either the same URL as the form or link destination is for
2389  *   someone with JavaScript disabled, or a slightly modified version (e.g.,
2390  *   with a query parameter added, removed, or changed) of that URL if
2391  *   necessary to support Drupal's content negotiation. It is recommended to
2392  *   omit this key and use Drupal's content negotiation rather than using
2393  *   substantially different URLs between Ajax and non-Ajax.
2394  *
2395  * @subsection sub_callback Setting up a callback to process Ajax
2396  * Once you have set up your form to trigger an Ajax response (see @ref sub_form
2397  * above), you need to write some PHP code to process the response. If you use
2398  * 'path' in your Ajax set-up, your route controller will be triggered with only
2399  * the information you provide in the URL. If you use 'callback', your callback
2400  * method is a function, which will receive the $form and $form_state from the
2401  * triggering form. You can use $form_state to get information about the
2402  * data the user has entered into the form. For instance, in the above example
2403  * for the date format preview,
2404  * \Drupal\config_translation\FormElement\DateFormat\ajaxSample() does this to
2405  * get the format string entered by the user:
2406  * @code
2407  * $format_value = \Drupal\Component\Utility\NestedArray::getValue(
2408  *   $form_state->getValues(),
2409  *   $form_state->getTriggeringElement()['#array_parents']);
2410  * @endcode
2411  *
2412  * Once you have processed the input, you have your choice of returning HTML
2413  * markup or a set of Ajax commands. If you choose to return HTML markup, you
2414  * can return it as a string or a renderable array, and it will be placed in
2415  * the defined 'wrapper' element (see documentation above in @ref sub_form).
2416  * In addition, any messages returned by drupal_get_messages(), themed as in
2417  * status-messages.html.twig, will be prepended.
2418  *
2419  * To return commands, you need to set up an object of class
2420  * \Drupal\Core\Ajax\AjaxResponse, and then use its addCommand() method to add
2421  * individual commands to it. In the date format preview example, the format
2422  * output is calculated, and then it is returned as replacement markup for a div
2423  * like this:
2424  * @code
2425  * $response = new AjaxResponse();
2426  * $response->addCommand(new ReplaceCommand(
2427  *   '#edit-date-format-suffix',
2428  *   '<small id="edit-date-format-suffix">' . $format . '</small>'));
2429  * return $response;
2430  * @endcode
2431  *
2432  * The individual commands that you can return implement interface
2433  * \Drupal\Core\Ajax\CommandInterface. Available commands provide the ability
2434  * to pop up alerts, manipulate text and markup in various ways, redirect
2435  * to a new URL, and the generic \Drupal\Core\Ajax\InvokeCommand, which
2436  * invokes an arbitrary jQuery command.
2437  *
2438  * As noted above, status messages are prepended automatically if you use the
2439  * 'wrapper' method and return HTML markup. This is not the case if you return
2440  * commands, but if you would like to show status messages, you can add
2441  * @code
2442  * array('#type' => 'status_messages')
2443  * @endcode
2444  * to a render array, use drupal_render() to render it, and add a command to
2445  * place the messages in an appropriate location.
2446  *
2447  * @section sec_other Other methods for triggering Ajax
2448  * Here are some additional methods you can use to trigger Ajax responses in
2449  * Drupal:
2450  * - Add class 'use-ajax' to a link. The link will be loaded using an Ajax
2451  *   call. When using this method, the href of the link can contain '/nojs/' as
2452  *   part of the path. When the Ajax JavaScript processes the page, it will
2453  *   convert this to '/ajax/'. The server is then able to easily tell if this
2454  *   request was made through an actual Ajax request or in a degraded state, and
2455  *   respond appropriately.
2456  * - Add class 'use-ajax-submit' to a submit button in a form. The form will
2457  *   then be submitted via Ajax to the path specified in the #action.  Like the
2458  *   ajax-submit class on links, this path will have '/nojs/' replaced with
2459  *   '/ajax/' so that the submit handler can tell if the form was submitted in a
2460  *   degraded state or not.
2461  * - Add property '#autocomplete_route_name' to a text field in a form. The
2462  *   route controller for this route must return an array of options for
2463  *   autocomplete, as a \Symfony\Component\HttpFoundation\JsonResponse object.
2464  *   See the @link menu Routing topic @endlink for more information about
2465  *   routing.
2466  */
2467
2468 /**
2469  * @} End of "defgroup ajax".
2470  */
2471
2472 /**
2473  * @defgroup service_tag Service Tags
2474  * @{
2475  * Service tags overview
2476  *
2477  * Some services have tags, which are defined in the service definition. Tags
2478  * are used to define a group of related services, or to specify some aspect of
2479  * how the service behaves. Typically, if you tag a service, your service class
2480  * must also implement a corresponding interface. Some common examples:
2481  * - access_check: Indicates a route access checking service; see the
2482  *   @link menu Menu and routing system topic @endlink for more information.
2483  * - cache.bin: Indicates a cache bin service; see the
2484  *   @link cache Cache topic @endlink for more information.
2485  * - event_subscriber: Indicates an event subscriber service. Event subscribers
2486  *   can be used for dynamic routing and route altering; see the
2487  *   @link menu Menu and routing system topic @endlink for more information.
2488  *   They can also be used for other purposes; see
2489  *   http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
2490  *   for more information.
2491  * - needs_destruction: Indicates that a destruct() method needs to be called
2492  *   at the end of a request to finalize operations, if this service was
2493  *   instantiated. Services should implement \Drupal\Core\DestructableInterface
2494  *   in this case.
2495  * - context_provider: Indicates a block context provider, used for example
2496  *   by block conditions. It has to implement
2497  *   \Drupal\Core\Plugin\Context\ContextProviderInterface.
2498  * - http_client_middleware: Indicates that the service provides a guzzle
2499  *   middleware, see
2500  *   https://guzzle.readthedocs.org/en/latest/handlers-and-middleware.html for
2501  *   more information.
2502  *
2503  * Creating a tag for a service does not do anything on its own, but tags
2504  * can be discovered or queried in a compiler pass when the container is built,
2505  * and a corresponding action can be taken. See
2506  * \Drupal\Core\Render\MainContent\MainContentRenderersPass for an example of
2507  * finding tagged services.
2508  *
2509  * See @link container Services and Dependency Injection Container @endlink for
2510  * information on services and the dependency injection container.
2511  *
2512  * @}
2513  */
2514
2515 /**
2516  * @defgroup events Events
2517  * @{
2518  * Overview of event dispatch and subscribing
2519  *
2520  * @section sec_intro Introduction and terminology
2521  * Events are part of the Symfony framework: they allow for different components
2522  * of the system to interact and communicate with each other. Each event has a
2523  * unique string name. One system component dispatches the event at an
2524  * appropriate time; many events are dispatched by Drupal core and the Symfony
2525  * framework in every request. Other system components can register as event
2526  * subscribers; when an event is dispatched, a method is called on each
2527  * registered subscriber, allowing each one to react. For more on the general
2528  * concept of events, see
2529  * http://symfony.com/doc/current/components/event_dispatcher/introduction.html
2530  *
2531  * @section sec_dispatch Dispatching events
2532  * To dispatch an event, call the
2533  * \Symfony\Component\EventDispatcher\EventDispatchInterface::dispatch() method
2534  * on the 'event_dispatcher' service (see the
2535  * @link container Services topic @endlink for more information about how to
2536  * interact with services). The first argument is the unique event name, which
2537  * you should normally define as a constant in a separate static class (see
2538  * \Symfony\Component\HttpKernel\KernelEvents and
2539  * \Drupal\Core\Config\ConfigEvents for examples). The second argument is a
2540  * \Symfony\Component\EventDispatcher\Event object; normally you will need to
2541  * extend this class, so that your event class can provide data to the event
2542  * subscribers.
2543  *
2544  * @section sec_subscribe Registering event subscribers
2545  * Here are the steps to register an event subscriber:
2546  * - Define a service in your module, tagged with 'event_subscriber' (see the
2547  *   @link container Services topic @endlink for instructions).
2548  * - Define a class for your subscriber service that implements
2549  *   \Symfony\Component\EventDispatcher\EventSubscriberInterface
2550  * - In your class, the getSubscribedEvents method returns a list of the events
2551  *   this class is subscribed to, and which methods on the class should be
2552  *   called for each one. Example:
2553  *   @code
2554  *   public static function getSubscribedEvents() {
2555  *     // Subscribe to kernel terminate with priority 100.
2556  *     $events[KernelEvents::TERMINATE][] = array('onTerminate', 100);
2557  *     // Subscribe to kernel request with default priority of 0.
2558  *     $events[KernelEvents::REQUEST][] = array('onRequest');
2559  *     return $events;
2560  *   }
2561  *   @endcode
2562  * - Write the methods that respond to the events; each one receives the
2563  *   event object provided in the dispatch as its one argument. In the above
2564  *   example, you would need to write onTerminate() and onRequest() methods.
2565  *
2566  * Note that in your getSubscribedEvents() method, you can optionally set the
2567  * priority of your event subscriber (see terminate example above). Event
2568  * subscribers with higher priority numbers get executed first; the default
2569  * priority is zero. If two event subscribers for the same event have the same
2570  * priority, the one defined in a module with a lower module weight will fire
2571  * first. Subscribers defined in the same services file are fired in
2572  * definition order. If order matters defining a priority is strongly advised
2573  * instead of relying on these two tie breaker rules as they might change in a
2574  * minor release.
2575  * @}
2576  */