controller with LINK method
<?php
namespace AppBundle\Controller\Rest;
use AppBundle\Entity\Candidate;
use AppBundle\Event\CandidateApplyForJobEvent;
use AppBundle\Repository\JobRepository;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Link;
use FOS\RestBundle\Controller\Annotations\Route;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* @Route(service="app.controller.job")
*/
class JobController extends FOSRestController implements TokenAuthenticatedController
{
private $repository;
private $dispatcher;
/**
* JobController constructor.
*
* @param JobRepository $repository
* @param EventDispatcherInterface $dispatcher
*/
public function __construct(JobRepository $repository, EventDispatcherInterface $dispatcher) {
$this->repository = $repository;
$this->dispatcher = $dispatcher;
}
/**
* @Get("/job/{id}", name="get_job", options={"method_prefix" = false})
*
* @return View
*/
public function getAction($id)
{
if (null == $job = $this->repository->find($id)) {
throw new NotFoundHttpException("No job with id=$id was found");
}
return $this->view($job, Response::HTTP_OK);
}
/**
* @Get("/jobs/count", name="jobs_count", options={"method_prefix" = false})
*
* @return View
*/
public function countAction()
{
$count = $this->repository->countActivated();
return $this->view(['count' => $count], Response::HTTP_OK);
}
/**
* @Link("/job/{id}/candidate", name="link_candidate_to_job", options={"method_prefix" = false})
*
* @return View
*
* @throws NotFoundHttpException
* @throws BadRequestHttpException
* @throws ConflictHttpException
*/
public function linkCandidateAction($id, Request $request)
{
if (null == $job = $this->repository->find($id)) {
throw new NotFoundHttpException("No job with id=$id was found");
}
if (!$request->headers->has('link')) {
throw new BadRequestHttpException('Link header was not set');
}
foreach ($request->attributes->get('link') as $candidate) {
if (!$candidate instanceof Candidate) {
throw new NotFoundHttpException('Link contains invalid resource');
}
if ($job->hasCandidate($candidate)) {
throw new ConflictHttpException('Candidate has already been applied for this job');
}
$job->addCandidate($candidate);
$this->repository->save($job);
$event = new CandidateApplyForJobEvent($candidate, $job);
$event->addAttachment($candidate->getResumeFile());
$this->dispatcher->dispatch(
CandidateApplyForJobEvent::APP_CANDIDATE_APPLY,
$event
);
}
return $this->view(null, Response::HTTP_OK);
}
}