Prepares a single term output for response.

@param obj             $item    Term object.
@param WP_REST_Request $request Request object.
@return WP_REST_Response $response
184439
public function prepare_item_for_response( $item, $request ) {

		$schema = $this->get_item_schema();
		$data = array();
		if ( ! empty( $schema['properties']['id'] ) ) {
			$data['id'] = (int) $item->term_id;
		}
		if ( ! empty( $schema['properties']['count'] ) ) {
			$data['count'] = (int) $item->count;
		}
		if ( ! empty( $schema['properties']['description'] ) ) {
			$data['description'] = $item->description;
		}
		if ( ! empty( $schema['properties']['link'] ) ) {
			$data['link'] = get_term_link( $item );
		}
		if ( ! empty( $schema['properties']['name'] ) ) {
			$data['name'] = $item->name;
		}
		if ( ! empty( $schema['properties']['slug'] ) ) {
			$data['slug'] = $item->slug;
		}
		if ( ! empty( $schema['properties']['taxonomy'] ) ) {
			$data['taxonomy'] = $item->taxonomy;
		}
		if ( ! empty( $schema['properties']['parent'] ) ) {
			$data['parent'] = (int) $item->parent;
		}
		if ( ! empty( $schema['properties']['meta'] ) ) {
			$data['meta'] = $this->meta->get_value( $item->term_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 );

		$response = rest_ensure_response( $data );

		$response->add_links( $this->prepare_links( $item ) );

		/**
		 * Filters a term item returned from the API.
		 *
		 * Allows modification of the term data right before it is returned.
		 *
		 * @param WP_REST_Response  $response  The response object.
		 * @param object            $item      The original term object.
		 * @param WP_REST_Request   $request   Request used to generate the response.
		 */
		return apply_filters( "rest_prepare_{$this->taxonomy}", $response, $item, $request );
	}
459122
private function processForm(Item $item) {

        $created = ($item && null === $item->getId());
        $statusCode = ($created)? Response::HTTP_CREATED : Response::HTTP_NO_CONTENT;
        $method = ($created) ? "POST" : "PUT";

        $form = $this->createForm(new ItemType(), $item, array('method' => $method));
        $form->handleRequest($this->getRequest());

        $view;
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($item);
            $em->flush();

            $view = $this->view()->setStatusCode($statusCode);

            // HTTP Convention : return HTTP 201 Created + Location of created resource
            if ($created) {
                $view->setLocation(
                    $this->generateUrl('get_item', ['id' => $item->getId()])
                );
            }
        } else {
            $view = $this->view($form, Response::HTTP_BAD_REQUEST);
        }

        return $this->handleView($view);
    }
836215
public function delete_item( $request ) {
		$id = (int) $request['id'];
		$reassign = isset( $request['reassign'] ) ? absint( $request['reassign'] ) : null;
		$force = isset( $request['force'] ) ? (bool) $request['force'] : false;

		// We don't support trashing for this type, error out
		if ( ! $force ) {
			return new WP_Error( 'rest_trash_not_supported', __( 'Users do not support trashing.' ), array( 'status' => 501 ) );
		}

		$user = get_userdata( $id );
		if ( ! $user ) {
			return new WP_Error( 'rest_user_invalid_id', __( 'Invalid resource id.' ), array( 'status' => 404 ) );
		}

		if ( ! empty( $reassign ) ) {
			if ( $reassign === $id || ! get_userdata( $reassign ) ) {
				return new WP_Error( 'rest_user_invalid_reassign', __( 'Invalid resource id for reassignment.' ), array( 'status' => 400 ) );
			}
		}

		$request->set_param( 'context', 'edit' );
		$response = $this->prepare_item_for_response( $user, $request );

		/** Include admin user functions to get access to wp_delete_user() */
		require_once ABSPATH . 'wp-admin/includes/user.php';

		$result = wp_delete_user( $id, $reassign );

		if ( ! $result ) {
			return new WP_Error( 'rest_cannot_delete', __( 'The resource cannot be deleted.' ), array( 'status' => 500 ) );
		}

		/**
		 * Fires after a user is deleted via the REST API.
		 *
		 * @param WP_User          $user     The user 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_user', $user, $response, $request );

		return $response;
	}
689080
protected function handlePut($item, $data)
    {
        PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s %s", $item, $data);
        throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
    }
939922
public function indexAction(Request $request)
    {
        $dispatcher = $this->get('event_dispatcher');
        $event = new ResponseEvent($request);
        $dispatcher->dispatch(OpiferMediaEvents::MEDIA_CONTROLLER_INDEX, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $media = $this->get('opifer.media.media_manager')->getPaginatedByRequest($request);

        $items = $this->get('jms_serializer')->serialize(iterator_to_array($media->getCurrentPageResults()), 'json', SerializationContext::create()->setGroups(['Default', 'list']));

        return new JsonResponse([
            'results' => json_decode($items, true),
            'total_results' => $media->getNbResults(),
            'results_per_page' => $media->getMaxPerPage(),
        ]);
    }
1362707
public function changeAction(Item $item, Request $request)
    {
        /* @var $form Form */
        $form = $this->createForm('entity_item', $item)
            ->handleRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($item);
            $em->flush();

            return $this->redirect($this->generateUrl(
                'item_show',
                ['id' => $item->getId(), 'name' => $item->getUrlName()]
            ));
        }

        return $this->render('AnimeDbCatalogBundle:Item:change.html.twig', [
            'item' => $item,
            'form' => $form->createView(),
        ]);
    }
792863
public function resolve(CartItem $item, Request $request)
    {
        
        $productId = $request->query->get('id');
        $itemForm = $request->request->get('cart_item_simple');

        $productRepository = $this->manager->getRepository('EcommerceBundle:Product');
        if (!$productId || !$product = $productRepository->find($productId)) {
            // no product id given, or product not found
            throw new \Exception('Requested product was not found');
        }

        // assign the product and quantity to the item
        $item->setProduct($product);
        $item->setQuantity(intval($itemForm['quantity']));

        // calculate item price adding the special charge
        $price = $product->getPrice();
        if ($this->specialPercentageCharge > 0) {
            $price += $price * ($this->specialPercentageCharge / 100);
        }
        $item->setUnitPrice(intval($price));

        return $item;
    }
1036148
public function addMenuItem(Request $request, array $item, MenuItem $menu)
    {
        $attributes = array();

        // if the menu item has a name, add it as a css class.
        if ($name = $item['name']) {
            $attributes['class'] = $name;
        }
        if (empty($item['path'])) {
            $uri = null;
        } elseif (preg_match('!^(?:https?://|mailto:)!', $item['path'])) {
            $uri = $item['path'];
        } else {
            $baseUrl = $request->getBaseUrl();
            $uri = $baseUrl . '/' . ltrim($item['path'], '/');
        }

        $menuItem = $menu->addChild(
            $item['id'],
            array(
                'uri' => $uri,
                'attributes' => $attributes,
                'label' => $item['title']
            )
        );

        if (!empty($item['json_data'])) {
            $item['json_data'] = @json_decode($item['json_data']);
        }

        $menuItem->setExtras($item);
        return $menuItem;
    }
52419
public function formatItem($item, $format = 'json')
    {
        $formatted = null;

        switch ($format) {
            case 'json':
                // serialize properties with null values
                $context = new SerializationContext();
                $context->setSerializeNull(true);
                $context->enableMaxDepthChecks(true);
                $formatted = $this->getSerializer()->serialize($item, 'json', $context);
                break;
            case 'jsonp':
                $callback = $this->getRequest()->query->get('jsonp.callback', 'JSONP.callback');

                // validate against XSS
                $validator = new \JsonpCallbackValidator();
                if (!$validator->validate($callback)) {
                    throw new BadRequestHttpException('Invalid JSONP callback value');
                }

                $context = new SerializationContext();
                $context->setSerializeNull(true);
                $json = $this->getSerializer()->serialize($item, 'json');

                $formatted = sprintf('/**/%s(%s)', $callback, $json);
                break;
            default:
                // any other format is not supported
                throw new \InvalidArgumentException(sprintf('Format not supported: %s', $format));
        }

        return $formatted;
    }
597442
public function delete_item( $request ) {
		$id = (int) $request['id'];
		$force = (bool) $request['force'];

		$post = $this->get_post( $id );

		if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
			return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post id.' ), array( 'status' => 404 ) );
		}

		$supports_trash = ( EMPTY_TRASH_DAYS > 0 );
		if ( 'attachment' === $post->post_type ) {
			$supports_trash = $supports_trash && MEDIA_TRASH;
		}

		/**
		 * Filter whether a post is trashable.
		 *
		 * Return false to disable trash support for the post.
		 *
		 * @param boolean $supports_trash Whether the post type support trashing.
		 * @param WP_Post $post           The Post object being considered for trashing support.
		 */
		$supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post );

		if ( ! $this->check_delete_permission( $post ) ) {
			return new WP_Error( 'rest_user_cannot_delete_post', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		$request->set_param( 'context', 'edit' );
		$response = $this->prepare_item_for_response( $post, $request );

		// If we're forcing, then delete permanently.
		if ( $force ) {
			$result = wp_delete_post( $id, true );
		} else {
			// If we don't support trashing for this type, error out.
			if ( ! $supports_trash ) {
				return new WP_Error( 'rest_trash_not_supported', __( 'The post does not support trashing.' ), array( 'status' => 501 ) );
			}

			// Otherwise, only trash if we haven't already.
			if ( 'trash' === $post->post_status ) {
				return new WP_Error( 'rest_already_trashed', __( 'The post has already been deleted.' ), array( 'status' => 410 ) );
			}

			// (Note that internally this falls through to `wp_delete_post` if
			// the trash is disabled.)
			$result = wp_trash_post( $id );
		}

		if ( ! $result ) {
			return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) );
		}

		/**
		 * Fires after a single post is deleted or trashed via the REST API.
		 *
		 * @param object           $post     The deleted or trashed post.
		 * @param WP_REST_Response $response The response data.
		 * @param WP_REST_Request  $request  The request sent to the API.
		 */
		do_action( "rest_delete_{$this->post_type}", $post, $response, $request );

		return $response;
	}
1172628
public function get_item( $request ) {
		$id = (int) $request['id'];

		$comment = get_comment( $id );
		if ( empty( $comment ) ) {
			return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment id.' ), array( 'status' => 404 ) );
		}

		if ( ! empty( $comment->comment_post_ID ) ) {
			$post = $this->get_post( $comment->comment_post_ID );
			if ( empty( $post ) ) {
				return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post id.' ), array( 'status' => 404 ) );
			}
		}

		$data = $this->prepare_item_for_response( $comment, $request );
		$response = rest_ensure_response( $data );

		return $response;
	}
260488
public function get_item( $request ) {

		$meta = Book::getBookInformation();
		$meta = $this->buildMetadata( $meta );

		$response = rest_ensure_response( $meta );
		$this->linkCollector['self'] = [
			'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
		];
		$response->add_links( $this->linkCollector );

		return $response;
	}
96839
protected function generateResponseForRequest($request = null)
    {
        $leafClass = $this->getPresenterClassName();
        $leaf = new $leafClass();
        $leaf->itemIdentifier = $this->resourceIdentifier;

        $response = $leaf->generateResponse($request);

        if (is_string($response)) {
            $htmlResponse = new HtmlResponse($leaf);
            $htmlResponse->setContent($response);
            $response = $htmlResponse;
        }

        return $response;
    }
1064282
public function prepare_item_for_database( $request ) {
		$prepared_term = new stdClass;

		$schema = $this->get_item_schema();
		if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
			$prepared_term->name = $request['name'];
		}

		if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) {
			$prepared_term->slug = $request['slug'];
		}

		if ( isset( $request['taxonomy'] ) && ! empty( $schema['properties']['taxonomy'] ) ) {
			$prepared_term->taxonomy = $request['taxonomy'];
		}

		if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) {
			$prepared_term->description = $request['description'];
		}

		if ( isset( $request['parent'] ) && ! empty( $schema['properties']['parent'] ) ) {
			$parent_term_id = 0;
			$parent_term = get_term( (int) $request['parent'], $this->taxonomy );

			if ( $parent_term ) {
				$parent_term_id = $parent_term->term_id;
			}

			$prepared_term->parent = $parent_term_id;
		}

		/**
		 * Filters term data before inserting term via the REST API.
		 *
		 * @param object          $prepared_term Term object.
		 * @param WP_REST_Request $request       Request object.
		 */
		return apply_filters( "rest_pre_insert_{$this->taxonomy}", $prepared_term, $request );
	}
151830
public function prepareItems($items)
    {

        if (is_array($items) && !empty($items)) {
            foreach ($items as $key => &$item) {

                //Get linked post object.
                $postData = is_object($item['page']) ? $item['page'] : false;

                //Linking
                if ($item['link_type'] == 'external') {
                    $item['permalink'] = $item['link_url'];
                } elseif (is_object($postData) && isset($postData->ID) && $item['link_type'] == 'internal') {
                    $item['permalink'] = get_permalink($postData->ID);
                }

                //Thumbnail
                $item['thumbnail'] = $this->getThumbnail($item);

                if ($postData !== false && get_post_status($postData->ID)) {

                    //Retrive post content & lead
                    if (is_object($postData) && isset($postData->ID)) {
                        $item['title']          = $this->switchContent($item['title'], $postData->post_title);
                        $item['lead']           = $this->switchContent($item['lead'], $this->parseExcerpt($postData->post_content));
                    }

                } else {
                    unset($item);
                }

                //Removes empty/unfetchable objects from index
                if($item['link_type'] == "internal" && empty($item['title']) && empty($item['lead']) && empty($item['thumbnail']) && empty($item['permalink'])) {
                    unset($items[$key]);
                }

            }
        }

        return $items;
    }
431365
protected function buildResponseProcessing(DOMElement $data, Item $item){
        $returnValue = null;

        // try template
        try{
            $returnValue = $this->buildTemplateResponseProcessing($data);

            try{
                //warning: require to add interactions to the item to make it work
                $returnValue = TemplatesDriven::takeOverFrom($returnValue, $item);
            }catch(TakeoverFailedException $e){}
        }catch(UnexpectedResponseProcessing $e){

        }

        //try templatedriven
        if(is_null($returnValue)){
            try{
                $returnValue = $this->buildTemplatedrivenResponse($data, $item->getInteractions());
            }catch(UnexpectedResponseProcessing $e){}
        }

        // build custom
        if(is_null($returnValue)){
            try{
                $returnValue = $this->buildCustomResponseProcessing($data);
            }catch(UnexpectedResponseProcessing $e){
                // not a Template
                common_Logger::e('custom response processing failed', array('TAOITEMS', 'QTI'));
            }
        }

        if(is_null($returnValue)){
            common_Logger::w('failed to determine ResponseProcessing');
        }

        return $returnValue;
    }
775996
public function prepare_response_for_collection( $response ) {
		if ( ! ( $response instanceof WP_REST_Response ) ) {
			return $response;
		}

		$data = (array) $response->get_data();
		$server = rest_get_server();

		if ( method_exists( $server, 'get_compact_response_links' ) ) {
			$links = call_user_func( array( $server, 'get_compact_response_links' ), $response );
		} else {
			$links = call_user_func( array( $server, 'get_response_links' ), $response );
		}

		if ( ! empty( $links ) ) {
			$data['_links'] = $links;
		}

		return $data;
	}