First commit

This commit is contained in:
Michel Roux 2016-05-29 14:43:43 +02:00
commit 825d9c8e02
12 changed files with 3723 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.idea
*.iml
.DS_Store
*~
tmp/

5
.htaccess Normal file
View File

@ -0,0 +1,5 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L,QSA]

46
README.md Normal file
View File

@ -0,0 +1,46 @@
# Hardis
## Config for webservers
### Apache2
```
DocumentRoot "/var/www/html"
<Directory "/var/www/html">
Options -Indexes +FollowSymLinks +Includes
AllowOverride All
Order allow,deny
Allow from All
</Directory>
```
**Apache must have mod_rewrite enabled !**
### Nginx
```
server {
root /var/www/html;
location / {
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass ip_address:port;
include fastcgi_params;
}
}
```
### Notes
This project is based on [Fat Free Framework (F3)](http://fatfreeframework.com).
You have to have a /tmp folder with chmod 777.
This folder store cached files for the F3's template generator
## Urls
- / => Test page
- /api/member => List all members
- /api/member/identifiant or /api/member?identifiant= => List a member by id

View File

@ -0,0 +1,57 @@
<?php
/**
* Class MemberController
*
* Controller de l'action /member
*/
class MemberController {
/**
* @param Base $f3
* @param array $params
*
* Gestion de l'URL /api/member
*/
public function member(Base $f3, array $params) {
try {
$db = Csvdb::getInstance();
} catch (Exception $e) {
$f3->error($e->getCode(), $this->render(array(), $e->getMessage()));
return;
}
// Fusion du paramètre /member/identifiant avec /member?identifiant=
$params = array_merge($params, $f3->get('GET'));
if (!empty($params['identifiant'])) {
$adherant = $db->get($params['identifiant']);
if (!empty($adherant)) {
echo $this->render(array($adherant));
} else {
echo $this->render(array(), 'Aucun adhérent ne correspond à votre demande');
}
} else {
echo $this->render($db->getAll());
}
}
/**
* @param array $datas
* @param string $error
* @return string
*
* Fonction de rendu JSON pour le WS
*/
private function render(array $datas, $error = '') {
usort($datas, function ($a, $b) {
return strcmp($a['nom'], $b['nom']) + strcmp($a['prenom'], $b['prenom']);
});
return json_encode(array(
'count' => count($datas),
'datas' => $datas,
'error' => $error
));
}
}

View File

@ -0,0 +1,9 @@
<?php
class TestController {
public function index(Base $f3, array $params) {
echo Template::instance()->render('test.htm');
}
}

6
db.csv Normal file
View File

@ -0,0 +1,6 @@
identifiant;nom;prenom;telephone
1;Bland; Angie;0611111111
2;Doležalová ; Michaela;0622222222
3;Williams ; Sherri ;0633333333
4;Koutouxídou; Nikolétta ;0644444444
6;Vandesteene ; Els;0655555555
1 identifiant nom prenom telephone
2 1 Bland Angie 0611111111
3 2 Doležalová Michaela 0622222222
4 3 Williams Sherri 0633333333
5 4 Koutouxídou Nikolétta 0644444444
6 6 Vandesteene Els 0655555555

24
index.php Normal file
View File

@ -0,0 +1,24 @@
<?php
$f3 = require('lib/base.php');
// Définition des variable de base pour F3
$f3->set('AUTOLOAD', 'lib/;controllers/;models/');
$f3->set('DEBUG', 3);
$f3->set('UI', 'views/');
// Gestion des erreurs, l'api = retour JSON, autres = retour HTML
$f3->set('ONERROR', function (Base $f3) {
if (strpos($f3->get('PATH'), '/api')) {
echo $f3->get('ERROR.text');
} else {
echo Template::instance()->render('error.htm');
}
});
// Routes
$f3->route('GET /api/member/@identifiant', 'MemberController->member');
$f3->route('GET /api/member', 'MemberController->member');
$f3->route('GET /', 'TestController->index');
$f3->run();

3107
lib/base.php Executable file

File diff suppressed because it is too large Load Diff

350
lib/template.php Executable file
View File

@ -0,0 +1,350 @@
<?php
/*
Copyright (c) 2009-2015 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or later.
Fat-Free Framework is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! XML-style template engine
class Template extends Preview {
//@{ Error messages
const
E_Method='Call to undefined method %s()';
//@}
protected
//! Template tags
$tags,
//! Custom tag handlers
$custom=array();
/**
* Template -set- tag handler
* @return string
* @param $node array
**/
protected function _set(array $node) {
$out='';
foreach ($node['@attrib'] as $key=>$val)
$out.='$'.$key.'='.
(preg_match('/\{\{(.+?)\}\}/',$val)?
$this->token($val):
Base::instance()->stringify($val)).'; ';
return '<?php '.$out.'?>';
}
/**
* Template -include- tag handler
* @return string
* @param $node array
**/
protected function _include(array $node) {
$attrib=$node['@attrib'];
$hive=isset($attrib['with']) &&
($attrib['with']=$this->token($attrib['with'])) &&
preg_match_all('/(\w+)\h*=\h*(.+?)(?=,|$)/',
$attrib['with'],$pairs,PREG_SET_ORDER)?
'array('.implode(',',
array_map(function($pair) {
return '\''.$pair[1].'\'=>'.
(preg_match('/^\'.*\'$/',$pair[2]) ||
preg_match('/\$/',$pair[2])?
$pair[2]:
\Base::instance()->stringify($pair[2]));
},$pairs)).')+get_defined_vars()':
'get_defined_vars()';
$ttl=isset($attrib['ttl'])?(int)$attrib['ttl']:0;
return
'<?php '.(isset($attrib['if'])?
('if ('.$this->token($attrib['if']).') '):'').
('echo $this->render('.
(preg_match('/^\{\{(.+?)\}\}$/',$attrib['href'])?
$this->token($attrib['href']):
Base::instance()->stringify($attrib['href'])).','.
'$this->mime,'.$hive.','.$ttl.'); ?>');
}
/**
* Template -exclude- tag handler
* @return string
**/
protected function _exclude() {
return '';
}
/**
* Template -ignore- tag handler
* @return string
* @param $node array
**/
protected function _ignore(array $node) {
return $node[0];
}
/**
* Template -loop- tag handler
* @return string
* @param $node array
**/
protected function _loop(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
return
'<?php for ('.
$this->token($attrib['from']).';'.
$this->token($attrib['to']).';'.
$this->token($attrib['step']).'): ?>'.
$this->build($node).
'<?php endfor; ?>';
}
/**
* Template -repeat- tag handler
* @return string
* @param $node array
**/
protected function _repeat(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
return
'<?php '.
(isset($attrib['counter'])?
(($ctr=$this->token($attrib['counter'])).'=0; '):'').
'foreach (('.
$this->token($attrib['group']).'?:array()) as '.
(isset($attrib['key'])?
($this->token($attrib['key']).'=>'):'').
$this->token($attrib['value']).'):'.
(isset($ctr)?(' '.$ctr.'++;'):'').' ?>'.
$this->build($node).
'<?php endforeach; ?>';
}
/**
* Template -check- tag handler
* @return string
* @param $node array
**/
protected function _check(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
// Grab <true> and <false> blocks
foreach ($node as $pos=>$block)
if (isset($block['true']))
$true=array($pos,$block);
elseif (isset($block['false']))
$false=array($pos,$block);
if (isset($true,$false) && $true[0]>$false[0])
// Reverse <true> and <false> blocks
list($node[$true[0]],$node[$false[0]])=array($false[1],$true[1]);
return
'<?php if ('.$this->token($attrib['if']).'): ?>'.
$this->build($node).
'<?php endif; ?>';
}
/**
* Template -true- tag handler
* @return string
* @param $node array
**/
protected function _true(array $node) {
return $this->build($node);
}
/**
* Template -false- tag handler
* @return string
* @param $node array
**/
protected function _false(array $node) {
return '<?php else: ?>'.$this->build($node);
}
/**
* Template -switch- tag handler
* @return string
* @param $node array
**/
protected function _switch(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
foreach ($node as $pos=>$block)
if (is_string($block) && !preg_replace('/\s+/','',$block))
unset($node[$pos]);
return
'<?php switch ('.$this->token($attrib['expr']).'): ?>'.
$this->build($node).
'<?php endswitch; ?>';
}
/**
* Template -case- tag handler
* @return string
* @param $node array
**/
protected function _case(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
return
'<?php case '.(preg_match('/\{\{(.+?)\}\}/',$attrib['value'])?
$this->token($attrib['value']):
Base::instance()->stringify($attrib['value'])).': ?>'.
$this->build($node).
'<?php '.(isset($attrib['break'])?
'if ('.$this->token($attrib['break']).') ':'').
'break; ?>';
}
/**
* Template -default- tag handler
* @return string
* @param $node array
**/
protected function _default(array $node) {
return
'<?php default: ?>'.
$this->build($node).
'<?php break; ?>';
}
/**
* Assemble markup
* @return string
* @param $node array|string
**/
protected function build($node) {
if (is_string($node))
return parent::build($node);
$out='';
foreach ($node as $key=>$val)
$out.=is_int($key)?$this->build($val):$this->{'_'.$key}($val);
return $out;
}
/**
* Extend template with custom tag
* @return NULL
* @param $tag string
* @param $func callback
**/
function extend($tag,$func) {
$this->tags.='|'.$tag;
$this->custom['_'.$tag]=$func;
}
/**
* Call custom tag handler
* @return string|FALSE
* @param $func callback
* @param $args array
**/
function __call($func,array $args) {
if ($func[0]=='_')
return call_user_func_array($this->custom[$func],$args);
if (method_exists($this,$func))
return call_user_func_array(array($this,$func),$args);
user_error(sprintf(self::E_Method,$func),E_USER_ERROR);
}
/**
* Parse string for template directives and tokens
* @return string|array
* @param $text string
**/
function parse($text) {
// Build tree structure
for ($ptr=0,$w=5,$len=strlen($text),$tree=array(),$tmp='';$ptr<$len;)
if (preg_match('/^(.{0,'.$w.'}?)<(\/?)(?:F3:)?'.
'('.$this->tags.')\b((?:\h+[\w-]+'.
'(?:\h*=\h*(?:"(?:.*?)"|\'(?:.*?)\'))?|'.
'\h*\{\{.+?\}\})*)\h*(\/?)>/is',
substr($text,$ptr),$match)) {
if (strlen($tmp)||$match[1])
$tree[]=$tmp.$match[1];
// Element node
if ($match[2]) {
// Find matching start tag
$stack=array();
for($i=count($tree)-1;$i>=0;$i--) {
$item = $tree[$i];
if (is_array($item) && array_key_exists($match[3],$item)
&& !isset($item[$match[3]][0])) {
// Start tag found
$tree[$i][$match[3]]+=array_reverse($stack);
$tree=array_slice($tree,0,$i+1);
break;
} else $stack[]=$item;
}
}
else {
// Start tag
$node=&$tree[][$match[3]];
$node=array();
if ($match[4]) {
// Process attributes
preg_match_all(
'/(?:\b([\w-]+)\h*'.
'(?:=\h*(?:"(.*?)"|\'(.*?)\'))?|'.
'(\{\{.+?\}\}))/s',
$match[4],$attr,PREG_SET_ORDER);
foreach ($attr as $kv)
if (isset($kv[4]))
$node['@attrib'][]=$kv[4];
else
$node['@attrib'][$kv[1]]=
(isset($kv[2]) && $kv[2]!==''?
$kv[2]:
(isset($kv[3]) && $kv[3]!==''?
$kv[3]:NULL));
}
}
$tmp='';
$ptr+=strlen($match[0]);
$w=5;
}
else {
// Text node
$tmp.=substr($text,$ptr,$w);
$ptr+=$w;
if ($w<50)
$w++;
}
if (strlen($tmp))
// Append trailing text
$tree[]=$tmp;
// Break references
unset($node);
return $tree;
}
/**
* Class constructor
* return object
**/
function __construct() {
$ref=new ReflectionClass(__CLASS__);
$this->tags='';
foreach ($ref->getmethods() as $method)
if (preg_match('/^_(?=[[:alpha:]])/',$method->name))
$this->tags.=(strlen($this->tags)?'|':'').
substr($method->name,1);
}
}

88
models/Csvdb.php Normal file
View File

@ -0,0 +1,88 @@
<?php
/**
* Class Csvdb
*
* Singleton
* Stock en son objet l'intégralité du fichier CSV (performance)
*/
class Csvdb {
private $_db = array();
private static $_instance;
private $_filename = 'db.csv';
/**
* Csvdb constructor.
*
* Le contructeur se charge de contruire la base de donnée interne au singleton ($_bd)
*/
protected function __construct()
{
if (file_exists($this->_filename)) {
$i = 0;
$headers = array();
$filedata = file($this->_filename);
for ($i = 0; $i < count($filedata); $i++) {
// Première ligne, index 0 = headers
if (!$i) {
foreach (str_getcsv($filedata[$i], ';') as $headerdata) {
$headers[] = trim($headerdata);
}
} else {
$linedata = str_getcsv($filedata[$i], ';');
$nline = $i - 1;
$this->_db[$nline] = array();
for ($j = 0; $j < count($linedata); $j++) {
$this->_db[$nline][$headers[$j]] = trim($linedata[$j]);
}
}
}
if (empty($this->_db)) {
throw new Exception('Aucun adhérent nest présent', 200);
}
} else {
throw new Exception('Le fichier dentrée est introuvable', 404);
}
}
/**
* @return Csvdb
*
* Retourne l'instance du Singleton
*/
public static function getInstance() {
if (is_null(self::$_instance)) {
self::$_instance = new Csvdb();
}
return self::$_instance;
}
/**
* @param $id
* @return array|null
*
* Retourne un adhérent en fonction de son identifiant
*/
public function get($id) {
foreach ($this->_db as $item) {
if ($item['identifiant'] == $id) {
return $item;
}
}
return null;
}
/**
* @return array
*
* Retourne toute la base de données
*/
public function getAll() {
return $this->_db;
}
}

11
views/error.htm Normal file
View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>{{ @ERROR.text }} {{ @ERROR.status }}</title>
</head>
<body>
<h1>{{ @ERROR.status }}</h1>
<p>{{ @ERROR.text }}</p>
<pre>{{ @ERROR.trace }}</pre>
</body>
</html>

15
views/test.htm Normal file
View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Test du webservice</title>
</head>
<body>
<form action="{{@BASE}}/api/member" method="get">
<input type="text" value="" name="identifiant" placeholder="Identifiant">
<input type="submit">
</form>
</body>
</html>