Zec Data Parsing和模式聲明庫旨在為 PHP 應用程式帶來模式定義和驗證功能。
composer require mohamed-amine-sayagh/zec以下是如何使用 Zec 程式庫定義和驗證使用者設定檔架構的範例:
use function Zec Utils z ;
// Define the user profile schema
$ userProfileParser = z ()-> options ([
' name ' => z ()-> string ()-> min ( 3 )-> max ( 50 ), // Name must be a string between 3 and 50 characters
' age ' => z ()-> number ()-> min ( 18 ), // Age must be a number and at least 18
' email ' => z ()-> email (), // Email must be a valid email address
' address ' => z ()-> options ([
' street ' => z ()-> string (),
' city ' => z ()-> string ()
]),
' hobbies ' => z ()-> each ( z ()-> string ()), // Hobbies must be an array of strings
' metadata ' => z ()-> optional ()-> each ( z ()-> options ([ // Metadata is optional and must be an array of objects
' key ' => z ()-> string (), // Each object must have a key as a string
' value ' => z ()-> string () // Each object must have a value as a string
]))
]); // Parse and validate user data
$ userData = [
' name ' => ' Jane Doe ' ,
' age ' => 1 , // 1 is not a valid age
' email ' => ' jane.doe@examplecom ' , // missing dot
' address ' => [
' street ' => ' 123 Elm St ' ,
' city ' => 3 // city is not a string
],
' hobbies ' => [ ' photography ' , ' traveling ' , ' reading ' , 5 ], // 5 is not a string
' metadata ' => [
[ ' key ' => ' memberSince ' , ' value ' => ' 2019 ' ],
[ ' key ' => ' newsletter ' , ' value ' => ' true ' ]
]
];
try {
$ userProfileParser -> parseOrThrow ( $ userData ); // Throws an error
echo " User data is valid n" ;
} catch ( Zec ZecError $ e ) {
echo " User data is invalid: " ;
$ e -> log (); // Log the error
} User data is invalid: [
{
"parser": "min",
"value": 1,
"min": 18,
"message": "Invalid value",
"path": [
"age"
]
},
{
"parser": "email",
"value": "jane.doe@examplecom",
"message": "Invalid email address",
"path": [
"email"
]
},
{
"parser": "string",
"value": 5,
"message": "Invalid string value",
"path": [
"hobbies",
"3"
]
}
]
目前版本: v1.0.0,發布日期: 2024-10-01,作者: Mohamed Amine SAYAGH,發布說明: Zec PHP資料解析庫的初始版本。
注意:該庫目前正在開發中。官方文件和更多資源將很快提供。
作者資訊:
我們完全開放合作!如果您有興趣為 PHP 資料解析庫做出貢獻,我們很樂意聽取您的意見。無論是透過程式碼貢獻、文件改進或功能建議,我們都非常歡迎您提出意見。
有關更多詳細信息,請查看我們的貢獻指南(連結到詳細的貢獻指南(如果有))。
我們期待與充滿活力的貢獻者社群一起建立強大的數據解析工具!
使用簡單的模式定義來定義和驗證資料類型:
use function Zec Utils z ;
$ my_schema = z ()-> string ();
$ response_valid = $ my_schema -> parse ( " Hello, World! " ); // Returns Zec data object
$ value = $ response_valid -> value ; // Returns "Hello, World!"
$ response_invalid = $ my_schema -> parse ( 123 ); // Returns Zec data object
$ errors = $ response_invalid -> errors ; // Returns an array of ZecError object an exception extends class解析後快速驗證資料:
$ is_valid = $ my_schema -> parse ( " Hello, World! " )-> isValid (); // Returns true
$ is_invalid = $ my_schema -> parse ( 123 )-> isValid (); // Returns false使用 parse_or_throw 處理異常以進行關鍵資料驗證:
try {
$ response = $ my_schema -> parseOrThrow ( 123 ); // Throws ZecError
} catch ( ZecError $ error ) {
$ error_message = $ error -> message ; // Returns "Invalid type: expected string, received integer"
$ error -> log (); // Logs the error
}您可以透過合併其他驗證選項來增強架構定義。這樣可以根據特定要求對資料一致性進行更詳細的控制。
use function Zec z ;
$ user_schema = z ()-> options ([
' name ' => z ()-> string ()-> min ( 3 )-> max ( 50 ),
' email ' => z ()-> email (),
' age ' => z ()-> number ()-> min ( 18 ),
' isActive ' => z ()-> boolean (),
' registrationDate ' => z ()-> date ()
]);
// Parsing a valid user object
$ valid_user = $ user_schema -> parse ([
' name ' => ' John Doe ' ,
' email ' => ' [email protected] ' ,
' age ' => 30 ,
' isActive ' => true ,
' registrationDate ' => ' 2021-01-01 '
]);
// Parsing an invalid user object
$ invalid_user = $ user_schema -> parse ([
' name ' => ' JD ' , // Too short
' email ' => ' john.doe@ ' , // Invalid email format
' age ' => 17 , // Below minimum age requirement
' isActive ' => ' yes ' , // Incorrect type (should be boolean)
' registrationDate ' => ' 01-01-2021 ' // Wrong date format
]);
// Handling validation results
if ( $ valid_user -> isValid ()) {
echo ' User is valid. ' ;
} else {
echo ' User is invalid. Errors: ' ;
var_dump ( $ valid_user -> errors ());
}
if ( $ invalid_user -> isValid ()) {
echo ' User is valid. ' ;
} else {
echo ' User is invalid. Errors: ' ;
var_dump ( $ invalid_user -> errors ());
}該程式庫為資料驗證提供了廣泛的可配置性,允許使用者使用自訂訊息和條件定義複雜的驗證規則。以下是如何使用特定驗證規則為電子郵件欄位配置詳細架構的範例:
use function Zec z ;
// Define a configurable email schema
$ my_configurable_email_schema = z ()-> string ([
' message ' => ' Invalid string data '
])-> min ([
' min ' => 3 ,
' message ' => ' String data must be at least 3 characters long ' // Custom message
])-> max ([
' max ' => 10 ,
' message ' => ' String {{value}} must be at most ((max)) characters long ' // Custom message with value interpolation
]). email ([
' message ' => ' Invalid email ' ,
' domain ' => [ ' gmail.com ' , ' yahoo.com ' ] // Custom domain validation rules
]);
// Define a user schema using the configurable email schema
$ my_user = z ()-> options ([
' email ' => $ my_configurable_email_schema -> required ()
]);此範例示範驗證包括巢狀數組、可選欄位和聯合類型的使用者資料結構,展示此庫處理複雜且真實的資料模型的能力。
use function Zec z ;
// Define a user schema with various data validation rules
$ user_parser = z ()-> options ([
' name ' => z ()-> required ()-> string ()-> min ( 3 )-> max ( 50 ),
' email ' => z ()-> url ([
' message ' => ' Invalid email address ' ,
' domain ' => [ ' gmail.com ' ]
]),
' age ' => z ()-> number (),
' friends ' => z ()-> each (
function ( $ user ) {
return $ user -> nullable ();
} // Each friend is a user object (nullable)
),
' password ' => z ()-> optional ()-> options ([
' password ' => z ()-> string (), // Path: 'password.password'
' confirm_password ' => z ()-> string (),
' created_at ' => z ()-> date (),
]),
' created_at ' => z ()-> date (),
' updated_at ' => z ()-> date (),
' document ' => z ()-> union ([
z ()-> options ([
' type ' => z ()-> enum ([ ' student ' ]),
' content ' => z ()-> options ([
' school ' => z ()-> string (),
' grade ' => z ()-> number (),
]),
]),
z ()-> options ([
' type ' => z ()-> enum ([ ' teacher ' ]),
' content ' => z ()-> options ([
' school ' => z ()-> string (),
' subject ' => z ()-> string (),
]),
]),
]) // Union type for document, can be student or teacher document
]);
// Parse a valid user object
$ user = $ user_parser -> parse ([
' name ' => ' John Doe ' ,
' email ' => ' [email protected] ' ,
' age ' => 25 ,
' friends ' => [
[
' name ' => ' Jane Doe ' ,
' email ' => ' [email protected] ' ,
' age ' => 30 ,
],
],
' password ' => [
' password ' => ' password ' ,
' confirm_password ' => ' password ' ,
' created_at ' => ' 2021-10-10 '
],
' created_at ' => ' 2021-10-10 ' ,
' updated_at ' => ' 2021-10-10 ' ,
' document ' => [
' type ' => ' student ' ,
' content ' => [
' school ' => ' School ' ,
' grade ' => 10 ,
]
]
]); // Returns a Zec object
// Validate the parsed data
if ( $ user -> isValid ()) {
echo ' User is valid. ' ;
var_dump ( $ user -> getValue ()); // Outputs the validated data
} else {
echo ' User is invalid. ' ;
var_dump ( $ user -> errors ()); // Outputs validation errors
}為了增強靈活性並滿足特定的驗證需求,我們的程式庫允許使用者定義自訂解析器方法。本節示範如何建立size解析器方法,該方法驗證陣列的大小、字串的長度或數字的值是否符合特定要求。
size方法檢查是否:
以下是實作此自訂解析器的方法:
use function Zec z ;
use function Zec bundler ;
use Zec FIELD as FK ;
$ custom_size_parser = parser_build ()
-> name ( ' size ' )
-> prioritize ( ' string ' , ' number ' , ' array ' ) // Prioritize the parser for string, number, and array types
-> argument ( ' message ' , ' Invalid size ' , function ( Zec Zec $ z ) {
return $ z -> required ()-> string ();
}) // argument for custom message, default is 'Invalid size'
-> argument ( ' size ' , 0 , function ( Zec Zec $ z ) {
return $ z -> required ()-> number ();
}) // argument for size, default is 0
-> function ( function ( array $ args ): string | bool {
$ value = $ args [ ' value ' ];
$ expected_size = $ args [ ' size ' ];
$ message = $ args [ ' message ' ];
if ( is_array ( $ value )) {
$ actual_size = count ( $ value );
} elseif ( is_string ( $ value )) {
$ actual_size = strlen ( $ value );
} elseif ( is_numeric ( $ value )) {
$ actual_size = $ value ;
} else {
return $ message ?? ' Invalid data type ' ;
}
if ( $ actual_size === $ expected_size ) {
return true ;
}
return $ message ?? ' Invalid size ' ;
})-> priority ( 4 ); // priority of the parser, the default priority of parser is 10, parser with 5 as priority will override before parser with 10 as priority if they have the same parser name
-> build (); // Build the parser
bundler-> addParser ( $ custom_size_parser );現在您可以在架構定義中使用自訂size解析器方法:
$ my_schema = z ()-> options ([
' username ' => z ()-> string ()-> size ( 5 ), // Username must be a string of length 5
' favorite_numbers ' => z ()-> array ()-> size ( 5 ), // Favorite numbers must be an array of length 5
' lucky_number ' => z ()-> number ()-> size ( 5 ), // Lucky number must be 5
]);
$ user_data = [
' username ' => ' admin ' ,
' favorite_numbers ' => [ 1 , 2 , 3 , 4 , 5 ],
' lucky_number ' => 5
]; // Valid data
$ parsed_data = $ my_schema -> parse ( $ user_data ); // Returns a Zec object
// Validate the parsed data
if ( $ parsed_data -> isValid ()) { // Returns true if data is valid
echo ' All data is valid. ' ;
} else {
echo ' Data validation failed. Errors: ' ;
var_dump ( $ parsed_data -> errors ()); // Outputs validation errors
}該項目已根據 MIT 許可證獲得許可 - 有關詳細信息,請參閱 LICENSE.md 文件。
版權所有 (c) 2024 穆罕默德·阿明·SAYAGH
版權所有。
特此免費授予任何獲得本軟體及相關文件文件(「軟體」)副本的人不受限制地使用本軟體,包括但不限於使用、複製、修改、合併的權利、發布、散佈、再授權和/或銷售軟體的副本,並允許向其提供軟體的人員這樣做,但須滿足以下條件:
上述版權聲明和本授權聲明應包含在本軟體的所有副本或主要部分中。
本軟體以「現況」提供,不提供任何明示或暗示的保證,包括但不限於適銷性、特定用途的適用性和不侵權的保證。 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE軟體.