[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-entity-fields-registry.php (source)

   1  <?php
   2  /**
   3   * Entity Fields API: WP_Entity_Fields_Registry class
   4   *
   5   * @package WordPress
   6   * @subpackage Entity Fields API
   7   * @since 7.2.0
   8   */
   9  
  10  /**
  11   * Holds the fields registered for entities.
  12   *
  13   * The registry maps an entity, identified by its kind and name, to its
  14   * registered field definitions keyed by id, in registration order, each
  15   * with the origins that registered and updated it, and to the script modules
  16   * registered for it, each with the ids of the fields it applies to.
  17   * register() adds fields, update() changes registered ones, and both
  18   * validate the definitions before storing them: a field that cannot be
  19   * stored is reported and skipped, and the rest of the call is stored.
  20   * register_collection() adds the fields a folder declares, see it for the
  21   * format.
  22   *
  23   * Fields are registered on the `wp_entity_fields_api_init` action, and only
  24   * there, with wp_register_entity_fields(), wp_update_entity_fields(),
  25   * wp_unregister_entity_fields(), and wp_register_entity_field_collection():
  26   * register(), update(), unregister(), and register_collection() refuse to run
  27   * unless the registry itself is firing the action, on the first read of its
  28   * fields. Firing the action by other means does not allow them to run.
  29   *
  30   * The registry is filled lazily: the first time its fields are read, it
  31   * fires the `wp_entity_fields_api_init` action, on which the default fields of every
  32   * post type and the fields of plugins are registered. A read before `init`
  33   * has completed is refused, see initialize().
  34   *
  35   * Once the action has fired the registry does not change: every reader of
  36   * a request, the REST controller as well as the import map of the editor
  37   * script, sees the same fields.
  38   *
  39   * @since 7.2.0
  40   *
  41   * @access private
  42   */
  43  class WP_Entity_Fields_Registry {
  44  
  45      /**
  46       * Registered fields, as kind => name => array of field id => definition.
  47       *
  48       * Kept nested rather than under a joined `{$kind}/{$name}` key: both parts
  49       * may contain any character, so no separator keeps two entities apart.
  50       *
  51       * @since 7.2.0
  52       * @var array<string, array<string, array<string, array>>>
  53       */
  54      protected $fields = array();
  55  
  56      /**
  57       * Registered script modules, as kind => name => array of module id =>
  58       * list of the ids of the fields the module applies to, in registration
  59       * order.
  60       *
  61       * @since 7.2.0
  62       * @var array<string, array<string, array<string, string[]>>>
  63       */
  64      protected $field_modules = array();
  65  
  66      /**
  67       * Whether the `wp_entity_fields_api_init` action has fired since the registry
  68       * was created.
  69       *
  70       * @since 7.2.0
  71       * @var bool
  72       */
  73      protected $initialized = false;
  74  
  75      /**
  76       * Whether the registry is firing the `wp_entity_fields_api_init` action, the
  77       * only time register(), update(), unregister(), and register_collection() run.
  78       *
  79       * @since 7.2.0
  80       * @var bool
  81       */
  82      protected $initializing = false;
  83  
  84      /**
  85       * The singleton instance.
  86       *
  87       * @since 7.2.0
  88       * @var WP_Entity_Fields_Registry|null
  89       */
  90      protected static $instance = null;
  91  
  92      /**
  93       * Returns the singleton instance.
  94       *
  95       * @since 7.2.0
  96       *
  97       * @return WP_Entity_Fields_Registry The registry.
  98       */
  99  	public static function get_instance() {
 100          if ( null === self::$instance ) {
 101              self::$instance = new self();
 102          }
 103  
 104          return self::$instance;
 105      }
 106  
 107      /**
 108       * Registers fields for an entity.
 109       *
 110       * The fields must be new: a field with the id of a registered field is
 111       * reported and skipped, and so is every definition after the first of an
 112       * id that appears more than once in the call. The rest of the fields of
 113       * the call are registered: a field another plugin got to first does not
 114       * cost a plugin the others. A definition that is not an array with a
 115       * non-empty string `id` is reported and skipped the same way. To change
 116       * a registered field, see update(); to replace it, unregister it first.
 117       * The script module, if any, applies to every field the call registers.
 118       * A field whose `type` DataViews does not provide is reported and
 119       * registered anyway.
 120       *
 121       * The origin is stored as the `origin` property of each field, as
 122       * `registeredBy`, replacing any `origin` the definition sets.
 123       *
 124       * @since 7.2.0
 125       *
 126       * @param string      $origin        Who registers the fields: `core`, or
 127       *                                   the slug of the plugin or theme.
 128       * @param string      $kind          The entity kind (e.g. `postType`).
 129       * @param string      $name          The entity name (e.g. `page`).
 130       * @param array[]     $fields        The list of field definitions, each with an `id`.
 131       * @param string|null $script_module The id of the script module providing
 132       *                                   the JavaScript parts of the fields, if any.
 133       * @return string[] The ids of the fields registered, in the order of the
 134       *                  call. Empty when none is, when called outside the
 135       *                  `wp_entity_fields_api_init` action, or when an argument is
 136       *                  invalid.
 137       */
 138  	public function register( $origin, $kind, $name, $fields, $script_module = null ) {
 139          if ( ! $this->validate_arguments( __METHOD__, $origin, $kind, $name, $fields, $script_module ) ) {
 140              return array();
 141          }
 142          $fields = $this->skip_invalid_definitions( __METHOD__, $kind, $name, $fields );
 143          if ( ! $fields ) {
 144              return array();
 145          }
 146  
 147          $new_fields     = array();
 148          $duplicated     = array();
 149          $registered_ids = array();
 150          foreach ( $fields as $field ) {
 151              $id = $field['id'];
 152              if ( isset( $this->fields[ $kind ][ $name ][ $id ] ) ) {
 153                  $registered_ids[ $id ] = $id;
 154              } elseif ( isset( $new_fields[ $id ] ) ) {
 155                  $duplicated[ $id ] = $id;
 156              } else {
 157                  $new_fields[ $id ] = $field;
 158              }
 159          }
 160  
 161          if ( $duplicated ) {
 162              _doing_it_wrong(
 163                  __METHOD__,
 164                  sprintf(
 165                      /* translators: 1: Entity kind, e.g. postType. 2: Entity name, e.g. page. 3: Comma-separated list of field ids. */
 166                      __( 'A field can only be registered once. These fields of %1$s "%2$s" appear more than once in the same call: %3$s. Only their first definition is registered.' ),
 167                      $kind,
 168                      $name,
 169                      implode( ', ', $duplicated )
 170                  ),
 171                  '7.2.0'
 172              );
 173          }
 174  
 175          if ( $registered_ids ) {
 176              _doing_it_wrong(
 177                  __METHOD__,
 178                  sprintf(
 179                      /* translators: 1: Entity kind, e.g. postType. 2: Entity name, e.g. page. 3: Comma-separated list of field ids. 4: update() */
 180                      __( 'A field can only be registered once. These fields of %1$s "%2$s" are skipped because they are already registered: %3$s. Use %4$s to change a registered field, or unregister it first to replace it.' ),
 181                      $kind,
 182                      $name,
 183                      implode( ', ', $registered_ids ),
 184                      '<code>update()</code>'
 185                  ),
 186                  '7.2.0'
 187              );
 188          }
 189  
 190          if ( ! $new_fields ) {
 191              return array();
 192          }
 193          $this->report_unknown_types( __METHOD__, $kind, $name, $new_fields );
 194  
 195          foreach ( $new_fields as $field ) {
 196              $this->fields[ $kind ][ $name ][ $field['id'] ] = array_merge(
 197                  $field,
 198                  array(
 199                      'origin' => array(
 200                          'registeredBy' => $origin,
 201                          'updatedBy'    => array(),
 202                      ),
 203                  )
 204              );
 205          }
 206          $ids = array_column( $new_fields, 'id' );
 207          $this->add_field_module( $kind, $name, $ids, $script_module );
 208  
 209          return $ids;
 210      }
 211  
 212      /**
 213       * Updates registered fields of an entity.
 214       *
 215       * Each definition is merged into the registered field with its id,
 216       * property by property; the field keeps its position. The fields must be
 217       * registered: a field that is not is reported and skipped, and so is a
 218       * definition that is not an array with a non-empty string `id`; the rest
 219       * of the fields of the call are updated. The script module, if any,
 220       * applies to every field the call updates, on top of the modules the
 221       * fields have. A field whose `type` DataViews does not provide is
 222       * reported and updated anyway.
 223       *
 224       * The origin is appended to the `updatedBy` list of the `origin` property
 225       * of each field, once; the rest of the `origin` property cannot be
 226       * updated, and any `origin` the definition sets is ignored.
 227       *
 228       * Like register(), it only runs on the `wp_entity_fields_api_init` action.
 229       *
 230       * @since 7.2.0
 231       *
 232       * @param string      $origin        Who updates the fields: `core`, or
 233       *                                   the slug of the plugin or theme.
 234       * @param string      $kind          The entity kind (e.g. `postType`).
 235       * @param string      $name          The entity name (e.g. `page`).
 236       * @param array[]     $fields        The list of partial field definitions,
 237       *                                   each with the `id` of a registered field.
 238       * @param string|null $script_module The id of the script module providing
 239       *                                   the JavaScript parts of the fields, if any.
 240       * @return string[] The ids of the fields updated, in the order of the
 241       *                  call. Empty when none is, when called outside the
 242       *                  `wp_entity_fields_api_init` action, or when an argument is
 243       *                  invalid.
 244       */
 245  	public function update( $origin, $kind, $name, $fields, $script_module = null ) {
 246          if ( ! $this->validate_arguments( __METHOD__, $origin, $kind, $name, $fields, $script_module ) ) {
 247              return array();
 248          }
 249          $fields = $this->skip_invalid_definitions( __METHOD__, $kind, $name, $fields );
 250          if ( ! $fields ) {
 251              return array();
 252          }
 253          $this->report_unknown_types( __METHOD__, $kind, $name, $fields );
 254  
 255          $ids              = array();
 256          $unregistered_ids = array();
 257          foreach ( $fields as $field ) {
 258              $id = $field['id'];
 259              if ( ! isset( $this->fields[ $kind ][ $name ][ $id ] ) ) {
 260                  $unregistered_ids[ $id ] = $id;
 261                  continue;
 262              }
 263  
 264              $registered   = $this->fields[ $kind ][ $name ][ $id ];
 265              $field_origin = $registered['origin'];
 266              if ( ! in_array( $origin, $field_origin['updatedBy'], true ) ) {
 267                  $field_origin['updatedBy'][] = $origin;
 268              }
 269  
 270              $this->fields[ $kind ][ $name ][ $id ] = array_merge( $registered, $field, array( 'origin' => $field_origin ) );
 271              if ( ! in_array( $id, $ids, true ) ) {
 272                  $ids[] = $id;
 273              }
 274          }
 275  
 276          if ( $unregistered_ids ) {
 277              _doing_it_wrong(
 278                  __METHOD__,
 279                  sprintf(
 280                      /* translators: 1: Entity kind, e.g. postType. 2: Entity name, e.g. page. 3: Comma-separated list of field ids. 4: register() */
 281                      __( 'Only registered fields can be updated. These fields of %1$s "%2$s" are skipped because they are not registered: %3$s. Use %4$s to add a field.' ),
 282                      $kind,
 283                      $name,
 284                      implode( ', ', $unregistered_ids ),
 285                      '<code>register()</code>'
 286                  ),
 287                  '7.2.0'
 288              );
 289          }
 290  
 291          if ( $ids ) {
 292              $this->add_field_module( $kind, $name, $ids, $script_module );
 293          }
 294  
 295          return $ids;
 296      }
 297  
 298      /**
 299       * Unregisters fields of an entity.
 300       *
 301       * Unregistering a field removes its registered definition and
 302       * drops it from the script modules that applied to it (a module left with
 303       * no field is forgotten). Unregistering every field forgets the entity:
 304       * its registered fields and script modules.
 305       *
 306       * Like register(), it only runs on the `wp_entity_fields_api_init` action, and an
 307       * invalid entity is reported and unregisters nothing. An id that is not a
 308       * non-empty string is reported and skipped, like a definition register()
 309       * cannot store.
 310       *
 311       * @since 7.2.0
 312       *
 313       * @param string        $kind The entity kind (e.g. `postType`).
 314       * @param string        $name The entity name (e.g. `page`).
 315       * @param string[]|null $ids  The ids of the fields to unregister. Default
 316       *                            null, every field of the entity.
 317       * @return array[] The list of the definitions unregistered, in
 318       *                 registration order, as get_registered() returns them.
 319       *                 Empty when none of the fields is registered, when
 320       *                 called outside the `wp_entity_fields_api_init` action, or when
 321       *                 the entity is invalid.
 322       */
 323  	public function unregister( $kind, $name, $ids = null ) {
 324          if ( ! $this->doing_entity_fields_api_init( __METHOD__ ) || ! $this->validate_entity( __METHOD__, $kind, $name ) ) {
 325              return array();
 326          }
 327  
 328          if ( null === $ids ) {
 329              $unregistered = array_values( $this->fields[ $kind ][ $name ] ?? array() );
 330              unset( $this->fields[ $kind ][ $name ], $this->field_modules[ $kind ][ $name ] );
 331              $this->forget_empty_entity( $kind, $name );
 332              return $unregistered;
 333          }
 334  
 335          $ids = $this->skip_invalid_ids( __METHOD__, $kind, $name, (array) $ids );
 336          if ( ! $ids ) {
 337              return array();
 338          }
 339  
 340          $unregistered = array_intersect_key( $this->fields[ $kind ][ $name ] ?? array(), array_flip( $ids ) );
 341          if ( empty( $unregistered ) ) {
 342              return array();
 343          }
 344  
 345          // A script module only ever applies to registered fields: register()
 346          // and update() add it for fields they store, and fields leave both
 347          // lists together here. So the fields removed are all the registry
 348          // loses, and the modules are not returned: the ones that applied to
 349          // them are listed by get_registered_field_modules(), read beforehand.
 350          $ids = array_keys( $unregistered );
 351          foreach ( $ids as $id ) {
 352              unset( $this->fields[ $kind ][ $name ][ $id ] );
 353          }
 354          foreach ( $this->field_modules[ $kind ][ $name ] ?? array() as $module => $module_ids ) {
 355              $remaining = array_values( array_diff( $module_ids, $ids ) );
 356              if ( empty( $remaining ) ) {
 357                  unset( $this->field_modules[ $kind ][ $name ][ $module ] );
 358              } else {
 359                  $this->field_modules[ $kind ][ $name ][ $module ] = $remaining;
 360              }
 361          }
 362          $this->forget_empty_entity( $kind, $name );
 363  
 364          return array_values( $unregistered );
 365      }
 366  
 367      /**
 368       * Registers the fields of a field collection.
 369       *
 370       * A collection is a folder whose `index.php` returns its configuration, with
 371       * a folder per field whose `field.php` returns the serializable part of the
 372       * field (see get_collection_fields()). Each file is required without
 373       * sharing the variables of the caller, see require_file(). The JavaScript
 374       * parts of the fields, if any, ship in the script module of the
 375       * collection. The configuration is an array with these keys:
 376       *
 377       * - `origin` (required): who registers the fields: `core`, or the slug of
 378       *   the plugin or theme. See register().
 379       * - `kind` (required): the entity kind, e.g. `postType`.
 380       * - `name` (required): the entity name, e.g. `wp_template`.
 381       * - `module` (optional): the id of the script module providing the
 382       *   JavaScript parts of the fields. Every field of the collection is
 383       *   registered with it.
 384       *
 385       * The collection registers its fields on the entity, after the fields
 386       * registered on it before, in the alphabetical order of their folders.
 387       * register() skips a field already registered for the entity, and
 388       * registers the rest of the collection. Like register(), it does not check
 389       * that the entity exists: the `/wp/v2/entity-fields` route only serves the fields
 390       * of the entities the REST API exposes.
 391       *
 392       * Fields that apply to several entities, such as the defaults every post
 393       * type derives from its supports, are registered in code: a
 394       * `wp_entity_fields_api_init` callback can read their definitions from files with
 395       * get_collection_fields() and register them on each entity with
 396       * register().
 397       *
 398       * Like register(), it only runs on the `wp_entity_fields_api_init` action. An
 399       * invalid configuration is reported with _doing_it_wrong() and skipped. So
 400       * is an invalid `field.php`, see get_collection_fields(): the rest of the
 401       * fields of the collection are registered.
 402       *
 403       * @since 7.2.0
 404       *
 405       * @param string $directory The directory of the collection.
 406       * @return bool Whether the collection is valid and all of its fields are
 407       *              registered. True as well when it has no fields; false when
 408       *              a `field.php` is skipped, or when called outside the
 409       *              `wp_entity_fields_api_init` action.
 410       */
 411  	public function register_collection( $directory ) {
 412          if ( ! $this->doing_entity_fields_api_init( __METHOD__ ) ) {
 413              return false;
 414          }
 415  
 416          $collection = $this->get_collection( __METHOD__, $directory );
 417          if ( null === $collection ) {
 418              return false;
 419          }
 420  
 421          if ( empty( $collection['fields'] ) ) {
 422              return ! $collection['skipped'];
 423          }
 424          $registered = $this->register( $collection['origin'], $collection['kind'], $collection['name'], $collection['fields'], $collection['module'] );
 425  
 426          return ! $collection['skipped'] && count( $registered ) === count( $collection['fields'] );
 427      }
 428  
 429      /**
 430       * Returns the fields of a field collection.
 431       *
 432       * A collection holds a folder per field, whose `field.php` returns the
 433       * serializable part of the field, see register_collection().
 434       *
 435       * @since 7.2.0
 436       *
 437       * @param string $directory The directory of the collection.
 438       * @return array<string, array> The fields of the collection, keyed by id, in
 439       *                              the alphabetical order of their folders. The
 440       *                              id of a field is the name of its folder,
 441       *                              unless its `field.php` sets an `id`, and it
 442       *                              comes first in the field. A `field.php`
 443       *                              that does not return an array with a
 444       *                              non-empty string id, or whose id an earlier
 445       *                              folder took, is reported and skipped.
 446       */
 447  	public function get_collection_fields( $directory ) {
 448          return $this->read_collection_fields( __METHOD__, $directory )['fields'];
 449      }
 450  
 451      /**
 452       * Returns the fields registered for an entity.
 453       *
 454       * @since 7.2.0
 455       *
 456       * @param string $kind The entity kind (e.g. `postType`).
 457       * @param string $name The entity name (e.g. `page`).
 458       * @return array[] The list of field definitions, in registration order.
 459       *                 Empty when the entity is invalid.
 460       */
 461  	public function get_registered( $kind, $name ) {
 462          if ( ! $this->validate_entity( __METHOD__, $kind, $name ) ) {
 463              return array();
 464          }
 465          $this->initialize();
 466          return array_values( $this->fields[ $kind ][ $name ] ?? array() );
 467      }
 468  
 469      /**
 470       * Returns the fields registered for every entity.
 471       *
 472       * @since 7.2.0
 473       *
 474       * @return array<string, array<string, array[]>> The lists of field
 475       *                                               definitions, keyed by
 476       *                                               kind, then by name.
 477       */
 478  	public function get_all_registered() {
 479          $this->initialize();
 480          return array_map(
 481              static function ( $entities ) {
 482                  return array_map( 'array_values', $entities );
 483              },
 484              $this->fields
 485          );
 486      }
 487  
 488      /**
 489       * Returns the script modules registered for an entity.
 490       *
 491       * @since 7.2.0
 492       *
 493       * @param string $kind The entity kind (e.g. `postType`).
 494       * @param string $name The entity name (e.g. `page`).
 495       * @return array[] {
 496       *     The script modules, in registration order. Empty when the entity
 497       *     is invalid.
 498       *
 499       *     @type array ...$0 {
 500       *         @type string   $id     The id of the script module.
 501       *         @type string[] $fields The ids of the fields the module applies
 502       *                                to, in registration order.
 503       *     }
 504       * }
 505       */
 506  	public function get_registered_field_modules( $kind, $name ) {
 507          if ( ! $this->validate_entity( __METHOD__, $kind, $name ) ) {
 508              return array();
 509          }
 510          $this->initialize();
 511          $modules = array();
 512          foreach ( $this->field_modules[ $kind ][ $name ] ?? array() as $module => $field_ids ) {
 513              $modules[] = array(
 514                  // A numeric module id is an integer as an array key.
 515                  'id'     => (string) $module,
 516                  'fields' => $field_ids,
 517              );
 518          }
 519          return $modules;
 520      }
 521  
 522      /**
 523       * Returns the ids of the script modules registered for every entity.
 524       *
 525       * @since 7.2.0
 526       *
 527       * @return array<string, array<string, string[]>> The lists of module ids,
 528       *                                                keyed by kind, then by
 529       *                                                name.
 530       */
 531  	public function get_all_registered_field_modules() {
 532          $this->initialize();
 533          /*
 534           * Keeps the module ids and drops the field ids they apply to, e.g.:
 535           *
 536           *     array(
 537           *         'postType' => array(
 538           *             'page' => array( 'my-plugin/fields', '123' ),
 539           *             'post' => array( 'my-plugin/fields' ),
 540           *         ),
 541           *     )
 542           */
 543          return array_map(
 544              static function ( $entities ) {
 545                  return array_map(
 546                      static function ( $modules ) {
 547                          // A numeric module id is an integer as an array key.
 548                          return array_map( 'strval', array_keys( $modules ) );
 549                      },
 550                      $entities
 551                  );
 552              },
 553              $this->field_modules
 554          );
 555      }
 556  
 557      /**
 558       * Fires the `wp_entity_fields_api_init` action the first time the registry
 559       * is read.
 560       *
 561       * The read is refused until `init` has completed. The registry holds the
 562       * fields of post types, and post types are not known until then: core
 563       * registers its own on `init` at priority 0, plugins theirs at the default
 564       * priority, and supports are added and removed on `init` too. The default
 565       * fields of a post type derive from its supports, and the action fires
 566       * once, so a read before or during `init` would fix the defaults from the
 567       * post types registered so far for the rest of the request.
 568       *
 569       * did_action() is true from the first `init` callback on, hence the
 570       * doing_action() check for the reads made while it runs.
 571       *
 572       * @since 7.2.0
 573       */
 574  	protected function initialize() {
 575          if ( $this->initialized ) {
 576              return;
 577          }
 578  
 579          if ( ! did_action( 'init' ) || doing_action( 'init' ) ) {
 580              _doing_it_wrong(
 581                  __METHOD__,
 582                  sprintf(
 583                      /* translators: 1: init, 2: wp_entity_fields_api_init */
 584                      __( 'The registered fields cannot be read until the %1$s action has completed: the post types and supports they derive from are registered on %1$s. Read them once %1$s has completed, or hook %2$s.' ),
 585                      '<code>init</code>',
 586                      '<code>wp_entity_fields_api_init</code>'
 587                  ),
 588                  '7.2.0'
 589              );
 590              return;
 591          }
 592  
 593          // Set before firing, so a callback reading the registry to inspect
 594          // the fields it updates does not fire the action again.
 595          $this->initialized = true;
 596  
 597          $this->initializing = true;
 598          try {
 599              /**
 600               * Fires the first time the registered fields are read, after `init`.
 601               *
 602               * Register or adjust fields here, with wp_register_entity_fields(),
 603               * wp_update_entity_fields(), and wp_unregister_entity_fields(): it is the only
 604               * time they run.
 605               *
 606               * The first read happens wherever the fields are needed: while
 607               * handling a REST request as well as on `admin_footer` of the pages
 608               * that load the editor script. A callback should register fields and
 609               * nothing else; script modules, styles, and their enqueue hooks
 610               * belong on `init`.
 611               *
 612               * @since 7.2.0
 613               */
 614              do_action( 'wp_entity_fields_api_init' );
 615          } finally {
 616              $this->initializing = false;
 617          }
 618      }
 619  
 620      /**
 621       * Checks that the registry is firing the `wp_entity_fields_api_init` action,
 622       * as register(), update(), unregister(), and register_collection() require.
 623       *
 624       * Outside the action a registration would either come before the
 625       * defaults, which could then not be registered, or after the fields have been read
 626       * and the import map of the editor script built from them. Refusing
 627       * keeps the registry immutable once read, even when the action is fired
 628       * again with do_action(), which is why the registry tracks its own firing
 629       * rather than check doing_action().
 630       *
 631       * @since 7.2.0
 632       *
 633       * @param string $method The calling method, for the notice.
 634       * @return bool Whether the action is firing.
 635       */
 636  	protected function doing_entity_fields_api_init( $method ) {
 637          if ( $this->initializing ) {
 638              return true;
 639          }
 640  
 641          _doing_it_wrong(
 642              $method,
 643              sprintf(
 644                  /* translators: %s: wp_entity_fields_api_init */
 645                  __( 'Fields can only be registered, updated, and unregistered on the %s action.' ),
 646                  '<code>wp_entity_fields_api_init</code>'
 647              ),
 648              '7.2.0'
 649          );
 650          return false;
 651      }
 652  
 653      /**
 654       * Reports the fields whose `type` is not one the REST schema of the
 655       * fields lists, with _doing_it_wrong(). Those are the types DataViews
 656       * provides a control for: a misspelt type is otherwise silent, the field
 657       * renders without a control. A missing `type` is fine.
 658       *
 659       * @since 7.2.0
 660       *
 661       * @param string  $method The calling method, for the notice.
 662       * @param string  $kind   The entity kind.
 663       * @param string  $name   The entity name.
 664       * @param array[] $fields The field definitions.
 665       */
 666  	protected function report_unknown_types( $method, $kind, $name, $fields ) {
 667          $type_schema = ( new WP_REST_Entity_Fields_Controller() )->get_item_schema()['properties']['fields']['items']['properties']['type'];
 668          $unknown     = array();
 669          foreach ( $fields as $field ) {
 670              if ( ! isset( $field['type'] ) ) {
 671                  continue;
 672              }
 673              $valid = rest_validate_value_from_schema( $field['type'], $type_schema, 'type' );
 674              if ( is_wp_error( $valid ) ) {
 675                  $unknown[] = sprintf( '%s (%s)', $field['id'], $valid->get_error_message() );
 676              }
 677          }
 678          if ( ! $unknown ) {
 679              return;
 680          }
 681          _doing_it_wrong(
 682              $method,
 683              sprintf(
 684                  /* translators: 1: Entity kind, e.g. postType. 2: Entity name, e.g. page. 3: Comma-separated list of field ids, each with the error of its type. */
 685                  __( 'These fields of %1$s "%2$s" have a type DataViews does not provide, so they render without a control: %3$s' ),
 686                  $kind,
 687                  $name,
 688                  implode( ', ', $unknown )
 689              ),
 690              '7.2.0'
 691          );
 692      }
 693  
 694      /**
 695       * Validates the arguments of register() and update().
 696       *
 697       * @since 7.2.0
 698       *
 699       * @param string $method        The calling method, for the notice.
 700       * @param mixed  $origin        The origin.
 701       * @param mixed  $kind          The entity kind.
 702       * @param mixed  $name          The entity name.
 703       * @param mixed  $fields        The field definitions.
 704       * @param mixed  $script_module The script module id, if any.
 705       * @return bool Whether the call may proceed: the `wp_entity_fields_api_init` action
 706       *              is firing and the arguments are valid.
 707       */
 708  	protected function validate_arguments( $method, $origin, $kind, $name, $fields, $script_module ) {
 709          if ( ! $this->doing_entity_fields_api_init( $method ) ) {
 710              return false;
 711          }
 712  
 713          if ( ! is_string( $origin ) || '' === $origin ) {
 714              _doing_it_wrong(
 715                  $method,
 716                  __( 'The origin must be a non-empty string.' ),
 717                  '7.2.0'
 718              );
 719              return false;
 720          }
 721  
 722          if ( ! $this->validate_entity( $method, $kind, $name ) ) {
 723              return false;
 724          }
 725  
 726          if ( ! is_array( $fields ) || empty( $fields ) || ! array_is_list( $fields ) ) {
 727              _doing_it_wrong(
 728                  $method,
 729                  __( 'The fields must be a list of non-empty field definitions.' ),
 730                  '7.2.0'
 731              );
 732              return false;
 733          }
 734  
 735          if ( null !== $script_module && ( ! is_string( $script_module ) || '' === $script_module ) ) {
 736              _doing_it_wrong(
 737                  $method,
 738                  __( 'The script module must be the id of a script module.' ),
 739                  '7.2.0'
 740              );
 741              return false;
 742          }
 743  
 744          return true;
 745      }
 746  
 747      /**
 748       * Checks that the entity kind and name are non-empty strings, reporting
 749       * them with _doing_it_wrong() otherwise.
 750       *
 751       * @since 7.2.0
 752       *
 753       * @param string $method The calling method, for the notice.
 754       * @param mixed  $kind   The entity kind.
 755       * @param mixed  $name   The entity name.
 756       * @return bool Whether both are valid.
 757       */
 758  	protected function validate_entity( $method, $kind, $name ) {
 759          foreach ( array( $kind, $name ) as $argument ) {
 760              if ( ! is_string( $argument ) || '' === $argument ) {
 761                  _doing_it_wrong(
 762                      $method,
 763                      __( 'The entity kind and the entity name must be non-empty strings.' ),
 764                      '7.2.0'
 765                  );
 766                  return false;
 767              }
 768          }
 769          return true;
 770      }
 771  
 772      /**
 773       * Drops the definitions that are not an array with a non-empty string
 774       * `id`, reporting their positions in the call with _doing_it_wrong():
 775       * like a duplicated field, an invalid definition does not cost the call
 776       * its other fields.
 777       *
 778       * @since 7.2.0
 779       *
 780       * @param string  $method The calling method, for the notice.
 781       * @param string  $kind   The entity kind.
 782       * @param string  $name   The entity name.
 783       * @param array[] $fields The list of field definitions.
 784       * @return array[] The valid definitions, in the order of the call.
 785       */
 786  	protected function skip_invalid_definitions( $method, $kind, $name, $fields ) {
 787          $valid   = array();
 788          $invalid = array();
 789          foreach ( $fields as $position => $field ) {
 790              if ( is_array( $field ) && isset( $field['id'] ) && is_string( $field['id'] ) && '' !== $field['id'] ) {
 791                  $valid[] = $field;
 792              } else {
 793                  $invalid[] = '#' . ( $position + 1 );
 794              }
 795          }
 796  
 797          if ( $invalid ) {
 798              _doing_it_wrong(
 799                  $method,
 800                  sprintf(
 801                      /* translators: 1: Entity kind, e.g. postType. 2: Entity name, e.g. page. 3: Comma-separated list of positions, e.g. #2, #4. 4: id */
 802                      __( 'Every field definition must be an array with a non-empty string %4$s. These definitions of %1$s "%2$s" are skipped: %3$s. The rest of the fields of the call are stored.' ),
 803                      $kind,
 804                      $name,
 805                      implode( ', ', $invalid ),
 806                      '<code>id</code>'
 807                  ),
 808                  '7.2.0'
 809              );
 810          }
 811  
 812          return $valid;
 813      }
 814  
 815      /**
 816       * Drops the ids that are not a non-empty string, reporting their
 817       * positions in the call with _doing_it_wrong(): like an invalid
 818       * definition, an invalid id does not cost the call its other ids.
 819       *
 820       * @since 7.2.0
 821       *
 822       * @param string $method The calling method, for the notice.
 823       * @param string $kind   The entity kind.
 824       * @param string $name   The entity name.
 825       * @param array  $ids    The ids of the fields.
 826       * @return string[] The valid ids, in the order of the call.
 827       */
 828  	protected function skip_invalid_ids( $method, $kind, $name, $ids ) {
 829          $valid   = array();
 830          $invalid = array();
 831          foreach ( array_values( $ids ) as $position => $id ) {
 832              if ( is_string( $id ) && '' !== $id ) {
 833                  $valid[] = $id;
 834              } else {
 835                  $invalid[] = '#' . ( $position + 1 );
 836              }
 837          }
 838  
 839          if ( $invalid ) {
 840              _doing_it_wrong(
 841                  $method,
 842                  sprintf(
 843                      /* translators: 1: Entity kind, e.g. postType. 2: Entity name, e.g. page. 3: Comma-separated list of positions, e.g. #2, #4. */
 844                      __( 'Every field id must be a non-empty string. These ids of %1$s "%2$s" are skipped: %3$s. The rest of the fields of the call are unregistered.' ),
 845                      $kind,
 846                      $name,
 847                      implode( ', ', $invalid )
 848                  ),
 849                  '7.2.0'
 850              );
 851          }
 852  
 853          return $valid;
 854      }
 855  
 856      /**
 857       * Reads and validates a field collection, see register_collection() for
 858       * its format.
 859       *
 860       * An invalid configuration is reported with _doing_it_wrong(): the
 861       * collection is skipped.
 862       *
 863       * @since 7.2.0
 864       *
 865       * @param string $method    The calling method, for the notice.
 866       * @param string $directory The directory of the collection.
 867       * @return array|null The configuration of the collection, with the `module`
 868       *                    key set, its valid `fields` as a list, and `skipped`
 869       *                    telling whether a `field.php` was skipped, see
 870       *                    read_collection_fields(); or null when the
 871       *                    configuration is invalid.
 872       */
 873  	protected function get_collection( $method, $directory ) {
 874          $slug   = basename( $directory );
 875          $file   = $directory . '/index.php';
 876          $config = is_file( $file ) ? self::require_file( $file ) : null;
 877          $error  = null;
 878  
 879          if ( ! is_array( $config ) ) {
 880              $error = sprintf(
 881                  /* translators: %s: index.php */
 882                  __( 'The %s of a field collection must return an array.' ),
 883                  '<code>index.php</code>'
 884              );
 885          } elseif ( ! isset( $config['origin'] ) || ! is_string( $config['origin'] ) || '' === $config['origin'] ) {
 886              $error = sprintf(
 887                  /* translators: %s: origin */
 888                  __( 'The %s of a field collection must be a non-empty string.' ),
 889                  '<code>origin</code>'
 890              );
 891          } elseif ( ! isset( $config['kind'] ) || ! is_string( $config['kind'] ) || '' === $config['kind'] ) {
 892              $error = sprintf(
 893                  /* translators: %s: kind */
 894                  __( 'The %s of a field collection must be a non-empty string.' ),
 895                  '<code>kind</code>'
 896              );
 897          } elseif ( ! isset( $config['name'] ) || ! is_string( $config['name'] ) || '' === $config['name'] ) {
 898              $error = sprintf(
 899                  /* translators: %s: name */
 900                  __( 'The %s of a field collection must be a non-empty string.' ),
 901                  '<code>name</code>'
 902              );
 903          } elseif ( isset( $config['module'] ) && ( ! is_string( $config['module'] ) || '' === $config['module'] ) ) {
 904              $error = sprintf(
 905                  /* translators: %s: module */
 906                  __( 'The %s of a field collection must be the id of a script module.' ),
 907                  '<code>module</code>'
 908              );
 909          }
 910  
 911          if ( null !== $error ) {
 912              _doing_it_wrong(
 913                  $method,
 914                  /* translators: 1: The name of a field collection. 2: The error. */
 915                  sprintf( __( 'The field collection "%1$s" is skipped. %2$s' ), $slug, $error ),
 916                  '7.2.0'
 917              );
 918              return null;
 919          }
 920  
 921          $read = $this->read_collection_fields( $method, $directory );
 922  
 923          return array_merge(
 924              $config,
 925              array(
 926                  'module'  => $config['module'] ?? null,
 927                  'fields'  => array_values( $read['fields'] ),
 928                  'skipped' => $read['skipped'],
 929              )
 930          );
 931      }
 932  
 933      /**
 934       * Reads the fields of a field collection, see get_collection_fields().
 935       *
 936       * The id of a field is used as a key, so it is checked before: a
 937       * `field.php` that does not return an array with a non-empty string id
 938       * is reported with _doing_it_wrong() and skipped, and so is one whose
 939       * id an earlier folder of the collection took. The rest of the fields
 940       * are read.
 941       *
 942       * @since 7.2.0
 943       *
 944       * @param string $method    The calling method, for the notice.
 945       * @param string $directory The directory of the collection.
 946       * @return array {
 947       *     The fields of the collection.
 948       *
 949       *     @type array<string, array> $fields  The valid fields, keyed by id,
 950       *                                         in the alphabetical order of
 951       *                                         their folders.
 952       *     @type bool                 $skipped Whether a `field.php` was skipped.
 953       * }
 954       */
 955  	protected function read_collection_fields( $method, $directory ) {
 956          $files = glob( $directory . '/*/field.php' );
 957          if ( empty( $files ) ) {
 958              return array(
 959                  'fields'  => array(),
 960                  'skipped' => false,
 961              );
 962          }
 963          sort( $files, SORT_STRING );
 964  
 965          $fields     = array();
 966          $invalid    = array();
 967          $duplicated = array();
 968          foreach ( $files as $file ) {
 969              $folder = basename( dirname( $file ) );
 970              $field  = self::require_file( $file );
 971              if ( ! is_array( $field ) ) {
 972                  $invalid[] = $folder;
 973                  continue;
 974              }
 975  
 976              // The id comes first, like in the fields registered directly.
 977              $field = array_merge( array( 'id' => $folder ), $field );
 978              $id    = $field['id'];
 979              if ( ! is_string( $id ) || '' === $id ) {
 980                  $invalid[] = $folder;
 981              } elseif ( isset( $fields[ $id ] ) ) {
 982                  $duplicated[] = $folder;
 983              } else {
 984                  $fields[ $id ] = $field;
 985              }
 986          }
 987  
 988          $collection = basename( $directory );
 989          if ( $invalid ) {
 990              _doing_it_wrong(
 991                  $method,
 992                  sprintf(
 993                      /* translators: 1: The name of a field collection. 2: Comma-separated list of folder names. 3: field.php 4: id */
 994                      __( 'The %3$s of a field must return an array, with a non-empty string %4$s if it sets one. These fields of the field collection "%1$s" are skipped: %2$s.' ),
 995                      $collection,
 996                      implode( ', ', $invalid ),
 997                      '<code>field.php</code>',
 998                      '<code>id</code>'
 999                  ),
1000                  '7.2.0'
1001              );
1002          }
1003  
1004          if ( $duplicated ) {
1005              _doing_it_wrong(
1006                  $method,
1007                  sprintf(
1008                      /* translators: 1: The name of a field collection. 2: Comma-separated list of folder names. */
1009                      __( 'A field can only be defined once in a field collection. These fields of the field collection "%1$s" are skipped because an earlier folder defines their id: %2$s.' ),
1010                      $collection,
1011                      implode( ', ', $duplicated )
1012                  ),
1013                  '7.2.0'
1014              );
1015          }
1016  
1017          return array(
1018              'fields'  => $fields,
1019              'skipped' => $invalid || $duplicated,
1020          );
1021      }
1022  
1023      /**
1024       * Requires a file without sharing the variables of the caller: this is
1025       * about variable scope.
1026       *
1027       * @since 7.2.0
1028       *
1029       * @param string $file The path of the file.
1030       * @return mixed The return value of the file.
1031       */
1032  	protected static function require_file( $file ) {
1033          return require $file;
1034      }
1035  
1036      /**
1037       * Applies a script module to fields of an entity, after the fields it
1038       * already applies to.
1039       *
1040       * @since 7.2.0
1041       *
1042       * @param string      $kind          The entity kind.
1043       * @param string      $name          The entity name.
1044       * @param string[]    $ids           The ids of the fields.
1045       * @param string|null $script_module The id of the script module, if any.
1046       */
1047  	protected function add_field_module( $kind, $name, $ids, $script_module ) {
1048          if ( null === $script_module ) {
1049              return;
1050          }
1051  
1052          $module_ids = $this->field_modules[ $kind ][ $name ][ $script_module ] ?? array();
1053          foreach ( $ids as $id ) {
1054              if ( ! in_array( $id, $module_ids, true ) ) {
1055                  $module_ids[] = $id;
1056              }
1057          }
1058          $this->field_modules[ $kind ][ $name ][ $script_module ] = $module_ids;
1059      }
1060  
1061      /**
1062       * Forgets an entity left without fields or script modules, and its kind
1063       * once no entity of the kind is left, so the registry only lists
1064       * entities that have some.
1065       *
1066       * @since 7.2.0
1067       *
1068       * @param string $kind The entity kind.
1069       * @param string $name The entity name.
1070       */
1071  	protected function forget_empty_entity( $kind, $name ) {
1072          if ( empty( $this->fields[ $kind ][ $name ] ) ) {
1073              unset( $this->fields[ $kind ][ $name ] );
1074          }
1075          if ( empty( $this->fields[ $kind ] ) ) {
1076              unset( $this->fields[ $kind ] );
1077          }
1078          if ( empty( $this->field_modules[ $kind ][ $name ] ) ) {
1079              unset( $this->field_modules[ $kind ][ $name ] );
1080          }
1081          if ( empty( $this->field_modules[ $kind ] ) ) {
1082              unset( $this->field_modules[ $kind ] );
1083          }
1084      }
1085  }


Generated : Sun Nov 29 08:20:01 2026 Cross-referenced by PHPXref