Merge branch 'release/v1.0.0'

This commit is contained in:
Simon Vieille 2018-01-16 11:43:58 +01:00
commit d64f5ad1cd
23 changed files with 2756 additions and 0 deletions

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
/propel.yaml
/etc/propel/
/etc/security/users.json
/**/**/Om/
/**/**/Map/
/vendor
/var/*
!/var/.gitkeep

37
Makefile Normal file
View file

@ -0,0 +1,37 @@
COMPOSER ?= composer
GIT ?= git
MKDIR ?= mkdir
PHP ?= php
all: composer
composer:
@echo "Installing application's dependencies"
@echo "-------------------------------------"
@echo
$(COMPOSER) install $(COMPOSER_INSTALL_FLAGS)
optimize:
@echo "Optimizing Composer's autoloader, can take some time"
@echo "----------------------------------------------------"
@echo
$(COMPOSER) dump-autoload --optimize
run:
@echo "Run development server"
@echo "----------------------"
@echo
$(PHP) -S 0.0.0.0:8080 -t web
propel:
@echo "Propel migration"
@echo "----------------"
@echo
./vendor/propel/propel/bin/propel config:convert
./vendor/propel/propel/bin/propel model:build --recursive
./vendor/propel/propel/bin/propel migration:diff --recursive
./vendor/propel/propel/bin/propel migration:migrate --recursive

66
README.md Normal file
View file

@ -0,0 +1,66 @@
Automate Android API
====================
## Installation
```
$ git clone https://gitnet.fr/deblan/android-automate-api.git
$ cd android-automate-api
$ make
$ cp propel-dist.yaml propel.yaml # Edit propel.yaml
$ cp etc/security/users.json-dist etc/security/users.json # Edit users.json
$ make propel
```
## API
### HTTP Response status
* `200`: Resource found
* `201`: Resource created
* `204`: Resource removed
* `404`: Resource not found
* `500`: Internal error
When a resource is created or deleted, the response will be like:
```
{
"status": true|false,
"code": 200|201|204|404|500,
"message": "A message"
}
```
#### Create a SMS
`POST /api/sms/create` with MIME media type `application/json`
*Body*
```
{"sender": "+33611223344", "message": "Hello, World!", "time": "1516031177"}
```
#### Delete a SMS
`DELETE /api/sms/delete/{id}`
#### Get all SMS
`GET /api/sms/list`
The response contains an collection of SMS:
```
[
{
"id": 1234,
"sender": "+33611223344",
"message": "Hello, World!",
"received_at": 1516031177,
"notified_at": 1516031179
},
...
]
```

17
bin/generate-password Executable file
View file

@ -0,0 +1,17 @@
#!/usr/bin/env php
<?php
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;
require_once __DIR__.'/../vendor/autoload.php';
if (isset($argv[1])) {
$password = $argv[1];
} else {
$password = trim(readline('Password: '));
}
$encoder = new BCryptPasswordEncoder(13);
$hash = $encoder->encodePassword($password, '');
echo "$hash\n";

1
bin/propel Symbolic link
View file

@ -0,0 +1 @@
../vendor/propel/propel/bin/propel

12
composer.json Normal file
View file

@ -0,0 +1,12 @@
{
"require": {
"silex/silex": "2.*",
"symfony/security": "^3.4",
"propel/propel": "~2.0@dev"
},
"autoload": {
"psr-4": {
"App\\": "src/App"
}
}
}

View file

@ -0,0 +1,3 @@
{
"foo": ["ROLE_USER", "Use ./bin/generate-password to fill this value"]
}

32
propel-dist.yaml Normal file
View file

@ -0,0 +1,32 @@
propel:
database:
connections:
default:
adapter: mysql
classname: Propel\Runtime\Connection\ConnectionWrapper
dsn: "mysql:host=localhost;dbname=androidapi"
user: root
password: root
settings:
charset: utf8
queries:
utf8: "SET NAMES utf8 COLLATE utf8_unicode_ci, COLLATION_CONNECTION = utf8_unicode_ci, COLLATION_DATABASE = utf8_unicode_ci, COLLATION_SERVER = utf8_unicode_ci"
paths:
projectDir: src/
schemaDir: src/
outputDir: src/
phpDir: src/
phpConfDir: etc/propel
sqlDir: var/propel/sql
migrationDir: var/propel/migration
runtime:
defaultConnection: default
connections: [default]
generator:
defaultConnection: default
connections: [default]
objectModel:
addClassLevelComment: false

88
src/App/Application.php Normal file
View file

@ -0,0 +1,88 @@
<?php
namespace App;
use Silex\Application as SilexApplication;
use Silex\Provider\SecurityServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use App\Validator\SmsValidator;
use App\Factory\SmsFactory;
use Propel\Runtime\Propel;
use App\Controller\Controller;
/**
* class Application.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class Application extends SilexApplication
{
/**
* @var string
*/
protected $rootDir;
/*
* Init the application.
*/
public function init()
{
Propel::init($this->getRootDir().'etc/propel/config.php');
$users = json_decode(file_get_contents($this->getRootDir().'/etc/security/users.json'), true);
$this->register(new SecurityServiceProvider(), [
'security.firewalls' => [
'api' => [
'pattern' => '^/api',
'http' => true,
'users' => $users,
],
],
]);
$this['sms.validator'] = new SmsValidator();
$this['sms.factory'] = new SmsFactory();
$this->error(function (\Exception $e, Request $request, $code) {
return $this->json([
'status' => false,
'code' => $code,
'message' => $e->getMessage(),
]);
});
return $this;
}
/*
* Set the value of "rootDir".
*
* @param string $rootDir
*
* @return
*/
public function setRootDir($rootDir)
{
$this->rootDir = $rootDir;
return $this;
}
/*
* Get the value of "rootDir".
*
* @return string
*/
public function getRootDir()
{
return $this->rootDir;
}
public function addController(Controller $controller)
{
$controller->setApp($this);
$controller->registerRoutes();
return $this;
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace App\Controller;
use App\Application;
/**
* class Controller.
*
* @author Simon Vieille <simon@deblan.fr>
*/
abstract class Controller
{
/**
* @var Application
*/
protected $app;
/*
* Set the value of "app".
*
* @param Application $app
*
* @return Controller
*/
public function setApp($app)
{
$this->app = $app;
return $this;
}
/*
* Get the value of "app".
*
* @return Application
*/
public function getApp()
{
return $this->app;
}
/**
* Registers routes.
*
* @param Application $app
*
* @return void
*/
abstract public function registerRoutes();
}

View file

@ -0,0 +1,125 @@
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* class SmsController.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class SmsController extends Controller
{
/**
* {@inheritdoc}
*/
public function registerRoutes()
{
$this->app
->post('/api/sms/create', [$this, 'create'])
->bind('api_sms_create');
$this->app
->delete('/api/sms/delete/{id}', [$this, 'delete'])
->bind('api_sms_delete')
->assert('id', '\d+')
->convert('id', function ($value) {
return (int) $value;
});
$this->app
->get('/api/sms/list', [$this, 'list'])
->bind('api_sms_list');
}
/**
* Create action.
*
* @param Request $request
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function create(Request $request)
{
$app = $this->app;
if (!$app['sms.validator']->validateRequest($request)) {
return $app->abort(422, 'Invalid request.');
}
$persisted = $app['sms.factory']->createByRequest($request);
if (!$persisted) {
return $app->abort(500, 'An error occured.');
} else {
return $app->json([
'status' => true,
'code' => 201,
'message' => 'Resource created.',
], 201);
}
}
/**
* Delete action.
*
* @param Request $request
* @param int $id
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function delete(Request $request, $id)
{
$app = $this->app;
$object = $app['sms.factory']->get($id);
if (!$object) {
return $app->json([
'status' => false,
'code' => 404,
'message' => 'Resource not found.',
], 404);
}
$app['sms.factory']->remove($object);
return $app->json([
'status' => true,
'code' => 204,
'message' => 'Resource removed.',
], 204);
}
/**
* List action.
*
* @param Request $request
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function list()
{
$app = $this->app;
$objects = $app['sms.factory']->getAll()->getData();
$data = [];
foreach ($objects as $object) {
$data[] = [
'id' => $object->getId(),
'sender' => $object->getSender(),
'message' => $object->getMessage(),
'received_at' => (int) $object->getTime(),
'notified_at' => $object->getCreatedAt()->getTimestamp(),
];
}
return $app->json($data);
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace App\Factory;
use Symfony\Component\HttpFoundation\Request;
/**
* interface Factory.
*
* @author Simon Vieille <simon@deblan.fr>
*/
interface Factory
{
/*
* Validates data.
*
* @param mixed $data
*
* @return bool
*/
public function createByRequest(Request $request);
}

View file

@ -0,0 +1,82 @@
<?php
namespace App\Factory;
use Symfony\Component\HttpFoundation\Request;
use App\Model\Sms;
use Propel\Runtime\Collection\ObjectCollection;
use App\Model\SmsQuery;
/**
* class SmsFactory.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class SmsFactory implements Factory
{
/**
* Creates a SMS.
*
* @param mixed $sender
* @param mixed $message
* @param mixed $time
*
* @return bool
*/
public function create($sender, $message, $time)
{
return (new Sms())
->setSender($sender)
->setMessage($message)
->setTime((int) $time)
->save() > 0;
}
/*
* Finds SMS.
*
* @return ObjectCollection
*/
public function getAll()
{
return SmsQuery::create()->find();
}
/*
* Get a SMS.
*
* @param int $id
*
* @return Sms|null
*/
public function get($id)
{
return SmsQuery::create()
->filterById($id)
->findOne();
}
/*
* Removes a SMS.
*
* @return bool
*/
public function remove(Sms $object)
{
return $object->delete();
}
/**
* Creates a SMS with a Request content.
*
* @param Request $request
*
* @return bool
*/
public function createByRequest(Request $request)
{
$content = json_decode($request->getContent(), true);
return $this->create($content['sender'], $content['message'], $content['time']);
}
}

1476
src/App/Model/Base/Sms.php Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,609 @@
<?php
namespace App\Model\Base;
use \Exception;
use \PDO;
use App\Model\Sms as ChildSms;
use App\Model\SmsQuery as ChildSmsQuery;
use App\Model\Map\SmsTableMap;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
/**
* Base class that represents a query for the 'sms' table.
*
*
*
* @method ChildSmsQuery orderById($order = Criteria::ASC) Order by the id column
* @method ChildSmsQuery orderBySender($order = Criteria::ASC) Order by the sender column
* @method ChildSmsQuery orderByMessage($order = Criteria::ASC) Order by the message column
* @method ChildSmsQuery orderByTime($order = Criteria::ASC) Order by the time column
* @method ChildSmsQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column
* @method ChildSmsQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column
*
* @method ChildSmsQuery groupById() Group by the id column
* @method ChildSmsQuery groupBySender() Group by the sender column
* @method ChildSmsQuery groupByMessage() Group by the message column
* @method ChildSmsQuery groupByTime() Group by the time column
* @method ChildSmsQuery groupByCreatedAt() Group by the created_at column
* @method ChildSmsQuery groupByUpdatedAt() Group by the updated_at column
*
* @method ChildSmsQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method ChildSmsQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
* @method ChildSmsQuery innerJoin($relation) Adds a INNER JOIN clause to the query
*
* @method ChildSmsQuery leftJoinWith($relation) Adds a LEFT JOIN clause and with to the query
* @method ChildSmsQuery rightJoinWith($relation) Adds a RIGHT JOIN clause and with to the query
* @method ChildSmsQuery innerJoinWith($relation) Adds a INNER JOIN clause and with to the query
*
* @method ChildSms findOne(ConnectionInterface $con = null) Return the first ChildSms matching the query
* @method ChildSms findOneOrCreate(ConnectionInterface $con = null) Return the first ChildSms matching the query, or a new ChildSms object populated from the query conditions when no match is found
*
* @method ChildSms findOneById(int $id) Return the first ChildSms filtered by the id column
* @method ChildSms findOneBySender(string $sender) Return the first ChildSms filtered by the sender column
* @method ChildSms findOneByMessage(resource $message) Return the first ChildSms filtered by the message column
* @method ChildSms findOneByTime(string $time) Return the first ChildSms filtered by the time column
* @method ChildSms findOneByCreatedAt(string $created_at) Return the first ChildSms filtered by the created_at column
* @method ChildSms findOneByUpdatedAt(string $updated_at) Return the first ChildSms filtered by the updated_at column *
* @method ChildSms requirePk($key, ConnectionInterface $con = null) Return the ChildSms by primary key and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
* @method ChildSms requireOne(ConnectionInterface $con = null) Return the first ChildSms matching the query and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
*
* @method ChildSms requireOneById(int $id) Return the first ChildSms filtered by the id column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
* @method ChildSms requireOneBySender(string $sender) Return the first ChildSms filtered by the sender column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
* @method ChildSms requireOneByMessage(resource $message) Return the first ChildSms filtered by the message column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
* @method ChildSms requireOneByTime(string $time) Return the first ChildSms filtered by the time column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
* @method ChildSms requireOneByCreatedAt(string $created_at) Return the first ChildSms filtered by the created_at column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
* @method ChildSms requireOneByUpdatedAt(string $updated_at) Return the first ChildSms filtered by the updated_at column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
*
* @method ChildSms[]|ObjectCollection find(ConnectionInterface $con = null) Return ChildSms objects based on current ModelCriteria
* @method ChildSms[]|ObjectCollection findById(int $id) Return ChildSms objects filtered by the id column
* @method ChildSms[]|ObjectCollection findBySender(string $sender) Return ChildSms objects filtered by the sender column
* @method ChildSms[]|ObjectCollection findByMessage(resource $message) Return ChildSms objects filtered by the message column
* @method ChildSms[]|ObjectCollection findByTime(string $time) Return ChildSms objects filtered by the time column
* @method ChildSms[]|ObjectCollection findByCreatedAt(string $created_at) Return ChildSms objects filtered by the created_at column
* @method ChildSms[]|ObjectCollection findByUpdatedAt(string $updated_at) Return ChildSms objects filtered by the updated_at column
* @method ChildSms[]|\Propel\Runtime\Util\PropelModelPager paginate($page = 1, $maxPerPage = 10, ConnectionInterface $con = null) Issue a SELECT query based on the current ModelCriteria and uses a page and a maximum number of results per page to compute an offset and a limit
*
*/
abstract class SmsQuery extends ModelCriteria
{
protected $entityNotFoundExceptionClass = '\\Propel\\Runtime\\Exception\\EntityNotFoundException';
/**
* Initializes internal state of \App\Model\Base\SmsQuery object.
*
* @param string $dbName The database name
* @param string $modelName The phpName of a model, e.g. 'Book'
* @param string $modelAlias The alias for the model in this query, e.g. 'b'
*/
public function __construct($dbName = 'default', $modelName = '\\App\\Model\\Sms', $modelAlias = null)
{
parent::__construct($dbName, $modelName, $modelAlias);
}
/**
* Returns a new ChildSmsQuery object.
*
* @param string $modelAlias The alias of a model in the query
* @param Criteria $criteria Optional Criteria to build the query from
*
* @return ChildSmsQuery
*/
public static function create($modelAlias = null, Criteria $criteria = null)
{
if ($criteria instanceof ChildSmsQuery) {
return $criteria;
}
$query = new ChildSmsQuery();
if (null !== $modelAlias) {
$query->setModelAlias($modelAlias);
}
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
}
/**
* Find object by primary key.
* Propel uses the instance pool to skip the database if the object exists.
* Go fast if the query is untouched.
*
* <code>
* $obj = $c->findPk(12, $con);
* </code>
*
* @param mixed $key Primary key to use for the query
* @param ConnectionInterface $con an optional connection object
*
* @return ChildSms|array|mixed the result, formatted by the current formatter
*/
public function findPk($key, ConnectionInterface $con = null)
{
if ($key === null) {
return null;
}
if ($con === null) {
$con = Propel::getServiceContainer()->getReadConnection(SmsTableMap::DATABASE_NAME);
}
$this->basePreSelect($con);
if (
$this->formatter || $this->modelAlias || $this->with || $this->select
|| $this->selectColumns || $this->asColumns || $this->selectModifiers
|| $this->map || $this->having || $this->joins
) {
return $this->findPkComplex($key, $con);
}
if ((null !== ($obj = SmsTableMap::getInstanceFromPool(null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key)))) {
// the object is already in the instance pool
return $obj;
}
return $this->findPkSimple($key, $con);
}
/**
* Find object by primary key using raw SQL to go fast.
* Bypass doSelect() and the object formatter by using generated code.
*
* @param mixed $key Primary key to use for the query
* @param ConnectionInterface $con A connection object
*
* @throws \Propel\Runtime\Exception\PropelException
*
* @return ChildSms A model object, or null if the key is not found
*/
protected function findPkSimple($key, ConnectionInterface $con)
{
$sql = 'SELECT id, sender, message, time, created_at, updated_at FROM sms WHERE id = :p0';
try {
$stmt = $con->prepare($sql);
$stmt->bindValue(':p0', $key, PDO::PARAM_INT);
$stmt->execute();
} catch (Exception $e) {
Propel::log($e->getMessage(), Propel::LOG_ERR);
throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e);
}
$obj = null;
if ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
/** @var ChildSms $obj */
$obj = new ChildSms();
$obj->hydrate($row);
SmsTableMap::addInstanceToPool($obj, null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key);
}
$stmt->closeCursor();
return $obj;
}
/**
* Find object by primary key.
*
* @param mixed $key Primary key to use for the query
* @param ConnectionInterface $con A connection object
*
* @return ChildSms|array|mixed the result, formatted by the current formatter
*/
protected function findPkComplex($key, ConnectionInterface $con)
{
// As the query uses a PK condition, no limit(1) is necessary.
$criteria = $this->isKeepQuery() ? clone $this : $this;
$dataFetcher = $criteria
->filterByPrimaryKey($key)
->doSelect($con);
return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher);
}
/**
* Find objects by primary key
* <code>
* $objs = $c->findPks(array(12, 56, 832), $con);
* </code>
* @param array $keys Primary keys to use for the query
* @param ConnectionInterface $con an optional connection object
*
* @return ObjectCollection|array|mixed the list of results, formatted by the current formatter
*/
public function findPks($keys, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getReadConnection($this->getDbName());
}
$this->basePreSelect($con);
$criteria = $this->isKeepQuery() ? clone $this : $this;
$dataFetcher = $criteria
->filterByPrimaryKeys($keys)
->doSelect($con);
return $criteria->getFormatter()->init($criteria)->format($dataFetcher);
}
/**
* Filter the query by primary key
*
* @param mixed $key Primary key to use for the query
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterByPrimaryKey($key)
{
return $this->addUsingAlias(SmsTableMap::COL_ID, $key, Criteria::EQUAL);
}
/**
* Filter the query by a list of primary keys
*
* @param array $keys The list of primary key to use for the query
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterByPrimaryKeys($keys)
{
return $this->addUsingAlias(SmsTableMap::COL_ID, $keys, Criteria::IN);
}
/**
* Filter the query on the id column
*
* Example usage:
* <code>
* $query->filterById(1234); // WHERE id = 1234
* $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
* $query->filterById(array('min' => 12)); // WHERE id > 12
* </code>
*
* @param mixed $id The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterById($id = null, $comparison = null)
{
if (is_array($id)) {
$useMinMax = false;
if (isset($id['min'])) {
$this->addUsingAlias(SmsTableMap::COL_ID, $id['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($id['max'])) {
$this->addUsingAlias(SmsTableMap::COL_ID, $id['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(SmsTableMap::COL_ID, $id, $comparison);
}
/**
* Filter the query on the sender column
*
* Example usage:
* <code>
* $query->filterBySender('fooValue'); // WHERE sender = 'fooValue'
* $query->filterBySender('%fooValue%', Criteria::LIKE); // WHERE sender LIKE '%fooValue%'
* </code>
*
* @param string $sender The value to use as filter.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterBySender($sender = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($sender)) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(SmsTableMap::COL_SENDER, $sender, $comparison);
}
/**
* Filter the query on the message column
*
* @param mixed $message The value to use as filter
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterByMessage($message = null, $comparison = null)
{
return $this->addUsingAlias(SmsTableMap::COL_MESSAGE, $message, $comparison);
}
/**
* Filter the query on the time column
*
* Example usage:
* <code>
* $query->filterByTime(1234); // WHERE time = 1234
* $query->filterByTime(array(12, 34)); // WHERE time IN (12, 34)
* $query->filterByTime(array('min' => 12)); // WHERE time > 12
* </code>
*
* @param mixed $time The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterByTime($time = null, $comparison = null)
{
if (is_array($time)) {
$useMinMax = false;
if (isset($time['min'])) {
$this->addUsingAlias(SmsTableMap::COL_TIME, $time['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($time['max'])) {
$this->addUsingAlias(SmsTableMap::COL_TIME, $time['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(SmsTableMap::COL_TIME, $time, $comparison);
}
/**
* Filter the query on the created_at column
*
* Example usage:
* <code>
* $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14'
* $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14'
* $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13'
* </code>
*
* @param mixed $createdAt The value to use as filter.
* Values can be integers (unix timestamps), DateTime objects, or strings.
* Empty strings are treated as NULL.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterByCreatedAt($createdAt = null, $comparison = null)
{
if (is_array($createdAt)) {
$useMinMax = false;
if (isset($createdAt['min'])) {
$this->addUsingAlias(SmsTableMap::COL_CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($createdAt['max'])) {
$this->addUsingAlias(SmsTableMap::COL_CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(SmsTableMap::COL_CREATED_AT, $createdAt, $comparison);
}
/**
* Filter the query on the updated_at column
*
* Example usage:
* <code>
* $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14'
* $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14'
* $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13'
* </code>
*
* @param mixed $updatedAt The value to use as filter.
* Values can be integers (unix timestamps), DateTime objects, or strings.
* Empty strings are treated as NULL.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function filterByUpdatedAt($updatedAt = null, $comparison = null)
{
if (is_array($updatedAt)) {
$useMinMax = false;
if (isset($updatedAt['min'])) {
$this->addUsingAlias(SmsTableMap::COL_UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($updatedAt['max'])) {
$this->addUsingAlias(SmsTableMap::COL_UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(SmsTableMap::COL_UPDATED_AT, $updatedAt, $comparison);
}
/**
* Exclude object from result
*
* @param ChildSms $sms Object to remove from the list of results
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function prune($sms = null)
{
if ($sms) {
$this->addUsingAlias(SmsTableMap::COL_ID, $sms->getId(), Criteria::NOT_EQUAL);
}
return $this;
}
/**
* Deletes all rows from the sms table.
*
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
*/
public function doDeleteAll(ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(SmsTableMap::DATABASE_NAME);
}
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
return $con->transaction(function () use ($con) {
$affectedRows = 0; // initialize var to track total num of affected rows
$affectedRows += parent::doDeleteAll($con);
// Because this db requires some delete cascade/set null emulation, we have to
// clear the cached instance *after* the emulation has happened (since
// instances get re-added by the select statement contained therein).
SmsTableMap::clearInstancePool();
SmsTableMap::clearRelatedInstancePool();
return $affectedRows;
});
}
/**
* Performs a DELETE on the database based on the current ModelCriteria
*
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public function delete(ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(SmsTableMap::DATABASE_NAME);
}
$criteria = $this;
// Set the correct dbName
$criteria->setDbName(SmsTableMap::DATABASE_NAME);
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
return $con->transaction(function () use ($con, $criteria) {
$affectedRows = 0; // initialize var to track total num of affected rows
SmsTableMap::removeInstanceFromPool($criteria);
$affectedRows += ModelCriteria::delete($con);
SmsTableMap::clearRelatedInstancePool();
return $affectedRows;
});
}
// timestampable behavior
/**
* Filter by the latest updated
*
* @param int $nbDays Maximum age of the latest update in days
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function recentlyUpdated($nbDays = 7)
{
return $this->addUsingAlias(SmsTableMap::COL_UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL);
}
/**
* Order by update date desc
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function lastUpdatedFirst()
{
return $this->addDescendingOrderByColumn(SmsTableMap::COL_UPDATED_AT);
}
/**
* Order by update date asc
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function firstUpdatedFirst()
{
return $this->addAscendingOrderByColumn(SmsTableMap::COL_UPDATED_AT);
}
/**
* Order by create date desc
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function lastCreatedFirst()
{
return $this->addDescendingOrderByColumn(SmsTableMap::COL_CREATED_AT);
}
/**
* Filter by the latest created
*
* @param int $nbDays Maximum age of in days
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function recentlyCreated($nbDays = 7)
{
return $this->addUsingAlias(SmsTableMap::COL_CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL);
}
/**
* Order by create date asc
*
* @return $this|ChildSmsQuery The current query, for fluid interface
*/
public function firstCreatedFirst()
{
return $this->addAscendingOrderByColumn(SmsTableMap::COL_CREATED_AT);
}
} // SmsQuery

20
src/App/Model/Sms.php Normal file
View file

@ -0,0 +1,20 @@
<?php
namespace App\Model;
use App\Model\Base\Sms as BaseSms;
class Sms extends BaseSms
{
/*
* Transforms and return the blob as string.
*
* @return string
*/
public function getMessage()
{
$blob = parent::getMessage();
return $blob !== null ? stream_get_contents($blob, -1, 0) : null;
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Model;
use App\Model\Base\SmsQuery as BaseSmsQuery;
class SmsQuery extends BaseSmsQuery
{
}

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<database defaultIdMethod="native" name="default" namespace="App\Model">
<table name="sms" isCrossRef="true">
<column name="id" type="INTEGER" primaryKey="true" required="true" autoIncrement="true"/>
<column name="sender" type="VARCHAR" size="50" required="true" />
<column name="message" type="BLOB" required="true" />
<column name="time" type="BIGINT" required="true" />
<behavior name="timestampable"/>
</table>
</database>

View file

@ -0,0 +1,25 @@
<?php
namespace App\Validator\Helper;
use Symfony\Component\HttpFoundation\Request;
/**
* trait RequestValidator.
*
* @author Simon Vieille <simon@deblan.fr>
*/
trait RequestValidator
{
/**
* Validates a Request
*
* @param Request $request
*
* @return bool
*/
public function validateRequest(Request $request)
{
return $this->validate(json_decode($request->getContent(), true));
}
}

View file

@ -0,0 +1,25 @@
<?php
namespace App\Validator;
/**
* class SmsValidator.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class SmsValidator implements Validator
{
use Helper\RequestValidator;
/**
* {@inheritdoc}
*/
public function validate($data)
{
if (!is_array($data)) {
return false;
}
return isset($data['sender'], $data['message'], $data['time']);
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace App\Validator;
/**
* interface Validator.
*
* @author Simon Vieille <simon@deblan.fr>
*/
interface Validator
{
/*
* Validates data.
*
* @param mixed $data
*
* @return bool
*/
public function validate($data);
}

0
var/.gitkeep Normal file
View file

15
web/index.php Normal file
View file

@ -0,0 +1,15 @@
<?php
use App\Application;
use Symfony\Component\HttpFoundation\Request;
use App\Controller\SmsController;
require_once __DIR__.'/../vendor/autoload.php';
$app = new Application();
$app
->setRootDir(__DIR__.'/../')
->init()
->addController(new SmsController())
->run();