Mercurial > pub > Impl
annotate Lib/IMPL/Web/Application/ControllerUnit.pm @ 144:b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
minor speed improvements to the object CTOR caching
Added support for a secure processing (and 'laundering' ) a CGI parameters
Many minor fixes
author | wizard |
---|---|
date | Tue, 13 Jul 2010 02:05:38 +0400 |
parents | 4c9849f0f879 |
children | 60fd224f3e3c |
rev | line source |
---|---|
133 | 1 use strict; |
110 | 2 package IMPL::Web::Application::ControllerUnit; |
3 use base qw(IMPL::Object); | |
4 | |
5 use IMPL::Class::Property; | |
112 | 6 use IMPL::DOM::Transform::PostToDOM; |
7 use IMPL::DOM::Schema; | |
113 | 8 use Class::Inspector; |
9 use File::Spec; | |
133 | 10 use Sub::Name; |
112 | 11 |
12 use constant { | |
13 CONTROLLER_METHODS => 'controller_methods', | |
14 STATE_CORRECT => 'correct', | |
15 STATE_NEW => 'new', | |
16 STATE_INVALID => 'invalid' | |
17 }; | |
110 | 18 |
19 BEGIN { | |
20 public property action => prop_get | owner_set; | |
21 public property application => prop_get | owner_set; | |
22 public property query => prop_get | owner_set; | |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
142
diff
changeset
|
23 public property response => prop_get | owner_set; |
111 | 24 public property formData => prop_get | owner_set; |
25 public property formSchema => prop_get | owner_set; | |
26 public property formErrors => prop_get | owner_set; | |
110 | 27 } |
28 | |
133 | 29 my %publicProps = map {$_->Name , 1} __PACKAGE__->get_meta(typeof IMPL::Class::PropertyInfo); |
30 | |
113 | 31 __PACKAGE__->class_data(CONTROLLER_METHODS,{}); |
32 | |
110 | 33 sub CTOR { |
112 | 34 my ($this,$action,$args) = @_; |
110 | 35 |
36 $this->action($action); | |
37 $this->application($action->application); | |
38 $this->query($action->query); | |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
142
diff
changeset
|
39 $this->response($action->response); |
112 | 40 |
41 $this->$_($args->{$_}) foreach qw(formData formSchema formErrors); | |
42 } | |
43 | |
134 | 44 sub unitNamespace() { |
45 "" | |
46 } | |
47 | |
48 sub transactions { | |
49 my ($self,%methods) = @_; | |
50 | |
51 while (my ($method,$info) = each %methods) { | |
52 if ($info and ref $info ne 'HASH') { | |
53 warn "Bad transaction $method description"; | |
54 $info = {}; | |
55 } | |
56 | |
57 $info->{wrapper} = 'TransactionWrapper'; | |
58 $self->class_data(CONTROLLER_METHODS)->{$method} = $info; | |
59 } | |
60 } | |
61 | |
112 | 62 sub forms { |
63 my ($self,%forms) = @_; | |
64 | |
65 while ( my ($method,$info) = each %forms ) { | |
66 die new IMPL::Exception("A method doesn't exists in the controller",$self,$method) unless $self->can($method); | |
67 if ( not ref $info ) { | |
68 $self->class_data(CONTROLLER_METHODS)->{$method} = { | |
69 wrapper => 'FormWrapper', | |
70 schema => $info | |
71 }; | |
72 } elsif (ref $info eq 'HASH') { | |
73 die new IMPL::Exception("A schema must be specified",$self,$method) unless $info->{schema}; | |
74 | |
75 $self->class_data(CONTROLLER_METHODS)->{$method} = { | |
76 wrapper => 'FormWrapper', | |
142 | 77 schema => $info->{schema}, |
78 form => $info->{form} | |
112 | 79 }; |
80 } else { | |
81 die new IMPL::Exception("Unsupported method information",$self,$method); | |
82 } | |
83 } | |
84 } | |
85 | |
110 | 86 sub InvokeAction { |
87 my ($self,$method,$action) = @_; | |
88 | |
112 | 89 if (my $methodInfo = $self->class_data(CONTROLLER_METHODS)->{$method}) { |
90 if (my $wrapper = $methodInfo->{wrapper}) { | |
91 return $self->$wrapper($method,$action,$methodInfo); | |
92 } else { | |
93 return $self->TransactionWrapper($method,$action,$methodInfo); | |
94 } | |
110 | 95 } else { |
96 die new IMPL::InvalidOperationException("Invalid method call",$self,$method); | |
97 } | |
111 | 98 } |
99 | |
133 | 100 sub MakeParams { |
101 my ($this,$methodInfo) = @_; | |
102 | |
103 my $params; | |
104 if ($params = $methodInfo->{parameters} and ref $params eq 'ARRAY') { | |
105 return map $this->ResolveParam($_), @$params; | |
106 } | |
107 return(); | |
108 } | |
109 | |
110 sub ResolveParam { | |
111 my ($this,$param) = @_; | |
112 | |
113 if ( $param =~ /^::(\w+)$/ and $publicProps{$1}) { | |
114 return $this->$1(); | |
115 } else { | |
144
b56ebc31bf18
Empty nodes no more created while transforming a post request to the DOM document
wizard
parents:
142
diff
changeset
|
116 return scalar($this->query->param($param)); |
133 | 117 } |
118 } | |
119 | |
112 | 120 sub TransactionWrapper { |
121 my ($self,$method,$action,$methodInfo) = @_; | |
122 | |
123 my $unit = $self->new($action); | |
133 | 124 return $unit->$method($unit->MakeParams($methodInfo)); |
112 | 125 } |
126 | |
127 sub FormWrapper { | |
113 | 128 my ($self,$method,$action,$methodInfo) = @_; |
129 | |
130 my $schema = $self->loadSchema($methodInfo->{schema}); | |
131 | |
132 my $process = $action->query->param('process') || 0; | |
133 my $form = $methodInfo->{form} | |
134 || $action->query->param('form') | |
135 || $schema->selectSingleNode('ComplexNode')->name | |
136 or die new IMPL::Exception('No situable form name could be determined',$self,$method); | |
112 | 137 |
113 | 138 my %result; |
112 | 139 |
113 | 140 my $transform = IMPL::DOM::Transform::PostToDOM->new( |
141 undef, | |
142 $schema, | |
143 $form | |
144 ); | |
145 | |
138 | 146 $result{formName} = $form; |
113 | 147 $result{formSchema} = $schema; |
126 | 148 $result{formData} = $transform->Transform($action->query); |
149 | |
112 | 150 |
113 | 151 if ($process) { |
152 $result{formErrors} = $transform->Errors->as_list; | |
153 if ($transform->Errors->Count) { | |
154 $result{state} = STATE_INVALID; | |
155 } else { | |
156 $result{state} = STATE_CORRECT; | |
157 my $unit = $self->new($action,\%result); | |
127
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
158 |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
159 eval { |
133 | 160 $result{result} = $unit->$method($unit->MakeParams($methodInfo)); |
127
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
161 }; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
162 if (my $err = $@) { |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
163 $result{state} = STATE_INVALID; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
164 if (eval { $err->isa(typeof IMPL::WrongDataException) } ) { |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
165 $result{formErrors} = $err->Args; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
166 } else { |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
167 die $err; |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
168 } |
0dce0470a3d8
In the IMPL::Web::ControllerUnit added the ability to notify a form about a wrong data from a transaction
wizard
parents:
126
diff
changeset
|
169 } |
113 | 170 } |
171 } else { | |
172 $result{state} = STATE_NEW; | |
173 } | |
112 | 174 |
113 | 175 return \%result; |
176 } | |
177 | |
178 sub loadSchema { | |
179 my ($self,$name) = @_; | |
180 | |
126 | 181 if (-f $name) { |
182 return IMPL::DOM::Schema->LoadSchema($name); | |
183 } else { | |
184 my ($vol,$dir,$file) = File::Spec->splitpath( Class::Inspector->resolved_filename(ref $self || $self) ); | |
185 | |
186 return IMPL::DOM::Schema->LoadSchema(File::Spec->catfile($vol,$dir,$name)); | |
187 } | |
112 | 188 } |
189 | |
134 | 190 sub discover { |
191 my ($this) = @_; | |
192 | |
193 my $methods = $this->class_data(CONTROLLER_METHODS); | |
194 | |
195 my $namespace = $this->unitNamespace; | |
196 (my $module = typeof $this) =~ s/^$namespace//; | |
133 | 197 |
134 | 198 my %smd = ( |
199 module => [grep $_, split /::/, $module ], | |
200 ); | |
133 | 201 |
134 | 202 while (my ($method,$info) = each %$methods) { |
203 my %methodInfo = ( | |
204 name => $method | |
205 ); | |
206 $methodInfo{parameters} = $info->{parameters} if $info->{parameters}; | |
207 push @{$smd{methods}},\%methodInfo; | |
208 } | |
209 return \%smd; | |
133 | 210 } |
211 | |
134 | 212 __PACKAGE__->transactions( |
213 discover => undef | |
214 ); | |
133 | 215 |
111 | 216 1; |
217 | |
218 __END__ | |
219 | |
220 =pod | |
221 | |
222 =head1 NAME | |
223 | |
224 C<IMPL::Web::Application::ControllerUnit> - базовый класс для обработчика транзакций в модели контроллера. | |
225 | |
226 =head1 DESCRIPTION | |
227 | |
113 | 228 Классы, наследуемые от данного класса называется пакетом транзакций. Часть методов в таком классе |
229 объявляются как транзакции при помощи методов C<transaction>, C<form>. | |
111 | 230 |
231 Перед выполнением транзакции создается экземпляр объекта, в рамках которого будет выполнена транзакция. | |
232 Для этого вызывается метод C<InvokeAction($method,$action)>, который создает/восстанавливает контекст | |
233 транзакции. | |
234 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
235 Транзакции на данный момент делятся на простые и формы. Различные типы транзакций выполняются при помощи |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
236 различных оберток (C<TransactionWrapper> и C<FormWrapper>). Каждая обертка отвечает за конструирование |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
237 экземпляра объекта и вызов метода для выполнения транзакции, а также за возврат результата выполнения. |
111 | 238 |
239 =head2 Простые транзакции | |
240 | |
241 Простые транзакции получаю только запрос, без предварительной обработки, и возвращенный результат напрямую | |
242 передается пользователю. | |
243 | |
244 =head2 Формы | |
245 | |
246 При использовании форм запрос предварительно обрабатывается, для получения DOM документа с данными формы. | |
247 Для постороенния DOM документа используется схема. При этом становятся доступны дополнительные свойства | |
248 C<formData>, C<formSchema>, C<formErrors>. | |
249 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
250 Результат выполнения транзакции не возвращается наверх напрямую, а включается в структуру, которая |
111 | 251 выглядит следующим образом |
252 | |
253 =begin code | |
254 | |
255 { | |
256 state => '{ new | correct | invalid }', | |
257 result => $transactionResult, | |
258 formData => $formDOM, | |
259 formSchema => $formSchema, | |
260 formErrors => @errors | |
261 } | |
262 | |
263 =end code | |
264 | |
265 =over | |
266 | |
267 =item C<state> | |
268 | |
269 Состояние верификации формы. | |
270 | |
271 =over | |
272 | |
273 =item C<new> | |
274 | |
275 Первоначальное содержимое формы, оно может быть некорректным, но это нормально. | |
276 В данном состоянии транзакция обычно не выполняется. | |
277 | |
278 =item C<correct> | |
279 | |
280 Данные формы корректны, транзакция выполнена, и ее результат доступен через поле C<result> | |
281 | |
282 =item C<invalid> | |
283 | |
284 Содержимое формы не прошло верификацию, ошибки доступны через поле C<formErrors>. Транзакция | |
285 не выполнялась. | |
286 | |
287 =back | |
288 | |
289 =item C<result> | |
290 | |
291 Результат выполнения транзакции, если конечно таковая выполнялась. | |
292 | |
293 =item C<formData> | |
294 | |
295 ДОМ документ с данными формами. Документ существует всегда, не зависимо от его корректности, | |
296 может быть использован для построения формы, уже заполненную параметрами. | |
297 | |
298 =item C<formSchema> | |
299 | |
300 Схема данных формы, может использоваться для построения динамических форм. | |
301 | |
302 =item C<formErrors> | |
303 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
304 Ссылка на массив с ошибками при проверки формы. |
111 | 305 |
306 =back | |
307 | |
308 =head1 MEMBERS | |
309 | |
310 =over | |
311 | |
312 =item C<[get] application> | |
313 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
314 Объект приложения, которое обрабатывает запрос. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
315 |
111 | 316 =item C<[get] query> |
317 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
318 Текущий запрос. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
319 |
111 | 320 =item C<[get] response> |
321 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
322 Текущий ответ. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
323 |
111 | 324 =item C<[get] formData> |
325 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
326 C<IMPL::DOM::Document> документ с данныим, если данный запрос является формой. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
327 |
111 | 328 =item C<[get] formSchema> |
329 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
330 C<IMPL::DOM::Schema> документ со схемой формы данного запроса. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
331 |
111 | 332 =item C<[get] formErrors> |
333 | |
128
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
334 Ошибки верификации данных, если таковые были. Обычно при наличии ошибок в форме, транзакция |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
335 не выполняется, а эти ошибки передаются в ответ. |
08753833173d
Fixed a error handling issue in JSON output: errors are correctly transfered
wizard
parents:
127
diff
changeset
|
336 |
111 | 337 =item C<InvokeAction($method,$action)> |
338 | |
339 Конструирует контекст выполнения транзакции, может быть переопределен для конструирования контекста по | |
112 | 340 своим правилам. |
341 | |
342 =item C<TransactionWrapper($method,$action,$methodInfo)> | |
343 | |
344 Обертка для конструирования простых транзакций, может быть переопределен для конструирования контекста по | |
345 своим правилам. | |
346 | |
347 =item C<FormWrapper($method,$action,$methodInfo)> | |
348 | |
349 Обертка для конструирования форм, может быть переопределен для конструирования контекста по | |
350 своим правилам. | |
111 | 351 |
134 | 352 =item C<discover()> |
353 | |
354 Метод, опубликованный для вызова контроллером, возвращает описание методов в формате C<Simple Module Definition>. | |
355 | |
356 =begin code | |
357 | |
358 # SMD structure | |
359 { | |
360 module => ['Foo','Bar'], | |
361 methods => [ | |
362 { | |
363 name => 'search', | |
364 parameters => ['text','limit'] #optional | |
365 } | |
366 ] | |
367 } | |
368 | |
369 =end code | |
370 | |
111 | 371 =back |
372 | |
373 =head1 EXAMPLE | |
374 | |
375 =begin code | |
376 | |
377 package MyBooksUnit; | |
378 use strict; | |
379 use base qw(IMPL::Web::Application::ControllerUnit); | |
380 | |
381 __PACKAGE__->PassThroughArgs; | |
382 | |
134 | 383 sub unitDataClass { 'My::Books' } |
384 | |
385 __PACKAGE__->transactions( | |
386 find => { | |
387 parameters => [qw(author)] | |
388 }, | |
389 info => { | |
390 parameters => [qw(id)] | |
391 } | |
392 ); | |
111 | 393 __PACKAGE__->forms( |
394 create => 'books.create.xml' | |
395 ); | |
396 | |
397 sub find { | |
134 | 398 my ($this,$author) = @_; |
111 | 399 |
134 | 400 return $this->ds->find({author => $author}); |
111 | 401 } |
402 | |
403 sub info { | |
134 | 404 my ($this,$id) = @_; |
111 | 405 |
134 | 406 return $this->ds->find({id => $id}); |
111 | 407 } |
408 | |
409 sub create { | |
410 my ($this) = @_; | |
411 | |
412 my %book = map { | |
134 | 413 $_->nodeName, $_->nodeValue |
414 } $this->formData->selectNodes([qw(author_id title year ISBN)]); | |
111 | 415 |
134 | 416 return $this->ds->create(\%book); |
111 | 417 } |
418 | |
419 =end code | |
420 | |
421 =cut |