{"id":15296446,"url":"https://github.com/aminesayagh/zec-data-parsing","last_synced_at":"2025-10-25T09:43:59.114Z","repository":{"id":239605154,"uuid":"776767310","full_name":"aminesayagh/Zec-Data-Parsing","owner":"aminesayagh","description":"Data Parsing and schema declaration Library","archived":false,"fork":false,"pushed_at":"2024-06-18T16:10:36.000Z","size":1267,"stargazers_count":8,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-27T10:37:58.785Z","etag":null,"topics":["dataparsing","dataschema","php","php-library","php8","security"],"latest_commit_sha":null,"homepage":"https://masayagh.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aminesayagh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-03-24T12:42:54.000Z","updated_at":"2024-08-22T08:38:59.000Z","dependencies_parsed_at":"2024-05-19T13:52:14.214Z","dependency_job_id":"96b16091-c8da-4fb1-bcb8-6d89532bf108","html_url":"https://github.com/aminesayagh/Zec-Data-Parsing","commit_stats":null,"previous_names":["aminesayagh/data-parsing-library","aminesayagh/zec-data-parsing"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aminesayagh%2FZec-Data-Parsing","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aminesayagh%2FZec-Data-Parsing/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aminesayagh%2FZec-Data-Parsing/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aminesayagh%2FZec-Data-Parsing/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aminesayagh","download_url":"https://codeload.github.com/aminesayagh/Zec-Data-Parsing/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248773848,"owners_count":21159520,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dataparsing","dataschema","php","php-library","php8","security"],"created_at":"2024-09-30T18:10:32.009Z","updated_at":"2025-10-25T09:43:54.067Z","avatar_url":"https://github.com/aminesayagh.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Zec: PHP Data Parsing Library\n\nThe Zec Data Parsing and schema declaration Library is designed to bring schema definition and validation capabilities to PHP applications.\n\n## Installation\n\n### Composer\n\n```bash\ncomposer require mohamed-amine-sayagh/zec\n```\n\n### Requirements\n\n- PHP 8.0 or higher\n\n## Usage Example\n\nHere's an example of how to use the Zec library to define and validate a user profile schema:\n\n### Define a schema for user data validation\n\n```php\n    use function Zec\\Utils\\z;\n\n    // Define the user profile schema\n    $userProfileParser = z()-\u003eoptions([\n        'name' =\u003e z()-\u003estring()-\u003emin(3)-\u003emax(50),  // Name must be a string between 3 and 50 characters\n        'age' =\u003e z()-\u003enumber()-\u003emin(18),           // Age must be a number and at least 18\n        'email' =\u003e z()-\u003eemail(),                   // Email must be a valid email address\n        'address' =\u003e z()-\u003eoptions([               \n            'street' =\u003e z()-\u003estring(),             \n            'city' =\u003e z()-\u003estring()                \n        ]),\n        'hobbies' =\u003e z()-\u003eeach(z()-\u003estring()),     // Hobbies must be an array of strings\n        'metadata' =\u003e z()-\u003eoptional()-\u003eeach(z()-\u003eoptions([  // Metadata is optional and must be an array of objects\n            'key' =\u003e z()-\u003estring(),                // Each object must have a key as a string\n            'value' =\u003e z()-\u003estring()               // Each object must have a value as a string\n        ]))\n    ]);\n```\n\n### Parse user data and validate it\n\n```php\n    // Parse and validate user data\n    $userData = [\n        'name' =\u003e 'Jane Doe',\n        'age' =\u003e 1, // 1 is not a valid age\n        'email' =\u003e 'jane.doe@examplecom', // missing dot\n        'address' =\u003e [\n            'street' =\u003e '123 Elm St',\n            'city' =\u003e 3 // city is not a string\n        ],\n        'hobbies' =\u003e ['photography', 'traveling', 'reading', 5], // 5 is not a string     \n        'metadata' =\u003e [\n            ['key' =\u003e 'memberSince', 'value' =\u003e '2019'],\n            ['key' =\u003e 'newsletter', 'value' =\u003e 'true']\n        ]\n    ];\n\n    try {\n        $userProfileParser-\u003eparseOrThrow($userData); // Throws an error\n        echo \"User data is valid\\n\";\n    } catch (\\Zec\\ZecError $e) {\n        echo \"User data is invalid: \";\n        $e-\u003elog(); // Log the error\n    }\n```\n\n### Expected Error Response\n\n```plaintext\n    User data is invalid: [\n        {\n            \"parser\": \"min\",\n            \"value\": 1,\n            \"min\": 18,\n            \"message\": \"Invalid value\",\n            \"path\": [\n                \"age\"\n            ]\n        },\n        {\n            \"parser\": \"email\",\n            \"value\": \"jane.doe@examplecom\",\n            \"message\": \"Invalid email address\",\n            \"path\": [\n                \"email\"\n            ]\n        },\n        {\n            \"parser\": \"string\",\n            \"value\": 5,\n            \"message\": \"Invalid string value\",\n            \"path\": [\n                \"hobbies\",\n                \"3\"\n            ]\n        }\n    ]\n```\n\n**Current Version:** v1.0.0, **Release Date:** 2024-10-01, **Author:** Mohamed Amine SAYAGH, **Release Notes:** Initial release of the Zec PHP Data Parsing Library., **Release Link:** [Zec 1.0.0](\n\n**Note:** This library is currently in development. Official documentation and further resources will be available soon.\n\n**Author Information:**\n\n- [LinkedIn](https://www.linkedin.com/in/mohamedamine-sayagh/)\n- [GitHub](https://github.com/aminesayagh/)\n- [Portfolio](https://www.masayagh.com/)\n\n## Table of Contents\n\n- [Installation](#installation)\n- [Collaboration](#collaboration)\n- [How to Contribute](#how-to-contribute)\n- [Usage](#usage)\n  - [Basic Parsing](#basic-parsing)\n  - [Validation](#validation)\n  - [Exception Handling with Parsing](#exception-handling-with-parsing)\n  - [Parsing of an array of options](#parsing-of-an-array-of-options)\n  - [Advanced Parser Configuration](#advanced-parser-configuration)\n  - [Complex Example: User Data Validation](#complex-example-user-data-validation)\n- [Creating Custom Parser Methods](#creating-custom-parser-methods)\n- [License](#license)\n\n### Some other great aspects\n\n- **Robust Schema Validation**: Provides strong typing and validation similar to the Zec library, ensuring accurate data handling.\n- **Modular and Extensible**: Easy to extend with custom parsers, accommodating diverse data validation needs.\n- **Separation of Concerns**: Keeps data parsing separate from business logic for better security and maintainability.\n- **Ease of Testing**: Simplifies testing by enforcing strict data validation.\n- **Flexible Configuration**: Supports dynamic parser configurations and customizations without altering the core library.\n- **Community-Focused**: Open for contributions, enhancing collective improvement and support.\n\n## Collaboration\n\n**We are fully open to collaboration!** If you're interested in contributing to the PHP Data Parsing Library, we'd love to hear from you. Whether it's through code contributions, documentation improvements, or feature suggestions, your input is highly welcome.\n\n## How to Contribute\n\n1. **Fork the Repository**: Start by forking the repository to your own GitHub account.\n2. **Clone Your Fork**: Clone your fork to your local machine and set up the development environment.\n3. **Create a New Branch**: Make your changes in a new git branch.\n4. **Commit Your Changes**: Commit your modifications with clear and descriptive commit messages.\n5. **Push Your Changes**: Push your changes to your fork on GitHub.\n6. **Submit a Pull Request**: Open a pull request to the main branch of our repository. Please provide a clear description of the changes and any other information that will help us understand your contributions.\n\nFor more details, check our contribution guidelines (link to detailed contribution guidelines if available).\n\nWe look forward to building a powerful data parsing tool with a vibrant community of contributors!\n\n## Usage\n\n### Basic Parsing\n\nDefine and validate data types using simple schema definitions:\n\n```php\n    use function Zec\\Utils\\z;\n    $my_schema = z()-\u003estring();\n    \n    $response_valid = $my_schema-\u003eparse(\"Hello, World!\"); // Returns Zec data object\n    $value = $response_valid-\u003evalue; // Returns \"Hello, World!\"\n\n    $response_invalid = $my_schema-\u003eparse(123); // Returns Zec data object\n    $errors = $response_invalid-\u003eerrors; // Returns an array of ZecError object an exception extends class\n```\n\n### Validation\n\nQuickly validate data after parsing:\n\n```php\n    $is_valid = $my_schema-\u003eparse(\"Hello, World!\")-\u003eisValid(); // Returns true\n    $is_invalid = $my_schema-\u003eparse(123)-\u003eisValid(); // Returns false\n```\n\n### Exception Handling with Parsing\n\nHandle exceptions using parse_or_throw for critical data validation:\n\n```php\n    try {\n        $response = $my_schema-\u003eparseOrThrow(123); // Throws ZecError\n    } catch (ZecError $error) {\n        $error_message = $error-\u003emessage; // Returns \"Invalid type: expected string, received integer\"\n        $error-\u003elog(); // Logs the error\n    }\n```\n\n### Parsing of an array of options\n\nYou can enhance the schema definition by incorporating additional validation options. This allows for more detailed control over data conformity based on specific requirements.\n\n```php\n    use function Zec\\z;\n\n    $user_schema = z()-\u003eoptions([\n        'name' =\u003e z()-\u003estring()-\u003emin(3)-\u003emax(50),\n        'email' =\u003e z()-\u003eemail(),\n        'age' =\u003e z()-\u003enumber()-\u003emin(18),\n        'isActive' =\u003e z()-\u003eboolean(),\n        'registrationDate' =\u003e z()-\u003edate()\n    ]);\n\n    // Parsing a valid user object\n    $valid_user = $user_schema-\u003eparse([\n        'name' =\u003e 'John Doe',\n        'email' =\u003e 'john.doe@example.com',\n        'age' =\u003e 30,\n        'isActive' =\u003e true,\n        'registrationDate' =\u003e '2021-01-01'\n    ]);\n\n    // Parsing an invalid user object\n    $invalid_user = $user_schema-\u003eparse([\n        'name' =\u003e 'JD', // Too short\n        'email' =\u003e 'john.doe@', // Invalid email format\n        'age' =\u003e 17, // Below minimum age requirement\n        'isActive' =\u003e 'yes', // Incorrect type (should be boolean)\n        'registrationDate' =\u003e '01-01-2021' // Wrong date format\n    ]);\n\n    // Handling validation results\n    if ($valid_user-\u003eisValid()) {\n        echo 'User is valid.';\n    } else {\n        echo 'User is invalid. Errors: ';\n        var_dump($valid_user-\u003eerrors());\n    }\n\n    if ($invalid_user-\u003eisValid()) {\n        echo 'User is valid.';\n    } else {\n        echo 'User is invalid. Errors: ';\n        var_dump($invalid_user-\u003eerrors());\n    }\n```\n\n### Advanced Parser Configuration\n\nThe library provides extensive Configurability for data validation, allowing users to define complex validation rules with custom messages and conditions. Below is an example of how to configure a detailed schema for an email field with specific validation rules:\n\n```php\n    use function Zec\\z;\n\n    // Define a configurable email schema\n    $my_configurable_email_schema = z()-\u003estring([\n        'message' =\u003e 'Invalid string data'\n    ])-\u003emin([\n        'min' =\u003e 3,\n        'message' =\u003e 'String data must be at least 3 characters long' // Custom message\n    ])-\u003emax([\n        'max' =\u003e 10,\n        'message' =\u003e 'String {{value}} must be at most ((max)) characters long' // Custom message with value interpolation\n    ]).email([\n        'message' =\u003e 'Invalid email',\n        'domain' =\u003e ['gmail.com', 'yahoo.com'] // Custom domain validation rules\n    ]);\n\n    // Define a user schema using the configurable email schema\n    $my_user = z()-\u003eoptions([\n        'email' =\u003e $my_configurable_email_schema-\u003erequired()\n    ]);\n```\n\n### Complex Example: User Data Validation\n\nThis example demonstrates validating a user data structure that includes nested arrays, optional fields, and union types, showcasing the library's capability to handle complex and realistic data models.\n\n```php\n    use function Zec\\z;\n\n    // Define a user schema with various data validation rules\n    $user_parser = z()-\u003eoptions([\n        'name' =\u003e z()-\u003erequired()-\u003estring()-\u003emin(3)-\u003emax(50),\n        'email' =\u003e z()-\u003eurl([\n            'message' =\u003e 'Invalid email address', \n            'domain' =\u003e ['gmail.com']\n        ]),\n        'age' =\u003e z()-\u003enumber(),\n        'friends' =\u003e z()-\u003eeach(\n            function ($user) {\n                return $user-\u003enullable();\n            } // Each friend is a user object (nullable)\n        ),\n        'password' =\u003e z()-\u003eoptional()-\u003eoptions([\n            'password' =\u003e z()-\u003estring(),  // Path: 'password.password'\n            'confirm_password' =\u003e z()-\u003estring(),\n            'created_at' =\u003e z()-\u003edate(),\n        ]),\n        'created_at' =\u003e z()-\u003edate(),\n        'updated_at' =\u003e z()-\u003edate(),\n        'document' =\u003e z()-\u003eunion([\n            z()-\u003eoptions([\n                'type' =\u003e z()-\u003eenum(['student']),\n                'content' =\u003e z()-\u003eoptions([\n                    'school' =\u003e z()-\u003estring(),\n                    'grade' =\u003e z()-\u003enumber(),\n                ]),\n            ]),\n            z()-\u003eoptions([\n                'type' =\u003e z()-\u003eenum(['teacher']),\n                'content' =\u003e z()-\u003eoptions([\n                    'school' =\u003e z()-\u003estring(),\n                    'subject' =\u003e z()-\u003estring(),\n                ]),\n            ]),\n        ]) // Union type for document, can be student or teacher document\n    ]);\n\n    // Parse a valid user object\n    $user = $user_parser-\u003eparse([\n        'name' =\u003e 'John Doe',\n        'email' =\u003e 'amine@gmail.com',\n        'age' =\u003e 25,\n        'friends' =\u003e [\n            [\n                'name' =\u003e 'Jane Doe',\n                'email' =\u003e 'john@gmail.com',\n                'age' =\u003e 30,\n            ],\n        ],\n        'password' =\u003e [\n            'password' =\u003e 'password',\n            'confirm_password' =\u003e 'password',\n            'created_at' =\u003e '2021-10-10'\n        ],\n        'created_at' =\u003e '2021-10-10',\n        'updated_at' =\u003e '2021-10-10',\n        'document' =\u003e [\n            'type' =\u003e 'student',\n            'content' =\u003e [\n                'school' =\u003e 'School',\n                'grade' =\u003e 10,\n            ]\n        ]\n    ]); // Returns a Zec object\n\n    // Validate the parsed data\n    if ($user-\u003eisValid()) {\n        echo 'User is valid.';\n        var_dump($user-\u003egetValue()); // Outputs the validated data\n    } else {\n        echo 'User is invalid.';\n        var_dump($user-\u003eerrors()); // Outputs validation errors\n    }\n```\n\n## Creating Custom Parser Methods\n\nTo enhance flexibility and cater to specific validation needs, our library allows users to define custom parser methods. This section demonstrates how to create a `size` parser method, which validates that the size of an array, length of a string, or value of a number meets a specific requirement.\n\nThe `size` method checks if:\n\n- An array's length equals a specified size.\n- A string's length equals a specified number of characters.\n- A numeric value is exactly equal to a specified number.\n\nHere is how you can implement this custom parser:\n\n```php\n    use function Zec\\z;\n    use function Zec\\bundler;\n    use Zec\\FIELD as FK;\n\n    $custom_size_parser = parser_build()\n        -\u003ename('size')\n        -\u003eprioritize('string', 'number', 'array') // Prioritize the parser for string, number, and array types\n        -\u003eargument('message', 'Invalid size', function (Zec\\Zec $z) {\n            return $z-\u003erequired()-\u003estring();\n        }) // argument for custom message, default is 'Invalid size'\n        -\u003eargument('size', 0, function (Zec\\Zec $z) {\n            return $z-\u003erequired()-\u003enumber();\n        }) // argument for size, default is 0\n        -\u003efunction(function (array $args): string|bool {\n            $value = $args['value'];\n            $expected_size = $args['size'];\n            $message = $args['message'];\n\n            if (is_array($value)) {\n                $actual_size = count($value);\n            } elseif (is_string($value)) {\n                $actual_size = strlen($value);\n            } elseif (is_numeric($value)) {\n                $actual_size = $value;\n            } else {\n                return $message ?? 'Invalid data type';\n            }\n\n            if ($actual_size === $expected_size) {\n                return true;\n            }\n            return $message ?? 'Invalid size';\n        })-\u003epriority(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\n        -\u003ebuild(); // Build the parser\n\n    bundler-\u003eaddParser($custom_size_parser);\n```\n\nYou can now use the custom `size` parser method in your schema definitions:\n\n```php\n    $my_schema = z()-\u003eoptions([\n        'username' =\u003e z()-\u003estring()-\u003esize(5), // Username must be a string of length 5\n        'favorite_numbers' =\u003e z()-\u003earray()-\u003esize(5), // Favorite numbers must be an array of length 5\n        'lucky_number' =\u003e z()-\u003enumber()-\u003esize(5), // Lucky number must be 5\n    ]);\n\n    $user_data = [\n        'username' =\u003e 'admin',\n        'favorite_numbers' =\u003e [1, 2, 3, 4, 5],\n        'lucky_number' =\u003e 5\n    ]; // Valid data\n\n    $parsed_data = $my_schema-\u003eparse($user_data); // Returns a Zec object\n\n    // Validate the parsed data\n    if ($parsed_data-\u003eisValid()) { // Returns true if data is valid\n        echo 'All data is valid.';\n    } else {\n        echo 'Data validation failed. Errors: ';\n        var_dump($parsed_data-\u003eerrors()); // Outputs validation errors\n    }\n```\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE.md file for details.\n\n### MIT License\n\nCopyright (c) 2024 Mohamed Amine SAYAGH\n\nAll rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faminesayagh%2Fzec-data-parsing","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faminesayagh%2Fzec-data-parsing","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faminesayagh%2Fzec-data-parsing/lists"}