Performs a couple of checks like edit_user() in wp-admin/includes/user.php. * * @since 4.7.0 * * @param string $value The username submitted in the request. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized username, if valid, otherwise an error. */ public function check_username( $value, $request, $param ) { $username = (string) $value; if ( ! validate_username( $username ) ) { return new WP_Error( 'rest_user_invalid_username', __( 'This username is invalid because it uses illegal characters. Please enter a valid username.' ), array( 'status' => 400 ) ); } /** This filter is documented in wp-includes/user.php */ $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() ); if ( in_array( strtolower( $username ), array_map( 'strtolower', $illegal_logins ), true ) ) { return new WP_Error( 'rest_user_invalid_username', __( 'Sorry, that username is not allowed.' ), array( 'status' => 400 ) ); } return $username; } /** * Check a user password for the REST API. * * Performs a couple of checks like edit_user() in wp-admin/includes/user.php. * * @since 4.7.0 * * @param string $value The password submitted in the request. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized password, if valid, otherwise an error. */ public function check_user_password( $value, $request, $param ) { $password = (string) $value; if ( empty( $password ) ) { return new WP_Error( 'rest_user_invalid_password', __( 'Passwords cannot be empty.' ), array( 'status' => 400 ) ); } if ( str_contains( $password, '\\' ) ) { return new WP_Error( 'rest_user_invalid_password', sprintf( /* translators: %s: The '\' character. */ __( 'Passwords cannot contain the "%s" character.' ), '\\' ), array( 'status' => 400 ) ); } return $password; } /** * Retrieves the user's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'user', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'Unique identifier for the user.' ), 'type' => 'integer', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'username' => array( 'description' => __( 'Login name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'required' => true, 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_username' ), ), ), 'name' => array( 'description' => __( 'Display name for the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'first_name' => array( 'description' => __( 'First name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'last_name' => array( 'description' => __( 'Last name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'email' => array( 'description' => __( 'The email address for the user.' ), 'type' => 'string', 'format' => 'email', 'context' => array( 'edit' ), 'required' => true, ), 'url' => array( 'description' => __( 'URL of the user.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ), 'description' => array( 'description' => __( 'Description of the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), ), 'link' => array( 'description' => __( 'Author URL of the user.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'locale' => array( 'description' => __( 'Locale for the user.' ), 'type' => 'string', 'enum' => array_merge( array( '', 'en_US' ), get_available_languages() ), 'context' => array( 'edit' ), ), 'nickname' => array( 'description' => __( 'The nickname for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => array( $this, 'sanitize_slug' ), ), ), 'registered_date' => array( 'description' => __( 'Registration date for the user.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'edit' ), 'readonly' => true, ), 'roles' => array( 'description' => __( 'Roles assigned to the user.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), 'context' => array( 'edit' ), ), 'password' => array( 'description' => __( 'Password for the user (never included).' ), 'type' => 'string', 'context' => array(), // Password is never displayed. 'required' => true, 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_user_password' ), ), ), 'capabilities' => array( 'description' => __( 'All capabilities assigned to the user.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'extra_capabilities' => array( 'description' => __( 'Any extra capabilities assigned to the user.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), ), ); if ( get_option( 'show_avatars' ) ) { $avatar_properties = array(); $avatar_sizes = rest_get_avatar_sizes(); foreach ( $avatar_sizes as $size ) { $avatar_properties[ $size ] = array( /* translators: %d: Avatar image size in pixels. */ 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ); } $schema['properties']['avatar_urls'] = array( 'description' => __( 'Avatar URLs for the user.' ), 'type' => 'object', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, 'properties' => $avatar_properties, ); } $schema['properties']['meta'] = $this->meta->get_field_schema(); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params['exclude'] = array( 'description' => __( 'Ensure result set excludes specific IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['include'] = array( 'description' => __( 'Limit result set to specific IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['offset'] = array( 'description' => __( 'Offset the result set by a specific number of items.' ), 'type' => 'integer', ); $query_params['order'] = array( 'default' => 'asc', 'description' => __( 'Order sort attribute ascending or descending.' ), 'enum' => array( 'asc', 'desc' ), 'type' => 'string', ); $query_params['orderby'] = array( 'default' => 'name', 'description' => __( 'Sort collection by user attribute.' ), 'enum' => array( 'id', 'include', 'name', 'registered_date', 'slug', 'include_slugs', 'email', 'url', ), 'type' => 'string', ); $query_params['slug'] = array( 'description' => __( 'Limit result set to users with one or more specific slugs.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['roles'] = array( 'description' => __( 'Limit result set to users matching at least one specific role provided. Accepts csv list or single role.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['capabilities'] = array( 'description' => __( 'Limit result set to users matching at least one specific capability provided. Accepts csv list or single capability.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['who'] = array( 'description' => __( 'Limit result set to users who are considered authors.' ), 'type' => 'string', 'enum' => array( 'authors', ), ); $query_params['has_published_posts'] = array( 'description' => __( 'Limit result set to users who have published posts.' ), 'type' => array( 'boolean', 'array' ), 'items' => array( 'type' => 'string', 'enum' => get_post_types( array( 'show_in_rest' => true ), 'names' ), ), ); /** * Filters REST API collection parameters for the users controller. * * This filter registers the collection parameter, but does not map the * collection parameter to an internal WP_User_Query parameter. Use the * `rest_user_query` filter to set WP_User_Query arguments. * * @since 4.7.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_user_collection_params', $query_params ); } } * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. */ public function delete_item( $request ) { $comment = $this->get_comment( $request['id'] ); if ( is_wp_error( $comment ) ) { return $comment; } $force = isset( $request['force'] ) ? (bool) $request['force'] : false; /** * Filters whether a comment can be trashed via the REST API. * * Return false to disable trash support for the comment. * * @since 4.7.0 * * @param bool $supports_trash Whether the comment supports trashing. * @param WP_Comment $comment The comment object being considered for trashing support. */ $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment ); $request->set_param( 'context', 'edit' ); if ( $force ) { $previous = $this->prepare_item_for_response( $comment, $request ); $result = wp_delete_comment( $comment->comment_ID, true ); $response = new WP_REST_Response(); $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); } else { // If this type doesn't support trashing, error out. if ( ! $supports_trash ) { return new WP_Error( 'rest_trash_not_supported', /* translators: %s: force=true */ sprintf( __( "The comment does not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) ); } if ( 'trash' === $comment->comment_approved ) { return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) ); } $result = wp_trash_comment( $comment->comment_ID ); $comment = get_comment( $comment->comment_ID ); $response = $this->prepare_item_for_response( $comment, $request ); } if ( ! $result ) { return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) ); } /** * Fires after a comment is deleted via the REST API. * * @since 4.7.0 * * @param WP_Comment $comment The deleted comment data. * @param WP_REST_Response $response The response returned from the API. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_delete_comment', $comment, $response, $request ); return $response; } /** * Prepares a single comment output for response. * * @since 4.7.0 * @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Comment $item Comment object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $comment = $item; $fields = $this->get_fields_for_response( $request ); $data = array(); if ( in_array( 'id', $fields, true ) ) { $data['id'] = (int) $comment->comment_ID; } if ( in_array( 'post', $fields, true ) ) { $data['post'] = (int) $comment->comment_post_ID; } if ( in_array( 'parent', $fields, true ) ) { $data['parent'] = (int) $comment->comment_parent; } if ( in_array( 'author', $fields, true ) ) { $data['author'] = (int) $comment->user_id; } if ( in_array( 'author_name', $fields, true ) ) { $data['author_name'] = $comment->comment_author; } if ( in_array( 'author_email', $fields, true ) ) { $data['author_email'] = $comment->comment_author_email; } if ( in_array( 'author_url', $fields, true ) ) { $data['author_url'] = $comment->comment_author_url; } if ( in_array( 'author_ip', $fields, true ) ) { $data['author_ip'] = $comment->comment_author_IP; } if ( in_array( 'author_user_agent', $fields, true ) ) { $data['author_user_agent'] = $comment->comment_agent; } if ( in_array( 'date', $fields, true ) ) { $data['date'] = mysql_to_rfc3339( $comment->comment_date ); } if ( in_array( 'date_gmt', $fields, true ) ) { $data['date_gmt'] = mysql_to_rfc3339( $comment->comment_date_gmt ); } if ( in_array( 'content', $fields, true ) ) { $data['content'] = array( /** This filter is documented in wp-includes/comment-template.php */ 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment, array() ), 'raw' => $comment->comment_content, ); } if ( in_array( 'link', $fields, true ) ) { $data['link'] = get_comment_link( $comment ); } if ( in_array( 'status', $fields, true ) ) { $data['status'] = $this->prepare_status_response( $comment->comment_approved ); } if ( in_array( 'type', $fields, true ) ) { $data['type'] = get_comment_type( $comment->comment_ID ); } if ( in_array( 'author_avatar_urls', $fields, true ) ) { $data['author_avatar_urls'] = rest_get_avatar_urls( $comment ); } if ( in_array( 'meta', $fields, true ) ) { $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request ); } $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $data = $this->add_additional_fields_to_object( $data, $request ); $data = $this->filter_response_by_context( $data, $context ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $comment ) ); } /** * Filters a comment returned from the REST API. * * Allows modification of the comment right before it is returned. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_Comment $comment The original comment object. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_comment', $response, $comment, $request ); } /** * Prepares links for the request. * * @since 4.7.0 * * @param WP_Comment $comment Comment object. * @return array Links for the given comment. */ protected function prepare_links( $comment ) { $links = array( 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ), ), 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), ); if ( 0 !== (int) $comment->user_id ) { $links['author'] = array( 'href' => rest_url( 'wp/v2/users/' . $comment->user_id ), 'embeddable' => true, ); } if ( 0 !== (int) $comment->comment_post_ID ) { $post = get_post( $comment->comment_post_ID ); $post_route = rest_get_route_for_post( $post ); if ( ! empty( $post->ID ) && $post_route ) { $links['up'] = array( 'href' => rest_url( $post_route ), 'embeddable' => true, 'post_type' => $post->post_type, ); } } if ( 0 !== (int) $comment->comment_parent ) { $links['in-reply-to'] = array( 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ), 'embeddable' => true, ); } // Only grab one comment to verify the comment has children. $comment_children = $comment->get_children( array( 'count' => true, 'orderby' => 'none', ) ); if ( ! empty( $comment_children ) ) { $args = array( 'parent' => $comment->comment_ID, ); $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) ); $links['children'] = array( 'href' => $rest_url, 'embeddable' => true, ); } return $links; } /** * Prepends internal property prefix to query parameters to match our response fields. * * @since 4.7.0 * * @param string $query_param Query parameter. * @return string The normalized query parameter. */ protected function normalize_query_param( $query_param ) { $prefix = 'comment_'; switch ( $query_param ) { case 'id': $normalized = $prefix . 'ID'; break; case 'post': $normalized = $prefix . 'post_ID'; break; case 'parent': $normalized = $prefix . 'parent'; break; case 'include': $normalized = 'comment__in'; break; default: $normalized = $prefix . $query_param; break; } return $normalized; } /** * Checks comment_approved to set comment status for single comment output. * * @since 4.7.0 * * @param string|int $comment_approved comment status. * @return string Comment status. */ protected function prepare_status_response( $comment_approved ) { switch ( $comment_approved ) { case 'hold': case '0': $status = 'hold'; break; case 'approve': case '1': $status = 'approved'; break; case 'spam': case 'trash': default: $status = $comment_approved; break; } return $status; } /** * Prepares a single comment to be inserted into the database. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return array|WP_Error Prepared comment, otherwise WP_Error object. */ protected function prepare_item_for_database( $request ) { $prepared_comment = array(); /* * Allow the comment_content to be set via the 'content' or * the 'content.raw' properties of the Request object. */ if ( isset( $request['content'] ) && is_string( $request['content'] ) ) { $prepared_comment['comment_content'] = trim( $request['content'] ); } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) { $prepared_comment['comment_content'] = trim( $request['content']['raw'] ); } if ( isset( $request['post'] ) ) { $prepared_comment['comment_post_ID'] = (int) $request['post']; } if ( isset( $request['parent'] ) ) { $prepared_comment['comment_parent'] = $request['parent']; } if ( isset( $request['author'] ) ) { $user = new WP_User( $request['author'] ); if ( $user->exists() ) { $prepared_comment['user_id'] = $user->ID; $prepared_comment['comment_author'] = $user->display_name; $prepared_comment['comment_author_email'] = $user->user_email; $prepared_comment['comment_author_url'] = $user->user_url; } else { return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) ); } } if ( isset( $request['author_name'] ) ) { $prepared_comment['comment_author'] = $request['author_name']; } if ( isset( $request['author_email'] ) ) { $prepared_comment['comment_author_email'] = $request['author_email']; } if ( isset( $request['author_url'] ) ) { $prepared_comment['comment_author_url'] = $request['author_url']; } if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) { $prepared_comment['comment_author_IP'] = $request['author_ip']; } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) { $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR']; } else { $prepared_comment['comment_author_IP'] = '127.0.0.1'; } if ( ! empty( $request['author_user_agent'] ) ) { $prepared_comment['comment_agent'] = $request['author_user_agent']; } elseif ( $request->get_header( 'user_agent' ) ) { $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' ); } if ( ! empty( $request['date'] ) ) { $date_data = rest_get_date_with_gmt( $request['date'] ); if ( ! empty( $date_data ) ) { list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data; } } elseif ( ! empty( $request['date_gmt'] ) ) { $date_data = rest_get_date_with_gmt( $request['date_gmt'], true ); if ( ! empty( $date_data ) ) { list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data; } } /** * Filters a comment added via the REST API after it is prepared for insertion into the database. * * Allows modification of the comment right after it is prepared for the database. * * @since 4.7.0 * * @param array $prepared_comment The prepared comment data for `wp_insert_comment`. * @param WP_REST_Request $request The current request. */ return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request ); } /** * Retrieves the comment's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'comment', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'Unique identifier for the comment.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'author' => array( 'description' => __( 'The ID of the user object, if author was a user.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ), 'author_email' => array( 'description' => __( 'Email address for the comment author.' ), 'type' => 'string', 'format' => 'email', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_comment_author_email' ), 'validate_callback' => null, // Skip built-in validation of 'email'. ), ), 'author_ip' => array( 'description' => __( 'IP address for the comment author.' ), 'type' => 'string', 'format' => 'ip', 'context' => array( 'edit' ), ), 'author_name' => array( 'description' => __( 'Display name for the comment author.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'author_url' => array( 'description' => __( 'URL for the comment author.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), ), 'author_user_agent' => array( 'description' => __( 'User agent for the comment author.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'content' => array( 'description' => __( 'The content for the comment.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). ), 'properties' => array( 'raw' => array( 'description' => __( 'Content for the comment, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'rendered' => array( 'description' => __( 'HTML content for the comment, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ), 'date' => array( 'description' => __( "The date the comment was published, in the site's timezone." ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit', 'embed' ), ), 'date_gmt' => array( 'description' => __( 'The date the comment was published, as GMT.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), ), 'link' => array( 'description' => __( 'URL to the comment.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'parent' => array( 'description' => __( 'The ID for the parent of the comment.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), 'default' => 0, ), 'post' => array( 'description' => __( 'The ID of the associated post object.' ), 'type' => 'integer', 'context' => array( 'view', 'edit' ), 'default' => 0, ), 'status' => array( 'description' => __( 'State of the comment.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_key', ), ), 'type' => array( 'description' => __( 'Type of the comment.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); if ( get_option( 'show_avatars' ) ) { $avatar_properties = array(); $avatar_sizes = rest_get_avatar_sizes(); foreach ( $avatar_sizes as $size ) { $avatar_properties[ $size ] = array( /* translators: %d: Avatar image size in pixels. */ 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ); } $schema['properties']['author_avatar_urls'] = array( 'description' => __( 'Avatar URLs for the comment author.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, 'properties' => $avatar_properties, ); } $schema['properties']['meta'] = $this->meta->get_field_schema(); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Comments collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params['after'] = array( 'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); $query_params['author'] = array( 'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['author_exclude'] = array( 'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['author_email'] = array( 'default' => null, 'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ), 'format' => 'email', 'type' => 'string', ); $query_params['before'] = array( 'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); $query_params['exclude'] = array( 'description' => __( 'Ensure result set excludes specific IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['include'] = array( 'description' => __( 'Limit result set to specific IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['offset'] = array( 'description' => __( 'Offset the result set by a specific number of items.' ), 'type' => 'integer', ); $query_params['order'] = array( 'description' => __( 'Order sort attribute ascending or descending.' ), 'type' => 'string', 'default' => 'desc', 'enum' => array( 'asc', 'desc', ), ); $query_params['orderby'] = array( 'description' => __( 'Sort collection by comment attribute.' ), 'type' => 'string', 'default' => 'date_gmt', 'enum' => array( 'date', 'date_gmt', 'id', 'include', 'post', 'parent', 'type', ), ); $query_params['parent'] = array( 'default' => array(), 'description' => __( 'Limit result set to comments of specific parent IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['parent_exclude'] = array( 'default' => array(), 'description' => __( 'Ensure result set excludes specific parent IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['post'] = array( 'default' => array(), 'description' => __( 'Limit result set to comments assigned to specific post IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['status'] = array( 'default' => 'approve', 'description' => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ), 'sanitize_callback' => 'sanitize_key', 'type' => 'string', 'validate_callback' => 'rest_validate_request_arg', ); $query_params['type'] = array( 'default' => 'comment', 'description' => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ), 'sanitize_callback' => 'sanitize_key', 'type' => 'string', 'validate_callback' => 'rest_validate_request_arg', ); $query_params['password'] = array( 'description' => __( 'The password for the post if it is password protected.' ), 'type' => 'string', ); /** * Filters REST API collection parameters for the comments controller. * * This filter registers the collection parameter, but does not map the * collection parameter to an internal WP_Comment_Query parameter. Use the * `rest_comment_query` filter to set WP_Comment_Query parameters. * * @since 4.7.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_comment_collection_params', $query_params ); } /** * Sets the comment_status of a given comment object when creating or updating a comment. * * @since 4.7.0 * * @param string|int $new_status New comment status. * @param int $comment_id Comment ID. * @return bool Whether the status was changed. */ protected function handle_status_param( $new_status, $comment_id ) { $old_status = wp_get_comment_status( $comment_id ); if ( $new_status === $old_status ) { return false; } switch ( $new_status ) { case 'approved': case 'approve': case '1': $changed = wp_set_comment_status( $comment_id, 'approve' ); break; case 'hold': case '0': $changed = wp_set_comment_status( $comment_id, 'hold' ); break; case 'spam': $changed = wp_spam_comment( $comment_id ); break; case 'unspam': $changed = wp_unspam_comment( $comment_id ); break; case 'trash': $changed = wp_trash_comment( $comment_id ); break; case 'untrash': $changed = wp_untrash_comment( $comment_id ); break; default: $changed = false; break; } return $changed; } /** * Checks if the post can be read. * * Correctly handles posts with the inherit status. * * @since 4.7.0 * * @param WP_Post $post Post object. * @param WP_REST_Request $request Request data to check. * @return bool Whether post can be read. */ protected function check_read_post_permission( $post, $request ) { $post_type = get_post_type_object( $post->post_type ); // Return false if custom post type doesn't exist if ( ! $post_type ) { return false; } $posts_controller = $post_type->get_rest_controller(); /* * Ensure the posts controller is specifically a WP_REST_Posts_Controller instance * before using methods specific to that controller. */ if ( ! $posts_controller instanceof WP_REST_Posts_Controller ) { $posts_controller = new WP_REST_Posts_Controller( $post->post_type ); } $has_password_filter = false; // Only check password if a specific post was queried for or a single comment $requested_post = ! empty( $request['post'] ) && ( ! is_array( $request['post'] ) || 1 === count( $request['post'] ) ); $requested_comment = ! empty( $request['id'] ); if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) { add_filter( 'post_password_required', '__return_false' ); $has_password_filter = true; } if ( post_password_required( $post ) ) { $result = current_user_can( 'edit_post', $post->ID ); } else { $result = $posts_controller->check_read_permission( $post ); } if ( $has_password_filter ) { remove_filter( 'post_password_required', '__return_false' ); } return $result; } /** * Checks if the comment can be read. * * @since 4.7.0 * * @param WP_Comment $comment Comment object. * @param WP_REST_Request $request Request data to check. * @return bool Whether the comment can be read. */ protected function check_read_permission( $comment, $request ) { if ( ! empty( $comment->comment_post_ID ) ) { $post = get_post( $comment->comment_post_ID ); if ( $post ) { if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) { return true; } } } if ( 0 === get_current_user_id() ) { return false; } if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) { return false; } if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) { return true; } return current_user_can( 'edit_comment', $comment->comment_ID ); } /** * Checks if a comment can be edited or deleted. * * @since 4.7.0 * * @param WP_Comment $comment Comment object. * @return bool Whether the comment can be edited or deleted. */ protected function check_edit_permission( $comment ) { if ( 0 === (int) get_current_user_id() ) { return false; } if ( current_user_can( 'moderate_comments' ) ) { return true; } return current_user_can( 'edit_comment', $comment->comment_ID ); } /** * Checks a comment author email for validity. * * Accepts either a valid email address or empty string as a valid comment * author email address. Setting the comment author email to an empty * string is allowed when a comment is being updated. * * @since 4.7.0 * * @param string $value Author email value submitted. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized email address, if valid, * otherwise an error. */ public function check_comment_author_email( $value, $request, $param ) { $email = (string) $value; if ( empty( $email ) ) { return $email; } $check_email = rest_validate_request_arg( $email, $request, $param ); if ( is_wp_error( $check_email ) ) { return $check_email; } return $email; } /** * If empty comments are not allowed, checks if the provided comment content is not empty. * * @since 5.6.0 * * @param array $prepared_comment The prepared comment data. * @return bool True if the content is allowed, false otherwise. */ protected function check_is_comment_content_allowed( $prepared_comment ) { $check = wp_parse_args( $prepared_comment, array( 'comment_post_ID' => 0, 'comment_author' => null, 'comment_author_email' => null, 'comment_author_url' => null, 'comment_parent' => 0, 'user_id' => 0, ) ); /** This filter is documented in wp-includes/comment.php */ $allow_empty = apply_filters( 'allow_empty_comment', false, $check ); if ( $allow_empty ) { return true; } /* * Do not allow a comment to be created with missing or empty * comment_content. See wp_handle_comment_submission(). */ return '' !== $check['comment_content']; } } return $array; } /** * Check if an item or items (using key) exist in an array using "dot" notation. * * @param \ArrayAccess|array $array * @param string|array $keys * @return bool */ public static function has($array, $keys) { $keys = (array) $keys; if (! $array || $keys === []) { return false; } foreach ($keys as $key) { $subKeyArray = $array; if (static::exists($array, $key)) { continue; } foreach (explode('.', $key) as $segment) { if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) { $subKeyArray = $subKeyArray[$segment]; } else { return false; } } } return true; } /** * Determine if any of the keys exist in an array using "dot" notation. * * @param \ArrayAccess|array $array * @param string|array $keys * @return bool */ public static function hasAny($array, $keys) { if (is_null($keys)) { return false; } $keys = (array) $keys; if (! $array) { return false; } if ($keys === []) { return false; } foreach ($keys as $key) { if (static::has($array, $key)) { return true; } } return false; } /** * Alias of contains. * * @param array $array * @param string|array $values * @return bool */ public static function inArray($array, $value) { return static::contains($array, $value); } /** * Determines if an array is associative. * * An array is "associative" if it doesn't have sequential numerical keys beginning with zero. * * @param array $array * @return bool */ public static function isAssoc(array $array) { $keys = array_keys($array); return array_keys($keys) !== $keys; } /** * Determines if an array is a list. * * An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between. * * @param array $array * @return bool */ public static function isList($array) { return ! self::isAssoc($array); } /** * Determines if the given key contains a boolean value. * * Returns true for true, 1, "1", "true", "on" and "yes" * Returns false for false, "0", "false", "off", "no", and "" * Returns for all non-boolean values. * * @param array $array * @param string $key * * @return bool|null * @see https://www.php.net/manual/en/filter.filters.validate.php */ public static function isTrue($array, $key) { return filter_var( static::get($array, $key), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE ); } /** * Get a subset of the items from the given array. * * @param array $array * @param array|string $keys * @return array */ public static function only($array, $keys) { return array_intersect_key($array, array_flip((array) $keys)); } /** * Pluck an array of values from an array. * * @param iterable $array * @param string|array|int|null $value * @param string|array|null $key * @return array */ public static function pluck($array, $value, $key = null) { $results = []; [$value, $key] = static::explodePluckParameters($value, $key); foreach ($array as $item) { $itemValue = Helper::dataGet($item, $value); // If the key is "null", we will just append the value to the array and keep // looping. Otherwise we will key the array using the value of the key we // received from the developer. Then we'll return the final array form. if (is_null($key)) { $results[] = $itemValue; } else { $itemKey = Helper::dataGet($item, $key); if (is_object($itemKey) && method_exists($itemKey, '__toString')) { $itemKey = (string) $itemKey; } $results[$itemKey] = $itemValue; } } return $results; } /** * Explode the "value" and "key" arguments passed to "pluck". * * @param string|array $value * @param string|array|null $key * @return array */ protected static function explodePluckParameters($value, $key) { $value = is_string($value) ? explode('.', $value) : $value; $key = is_null($key) || is_array($key) ? $key : explode('.', $key); return [$value, $key]; } /** * Push an item onto the beginning of an array. * * @param array $array * @param mixed $value * @param mixed $key * @return array */ public static function prepend($array, $value, $key = null) { if (func_num_args() == 2) { array_unshift($array, $value); } else { $array = [$key => $value] + $array; } return $array; } /** * Get a value from the array, and remove it. * * @param array $array * @param string|int $key * @param mixed $default * @return mixed */ public static function pull(&$array, $key, $default = null) { $value = static::get($array, $key, $default); static::forget($array, $key); return $value; } /** * Convert the array into a query string. * * @param array $array * @return string */ public static function query($array) { return http_build_query($array, '', '&', PHP_QUERY_RFC3986); } /** * Get one or a specified number of random values from an array. * * @param array $array * @param int|null $number * @param bool|false $preserveKeys * @return mixed * * @throws \InvalidArgumentException */ public static function random($array, $number = null, $preserveKeys = false) { $requested = is_null($number) ? 1 : $number; $count = count($array); if ($requested > $count) { throw new InvalidArgumentException( "You requested {$requested} items, but there are only {$count} items available." ); } if (is_null($number)) { return $array[array_rand($array)]; } if ((int) $number === 0) { return []; } $keys = array_rand($array, $number); $results = []; if ($preserveKeys) { foreach ((array) $keys as $key) { $results[$key] = $array[$key]; } } else { foreach ((array) $keys as $key) { $results[] = $array[$key]; } } return $results; } /** * Set an array item to a given value using "dot" notation. * * If no key is given to the method, the entire array will be replaced. * * @param array $array * @param string|null $key * @param mixed $value * @return array */ public static function set(&$array, $key, $value) { if (is_null($key)) { return $array = $value; } $keys = explode('.', $key); foreach ($keys as $i => $key) { if (count($keys) === 1) { break; } unset($keys[$i]); // If the key doesn't exist at this depth, we will just create an empty array // to hold the next value, allowing us to create the arrays to hold final // values at the correct depth. Then we'll keep digging into the array. if (! isset($array[$key]) || ! is_array($array[$key])) { $array[$key] = []; } $array = &$array[$key]; } $array[array_shift($keys)] = $value; return $array; } /** * Shuffle the given array and return the result. * * @param array $array * @param int|null $seed * @return array */ public static function shuffle($array, $seed = null) { if (is_null($seed)) { shuffle($array); } else { mt_srand($seed); shuffle($array); mt_srand(); } return $array; } /** * Sort the array using the given callback or "dot" notation. * * @param array $array * @param callable|array|string|null $callback * @return array */ public static function sort($array, $callback = null) { return Collection::make($array)->sortBy($callback)->all(); } /** * Sort an array in descending order. * * @param array $array * @param Flags * @return array * @see https://www.php.net/manual/en/function.rsort.php */ public static function rsort($array, $flags = SORT_REGULAR) { rsort($array, $flags); return $array; } /** * Sort an array in ascending order and maintain index association. * * @param array $array * @param Flags * @return array * @see https://www.php.net/manual/en/function.asort.php */ public static function asort($array, $flags = SORT_REGULAR) { asort($array, $flags); return $array; } /** * Sort an array in descending order and maintain index association. * * @param array $array * @param Flags * @return array * @see https://www.php.net/manual/en/function.arsort.php */ public static function arsort($array, $flags = SORT_REGULAR) { arsort($array, $flags); return $array; } /** * Sort an array by key in ascending order. * * @param array $array * @param Flags * @return array * @see https://www.php.net/manual/en/function.ksort.php */ public static function ksort($array, $flags = SORT_REGULAR) { ksort($array, $flags); return $array; } /** * Sort an array by key in descending order. * * @param array $array * @param Flags * @return array * @see https://www.php.net/manual/en/function.krsort.php */ public static function krsort($array, $flags = SORT_REGULAR) { krsort($array, $flags); return $array; } /** * Sort an array using a "natural order" algorithm. * * @param array $array * @return array * @see https://www.php.net/manual/en/function.natsort.php */ public static function natsort($array) { natsort($array); return $array; } /** * Sort an array using a case insensitive "natural order" algorithm. * * @param array $array * @return array * @see https://www.php.net/manual/en/function.natcasesort.php */ public static function natcasesort($array) { natcasesort($array); return $array; } /** * Sort an array by values using a user-defined comparison function. * * @param array $array * @return array * @see https://www.php.net/manual/en/function.usort.php */ public static function usort($array, callable $callback) { usort($array, $callback); return $array; } /** * Sort an array with a user-defined comparison * function and maintain index association. * * @param array $array * @return array * @see https://www.php.net/manual/en/function.uasort.php */ public static function uasort($array, callable $callback) { uasort($array, $callback); return $array; } /** * Sort an array by keys using a user-defined comparison function. * * @param array $array * @return array * @see https://www.php.net/manual/en/function.uksort.php */ public static function uksort($array, callable $callback) { uksort($array, $callback); return $array; } /** * Recursively sort an array by keys and values. * * @param array $array * @param int $options * @param bool $desc * @return array */ public static function sortRecursive($array, $options = SORT_REGULAR, $desc = false) { foreach ($array as &$value) { if (is_array($value)) { $value = static::sortRecursive($value, $options, $desc); } } if (static::isAssoc($array)) { $desc ? krsort($array, $options) : ksort($array, $options); } else { $desc ? rsort($array, $options) : sort($array, $options); } return $array; } /** * Conditionally compile classes from an array into a CSS class list. * * @param array $array * @return string */ public static function toCssClasses($array) { $classList = static::wrap($array); $classes = []; foreach ($classList as $class => $constraint) { if (is_numeric($class)) { $classes[] = $constraint; } elseif ($constraint) { $classes[] = $class; } } return implode(' ', $classes); } /** * Transforms an array to \stdClass * @param array $array * @return \stdClass */ public static function toObject($array) { return StdObject::create($array); } /** * Filter the array using the given callback. * * @param array $array * @param callable $callback * @return array */ public static function where($array, callable $callback) { return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH); } /** * Filter items where the value is not null. * * @param array $array * @return array */ public static function whereNotNull($array) { return static::where($array, function ($value) { return ! is_null($value); }); } /** * Filter items where the value is not null. * * @param array $array * @return array */ public static function whereNotTrue($array, $strict = false) { return static::where($array, function ($value) use ($strict) { return $strict ? $value === false : !$value; }); } /** * If the given value is not an array and not null, wrap it in one. * * @param mixed $value * @return array */ public static function wrap($value) { if (is_null($value)) { return []; } return is_array($value) ? $value : [$value]; } /** * Maps a function to all non-iterable elements of an array or an object. * * This is similar to `array_walk_recursive()` but acts upon objects too. * * @param mixed $value The array, object, or scalar. * @param callable $callback The function to map onto $value. * @see https://developer.wordpress.org/reference/functions/map_deep/ * * @return mixed The value with the callback applied to all non-arrays and non-objects inside it. */ public static function map($value, $callback) { return map_deep($value, $callback); } /** * Check if the value(s) exist in an array using "dot" notation. * * @param array $array * @param string|array $values * @return bool */ public static function contains(array $array, $values) { $result = []; $values = is_array($values) ? $values : [$values]; foreach ($values as $value) { if (in_array($value, $array)) { $result[] = $value; continue; } $segments = explode('.', $value); $value = array_pop($segments); $nested = (array) static::get($array, implode('.', $segments)); if ($nested && in_array($value, $nested)) { $result[] = $value; } } return count($result) === count($values); } /** * Check if the any value exist in an array using "dot" notation. * * @param array $array * @param string|array $values * @return bool */ public static function containsAny(array $array, $values) { $result = []; $values = is_array($values) ? $values : [$values]; foreach ($values as $value) { if (in_array($value, $array)) { return true; } $segments = explode('.', $value); $value = array_pop($segments); $nested = (array) static::get($array, implode('.', $segments)); if ($nested && in_array($value, $nested)) { return true; } } return false; } /** * Compare two nested arrays side by side * @param array $array1 * @param array $array2 * @param array $path * @return array */ public static function compare($array1, $array2, $path = []) { $differences = []; foreach ($array1 as $key => $value1) { // Check if the key exists in the second array if (!array_key_exists($key, $array2)) { $differences[implode('.', array_merge($path, [$key]))] = [ 'array_1' => $value1, 'array_2' => null, ]; } else { // If the value is an array, recursively compare if (is_array($value1) && is_array($array2[$key])) { $differences = array_merge($differences, static::compare( $value1, $array2[$key], array_merge($path, [$key]) )); } else { // Compare values if ($value1 !== $array2[$key]) { $differences[implode('.', array_merge($path, [$key]))] = [ 'array_1' => $value1, 'array_2' => $array2[$key], ]; } } } } // Check for keys in the second array that are not in the first array foreach ($array2 as $key => $value2) { if (!array_key_exists($key, $array1)) { $differences[implode('.', array_merge($path, [$key]))] = [ 'array_1' => null, 'array_2' => $value2, ]; } } return $differences; } /** * Merge the items from the first array into the * second array if the second array is missing it. * * @param array &$array1 * @param array &$array2 * @return array */ public static function mergeMissing(&$array1, &$array2) { foreach ($array1 as $key => $value1) { // If the key exists in the second array if (array_key_exists($key, $array2)) { // If the value is an array, recursively add missing items if (is_array($value1) && is_array($array2[$key])) { static::mergeMissing($value1, $array2[$key]); } } else { // If the key doesn't exist in the second array, // then add it with the corresponding value $array2[$key] = $value1; } } return $array2; } /** * Recursively merge the given array with defaults. * Overwrite $array with $defaults if only $array * contains null or empty values or doesn't exist. * * @param array $array * @param array $defaults * @return array */ public static function mergeMissingValues(array $array, array $defaults) { $merged = array_merge($defaults, $array); foreach ($merged as $key => $value) { if ( is_array($value) && isset($defaults[$key]) && is_array($defaults[$key]) ) { // Recursively merge arrays $merged[$key] = static::mergeMissingValues( $value, $defaults[$key] ); } elseif ( isset($defaults[$key]) && (is_null($value) || $value === '') ) { // Replace null or empty values $merged[$key] = $defaults[$key]; } } return $merged; } /** * Return matching items from array (similar to mysql's %LIKE%) * * @param string|regex $pattern * @param array $array * @return array|false */ public static function like($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '~i'; } return preg_grep($pattern, $array); } /** * Return non-matching items from array (similar to mysql's NOT %LIKE%) * * @param string|regex $pattern * @param array $array * @return array|false */ public static function notLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '~i'; } return preg_grep($pattern, $array, PREG_GREP_INVERT); } /** * Return matching starting of items from array (similar to mysql's %LIKE) * * @param string|regex $pattern * @param array $array * @return array|false */ public static function startsLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~^'. preg_quote($pattern, '~') . '~i'; } return preg_grep($pattern, $array); } /** * Return non-matching starting of items from array (similar to mysql's NOT %LIKE) * * @param string|regex $pattern * @param array $array * @return array|false */ public static function DoesNotStartLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~^(?!' . preg_quote($pattern, '~') . ')~i'; } return preg_grep($pattern, $array); } /** * Return matching ending of items from array (similar to mysql's LIKE%) * * @param string|regex $pattern * @param array $array * @return array|false */ public static function endsLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '$~i'; } return preg_grep($pattern, $array); } /** * Return non-matching ending of items from array (similar to mysql's NOT LIKE%) * * @param string|regex $pattern * @param array $array * @return array|false */ public static function DoesNotEndLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '$~i'; } return preg_grep($pattern, $array, PREG_GREP_INVERT); } /** * Return matching items from array by keys * * @param string|regex $pattern * @param array $array * @return array|false */ public static function keysLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '~i'; } $values = []; $keys = preg_grep($pattern, array_keys($array)); foreach ($keys as $key) { $values[$key] = $array[$key]; } return $values; } /** * Return non-matching items from array by keys * * @param string|regex $pattern * @param array $array * @return array|false */ public static function keysNotLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '~i'; } $values = []; $keys = preg_grep($pattern, array_keys($array), 1); foreach ($keys as $key) { $values[$key] = $array[$key]; } return $values; } /** * Return matching starting of items from array by keys * * @param string|regex $pattern * @param array $array * @return array|false */ public static function keysStartLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~^'. preg_quote($pattern, '~') . '~i'; } $values = []; $keys = preg_grep($pattern, array_keys($array)); foreach ($keys as $key) { $values[$key] = $array[$key]; } return $values; } /** * Return non-matching starting of items from array by keys * * @param string|regex $pattern * @param array $array * @return array|false */ public static function keysDoesNotStartLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~^(?!' . preg_quote($pattern, '~') . ')~i'; } $values = []; $keys = preg_grep($pattern, array_keys($array)); foreach ($keys as $key) { $values[$key] = $array[$key]; } return $values; } /** * Return matching ending of items from array by keys * * @param string|regex $pattern * @param array $array * @return array|false */ public static function keysEndLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '$~i'; } $values = []; $keys = preg_grep($pattern, array_keys($array)); foreach ($keys as $key) { $values[$key] = $array[$key]; } return $values; } /** * Return non-matching ending of items from array by keys * * @param string|regex $pattern * @param array $array * @return array|false */ public static function keysDoesNotEndLike($array, $pattern) { if (!preg_match('/^([\/#~]).*\1$/', $pattern)) { $pattern = '~'. preg_quote($pattern, '~') . '$~i'; } $values = []; $keys = preg_grep($pattern, array_keys($array), PREG_GREP_INVERT); foreach ($keys as $key) { $values[$key] = $array[$key]; } return $values; } /** * Insert a new item in the array at the given position. * * @param array $array * @param int $pos * @param mixed $newItem * @return array */ public static function insertAt($array, $pos, $newItem) { if (!isset($array[$pos])) { $array[] = $newItem; } else { $array = array_splice($array, $pos, 0, $newItem); } return $array; } /** * Inserts an item before the specified key in the given array. If the * key is not found, inserts the item at the beginning of the array. * * @param array $array * @param mixed $key * @param mixed $newKey * @param mixed $newValue * @return array $newArray */ public static function insertBefore($array, $key, $newKey, $newValue) { $newArray = []; $keyFound = false; foreach ($array as $k => $v) { if ($k === $key) { $newArray[$newKey] = $newValue; $keyFound = true; } $newArray[$k] = $v; } if (!$keyFound) { $newArray = [$newKey => $newValue] + $newArray; } return $newArray; } /** * Inserts an item after the specified key in the given array. If the * key is not found, inserts the item at the end of the array. * * @param array $array * @param mixed $key * @param mixed $newKey * @param mixed $newValue * @return array $newArray */ public static function insertAfter($array, $key, $newKey, $newValue): array { $newArray = []; $keyFound = false; foreach ($array as $k => $v) { $newArray[$k] = $v; if ($k === $key) { $newArray[$newKey] = $newValue; $keyFound = true; } } if (!$keyFound) { $newArray[$newKey] = $newValue; } return $newArray; } /** * Tests whether at least one element in the array passes * the test implemented by the provided callback. * * @param array $array * @param callable $callback * @return bool */ public static function some($array, callable $callback) { foreach ($array as $k => $v) { if ($callback($v, $k, $array)) { return true; } } return false; } /** * Tests whether all elements in the array pass the * test implemented by the provided callback. * * @param array $array * @param callable $callback * @return bool */ public static function every($array, callable $callback) { foreach ($array as $k => $v) { if (!$callback($v, $k, $array)) { return false; } } return true; } /** * Finds the first element in the array that satisfies the * condition implemented by the callback function. * * @param array $array * @param callable $callback * @return mixed */ public static function find($array, callable $callback, $findKey = false) { foreach ($array as $k => $v) { if ($callback($v, $k, $array)) { return $findKey ? $k : $v; } } return null; } /** * Finds the first key in the array that satisfies the * condition implemented by the callback function. * * @param array $array * @param callable $callback * @return mixed */ public static function findKey($array, callable $callback) { return static::find($array, $callback, true); } }