1
0
mirror of https://gitnet.fr/deblan/gist.git synced 2021-08-14 08:30:49 +02:00

API: create

This commit is contained in:
Simon Vieille 2015-07-19 16:45:55 +02:00
parent 5fb853f3d5
commit 0d0403e242
4 changed files with 99 additions and 2 deletions

View File

@ -29,3 +29,7 @@ download:
revisions:
path: /revs/{gist}
defaults: {_controller: Gist\Controller\ViewController::revisionsAction, _locale: en}
api_create:
path: /api/create
defaults: {_controller: Gist\Controller\ApiController::createAction, _locale: en}

View File

@ -0,0 +1,74 @@
<?php
namespace Gist\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Gist\Model\Gist;
use Symfony\Component\HttpFoundation\JsonResponse;
use Gist\Form\ApiCreateGistForm;
/**
* Class ApiController
* @author Simon Vieille <simon@deblan.fr>
*/
class ApiController extends Controller
{
public function createAction(Request $request, Application $app)
{
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)');
}
protected function invalidMethodResponse($message = null)
{
$data = [
'error' => 'Method Not Allowed',
'message' => $message,
];
return new JsonResponse($data, 405);
}
protected function invalidRequestResponse($message = null)
{
$data = [
'error' => 'Bad request',
'message' => $message,
];
return new JsonResponse($data, 400);
}
}

View File

@ -15,11 +15,11 @@ abstract class AbstractForm
protected $translator;
public function __construct(FormFactory $formFactory, Translator $translator, array $data = array())
public function __construct(FormFactory $formFactory, Translator $translator, array $data = array(), $formFactoryOptions = array())
{
$this->translator = $translator;
$this->builder = $formFactory->createBuilder('form', $data);
$this->builder = $formFactory->createBuilder('form', $data, $formFactoryOptions);
}
public function getForm()

View File

@ -0,0 +1,19 @@
<?php
namespace Gist\Form;
/**
* Class CreateGistForm
* @author Simon Vieille <simon@deblan.fr>
*/
class ApiCreateGistForm extends CreateGistForm
{
public function build(array $options = array())
{
parent::build($options);
$this->builder->remove('cipher');
return $this->builder;
}
}