Convert to Facebook format to response

@return Array
965932
public function normalize()
    {
        $url = $this->getMediaUrl($this->mediaType);

        return [
            'type'    => $this->mediaType,
            'content' => [
                'attachment' => [
                    'type'    => $this->mediaType,
                    'payload' => [
                        'url'         => $url,
                        'is_reusable' => true
                    ]
                ]
            ]
        ];
    }
668767
private function extractHeadersFromResponse() {
    $response = "";
    $code = $this->response->getStatusCode();
    $text = HttpUtil::getResponseTextForCode($code);
    $response .= sprintf(self::STATUS_LINE_FORMAT, $code, $text);

    foreach($this->response->getHeaderList() as $header) {
      $response .= sprintf("%s: %s%s",
                           $header->getKey(),
                           $header->getValue(),
                           self::CRLF);
    }
    $response .= self::CRLF;
    return $response;
  }
1276468
public function index(): HTTPResponse
    {
        $body = null;
        $contentType = $this->getRequest()->getHeader('Content-Type');

        if ($contentType === 'application/json') {
            $body = json_decode($this->getRequest()->getBody(), true);
        } else {
            $body = $this->getRequest()->postVars();
        }

        if (empty($body)) {
            return $this->getErrorResponse(
                'No parameters could be found in request body. Did you correctly set the Content-Type header?',
                500
            );
        }

        // request needs parsed body
        $psrRequest = (new HttpRequestAdapter())->toPsr7($this->getRequest())
            ->withParsedBody($body);
        $psrResponse = new Response();

        $authServer = $this->serverGenerator->getServer();

        try {
            return (new HttpResponseAdapter())
                ->fromPsr7($authServer->respondToAccessTokenRequest($psrRequest, $psrResponse));
        } catch (OAuthServerException $e) {
            return $this->convertResponse($e->generateHttpResponse(new Response()));
        } catch (Exception $e) {
            return $this->getErrorResponse($e->getMessage());
        }
    }
327350
public function getAvatar(){
		//Get User picture
		$params = array(/*'access_token'=>$this->access_token,*/'height'=>512,'width'=>512,'redirect'=>0,'type'=>'square');
		$userPicture = $this->get('https://graph.facebook.com/'.$this->userInfo['id'].'/picture', $params);
		if(!isset($userPicture['data'])) {
			BLog::addToLog('[Social.FB] User photo is not set!',LL_ERROR);
			return false;
			}
		$result=$userPicture['data']['url'];
		return $result;
		}
1096413
public function getResponse()
	{
		if (method_exists($this->controller, 'getResponse'))
		{
			/** @var HttpResponse $response */
			$response = $this->controller->getResponse();
		}
		else
		{
			$response = new HttpResponse;
		}

		$fp = fopen('php://output', 'w');
		ob_start();
		fputcsv($fp, $this->header, $this->delimiter, $this->enclosure);
		foreach ($this->content as $i => $item)
		{
			try
			{
				$fields = $this->callback ? call_user_func($this->callback, $item) : $item;
				if (!is_array($fields))
				{
					throw new \RuntimeException('CsvExport can only accept arrays, '. gettype($fields) .' provided at index '. $i .'. Either use arrays when setting the records or use a callback to convert each record into an array.');
				}
				fputcsv($fp, $fields, $this->delimiter, $this->enclosure);
			}
			catch (\Exception $ex)
			{
				ob_end_clean();
				throw $ex;
			}
		}
		fclose($fp);
		$response->setContent(ob_get_clean());

		$response->getHeaders()->addHeaders(array(
			'Content-Type' => 'text/csv',
			'Content-Disposition' => 'attachment;filename="'. str_replace('"', '\\"', $this->name) .'.csv"',
		));

		return $response;
	}
676172
public function ajaxGetVisits()
    {
        $data = Base::getVisitsRepository()->orderBy('created_at', 'desc')->take(300)->get(['url', 'browser', 'ip', 'created_at', 'country']);

        return \Response::json(array('data' => $data));
    }
940262
public function getResponse()
    {
        $response = new Response();

        $message = new Message();
        $message->setData(['message' => $this->getMessage()]);

        if (!empty($this->getPrivateKey())) {
            $message->setCertificate($this->getCertificate());
            $message->sign($this->getPrivateKey());
        }

        $response->getBody()->write(json_encode($message));

        return $response
            ->withStatus($this->getCode())
            ->withAddedHeader('Content-Type', 'application/json');
    }
289936
public function handler(): Response
    {
        $response = [];
        foreach (Permission::all() as $permission) {
            $response[] = [
                'id' => $permission->getId(),
                'permission' => $permission->getPermission(),
                'role' => [
                    'id' => $permission->getRole()->getId(),
                    'name' => $permission->getRole()->getName(),
                    'slug' => $permission->getRole()->getSlug()
                ]
            ];
        }
        return response($response);
    }
1094708
private function formatResponse()
    {
        $return = array();

        // Method
        if (isset($this->state['method'])) {
            $return['method'] = $this->state['method'];
        }

        // Request
        if (!empty($this->state['request'])) {
            $return['request'] = $this->state['request'];
        }

        // Response
        if (!empty($this->state['response'])) {
            $return['response'] = $this->state['response'];
        }

        return $return;
    }
1098956
public function jsonSerialize()
    {
        ob_start();
        echo $this->renderSearchField();
        $field = ob_get_contents();
        ob_end_clean();

        $ag = ResponseAssetGroup::get();
        $assetsResponse = [];
        foreach ($ag->getAssetsToOutput() as $position => $assets) {
            foreach ($assets as $asset) {
                if (is_object($asset)) {
                    $assetsResponse[$asset->getAssetType()][] = $asset->getAssetURL();
                }
            }
        }

        return [
            'key' => $this->getKey(),
            'label' => $this->getDisplayName(),
            'element' => $field,
            'data' => $this->data,
            'assets' => $assetsResponse,
        ];
    }
1344151
public function getList()
	{
		$this->getResponse()
			->setStatusCode(Response::STATUS_CODE_200);
		
		// 1) getting params
		$page = (int) $this->params()->fromQuery("page", 1);
		$category = $this->params()->fromQuery("category", "usato");
		$purpose = $this->params()->fromQuery("purpose", "compravendita");
		$location = $this->params()->fromQuery("location", "italia");
		$limit = 30;
		$offset = ($page * $limit) - $limit;
		$returnSelect = true;
		
		// 2) Discard useless params and prepare them to be passed to the model
		$params = $this->requestToSearchParams($this->params()->fromQuery());
		$params = is_array($params) ? $params + compact('returnSelect', 'offset', 'limit') : array();
		
		if(empty($params)) {
            return new JsonModel(array());
		}
		
		// 3) get only for current user?
		$onlyCurrentUser = (bool) $this->params()->fromQuery("current", false);
		$k = 0;
		foreach($params['field'] as $f) {
			if('current' == $f || 'user' == $f) {
				unset($params['field'][$k]);
				unset($params['value'][$k]);
			}
			$k++;
		}
		if($onlyCurrentUser) {
			if($this->zfcUserAuthentication()->hasIdentity()) {
				$identity = $this->zfcUserAuthentication()->getIdentity();
// 				$params['field'][] = 'user';
// 				$params['value'][] = sha1('neo' . $identity->getUserId() . 'bazaar');
				$params['field'][] = 'account';
				$params['value'][] = sha1('neo' . $identity->getUserId() . 'bazaar');
			} else {
				// Questo è necessario per non far restituire la lista completa se l'utente non è connesso
				$params['field'][] = 'account';
				$params['value'][] = sha1('usernotconnected');
			}
		}
		
		// 4) all classifieds? This should be requested only by the admin, will not use sphinx
		if((bool) $this->params()->fromQuery("full", false)) {
			if($this->zfcUserAuthentication()->hasIdentity()) {
			    $params = $this->params()->fromQuery();
				$identity = $this->zfcUserAuthentication()->getIdentity();
				$userModel = $this->getServiceLocator()->get('user.model.user');
				$userModel->init($identity, $this->getServiceLocator());
				if(!$userModel->getIsAdmin()) {
				    return new JsonModel(array());
				}
				
				$paginator = $this->getServiceLocator()->get('document.paginator.classifiedFull');
				$paginator->build($params);

				$data = array();
				foreach($paginator as $post) {
            		$file = $this->getServiceLocator()->get('document.model.classifiedAdminListing');
				    $data[] = $file->init($post);
				}

				$routeName = 'DocumentAdminClassified/page';
				$routeParams = array('page' => $this->params()->fromQuery("page", 1));
				$queryParams = array('full' => 1, 'user' => $this->params()->fromQuery("user"));
				$data = $this->getModel()->getPaginationData($this->getServiceLocator(), $paginator, $data, $routeName, $routeParams, $queryParams);

				return new JsonModel($data);
			}
		}
		
		// 5) Pass param to the model and get the data
		$data = $this->getModel()->getList($params, $this->getServiceLocator());
		
		return new JsonModel($data);
	}
1710
protected function handleRequest()
    {
        $message = $this->getMessage();
        $response = $this->handleMessage($message);

        return [
            'to'       => $message['FromUserName'],
            'from'     => $message['ToUserName'],
            'response' => $response,
        ];
    }
1168812
private function format()
    {
        $request_uri = sprintf('%s %s', $this->request->getMethod(), $this->request->getBasePath().$this->request->getPathInfo());

        $ret = [
            'meta' => [
                'api_version'   => $this->getVersion(),
                'request'       => $request_uri,
                'response_time' => $this->responseTime,
                'http_code'     => $this->code,
                'error_type'    => $this->errorType,
                'error_message' => $this->errorMessage,
                'error_details' => $this->errorDetails,
                'charset'       => 'UTF-8',
            ],
            'response'          => $this->data,
        ];

        switch ($this->responseType) {
            case self::FORMAT_JSON:
            default:
                return new JsonResponse($ret);
            case self::FORMAT_YAML:
                if ($ret['response'] instanceof \stdClass) {
                    $ret['response'] = [];
                }

                $dumper = new Dumper();

                return new Response($dumper->dump($ret, 8));
            case self::FORMAT_JSONP:
                $response = new JsonResponse($ret);
                $response->setCallback(trim($this->request->get('callback')));

                return $response;
                break;
        }
    }
844508
public function handler(): Response
    {
        $response = [];
        foreach (Bulletin::all() as $bulletin) {
            $response[] = [
                'id' => $bulletin->getId(),
                'createdAt' => $bulletin->getCreatedAt()->getTimestamp(),
                'title' => $bulletin->getTitle(),
                'abstract' => $bulletin->getAbstract(),
                'isDraft' => $bulletin->isDraft(),
                'statistics' => $bulletin->getStatistics()
            ];
        }
        return response($response);
    }
1035654
public function loginFromOAuthResponseAction()
    {
        $userManager = $this->container->get('fos_user.user_manager');
        $userIdentityField = $this->container->get('rch_jwt_user.user_identity_field');

        $data = $this->get('rch_jwt_user.credential_fetcher')
            ->create([
                $userIdentityField      => ['requirements' => $userIdentityField == 'email' ? new Email() : '[^/+]'],
                'facebook_id'           => ['requirements' => '\d+'],
                'facebook_access_token' => ['requirements' => '[^/]+'],
            ])
            ->all();

        if (true !== $this->isValidFacebookAccount($data['facebook_id'], $data['facebook_access_token'])) {
            throw new InvalidPropertyUserException('The given facebook_id does not correspond to a valid acount');
        }

        $user = $userManager->findUserBy(['facebookId' => $data['facebook_id']]);

        if ($user) {
            return $this->renderToken($user);
        }

        $user = $userManager->findUserBy([$userIdentityField => $data[$userIdentityField]]);

        if ($user) {
            $user->setFacebookId($data['facebook_id']);
            $userManager->updateUser($user);

            return $this->renderToken($user);
        }

        $data['password'] = $this->generateRandomPassword();

        return $this->renderToken($this->createUser($data));
    }
758145
public function getResponse()
    {
        $curl = curl_init();

        $this->addParameters()->addHeaders();
        $this->options[CURLOPT_RETURNTRANSFER] = true;
        curl_setopt_array($curl, $this->options);

        $response = curl_exec($curl);

        $this->meta = array(
            'info'             => curl_getinfo($curl, CURLINFO_HTTP_CODE),
            'error_message'    => curl_errno($curl),
            'error_code'    => curl_error($curl));

        curl_close($curl);
        unset($curl);

        return $response;
    }
554600
public function userRegisterCallback() {
    $sdk = $this->getSdk('register');

    if ($sdk instanceof RedirectResponse) {
      return $sdk;
    }

    $this->authManager->setSdk($sdk);
    $profile = $this->getProfile('register');

    if ($profile instanceof RedirectResponse) {
      return $profile;
    }

    // Check whether user account exists. If account already exists,
    // authorize the user and redirect him to the account page.
    $account = $this->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
        'facebook_id' => $profile->getField('id'),
      ]);

    if ($account) {
      $account = current($account);

      if (!$account->get('status')->value) {
        drupal_set_message($this->t('You already have account on this site, but your account is blocked. Contact the site administrator.'), 'error');
        return $this->redirect('user.register');
      }

      user_login_finalize($account);
      return $this->redirect('entity.user.canonical', [
        'user' => $account->id(),
      ]);
    }

    // Save email and name to storage to use for auto fill the registration
    // form.
    $data_handler = $this->networkManager->createInstance('social_auth_facebook')->getDataHandler();
    $data_handler->set('access_token', $this->accessToken);
    $data_handler->set('mail', $profile->getField('email'));
    $data_handler->set('name', $profile->getField('name'));

    drupal_set_message($this->t('You are now connected with @network, please continue registration', [
      '@network' => $this->t('Facebook'),
    ]));

    return $this->redirect('user.register', [
      'provider' => 'facebook',
    ]);
  }