<commit_before><?php

namespace RestGistBundle\Controller;

use BetterGistsBundle\Entity\Gist;
use BetterGistsBundle\Entity\Tags;
use Doctrine\ORM\Query;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use RestGistBundle\Controller\TokenAuthenticationController;
use Symfony\Component\HttpKernel\Exception\HttpException;

// JWT.
use Psecio\Jwt\Header;
use Psecio\Jwt\Claim;
use BetterGistsBundle\DependencyInjection\JwtBetterGist;

// JSON Encoders.
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

// Entity Repository.
use Doctrine\ORM\EntityRepository;

class RestGistController extends Controller implements TokenAuthenticationController
{
  /**
   * Index function.
   * @Route("/gists", name="rest_gist_index")
   * @Method({"GET", "POST"})
   */
  public function indexRestAction(Request $request)
  {
    $uid = $this->get('jwt.requestparser')->getUserIdFromRequest($request);
    $request_method = $request->getMethod();

    if($request_method === "POST") {

      $all = $request->request->all();
      if(isset($all)) {

        if(empty($request->request->get('title'))) {
            $json_response = new JsonResponse();
            $json_response->setContent('title cannot be empty');
            $json_response->setStatusCode(400);
            return $json_response;
        }

        $em = $this->getDoctrine()->getManager();

        $author_repository = $this->getDoctrine()->getRepository('AppBundle:User');
        $author = $author_repository->find($uid);
        $gist = new Gist();
        $gist->setTitle($request->request->get('title'));
        $gist->setBody($request->request->get('body'));
        $gist->setAuthor($author);
        $gist->setCreated(new \DateTime('now'));
        $gist->setUpdated(new \DateTime('now'));

        // Tags.
        $tags = $request->request->get('tags');

        // todo move to a service or a private function.
        // should accept two params gist and tags array.

        if(!is_null($tags)) {

          $tag_instance = new Tags();

          $tags_repository = $this->getDoctrine()->getRepository('BetterGistsBundle:Tags');

          foreach ($tags as $tag) {

            $tag_name = $tag['name'];
            $tag_in_db = $tags_repository->findByExactName($tag_name);

            if($tag_in_db instanceof $tag_instance) {
              $gist->getTags()->add($tag_in_db);
            } else {
              // create a new tag.
              $new_tag = new Tags();
              $new_tag->setName($tag_name);
              $em->persist($new_tag);
              $gist->getTags()->add($new_tag);
            }

          }

        }

        // Persist Gist.
        $em->persist($gist);
        $em->flush();

        $gid = $gist->getId();
        $gist_repository = $this->getDoctrine()->getManager()->getRepository('BetterGistsBundle:Gist');
        $gist_array = $gist_repository->getGistById($gid, $uid, TRUE);
        $json_content = $this->jsonIndexResponse($gist_array);

      }

    } elseif ($request_method === "GET") {


      /**
       * Todo tranform this in class.
       * Query builder test.
       */

      $gist_repo = $this->getDoctrine()->getRepository('BetterGistsBundle:Gist');

      $query_params = $request->query->all();

      $qb = $gist_repo->createQueryBuilder('gist');

      if ($query_params['updated'] === 'ASC') {
        $qb->orderBy('gist.updated', 'ASC');
      } else if ($query_params['updated'] === 'DESC') {
        $qb->orderBy('gist.updated', 'DESC');
      }

      $qb->andWhere('gist.author = :author');
      $qb->setParameter(':author', $uid);
      $qb->setMaxResults(2);

      $result = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);

      // ----------------------- //

      $json_content = $this->jsonIndexResponse($result);

    }

    $response = new Response();
    $response->headers->set('Content-type','application/json');
    $response->setContent($json_content);

    return $response;
    
  }

  /**
   * Get single Gist.
   * @Route("/gists/{gist_id}", name="rest_gist_by_id")
   * @Method({"GET", "POST", "DELETE"})
   */
  public function getGistAction(Request $request, $gist_id)
  {

    $request_parser = $this->get('jwt.requestparser');
    $uid = $request_parser->getUserIdFromRequest($request);

    $request_method = $request->getMethod();
<commit_msg>added some params to the get_gists request<commit_after><?php

namespace RestGistBundle\Controller;

use BetterGistsBundle\Entity\Gist;
use BetterGistsBundle\Entity\Tags;
use Doctrine\ORM\Query;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use RestGistBundle\Controller\TokenAuthenticationController;
use Symfony\Component\HttpKernel\Exception\HttpException;

// JWT.
use Psecio\Jwt\Header;
use Psecio\Jwt\Claim;
use BetterGistsBundle\DependencyInjection\JwtBetterGist;

// JSON Encoders.
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

// Entity Repository.
use Doctrine\ORM\EntityRepository;

class RestGistController extends Controller implements TokenAuthenticationController
{
  /**
   * Index function.
   * @Route("/gists", name="rest_gist_index")
   * @Method({"GET", "POST"})
   */
  public function indexRestAction(Request $request)
  {
    $uid = $this->get('jwt.requestparser')->getUserIdFromRequest($request);
    $request_method = $request->getMethod();

    if($request_method === "POST") {

      $all = $request->request->all();
      if(isset($all)) {

        if(empty($request->request->get('title'))) {
            $json_response = new JsonResponse();
            $json_response->setContent('title cannot be empty');
            $json_response->setStatusCode(400);
            return $json_response;
        }

        $em = $this->getDoctrine()->getManager();

        $author_repository = $this->getDoctrine()->getRepository('AppBundle:User');
        $author = $author_repository->find($uid);
        $gist = new Gist();
        $gist->setTitle($request->request->get('title'));
        $gist->setBody($request->request->get('body'));
        $gist->setAuthor($author);
        $gist->setCreated(new \DateTime('now'));
        $gist->setUpdated(new \DateTime('now'));

        // Tags.
        $tags = $request->request->get('tags');

        // todo move to a service or a private function.
        // should accept two params gist and tags array.

        if(!is_null($tags)) {

          $tag_instance = new Tags();

          $tags_repository = $this->getDoctrine()->getRepository('BetterGistsBundle:Tags');

          foreach ($tags as $tag) {

            $tag_name = $tag['name'];
            $tag_in_db = $tags_repository->findByExactName($tag_name);

            if($tag_in_db instanceof $tag_instance) {
              $gist->getTags()->add($tag_in_db);
            } else {
              // create a new tag.
              $new_tag = new Tags();
              $new_tag->setName($tag_name);
              $em->persist($new_tag);
              $gist->getTags()->add($new_tag);
            }

          }

        }

        // Persist Gist.
        $em->persist($gist);
        $em->flush();

        $gid = $gist->getId();
        $gist_repository = $this->getDoctrine()->getManager()->getRepository('BetterGistsBundle:Gist');
        $gist_array = $gist_repository->getGistById($gid, $uid, TRUE);
        $json_content = $this->jsonIndexResponse($gist_array);

      }

    } elseif ($request_method === "GET") {


      /**
       * Todo tranform this in class.
       * Query builder test.
       */

      $query_params_from_request = $request->query->all();

      $gist_repo = $this->getDoctrine()->getRepository('BetterGistsBundle:Gist');

      $qb = $gist_repo->createQueryBuilder('gist');

      if(isset($query_params['updated'])) {
        if ($query_params['updated'] === 'ASC') {
          $qb->orderBy('gist.updated', 'ASC');
        } else if ($query_params['updated'] === 'DESC') {
          $qb->orderBy('gist.updated', 'DESC');
        }
      }

      if(isset($query_params['created'])) {
        if ($query_params['created'] === 'ASC') {
          $qb->orderBy('gist.created', 'ASC');
        } else if ($query_params['created'] === 'DESC') {
          $qb->orderBy('gist.created', 'DESC');
        }
      }

      $qb->andWhere('gist.author = :author');
      $qb->setParameter(':author', $uid);
      $qb->setMaxResults(1);

      $result = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);

      // Response.
      $json_content = $this->jsonIndexResponse($result);

    }

    $response = new Response();
    $response->headers->set('Content-type','application/json');
    $response->setContent($json_content);

    return $response;
    
  }

  /**
   * Get single Gist.
   * @Route("/gists/{gist_id}", name="rest_gist_by_id")
   * @Method({"GET", "POST", "DELETE"})
   */
  public function getGistAction(Request $request, $gist_id)
  {

    $request_parser = $this->get('jwt.requestparser');
    $uid = $request_parser->getUserIdFromRequest($request);

    $request_method = $request->getMethod();

{'fraction_non_alphanumeric': 0.16461664616646166, 'fraction_numerical': 0.0008200082000820008, 'mean_word_length': 2.9873314262362074, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 127, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2554873', 'n_tokens_mistral': 3017, 'n_tokens_neox': 2936, 'n_words': 466}