未加星标

Stand-alone usage of Zend-InputFilter - Rob Allen

字体大小 | |
[开发(php) 所属分类 开发(php) | 发布者 店小二05 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Any data that you receive needs to be checked and validated. There are number of ways to do this includingphp's filter_var , but I prefer Zend-InputFilter . This is how to use it as a stand-alone component.

Installation

Firstly, we install it using Composer:

$ composer require zendframework/zend-inputfilter $ composer require zendframework/zend-servicemanager

You don't have to have ServiceManager, but it makes working with InputFilter much easier, so it's worth installing.

Create the InputFilter

The easiest way to create an InputFilter is to use the provided Factory class. Let's consider an Author entity that has the properties: author_id , name , biography & date_of_birth . We can create an input filter like this:

use Zend\InputFilter\Factory as InputFilterFactory; class Author { protected $author_id; protected $name; protected $biography; protected $date_of_birth; // ... protected function createInputFilter() { $factory = new InputFilterFactory(); $inputFilter = $factory->createInputFilter([ 'author_id' => [ 'required' => true, 'validators' => [ ['name' => 'Uuid'], ], ], 'name' => [ 'required' => true, 'filters' => [ ['name' => 'StringTrim'], ['name' => 'StripTags'], ], ], 'biography' => [ 'required' => false, 'filters' => [ ['name' => 'StringTrim'], ['name' => 'StripTags'], ], ], 'date_of_birth' => [ 'required' => false, 'validators' => [ ['name' => 'Date'], [ 'name' => 'LessThan', 'options' => [ 'max' => date('Y-m-d'), 'inclusive' => true, ], ], ], ], ]); return $inputFilter; } }

The createInputFilter() method takes an associative array where the key is the name of the input and then the value is a specification. There are a number of elements in the specification, but we usually just specify required , filters and validators .

required This can be either true or false . If false , then the validators do not execute, but the filters do. filters An optional array of Zend-Filters . A filter modifies the supplied data before it is passed to the validators (if any). The filtered data is used by the rest of the application. In this example, we have added two filters: StringTrim & StripTags . validators An optional array of Zend-Validators . A validator will test the filtered value for the input and fail if the data is not valid. If any validator fails, then the entire InputFilter is invalid.

This particular input filter requires that author_id and name are present, but that biography and date_of_birth are optional. The author_id must be a UUID, the name & biography must not have leading or trailing whitespace or no HTML tags and the date_of_birth , if present, must be a valid date in the past.

Using the InputFilter

To use the InputFilter, we set the data and then call isValid() . This can be done in a validate() method that looks like this:

Use Crell\ApiProblem\ApiProblem; use Error\Exception\ProblemException; Class Author { // ... /** * Create an author * * @param array $data * @return Author * @throws ProblemException */ public static function createAuthor($data) { $inputFilter = $this->createInputFilter(); $inputFilter->setData($data); if ($inputFilter->isValid()) { return new Author($inputFilter->getValues()); } $problem = new ApiProblem('Validation failed'); $problem->setStatus(400); $problem['errors'] = $inputFilter->getMessages(); throw new ProblemException($problem); } }

In this case, it's an API, so the data has come from a PUT or POST request. We call setData() to pass the array of data into the InputFilter and then call isValid() . If the data is valid, we can return a newly instantiated Author object that is constructed with the filter data. If the validation fails, then we throw a ProblemException which needs an ApiProblem instance, so we create one for it.

To find out which validators failed, getMessages() provides a nested array which is very useful for passing back to the API client.

As an example, this is what failure looks like:

$ curl -i -X "POST" "http://localhost:8888/authors" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -d $'{ "name": "", "author_id": "1234" }' HTTP/1.1 400 Bad Request Host: localhost:8888 Connection: close X-Powered-By: PHP/7.0.14 Content-type: application/problem+json { "errors": { "author_id": { "valueNotUuid": "Invalid UUID format" }, "name": { "isEmpty": "Value is required and can't be empty" } }, "title": "Validation failed", "type": "about:blank", "status": 400 } Fin

That's all there is to it. Zend-InputFilter is a very flexible data filter and validator and works really well for APIs, such as those written in Slim .

本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师

主题: PHPHTMLUT
分页:12
转载请注明
本文标题:Stand-alone usage of Zend-InputFilter - Rob Allen
本站链接:http://www.codesec.net/view/534945.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(php) | 评论(0) | 阅读(121)