ビジネスモデル、ライブラリ、およびアプリケーションの低レベルコードでの入力検証 (フィルタリングではありません!) のためのアサーションとガードメソッドが含まれるシンプルな PHP ライブラリです。このライブラリを使用して、入力データに事前/事後条件を実装できます。
アイデアは、モデルにアサーションを実装するためのコードの量を削減し、アサーションを実装するためのコード パスを簡素化することです。アサーションが失敗すると例外がスローされ、コード内に if 節が必要なくなります。
ライブラリが Symfony または Zend Validators を使用していないのには、次の理由があります。チェックは、必要な場所で使用できるように、低レベルで高速な非オブジェクト指向のコードでなければなりません。 2 つのライブラリのいずれかを使用するには、ロケール コンポーネントや翻訳などを使用して、いくつかのオブジェクトをインスタンス化する必要があります。膨らみすぎです。
コンポーザの使用:
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 );
}
ヘルパー メソッド ( Assertion::nullOr*
) は、値が null であるか、またはアサーションに当てはまるかどうかをチェックするために提供されています。
<?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
指定する必要があるのは 1 回だけです。
<?php
Assert :: that ( $ value )-> notEmpty ()-> integer ();
Assert :: that ( $ value )-> nullOr ()-> string ()-> startsWith ( " Foo " );
Assert :: that ( $ values )-> all ()-> float ();
また、それぞれ「nullOr」または「all」ヘルパーを有効にする 2 つのショートカット関数Assert::thatNullOr()
とAssert::thatAll()
もあります。
Web 開発では、特にフォームが関係する場合、最初のエラーで直接中止するのではなく、いくつかのエラーを収集したいケースが数多くあります。これが遅延アサーションの目的です。これらの API は、流暢なAssert::that()
API とまったく同じように機能しますが、例外を直接スローする代わりに、すべてのエラーを収集し、メソッドverifyNow()
がAssertSoftAssertion
オブジェクトで呼び出された場合にのみ例外をトリガーします。
<?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
を取得することもできます。これは、たとえばユーザーに対する失敗への応答を作成する場合に役立ちます。
遅延アサーション チェーンを使用するときに単一の値で複数のエラーをキャプチャしたい場合は、 that
呼び出しの後にtryAll
を使用して、値に対してすべてのアサーションを実行し、その結果として発生する失敗したアサーション エラー メッセージをすべてキャプチャできます。以下に例を示します。
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 Assertion は独自のアサーション クラスに存在する追加のアサーションにアクセスできるようになりました。
詳細については、「貢献」を参照してください。