Skip to content

Commit 4cf339c

Browse files
committed
Before handler to facilitate #151
1 parent 7ff9ff9 commit 4cf339c

File tree

7 files changed

+48
-13
lines changed

7 files changed

+48
-13
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ $api = new PHP_CRUD_API(array(
9191
'tenancy_function'=>function($cmd,$db,$tab,$col) { return null; },
9292
'input_sanitizer'=>function($cmd,$db,$tab,$col,$typ,$val) { return $val; },
9393
'input_validator'=>function($cmd,$db,$tab,$col,$typ,$val,$ctx) { return true; },
94+
'before'=>function($cmd,$db,$tab,$id,$in) { /* adjust array $in */ },
9495
'after'=>function($cmd,$db,$tab,$id,$in,$out) { /* do something */ },
9596
// configurable options
9697
'allow_origin'=>'*',
@@ -756,6 +757,11 @@ PUT http://localhost/api.php/categories/2
756757
{"name":"Internet","icon":null}
757758
```
758759

760+
## Automatic fields
761+
762+
Before any operation the 'before' function is called that allows you to do set some automatic fields.
763+
Note that the 'inputs' parameter is writable and is an array. The array may contain NULL values on invalid JSON.
764+
759765
## Custom actions
760766

761767
After any operation the 'after' function is called that allows you to do some custom actions.

api.php

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1134,14 +1134,25 @@ protected function parseGetParameterArray($get,$name,$characters) {
11341134
return $values;
11351135
}
11361136

1137+
protected function applyBeforeHandler($parameters,&$inputs) {
1138+
$callback = $parameters['before'];
1139+
if (is_callable($callback,true)) {
1140+
$action = $parameters['action'];
1141+
$database = $parameters['database'];
1142+
$table = $parameters['tables'][0];
1143+
$id = $parameters['key'][0];
1144+
$callback($action,$database,$table,$id,$inputs);
1145+
}
1146+
}
1147+
11371148
protected function applyAfterHandler($parameters,$output) {
11381149
$callback = $parameters['after'];
11391150
if (is_callable($callback,true)) {
11401151
$action = $parameters['action'];
11411152
$database = $parameters['database'];
11421153
$table = $parameters['tables'][0];
11431154
$id = $parameters['key'][0];
1144-
$input = isset($parameters['inputs'])?$parameters['inputs']:false;
1155+
$input = $parameters['inputs'];
11451156
$callback($action,$database,$table,$id,$input,$output);
11461157
}
11471158
}
@@ -1868,11 +1879,14 @@ protected function getParameters($settings) {
18681879
if ($column_authorizer) $this->applyColumnAuthorizer($column_authorizer,$action,$database,$fields);
18691880

18701881
$multi = strpos($key[0],',')!==false;
1882+
$inputs = array();
18711883
if (strlen($post)) {
18721884
// input
18731885
$multi = $post[0]=='[';
18741886
$contexts = $this->retrieveInputs($post);
1875-
$inputs = array();
1887+
if ($before) {
1888+
$this->applyBeforeHandler(compact('action','database','tables','key','before'),$contexts);
1889+
}
18761890
foreach ($contexts as $context) {
18771891
$input = $this->filterInputByFields($context,$fields[$tables[0]]);
18781892

@@ -1885,7 +1899,7 @@ protected function getParameters($settings) {
18851899
}
18861900
}
18871901

1888-
return compact('action','database','tables','key','page','filters','fields','orderings','transform','multi','inputs','collect','select','after');
1902+
return compact('action','database','tables','key','page','filters','fields','orderings','transform','multi','inputs','collect','select','before','after');
18891903
}
18901904

18911905
protected function addWhereFromFilters($filters,&$sql,&$params) {
@@ -2121,6 +2135,7 @@ public function __construct($config) {
21212135
$input_validator = isset($input_validator)?$input_validator:null;
21222136
$auto_include = isset($auto_include)?$auto_include:null;
21232137
$allow_origin = isset($allow_origin)?$allow_origin:null;
2138+
$before = isset($before)?$before:null;
21242139
$after = isset($after)?$after:null;
21252140

21262141
$db = isset($db)?$db:null;
@@ -2173,7 +2188,7 @@ public function __construct($config) {
21732188
}
21742189

21752190
$this->db = $db;
2176-
$this->settings = compact('method', 'request', 'get', 'post', 'origin', 'database', 'table_authorizer', 'record_filter', 'column_authorizer', 'tenancy_function', 'input_sanitizer', 'input_validator', 'after', 'auto_include', 'allow_origin');
2191+
$this->settings = compact('method', 'request', 'get', 'post', 'origin', 'database', 'table_authorizer', 'record_filter', 'column_authorizer', 'tenancy_function', 'input_sanitizer', 'input_validator', 'before', 'after', 'auto_include', 'allow_origin');
21772192
}
21782193

21792194
public static function php_crud_api_transform(&$tables) {

tests/blog_mysql.sql

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,11 @@ CREATE TABLE `products` (
125125
`name` varchar(255) NOT NULL,
126126
`price` decimal(10,2) NOT NULL,
127127
`properties` JSON NOT NULL,
128+
`created_at` datetime(3) NOT NULL,
128129
PRIMARY KEY (`id`)
129130
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
130131

131-
INSERT INTO `products` (`id`, `name`, `price`, `properties`) VALUES
132-
(1, 'Calculator', '23.01', '{"depth":false,"model":"TRX-120","width":100,"height":null}');
132+
INSERT INTO `products` (`id`, `name`, `price`, `properties`, `created_at`) VALUES
133+
(1, 'Calculator', '23.01', '{"depth":false,"model":"TRX-120","width":100,"height":null}', '1970-01-01 01:01:01.001');
133134

134135
-- 2016-11-05 13:11:47

tests/blog_postgresql.sql

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,8 @@ CREATE TABLE products (
130130
id serial NOT NULL,
131131
name character varying(255) NOT NULL,
132132
price decimal(10,2) NOT NULL,
133-
properties jsonb NOT NULL
133+
properties jsonb NOT NULL,
134+
created_at timestamp NOT NULL
134135
);
135136

136137
--
@@ -204,8 +205,8 @@ INSERT INTO "events" ("name", "datetime", "visitors") VALUES
204205
-- Data for Name: events; Type: TABLE DATA; Schema: public; Owner: postgres
205206
--
206207

207-
INSERT INTO "products" ("name", "price", "properties") VALUES
208-
('Calculator', '23.01', '{"depth":false,"model":"TRX-120","width":100,"height":null}');
208+
INSERT INTO "products" ("name", "price", "properties", "created_at") VALUES
209+
('Calculator', '23.01', '{"depth":false,"model":"TRX-120","width":100,"height":null}', '1970-01-01 01:01:01.001');
209210

210211
--
211212
-- Name: categories_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:

tests/blog_sqlite.sql

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,10 @@ CREATE TABLE `products` (
106106
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,
107107
`name` text(255) NOT NULL,
108108
`price` text(12) NOT NULL,
109-
`properties` json NOT NULL
109+
`properties` json NOT NULL,
110+
`created_at` datetime NOT NULL
110111
);
111112

112-
INSERT INTO `products` (`id`, `name`, `price`, `properties`) VALUES (1, 'Calculator', '23.01', '{"depth":false,"model":"TRX-120","width":100,"height":null}');
113+
INSERT INTO `products` (`id`, `name`, `price`, `properties`, `created_at`) VALUES (1, 'Calculator', '23.01', '{"depth":false,"model":"TRX-120","width":100,"height":null}', '1970-01-01 01:01:01.001');
113114

114115
--

tests/blog_sqlserver.sql

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ CREATE TABLE [products](
209209
[name] [nvarchar](max) NOT NULL,
210210
[price] [decimal](10,2) NOT NULL,
211211
[properties] [xml] NOT NULL,
212+
[created_at] [datetime2](3) NOT NULL,
212213
CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED
213214
(
214215
[id] ASC
@@ -288,7 +289,7 @@ SET IDENTITY_INSERT [events] OFF
288289
GO
289290
SET IDENTITY_INSERT [products] ON
290291
GO
291-
INSERT [products] ([id], [name], [price], [properties]) VALUES (1, N'Calculator', N'23.01', N'<root type="object"><depth type="boolean">false</depth><model type="string">TRX-120</model><width type="number">100</width><height type="null" /></root>')
292+
INSERT [products] ([id], [name], [price], [properties], [created_at]) VALUES (1, N'Calculator', N'23.01', N'<root type="object"><depth type="boolean">false</depth><model type="string">TRX-120</model><width type="number">100</width><height type="null" /></root>', '1970-01-01 01:01:01.001')
292293
GO
293294
SET IDENTITY_INSERT [products] OFF
294295
GO

tests/tests.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ private function action($method,$url,$data='')
3434
'tenancy_function'=>function($action,$database,$table,$column) { return ($table=='users'&&$column=='id')?1:null; },
3535
'input_sanitizer'=>function($action,$database,$table,$column,$type,$value) { return is_string($value)?strip_tags($value):$value; },
3636
'input_validator'=>function($action,$database,$table,$column,$type,$value,$context) { return ($column=='category_id' && !is_numeric($value))?'must be numeric':true; },
37-
'after' => function ($action,$database,$table,$id,$input,$output) { file_put_contents('log.txt',var_export(array($action,$database,$table,$id,$input,$output),true),FILE_APPEND); },
37+
'before' => function ($action,$database,$table,$id,$inputs) { if ($action=='create') foreach ($inputs as $input) if ($input) $input->created_at = date('Y-m-d H:i:s',1386752948); },
38+
'after' => function ($action,$database,$table,$id,$inputs,$output) { file_put_contents('log.txt',var_export(array($action,$database,$table,$id,$inputs,$output),true),FILE_APPEND); },
3839
// for tests
3940
'method' =>$method,
4041
'request' =>$url['path'],
@@ -780,4 +781,13 @@ public function testWriteProductProperties()
780781
$test->get('/products/1?columns=id,properties');
781782
$test->expect('{"id":1,"properties":{"depth":false,"model":"TRX-120","width":100,"height":123}}');
782783
}
784+
785+
public function testAddProducts()
786+
{
787+
$test = new API($this);
788+
$test->post('/products','{"name":"Laptop","price":"1299.99"}');
789+
$test->expect('2');
790+
$test->get('/products/2');
791+
$test->expect('{"id":2,"name":"Laptop","price":"1299.99","properties":null,"created_at":"2013-12-11 10:09:08.000"}');
792+
}
783793
}

0 commit comments

Comments
 (0)