resume/src/Sikofitt/Controller/ApiControllerProvider.php

234 lines
7.0 KiB
PHP

<?php
/*
* This file is part of Resume.PHP.
*
* (copyleft) R. Eric Wheeler <sikofitt@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* This file is part of test.
*
* @file ApiControllerProvider.php
*
* R. Eric Wheeler <reric@ee.stanford.edu>
*
* 7/8/16 / 10:11 AM
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sikofitt\Controller;
use ReCaptcha\ReCaptcha;
use Silex\Api\ControllerProviderInterface;
use Silex\Application;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\EqualTo;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* Class ApiControllerProvider
*
* @package Sikofitt\Controller
*/
class ApiControllerProvider implements ControllerProviderInterface {
/**
* {@inheritdoc}
*
* @param Application $app
*
* @return mixed
*/
public function connect(Application $app) {
$controllers = $app['controllers_factory'];
$controllers->get('/v1/schema', function () use ($app) {
$response = new Response(file_get_contents($app->getDataDirectory() . '/schema/schema.v1.json'), Response::HTTP_OK);
$response->headers->set('Content-Type', 'application/schema+json');
return $response;
});
$controllers->match('/v1/message', function (Request $request) use ($app) {
static $code = 255;
$returnData = [
'status' => 'error',
'message' => 'Unknown error.',
'code' => $code,
];
$csrf = $request->getSession()->get('_csrf/contact') ?: false;
// Set some validation constraints
$constraints = [
'contact' => new Collection([
'name' => [
new Length([
'min' => 4,
'minMessage' => 'Name must be at least 4 characters.',
]
),
new NotBlank([
'message' => 'Name must not be blank.',
]
),
],
'email' => [
new Email([
'message' => 'Invalid email',
]),
new NotBlank([
'message' => 'Email must not be blank.',
]),
],
'message' => [
new Length([
'min' => 20,
'minMessage' => 'Message must be at least 20 characters.',
]),
new NotBlank([
'message' => 'Message must not be blank',
]),
],
'_token' => [
new EqualTo(['value' => $csrf, 'message' => 'Invalid token.']),
],
]
),
];
$contactFormData = $request->request->all();
$valid = $app['validator']->validate($contactFormData, new Collection($constraints));
if (count($valid) > 0) {
$sanitizeProperty = function () use ($valid) {
return str_replace(['][', '[', ']'], [
'_',
'',
'',
], $valid[0]->getPropertyPath());
};
return new JsonResponse([
'status' => 'error',
'message' => $valid[0]->getMessage(),
'id' => $sanitizeProperty(),
'const' => $valid[0]->getCode(),
'code' => 256,
], 256);
}
else {
$contactFormName = $contactFormData['contact']['name'];
$contactFormEmail = $contactFormData['contact']['email'];
$contactFormMessage = $contactFormData['contact']['message'];
$failures = '';
$sent = $app['mailer']->send(\Swift_Message::newInstance()
->setSubject('[Resume] Message')
->setFrom([$contactFormEmail => $contactFormName])
->setTo($app->config('app.email'))
->setBody($contactFormMessage)
, $failures);
if($sent > 0) {
$request->getSession()->remove('_csrf/contact');
return new JsonResponse([
'status' => 'success',
'message' => 'Message successfully sent.',
'code' => 201,
'data' => $contactFormData,
'failed' => $failures,
'sent' => $sent,
], 200);
} else {
return new JsonResponse([
'status' => 'error',
'message' => 'There was an error sending the message.',
'code' => 255,
'data' => $contactFormData,
'failed' => $failures,
'sent' => $sent,
], 255);
}
}
})->method('GET|POST')->bind('api_message');
$controllers->get('/v1/emailTest', function (Request $request) use ($app) {
try {
$app->mail(\Swift_Message::newInstance()
->setSubject('[Resume] Message')
->setFrom(['eric@rewiv.com' => 'Eric'])
->setTo('eric@ericwheeler.net')
->setBody('Testing message.')
);
} catch (\Exception $e) {
dump($e->getMessage());
}
return new Response('Hello');
});
$controllers->post('/v1/captcha', function (Request $request) use ($app) {
$captcha = new ReCaptcha('6LcvmSQTAAAAAITkvYJjgLar1LqGGLz-ic0ZMiXo');
$valid = $captcha->verify(
$request->request->get('g-recaptcha-response'),
$request->server->get('REMOTE_ADDR')
);
if ($valid->isSuccess()) {
$return = [
'valid' => true,
'message' => [
'email' => null !== $app->config('app.email') ? $app->config('app.email') : 'No email has been set in the configuration. Please let the owner know.',
'phone' => null !== $app->config('app.phone') ? $app->config('app.phone') : 'No phone has been set in the configuration. Please let the owner know.',
],
];
}
else {
$errorCodes = [
'missing-input-secret' => 'The secret parameter is missing.',
'invalid-input-secret' => 'The secret parameter is invalid or malformed.',
'missing-input-response' => 'The response parameter is missing.',
'invalid-input-response' => 'The response parameter is invalid or malformed.',
];
foreach ($valid->getErrorCodes() as $code) {
if (array_key_exists($code, $errorCodes)) {
$errors[] = $errorCodes[$code];
}
}
if (!isset($errors)) {
$errors[] = 'An unknown error occurred.';
}
$return = [
'valid' => false,
'message' => $errors,
];
}
return new JsonResponse(json_encode($return));
})->bind('api_captcha');
return $controllers;
}
}