gist/src/Gist/Controller/ApiController.php

129 lines
3.3 KiB
PHP
Raw Normal View History

2015-07-19 16:45:55 +02:00
<?php
namespace Gist\Controller;
use Symfony\Component\HttpFoundation\Request;
use Gist\Model\Gist;
use Symfony\Component\HttpFoundation\JsonResponse;
use Gist\Form\ApiCreateGistForm;
2015-11-07 22:13:08 +01:00
use Gist\Model\GistQuery;
use Gist\Form\ApiUpdateGistForm;
2015-07-19 16:45:55 +02:00
/**
2016-11-13 00:44:23 +01:00
* Class ApiController.
*
2015-07-19 16:45:55 +02:00
* @author Simon Vieille <simon@deblan.fr>
*/
class ApiController extends Controller
{
public function createAction(Request $request)
2015-07-19 16:45:55 +02:00
{
$app = $this->getApp();
2015-07-19 16:45:55 +02:00
if (false === $request->isMethod('post')) {
return $this->invalidMethodResponse('POST method is required.');
}
$form = new ApiCreateGistForm(
$app['form.factory'],
$app['translator'],
[],
['csrf_protection' => false]
);
$form = $form->build()->getForm();
$form->submit($request);
if ($form->isValid()) {
$gist = $app['gist']->create(new Gist(), $form->getData());
$gist->setCipher(false)->save();
$history = $app['gist']->getHistory($gist);
return new JsonResponse(array(
'url' => $request->getSchemeAndHttpHost().$app['url_generator']->generate(
'view',
array(
'gist' => $gist->getFile(),
'commit' => array_pop($history)['commit'],
)
),
'gist' => $gist->toArray(),
));
}
return $this->invalidRequestResponse('Invalid field(s)');
}
public function updateAction(Request $request, $gist)
2015-11-07 22:13:08 +01:00
{
$app = $this->getApp();
2015-11-07 22:13:08 +01:00
if (false === $request->isMethod('post')) {
return $this->invalidMethodResponse('POST method is required.');
}
$gist = GistQuery::create()
->filterByCipher(false)
2015-11-07 22:27:41 +01:00
->filterById((int) $gist)
->_or()
->filterByFile($gist)
2015-11-07 22:13:08 +01:00
->findOne();
if (!$gist) {
return $this->invalidRequestResponse('Invalid Gist');
}
$form = new ApiUpdateGistForm(
$app['form.factory'],
$app['translator'],
[],
['csrf_protection' => false]
);
$form = $form->build()->getForm();
$form->submit($request);
if ($form->isValid()) {
$gist = $app['gist']->commit($gist, $form->getData());
$history = $app['gist']->getHistory($gist);
return new JsonResponse(array(
'url' => $request->getSchemeAndHttpHost().$app['url_generator']->generate(
'view',
array(
'gist' => $gist->getFile(),
'commit' => array_pop($history)['commit'],
)
),
'gist' => $gist->toArray(),
));
}
return $this->invalidRequestResponse('Invalid field(s)');
}
2015-07-19 16:45:55 +02:00
protected function invalidMethodResponse($message = null)
{
$data = [
'error' => 'Method Not Allowed',
'message' => $message,
];
return new JsonResponse($data, 405);
}
protected function invalidRequestResponse($message = null)
{
$data = [
2015-07-19 18:39:46 +02:00
'error' => 'Bad Request',
2015-07-19 16:45:55 +02:00
'message' => $message,
];
return new JsonResponse($data, 400);
}
}