비즈니스 모델, 라이브러리 및 애플리케이션 하위 수준 코드에서 입력 유효성 검사(필터링 아님!)를 위한 어설션 및 보호 메서드가 포함된 간단한 PHP 라이브러리입니다. 라이브러리를 사용하여 입력 데이터에 대한 사전/사후 조건을 구현할 수 있습니다.
아이디어는 모델에서 어설션을 구현하기 위한 코드의 양을 줄이고 어설션을 구현하기 위한 코드 경로도 단순화하는 것입니다. 어설션이 실패하면 예외가 발생하여 코드에서 if 절의 필요성이 제거됩니다.
라이브러리는 다음과 같은 이유로 Symfony 또는 Zend Validator를 사용하지 않습니다. 검사는 필요한 모든 곳에서 사용할 수 있도록 낮은 수준의 빠른 비객체 지향 코드여야 합니다. 두 라이브러리 중 하나를 사용하려면 로케일 구성 요소, 번역, 이름을 사용하여 여러 개체의 인스턴스화가 필요합니다. 너무 부풀어 오른다.
작곡가 사용:
composer require beberlei/assert
<?php
use Assert Assertion ;
function duplicateFile ( $ file , $ times )
{
Assertion :: file ( $ file );
Assertion :: digit ( $ times );
for ( $ i = 0 ; $ i < $ times ; $ i ++) {
copy ( $ file , $ file . $ i );
}
}
Azure Blob Storage의 실시간 사용량:
<?php
public function putBlob ( $ containerName = '' , $ blobName = '' , $ localFileName = '' , $ metadata = array (), $ leaseId = null , $ additionalHeaders = array ())
{
Assertion :: notEmpty ( $ containerName , ' Container name is not specified ' );
self :: assertValidContainerName ( $ containerName );
Assertion :: notEmpty ( $ blobName , ' Blob name is not specified. ' );
Assertion :: notEmpty ( $ localFileName , ' Local file name is not specified. ' );
Assertion :: file ( $ localFileName , ' Local file name is not specified. ' );
self :: assertValidRootContainerBlobName ( $ containerName , $ blobName );
// Check file size
if ( filesize ( $ localFileName ) >= self :: MAX_BLOB_SIZE ) {
return $ this -> putLargeBlob ( $ containerName , $ blobName , $ localFileName , $ metadata , $ leaseId , $ additionalHeaders );
}
// Put the data to Windows Azure Storage
return $ this -> putBlobData ( $ containerName , $ blobName , file_get_contents ( $ localFileName ), $ metadata , $ leaseId , $ additionalHeaders );
}
값이 null인지 또는 어설션을 유지하는지 확인하기 위해 도우미 메서드( Assertion::nullOr*
)가 제공됩니다.
<?php
Assertion :: nullOrMax ( null , 42 ); // success
Assertion :: nullOrMax ( 1 , 42 ); // success
Assertion :: nullOrMax ( 1337 , 42 ); // exception
Assertion::all*
메소드는 제공된 모든 값이 어설션에 대해 유효한지 확인합니다. 다음 값 중 하나에 대해 주장이 유효하지 않다는 예외가 발생합니다.
<?php
Assertion :: allIsInstanceOf ( array ( new stdClass, new stdClass), ' stdClass ' ); // success
Assertion :: allIsInstanceOf ( array ( new stdClass, new stdClass), ' PDO ' ); // exception
여러 어설션에 대해 값을 확인할 때 값에 정적 API를 사용하는 것은 매우 장황합니다. Assert 2.6.7부터 Assert
클래스는 Assert::that($value)
로 시작하여 유창한 인터페이스에서 호출하려는 주장을 수신하는 훨씬 더 멋진 유창한 주장 API를 제공합니다. $value
한 번만 지정하면 됩니다.
<?php
Assert :: that ( $ value )-> notEmpty ()-> integer ();
Assert :: that ( $ value )-> nullOr ()-> string ()-> startsWith ( " Foo " );
Assert :: that ( $ values )-> all ()-> float ();
또한 "nullOr" 또는 "all" 도우미를 각각 활성화하는 두 가지 바로 가기 함수 Assert::thatNullOr()
및 Assert::thatAll()
도 있습니다.
웹 개발에는 특히 양식과 관련된 경우 첫 번째 오류에서 직접 중단하는 대신 여러 오류를 수집하려는 경우가 많습니다. 이것이 게으른 주장의 목적입니다. 해당 API는 유창한 Assert::that()
API와 동일하게 작동하지만 예외를 직접 발생시키는 대신 모든 오류를 수집하고 AssertSoftAssertion
개체에서 verifyNow()
메서드가 호출될 때만 예외를 트리거합니다.
<?php
Assert :: lazy ()
-> that ( 10 , ' foo ' )-> string ()
-> that ( null , ' bar ' )-> notEmpty ()
-> that ( ' string ' , ' baz ' )-> isArray ()
-> verifyNow ();
that($value, $propertyPath)
메서드에는 나중에 오류를 구별하는 방법을 알 수 있도록 속성 경로(이름)가 필요합니다.
실패 시 verifyNow()
다음 메시지와 함께 Assert\LazyAssertionException
예외를 발생시킵니다.
The following 3 assertions failed:
1) foo: Value "10" expected to be string, type integer given.
2) bar: Value "<NULL>" is empty, but non empty value was expected.
3) baz: Value "string" is not an array.
getErrorExceptions()
호출하여 모든 AssertionFailedException
을 검색할 수도 있습니다. 이는 예를 들어 사용자에 대한 실패 응답을 작성하는 데 유용할 수 있습니다.
게으른 어설션 체인을 사용할 때 단일 값에 대한 여러 오류를 캡처하려는 경우 tryAll
을 사용하여 that
호출에 따라 해당 값에 대해 모든 어설션을 실행하고 결과적으로 실패한 어설션 오류 메시지를 모두 캡처할 수 있습니다. 예는 다음과 같습니다.
Assert :: lazy ()
-> that ( 10 , ' foo ' )-> tryAll ()-> integer ()-> between ( 5 , 15 )
-> that ( null , ' foo ' )-> tryAll ()-> notEmpty ()-> string ()
-> verifyNow ();
위는 이 기능을 사용하여 실패 보고 동작을 미세 조정하는 방법을 보여 주지만, 모든 실패를 더 쉽게 포착하려면 아래와 같이 어설션을 하기 전에 tryAll
호출할 수도 있습니다. 이는 메소드 호출을 줄이는 데 도움이 되며 위와 동일한 동작을 갖습니다.
Assert :: lazy ()-> tryAll ()
-> that ( 10 , ' foo ' )-> integer ()-> between ( 5 , 15 )
-> that ( null , ' foo ' )-> notEmpty ()-> string ()
-> verifyNow ();
다음 함수는 Assert
정적 생성자의 별칭으로 존재합니다.
Assertthat()
AssertthatAll()
AssertthatNullOr()
Assertlazy()
함수형 또는 정적 생성자를 사용하는 것은 전적으로 개인 취향입니다.
참고: 함수 생성자는 Assertion
확장과 함께 작동하지 않습니다. 그러나 확장 클래스를 가리키는 방식으로 이러한 함수를 다시 만드는 것은 쉽지 않습니다.
<?php
use Assert Assertion ;
Assertion :: alnum (mixed $ value );
Assertion :: base64 (string $ value );
Assertion :: between (mixed $ value , mixed $ lowerLimit , mixed $ upperLimit );
Assertion :: betweenExclusive (mixed $ value , mixed $ lowerLimit , mixed $ upperLimit );
Assertion :: betweenLength (mixed $ value , int $ minLength , int $ maxLength );
Assertion :: boolean (mixed $ value );
Assertion :: choice (mixed $ value , array $ choices );
Assertion :: choicesNotEmpty (array $ values , array $ choices );
Assertion :: classExists (mixed $ value );
Assertion :: contains (mixed $ string , string $ needle );
Assertion ::count(array| Countable | ResourceBundle | SimpleXMLElement $ countable , int $ count );
Assertion :: date (string $ value , string $ format );
Assertion :: defined (mixed $ constant );
Assertion :: digit (mixed $ value );
Assertion :: directory (string $ value );
Assertion :: e164 (string $ value );
Assertion :: email (mixed $ value );
Assertion :: endsWith (mixed $ string , string $ needle );
Assertion :: eq (mixed $ value , mixed $ value2 );
Assertion :: eqArraySubset (mixed $ value , mixed $ value2 );
Assertion :: extensionLoaded (mixed $ value );
Assertion :: extensionVersion (string $ extension , string $ operator , mixed $ version );
Assertion :: false (mixed $ value );
Assertion :: file (string $ value );
Assertion :: float (mixed $ value );
Assertion :: greaterOrEqualThan (mixed $ value , mixed $ limit );
Assertion :: greaterThan (mixed $ value , mixed $ limit );
Assertion :: implementsInterface (mixed $ class , string $ interfaceName );
Assertion :: inArray (mixed $ value , array $ choices );
Assertion :: integer (mixed $ value );
Assertion :: integerish (mixed $ value );
Assertion :: interfaceExists (mixed $ value );
Assertion :: ip (string $ value , int $ flag = null );
Assertion :: ipv4 (string $ value , int $ flag = null );
Assertion :: ipv6 (string $ value , int $ flag = null );
Assertion :: isArray (mixed $ value );
Assertion :: isArrayAccessible (mixed $ value );
Assertion :: isCallable (mixed $ value );
Assertion ::isCountable(array| Countable | ResourceBundle | SimpleXMLElement $ value );
Assertion :: isInstanceOf (mixed $ value , string $ className );
Assertion :: isJsonString (mixed $ value );
Assertion :: isObject (mixed $ value );
Assertion :: isResource (mixed $ value );
Assertion :: isTraversable (mixed $ value );
Assertion :: keyExists (mixed $ value , string|int $ key );
Assertion :: keyIsset (mixed $ value , string|int $ key );
Assertion :: keyNotExists (mixed $ value , string|int $ key );
Assertion :: length (mixed $ value , int $ length );
Assertion :: lessOrEqualThan (mixed $ value , mixed $ limit );
Assertion :: lessThan (mixed $ value , mixed $ limit );
Assertion :: max (mixed $ value , mixed $ maxValue );
Assertion ::maxCount(array| Countable | ResourceBundle | SimpleXMLElement $ countable , int $ count );
Assertion :: maxLength (mixed $ value , int $ maxLength );
Assertion :: methodExists (string $ value , mixed $ object );
Assertion :: min (mixed $ value , mixed $ minValue );
Assertion ::minCount(array| Countable | ResourceBundle | SimpleXMLElement $ countable , int $ count );
Assertion :: minLength (mixed $ value , int $ minLength );
Assertion :: noContent (mixed $ value );
Assertion :: notBlank (mixed $ value );
Assertion :: notContains (mixed $ string , string $ needle );
Assertion :: notEmpty (mixed $ value );
Assertion :: notEmptyKey (mixed $ value , string|int $ key );
Assertion :: notEq (mixed $ value1 , mixed $ value2 );
Assertion :: notInArray (mixed $ value , array $ choices );
Assertion :: notIsInstanceOf (mixed $ value , string $ className );
Assertion :: notNull (mixed $ value );
Assertion :: notRegex (mixed $ value , string $ pattern );
Assertion :: notSame (mixed $ value1 , mixed $ value2 );
Assertion :: null (mixed $ value );
Assertion :: numeric (mixed $ value );
Assertion :: objectOrClass (mixed $ value );
Assertion :: phpVersion (string $ operator , mixed $ version );
Assertion :: propertiesExist (mixed $ value , array $ properties );
Assertion :: propertyExists (mixed $ value , string $ property );
Assertion :: range (mixed $ value , mixed $ minValue , mixed $ maxValue );
Assertion :: readable (string $ value );
Assertion :: regex (mixed $ value , string $ pattern );
Assertion :: same (mixed $ value , mixed $ value2 );
Assertion :: satisfy (mixed $ value , callable $ callback );
Assertion :: scalar (mixed $ value );
Assertion :: startsWith (mixed $ string , string $ needle );
Assertion :: string (mixed $ value );
Assertion :: subclassOf (mixed $ value , string $ className );
Assertion :: true (mixed $ value );
Assertion :: uniqueValues (array $ values );
Assertion :: url (mixed $ value );
Assertion :: uuid (string $ value );
Assertion :: version (string $ version1 , string $ operator , string $ version2 );
Assertion :: writeable (string $ value );
기억하세요: 구성 매개변수가 필요한 경우 항상 값 뒤에 전달됩니다. 값은 항상 첫 번째 매개변수입니다.
어설션 중 하나라도 실패하면 AssertAssertionFailedException
이 발생합니다. $message
라는 인수를 어설션에 전달하여 예외 메시지를 제어할 수 있습니다. 모든 예외에는 기본적으로 기본 메시지와 고유 메시지 코드가 포함됩니다.
<?php
use Assert Assertion ;
use Assert AssertionFailedException ;
try {
Assertion :: integer ( $ value , " The pressure of gas is measured in integers. " );
} catch ( AssertionFailedException $ e ) {
// error handling
$ e -> getValue (); // the value that caused the failure
$ e -> getConstraints (); // the additional constraints of the assertion.
}
AssertAssertionFailedException
은 단지 인터페이스이고 기본 구현은 SPL InvalidArgumentException
을 확장하는 AssertInvalidArgumentException
입니다. 패키지 기반 수준에서 사용되는 예외를 변경할 수 있습니다.
메시지 매개변수로 콜백을 전달할 수 있으므로 테스트를 실행할 때마다가 아니라 어설션이 실패한 경우에만 자신만의 메시지를 구성할 수 있습니다.
콜백에는 어설션을 위한 매개변수 배열이 제공됩니다.
일부 어설션은 다른 어설션을 호출하므로 콜백은 어떤 어설션이 실패했는지 확인하기 위해 배열을 예시로 들어야 합니다.
배열에는 어떤 어설션이 실패했는지 나타내는 ::assertion
이라는 키가 포함됩니다.
콜백은 예외 메시지로 사용될 문자열을 반환해야 합니다.
Assert 내에서 발생할 수 있는 버그, 잘못된 해석 또는 BC 중단으로부터 라이브러리를 보호하려면 발생한 예외도 재정의할 수 있는 라이브러리/프로젝트 기반 어설션 하위 클래스를 도입해야 합니다.
또한 AssertAssertion::stringify()
메서드를 재정의하여 오류 처리 중에 유형에 대한 고유한 해석을 제공할 수 있습니다.
<?php
namespace MyProject ;
use Assert Assertion as BaseAssertion ;
class Assertion extends BaseAssertion
{
protected static $ exceptionClass = ' MyProjectAssertionFailedException ' ;
}
V2.9.2부터 Lazy Assertions는 이제 자체 어설션 클래스에 있는 추가 어설션에 액세스할 수 있습니다.
자세한 내용은 CONTRIBUTING을 참조하세요.