BP_REST_Document_Folder_Endpoint::folder_tree_items( WP_REST_Request $request )

Retrieve document folder tree.

Description

Parameters

$request

(Required) Full details about the request.

Return

(WP_REST_Response) | WP_Error

Source

File: bp-document/classes/class-bp-rest-document-folder-endpoint.php

	public function folder_tree_items( $request ) {
		global $wpdb, $bp;

		$group_id = $request->get_param( 'group_id' );
		$user_id  = bp_loggedin_user_id();

		if ( empty( $group_id ) ) {
			$group_id = 0;
		}

		// phpcs:ignore
		$documents_folder_query = $wpdb->prepare( "SELECT * FROM {$bp->document->table_name_folder} WHERE user_id = %d AND group_id = %d ORDER BY id DESC", $user_id, $group_id );

		// phpcs:ignore
		$data = $wpdb->get_results( $documents_folder_query, ARRAY_A ); // db call ok; no-cache ok.

		if ( ! empty( $data ) ) {
			// Build array of item references.
			foreach ( $data as $key => &$item ) {
				$items_by_reference[ $item['id'] ] = &$item;
				// Children array.
				$items_by_reference[ $item['id'] ]['children'] = array();
			}
		}

		if ( ! empty( $data ) ) {
			// Set items as children of the relevant parent item.
			foreach ( $data as $key => &$item ) {
				if ( $item['parent'] && isset( $items_by_reference[ $item['parent'] ] ) ) {
					$items_by_reference [ $item['parent'] ]['children'][] = &$item;
				}
			}
		}

		if ( ! empty( $data ) ) {
			// Remove items that were added to parents elsewhere.
			foreach ( $data as $key => &$item ) {
				if ( $item['parent'] && isset( $items_by_reference[ $item['parent'] ] ) ) {
					unset( $data[ $key ] );
				}
			}
		}

		if ( ! empty( $data ) ) {
			$data = array_values( $data );
		}

		$response = rest_ensure_response( $data );

		/**
		 * Fires after a list of document's folder tree is fetched via the REST API.
		 *
		 * @since 0.1.0
		 *
		 * @param WP_REST_Response $response The response data.
		 * @param WP_REST_Request  $request  The request sent to the API.
		 */
		do_action( 'bp_rest_document_folder_tree_items', $response, $request );

		return $response;
	}

Changelog

Changelog
Version Description
0.1.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.