{"id":18273456,"url":"https://github.com/arraypress/slurp","last_synced_at":"2026-01-03T05:04:32.195Z","repository":{"id":218422515,"uuid":"746367734","full_name":"arraypress/slurp","owner":"arraypress","description":"The Slurp library provides a powerful and efficient solution for dynamically including PHP files in WordPress or general PHP projects.","archived":false,"fork":false,"pushed_at":"2024-05-20T15:09:03.000Z","size":38,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-22T11:14:21.109Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/arraypress.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"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-01-21T20:53:46.000Z","updated_at":"2024-05-20T15:09:07.000Z","dependencies_parsed_at":"2024-02-07T14:41:22.118Z","dependency_job_id":"8174c63a-04c5-4fb2-97e5-d1b7dbbc8b09","html_url":"https://github.com/arraypress/slurp","commit_stats":null,"previous_names":["arraypress/slurp"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fslurp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fslurp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fslurp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fslurp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/arraypress","download_url":"https://codeload.github.com/arraypress/slurp/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243796739,"owners_count":20349264,"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":[],"created_at":"2024-11-05T12:06:32.331Z","updated_at":"2026-01-03T05:04:32.099Z","avatar_url":"https://github.com/arraypress.png","language":"PHP","readme":"# Slurp Library\n\nThe Slurp library provides a powerful and efficient solution for dynamically including PHP files in WordPress or general\nPHP projects. It supports recursive file inclusion, conditional inclusion via callbacks, and offers robust debugging\ncapabilities by tracking and logging included files. Ideal for organized and efficient file management in plugin or\napplication development.\n\n## Features ##\n\n* **Dynamic File Inclusion:** Automatically include PHP files from specified directories, streamlining project setup and\n  maintenance.\n* **Recursive Inclusion:** Capable of including files from subdirectories recursively, ensuring no file is left behind.\n* **Conditional Inclusion:** Utilize callbacks to conditionally include files based on custom logic, such as user roles\n  or environment settings.\n* **Global Callbacks:** Set a global callback for file inclusion, applying a single condition across all included files.\n* **Exclusion Capability:** Specify files to exclude from inclusion, allowing for precise control over which files are\n  loaded.\n* **Debugging Support:** Dump a list of all included files to a file, aiding in debugging and ensuring transparency in\n  file management.\n* **Flexible Usage:** Designed for both WordPress and general PHP projects, offering versatility across different\n  development environments.\n* **Helper Function:** Provides a `slurp` helper function to simplify usage within WordPress, making it easy to\n  integrate into plugins or themes.\n\n## Minimum Requirements ##\n\n* **PHP:** 7.4\n\n## Installation ##\n\nSlurp is a developer library, not a plugin, which means you need to include it somewhere in your own\nproject.\n\nYou can use Composer:\n\n```bash\ncomposer require arraypress/slurp\n```\n\n#### Basic File Inclusion\n\n```php\n// Require the Composer autoloader.\nrequire_once __DIR__ . '/vendor/autoload.php';\n\n// Use the Slurp class from the ArrayPress\\Utils namespace.\nUse ArrayPress\\Utils\\Slurp;\n\n// Create a Slurp instance for a specific directory. This prepares the Slurp class to handle file inclusions from the given directory.\n$slurp = new Slurp(__DIR__);\n\n// Include all PHP files from the specified subdirectory. The include method facilitates the inclusion of files from a directory relative to the base directory specified during instantiation.\n$slurp-\u003einclude( 'subdirectory' );\n\n// Include all PHP files directly from the base directory. By calling the include method without any arguments, Slurp will include files from the base directory specified during its instantiation.\n$slurp-\u003einclude();\n```\n\n#### Recursive File Inclusion\n\n```php\n// Include files from a directory and all its subdirectories.\n$slurp-\u003einclude( 'subdirectory', true );\n```\n\n#### Multiple Directory Inclusion\n\n```php\n$slurp-\u003einclude( [ 'subdirectory1', 'subdirectory2' ] );\n```\n\n#### Conditional File Inclusion with Callback\n\n```php\n$slurp-\u003einclude( [\n    'subdirectory' =\u003e function( $filePath ) {\n        // Only include files that contain 'module' in their name.\n        return strpos( $filePath, 'module' ) !== false;\n    }\n] );\n```\n\n#### Conditional File Inclusion with Global Callback\n\n```php\n// Instantiate the Slurp class, setting the base directory and providing a global callback.\n// The global callback uses is_admin() to determine if the file should be included,\n// which is useful for admin-only features.\n$slurp = new Slurp( __DIR__, function( $filePath ) {\n    return is_admin(); // Global callback to include files only in the WordPress admin area.\n} );\n\n// Include PHP files from a specific directory. Thanks to the global callback,\n// files will only be included if is_admin() returns true.\n$slurp-\u003einclude( [ 'admin', 'reports' ] );\n```\n\n#### Excluding Specific Files Upon Initialization\n\nWhen creating a new instance of the `Slurp` class, you can immediately specify files to exclude by passing an array of\nfilenames as the third argument to the constructor. This method is useful when you know upfront which files should not\nbe included.\n\n```php\n// Initialize Slurp with an exclusion list.\n$slurp = new Slurp( __DIR__, null, [ 'index.php', 'exclude.php' ] );\n// Proceed to include all PHP files from the directory except 'index.php' and 'exclude.php'.\n$slurp-\u003einclude();\n```\n\n#### Setting an Exclusion List\n\nThe `setExcluded` method replaces the current list of excluded files with a new array of filenames. Use this method when\nyou need to redefine the entire list of exclusions.\n\n```php\n// Set a new list of specific files to be excluded from inclusion.\n$slurp-\u003esetExcluded( ['newexclude.php', 'anotherexclude.php'] );\n// This will override any previous exclusions and only exclude 'newexclude.php' and 'anotherexclude.php'.\n```\n\n#### Adding to an Existing Exclusion List\n\nThe `addExclusion` method allows you to add one or more files to the existing list of exclusions. You can pass a single\nfilename as a string or an array of filenames. This method is ideal for dynamically adjusting the list of exclusions\nafter the Slurp instance has been created.\n\n```php\n// Add a single file to the existing list of excluded files.\n$slurp-\u003eaddExclusion( 'additionalExclude.php' );\n```\n\nOr\n\n```php\n// Add multiple files to the existing list of excluded files.\n$slurp-\u003eaddExclusion( ['additionalExclude1.php', 'additionalExclude2.php'] );\n```\n\nThese additions are cumulative and do not overwrite the existing exclusion list but rather extend it. The `addExclusion`\nmethod ensures that all specified files are uniquely added, preventing duplicates in the exclusion list.\n\n#### Overriding Global Callback\n\n```php\n // Global callback to include files only in the WordPress admin area.\n$slurp-\u003esetCallback( function( $filePath ) {\n    return is_admin();\n} );\n```\n\n#### Overriding Base Directory\n\n```php\n// Include all other PHP files from the directory.\n$slurp-\u003esetBaseDir( __DIR__ . '/includes' );\n```\n\n#### Dumping Loaded Files for Debugging\n\n```php\n// Dump the list of included files to a text file for debugging.\n$slurp-\u003edumpFiles( 'debug.txt' );\n```\n\n#### Retrieving List of Loaded Files\n\n```php\n$loadedFiles = $slurp-\u003egetFiles(); // Get an array of all the PHP files that have been included.\necho '\u003cpre\u003e';\nprint_r( $loadedFiles );\necho '\u003c/pre\u003e';\n```\n\n#### Including Files from Multiple Directories\n\n```php\n// Assuming the Slurp class is already autoloaded via Composer\n$slurp = new Slurp( __DIR__ );\n\n// Include files from multiple directories.\n$directories = [ 'directory1', 'directory2', 'directory3' ];\n$slurp-\u003einclude( $directories );\n\n// You can also include files recursively from these directories\n$slurp-\u003einclude( $directories, true );\n\n// Or include files based on a callback condition for each directory\n$slurp-\u003einclude( [\n    'directory1' =\u003e function( $file ) { return strpos( $file, 'condition1' ) !== false; },\n    'directory2' =\u003e function( $file ) { return strpos( $file, 'condition2' ) !== false; },\n    'directory3' =\u003e null // Include all files from directory3\n] );\n```\n\n#### Utilizing Whitelist to Restrict File Inclusion\n\nThe whitelist feature allows you to specify a list of directories from which files can be safely included. This is\nparticularly useful when you want to include files from a limited set of locations, further tightening security around\nfile inclusion.\n\n```php\n$slurp = new Slurp( __DIR__ );\n\n// Add directories to the whitelist\n$slurp-\u003eaddToWhitelist( __DIR__ . '/safe_includes' );\n$slurp-\u003eaddToWhitelist( __DIR__ . '/more_safe_includes' );\n\n// Including files from whitelisted directories\n$slurp-\u003einclude( 'safe_includes' ); // Allowed\n$slurp-\u003einclude( 'more_safe_includes' ); // Allowed\n\n// Attempting to include files from a directory not in the whitelist will prevent inclusion\n$slurp-\u003einclude( 'unsafe_includes' ); // Prevented, no exception thrown but inclusion does not happen\n```\n\n#### Using the Helper Function in WordPress\n\n##### Example 1: Including Files for Admin Pages Only\n\nThis example demonstrates how to include files from a specified directory only if the WordPress admin interface is being\naccessed. This can be useful for loading admin-specific functionalities.\n\n```php\nadd_action( 'admin_init', function() {\n    $slurp = slurp(\n        'admin', // Subdirectory containing admin files\n        __DIR__, // Base directory targeted towards admin-related files\n        false, // Non-recursive inclusion\n        function ( $filePath ) {\n            return is_admin();\n        }\n    );\n    // Assume further setup or actions are taken with $slurp if needed\n} );\n```\n\n##### Example 2: Including Plugin Core Files with Recursion\n\nThis example shows how to include all PHP files within the 'includes' directory of a plugin, doing so recursively to\nensure that files in subdirectories are also loaded.\n\n```php\n$slurp = slurp(\n    'dev-tools', // Subdirectory containing development tools\n    __DIR__, // Plugin root directory\n    true, // Recursive inclusion to get all tools\n    function ( $filePath ) {\n        return defined('WP_DEBUG') \u0026\u0026 WP_DEBUG; // Only include if WP_DEBUG is true\n    }\n);\n```\n\n##### Example 3: Conditional Inclusion Based on Site Context\n\nThis example uses a global callback to conditionally include files based on whether the site is in a development\nenvironment. This is useful for loading debug tools or additional resources that should not be present in production.\n\n```php\n$slurp = slurp(\n    'dev-tools', // Subdirectory containing development tools\n    __DIR__, // Plugin root directory\n    true, // Recursive inclusion to get all tools\n    function ( $filePath ) {\n        return defined('WP_DEBUG') \u0026\u0026 WP_DEBUG; // Only include if WP_DEBUG is true\n    }\n);\n// Development tools are loaded if the site is in debug mode\n```\n\n##### Example 4: Excluding Specific Files from Inclusion\n\nIn some cases, you might want to exclude specific files from being included, such as example files or documentation.\nThis example demonstrates how to use the `excludedFiles` parameter for this purpose.\n\n```php\n$slurp = slurp(\n    'includes', // Subdirectory containing plugin include files\n    __DIR__, // Base directory for inclusion\n    false, // Non-recursive inclusion\n    null, // No global callback, include all files\n    [ 'example.php', 'readme.md' ] // Exclude example and readme files from inclusion\n);\n// Only desired files are included, excluding the specified ones\n```\n\n##### Example 5: Error Handling with Callback\n\nThis example demonstrates how to use the `errorCallback` parameter for error handling, which can be particularly useful\nfor logging errors or handling them in a specific manner within your WordPress environment.\n\n```php\n$slurp = slurp(\n    'critical', // Include directly from the base directory\n    __DIR__, // Base directory for critical functionalities\n    false, // Non-recursive inclusion\n    null, // No global callback, include all files\n    [], // No files are excluded\n    function ( $e ) {\n        // Log error or handle it accordingly\n        error_log( 'Error loading critical files: ' . $e-\u003egetMessage() );\n    }\n);\n// Critical functionalities are attempted to be loaded, with error handling in place\n```\n\n##### Example 6: Conditional Inclusion with WordPress Hook\n\nThis example shows how to use the slurp_hooked function to include files only when specific conditions are met, such as\nbeing within the WordPress admin area. This setup is useful for plugins or themes that have admin-specific\nfunctionality.\n\n```php\n// Attach the file inclusion process to the WordPress 'init' hook\nslurp_hooked(\n    'init',                                  // The WordPress hook to attach to\n    __DIR__,                                 // Base directory for file inclusion\n    'admin',                                 // Subdirectory containing admin files\n    false,                                   // Non-recursive inclusion\n    function ( $filePath ) {                 // Global callback to include files conditionally\n        return is_admin();                   // Only include files if in the admin area\n    },\n    [ 'ignore-this.php', 'old-config.php' ], // Exclude specific files from inclusion\n    10,                                      // Default priority\n    1                                        // Number of arguments accepted by the function\n);\n// Files in the 'admin' subdirectory are included only when the user is in the admin area,\n// and specified files are excluded from inclusion.\n```\n\n## Contributions\n\nContributions to this library are highly appreciated. Raise issues on GitHub or submit pull requests for bug\nfixes or new features. Share feedback and suggestions for improvements.\n\n## License: GPLv2 or later\n\nThis program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public\nLicense as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied\nwarranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farraypress%2Fslurp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farraypress%2Fslurp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farraypress%2Fslurp/lists"}