This commit is contained in:
Jun Pataleta 2024-02-12 13:58:05 +08:00
commit a8a31f648d
No known key found for this signature in database
GPG Key ID: F83510526D99E2C7
140 changed files with 11476 additions and 381 deletions

View File

@ -170,7 +170,6 @@ function tool_dbtransfer_create_maintenance_file() {
$options = new stdClass();
$options->trusted = false;
$options->noclean = false;
$options->smiley = false;
$options->filter = false;
$options->para = true;
$options->newlines = false;

View File

@ -46,7 +46,6 @@ class tool_messageinbound_edit_handler_form extends moodleform {
$formatoptions = new stdClass();
$formatoptions->trusted = false;
$formatoptions->noclean = false;
$formatoptions->smiley = false;
$formatoptions->filter = false;
$formatoptions->para = true;
$formatoptions->newlines = false;

View File

@ -67,7 +67,6 @@ class tool_messageinbound_renderer extends plugin_renderer_base {
$descriptionoptions = new stdClass();
$descriptionoptions->trusted = false;
$descriptionoptions->noclean = false;
$descriptionoptions->smiley = false;
$descriptionoptions->filter = false;
$descriptionoptions->para = true;
$descriptionoptions->newlines = false;

View File

@ -47,7 +47,6 @@ if ($msgform->is_cancelled()) {
$options = new stdClass();
$options->para = false;
$options->newlines = true;
$options->smiley = false;
$options->trusted = trusttext_trusted(\context_system::instance());
$msg = format_text($formdata->messagebody['text'], $formdata->messagebody['format'], $options);

View File

@ -2013,17 +2013,10 @@ class coursecat_helper {
$options = (array)$options;
$context = context_course::instance($course->id);
if (!isset($options['context'])) {
// TODO see MDL-38521
// option 1 (current), page context - no code required
// option 2, system context
// $options['context'] = context_system::instance();
// option 3, course context:
// $options['context'] = $context;
// option 4, course category context:
// $options['context'] = $context->get_parent_context();
$options['context'] = $context;
}
$summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
$summary = format_text($summary, $course->summaryformat, $options, $course->id);
$summary = format_text($summary, $course->summaryformat, $options);
if (!empty($this->searchcriteria['search'])) {
$summary = highlight($this->searchcriteria['search'], $summary);
}

View File

@ -111,7 +111,6 @@ if ($grade = $DB->get_record('grade_grades', array('itemid' => $grade_item->id,
$grade->feedback = '';
} else {
$options = new stdClass();
$options->smiley = false;
$options->filter = false;
$options->noclean = false;
$options->para = false;

View File

@ -429,6 +429,9 @@ class behat_util extends testing_util {
core_courseformat\base::reset_course_cache(0);
get_fast_modinfo(0, 0, true);
// Reset the DI container.
\core\di::reset_container();
// Inform data generator.
self::get_data_generator()->reset();

View File

@ -117,12 +117,16 @@ class core_component {
'lib/psr/http-factory/src',
],
'Psr\\EventDispatcher' => 'lib/psr/event-dispatcher/src',
'Psr\\Container' => 'lib/psr/container/src',
'GuzzleHttp\\Psr7' => 'lib/guzzlehttp/psr7/src',
'GuzzleHttp\\Promise' => 'lib/guzzlehttp/promises/src',
'GuzzleHttp' => 'lib/guzzlehttp/guzzle/src',
'Kevinrob\\GuzzleCache' => 'lib/guzzlehttp/kevinrob/guzzlecache/src',
'Aws' => 'lib/aws-sdk/src',
'JmesPath' => 'lib/jmespath/src',
'Laravel\\SerializableClosure' => 'lib/laravel/serializable-closure/src',
'DI' => 'lib/php-di/php-di/src',
'Invoker' => 'lib/php-di/invoker/src',
];
/**

128
lib/classes/di.php Normal file
View File

@ -0,0 +1,128 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core;
use Psr\Container\ContainerInterface;
/**
* DI Container Helper.
*
* @package core
* @copyright 2023 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class di {
/** @var ContainerInterface The stored container */
protected static ?ContainerInterface $container;
/**
* Get the DI Container.
*
* @return ContainerInterface
*/
public static function get_container(): ContainerInterface {
if (!isset(self::$container)) {
self::$container = self::create_container();
}
return self::$container;
}
/**
* Reset the DI Container.
*
* This is primarily intended for Unit Testing, and for use in Scheduled tasks.
*/
public static function reset_container(): void {
self::$container = null;
}
/**
* Finds an entry of the container by its identifier and returns it.
*
* This is a shortcut helper for \core\di::get_container()->get($id).
*
* @param string $id Identifier of the entry to look for.
* @return mixed Entry.
*/
public static function get(string $id): mixed {
return self::get_container()->get($id);
}
/**
* Set an entry in the container by its identifier.
*
* @param string $id Identifier of the entry to set
* @param mixed $value The value to set
*/
public static function set(string $id, mixed $value): void {
// Please note that the `set` method is not a part of the PSR-11 standard.
// We currently make use of PHP-DI which does have this method, but its use is not guaranteed.
// If Moodle switches to alternative DI resolution, this method _must_ be updated to work with it.
/** @var \DI\Container */
$container = self::get_container();
$container->set($id, $value);
}
/**
* Create a new Container Instance.
*
* @return ContainerInterface
*/
protected static function create_container(): ContainerInterface {
global $CFG, $DB;
// PHP Does not support function autoloading. We must manually include the file.
require_once("{$CFG->libdir}/php-di/php-di/src/functions.php");
// Configure the Container builder.
$builder = new \DI\ContainerBuilder();
// At the moment we are using autowiring, but not automatic attribute injection.
// Automatic attribute injection is a php-di specific feature.
$builder->useAutowiring(true);
if (!$CFG->debugdeveloper) {
// Enable compilation of the container and write proxies to disk in production.
// See https://php-di.org/doc/performances.html for information.
$cachedir = make_localcache_directory('di');
$builder->enableCompilation($cachedir);
$builder->writeProxiesToFile(true, $cachedir);
}
// Get the hook manager.
$hookmanager = \core\hook\manager::get_instance();
// Configure some basic definitions.
$builder->addDefinitions([
// The hook manager should be in the container.
\core\hook\manager::class => $hookmanager,
// The database.
\moodle_database::class => $DB,
// The string manager.
\core_string_manager::class => fn() => get_string_manager(),
]);
// Add any additional definitions using hooks.
$hookmanager->dispatch(new \core\hook\di_configuration($builder));
// Build the container and return.
return $builder->build();
}
}

437
lib/classes/formatting.php Normal file
View File

@ -0,0 +1,437 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core;
/**
* Content formatting methods for Moodle.
*
* @package core
* @copyright 2023 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class formatting {
/** @var bool Whether to apply forceclean */
protected ?bool $forceclean;
/** @var bool Whether to apply striptags */
protected ?bool $striptags;
/** @var bool Whether to apply filters */
protected ?bool $filterall;
/** @var array A string cache for format_string */
protected $formatstringcache = [];
/**
* Given a simple string, this function returns the string
* processed by enabled string filters if $CFG->filterall is enabled
*
* This function should be used to print short strings (non html) that
* need filter processing e.g. activity titles, post subjects,
* glossary concepts.
*
* @param null|string $string The string to be filtered. Should be plain text, expect
* possibly for multilang tags.
* @param boolean $striplinks To strip any link in the result text.
* @param null|context $context The context used for formatting
* @param bool $filter Whether to apply filters
* @param bool $escape Whether to escape ampersands
* @return string
*/
public function format_string(
?string $string,
bool $striplinks = true,
?context $context = null,
bool $filter = true,
bool $escape = true,
): string {
global $PAGE;
if ($string === '' || is_null($string)) {
// No need to do any filters and cleaning.
return '';
}
if (!$this->should_filter_string()) {
return strip_tags($string);
}
if (count($this->formatstringcache) > 2000) {
// This number might need some tuning to limit memory usage in cron.
$this->formatstringcache = [];
}
if ($context === null) {
// Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
// In future we may want to add debugging here.
$context = $PAGE->context;
if (!$context) {
// We did not find any context? weird.
throw new \coding_exception(
'Unable to identify context for format_string()',
);
}
}
// Calculate md5.
$cachekeys = [
$string,
$striplinks,
$context->id,
$escape,
current_language(),
$filter,
];
$md5 = md5(implode('<+>', $cachekeys));
// Fetch from cache if possible.
if (array_key_exists($md5, $this->formatstringcache)) {
return $this->formatstringcache[$md5];
}
// First replace all ampersands not followed by html entity code
// Regular expression moved to its own method for easier unit testing.
if ($escape) {
$string = replace_ampersands_not_followed_by_entity($string);
}
if (!empty($this->get_filterall()) && $filter) {
$filtermanager = \filter_manager::instance();
$filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
$string = $filtermanager->filter_string($string, $context);
}
// If the site requires it, strip ALL tags from this string.
if (!empty($this->get_striptags())) {
if ($escape) {
$string = str_replace(['<', '>'], ['&lt;', '&gt;'], strip_tags($string));
} else {
$string = strip_tags($string);
}
} else {
// Otherwise strip just links if that is required (default).
if ($striplinks) {
// Strip links in string.
$string = strip_links($string);
}
$string = clean_text($string);
}
// Store to cache.
$this->formatstringcache[$md5] = $string;
return $string;
}
/**
* Given text in a variety of format codings, this function returns the text as safe HTML.
*
* This function should mainly be used for long strings like posts,
* answers, glossary items etc. For short strings {@link format_string()}.
*
* @param null|string $text The text to be formatted. This is raw text originally from user input.
* @param string $format Identifier of the text format to be used
* [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
* @param null|context $context The context used for filtering
* @param bool $trusted If true the string won't be cleaned.
* Note: FORMAT_MARKDOWN does not support trusted text.
* @param null|bool $clean If true the string will be cleaned.
* Note: This parameter is overridden if the text is trusted
* @param bool $filter If true the string will be run through applicable filters as well.
* @param bool $para If true then the returned string will be wrapped in div tags.
* @param bool $newlines If true then lines newline breaks will be converted to HTML newline breaks.
* @param bool $overflowdiv If set to true the formatted text will be encased in a div
* @param bool $blanktarget If true all <a> tags will have target="_blank" added unless target is explicitly specified.
* @param bool $allowid If true then id attributes will not be removed, even when using htmlpurifier.
* @return string
*/
public function format_text(
?string $text,
string $format = FORMAT_MOODLE,
?context $context = null,
bool $trusted = false,
?bool $clean = null,
bool $filter = true,
bool $para = true,
bool $newlines = true,
bool $overflowdiv = false,
bool $blanktarget = false,
bool $allowid = false,
): string {
global $CFG, $PAGE;
if ($text === '' || is_null($text)) {
// No need to do any filters and cleaning.
return '';
}
if ($format == FORMAT_MARKDOWN) {
// Markdown format cannot be trusted in trusttext areas,
// because we do not know how to sanitise it before editing.
$trusted = false;
}
if ($clean === null) {
if ($trusted && trusttext_active()) {
// No cleaning if text trusted and clean not specified.
$clean = false;
} else {
$clean = true;
}
}
if (!empty($this->get_forceclean())) {
// Whatever the caller claims, the admin wants all content cleaned anyway.
$clean = true;
}
// Calculate best context.
if (!$this->should_filter_string()) {
// Do not filter anything during installation or before upgrade completes.
$context = null;
} else if ($context === null) {
// Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages.
// In future we may want to add debugging here.
$context = $PAGE->context;
}
if (!$context) {
// Either install/upgrade or something has gone really wrong because context does not exist (yet?).
$filter = false;
}
if ($filter) {
$filtermanager = \filter_manager::instance();
$filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
$filteroptions = [
'originalformat' => $format,
'noclean' => !$clean,
];
} else {
$filtermanager = new \null_filter_manager();
$filteroptions = [];
}
switch ($format) {
case FORMAT_HTML:
$filteroptions['stage'] = 'pre_format';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
// Text is already in HTML format, so just continue to the next filtering stage.
$filteroptions['stage'] = 'pre_clean';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
if ($clean) {
$text = clean_text($text, FORMAT_HTML, [
'allowid' => $allowid,
]);
}
$filteroptions['stage'] = 'post_clean';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
break;
case FORMAT_PLAIN:
$text = s($text); // Cleans dangerous JS.
$text = rebuildnolinktag($text);
$text = str_replace(' ', '&nbsp; ', $text);
$text = nl2br($text);
break;
case FORMAT_MARKDOWN:
$filteroptions['stage'] = 'pre_format';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
$text = markdown_to_html($text);
$filteroptions['stage'] = 'pre_clean';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
if ($clean) {
$text = clean_text($text, FORMAT_HTML, [
'allowid' => $allowid,
]);
}
$filteroptions['stage'] = 'post_clean';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
break;
case FORMAT_MOODLE:
$filteroptions['stage'] = 'pre_format';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
$text = text_to_html($text, null, $para, $newlines);
$filteroptions['stage'] = 'pre_clean';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
if ($clean) {
$text = clean_text($text, FORMAT_HTML, [
'allowid' => $allowid,
]);
}
$filteroptions['stage'] = 'post_clean';
$text = $filtermanager->filter_text($text, $context, $filteroptions);
break;
default: // FORMAT_MOODLE or anything else.
throw new \coding_exception("Unkown format passed to format_text: {$format}");
}
if ($filter) {
// At this point there should not be any draftfile links any more,
// this happens when developers forget to post process the text.
// The only potential problem is that somebody might try to format
// the text before storing into database which would be itself big bug.
$text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
if ($CFG->debugdeveloper) {
if (strpos($text, '@@PLUGINFILE@@/') !== false) {
debugging(
'Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
DEBUG_DEVELOPER
);
}
}
}
if (!empty($overflowdiv)) {
$text = \html_writer::tag('div', $text, ['class' => 'no-overflow']);
}
if ($blanktarget) {
$domdoc = new \DOMDocument();
libxml_use_internal_errors(true);
$domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text);
libxml_clear_errors();
foreach ($domdoc->getElementsByTagName('a') as $link) {
if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) {
continue;
}
$link->setAttribute('target', '_blank');
if (strpos($link->getAttribute('rel'), 'noreferrer') === false) {
$link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer'));
}
}
// This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so:
// $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like some libxml
// versions don't work properly and end up leaving <html><body>, so I'm forced to use
// this regex to remove those tags as a preventive measure.
$text = trim(preg_replace(
'~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i',
'',
$domdoc->saveHTML($domdoc->documentElement),
));
}
return $text;
}
/**
* Set the value of the forceclean setting.
*
* @param bool $forceclean
* @return self
*/
public function set_forceclean(bool $forceclean): self {
$this->forceclean = $forceclean;
return $this;
}
/**
* Get the current forceclean value.
*
* @return bool
*/
public function get_forceclean(): bool {
global $CFG;
if (isset($this->forceclean)) {
return $this->forceclean;
}
if (isset($CFG->forceclean)) {
return $CFG->forceclean;
}
return false;
}
/**
* Set the value of the striptags setting.
*
* @param bool $striptags
* @return formatting
*/
public function set_striptags(bool $striptags): self {
$this->striptags = $striptags;
return $this;
}
/**
* Get the current striptags value.
*
* Reverts to CFG->formatstringstriptags if not set.
*
* @return bool
*/
public function get_striptags(): bool {
global $CFG;
if (isset($this->striptags)) {
return $this->striptags;
}
return $CFG->formatstringstriptags;
}
/**
* Set the value of the filterall setting.
*
* @param bool $filterall
* @return formatting
*/
public function set_filterall(bool $filterall): self {
$this->filterall = $filterall;
return $this;
}
/**
* Get the current filterall value.
*
* Reverts to CFG->filterall if not set.
*
* @return bool
*/
public function get_filterall(): bool {
global $CFG;
if (isset($this->filterall)) {
return $this->filterall;
}
return $CFG->filterall;
}
/**
* During initial install, or upgrade from a really old version of Moodle, we should not filter strings at all.
*
* @return bool
*/
protected function should_filter_string(): bool {
global $CFG;
if (empty($CFG->version) || $CFG->version < 2013051400 || during_initial_install()) {
// Do not filter anything during installation or before upgrade completes.
return false;
}
return true;
}
}

View File

@ -0,0 +1,89 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core\hook;
use DI\ContainerBuilder;
/**
* Allow for init-time configuration of the Dependency Injection container.
*
* @package core
* @copyright 2023 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class di_configuration implements described_hook {
/**
* Create the Dependency Injection configuration hook instance.
*
* @param ContainerBuilder $builder
*/
public function __construct(
protected ContainerBuilder $builder,
) {
}
/**
* Add a definition to the Dependency Injection container.
*
* A definition is a callable that returns an instance of the service.
*
* The callable can take arguments which are resolved using the DI container, for example a definition for the
* following example service requires \moodle_database, and \core\formatting which will be resolved using the DI
* container.
*
* <code>
* $hook->add_definition(
* id: \mod\example\service::class,
* definition: function (
* \moodle_database $db,
* \core\formatting $formatter,
* ): \mod\example\service {
* return new \mod\example\service(
* $database,
* $formatter,
* $some,
* $other,
* $args,
* )'
* },
* );
* </code>
*
* @param string $id The identifier of the container entry
* @param callable $definition The definition of the container entry
* @return self
* @example
*/
public function add_definition(
string $id,
callable $definition,
): self {
$this->builder->addDefinitions([
$id => $definition,
]);
return $this;
}
public static function get_hook_description(): string {
return 'The DI container, which allows plugins to register any service requiring configuration or initialisation.';
}
public static function get_hook_tags(): array {
return [];
}
}

View File

@ -86,7 +86,6 @@ class chooser_item implements renderable, templatable {
$options = new stdClass();
$options->trusted = false;
$options->noclean = false;
$options->smiley = false;
$options->filter = false;
$options->para = true;
$options->newlines = false;

View File

@ -55,13 +55,16 @@ function atto_equation_params_for_js($elementid, $options, $fpoptions) {
// Format a string with the active filter set.
// If it is modified - we assume that some sort of text filter is working in this context.
$result = format_text($texexample, true, $options);
$formatoptions = [
'context' => $options['context'],
'noclean' => $options['noclean'] ?? false,
'trusted' => $options['trusted'] ?? false,
];
$result = format_text($texexample, true, $formatoptions);
$texfilteractive = ($texexample !== $result);
$context = $options['context'];
if (!$context) {
$context = context_system::instance();
}
// Tex example librarys.
$library = array(

View File

@ -59,7 +59,11 @@ class plugininfo extends plugin implements plugin_with_buttons, plugin_with_menu
$texexample = '$$\pi$$';
// Format a string with the active filter set.
// If it is modified - we assume that some sort of text filter is working in this context.
$result = format_text($texexample, true, $options);
$formatoptions = [
'context' => $context,
];
$result = format_text($texexample, true, $formatoptions);
$texfilteractive = ($texexample !== $result);
if (isset($options['context'])) {

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Taylor Otwell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 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 SOFTWARE.

View File

@ -0,0 +1,73 @@
# Serializable Closure
<a href="https://github.com/laravel/serializable-closure/actions">
<img src="https://github.com/laravel/serializable-closure/workflows/tests/badge.svg" alt="Build Status">
</a>
<a href="https://packagist.org/packages/laravel/serializable-closure">
<img src="https://img.shields.io/packagist/dt/laravel/serializable-closure" alt="Total Downloads">
</a>
<a href="https://packagist.org/packages/laravel/serializable-closure">
<img src="https://img.shields.io/packagist/v/laravel/serializable-closure" alt="Latest Stable Version">
</a>
<a href="https://packagist.org/packages/laravel/serializable-closure">
<img src="https://img.shields.io/packagist/l/laravel/serializable-closure" alt="License">
</a>
## Introduction
> This project is a fork of the excellent [opis/closure: 3.x](https://github.com/opis/closure) package. At Laravel, we decided to fork this package as the upcoming version [4.x](https://github.com/opis/closure) is a complete rewrite on top of the [FFI extension](https://www.php.net/manual/en/book.ffi.php). As Laravel is a web framework, and FFI is not enabled by default in web requests, this fork allows us to keep using the `3.x` series while adding support for new PHP versions.
Laravel Serializable Closure provides an easy and secure way to **serialize closures in PHP**.
## Official Documentation
### Installation
> **Requires [PHP 7.4+](https://php.net/releases/)**
First, install Laravel Serializable Closure via the [Composer](https://getcomposer.org/) package manager:
```bash
composer require laravel/serializable-closure
```
### Usage
You may serialize a closure this way:
```php
use Laravel\SerializableClosure\SerializableClosure;
$closure = fn () => 'james';
// Recommended
SerializableClosure::setSecretKey('secret');
$serialized = serialize(new SerializableClosure($closure));
$closure = unserialize($serialized)->getClosure();
echo $closure(); // james;
```
### Caveats
* Anonymous classes cannot be created within closures.
* Attributes cannot be used within closures.
* Serializing closures on REPL environments like Laravel Tinker is not supported.
* Serializing closures that reference objects with readonly properties is not supported.
## Contributing
Thank you for considering contributing to Serializable Closure! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
Please review [our security policy](https://github.com/laravel/serializable-closure/security/policy) on how to report security vulnerabilities.
## License
Serializable Closure is open-sourced software licensed under the [MIT license](LICENSE.md).

View File

@ -0,0 +1,52 @@
{
"name": "laravel/serializable-closure",
"description": "Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.",
"keywords": ["laravel", "Serializable", "closure"],
"license": "MIT",
"support": {
"issues": "https://github.com/laravel/serializable-closure/issues",
"source": "https://github.com/laravel/serializable-closure"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
},
{
"name": "Nuno Maduro",
"email": "nuno@laravel.com"
}
],
"require": {
"php": "^7.3|^8.0"
},
"require-dev": {
"nesbot/carbon": "^2.61",
"pestphp/pest": "^1.21.3",
"phpstan/phpstan": "^1.8.2",
"symfony/var-dumper": "^5.4.11"
},
"autoload": {
"psr-4": {
"Laravel\\SerializableClosure\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"config": {
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"minimum-stability": "dev",
"prefer-stable": true
}

View File

@ -0,0 +1,3 @@
Please note that this library is required for use of PHP-DI.
Please update it in accordance with PHP-DI and see lib/php-di/readme_moodle.md for more information.

View File

@ -0,0 +1,20 @@
<?php
namespace Laravel\SerializableClosure\Contracts;
interface Serializable
{
/**
* Resolve the closure with the given arguments.
*
* @return mixed
*/
public function __invoke();
/**
* Gets the closure that got serialized/unserialized.
*
* @return \Closure
*/
public function getClosure();
}

View File

@ -0,0 +1,22 @@
<?php
namespace Laravel\SerializableClosure\Contracts;
interface Signer
{
/**
* Sign the given serializable.
*
* @param string $serializable
* @return array
*/
public function sign($serializable);
/**
* Verify the given signature.
*
* @param array $signature
* @return bool
*/
public function verify($signature);
}

View File

@ -0,0 +1,19 @@
<?php
namespace Laravel\SerializableClosure\Exceptions;
use Exception;
class InvalidSignatureException extends Exception
{
/**
* Create a new exception instance.
*
* @param string $message
* @return void
*/
public function __construct($message = 'Your serialized closure might have been modified or it\'s unsafe to be unserialized.')
{
parent::__construct($message);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Laravel\SerializableClosure\Exceptions;
use Exception;
class MissingSecretKeyException extends Exception
{
/**
* Create a new exception instance.
*
* @param string $message
* @return void
*/
public function __construct($message = 'No serializable closure secret key has been specified.')
{
parent::__construct($message);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Laravel\SerializableClosure\Exceptions;
use Exception;
class PhpVersionNotSupportedException extends Exception
{
/**
* Create a new exception instance.
*
* @param string $message
* @return void
*/
public function __construct($message = 'PHP 7.3 is not supported.')
{
parent::__construct($message);
}
}

View File

@ -0,0 +1,139 @@
<?php
namespace Laravel\SerializableClosure;
use Closure;
use Laravel\SerializableClosure\Exceptions\InvalidSignatureException;
use Laravel\SerializableClosure\Exceptions\PhpVersionNotSupportedException;
use Laravel\SerializableClosure\Serializers\Signed;
use Laravel\SerializableClosure\Signers\Hmac;
class SerializableClosure
{
/**
* The closure's serializable.
*
* @var \Laravel\SerializableClosure\Contracts\Serializable
*/
protected $serializable;
/**
* Creates a new serializable closure instance.
*
* @param \Closure $closure
* @return void
*/
public function __construct(Closure $closure)
{
if (\PHP_VERSION_ID < 70400) {
throw new PhpVersionNotSupportedException();
}
$this->serializable = Serializers\Signed::$signer
? new Serializers\Signed($closure)
: new Serializers\Native($closure);
}
/**
* Resolve the closure with the given arguments.
*
* @return mixed
*/
public function __invoke()
{
if (\PHP_VERSION_ID < 70400) {
throw new PhpVersionNotSupportedException();
}
return call_user_func_array($this->serializable, func_get_args());
}
/**
* Gets the closure.
*
* @return \Closure
*/
public function getClosure()
{
if (\PHP_VERSION_ID < 70400) {
throw new PhpVersionNotSupportedException();
}
return $this->serializable->getClosure();
}
/**
* Create a new unsigned serializable closure instance.
*
* @param Closure $closure
* @return \Laravel\SerializableClosure\UnsignedSerializableClosure
*/
public static function unsigned(Closure $closure)
{
return new UnsignedSerializableClosure($closure);
}
/**
* Sets the serializable closure secret key.
*
* @param string|null $secret
* @return void
*/
public static function setSecretKey($secret)
{
Serializers\Signed::$signer = $secret
? new Hmac($secret)
: null;
}
/**
* Sets the serializable closure secret key.
*
* @param \Closure|null $transformer
* @return void
*/
public static function transformUseVariablesUsing($transformer)
{
Serializers\Native::$transformUseVariables = $transformer;
}
/**
* Sets the serializable closure secret key.
*
* @param \Closure|null $resolver
* @return void
*/
public static function resolveUseVariablesUsing($resolver)
{
Serializers\Native::$resolveUseVariables = $resolver;
}
/**
* Get the serializable representation of the closure.
*
* @return array
*/
public function __serialize()
{
return [
'serializable' => $this->serializable,
];
}
/**
* Restore the closure after serialization.
*
* @param array $data
* @return void
*
* @throws \Laravel\SerializableClosure\Exceptions\InvalidSignatureException
*/
public function __unserialize($data)
{
if (Signed::$signer && ! $data['serializable'] instanceof Signed) {
throw new InvalidSignatureException();
}
$this->serializable = $data['serializable'];
}
}

View File

@ -0,0 +1,514 @@
<?php
namespace Laravel\SerializableClosure\Serializers;
use Closure;
use DateTimeInterface;
use Laravel\SerializableClosure\Contracts\Serializable;
use Laravel\SerializableClosure\SerializableClosure;
use Laravel\SerializableClosure\Support\ClosureScope;
use Laravel\SerializableClosure\Support\ClosureStream;
use Laravel\SerializableClosure\Support\ReflectionClosure;
use Laravel\SerializableClosure\Support\SelfReference;
use Laravel\SerializableClosure\UnsignedSerializableClosure;
use ReflectionObject;
use UnitEnum;
class Native implements Serializable
{
/**
* Transform the use variables before serialization.
*
* @var \Closure|null
*/
public static $transformUseVariables;
/**
* Resolve the use variables after unserialization.
*
* @var \Closure|null
*/
public static $resolveUseVariables;
/**
* The closure to be serialized/unserialized.
*
* @var \Closure
*/
protected $closure;
/**
* The closure's reflection.
*
* @var \Laravel\SerializableClosure\Support\ReflectionClosure|null
*/
protected $reflector;
/**
* The closure's code.
*
* @var array|null
*/
protected $code;
/**
* The closure's reference.
*
* @var string
*/
protected $reference;
/**
* The closure's scope.
*
* @var \Laravel\SerializableClosure\Support\ClosureScope|null
*/
protected $scope;
/**
* The "key" that marks an array as recursive.
*/
const ARRAY_RECURSIVE_KEY = 'LARAVEL_SERIALIZABLE_RECURSIVE_KEY';
/**
* Creates a new serializable closure instance.
*
* @param \Closure $closure
* @return void
*/
public function __construct(Closure $closure)
{
$this->closure = $closure;
}
/**
* Resolve the closure with the given arguments.
*
* @return mixed
*/
public function __invoke()
{
return call_user_func_array($this->closure, func_get_args());
}
/**
* Gets the closure.
*
* @return \Closure
*/
public function getClosure()
{
return $this->closure;
}
/**
* Get the serializable representation of the closure.
*
* @return array
*/
public function __serialize()
{
if ($this->scope === null) {
$this->scope = new ClosureScope();
$this->scope->toSerialize++;
}
$this->scope->serializations++;
$scope = $object = null;
$reflector = $this->getReflector();
if ($reflector->isBindingRequired()) {
$object = $reflector->getClosureThis();
static::wrapClosures($object, $this->scope);
}
if ($scope = $reflector->getClosureScopeClass()) {
$scope = $scope->name;
}
$this->reference = spl_object_hash($this->closure);
$this->scope[$this->closure] = $this;
$use = $reflector->getUseVariables();
if (static::$transformUseVariables) {
$use = call_user_func(static::$transformUseVariables, $reflector->getUseVariables());
}
$code = $reflector->getCode();
$this->mapByReference($use);
$data = [
'use' => $use,
'function' => $code,
'scope' => $scope,
'this' => $object,
'self' => $this->reference,
];
if (! --$this->scope->serializations && ! --$this->scope->toSerialize) {
$this->scope = null;
}
return $data;
}
/**
* Restore the closure after serialization.
*
* @param array $data
* @return void
*/
public function __unserialize($data)
{
ClosureStream::register();
$this->code = $data;
unset($data);
$this->code['objects'] = [];
if ($this->code['use']) {
$this->scope = new ClosureScope();
if (static::$resolveUseVariables) {
$this->code['use'] = call_user_func(static::$resolveUseVariables, $this->code['use']);
}
$this->mapPointers($this->code['use']);
extract($this->code['use'], EXTR_OVERWRITE | EXTR_REFS);
$this->scope = null;
}
$this->closure = include ClosureStream::STREAM_PROTO.'://'.$this->code['function'];
if ($this->code['this'] === $this) {
$this->code['this'] = null;
}
$this->closure = $this->closure->bindTo($this->code['this'], $this->code['scope']);
if (! empty($this->code['objects'])) {
foreach ($this->code['objects'] as $item) {
$item['property']->setValue($item['instance'], $item['object']->getClosure());
}
}
$this->code = $this->code['function'];
}
/**
* Ensures the given closures are serializable.
*
* @param mixed $data
* @param \Laravel\SerializableClosure\Support\ClosureScope $storage
* @return void
*/
public static function wrapClosures(&$data, $storage)
{
if ($data instanceof Closure) {
$data = new static($data);
} elseif (is_array($data)) {
if (isset($data[self::ARRAY_RECURSIVE_KEY])) {
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value) {
if ($key === self::ARRAY_RECURSIVE_KEY) {
continue;
}
static::wrapClosures($value, $storage);
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif ($data instanceof \stdClass) {
if (isset($storage[$data])) {
$data = $storage[$data];
return;
}
$data = $storage[$data] = clone $data;
foreach ($data as &$value) {
static::wrapClosures($value, $storage);
}
unset($value);
} elseif (is_object($data) && ! $data instanceof static && ! $data instanceof UnitEnum) {
if (isset($storage[$data])) {
$data = $storage[$data];
return;
}
$instance = $data;
$reflection = new ReflectionObject($instance);
if (! $reflection->isUserDefined()) {
$storage[$instance] = $data;
return;
}
$storage[$instance] = $data = $reflection->newInstanceWithoutConstructor();
do {
if (! $reflection->isUserDefined()) {
break;
}
foreach ($reflection->getProperties() as $property) {
if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) {
continue;
}
$property->setAccessible(true);
if (PHP_VERSION >= 7.4 && ! $property->isInitialized($instance)) {
continue;
}
$value = $property->getValue($instance);
if (is_array($value) || is_object($value)) {
static::wrapClosures($value, $storage);
}
$property->setValue($data, $value);
}
} while ($reflection = $reflection->getParentClass());
}
}
/**
* Gets the closure's reflector.
*
* @return \Laravel\SerializableClosure\Support\ReflectionClosure
*/
public function getReflector()
{
if ($this->reflector === null) {
$this->code = null;
$this->reflector = new ReflectionClosure($this->closure);
}
return $this->reflector;
}
/**
* Internal method used to map closure pointers.
*
* @param mixed $data
* @return void
*/
protected function mapPointers(&$data)
{
$scope = $this->scope;
if ($data instanceof static) {
$data = &$data->closure;
} elseif (is_array($data)) {
if (isset($data[self::ARRAY_RECURSIVE_KEY])) {
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value) {
if ($key === self::ARRAY_RECURSIVE_KEY) {
continue;
} elseif ($value instanceof static) {
$data[$key] = &$value->closure;
} elseif ($value instanceof SelfReference && $value->hash === $this->code['self']) {
$data[$key] = &$this->closure;
} else {
$this->mapPointers($value);
}
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif ($data instanceof \stdClass) {
if (isset($scope[$data])) {
return;
}
$scope[$data] = true;
foreach ($data as $key => &$value) {
if ($value instanceof SelfReference && $value->hash === $this->code['self']) {
$data->{$key} = &$this->closure;
} elseif (is_array($value) || is_object($value)) {
$this->mapPointers($value);
}
}
unset($value);
} elseif (is_object($data) && ! ($data instanceof Closure)) {
if (isset($scope[$data])) {
return;
}
$scope[$data] = true;
$reflection = new ReflectionObject($data);
do {
if (! $reflection->isUserDefined()) {
break;
}
foreach ($reflection->getProperties() as $property) {
if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) {
continue;
}
$property->setAccessible(true);
if (PHP_VERSION >= 7.4 && ! $property->isInitialized($data)) {
continue;
}
$item = $property->getValue($data);
if ($item instanceof SerializableClosure || $item instanceof UnsignedSerializableClosure || ($item instanceof SelfReference && $item->hash === $this->code['self'])) {
$this->code['objects'][] = [
'instance' => $data,
'property' => $property,
'object' => $item instanceof SelfReference ? $this : $item,
];
} elseif (is_array($item) || is_object($item)) {
$this->mapPointers($item);
$property->setValue($data, $item);
}
}
} while ($reflection = $reflection->getParentClass());
}
}
/**
* Internal method used to map closures by reference.
*
* @param mixed $data
* @return void
*/
protected function mapByReference(&$data)
{
if ($data instanceof Closure) {
if ($data === $this->closure) {
$data = new SelfReference($this->reference);
return;
}
if (isset($this->scope[$data])) {
$data = $this->scope[$data];
return;
}
$instance = new static($data);
$instance->scope = $this->scope;
$data = $this->scope[$data] = $instance;
} elseif (is_array($data)) {
if (isset($data[self::ARRAY_RECURSIVE_KEY])) {
return;
}
$data[self::ARRAY_RECURSIVE_KEY] = true;
foreach ($data as $key => &$value) {
if ($key === self::ARRAY_RECURSIVE_KEY) {
continue;
}
$this->mapByReference($value);
}
unset($value);
unset($data[self::ARRAY_RECURSIVE_KEY]);
} elseif ($data instanceof \stdClass) {
if (isset($this->scope[$data])) {
$data = $this->scope[$data];
return;
}
$instance = $data;
$this->scope[$instance] = $data = clone $data;
foreach ($data as &$value) {
$this->mapByReference($value);
}
unset($value);
} elseif (is_object($data) && ! $data instanceof SerializableClosure && ! $data instanceof UnsignedSerializableClosure) {
if (isset($this->scope[$data])) {
$data = $this->scope[$data];
return;
}
$instance = $data;
if ($data instanceof DateTimeInterface) {
$this->scope[$instance] = $data;
return;
}
if ($data instanceof UnitEnum) {
$this->scope[$instance] = $data;
return;
}
$reflection = new ReflectionObject($data);
if (! $reflection->isUserDefined()) {
$this->scope[$instance] = $data;
return;
}
$this->scope[$instance] = $data = $reflection->newInstanceWithoutConstructor();
do {
if (! $reflection->isUserDefined()) {
break;
}
foreach ($reflection->getProperties() as $property) {
if ($property->isStatic() || ! $property->getDeclaringClass()->isUserDefined()) {
continue;
}
$property->setAccessible(true);
if (PHP_VERSION >= 7.4 && ! $property->isInitialized($instance)) {
continue;
}
$value = $property->getValue($instance);
if (is_array($value) || is_object($value)) {
$this->mapByReference($value);
}
$property->setValue($data, $value);
}
} while ($reflection = $reflection->getParentClass());
}
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace Laravel\SerializableClosure\Serializers;
use Laravel\SerializableClosure\Contracts\Serializable;
use Laravel\SerializableClosure\Exceptions\InvalidSignatureException;
use Laravel\SerializableClosure\Exceptions\MissingSecretKeyException;
class Signed implements Serializable
{
/**
* The signer that will sign and verify the closure's signature.
*
* @var \Laravel\SerializableClosure\Contracts\Signer|null
*/
public static $signer;
/**
* The closure to be serialized/unserialized.
*
* @var \Closure
*/
protected $closure;
/**
* Creates a new serializable closure instance.
*
* @param \Closure $closure
* @return void
*/
public function __construct($closure)
{
$this->closure = $closure;
}
/**
* Resolve the closure with the given arguments.
*
* @return mixed
*/
public function __invoke()
{
return call_user_func_array($this->closure, func_get_args());
}
/**
* Gets the closure.
*
* @return \Closure
*/
public function getClosure()
{
return $this->closure;
}
/**
* Get the serializable representation of the closure.
*
* @return array
*/
public function __serialize()
{
if (! static::$signer) {
throw new MissingSecretKeyException();
}
return static::$signer->sign(
serialize(new Native($this->closure))
);
}
/**
* Restore the closure after serialization.
*
* @param array $signature
* @return void
*
* @throws \Laravel\SerializableClosure\Exceptions\InvalidSignatureException
*/
public function __unserialize($signature)
{
if (static::$signer && ! static::$signer->verify($signature)) {
throw new InvalidSignatureException();
}
/** @var \Laravel\SerializableClosure\Contracts\Serializable $serializable */
$serializable = unserialize($signature['serializable']);
$this->closure = $serializable->getClosure();
}
}

View File

@ -0,0 +1,53 @@
<?php
namespace Laravel\SerializableClosure\Signers;
use Laravel\SerializableClosure\Contracts\Signer;
class Hmac implements Signer
{
/**
* The secret key.
*
* @var string
*/
protected $secret;
/**
* Creates a new signer instance.
*
* @param string $secret
* @return void
*/
public function __construct($secret)
{
$this->secret = $secret;
}
/**
* Sign the given serializable.
*
* @param string $serialized
* @return array
*/
public function sign($serialized)
{
return [
'serializable' => $serialized,
'hash' => base64_encode(hash_hmac('sha256', $serialized, $this->secret, true)),
];
}
/**
* Verify the given signature.
*
* @param array $signature
* @return bool
*/
public function verify($signature)
{
return hash_equals(base64_encode(
hash_hmac('sha256', $signature['serializable'], $this->secret, true)
), $signature['hash']);
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace Laravel\SerializableClosure\Support;
use SplObjectStorage;
class ClosureScope extends SplObjectStorage
{
/**
* The number of serializations in current scope.
*
* @var int
*/
public $serializations = 0;
/**
* The number of closures that have to be serialized.
*
* @var int
*/
public $toSerialize = 0;
}

View File

@ -0,0 +1,179 @@
<?php
namespace Laravel\SerializableClosure\Support;
#[\AllowDynamicProperties]
class ClosureStream
{
/**
* The stream protocol.
*/
const STREAM_PROTO = 'laravel-serializable-closure';
/**
* Checks if this stream is registered.
*
* @var bool
*/
protected static $isRegistered = false;
/**
* The stream content.
*
* @var string
*/
protected $content;
/**
* The stream content.
*
* @var int
*/
protected $length;
/**
* The stream pointer.
*
* @var int
*/
protected $pointer = 0;
/**
* Opens file or URL.
*
* @param string $path
* @param string $mode
* @param string $options
* @param string|null $opened_path
* @return bool
*/
public function stream_open($path, $mode, $options, &$opened_path)
{
$this->content = "<?php\nreturn ".substr($path, strlen(static::STREAM_PROTO.'://')).';';
$this->length = strlen($this->content);
return true;
}
/**
* Read from stream.
*
* @param int $count
* @return string
*/
public function stream_read($count)
{
$value = substr($this->content, $this->pointer, $count);
$this->pointer += $count;
return $value;
}
/**
* Tests for end-of-file on a file pointer.
*
* @return bool
*/
public function stream_eof()
{
return $this->pointer >= $this->length;
}
/**
* Change stream options.
*
* @param int $option
* @param int $arg1
* @param int $arg2
* @return bool
*/
public function stream_set_option($option, $arg1, $arg2)
{
return false;
}
/**
* Retrieve information about a file resource.
*
* @return array|bool
*/
public function stream_stat()
{
$stat = stat(__FILE__);
// @phpstan-ignore-next-line
$stat[7] = $stat['size'] = $this->length;
return $stat;
}
/**
* Retrieve information about a file.
*
* @param string $path
* @param int $flags
* @return array|bool
*/
public function url_stat($path, $flags)
{
$stat = stat(__FILE__);
// @phpstan-ignore-next-line
$stat[7] = $stat['size'] = $this->length;
return $stat;
}
/**
* Seeks to specific location in a stream.
*
* @param int $offset
* @param int $whence
* @return bool
*/
public function stream_seek($offset, $whence = SEEK_SET)
{
$crt = $this->pointer;
switch ($whence) {
case SEEK_SET:
$this->pointer = $offset;
break;
case SEEK_CUR:
$this->pointer += $offset;
break;
case SEEK_END:
$this->pointer = $this->length + $offset;
break;
}
if ($this->pointer < 0 || $this->pointer >= $this->length) {
$this->pointer = $crt;
return false;
}
return true;
}
/**
* Retrieve the current position of a stream.
*
* @return int
*/
public function stream_tell()
{
return $this->pointer;
}
/**
* Registers the stream.
*
* @return void
*/
public static function register()
{
if (! static::$isRegistered) {
static::$isRegistered = stream_wrapper_register(static::STREAM_PROTO, __CLASS__);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,24 @@
<?php
namespace Laravel\SerializableClosure\Support;
class SelfReference
{
/**
* The unique hash representing the object.
*
* @var string
*/
public $hash;
/**
* Creates a new self reference instance.
*
* @param string $hash
* @return void
*/
public function __construct($hash)
{
$this->hash = $hash;
}
}

View File

@ -0,0 +1,82 @@
<?php
namespace Laravel\SerializableClosure;
use Closure;
use Laravel\SerializableClosure\Exceptions\PhpVersionNotSupportedException;
class UnsignedSerializableClosure
{
/**
* The closure's serializable.
*
* @var \Laravel\SerializableClosure\Contracts\Serializable
*/
protected $serializable;
/**
* Creates a new serializable closure instance.
*
* @param \Closure $closure
* @return void
*/
public function __construct(Closure $closure)
{
if (\PHP_VERSION_ID < 70400) {
throw new PhpVersionNotSupportedException();
}
$this->serializable = new Serializers\Native($closure);
}
/**
* Resolve the closure with the given arguments.
*
* @return mixed
*/
public function __invoke()
{
if (\PHP_VERSION_ID < 70400) {
throw new PhpVersionNotSupportedException();
}
return call_user_func_array($this->serializable, func_get_args());
}
/**
* Gets the closure.
*
* @return \Closure
*/
public function getClosure()
{
if (\PHP_VERSION_ID < 70400) {
throw new PhpVersionNotSupportedException();
}
return $this->serializable->getClosure();
}
/**
* Get the serializable representation of the closure.
*
* @return array
*/
public function __serialize()
{
return [
'serializable' => $this->serializable,
];
}
/**
* Restore the closure after serialization.
*
* @param array $data
* @return void
*/
public function __unserialize($data)
{
$this->serializable = $data['serializable'];
}
}

View File

@ -0,0 +1,15 @@
# Contributing
First of all, **thank you** for contributing!
Here are a few rules to follow in order to ease code reviews and merging:
- follow [PSR-1](http://www.php-fig.org/psr/1/) and [PSR-2](http://www.php-fig.org/psr/2/)
- run the test suite
- write (or update) unit tests when applicable
- write documentation for new features
- use [commit messages that make sense](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
One may ask you to [squash your commits](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html) too. This is used to "clean" your pull request before merging it (we don't want commits such as `fix tests`, `fix 2`, `fix 3`, etc.).
When creating your pull request on GitHub, please write a description which gives the context and/or explains why you are creating it.

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Matthieu Napoli
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 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 SOFTWARE.

View File

@ -0,0 +1,233 @@
# Invoker
Generic and extensible callable invoker.
[![CI](https://github.com/PHP-DI/Invoker/actions/workflows/ci.yml/badge.svg)](https://github.com/PHP-DI/Invoker/actions/workflows/ci.yml)
[![Latest Version](https://img.shields.io/github/release/PHP-DI/invoker.svg?style=flat-square)](https://packagist.org/packages/PHP-DI/invoker)
[![Total Downloads](https://img.shields.io/packagist/dt/php-di/invoker.svg?style=flat-square)](https://packagist.org/packages/php-di/invoker)
## Why?
Who doesn't need an over-engineered `call_user_func()`?
### Named parameters
Does this [Silex](https://github.com/silexphp/Silex#readme) example look familiar:
```php
$app->get('/project/{project}/issue/{issue}', function ($project, $issue) {
// ...
});
```
Or this command defined with [Silly](https://github.com/mnapoli/silly#usage):
```php
$app->command('greet [name] [--yell]', function ($name, $yell) {
// ...
});
```
Same pattern in [Slim](https://www.slimframework.com):
```php
$app->get('/hello/:name', function ($name) {
// ...
});
```
You get the point. These frameworks invoke the controller/command/handler using something akin to named parameters: whatever the order of the parameters, they are matched by their name.
**This library allows to invoke callables with named parameters in a generic and extensible way.**
### Dependency injection
Anyone familiar with AngularJS is familiar with how dependency injection is performed:
```js
angular.controller('MyController', ['dep1', 'dep2', function(dep1, dep2) {
// ...
}]);
```
In PHP we find this pattern again in some frameworks and DI containers with partial to full support. For example in Silex you can type-hint the application to get it injected, but it only works with `Silex\Application`:
```php
$app->get('/hello/{name}', function (Silex\Application $app, $name) {
// ...
});
```
In Silly, it only works with `OutputInterface` to inject the application output:
```php
$app->command('greet [name]', function ($name, OutputInterface $output) {
// ...
});
```
[PHP-DI](https://php-di.org/doc/container.html) provides a way to invoke a callable and resolve all dependencies from the container using type-hints:
```php
$container->call(function (Logger $logger, EntityManager $em) {
// ...
});
```
**This library provides clear extension points to let frameworks implement any kind of dependency injection support they want.**
### TL/DR
In short, this library is meant to be a base building block for calling a function with named parameters and/or dependency injection.
## Installation
```sh
$ composer require PHP-DI/invoker
```
## Usage
### Default behavior
By default the `Invoker` can call using named parameters:
```php
$invoker = new Invoker\Invoker;
$invoker->call(function () {
echo 'Hello world!';
});
// Simple parameter array
$invoker->call(function ($name) {
echo 'Hello ' . $name;
}, ['John']);
// Named parameters
$invoker->call(function ($name) {
echo 'Hello ' . $name;
}, [
'name' => 'John'
]);
// Use the default value
$invoker->call(function ($name = 'world') {
echo 'Hello ' . $name;
});
// Invoke any PHP callable
$invoker->call(['MyClass', 'myStaticMethod']);
// Using Class::method syntax
$invoker->call('MyClass::myStaticMethod');
```
Dependency injection in parameters is supported but needs to be configured with your container. Read on or jump to [*Built-in support for dependency injection*](#built-in-support-for-dependency-injection) if you are impatient.
Additionally, callables can also be resolved from your container. Read on or jump to [*Resolving callables from a container*](#resolving-callables-from-a-container) if you are impatient.
### Parameter resolvers
Extending the behavior of the `Invoker` is easy and is done by implementing a [`ParameterResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/ParameterResolver.php).
This is explained in details the [Parameter resolvers documentation](doc/parameter-resolvers.md).
#### Built-in support for dependency injection
Rather than have you re-implement support for dependency injection with different containers every time, this package ships with 2 optional resolvers:
- [`TypeHintContainerResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/Container/TypeHintContainerResolver.php)
This resolver will inject container entries by searching for the class name using the type-hint:
```php
$invoker->call(function (Psr\Logger\LoggerInterface $logger) {
// ...
});
```
In this example it will `->get('Psr\Logger\LoggerInterface')` from the container and inject it.
This resolver is only useful if you store objects in your container using the class (or interface) name. Silex or Symfony for example store services under a custom name (e.g. `twig`, `db`, etc.) instead of the class name: in that case use the resolver shown below.
- [`ParameterNameContainerResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/Container/ParameterNameContainerResolver.php)
This resolver will inject container entries by searching for the name of the parameter:
```php
$invoker->call(function ($twig) {
// ...
});
```
In this example it will `->get('twig')` from the container and inject it.
These resolvers can work with any dependency injection container compliant with [PSR-11](http://www.php-fig.org/psr/psr-11/).
Setting up those resolvers is simple:
```php
// $container must be an instance of Psr\Container\ContainerInterface
$container = ...
$containerResolver = new TypeHintContainerResolver($container);
// or
$containerResolver = new ParameterNameContainerResolver($container);
$invoker = new Invoker\Invoker;
// Register it before all the other parameter resolvers
$invoker->getParameterResolver()->prependResolver($containerResolver);
```
You can also register both resolvers at the same time if you wish by prepending both. Implementing support for more tricky things is easy and up to you!
### Resolving callables from a container
The `Invoker` can be wired to your DI container to resolve the callables.
For example with an invokable class:
```php
class MyHandler
{
public function __invoke()
{
// ...
}
}
// By default this doesn't work: an instance of the class should be provided
$invoker->call('MyHandler');
// If we set up the container to use
$invoker = new Invoker\Invoker(null, $container);
// Now 'MyHandler' is resolved using the container!
$invoker->call('MyHandler');
```
The same works for a class method:
```php
class WelcomeController
{
public function home()
{
// ...
}
}
// By default this doesn't work: home() is not a static method
$invoker->call(['WelcomeController', 'home']);
// If we set up the container to use
$invoker = new Invoker\Invoker(null, $container);
// Now 'WelcomeController' is resolved using the container!
$invoker->call(['WelcomeController', 'home']);
// Alternatively we can use the Class::method syntax
$invoker->call('WelcomeController::home');
```
That feature can be used as the base building block for a framework's dispatcher.
Again, any [PSR-11](https://www.php-fig.org/psr/psr-11/) compliant container can be provided.

View File

@ -0,0 +1,27 @@
{
"name": "php-di/invoker",
"description": "Generic and extensible callable invoker",
"keywords": ["invoker", "dependency-injection", "dependency", "injection", "callable", "invoke"],
"homepage": "https://github.com/PHP-DI/Invoker",
"license": "MIT",
"type": "library",
"autoload": {
"psr-4": {
"Invoker\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Invoker\\Test\\": "tests/"
}
},
"require": {
"php": ">=7.3",
"psr/container": "^1.0|^2.0"
},
"require-dev": {
"phpunit/phpunit": "^9.0",
"athletic/athletic": "~0.1.8",
"mnapoli/hard-mode": "~0.3.0"
}
}

View File

@ -0,0 +1,3 @@
Please note that this library is required for use of PHP-DI.
Please update it in accordance with PHP-DI and see lib/php-di/readme_moodle.md for more information.

View File

@ -0,0 +1,124 @@
<?php declare(strict_types=1);
namespace Invoker;
use Closure;
use Invoker\Exception\NotCallableException;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use ReflectionException;
use ReflectionMethod;
/**
* Resolves a callable from a container.
*/
class CallableResolver
{
/** @var ContainerInterface */
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Resolve the given callable into a real PHP callable.
*
* @param callable|string|array $callable
* @return callable Real PHP callable.
* @throws NotCallableException|ReflectionException
*/
public function resolve($callable): callable
{
if (is_string($callable) && strpos($callable, '::') !== false) {
$callable = explode('::', $callable, 2);
}
$callable = $this->resolveFromContainer($callable);
if (! is_callable($callable)) {
throw NotCallableException::fromInvalidCallable($callable, true);
}
return $callable;
}
/**
* @param callable|string|array $callable
* @return callable|mixed
* @throws NotCallableException|ReflectionException
*/
private function resolveFromContainer($callable)
{
// Shortcut for a very common use case
if ($callable instanceof Closure) {
return $callable;
}
// If it's already a callable there is nothing to do
if (is_callable($callable)) {
// TODO with PHP 8 that should not be necessary to check this anymore
if (! $this->isStaticCallToNonStaticMethod($callable)) {
return $callable;
}
}
// The callable is a container entry name
if (is_string($callable)) {
try {
return $this->container->get($callable);
} catch (NotFoundExceptionInterface $e) {
if ($this->container->has($callable)) {
throw $e;
}
throw NotCallableException::fromInvalidCallable($callable, true);
}
}
// The callable is an array whose first item is a container entry name
// e.g. ['some-container-entry', 'methodToCall']
if (is_array($callable) && is_string($callable[0])) {
try {
// Replace the container entry name by the actual object
$callable[0] = $this->container->get($callable[0]);
return $callable;
} catch (NotFoundExceptionInterface $e) {
if ($this->container->has($callable[0])) {
throw $e;
}
throw new NotCallableException(sprintf(
'Cannot call %s() on %s because it is not a class nor a valid container entry',
$callable[1],
$callable[0]
));
}
}
// Unrecognized stuff, we let it fail later
return $callable;
}
/**
* Check if the callable represents a static call to a non-static method.
*
* @param mixed $callable
* @throws ReflectionException
*/
private function isStaticCallToNonStaticMethod($callable): bool
{
if (is_array($callable) && is_string($callable[0])) {
[$class, $method] = $callable;
if (! method_exists($class, $method)) {
return false;
}
$reflection = new ReflectionMethod($class, $method);
return ! $reflection->isStatic();
}
return false;
}
}

View File

@ -0,0 +1,10 @@
<?php declare(strict_types=1);
namespace Invoker\Exception;
/**
* Impossible to invoke the callable.
*/
class InvocationException extends \Exception
{
}

View File

@ -0,0 +1,33 @@
<?php declare(strict_types=1);
namespace Invoker\Exception;
/**
* The given callable is not actually callable.
*/
class NotCallableException extends InvocationException
{
/**
* @param mixed $value
*/
public static function fromInvalidCallable($value, bool $containerEntry = false): self
{
if (is_object($value)) {
$message = sprintf('Instance of %s is not a callable', get_class($value));
} elseif (is_array($value) && isset($value[0], $value[1])) {
$class = is_object($value[0]) ? get_class($value[0]) : $value[0];
$extra = method_exists($class, '__call') || method_exists($class, '__callStatic')
? ' A __call() or __callStatic() method exists but magic methods are not supported.'
: '';
$message = sprintf('%s::%s() is not a callable.%s', $class, $value[1], $extra);
} elseif ($containerEntry) {
$message = var_export($value, true) . ' is neither a callable nor a valid container entry';
} else {
$message = var_export($value, true) . ' is not a callable';
}
return new self($message);
}
}

View File

@ -0,0 +1,10 @@
<?php declare(strict_types=1);
namespace Invoker\Exception;
/**
* Not enough parameters could be resolved to invoke the callable.
*/
class NotEnoughParametersException extends InvocationException
{
}

View File

@ -0,0 +1,109 @@
<?php declare(strict_types=1);
namespace Invoker;
use Invoker\Exception\NotCallableException;
use Invoker\Exception\NotEnoughParametersException;
use Invoker\ParameterResolver\AssociativeArrayResolver;
use Invoker\ParameterResolver\DefaultValueResolver;
use Invoker\ParameterResolver\NumericArrayResolver;
use Invoker\ParameterResolver\ParameterResolver;
use Invoker\ParameterResolver\ResolverChain;
use Invoker\Reflection\CallableReflection;
use Psr\Container\ContainerInterface;
use ReflectionParameter;
/**
* Invoke a callable.
*/
class Invoker implements InvokerInterface
{
/** @var CallableResolver|null */
private $callableResolver;
/** @var ParameterResolver */
private $parameterResolver;
/** @var ContainerInterface|null */
private $container;
public function __construct(?ParameterResolver $parameterResolver = null, ?ContainerInterface $container = null)
{
$this->parameterResolver = $parameterResolver ?: $this->createParameterResolver();
$this->container = $container;
if ($container) {
$this->callableResolver = new CallableResolver($container);
}
}
/**
* {@inheritdoc}
*/
public function call($callable, array $parameters = [])
{
if ($this->callableResolver) {
$callable = $this->callableResolver->resolve($callable);
}
if (! is_callable($callable)) {
throw new NotCallableException(sprintf(
'%s is not a callable',
is_object($callable) ? 'Instance of ' . get_class($callable) : var_export($callable, true)
));
}
$callableReflection = CallableReflection::create($callable);
$args = $this->parameterResolver->getParameters($callableReflection, $parameters, []);
// Sort by array key because call_user_func_array ignores numeric keys
ksort($args);
// Check all parameters are resolved
$diff = array_diff_key($callableReflection->getParameters(), $args);
$parameter = reset($diff);
if ($parameter && \assert($parameter instanceof ReflectionParameter) && ! $parameter->isVariadic()) {
throw new NotEnoughParametersException(sprintf(
'Unable to invoke the callable because no value was given for parameter %d ($%s)',
$parameter->getPosition() + 1,
$parameter->name
));
}
return call_user_func_array($callable, $args);
}
/**
* Create the default parameter resolver.
*/
private function createParameterResolver(): ParameterResolver
{
return new ResolverChain([
new NumericArrayResolver,
new AssociativeArrayResolver,
new DefaultValueResolver,
]);
}
/**
* @return ParameterResolver By default it's a ResolverChain
*/
public function getParameterResolver(): ParameterResolver
{
return $this->parameterResolver;
}
public function getContainer(): ?ContainerInterface
{
return $this->container;
}
/**
* @return CallableResolver|null Returns null if no container was given in the constructor.
*/
public function getCallableResolver(): ?CallableResolver
{
return $this->callableResolver;
}
}

View File

@ -0,0 +1,25 @@
<?php declare(strict_types=1);
namespace Invoker;
use Invoker\Exception\InvocationException;
use Invoker\Exception\NotCallableException;
use Invoker\Exception\NotEnoughParametersException;
/**
* Invoke a callable.
*/
interface InvokerInterface
{
/**
* Call the given function using the given parameters.
*
* @param callable|array|string $callable Function to call.
* @param array $parameters Parameters to use.
* @return mixed Result of the function.
* @throws InvocationException Base exception class for all the sub-exceptions below.
* @throws NotCallableException
* @throws NotEnoughParametersException
*/
public function call($callable, array $parameters = []);
}

View File

@ -0,0 +1,37 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Tries to map an associative array (string-indexed) to the parameter names.
*
* E.g. `->call($callable, ['foo' => 'bar'])` will inject the string `'bar'`
* in the parameter named `$foo`.
*
* Parameters that are not indexed by a string are ignored.
*/
class AssociativeArrayResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
if (array_key_exists($parameter->name, $providedParameters)) {
$resolvedParameters[$index] = $providedParameters[$parameter->name];
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,47 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver\Container;
use Invoker\ParameterResolver\ParameterResolver;
use Psr\Container\ContainerInterface;
use ReflectionFunctionAbstract;
/**
* Inject entries from a DI container using the parameter names.
*/
class ParameterNameContainerResolver implements ParameterResolver
{
/** @var ContainerInterface */
private $container;
/**
* @param ContainerInterface $container The container to get entries from.
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
$name = $parameter->name;
if ($name && $this->container->has($name)) {
$resolvedParameters[$index] = $this->container->get($name);
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,65 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver\Container;
use Invoker\ParameterResolver\ParameterResolver;
use Psr\Container\ContainerInterface;
use ReflectionFunctionAbstract;
use ReflectionNamedType;
/**
* Inject entries from a DI container using the type-hints.
*/
class TypeHintContainerResolver implements ParameterResolver
{
/** @var ContainerInterface */
private $container;
/**
* @param ContainerInterface $container The container to get entries from.
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
$parameterType = $parameter->getType();
if (! $parameterType) {
// No type
continue;
}
if (! $parameterType instanceof ReflectionNamedType) {
// Union types are not supported
continue;
}
if ($parameterType->isBuiltin()) {
// Primitive types are not supported
continue;
}
$parameterClass = $parameterType->getName();
if ($parameterClass === 'self') {
$parameterClass = $parameter->getDeclaringClass()->getName();
}
if ($this->container->has($parameterClass)) {
$resolvedParameters[$index] = $this->container->get($parameterClass);
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,43 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver;
use ReflectionException;
use ReflectionFunctionAbstract;
/**
* Finds the default value for a parameter, *if it exists*.
*/
class DefaultValueResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
\assert($parameter instanceof \ReflectionParameter);
if ($parameter->isDefaultValueAvailable()) {
try {
$resolvedParameters[$index] = $parameter->getDefaultValue();
} catch (ReflectionException $e) {
// Can't get default values from PHP internal classes and functions
}
} else {
$parameterType = $parameter->getType();
if ($parameterType && $parameterType->allowsNull()) {
$resolvedParameters[$index] = null;
}
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,37 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Simply returns all the values of the $providedParameters array that are
* indexed by the parameter position (i.e. a number).
*
* E.g. `->call($callable, ['foo', 'bar'])` will simply resolve the parameters
* to `['foo', 'bar']`.
*
* Parameters that are not indexed by a number (i.e. parameter position)
* will be ignored.
*/
class NumericArrayResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$providedParameters = array_diff_key($providedParameters, $resolvedParameters);
}
foreach ($providedParameters as $key => $value) {
if (is_int($key)) {
$resolvedParameters[$key] = $value;
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,30 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Resolves the parameters to use to call the callable.
*/
interface ParameterResolver
{
/**
* Resolves the parameters to use to call the callable.
*
* `$resolvedParameters` contains parameters that have already been resolved.
*
* Each ParameterResolver must resolve parameters that are not already
* in `$resolvedParameters`. That allows to chain multiple ParameterResolver.
*
* @param ReflectionFunctionAbstract $reflection Reflection object for the callable.
* @param array $providedParameters Parameters provided by the caller.
* @param array $resolvedParameters Parameters resolved (indexed by parameter position).
* @return array
*/
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
);
}

View File

@ -0,0 +1,61 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
/**
* Dispatches the call to other resolvers until all parameters are resolved.
*
* Chain of responsibility pattern.
*/
class ResolverChain implements ParameterResolver
{
/** @var ParameterResolver[] */
private $resolvers;
public function __construct(array $resolvers = [])
{
$this->resolvers = $resolvers;
}
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
$reflectionParameters = $reflection->getParameters();
foreach ($this->resolvers as $resolver) {
$resolvedParameters = $resolver->getParameters(
$reflection,
$providedParameters,
$resolvedParameters
);
$diff = array_diff_key($reflectionParameters, $resolvedParameters);
if (empty($diff)) {
// Stop traversing: all parameters are resolved
return $resolvedParameters;
}
}
return $resolvedParameters;
}
/**
* Push a parameter resolver after the ones already registered.
*/
public function appendResolver(ParameterResolver $resolver): void
{
$this->resolvers[] = $resolver;
}
/**
* Insert a parameter resolver before the ones already registered.
*/
public function prependResolver(ParameterResolver $resolver): void
{
array_unshift($this->resolvers, $resolver);
}
}

View File

@ -0,0 +1,54 @@
<?php declare(strict_types=1);
namespace Invoker\ParameterResolver;
use ReflectionFunctionAbstract;
use ReflectionNamedType;
/**
* Inject entries using type-hints.
*
* Tries to match type-hints with the parameters provided.
*/
class TypeHintResolver implements ParameterResolver
{
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
$parameters = $reflection->getParameters();
// Skip parameters already resolved
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
$parameterType = $parameter->getType();
if (! $parameterType) {
// No type
continue;
}
if (! $parameterType instanceof ReflectionNamedType) {
// Union types are not supported
continue;
}
if ($parameterType->isBuiltin()) {
// Primitive types are not supported
continue;
}
$parameterClass = $parameterType->getName();
if ($parameterClass === 'self') {
$parameterClass = $parameter->getDeclaringClass()->getName();
}
if (array_key_exists($parameterClass, $providedParameters)) {
$resolvedParameters[$index] = $providedParameters[$parameterClass];
}
}
return $resolvedParameters;
}
}

View File

@ -0,0 +1,56 @@
<?php declare(strict_types=1);
namespace Invoker\Reflection;
use Closure;
use Invoker\Exception\NotCallableException;
use ReflectionException;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
/**
* Create a reflection object from a callable or a callable-like.
*
* @internal
*/
class CallableReflection
{
/**
* @param callable|array|string $callable Can be a callable or a callable-like.
* @throws NotCallableException|ReflectionException
*/
public static function create($callable): ReflectionFunctionAbstract
{
// Closure
if ($callable instanceof Closure) {
return new ReflectionFunction($callable);
}
// Array callable
if (is_array($callable)) {
[$class, $method] = $callable;
if (! method_exists($class, $method)) {
throw NotCallableException::fromInvalidCallable($callable);
}
return new ReflectionMethod($class, $method);
}
// Callable object (i.e. implementing __invoke())
if (is_object($callable) && method_exists($callable, '__invoke')) {
return new ReflectionMethod($callable, '__invoke');
}
// Standard function
if (is_string($callable) && function_exists($callable)) {
return new ReflectionFunction($callable);
}
throw new NotCallableException(sprintf(
'%s is not a callable',
is_string($callable) ? $callable : 'Instance of ' . get_class($callable)
));
}
}

18
lib/php-di/php-di/LICENSE Normal file
View File

@ -0,0 +1,18 @@
The MIT License (MIT)
Copyright (c) Matthieu Napoli
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
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 SOFTWARE.

View File

@ -0,0 +1,21 @@
---
layout: home
---
[![](doc/img.png)](https://php-di.org/)
[![Downloads per months](https://img.shields.io/packagist/dm/PHP-DI/PHP-DI.svg?style=flat-square)](https://packagist.org/packages/PHP-DI/PHP-DI)
[![Total downloads](https://img.shields.io/packagist/dt/PHP-DI/PHP-DI.svg?style=flat-square)](https://packagist.org/packages/PHP-DI/PHP-DI)
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/PHP-DI/PHP-DI.svg)](http://isitmaintained.com/project/PHP-DI/PHP-DI "Average time to resolve an issue")
[![Percentage of issues still open](http://isitmaintained.com/badge/open/PHP-DI/PHP-DI.svg)](http://isitmaintained.com/project/PHP-DI/PHP-DI "Percentage of issues still open")
PHP-DI is a dependency injection container meant to be practical, powerful, and framework-agnostic.
Read more on the website: **[php-di.org](https://php-di.org)**
## For Enterprise
*Available as part of the Tidelift Subscription*
The maintainers of php-di/php-di and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-php-di-php-di?utm_source=packagist-php-di-php-di&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

View File

@ -0,0 +1,440 @@
# Change log
## 6.1.0
- [#791](https://github.com/PHP-DI/PHP-DI/issues/791) Support PHP 8.1, remove support for PHP 7.2
## 6.0.2
- Fix potential regression introduced when fixing [#582](https://github.com/PHP-DI/PHP-DI/issues/582)
## 6.0.1
- Fix [#526](https://github.com/PHP-DI/PHP-DI/issues/526): Support optional parameters in factories
- [#585](https://github.com/PHP-DI/PHP-DI/issues/585) Add support for PHP-Parser 4.0
- [#582](https://github.com/PHP-DI/PHP-DI/issues/582) Register `ContainerInterface` to point to the wrapper container if it was defined
## 6.0
This is the complete change log. You can also read the [migration guide](doc/migration/6.0.md) for upgrading or the [blog article](news/22-php-di-6-0-released.md) to see what's new.
Improvements:
- [#494](https://github.com/PHP-DI/PHP-DI/pull/494) The container can now be compiled for optimum performances in production
- [#294](https://github.com/PHP-DI/PHP-DI/issues/294), [#349](https://github.com/PHP-DI/PHP-DI/issues/349), [#449](https://github.com/PHP-DI/PHP-DI/pull/449): `DI\object()` has been replaced by more specific and less ambiguous helpers:
- `DI\create()` creates an object, overrides autowiring and previous definitions
- `DI\autowire()` autowires an object and allows to override specific constructor and method parameters
- The container can now be built without parameters: `new Container()`
- Definitions can be nested:
- [#490](https://github.com/PHP-DI/PHP-DI/issues/490) Definitions can be nested in arrays (by [@yuloh](https://github.com/yuloh))
- [#501](https://github.com/PHP-DI/PHP-DI/issues/501) & [#540](https://github.com/PHP-DI/PHP-DI/issues/540) Autowire definitions can be nested in other definitions
- [#487](https://github.com/PHP-DI/PHP-DI/issues/487) & [#540](https://github.com/PHP-DI/PHP-DI/issues/540) Closures are now handled as factories when they are nested in other definitions
- [#487](https://github.com/PHP-DI/PHP-DI/issues/487) Closures in the config are now always interpreted as factories, even when nested inside other definitions
- [#242](https://github.com/PHP-DI/PHP-DI/issues/242) Error in case a definition is not indexed by a string
- [#505](https://github.com/PHP-DI/PHP-DI/pull/505) Debug container entries
- [#564](https://github.com/PHP-DI/PHP-DI/pull/564) Caching was made almost entirely obsolete by the container compilation, however there is still a caching system entirely rebuilt over APCu for covering the last cases that compilation could not address (see [php-di.org/doc/performances.html](https://php-di.org/doc/performances.html))
Fixes:
- [#499](https://github.com/PHP-DI/PHP-DI/issues/499) & [#488](https://github.com/PHP-DI/PHP-DI/issues/488) Standardize resolution of nested definitions everywhere.
In PHP-DI 5, definitions could be nested in some places (e.g. use a get() in an object definition, etc.). However it did not behave everywhere the same, for example it didn't work for sub-definitions in arrays.
Now in PHP-DI 6 all nested definitions will all be recognized and resolved correctly everywhere. Since #494 (compiled container) performance will not be affected so we can implement a more robust behavior.
- [#343](https://github.com/PHP-DI/PHP-DI/issues/343) Autowiring and Annotations do not work for `object()` inside arrays: it now works with the new `create()` and `autowire()` helpers
BC breaks:
- PHP 7 or greater is required and HHVM is no longer supported
- `DI\object()` has been removed, use `DI\create()` or `DI\autowire()` instead
- [#409](https://github.com/PHP-DI/PHP-DI/issues/409): Scopes are removed, read more in the [scopes](doc/scopes.md) documentation.
- Caching was replaced by compiling the container: `ContainerBuilder::setDefinitionCache()` was removed, use `ContainerBuilder::enableCompilation()` instead.
- [#463](https://github.com/PHP-DI/PHP-DI/issues/463) & [#485](https://github.com/PHP-DI/PHP-DI/issues/485): Container-interop support was removed, PSR-11 is used instead (by [@juliangut](https://github.com/juliangut))
- The deprecated `DI\link()` helper was removed, used `DI\get()` instead
- [#484](https://github.com/PHP-DI/PHP-DI/pull/484) The deprecated `\DI\Debug` class has been removed. Definitions can be cast to string directly
- The exception `DI\Definition\Exception\DefinitionException` was renamed to `DI\Definition\Exception\InvalidDefinition`
- The exception `DI\Definition\Exception\AnnotationException` was renamed to `DI\Definition\Exception\InvalidAnnotation`
- [#516](https://github.com/PHP-DI/PHP-DI/issues/516) `DI\InvokerInterface` was removed in favor of `Invoker\InvokerInterface`.
Be also aware that internal classes or interfaces may have changed.
## 5.4.6
- Fix [#554](https://github.com/PHP-DI/PHP-DI/issues/554): `Container::make()` fails when combined with `decorate()`.
## 5.4.5
Fixup of 5.4.4.
- [#531](https://github.com/PHP-DI/PHP-DI/issues/531): performance improvement.
## 5.4.4
This release was broken because it was tagged against the wrong branch.
- [#531](https://github.com/PHP-DI/PHP-DI/issues/531): performance improvement.
## 5.4.3
- [#467](https://github.com/PHP-DI/PHP-DI/issues/467): register the container against the PSR ContainerInterface
## 5.4.2
- Minor patch to add the `provide: psr/container-implementation` to `composer.json`.
## 5.4.1
- [PSR-11](http://www.php-fig.org/psr/) compliance
Note that PHP-DI was already compliant with PSR-11 because it was implementing container-interop, and container-interop 1.2 extends PSR-11. This new version just makes it more explicit and will allow to drop container-interop support in the next major versions.
## 5.4
Read the [news entry](news/20-php-di-5-4-released.md).
New features:
- [#362](https://github.com/PHP-DI/PHP-DI/issues/362) implemented in [#428](https://github.com/PHP-DI/PHP-DI/pull/428), [#430](https://github.com/PHP-DI/PHP-DI/pull/430), [#431](https://github.com/PHP-DI/PHP-DI/pull/431) and [#432](https://github.com/PHP-DI/PHP-DI/pull/432): factory parameters can now be configured, for example:
```php
return [
'Database' => DI\factory(function ($host) {...})
->parameter('host', DI\get('db.host')),
];
```
Read the [factories documentation](https://php-di.org/doc/php-definitions.html#factories) to learn more. Feature implemented by [@predakanga](https://github.com/predakanga).
Improvements:
- [#429](https://github.com/PHP-DI/PHP-DI/pull/429): performance improvements in definition resolution (by [@mnapoli](https://github.com/mnapoli))
- [#421](https://github.com/PHP-DI/PHP-DI/issues/421): once a `ContainerBuilder` has built a container, it is locked to prevent confusion when adding new definitions to it (by [@mnapoli](https://github.com/mnapoli))
- [#423](https://github.com/PHP-DI/PHP-DI/pull/423): improved exception messages (by [@mnapoli](https://github.com/mnapoli))
## 5.3
Read the [news entry](news/19-php-di-5-3-released.md).
- release of the [2.0 version](https://github.com/PHP-DI/Symfony-Bridge/releases/tag/2.0.0) of the Symfony bridge (by [@mnapoli](https://github.com/mnapoli))
- PHP 5.5 or above is now required
- a lot of documentation improvements by 9 different contributors
- [#389](https://github.com/PHP-DI/PHP-DI/pull/389): exception message improvement by [@mopahle](https://github.com/mopahle)
- [#359](https://github.com/PHP-DI/PHP-DI/issues/359), [#411](https://github.com/PHP-DI/PHP-DI/issues/411), [#414](https://github.com/PHP-DI/PHP-DI/pull/414), [#412](https://github.com/PHP-DI/PHP-DI/pull/412): compatibility with ProxyManager 1.* and 2.* (by [@holtkamp](https://github.com/holtkamp) and [@mnapoli](https://github.com/mnapoli))
- [#416](https://github.com/PHP-DI/PHP-DI/pull/416): dumping definitions was refactored into a more lightweight and simple solution; definition "dumpers" have been removed (internal classes), definitions can now be cast to string directly (by [@mnapoli](https://github.com/mnapoli))
## 5.2
Read the [news entry](news/17-php-di-5-2-released.md).
Improvements:
- [#347](https://github.com/PHP-DI/PHP-DI/pull/347) (includes [#333](https://github.com/PHP-DI/PHP-DI/pull/333) and [#345](https://github.com/PHP-DI/PHP-DI/pull/345)): by [@jdreesen](https://github.com/jdreesen), [@quimcalpe](https://github.com/quimcalpe) and [@mnapoli](https://github.com/mnapoli)
- Allow injection of any container object as factory parameter via type hinting
- Allow injection of a `DI\Factory\RequestedEntry` object to get the requested entry name
- [#272](https://github.com/PHP-DI/PHP-DI/issues/272): Support `"Class::method""` syntax for callables (by [@jdreesen](https://github.com/jdreesen))
- [#332](https://github.com/PHP-DI/PHP-DI/issues/332): IDE support (plugin and documentation) (by [@pulyaevskiy](https://github.com/pulyaevskiy), [@avant1](https://github.com/avant1) and [@mnapoli](https://github.com/mnapoli))
- [#326](https://github.com/PHP-DI/PHP-DI/pull/326): Exception messages are simpler and more consistent (by [@mnapoli](https://github.com/mnapoli))
- [#325](https://github.com/PHP-DI/PHP-DI/pull/325): Add a "Edit this page" button in the website to encourage users to improve the documentation (by [@jdreesen](https://github.com/jdreesen))
Bugfixes:
- [#321](https://github.com/PHP-DI/PHP-DI/pull/321): Allow factory definitions to reference arbitrary container entries as callables (by [@jdreesen](https://github.com/jdreesen))
- [#335](https://github.com/PHP-DI/PHP-DI/issues/335): Class imports in traits are now considered when parsing annotations (by [@thebigb](https://github.com/thebigb))
## 5.1
Read the [news entry](news/16-php-di-5-1-released.md).
Improvements:
- [Zend Framework 2 integration](https://github.com/PHP-DI/ZF2-Bridge) (by @Rastusik)
- [#308](https://github.com/PHP-DI/PHP-DI/pull/308): Instantiate factories using the container (`DI\factory(['FooFactory', 'create'])`)
- Many performances improvements - some benchmarks show up to 35% performance improvements, real results may vary of course
- Many documentation improvements (@jdreesen, @mindplay-dk, @mnapoli, @holtkamp, @Rastusik)
- [#296](https://github.com/PHP-DI/PHP-DI/issues/296): Provide a faster `ArrayCache` implementation, mostly useful in micro-benchmarks
Bugfixes:
- [#257](https://github.com/PHP-DI/PHP-DI/issues/257) & [#274](https://github.com/PHP-DI/PHP-DI/issues/274): Private properties of parent classes are not injected when using annotations
- [#300](https://github.com/PHP-DI/PHP-DI/pull/300): Exception if object definition extends an incompatible definition
- [#306](https://github.com/PHP-DI/PHP-DI/issues/306): Errors when using parameters passed by reference (fixed by @bradynpoulsen)
- [#318](https://github.com/PHP-DI/PHP-DI/issues/318): `Container::call()` ignores parameter's default value
Internal changes:
- [#276](https://github.com/PHP-DI/PHP-DI/pull/276): Tests now pass on Windows (@bgaillard)
## 5.0
This is the complete change log. You can also read the [migration guide](doc/migration/5.0.md) for upgrading, or [the news article](news/15-php-di-5-0-released.md) for a nicer introduction to this new version.
Improvements:
- Moved to an organization on GitHub: [github.com/PHP-DI/PHP-DI](https://github.com/PHP-DI/PHP-DI)
- The package has been renamed to: from `mnapoli/php-di` to [`php-di/php-di`](https://packagist.org/packages/php-di/php-di)
- New [Silex integration](doc/frameworks/silex.md)
- Lighter package: from 10 to 3 Composer dependencies!
- [#235](https://github.com/PHP-DI/PHP-DI/issues/235): `DI\link()` is now deprecated in favor of `DI\get()`. There is no BC break as `DI\link()` still works.
- [#207](https://github.com/PHP-DI/PHP-DI/issues/207): Support for `DI\link()` in arrays
- [#203](https://github.com/PHP-DI/PHP-DI/issues/203): New `DI\string()` helper ([documentation](doc/php-definitions.md))
- [#208](https://github.com/PHP-DI/PHP-DI/issues/208): Support for nested definitions
- [#226](https://github.com/PHP-DI/PHP-DI/pull/226): `DI\factory()` can now be omitted with closures:
```php
// before
'My\Class' => DI\factory(function () { ... })
// now (optional shortcut)
'My\Class' => function () { ... }
```
- [#193](https://github.com/PHP-DI/PHP-DI/issues/193): `DI\object()->method()` now supports calling the same method twice (or more).
- [#248](https://github.com/PHP-DI/PHP-DI/issues/248): New `DI\decorate()` helper to decorate a previously defined entry ([documentation](doc/definition-overriding.md))
- [#215](https://github.com/PHP-DI/PHP-DI/pull/215): New `DI\add()` helper to add entries to an existing array ([documentation](doc/definition-overriding.md))
- [#218](https://github.com/PHP-DI/PHP-DI/issues/218): `ContainerBuilder::addDefinitions()` can now take an array of definitions
- [#211](https://github.com/PHP-DI/PHP-DI/pull/211): `ContainerBuilder::addDefinitions()` is now fluent (return `$this`)
- [#250](https://github.com/PHP-DI/PHP-DI/issues/250): `Container::call()` now also accepts parameters not indexed by name as well as embedded definitions ([documentation](doc/container.md))
- Various performance improvements, e.g. lower the number of files loaded, simpler architecture, …
BC breaks:
- PHP-DI now requires a version of PHP >= 5.4.0
- The package is lighter by default:
- [#251](https://github.com/PHP-DI/PHP-DI/issues/251): Annotations are disabled by default, if you use annotations enable them with `$containerBuilder->useAnnotations(true)`. Additionally the `doctrine/annotations` package isn't required by default anymore, so you also need to run `composer require doctrine/annotations`.
- `doctrine/cache` is not installed by default anymore, you need to require it in `composer.json` (`~1.0`) if you want to configure a cache for PHP-DI
- [#198](https://github.com/PHP-DI/PHP-DI/issues/198): `ocramius/proxy-manager` is not installed by default anymore, you need to require it in `composer.json` (`~1.0`) if you want to use **lazy injection**
- Closures are now converted into factory definitions automatically. If you ever defined a closure as a value (e.g. to have the closure injected in a class), you need to wrap the closure with the new `DI\value()` helper.
- [#223](https://github.com/PHP-DI/PHP-DI/issues/223): `DI\ContainerInterface` was deprecated since v4.1 and has been removed
Internal changes in case you were replacing/extending some parts:
- the definition sources architecture has been refactored, if you defined custom definition sources you will need to update your code (it should be much easier now)
- [#252](https://github.com/PHP-DI/PHP-DI/pull/252): `DI\Scope` internal implementation has changed. You are encouraged to use the constants (`DI\Scope::SINGLETON` and `DI\Scope::PROTOTYPE`) instead of the static methods, but backward compatibility is kept (static methods still work).
- [#241](https://github.com/PHP-DI/PHP-DI/issues/241): `Container::call()` now uses the *Invoker* external library
## 4.4
Read the [news entry](news/13-php-di-4-4-released.md).
- [#185](https://github.com/PHP-DI/PHP-DI/issues/185) Support for invokable objects in `Container::call()`
- [#192](https://github.com/PHP-DI/PHP-DI/pull/192) Support for invokable classes in `Container::call()` (will instantiate the class)
- [#184](https://github.com/PHP-DI/PHP-DI/pull/184) Option to ignore phpdoc errors
## 4.3
Read the [news entry](news/11-php-di-4-3-released.md).
- [#176](https://github.com/PHP-DI/PHP-DI/pull/176) New definition type for reading environment variables: `DI\env()`
- [#181](https://github.com/PHP-DI/PHP-DI/pull/181) `DI\FactoryInterface` and `DI\InvokerInterface` are now auto-registered inside the container so that you can inject them without any configuration needed
- [#173](https://github.com/PHP-DI/PHP-DI/pull/173) `$container->call(['MyClass', 'method]);` will get `MyClass` from the container if `method()` is not a static method
## 4.2.2
- Fixed [#180](https://github.com/PHP-DI/PHP-DI/pull/180): `Container::call()` with object methods (`[$object, 'method']`) is now supported
## 4.2.1
- Support for PHP 5.3.3, which was previously incomplete because of a bug in the reflection (there is now a workaround for this bug)
But if you can, seriously avoid this (really old) PHP version and upgrade.
## 4.2
Read the [news entry](news/10-php-di-4-2-released.md).
**Minor BC-break**: Optional parameters (that were not configured) were injected, they are now ignored, which is what naturally makes sense since they are optional.
Example:
```php
public function __construct(Bar $bar = null)
{
$this->bar = $bar ?: $this->createDefaultBar();
}
```
Before 4.2, PHP-DI would try to inject a `Bar` instance. From 4.2 and onwards, it will inject `null`.
Of course, you can still explicitly define an injection for the optional parameters and that will work.
All changes:
* [#162](https://github.com/PHP-DI/PHP-DI/pull/162) Added `Container::call()` to call functions with dependency injection
* [#156](https://github.com/PHP-DI/PHP-DI/issues/156) Wildcards (`*`) in definitions
* [#164](https://github.com/PHP-DI/PHP-DI/issues/164) Prototype scope is now available for `factory()` definitions too
* FIXED [#168](https://github.com/PHP-DI/PHP-DI/pull/168) `Container::has()` now returns false for interfaces and abstract classes that are not mapped in the definitions
* FIXED [#171](https://github.com/PHP-DI/PHP-DI/issues/171) Optional parameters are now ignored (not injected) if not set in the definitions (see the BC-break warning above)
## 4.1
Read the [news entry](news/09-php-di-4-1-released.md).
BC-breaks: None.
* [#138](https://github.com/PHP-DI/PHP-DI/issues/138) [Container-interop](https://github.com/container-interop/container-interop) compliance
* [#143](https://github.com/PHP-DI/PHP-DI/issues/143) Much more explicit exception messages
* [#157](https://github.com/PHP-DI/PHP-DI/issues/157) HHVM support
* [#158](https://github.com/PHP-DI/PHP-DI/issues/158) Improved the documentation for [Symfony 2 integration](https://php-di.org/doc/frameworks/symfony2.html)
## 4.0
Major changes:
* The configuration format has changed ([read more here to understand why](news/06-php-di-4-0-new-definitions.md))
Read the migration guide if you are using 3.x: [Migration guide from 3.x to 4.0](doc/migration/4.0.md).
BC-breaks:
* YAML, XML and JSON definitions have been removed, and the PHP definition format has changed (see above)
* `ContainerSingleton` has been removed
* You cannot configure an injection as lazy anymore, you can only configure a container entry as lazy
* The Container constructor now takes mandatory parameters. Use the ContainerBuilder to create a Container.
* Removed `ContainerBuilder::setDefinitionsValidation()` (no definition validation anymore)
* `ContainerBuilder::useReflection()` is now named: `ContainerBuilder::useAutowiring()`
* `ContainerBuilder::addDefinitionsFromFile()` is now named: `ContainerBuilder::addDefinitions()`
* The `$proxy` parameter in `Container::get($name, $proxy = true)` hase been removed. To get a proxy, you now need to define an entry as "lazy".
Other changes:
* Added `ContainerInterface` and `FactoryInterface`, both implemented by the container.
* [#115](https://github.com/PHP-DI/PHP-DI/issues/115) Added `Container::has()`
* [#142](https://github.com/PHP-DI/PHP-DI/issues/142) Added `Container::make()` to resolve an entry
* [#127](https://github.com/PHP-DI/PHP-DI/issues/127) Added support for cases where PHP-DI is wrapped by another container (like Acclimate): PHP-DI can now use the wrapping container to perform injections
* [#128](https://github.com/PHP-DI/PHP-DI/issues/128) Configure entry aliases
* [#110](https://github.com/PHP-DI/PHP-DI/issues/110) XML definitions are not supported anymore
* [#122](https://github.com/PHP-DI/PHP-DI/issues/122) JSON definitions are not supported anymore
* `ContainerSingleton` has finally been removed
* Added `ContainerBuilder::buildDevContainer()` to get started with a default container very easily.
* [#99](https://github.com/PHP-DI/PHP-DI/issues/99) Fixed "`@param` with PHP internal type throws exception"
## 3.5.1
* FIXED [#126](https://github.com/PHP-DI/PHP-DI/issues/126): `Container::set` without effect if a value has already been set and retrieved
## 3.5
Read the [news entry](news/05-php-di-3-5.md).
* Importing `@Inject` and `@Injectable` annotations is now optional! It means that you don't have to write `use DI\Annotation\Inject` anymore
* FIXED [#124](https://github.com/PHP-DI/PHP-DI/issues/124): `@Injects` annotation conflicts with other annotations
## 3.4
Read the [news entry](news/04-php-di-3-4.md).
* [#106](https://github.com/PHP-DI/PHP-DI/pull/106) You can now define arrays of values (in YAML, PHP, …) thanks to [@unkind](https://github.com/unkind)
* [#98](https://github.com/PHP-DI/PHP-DI/issues/98) `ContainerBuilder` is now fluent thanks to [@drdamour](https://github.com/drdamour)
* [#101](https://github.com/PHP-DI/PHP-DI/pull/101) Optional parameters are now supported: if you don't define a value to inject, their default value will be used
* XML definitions have been deprecated, there weren't even documented and were not maintained. They will be removed in 4.0.
* FIXED [#100](https://github.com/PHP-DI/PHP-DI/issues/100): bug for lazy injection in constructors
## 3.3
Read the [news entry](news/03-php-di-3-3.md).
* Inject dependencies on an existing instance with `Container::injectOn` (work from [Jeff Flitton](https://github.com/jflitton): [#89](https://github.com/PHP-DI/PHP-DI/pull/89)).
* [#86](https://github.com/PHP-DI/PHP-DI/issues/86): Optimized definition lookup (faster)
* FIXED [#87](https://github.com/PHP-DI/PHP-DI/issues/87): Rare bug in the `PhpDocParser`, fixed by [drdamour](https://github.com/drdamour)
## 3.2
Read the [news entry](news/02-php-di-3-2.md).
Small BC-break: PHP-DI 3.0 and 3.1 injected properties before calling the constructor. This was confusing and [not supported for internal classes](https://github.com/PHP-DI/PHP-DI/issues/74).
From 3.2 and on, properties are injected after calling the constructor.
* **[Lazy injection](doc/lazy-injection.md)**: it is now possible to use lazy injection on properties and methods (setters and constructors).
* Lazy dependencies are now proxies that extend the class they proxy, so type-hinting works.
* Addition of the **`ContainerBuilder`** object, that helps to [create and configure a `Container`](doc/container-configuration.md).
* Some methods for configuring the Container have gone **deprecated** in favor of the `ContainerBuilder`. Fear not, these deprecated methods will remain until next major version (4.0).
* `Container::useReflection`, use ContainerBuilder::useReflection instead
* `Container::useAnnotations`, use ContainerBuilder::useAnnotations instead
* `Container::setDefinitionCache`, use ContainerBuilder::setDefinitionCache instead
* `Container::setDefinitionsValidation`, use ContainerBuilder::setDefinitionsValidation instead
* The container is now auto-registered (as 'DI\Container'). You can now inject the container without registering it.
## 3.1.1
* Value definitions (`$container->set('foo', 80)`) are not cached anymore
* FIXED [#82](https://github.com/PHP-DI/PHP-DI/issues/82): Serialization error when using a cache
## 3.1
Read the [news entry](news/01-php-di-3-1.md).
* Zend Framework 1 integration through the [PHP-DI-ZF1 project](https://github.com/PHP-DI/PHP-DI-ZF1)
* Fixed the order of priorities when you mix different definition sources (reflection, annotations, files, …). See [Definition overriding](doc/definition-overriding.md)
* Now possible to define null values with `$container->set('foo', null)` (see [#79](https://github.com/PHP-DI/PHP-DI/issues/79)).
* Deprecated usage of `ContainerSingleton`, will be removed in next major version (4.0)
## 3.0.6
* FIXED [#76](https://github.com/PHP-DI/PHP-DI/issues/76): Definition conflict when setting a closure for a class name
## 3.0.5
* FIXED [#70](https://github.com/PHP-DI/PHP-DI/issues/70): Definition conflict when setting a value for a class name
## 3.0.4
* FIXED [#69](https://github.com/PHP-DI/PHP-DI/issues/69): YamlDefinitionFileLoader crashes if YAML file is empty
## 3.0.3
* Fixed over-restrictive dependencies in composer.json
## 3.0.2
* [#64](https://github.com/PHP-DI/PHP-DI/issues/64): Non PHP-DI exceptions are not captured-rethrown anymore when injecting dependencies (cleaner stack trace)
## 3.0.1
* [#62](https://github.com/PHP-DI/PHP-DI/issues/62): When using aliases, definitions are now merged
## 3.0
Major compatibility breaks with 2.x.
* The container is no longer a Singleton (but `ContainerSingleton::getInstance()` is available for fools who like it)
* Setter injection
* Constructor injection
* Scopes: singleton (share the same instance of the class) or prototype (create a new instance each time it is fetched). Defined at class level.
* Configuration is reworked from scratch. Now every configuration backend can do 100% of the job.
* Provided configuration backends:
* Reflection
* Annotations: @Inject, @Injectable
* PHP code (`Container::set()`)
* PHP array
* YAML file
* As a consequence, annotations are not mandatory anymore, all functionalities can be used with or without annotations.
* Renamed `DI\Annotations\` to `DI\Annotation\`
* `Container` no longer implements ArrayAccess, use only `$container->get($key)` now
* ZF1 integration broken and removed (work in progress for next releases)
* Code now follows PSR1 and PSR2 coding styles
* FIXED: [#58](https://github.com/PHP-DI/PHP-DI/issues/58) Getting a proxy of an alias didn't work
## 2.1
* `use` statements to import classes from other namespaces are now taken into account with the `@var` annotation
* Updated and lightened the dependencies : `doctrine/common` has been replaced with more specific `doctrine/annotations` and `doctrine/cache`
## 2.0
Major compatibility breaks with 1.x.
* `Container::resolveDependencies()` has been renamed to `Container::injectAll()`
* Dependencies are now injected **before** the constructor is called, and thus are available in the constructor
* Merged `@Value` annotation with `@Inject`: no difference between value and bean injection anymore
* Container implements ArrayAccess for get() and set() (`$container['db.host'] = 'localhost';`)
* Ini configuration files removed: configuration is done in PHP
* Allow to define beans within closures for lazy-loading
* Switched to MIT License
Warning:
* If you use PHP 5.3 and __wakeup() methods, they will be called when PHP-DI creates new instances of those classes.
## 1.1
* Caching of annotations based on Doctrine caches
## 1.0
* DependencyManager renamed to Container
* Refactored basic Container usage with `get` and `set`
* Allow named injection `@Inject(name="")`
* Zend Framework integration

View File

@ -0,0 +1,45 @@
{
"name": "php-di/php-di",
"type": "library",
"description": "The dependency injection container for humans",
"keywords": ["di", "dependency injection", "container", "ioc", "psr-11", "psr11", "container-interop"],
"homepage": "https://php-di.org/",
"license": "MIT",
"autoload": {
"psr-4": {
"DI\\": "src/"
},
"files": [
"src/functions.php"
]
},
"autoload-dev": {
"psr-4": {
"DI\\Test\\IntegrationTest\\": "tests/IntegrationTest/",
"DI\\Test\\UnitTest\\": "tests/UnitTest/"
}
},
"scripts": {
"test": "phpunit",
"format-code": "php-cs-fixer fix --allow-risky=yes"
},
"require": {
"php": ">=8.0",
"psr/container": "^1.1 || ^2.0",
"php-di/invoker": "^2.0",
"laravel/serializable-closure": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"mnapoli/phpunit-easymock": "^1.3",
"friendsofphp/proxy-manager-lts": "^1",
"friendsofphp/php-cs-fixer": "^3",
"vimeo/psalm": "^4.6"
},
"provide": {
"psr/container-implementation": "^1.0"
},
"suggest": {
"friendsofphp/proxy-manager-lts": "Install it if you want to use lazy injection (version ^1)"
}
}

View File

@ -0,0 +1 @@
See instructions in lib/php-di/readme_moodle.md

View File

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace DI\Attribute;
use Attribute;
use DI\Definition\Exception\InvalidAttribute;
/**
* #[Inject] attribute.
*
* Marks a property or method as an injection point
*
* @api
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_METHOD | Attribute::TARGET_PARAMETER)]
final class Inject
{
/**
* Entry name.
*/
private ?string $name = null;
/**
* Parameters, indexed by the parameter number (index) or name.
*
* Used if the attribute is set on a method
*/
private array $parameters = [];
/**
* @throws InvalidAttribute
*/
public function __construct(string|array|null $name = null)
{
// #[Inject('foo')] or #[Inject(name: 'foo')]
if (is_string($name)) {
$this->name = $name;
}
// #[Inject([...])] on a method
if (is_array($name)) {
foreach ($name as $key => $value) {
if (! is_string($value)) {
throw new InvalidAttribute(sprintf(
"#[Inject(['param' => 'value'])] expects \"value\" to be a string, %s given.",
json_encode($value, \JSON_THROW_ON_ERROR)
));
}
$this->parameters[$key] = $value;
}
}
}
/**
* @return string|null Name of the entry to inject
*/
public function getName() : string|null
{
return $this->name;
}
/**
* @return array Parameters, indexed by the parameter number (index) or name
*/
public function getParameters() : array
{
return $this->parameters;
}
}

View File

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace DI\Attribute;
use Attribute;
/**
* "Injectable" attribute.
*
* Marks a class as injectable
*
* @api
*
* @author Domenic Muskulus <domenic@muskulus.eu>
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
#[Attribute(Attribute::TARGET_CLASS)]
final class Injectable
{
/**
* @param bool|null $lazy Should the object be lazy-loaded.
*/
public function __construct(
private ?bool $lazy = null,
) {
}
public function isLazy() : bool|null
{
return $this->lazy;
}
}

View File

@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace DI;
use DI\Compiler\RequestedEntryHolder;
use DI\Definition\Definition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Invoker\FactoryParameterResolver;
use Invoker\Exception\NotCallableException;
use Invoker\Exception\NotEnoughParametersException;
use Invoker\Invoker;
use Invoker\InvokerInterface;
use Invoker\ParameterResolver\AssociativeArrayResolver;
use Invoker\ParameterResolver\DefaultValueResolver;
use Invoker\ParameterResolver\NumericArrayResolver;
use Invoker\ParameterResolver\ResolverChain;
/**
* Compiled version of the dependency injection container.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
abstract class CompiledContainer extends Container
{
/**
* This const is overridden in child classes (compiled containers).
* @var array
*/
protected const METHOD_MAPPING = [];
private ?InvokerInterface $factoryInvoker = null;
public function get(string $id) : mixed
{
// Try to find the entry in the singleton map
if (isset($this->resolvedEntries[$id]) || array_key_exists($id, $this->resolvedEntries)) {
return $this->resolvedEntries[$id];
}
/** @psalm-suppress UndefinedConstant */
$method = static::METHOD_MAPPING[$id] ?? null;
// If it's a compiled entry, then there is a method in this class
if ($method !== null) {
// Check if we are already getting this entry -> circular dependency
if (isset($this->entriesBeingResolved[$id])) {
throw new DependencyException("Circular dependency detected while trying to resolve entry '$id'");
}
$this->entriesBeingResolved[$id] = true;
try {
$value = $this->$method();
} finally {
unset($this->entriesBeingResolved[$id]);
}
// Store the entry to always return it without recomputing it
$this->resolvedEntries[$id] = $value;
return $value;
}
return parent::get($id);
}
public function has(string $id) : bool
{
// The parent method is overridden to check in our array, it avoids resolving definitions
/** @psalm-suppress UndefinedConstant */
if (isset(static::METHOD_MAPPING[$id])) {
return true;
}
return parent::has($id);
}
protected function setDefinition(string $name, Definition $definition) : void
{
// It needs to be forbidden because that would mean get() must go through the definitions
// every time, which kinds of defeats the performance gains of the compiled container
throw new \LogicException('You cannot set a definition at runtime on a compiled container. You can either put your definitions in a file, disable compilation or ->set() a raw value directly (PHP object, string, int, ...) instead of a PHP-DI definition.');
}
/**
* Invoke the given callable.
*/
protected function resolveFactory($callable, $entryName, array $extraParameters = []) : mixed
{
// Initialize the factory resolver
if (! $this->factoryInvoker) {
$parameterResolver = new ResolverChain([
new AssociativeArrayResolver,
new FactoryParameterResolver($this->delegateContainer),
new NumericArrayResolver,
new DefaultValueResolver,
]);
$this->factoryInvoker = new Invoker($parameterResolver, $this->delegateContainer);
}
$parameters = [$this->delegateContainer, new RequestedEntryHolder($entryName)];
$parameters = array_merge($parameters, $extraParameters);
try {
return $this->factoryInvoker->call($callable, $parameters);
} catch (NotCallableException $e) {
throw new InvalidDefinition("Entry \"$entryName\" cannot be resolved: factory " . $e->getMessage());
} catch (NotEnoughParametersException $e) {
throw new InvalidDefinition("Entry \"$entryName\" cannot be resolved: " . $e->getMessage());
}
}
}

View File

@ -0,0 +1,402 @@
<?php
declare(strict_types=1);
namespace DI\Compiler;
use function chmod;
use DI\Definition\ArrayDefinition;
use DI\Definition\DecoratorDefinition;
use DI\Definition\Definition;
use DI\Definition\EnvironmentVariableDefinition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\FactoryDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\Reference;
use DI\Definition\Source\DefinitionSource;
use DI\Definition\StringDefinition;
use DI\Definition\ValueDefinition;
use DI\DependencyException;
use DI\Proxy\ProxyFactory;
use function dirname;
use function file_put_contents;
use InvalidArgumentException;
use Laravel\SerializableClosure\Support\ReflectionClosure;
use function rename;
use function sprintf;
use function tempnam;
use function unlink;
/**
* Compiles the container into PHP code much more optimized for performances.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class Compiler
{
private string $containerClass;
private string $containerParentClass;
/**
* Definitions indexed by the entry name. The value can be null if the definition needs to be fetched.
*
* Keys are strings, values are `Definition` objects or null.
*/
private \ArrayIterator $entriesToCompile;
/**
* Progressive counter for definitions.
*
* Each key in $entriesToCompile is defined as 'SubEntry' + counter
* and each definition has always the same key in the CompiledContainer
* if PHP-DI configuration does not change.
*/
private int $subEntryCounter = 0;
/**
* Progressive counter for CompiledContainer get methods.
*
* Each CompiledContainer method name is defined as 'get' + counter
* and remains the same after each recompilation
* if PHP-DI configuration does not change.
*/
private int $methodMappingCounter = 0;
/**
* Map of entry names to method names.
*
* @var string[]
*/
private array $entryToMethodMapping = [];
/**
* @var string[]
*/
private array $methods = [];
private bool $autowiringEnabled;
public function __construct(
private ProxyFactory $proxyFactory,
) {
}
public function getProxyFactory() : ProxyFactory
{
return $this->proxyFactory;
}
/**
* Compile the container.
*
* @return string The compiled container file name.
*/
public function compile(
DefinitionSource $definitionSource,
string $directory,
string $className,
string $parentClassName,
bool $autowiringEnabled
) : string {
$fileName = rtrim($directory, '/') . '/' . $className . '.php';
if (file_exists($fileName)) {
// The container is already compiled
return $fileName;
}
$this->autowiringEnabled = $autowiringEnabled;
// Validate that a valid class name was provided
$validClassName = preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $className);
if (!$validClassName) {
throw new InvalidArgumentException("The container cannot be compiled: `$className` is not a valid PHP class name");
}
$this->entriesToCompile = new \ArrayIterator($definitionSource->getDefinitions());
// We use an ArrayIterator so that we can keep adding new items to the list while we compile entries
foreach ($this->entriesToCompile as $entryName => $definition) {
$silenceErrors = false;
// This is an entry found by reference during autowiring
if (!$definition) {
$definition = $definitionSource->getDefinition($entryName);
// We silence errors for those entries because type-hints may reference interfaces/abstract classes
// which could later be defined, or even not used (we don't want to block the compilation for those)
$silenceErrors = true;
}
if (!$definition) {
// We do not throw a `NotFound` exception here because the dependency
// could be defined at runtime
continue;
}
// Check that the definition can be compiled
$errorMessage = $this->isCompilable($definition);
if ($errorMessage !== true) {
continue;
}
try {
$this->compileDefinition($entryName, $definition);
} catch (InvalidDefinition $e) {
if ($silenceErrors) {
// forget the entry
unset($this->entryToMethodMapping[$entryName]);
} else {
throw $e;
}
}
}
$this->containerClass = $className;
$this->containerParentClass = $parentClassName;
ob_start();
require __DIR__ . '/Template.php';
$fileContent = ob_get_clean();
$fileContent = "<?php\n" . $fileContent;
$this->createCompilationDirectory(dirname($fileName));
$this->writeFileAtomic($fileName, $fileContent);
return $fileName;
}
private function writeFileAtomic(string $fileName, string $content) : void
{
$tmpFile = @tempnam(dirname($fileName), 'swap-compile');
if ($tmpFile === false) {
throw new InvalidArgumentException(
sprintf('Error while creating temporary file in %s', dirname($fileName))
);
}
@chmod($tmpFile, 0666);
$written = file_put_contents($tmpFile, $content);
if ($written === false) {
@unlink($tmpFile);
throw new InvalidArgumentException(sprintf('Error while writing to %s', $tmpFile));
}
@chmod($tmpFile, 0666);
$renamed = @rename($tmpFile, $fileName);
if (!$renamed) {
@unlink($tmpFile);
throw new InvalidArgumentException(sprintf('Error while renaming %s to %s', $tmpFile, $fileName));
}
}
/**
* @return string The method name
* @throws DependencyException
* @throws InvalidDefinition
*/
private function compileDefinition(string $entryName, Definition $definition) : string
{
// Generate a unique method name
$methodName = 'get' . (++$this->methodMappingCounter);
$this->entryToMethodMapping[$entryName] = $methodName;
switch (true) {
case $definition instanceof ValueDefinition:
$value = $definition->getValue();
$code = 'return ' . $this->compileValue($value) . ';';
break;
case $definition instanceof Reference:
$targetEntryName = $definition->getTargetEntryName();
$code = 'return $this->delegateContainer->get(' . $this->compileValue($targetEntryName) . ');';
// If this method is not yet compiled we store it for compilation
if (!isset($this->entriesToCompile[$targetEntryName])) {
$this->entriesToCompile[$targetEntryName] = null;
}
break;
case $definition instanceof StringDefinition:
$entryName = $this->compileValue($definition->getName());
$expression = $this->compileValue($definition->getExpression());
$code = 'return \DI\Definition\StringDefinition::resolveExpression(' . $entryName . ', ' . $expression . ', $this->delegateContainer);';
break;
case $definition instanceof EnvironmentVariableDefinition:
$variableName = $this->compileValue($definition->getVariableName());
$isOptional = $this->compileValue($definition->isOptional());
$defaultValue = $this->compileValue($definition->getDefaultValue());
$code = <<<PHP
\$value = \$_ENV[$variableName] ?? \$_SERVER[$variableName] ?? getenv($variableName);
if (false !== \$value) return \$value;
if (!$isOptional) {
throw new \DI\Definition\Exception\InvalidDefinition("The environment variable '{$definition->getVariableName()}' has not been defined");
}
return $defaultValue;
PHP;
break;
case $definition instanceof ArrayDefinition:
try {
$code = 'return ' . $this->compileValue($definition->getValues()) . ';';
} catch (\Exception $e) {
throw new DependencyException(sprintf(
'Error while compiling %s. %s',
$definition->getName(),
$e->getMessage()
), 0, $e);
}
break;
case $definition instanceof ObjectDefinition:
$compiler = new ObjectCreationCompiler($this);
$code = $compiler->compile($definition);
$code .= "\n return \$object;";
break;
case $definition instanceof DecoratorDefinition:
$decoratedDefinition = $definition->getDecoratedDefinition();
if (! $decoratedDefinition instanceof Definition) {
if (! $definition->getName()) {
throw new InvalidDefinition('Decorators cannot be nested in another definition');
}
throw new InvalidDefinition(sprintf(
'Entry "%s" decorates nothing: no previous definition with the same name was found',
$definition->getName()
));
}
$code = sprintf(
'return call_user_func(%s, %s, $this->delegateContainer);',
$this->compileValue($definition->getCallable()),
$this->compileValue($decoratedDefinition)
);
break;
case $definition instanceof FactoryDefinition:
$value = $definition->getCallable();
// Custom error message to help debugging
$isInvokableClass = is_string($value) && class_exists($value) && method_exists($value, '__invoke');
if ($isInvokableClass && !$this->autowiringEnabled) {
throw new InvalidDefinition(sprintf(
'Entry "%s" cannot be compiled. Invokable classes cannot be automatically resolved if autowiring is disabled on the container, you need to enable autowiring or define the entry manually.',
$entryName
));
}
$definitionParameters = '';
if (!empty($definition->getParameters())) {
$definitionParameters = ', ' . $this->compileValue($definition->getParameters());
}
$code = sprintf(
'return $this->resolveFactory(%s, %s%s);',
$this->compileValue($value),
var_export($entryName, true),
$definitionParameters
);
break;
default:
// This case should not happen (so it cannot be tested)
throw new \Exception('Cannot compile definition of type ' . $definition::class);
}
$this->methods[$methodName] = $code;
return $methodName;
}
public function compileValue(mixed $value) : string
{
// Check that the value can be compiled
$errorMessage = $this->isCompilable($value);
if ($errorMessage !== true) {
throw new InvalidDefinition($errorMessage);
}
if ($value instanceof Definition) {
// Give it an arbitrary unique name
$subEntryName = 'subEntry' . (++$this->subEntryCounter);
// Compile the sub-definition in another method
$methodName = $this->compileDefinition($subEntryName, $value);
// The value is now a method call to that method (which returns the value)
return "\$this->$methodName()";
}
if (is_array($value)) {
$value = array_map(function ($value, $key) {
$compiledValue = $this->compileValue($value);
$key = var_export($key, true);
return " $key => $compiledValue,\n";
}, $value, array_keys($value));
$value = implode('', $value);
return "[\n$value ]";
}
if ($value instanceof \Closure) {
return $this->compileClosure($value);
}
return var_export($value, true);
}
private function createCompilationDirectory(string $directory) : void
{
if (!is_dir($directory) && !@mkdir($directory, 0777, true) && !is_dir($directory)) {
throw new InvalidArgumentException(sprintf('Compilation directory does not exist and cannot be created: %s.', $directory));
}
if (!is_writable($directory)) {
throw new InvalidArgumentException(sprintf('Compilation directory is not writable: %s.', $directory));
}
}
/**
* @return string|true If true is returned that means that the value is compilable.
*/
private function isCompilable($value) : string|bool
{
if ($value instanceof ValueDefinition) {
return $this->isCompilable($value->getValue());
}
if (($value instanceof DecoratorDefinition) && empty($value->getName())) {
return 'Decorators cannot be nested in another definition';
}
// All other definitions are compilable
if ($value instanceof Definition) {
return true;
}
if ($value instanceof \Closure) {
return true;
}
/** @psalm-suppress UndefinedClass */
if ((\PHP_VERSION_ID >= 80100) && ($value instanceof \UnitEnum)) {
return true;
}
if (is_object($value)) {
return 'An object was found but objects cannot be compiled';
}
if (is_resource($value)) {
return 'A resource was found but resources cannot be compiled';
}
return true;
}
/**
* @throws InvalidDefinition
*/
private function compileClosure(\Closure $closure) : string
{
$reflector = new ReflectionClosure($closure);
if ($reflector->getUseVariables()) {
throw new InvalidDefinition('Cannot compile closures which import variables using the `use` keyword');
}
if ($reflector->isBindingRequired() || $reflector->isScopeRequired()) {
throw new InvalidDefinition('Cannot compile closures which use $this or self/static/parent references');
}
// Force all closures to be static (add the `static` keyword), i.e. they can't use
// $this, which makes sense since their code is copied into another class.
$code = ($reflector->isStatic() ? '' : 'static ') . $reflector->getCode();
return trim($code, "\t\n\r;");
}
}

View File

@ -0,0 +1,200 @@
<?php
declare(strict_types=1);
namespace DI\Compiler;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\ObjectDefinition\MethodInjection;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
/**
* Compiles an object definition into native PHP code that, when executed, creates the object.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ObjectCreationCompiler
{
public function __construct(
private Compiler $compiler,
) {
}
public function compile(ObjectDefinition $definition) : string
{
$this->assertClassIsNotAnonymous($definition);
$this->assertClassIsInstantiable($definition);
/** @var class-string $className At this point we have checked the class is valid */
$className = $definition->getClassName();
// Lazy?
if ($definition->isLazy()) {
return $this->compileLazyDefinition($definition);
}
try {
$classReflection = new ReflectionClass($className);
$constructorArguments = $this->resolveParameters($definition->getConstructorInjection(), $classReflection->getConstructor());
$dumpedConstructorArguments = array_map(function ($value) {
return $this->compiler->compileValue($value);
}, $constructorArguments);
$code = [];
$code[] = sprintf(
'$object = new %s(%s);',
$className,
implode(', ', $dumpedConstructorArguments)
);
// Property injections
foreach ($definition->getPropertyInjections() as $propertyInjection) {
$value = $propertyInjection->getValue();
$value = $this->compiler->compileValue($value);
$propertyClassName = $propertyInjection->getClassName() ?: $className;
$property = new ReflectionProperty($propertyClassName, $propertyInjection->getPropertyName());
if ($property->isPublic() && !(\PHP_VERSION_ID >= 80100 && $property->isReadOnly())) {
$code[] = sprintf('$object->%s = %s;', $propertyInjection->getPropertyName(), $value);
} else {
// Private/protected/readonly property
$code[] = sprintf(
'\DI\Definition\Resolver\ObjectCreator::setPrivatePropertyValue(%s, $object, \'%s\', %s);',
var_export($propertyInjection->getClassName(), true),
$propertyInjection->getPropertyName(),
$value
);
}
}
// Method injections
foreach ($definition->getMethodInjections() as $methodInjection) {
$methodReflection = new ReflectionMethod($className, $methodInjection->getMethodName());
$parameters = $this->resolveParameters($methodInjection, $methodReflection);
$dumpedParameters = array_map(function ($value) {
return $this->compiler->compileValue($value);
}, $parameters);
$code[] = sprintf(
'$object->%s(%s);',
$methodInjection->getMethodName(),
implode(', ', $dumpedParameters)
);
}
} catch (InvalidDefinition $e) {
throw InvalidDefinition::create($definition, sprintf(
'Entry "%s" cannot be compiled: %s',
$definition->getName(),
$e->getMessage()
));
}
return implode("\n ", $code);
}
public function resolveParameters(?MethodInjection $definition, ?ReflectionMethod $method) : array
{
$args = [];
if (! $method) {
return $args;
}
$definitionParameters = $definition ? $definition->getParameters() : [];
foreach ($method->getParameters() as $index => $parameter) {
if (array_key_exists($index, $definitionParameters)) {
// Look in the definition
$value = &$definitionParameters[$index];
} elseif ($parameter->isOptional()) {
// If the parameter is optional and wasn't specified, we take its default value
$args[] = $this->getParameterDefaultValue($parameter, $method);
continue;
} else {
throw new InvalidDefinition(sprintf(
'Parameter $%s of %s has no value defined or guessable',
$parameter->getName(),
$this->getFunctionName($method)
));
}
$args[] = &$value;
}
return $args;
}
private function compileLazyDefinition(ObjectDefinition $definition) : string
{
$subDefinition = clone $definition;
$subDefinition->setLazy(false);
$subDefinition = $this->compiler->compileValue($subDefinition);
/** @var class-string $className At this point we have checked the class is valid */
$className = $definition->getClassName();
$this->compiler->getProxyFactory()->generateProxyClass($className);
return <<<STR
\$object = \$this->proxyFactory->createProxy(
'{$definition->getClassName()}',
function (&\$wrappedObject, \$proxy, \$method, \$params, &\$initializer) {
\$wrappedObject = $subDefinition;
\$initializer = null; // turning off further lazy initialization
return true;
}
);
STR;
}
/**
* Returns the default value of a function parameter.
*
* @throws InvalidDefinition Can't get default values from PHP internal classes and functions
*/
private function getParameterDefaultValue(ReflectionParameter $parameter, ReflectionMethod $function) : mixed
{
try {
return $parameter->getDefaultValue();
} catch (\ReflectionException) {
throw new InvalidDefinition(sprintf(
'The parameter "%s" of %s has no type defined or guessable. It has a default value, '
. 'but the default value can\'t be read through Reflection because it is a PHP internal class.',
$parameter->getName(),
$this->getFunctionName($function)
));
}
}
private function getFunctionName(ReflectionMethod $method) : string
{
return $method->getName() . '()';
}
private function assertClassIsNotAnonymous(ObjectDefinition $definition) : void
{
if (str_contains($definition->getClassName(), '@')) {
throw InvalidDefinition::create($definition, sprintf(
'Entry "%s" cannot be compiled: anonymous classes cannot be compiled',
$definition->getName()
));
}
}
private function assertClassIsInstantiable(ObjectDefinition $definition) : void
{
if ($definition->isInstantiable()) {
return;
}
$message = ! $definition->classExists()
? 'Entry "%s" cannot be compiled: the class doesn\'t exist'
: 'Entry "%s" cannot be compiled: the class is not instantiable';
throw InvalidDefinition::create($definition, sprintf($message, $definition->getName()));
}
}

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace DI\Compiler;
use DI\Factory\RequestedEntry;
/**
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class RequestedEntryHolder implements RequestedEntry
{
public function __construct(
private string $name,
) {
}
public function getName() : string
{
return $this->name;
}
}

View File

@ -0,0 +1,16 @@
/**
* This class has been auto-generated by PHP-DI.
*/
class <?php echo $this->containerClass; ?> extends <?php echo $this->containerParentClass; ?>
{
const METHOD_MAPPING = <?php var_export($this->entryToMethodMapping); ?>;
<?php foreach ($this->methods as $methodName => $methodContent) { ?>
protected function <?php echo $methodName; ?>()
{
<?php echo $methodContent; ?>
}
<?php } ?>
}

View File

@ -0,0 +1,397 @@
<?php
declare(strict_types=1);
namespace DI;
use DI\Definition\Definition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\FactoryDefinition;
use DI\Definition\Helper\DefinitionHelper;
use DI\Definition\InstanceDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\Resolver\DefinitionResolver;
use DI\Definition\Resolver\ResolverDispatcher;
use DI\Definition\Source\DefinitionArray;
use DI\Definition\Source\MutableDefinitionSource;
use DI\Definition\Source\ReflectionBasedAutowiring;
use DI\Definition\Source\SourceChain;
use DI\Definition\ValueDefinition;
use DI\Invoker\DefinitionParameterResolver;
use DI\Proxy\ProxyFactory;
use InvalidArgumentException;
use Invoker\Invoker;
use Invoker\InvokerInterface;
use Invoker\ParameterResolver\AssociativeArrayResolver;
use Invoker\ParameterResolver\Container\TypeHintContainerResolver;
use Invoker\ParameterResolver\DefaultValueResolver;
use Invoker\ParameterResolver\NumericArrayResolver;
use Invoker\ParameterResolver\ResolverChain;
use Psr\Container\ContainerInterface;
/**
* Dependency Injection Container.
*
* @api
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class Container implements ContainerInterface, FactoryInterface, InvokerInterface
{
/**
* Map of entries that are already resolved.
*/
protected array $resolvedEntries = [];
private MutableDefinitionSource $definitionSource;
private DefinitionResolver $definitionResolver;
/**
* Map of definitions that are already fetched (local cache).
*
* @var array<Definition|null>
*/
private array $fetchedDefinitions = [];
/**
* Array of entries being resolved. Used to avoid circular dependencies and infinite loops.
*/
protected array $entriesBeingResolved = [];
private ?InvokerInterface $invoker = null;
/**
* Container that wraps this container. If none, points to $this.
*/
protected ContainerInterface $delegateContainer;
protected ProxyFactory $proxyFactory;
public static function create(
array $definitions
) : static {
$source = new SourceChain([new ReflectionBasedAutowiring]);
$source->setMutableDefinitionSource(new DefinitionArray($definitions, new ReflectionBasedAutowiring));
return new static($definitions);
}
/**
* Use `$container = new Container()` if you want a container with the default configuration.
*
* If you want to customize the container's behavior, you are discouraged to create and pass the
* dependencies yourself, the ContainerBuilder class is here to help you instead.
*
* @see ContainerBuilder
*
* @param ContainerInterface $wrapperContainer If the container is wrapped by another container.
*/
public function __construct(
array|MutableDefinitionSource $definitions = [],
ProxyFactory $proxyFactory = null,
ContainerInterface $wrapperContainer = null
) {
if (is_array($definitions)) {
$this->definitionSource = $this->createDefaultDefinitionSource($definitions);
} else {
$this->definitionSource = $definitions;
}
$this->delegateContainer = $wrapperContainer ?: $this;
$this->proxyFactory = $proxyFactory ?: new ProxyFactory;
$this->definitionResolver = new ResolverDispatcher($this->delegateContainer, $this->proxyFactory);
// Auto-register the container
$this->resolvedEntries = [
self::class => $this,
ContainerInterface::class => $this->delegateContainer,
FactoryInterface::class => $this,
InvokerInterface::class => $this,
];
}
/**
* Returns an entry of the container by its name.
*
* @template T
* @param string|class-string<T> $id Entry name or a class name.
*
* @return mixed|T
* @throws DependencyException Error while resolving the entry.
* @throws NotFoundException No entry found for the given name.
*/
public function get(string $id) : mixed
{
// If the entry is already resolved we return it
if (isset($this->resolvedEntries[$id]) || array_key_exists($id, $this->resolvedEntries)) {
return $this->resolvedEntries[$id];
}
$definition = $this->getDefinition($id);
if (! $definition) {
throw new NotFoundException("No entry or class found for '$id'");
}
$value = $this->resolveDefinition($definition);
$this->resolvedEntries[$id] = $value;
return $value;
}
private function getDefinition(string $name) : ?Definition
{
// Local cache that avoids fetching the same definition twice
if (!array_key_exists($name, $this->fetchedDefinitions)) {
$this->fetchedDefinitions[$name] = $this->definitionSource->getDefinition($name);
}
return $this->fetchedDefinitions[$name];
}
/**
* Build an entry of the container by its name.
*
* This method behave like get() except resolves the entry again every time.
* For example if the entry is a class then a new instance will be created each time.
*
* This method makes the container behave like a factory.
*
* @template T
* @param string|class-string<T> $name Entry name or a class name.
* @param array $parameters Optional parameters to use to build the entry. Use this to force
* specific parameters to specific values. Parameters not defined in this
* array will be resolved using the container.
*
* @return mixed|T
* @throws InvalidArgumentException The name parameter must be of type string.
* @throws DependencyException Error while resolving the entry.
* @throws NotFoundException No entry found for the given name.
*/
public function make(string $name, array $parameters = []) : mixed
{
$definition = $this->getDefinition($name);
if (! $definition) {
// If the entry is already resolved we return it
if (array_key_exists($name, $this->resolvedEntries)) {
return $this->resolvedEntries[$name];
}
throw new NotFoundException("No entry or class found for '$name'");
}
return $this->resolveDefinition($definition, $parameters);
}
public function has(string $id) : bool
{
if (array_key_exists($id, $this->resolvedEntries)) {
return true;
}
$definition = $this->getDefinition($id);
if ($definition === null) {
return false;
}
return $this->definitionResolver->isResolvable($definition);
}
/**
* Inject all dependencies on an existing instance.
*
* @template T
* @param object|T $instance Object to perform injection upon
* @return object|T $instance Returns the same instance
* @throws InvalidArgumentException
* @throws DependencyException Error while injecting dependencies
*/
public function injectOn(object $instance) : object
{
$className = $instance::class;
// If the class is anonymous, don't cache its definition
// Checking for anonymous classes is cleaner via Reflection, but also slower
$objectDefinition = str_contains($className, '@anonymous')
? $this->definitionSource->getDefinition($className)
: $this->getDefinition($className);
if (! $objectDefinition instanceof ObjectDefinition) {
return $instance;
}
$definition = new InstanceDefinition($instance, $objectDefinition);
$this->definitionResolver->resolve($definition);
return $instance;
}
/**
* Call the given function using the given parameters.
*
* Missing parameters will be resolved from the container.
*
* @param callable|array|string $callable Function to call.
* @param array $parameters Parameters to use. Can be indexed by the parameter names
* or not indexed (same order as the parameters).
* The array can also contain DI definitions, e.g. DI\get().
*
* @return mixed Result of the function.
*/
public function call($callable, array $parameters = []) : mixed
{
return $this->getInvoker()->call($callable, $parameters);
}
/**
* Define an object or a value in the container.
*
* @param string $name Entry name
* @param mixed|DefinitionHelper $value Value, use definition helpers to define objects
*/
public function set(string $name, mixed $value) : void
{
if ($value instanceof DefinitionHelper) {
$value = $value->getDefinition($name);
} elseif ($value instanceof \Closure) {
$value = new FactoryDefinition($name, $value);
}
if ($value instanceof ValueDefinition) {
$this->resolvedEntries[$name] = $value->getValue();
} elseif ($value instanceof Definition) {
$value->setName($name);
$this->setDefinition($name, $value);
} else {
$this->resolvedEntries[$name] = $value;
}
}
/**
* Get defined container entries.
*
* @return string[]
*/
public function getKnownEntryNames() : array
{
$entries = array_unique(array_merge(
array_keys($this->definitionSource->getDefinitions()),
array_keys($this->resolvedEntries)
));
sort($entries);
return $entries;
}
/**
* Get entry debug information.
*
* @param string $name Entry name
*
* @throws InvalidDefinition
* @throws NotFoundException
*/
public function debugEntry(string $name) : string
{
$definition = $this->definitionSource->getDefinition($name);
if ($definition instanceof Definition) {
return (string) $definition;
}
if (array_key_exists($name, $this->resolvedEntries)) {
return $this->getEntryType($this->resolvedEntries[$name]);
}
throw new NotFoundException("No entry or class found for '$name'");
}
/**
* Get formatted entry type.
*/
private function getEntryType(mixed $entry) : string
{
if (is_object($entry)) {
return sprintf("Object (\n class = %s\n)", $entry::class);
}
if (is_array($entry)) {
return preg_replace(['/^array \(/', '/\)$/'], ['[', ']'], var_export($entry, true));
}
if (is_string($entry)) {
return sprintf('Value (\'%s\')', $entry);
}
if (is_bool($entry)) {
return sprintf('Value (%s)', $entry === true ? 'true' : 'false');
}
return sprintf('Value (%s)', is_scalar($entry) ? (string) $entry : ucfirst(gettype($entry)));
}
/**
* Resolves a definition.
*
* Checks for circular dependencies while resolving the definition.
*
* @throws DependencyException Error while resolving the entry.
*/
private function resolveDefinition(Definition $definition, array $parameters = []) : mixed
{
$entryName = $definition->getName();
// Check if we are already getting this entry -> circular dependency
if (isset($this->entriesBeingResolved[$entryName])) {
throw new DependencyException("Circular dependency detected while trying to resolve entry '$entryName'");
}
$this->entriesBeingResolved[$entryName] = true;
// Resolve the definition
try {
$value = $this->definitionResolver->resolve($definition, $parameters);
} finally {
unset($this->entriesBeingResolved[$entryName]);
}
return $value;
}
protected function setDefinition(string $name, Definition $definition) : void
{
// Clear existing entry if it exists
if (array_key_exists($name, $this->resolvedEntries)) {
unset($this->resolvedEntries[$name]);
}
$this->fetchedDefinitions = []; // Completely clear this local cache
$this->definitionSource->addDefinition($definition);
}
private function getInvoker() : InvokerInterface
{
if (! $this->invoker) {
$parameterResolver = new ResolverChain([
new DefinitionParameterResolver($this->definitionResolver),
new NumericArrayResolver,
new AssociativeArrayResolver,
new DefaultValueResolver,
new TypeHintContainerResolver($this->delegateContainer),
]);
$this->invoker = new Invoker($parameterResolver, $this);
}
return $this->invoker;
}
private function createDefaultDefinitionSource(array $definitions) : SourceChain
{
$autowiring = new ReflectionBasedAutowiring;
$source = new SourceChain([$autowiring]);
$source->setMutableDefinitionSource(new DefinitionArray($definitions, $autowiring));
return $source;
}
}

View File

@ -0,0 +1,333 @@
<?php
declare(strict_types=1);
namespace DI;
use DI\Compiler\Compiler;
use DI\Definition\Source\AttributeBasedAutowiring;
use DI\Definition\Source\DefinitionArray;
use DI\Definition\Source\DefinitionFile;
use DI\Definition\Source\DefinitionSource;
use DI\Definition\Source\NoAutowiring;
use DI\Definition\Source\ReflectionBasedAutowiring;
use DI\Definition\Source\SourceCache;
use DI\Definition\Source\SourceChain;
use DI\Proxy\ProxyFactory;
use InvalidArgumentException;
use Psr\Container\ContainerInterface;
/**
* Helper to create and configure a Container.
*
* With the default options, the container created is appropriate for the development environment.
*
* Example:
*
* $builder = new ContainerBuilder();
* $container = $builder->build();
*
* @api
*
* @since 3.2
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*
* @psalm-template ContainerClass of Container
*/
class ContainerBuilder
{
/**
* Name of the container class, used to create the container.
* @var class-string<Container>
* @psalm-var class-string<ContainerClass>
*/
private string $containerClass;
/**
* Name of the container parent class, used on compiled container.
* @var class-string<Container>
* @psalm-var class-string<ContainerClass>
*/
private string $containerParentClass;
private bool $useAutowiring = true;
private bool $useAttributes = false;
/**
* If set, write the proxies to disk in this directory to improve performances.
*/
private ?string $proxyDirectory = null;
/**
* If PHP-DI is wrapped in another container, this references the wrapper.
*/
private ?ContainerInterface $wrapperContainer = null;
/**
* @var DefinitionSource[]|string[]|array[]
*/
private array $definitionSources = [];
/**
* Whether the container has already been built.
*/
private bool $locked = false;
private ?string $compileToDirectory = null;
private bool $sourceCache = false;
protected string $sourceCacheNamespace = '';
/**
* @param class-string<Container> $containerClass Name of the container class, used to create the container.
* @psalm-param class-string<ContainerClass> $containerClass
*/
public function __construct(string $containerClass = Container::class)
{
$this->containerClass = $containerClass;
}
/**
* Build and return a container.
*
* @return Container
* @psalm-return ContainerClass
*/
public function build()
{
$sources = array_reverse($this->definitionSources);
if ($this->useAttributes) {
$autowiring = new AttributeBasedAutowiring;
$sources[] = $autowiring;
} elseif ($this->useAutowiring) {
$autowiring = new ReflectionBasedAutowiring;
$sources[] = $autowiring;
} else {
$autowiring = new NoAutowiring;
}
$sources = array_map(function ($definitions) use ($autowiring) {
if (is_string($definitions)) {
// File
return new DefinitionFile($definitions, $autowiring);
}
if (is_array($definitions)) {
return new DefinitionArray($definitions, $autowiring);
}
return $definitions;
}, $sources);
$source = new SourceChain($sources);
// Mutable definition source
$source->setMutableDefinitionSource(new DefinitionArray([], $autowiring));
if ($this->sourceCache) {
if (!SourceCache::isSupported()) {
throw new \Exception('APCu is not enabled, PHP-DI cannot use it as a cache');
}
// Wrap the source with the cache decorator
$source = new SourceCache($source, $this->sourceCacheNamespace);
}
$proxyFactory = new ProxyFactory($this->proxyDirectory);
$this->locked = true;
$containerClass = $this->containerClass;
if ($this->compileToDirectory) {
$compiler = new Compiler($proxyFactory);
$compiledContainerFile = $compiler->compile(
$source,
$this->compileToDirectory,
$containerClass,
$this->containerParentClass,
$this->useAutowiring
);
// Only load the file if it hasn't been already loaded
// (the container can be created multiple times in the same process)
if (!class_exists($containerClass, false)) {
require $compiledContainerFile;
}
}
return new $containerClass($source, $proxyFactory, $this->wrapperContainer);
}
/**
* Compile the container for optimum performances.
*
* Be aware that the container is compiled once and never updated!
*
* Therefore:
*
* - in production you should clear that directory every time you deploy
* - in development you should not compile the container
*
* @see https://php-di.org/doc/performances.html
*
* @psalm-template T of CompiledContainer
*
* @param string $directory Directory in which to put the compiled container.
* @param string $containerClass Name of the compiled class. Customize only if necessary.
* @param class-string<Container> $containerParentClass Name of the compiled container parent class. Customize only if necessary.
* @psalm-param class-string<T> $containerParentClass
*
* @psalm-return self<T>
*/
public function enableCompilation(
string $directory,
string $containerClass = 'CompiledContainer',
string $containerParentClass = CompiledContainer::class
) : self {
$this->ensureNotLocked();
$this->compileToDirectory = $directory;
$this->containerClass = $containerClass;
$this->containerParentClass = $containerParentClass;
return $this;
}
/**
* Enable or disable the use of autowiring to guess injections.
*
* Enabled by default.
*
* @return $this
*/
public function useAutowiring(bool $bool) : self
{
$this->ensureNotLocked();
$this->useAutowiring = $bool;
return $this;
}
/**
* Enable or disable the use of PHP 8 attributes to configure injections.
*
* Disabled by default.
*
* @return $this
*/
public function useAttributes(bool $bool) : self
{
$this->ensureNotLocked();
$this->useAttributes = $bool;
return $this;
}
/**
* Configure the proxy generation.
*
* For dev environment, use `writeProxiesToFile(false)` (default configuration)
* For production environment, use `writeProxiesToFile(true, 'tmp/proxies')`
*
* @see https://php-di.org/doc/lazy-injection.html
*
* @param bool $writeToFile If true, write the proxies to disk to improve performances
* @param string|null $proxyDirectory Directory where to write the proxies
* @return $this
* @throws InvalidArgumentException when writeToFile is set to true and the proxy directory is null
*/
public function writeProxiesToFile(bool $writeToFile, string $proxyDirectory = null) : self
{
$this->ensureNotLocked();
if ($writeToFile && $proxyDirectory === null) {
throw new InvalidArgumentException(
'The proxy directory must be specified if you want to write proxies on disk'
);
}
$this->proxyDirectory = $writeToFile ? $proxyDirectory : null;
return $this;
}
/**
* If PHP-DI's container is wrapped by another container, we can
* set this so that PHP-DI will use the wrapper rather than itself for building objects.
*
* @return $this
*/
public function wrapContainer(ContainerInterface $otherContainer) : self
{
$this->ensureNotLocked();
$this->wrapperContainer = $otherContainer;
return $this;
}
/**
* Add definitions to the container.
*
* @param string|array|DefinitionSource ...$definitions Can be an array of definitions, the
* name of a file containing definitions
* or a DefinitionSource object.
* @return $this
*/
public function addDefinitions(string|array|DefinitionSource ...$definitions) : self
{
$this->ensureNotLocked();
foreach ($definitions as $definition) {
$this->definitionSources[] = $definition;
}
return $this;
}
/**
* Enables the use of APCu to cache definitions.
*
* You must have APCu enabled to use it.
*
* Before using this feature, you should try these steps first:
* - enable compilation if not already done (see `enableCompilation()`)
* - if you use autowiring or attributes, add all the classes you are using into your configuration so that
* PHP-DI knows about them and compiles them
* Once this is done, you can try to optimize performances further with APCu. It can also be useful if you use
* `Container::make()` instead of `get()` (`make()` calls cannot be compiled so they are not optimized).
*
* Remember to clear APCu on each deploy else your application will have a stale cache. Do not enable the cache
* in development environment: any change you will make to the code will be ignored because of the cache.
*
* @see https://php-di.org/doc/performances.html
*
* @param string $cacheNamespace use unique namespace per container when sharing a single APC memory pool to prevent cache collisions
* @return $this
*/
public function enableDefinitionCache(string $cacheNamespace = '') : self
{
$this->ensureNotLocked();
$this->sourceCache = true;
$this->sourceCacheNamespace = $cacheNamespace;
return $this;
}
/**
* Are we building a compiled container?
*/
public function isCompilationEnabled() : bool
{
return (bool) $this->compileToDirectory;
}
private function ensureNotLocked() : void
{
if ($this->locked) {
throw new \LogicException('The ContainerBuilder cannot be modified after the container has been built');
}
}
}

View File

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
/**
* Definition of an array containing values or references.
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ArrayDefinition implements Definition
{
/** Entry name. */
private string $name = '';
public function __construct(
private array $values,
) {
}
public function getName() : string
{
return $this->name;
}
public function setName(string $name) : void
{
$this->name = $name;
}
public function getValues() : array
{
return $this->values;
}
public function replaceNestedDefinitions(callable $replacer) : void
{
$this->values = array_map($replacer, $this->values);
}
public function __toString() : string
{
$str = '[' . \PHP_EOL;
foreach ($this->values as $key => $value) {
if (is_string($key)) {
$key = "'" . $key . "'";
}
$str .= ' ' . $key . ' => ';
if ($value instanceof Definition) {
$str .= str_replace(\PHP_EOL, \PHP_EOL . ' ', (string) $value);
} else {
$str .= var_export($value, true);
}
$str .= ',' . \PHP_EOL;
}
return $str . ']';
}
}

View File

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
use DI\Definition\Exception\InvalidDefinition;
/**
* Extends an array definition by adding new elements into it.
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ArrayDefinitionExtension extends ArrayDefinition implements ExtendsPreviousDefinition
{
private ?ArrayDefinition $subDefinition = null;
public function getValues() : array
{
if (! $this->subDefinition) {
return parent::getValues();
}
return array_merge($this->subDefinition->getValues(), parent::getValues());
}
public function setExtendedDefinition(Definition $definition) : void
{
if (! $definition instanceof ArrayDefinition) {
throw new InvalidDefinition(sprintf(
'Definition %s tries to add array entries but the previous definition is not an array',
$this->getName()
));
}
$this->subDefinition = $definition;
}
}

View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
/**
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class AutowireDefinition extends ObjectDefinition
{
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
/**
* Factory that decorates a sub-definition.
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class DecoratorDefinition extends FactoryDefinition implements Definition, ExtendsPreviousDefinition
{
private ?Definition $decorated = null;
public function setExtendedDefinition(Definition $definition) : void
{
$this->decorated = $definition;
}
public function getDecoratedDefinition() : ?Definition
{
return $this->decorated;
}
public function replaceNestedDefinitions(callable $replacer) : void
{
// no nested definitions
}
public function __toString() : string
{
return 'Decorate(' . $this->getName() . ')';
}
}

View File

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
use DI\Factory\RequestedEntry;
/**
* Definition.
*
* @internal This interface is internal to PHP-DI and may change between minor versions.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
interface Definition extends RequestedEntry, \Stringable
{
/**
* Returns the name of the entry in the container.
*/
public function getName() : string;
/**
* Set the name of the entry in the container.
*/
public function setName(string $name) : void;
/**
* Apply a callable that replaces the definitions nested in this definition.
*/
public function replaceNestedDefinitions(callable $replacer) : void;
/**
* Definitions can be cast to string for debugging information.
*/
public function __toString() : string;
}

View File

@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Dumper;
use DI\Definition\Definition;
use DI\Definition\ObjectDefinition;
use DI\Definition\ObjectDefinition\MethodInjection;
use ReflectionException;
/**
* Dumps object definitions to string for debugging purposes.
*
* @since 4.1
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ObjectDefinitionDumper
{
/**
* Returns the definition as string representation.
*/
public function dump(ObjectDefinition $definition) : string
{
$className = $definition->getClassName();
$classExist = class_exists($className) || interface_exists($className);
// Class
if (! $classExist) {
$warning = '#UNKNOWN# ';
} else {
$class = new \ReflectionClass($className);
$warning = $class->isInstantiable() ? '' : '#NOT INSTANTIABLE# ';
}
$str = sprintf(' class = %s%s', $warning, $className);
// Lazy
$str .= \PHP_EOL . ' lazy = ' . var_export($definition->isLazy(), true);
if ($classExist) {
// Constructor
$str .= $this->dumpConstructor($className, $definition);
// Properties
$str .= $this->dumpProperties($definition);
// Methods
$str .= $this->dumpMethods($className, $definition);
}
return sprintf('Object (' . \PHP_EOL . '%s' . \PHP_EOL . ')', $str);
}
/**
* @param class-string $className
*/
private function dumpConstructor(string $className, ObjectDefinition $definition) : string
{
$str = '';
$constructorInjection = $definition->getConstructorInjection();
if ($constructorInjection !== null) {
$parameters = $this->dumpMethodParameters($className, $constructorInjection);
$str .= sprintf(\PHP_EOL . ' __construct(' . \PHP_EOL . ' %s' . \PHP_EOL . ' )', $parameters);
}
return $str;
}
private function dumpProperties(ObjectDefinition $definition) : string
{
$str = '';
foreach ($definition->getPropertyInjections() as $propertyInjection) {
$value = $propertyInjection->getValue();
$valueStr = $value instanceof Definition ? (string) $value : var_export($value, true);
$str .= sprintf(\PHP_EOL . ' $%s = %s', $propertyInjection->getPropertyName(), $valueStr);
}
return $str;
}
/**
* @param class-string $className
*/
private function dumpMethods(string $className, ObjectDefinition $definition) : string
{
$str = '';
foreach ($definition->getMethodInjections() as $methodInjection) {
$parameters = $this->dumpMethodParameters($className, $methodInjection);
$str .= sprintf(\PHP_EOL . ' %s(' . \PHP_EOL . ' %s' . \PHP_EOL . ' )', $methodInjection->getMethodName(), $parameters);
}
return $str;
}
/**
* @param class-string $className
*/
private function dumpMethodParameters(string $className, MethodInjection $methodInjection) : string
{
$methodReflection = new \ReflectionMethod($className, $methodInjection->getMethodName());
$args = [];
$definitionParameters = $methodInjection->getParameters();
foreach ($methodReflection->getParameters() as $index => $parameter) {
if (array_key_exists($index, $definitionParameters)) {
$value = $definitionParameters[$index];
$valueStr = $value instanceof Definition ? (string) $value : var_export($value, true);
$args[] = sprintf('$%s = %s', $parameter->getName(), $valueStr);
continue;
}
// If the parameter is optional and wasn't specified, we take its default value
if ($parameter->isOptional()) {
try {
$value = $parameter->getDefaultValue();
$args[] = sprintf(
'$%s = (default value) %s',
$parameter->getName(),
var_export($value, true)
);
continue;
} catch (ReflectionException) {
// The default value can't be read through Reflection because it is a PHP internal class
}
}
$args[] = sprintf('$%s = #UNDEFINED#', $parameter->getName());
}
return implode(\PHP_EOL . ' ', $args);
}
}

View File

@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
/**
* Defines a reference to an environment variable, with fallback to a default
* value if the environment variable is not defined.
*
* @author James Harris <james.harris@icecave.com.au>
*/
class EnvironmentVariableDefinition implements Definition
{
/** Entry name. */
private string $name = '';
/**
* @param string $variableName The name of the environment variable
* @param bool $isOptional Whether or not the environment variable definition is optional. If true and the environment variable given by $variableName has not been defined, $defaultValue is used.
* @param mixed $defaultValue The default value to use if the environment variable is optional and not provided
*/
public function __construct(
private string $variableName,
private bool $isOptional = false,
private mixed $defaultValue = null,
) {
}
public function getName() : string
{
return $this->name;
}
public function setName(string $name) : void
{
$this->name = $name;
}
/**
* @return string The name of the environment variable
*/
public function getVariableName() : string
{
return $this->variableName;
}
/**
* @return bool Whether or not the environment variable definition is optional
*/
public function isOptional() : bool
{
return $this->isOptional;
}
/**
* @return mixed The default value to use if the environment variable is optional and not provided
*/
public function getDefaultValue() : mixed
{
return $this->defaultValue;
}
public function replaceNestedDefinitions(callable $replacer) : void
{
$this->defaultValue = $replacer($this->defaultValue);
}
public function __toString() : string
{
$str = ' variable = ' . $this->variableName . \PHP_EOL
. ' optional = ' . ($this->isOptional ? 'yes' : 'no');
if ($this->isOptional) {
if ($this->defaultValue instanceof Definition) {
$nestedDefinition = (string) $this->defaultValue;
$defaultValueStr = str_replace(\PHP_EOL, \PHP_EOL . ' ', $nestedDefinition);
} else {
$defaultValueStr = var_export($this->defaultValue, true);
}
$str .= \PHP_EOL . ' default = ' . $defaultValueStr;
}
return sprintf('Environment variable (' . \PHP_EOL . '%s' . \PHP_EOL . ')', $str);
}
}

View File

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Exception;
/**
* Error in the definitions using PHP attributes.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class InvalidAttribute extends InvalidDefinition
{
}

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Exception;
use DI\Definition\Definition;
use Psr\Container\ContainerExceptionInterface;
/**
* Invalid DI definitions.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class InvalidDefinition extends \Exception implements ContainerExceptionInterface
{
public static function create(Definition $definition, string $message, \Exception $previous = null) : self
{
return new self(sprintf(
'%s' . \PHP_EOL . 'Full definition:' . \PHP_EOL . '%s',
$message,
(string) $definition
), 0, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
/**
* A definition that extends a previous definition with the same name.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
interface ExtendsPreviousDefinition extends Definition
{
public function setExtendedDefinition(Definition $definition) : void;
}

View File

@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
/**
* Definition of a value or class with a factory.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class FactoryDefinition implements Definition
{
/**
* Entry name.
*/
private string $name;
/**
* Callable that returns the value.
* @var callable
*/
private $factory;
/**
* Factory parameters.
* @var mixed[]
*/
private array $parameters;
/**
* @param string $name Entry name
* @param callable|array|string $factory Callable that returns the value associated to the entry name.
* @param array $parameters Parameters to be passed to the callable
*/
public function __construct(string $name, callable|array|string $factory, array $parameters = [])
{
$this->name = $name;
$this->factory = $factory;
$this->parameters = $parameters;
}
public function getName() : string
{
return $this->name;
}
public function setName(string $name) : void
{
$this->name = $name;
}
/**
* @return callable|array|string Callable that returns the value associated to the entry name.
*/
public function getCallable() : callable|array|string
{
return $this->factory;
}
/**
* @return array Array containing the parameters to be passed to the callable, indexed by name.
*/
public function getParameters() : array
{
return $this->parameters;
}
public function replaceNestedDefinitions(callable $replacer) : void
{
$this->parameters = array_map($replacer, $this->parameters);
}
public function __toString() : string
{
return 'Factory';
}
}

View File

@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Helper;
use DI\Definition\AutowireDefinition;
/**
* Helps defining how to create an instance of a class using autowiring.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class AutowireDefinitionHelper extends CreateDefinitionHelper
{
public const DEFINITION_CLASS = AutowireDefinition::class;
/**
* Defines a value for a specific argument of the constructor.
*
* This method is usually used together with attributes or autowiring, when a parameter
* is not (or cannot be) type-hinted. Using this method instead of constructor() allows to
* avoid defining all the parameters (letting them being resolved using attributes or autowiring)
* and only define one.
*
* @param string|int $parameter Parameter name of position for which the value will be given.
* @param mixed $value Value to give to this parameter.
*
* @return $this
*/
public function constructorParameter(string|int $parameter, mixed $value) : self
{
$this->constructor[$parameter] = $value;
return $this;
}
/**
* Defines a method to call and a value for a specific argument.
*
* This method is usually used together with attributes or autowiring, when a parameter
* is not (or cannot be) type-hinted. Using this method instead of method() allows to
* avoid defining all the parameters (letting them being resolved using attributes or
* autowiring) and only define one.
*
* If multiple calls to the method have been configured already (e.g. in a previous definition)
* then this method only overrides the parameter for the *first* call.
*
* @param string $method Name of the method to call.
* @param string|int $parameter Parameter name of position for which the value will be given.
* @param mixed $value Value to give to this parameter.
*
* @return $this
*/
public function methodParameter(string $method, string|int $parameter, mixed $value) : self
{
// Special case for the constructor
if ($method === '__construct') {
$this->constructor[$parameter] = $value;
return $this;
}
if (! isset($this->methods[$method])) {
$this->methods[$method] = [0 => []];
}
$this->methods[$method][0][$parameter] = $value;
return $this;
}
}

View File

@ -0,0 +1,189 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Helper;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\ObjectDefinition\MethodInjection;
use DI\Definition\ObjectDefinition\PropertyInjection;
/**
* Helps defining how to create an instance of a class.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class CreateDefinitionHelper implements DefinitionHelper
{
private const DEFINITION_CLASS = ObjectDefinition::class;
private ?string $className;
private ?bool $lazy = null;
/**
* Array of constructor parameters.
*/
protected array $constructor = [];
/**
* Array of properties and their value.
*/
private array $properties = [];
/**
* Array of methods and their parameters.
*/
protected array $methods = [];
/**
* Helper for defining an object.
*
* @param string|null $className Class name of the object.
* If null, the name of the entry (in the container) will be used as class name.
*/
public function __construct(string $className = null)
{
$this->className = $className;
}
/**
* Define the entry as lazy.
*
* A lazy entry is created only when it is used, a proxy is injected instead.
*
* @return $this
*/
public function lazy() : self
{
$this->lazy = true;
return $this;
}
/**
* Defines the arguments to use to call the constructor.
*
* This method takes a variable number of arguments, example:
* ->constructor($param1, $param2, $param3)
*
* @param mixed ...$parameters Parameters to use for calling the constructor of the class.
*
* @return $this
*/
public function constructor(mixed ...$parameters) : self
{
$this->constructor = $parameters;
return $this;
}
/**
* Defines a value to inject in a property of the object.
*
* @param string $property Entry in which to inject the value.
* @param mixed $value Value to inject in the property.
*
* @return $this
*/
public function property(string $property, mixed $value) : self
{
$this->properties[$property] = $value;
return $this;
}
/**
* Defines a method to call and the arguments to use.
*
* This method takes a variable number of arguments after the method name, example:
*
* ->method('myMethod', $param1, $param2)
*
* Can be used multiple times to declare multiple calls.
*
* @param string $method Name of the method to call.
* @param mixed ...$parameters Parameters to use for calling the method.
*
* @return $this
*/
public function method(string $method, mixed ...$parameters) : self
{
if (! isset($this->methods[$method])) {
$this->methods[$method] = [];
}
$this->methods[$method][] = $parameters;
return $this;
}
public function getDefinition(string $entryName) : ObjectDefinition
{
$class = $this::DEFINITION_CLASS;
/** @var ObjectDefinition $definition */
$definition = new $class($entryName, $this->className);
if ($this->lazy !== null) {
$definition->setLazy($this->lazy);
}
if (! empty($this->constructor)) {
$parameters = $this->fixParameters($definition, '__construct', $this->constructor);
$constructorInjection = MethodInjection::constructor($parameters);
$definition->setConstructorInjection($constructorInjection);
}
if (! empty($this->properties)) {
foreach ($this->properties as $property => $value) {
$definition->addPropertyInjection(
new PropertyInjection($property, $value)
);
}
}
if (! empty($this->methods)) {
foreach ($this->methods as $method => $calls) {
foreach ($calls as $parameters) {
$parameters = $this->fixParameters($definition, $method, $parameters);
$methodInjection = new MethodInjection($method, $parameters);
$definition->addMethodInjection($methodInjection);
}
}
}
return $definition;
}
/**
* Fixes parameters indexed by the parameter name -> reindex by position.
*
* This is necessary so that merging definitions between sources is possible.
*
* @throws InvalidDefinition
*/
private function fixParameters(ObjectDefinition $definition, string $method, array $parameters) : array
{
$fixedParameters = [];
foreach ($parameters as $index => $parameter) {
// Parameter indexed by the parameter name, we reindex it with its position
if (is_string($index)) {
$callable = [$definition->getClassName(), $method];
try {
$reflectionParameter = new \ReflectionParameter($callable, $index);
} catch (\ReflectionException $e) {
throw InvalidDefinition::create($definition, sprintf("Parameter with name '%s' could not be found. %s.", $index, $e->getMessage()));
}
$index = $reflectionParameter->getPosition();
}
$fixedParameters[$index] = $parameter;
}
return $fixedParameters;
}
}

View File

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Helper;
use DI\Definition\Definition;
/**
* Helps defining container entries.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
interface DefinitionHelper
{
/**
* @param string $entryName Container entry name
*/
public function getDefinition(string $entryName) : Definition;
}

View File

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Helper;
use DI\Definition\DecoratorDefinition;
use DI\Definition\FactoryDefinition;
/**
* Helps defining how to create an instance of a class using a factory (callable).
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class FactoryDefinitionHelper implements DefinitionHelper
{
/**
* @var callable
*/
private $factory;
private bool $decorate;
private array $parameters = [];
/**
* @param bool $decorate Is the factory decorating a previous definition?
*/
public function __construct(callable|array|string $factory, bool $decorate = false)
{
$this->factory = $factory;
$this->decorate = $decorate;
}
public function getDefinition(string $entryName) : FactoryDefinition
{
if ($this->decorate) {
return new DecoratorDefinition($entryName, $this->factory, $this->parameters);
}
return new FactoryDefinition($entryName, $this->factory, $this->parameters);
}
/**
* Defines arguments to pass to the factory.
*
* Because factory methods do not yet support attributes or autowiring, this method
* should be used to define all parameters except the ContainerInterface and RequestedEntry.
*
* Multiple calls can be made to the method to override individual values.
*
* @param string $parameter Name or index of the parameter for which the value will be given.
* @param mixed $value Value to give to this parameter.
*
* @return $this
*/
public function parameter(string $parameter, mixed $value) : self
{
$this->parameters[$parameter] = $value;
return $this;
}
}

View File

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
/**
* Defines injections on an existing class instance.
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class InstanceDefinition implements Definition
{
/**
* @param object $instance Instance on which to inject dependencies.
*/
public function __construct(
private object $instance,
private ObjectDefinition $objectDefinition,
) {
}
public function getName() : string
{
// Name are superfluous for instance definitions
return '';
}
public function setName(string $name) : void
{
// Name are superfluous for instance definitions
}
public function getInstance() : object
{
return $this->instance;
}
public function getObjectDefinition() : ObjectDefinition
{
return $this->objectDefinition;
}
public function replaceNestedDefinitions(callable $replacer) : void
{
$this->objectDefinition->replaceNestedDefinitions($replacer);
}
public function __toString() : string
{
return 'Instance';
}
}

View File

@ -0,0 +1,242 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
use DI\Definition\Dumper\ObjectDefinitionDumper;
use DI\Definition\ObjectDefinition\MethodInjection;
use DI\Definition\ObjectDefinition\PropertyInjection;
use DI\Definition\Source\DefinitionArray;
use ReflectionClass;
/**
* Defines how an object can be instantiated.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ObjectDefinition implements Definition
{
/**
* Entry name (most of the time, same as $classname).
*/
private string $name;
/**
* Class name (if null, then the class name is $name).
*/
protected ?string $className = null;
protected ?MethodInjection $constructorInjection = null;
protected array $propertyInjections = [];
/**
* Method calls.
* @var MethodInjection[][]
*/
protected array $methodInjections = [];
protected ?bool $lazy = null;
/**
* Store if the class exists. Storing it (in cache) avoids recomputing this.
*/
private bool $classExists;
/**
* Store if the class is instantiable. Storing it (in cache) avoids recomputing this.
*/
private bool $isInstantiable;
/**
* @param string $name Entry name
*/
public function __construct(string $name, string $className = null)
{
$this->name = $name;
$this->setClassName($className);
}
public function getName() : string
{
return $this->name;
}
public function setName(string $name) : void
{
$this->name = $name;
}
public function setClassName(?string $className) : void
{
$this->className = $className;
$this->updateCache();
}
public function getClassName() : string
{
return $this->className ?? $this->name;
}
public function getConstructorInjection() : ?MethodInjection
{
return $this->constructorInjection;
}
public function setConstructorInjection(MethodInjection $constructorInjection) : void
{
$this->constructorInjection = $constructorInjection;
}
public function completeConstructorInjection(MethodInjection $injection) : void
{
if ($this->constructorInjection !== null) {
// Merge
$this->constructorInjection->merge($injection);
} else {
// Set
$this->constructorInjection = $injection;
}
}
/**
* @return PropertyInjection[] Property injections
*/
public function getPropertyInjections() : array
{
return $this->propertyInjections;
}
public function addPropertyInjection(PropertyInjection $propertyInjection) : void
{
$className = $propertyInjection->getClassName();
if ($className) {
// Index with the class name to avoid collisions between parent and
// child private properties with the same name
$key = $className . '::' . $propertyInjection->getPropertyName();
} else {
$key = $propertyInjection->getPropertyName();
}
$this->propertyInjections[$key] = $propertyInjection;
}
/**
* @return MethodInjection[] Method injections
*/
public function getMethodInjections() : array
{
// Return array leafs
$injections = [];
array_walk_recursive($this->methodInjections, function ($injection) use (&$injections) {
$injections[] = $injection;
});
return $injections;
}
public function addMethodInjection(MethodInjection $methodInjection) : void
{
$method = $methodInjection->getMethodName();
if (! isset($this->methodInjections[$method])) {
$this->methodInjections[$method] = [];
}
$this->methodInjections[$method][] = $methodInjection;
}
public function completeFirstMethodInjection(MethodInjection $injection) : void
{
$method = $injection->getMethodName();
if (isset($this->methodInjections[$method][0])) {
// Merge
$this->methodInjections[$method][0]->merge($injection);
} else {
// Set
$this->addMethodInjection($injection);
}
}
public function setLazy(bool $lazy = null) : void
{
$this->lazy = $lazy;
}
public function isLazy() : bool
{
if ($this->lazy !== null) {
return $this->lazy;
}
// Default value
return false;
}
public function classExists() : bool
{
return $this->classExists;
}
public function isInstantiable() : bool
{
return $this->isInstantiable;
}
public function replaceNestedDefinitions(callable $replacer) : void
{
array_walk($this->propertyInjections, function (PropertyInjection $propertyInjection) use ($replacer) {
$propertyInjection->replaceNestedDefinition($replacer);
});
$this->constructorInjection?->replaceNestedDefinitions($replacer);
array_walk($this->methodInjections, function ($injectionArray) use ($replacer) {
array_walk($injectionArray, function (MethodInjection $methodInjection) use ($replacer) {
$methodInjection->replaceNestedDefinitions($replacer);
});
});
}
/**
* Replaces all the wildcards in the string with the given replacements.
*
* @param string[] $replacements
*/
public function replaceWildcards(array $replacements) : void
{
$className = $this->getClassName();
foreach ($replacements as $replacement) {
$pos = strpos($className, DefinitionArray::WILDCARD);
if ($pos !== false) {
$className = substr_replace($className, $replacement, $pos, 1);
}
}
$this->setClassName($className);
}
public function __toString() : string
{
return (new ObjectDefinitionDumper)->dump($this);
}
private function updateCache() : void
{
$className = $this->getClassName();
$this->classExists = class_exists($className) || interface_exists($className);
if (! $this->classExists) {
$this->isInstantiable = false;
return;
}
/** @var class-string $className */
$class = new ReflectionClass($className);
$this->isInstantiable = $class->isInstantiable();
}
}

View File

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace DI\Definition\ObjectDefinition;
use DI\Definition\Definition;
/**
* Describe an injection in an object method.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class MethodInjection implements Definition
{
/**
* @param mixed[] $parameters
*/
public function __construct(
private string $methodName,
private array $parameters = [],
) {
}
public static function constructor(array $parameters = []) : self
{
return new self('__construct', $parameters);
}
public function getMethodName() : string
{
return $this->methodName;
}
/**
* @return mixed[]
*/
public function getParameters() : array
{
return $this->parameters;
}
/**
* Replace the parameters of the definition by a new array of parameters.
*/
public function replaceParameters(array $parameters) : void
{
$this->parameters = $parameters;
}
public function merge(self $definition) : void
{
// In case of conflicts, the current definition prevails.
$this->parameters += $definition->parameters;
}
public function getName() : string
{
return '';
}
public function setName(string $name) : void
{
// The name does not matter for method injections
}
public function replaceNestedDefinitions(callable $replacer) : void
{
$this->parameters = array_map($replacer, $this->parameters);
}
public function __toString() : string
{
return sprintf('method(%s)', $this->methodName);
}
}

View File

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace DI\Definition\ObjectDefinition;
/**
* Describe an injection in a class property.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class PropertyInjection
{
private string $propertyName;
/**
* Value that should be injected in the property.
*/
private mixed $value;
/**
* Use for injecting in properties of parent classes: the class name
* must be the name of the parent class because private properties
* can be attached to the parent classes, not the one we are resolving.
*/
private ?string $className;
/**
* @param string $propertyName Property name
* @param mixed $value Value that should be injected in the property
*/
public function __construct(string $propertyName, mixed $value, string $className = null)
{
$this->propertyName = $propertyName;
$this->value = $value;
$this->className = $className;
}
public function getPropertyName() : string
{
return $this->propertyName;
}
/**
* @return mixed Value that should be injected in the property
*/
public function getValue() : mixed
{
return $this->value;
}
public function getClassName() : ?string
{
return $this->className;
}
public function replaceNestedDefinition(callable $replacer) : void
{
$this->value = $replacer($this->value);
}
}

View File

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
use Psr\Container\ContainerInterface;
/**
* Represents a reference to another entry.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class Reference implements Definition, SelfResolvingDefinition
{
/** Entry name. */
private string $name = '';
/**
* @param string $targetEntryName Name of the target entry
*/
public function __construct(
private string $targetEntryName,
) {
}
public function getName() : string
{
return $this->name;
}
public function setName(string $name) : void
{
$this->name = $name;
}
public function getTargetEntryName() : string
{
return $this->targetEntryName;
}
public function resolve(ContainerInterface $container) : mixed
{
return $container->get($this->getTargetEntryName());
}
public function isResolvable(ContainerInterface $container) : bool
{
return $container->has($this->getTargetEntryName());
}
public function replaceNestedDefinitions(callable $replacer) : void
{
// no nested definitions
}
public function __toString() : string
{
return sprintf(
'get(%s)',
$this->targetEntryName
);
}
}

View File

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\ArrayDefinition;
use DI\Definition\Definition;
use DI\DependencyException;
use Exception;
/**
* Resolves an array definition to a value.
*
* @template-implements DefinitionResolver<ArrayDefinition>
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ArrayResolver implements DefinitionResolver
{
/**
* @param DefinitionResolver $definitionResolver Used to resolve nested definitions.
*/
public function __construct(
private DefinitionResolver $definitionResolver
) {
}
/**
* {@inheritDoc}
*
* Resolve an array definition to a value.
*
* An array definition can contain simple values or references to other entries.
*
* @param ArrayDefinition $definition
*/
public function resolve(Definition $definition, array $parameters = []) : array
{
$values = $definition->getValues();
// Resolve nested definitions
array_walk_recursive($values, function (& $value, $key) use ($definition) {
if ($value instanceof Definition) {
$value = $this->resolveDefinition($value, $definition, $key);
}
});
return $values;
}
public function isResolvable(Definition $definition, array $parameters = []) : bool
{
return true;
}
/**
* @throws DependencyException
*/
private function resolveDefinition(Definition $value, ArrayDefinition $definition, int|string $key) : mixed
{
try {
return $this->definitionResolver->resolve($value);
} catch (DependencyException $e) {
throw $e;
} catch (Exception $e) {
throw new DependencyException(sprintf(
'Error while resolving %s[%s]. %s',
$definition->getName(),
$key,
$e->getMessage()
), 0, $e);
}
}
}

View File

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\DecoratorDefinition;
use DI\Definition\Definition;
use DI\Definition\Exception\InvalidDefinition;
use Psr\Container\ContainerInterface;
/**
* Resolves a decorator definition to a value.
*
* @template-implements DefinitionResolver<DecoratorDefinition>
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class DecoratorResolver implements DefinitionResolver
{
/**
* The resolver needs a container. This container will be passed to the factory as a parameter
* so that the factory can access other entries of the container.
*
* @param DefinitionResolver $definitionResolver Used to resolve nested definitions.
*/
public function __construct(
private ContainerInterface $container,
private DefinitionResolver $definitionResolver
) {
}
/**
* Resolve a decorator definition to a value.
*
* This will call the callable of the definition and pass it the decorated entry.
*
* @param DecoratorDefinition $definition
*/
public function resolve(Definition $definition, array $parameters = []) : mixed
{
$callable = $definition->getCallable();
if (! is_callable($callable)) {
throw new InvalidDefinition(sprintf(
'The decorator "%s" is not callable',
$definition->getName()
));
}
$decoratedDefinition = $definition->getDecoratedDefinition();
if (! $decoratedDefinition instanceof Definition) {
if (! $definition->getName()) {
throw new InvalidDefinition('Decorators cannot be nested in another definition');
}
throw new InvalidDefinition(sprintf(
'Entry "%s" decorates nothing: no previous definition with the same name was found',
$definition->getName()
));
}
$decorated = $this->definitionResolver->resolve($decoratedDefinition, $parameters);
return $callable($decorated, $this->container);
}
public function isResolvable(Definition $definition, array $parameters = []) : bool
{
return true;
}
}

View File

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\Definition;
use DI\Definition\Exception\InvalidDefinition;
use DI\DependencyException;
/**
* Resolves a definition to a value.
*
* @since 4.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*
* @template T of Definition
*/
interface DefinitionResolver
{
/**
* Resolve a definition to a value.
*
* @param Definition $definition Object that defines how the value should be obtained.
* @psalm-param T $definition
* @param array $parameters Optional parameters to use to build the entry.
* @return mixed Value obtained from the definition.
*
* @throws InvalidDefinition If the definition cannot be resolved.
* @throws DependencyException
*/
public function resolve(Definition $definition, array $parameters = []) : mixed;
/**
* Check if a definition can be resolved.
*
* @param Definition $definition Object that defines how the value should be obtained.
* @psalm-param T $definition
* @param array $parameters Optional parameters to use to build the entry.
*/
public function isResolvable(Definition $definition, array $parameters = []) : bool;
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\Definition;
use DI\Definition\EnvironmentVariableDefinition;
use DI\Definition\Exception\InvalidDefinition;
/**
* Resolves a environment variable definition to a value.
*
* @template-implements DefinitionResolver<EnvironmentVariableDefinition>
*
* @author James Harris <james.harris@icecave.com.au>
*/
class EnvironmentVariableResolver implements DefinitionResolver
{
/** @var callable */
private $variableReader;
public function __construct(
private DefinitionResolver $definitionResolver,
$variableReader = null
) {
$this->variableReader = $variableReader ?? [$this, 'getEnvVariable'];
}
/**
* Resolve an environment variable definition to a value.
*
* @param EnvironmentVariableDefinition $definition
*/
public function resolve(Definition $definition, array $parameters = []) : mixed
{
$value = call_user_func($this->variableReader, $definition->getVariableName());
if (false !== $value) {
return $value;
}
if (!$definition->isOptional()) {
throw new InvalidDefinition(sprintf(
"The environment variable '%s' has not been defined",
$definition->getVariableName()
));
}
$value = $definition->getDefaultValue();
// Nested definition
if ($value instanceof Definition) {
return $this->definitionResolver->resolve($value);
}
return $value;
}
public function isResolvable(Definition $definition, array $parameters = []) : bool
{
return true;
}
protected function getEnvVariable(string $variableName)
{
return $_ENV[$variableName] ?? $_SERVER[$variableName] ?? getenv($variableName);
}
}

View File

@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\Definition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\FactoryDefinition;
use DI\Invoker\FactoryParameterResolver;
use Invoker\Exception\NotCallableException;
use Invoker\Exception\NotEnoughParametersException;
use Invoker\Invoker;
use Invoker\ParameterResolver\AssociativeArrayResolver;
use Invoker\ParameterResolver\DefaultValueResolver;
use Invoker\ParameterResolver\NumericArrayResolver;
use Invoker\ParameterResolver\ResolverChain;
use Psr\Container\ContainerInterface;
/**
* Resolves a factory definition to a value.
*
* @template-implements DefinitionResolver<FactoryDefinition>
*
* @since 4.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class FactoryResolver implements DefinitionResolver
{
private ?Invoker $invoker = null;
/**
* The resolver needs a container. This container will be passed to the factory as a parameter
* so that the factory can access other entries of the container.
*/
public function __construct(
private ContainerInterface $container,
private DefinitionResolver $resolver,
) {
}
/**
* Resolve a factory definition to a value.
*
* This will call the callable of the definition.
*
* @param FactoryDefinition $definition
*/
public function resolve(Definition $definition, array $parameters = []) : mixed
{
if (! $this->invoker) {
$parameterResolver = new ResolverChain([
new AssociativeArrayResolver,
new FactoryParameterResolver($this->container),
new NumericArrayResolver,
new DefaultValueResolver,
]);
$this->invoker = new Invoker($parameterResolver, $this->container);
}
$callable = $definition->getCallable();
try {
$providedParams = [$this->container, $definition];
$extraParams = $this->resolveExtraParams($definition->getParameters());
$providedParams = array_merge($providedParams, $extraParams, $parameters);
return $this->invoker->call($callable, $providedParams);
} catch (NotCallableException $e) {
// Custom error message to help debugging
if (is_string($callable) && class_exists($callable) && method_exists($callable, '__invoke')) {
throw new InvalidDefinition(sprintf(
'Entry "%s" cannot be resolved: factory %s. Invokable classes cannot be automatically resolved if autowiring is disabled on the container, you need to enable autowiring or define the entry manually.',
$definition->getName(),
$e->getMessage()
));
}
throw new InvalidDefinition(sprintf(
'Entry "%s" cannot be resolved: factory %s',
$definition->getName(),
$e->getMessage()
));
} catch (NotEnoughParametersException $e) {
throw new InvalidDefinition(sprintf(
'Entry "%s" cannot be resolved: %s',
$definition->getName(),
$e->getMessage()
));
}
}
public function isResolvable(Definition $definition, array $parameters = []) : bool
{
return true;
}
private function resolveExtraParams(array $params) : array
{
$resolved = [];
foreach ($params as $key => $value) {
// Nested definitions
if ($value instanceof Definition) {
$value = $this->resolver->resolve($value);
}
$resolved[$key] = $value;
}
return $resolved;
}
}

View File

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\Definition;
use DI\Definition\InstanceDefinition;
use DI\DependencyException;
use Psr\Container\NotFoundExceptionInterface;
/**
* Injects dependencies on an existing instance.
*
* @template-implements DefinitionResolver<InstanceDefinition>
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class InstanceInjector extends ObjectCreator implements DefinitionResolver
{
/**
* Injects dependencies on an existing instance.
*
* @param InstanceDefinition $definition
* @psalm-suppress ImplementedParamTypeMismatch
*/
public function resolve(Definition $definition, array $parameters = []) : ?object
{
/** @psalm-suppress InvalidCatch */
try {
$this->injectMethodsAndProperties($definition->getInstance(), $definition->getObjectDefinition());
} catch (NotFoundExceptionInterface $e) {
$message = sprintf(
'Error while injecting dependencies into %s: %s',
get_class($definition->getInstance()),
$e->getMessage()
);
throw new DependencyException($message, 0, $e);
}
return $definition;
}
public function isResolvable(Definition $definition, array $parameters = []) : bool
{
return true;
}
}

View File

@ -0,0 +1,207 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\Definition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\ObjectDefinition\PropertyInjection;
use DI\DependencyException;
use DI\Proxy\ProxyFactory;
use Exception;
use ProxyManager\Proxy\LazyLoadingInterface;
use Psr\Container\NotFoundExceptionInterface;
use ReflectionClass;
use ReflectionProperty;
/**
* Create objects based on an object definition.
*
* @template-implements DefinitionResolver<ObjectDefinition>
*
* @since 4.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ObjectCreator implements DefinitionResolver
{
private ParameterResolver $parameterResolver;
/**
* @param DefinitionResolver $definitionResolver Used to resolve nested definitions.
* @param ProxyFactory $proxyFactory Used to create proxies for lazy injections.
*/
public function __construct(
private DefinitionResolver $definitionResolver,
private ProxyFactory $proxyFactory
) {
$this->parameterResolver = new ParameterResolver($definitionResolver);
}
/**
* Resolve a class definition to a value.
*
* This will create a new instance of the class using the injections points defined.
*
* @param ObjectDefinition $definition
*/
public function resolve(Definition $definition, array $parameters = []) : ?object
{
// Lazy?
if ($definition->isLazy()) {
return $this->createProxy($definition, $parameters);
}
return $this->createInstance($definition, $parameters);
}
/**
* The definition is not resolvable if the class is not instantiable (interface or abstract)
* or if the class doesn't exist.
*
* @param ObjectDefinition $definition
*/
public function isResolvable(Definition $definition, array $parameters = []) : bool
{
return $definition->isInstantiable();
}
/**
* Returns a proxy instance.
*/
private function createProxy(ObjectDefinition $definition, array $parameters) : LazyLoadingInterface
{
/** @var class-string $className */
$className = $definition->getClassName();
return $this->proxyFactory->createProxy(
$className,
function (& $wrappedObject, $proxy, $method, $params, & $initializer) use ($definition, $parameters) {
$wrappedObject = $this->createInstance($definition, $parameters);
$initializer = null; // turning off further lazy initialization
return true;
}
);
}
/**
* Creates an instance of the class and injects dependencies..
*
* @param array $parameters Optional parameters to use to create the instance.
*
* @throws DependencyException
* @throws InvalidDefinition
*/
private function createInstance(ObjectDefinition $definition, array $parameters) : object
{
// Check that the class is instantiable
if (! $definition->isInstantiable()) {
// Check that the class exists
if (! $definition->classExists()) {
throw InvalidDefinition::create($definition, sprintf(
'Entry "%s" cannot be resolved: the class doesn\'t exist',
$definition->getName()
));
}
throw InvalidDefinition::create($definition, sprintf(
'Entry "%s" cannot be resolved: the class is not instantiable',
$definition->getName()
));
}
/** @psalm-var class-string $classname */
$classname = $definition->getClassName();
$classReflection = new ReflectionClass($classname);
$constructorInjection = $definition->getConstructorInjection();
/** @psalm-suppress InvalidCatch */
try {
$args = $this->parameterResolver->resolveParameters(
$constructorInjection,
$classReflection->getConstructor(),
$parameters
);
$object = new $classname(...$args);
$this->injectMethodsAndProperties($object, $definition);
} catch (NotFoundExceptionInterface $e) {
throw new DependencyException(sprintf(
'Error while injecting dependencies into %s: %s',
$classReflection->getName(),
$e->getMessage()
), 0, $e);
} catch (InvalidDefinition $e) {
throw InvalidDefinition::create($definition, sprintf(
'Entry "%s" cannot be resolved: %s',
$definition->getName(),
$e->getMessage()
));
}
return $object;
}
protected function injectMethodsAndProperties(object $object, ObjectDefinition $objectDefinition) : void
{
// Property injections
foreach ($objectDefinition->getPropertyInjections() as $propertyInjection) {
$this->injectProperty($object, $propertyInjection);
}
// Method injections
foreach ($objectDefinition->getMethodInjections() as $methodInjection) {
$methodReflection = new \ReflectionMethod($object, $methodInjection->getMethodName());
$args = $this->parameterResolver->resolveParameters($methodInjection, $methodReflection);
$methodReflection->invokeArgs($object, $args);
}
}
/**
* Inject dependencies into properties.
*
* @param object $object Object to inject dependencies into
* @param PropertyInjection $propertyInjection Property injection definition
*
* @throws DependencyException
*/
private function injectProperty(object $object, PropertyInjection $propertyInjection) : void
{
$propertyName = $propertyInjection->getPropertyName();
$value = $propertyInjection->getValue();
if ($value instanceof Definition) {
try {
$value = $this->definitionResolver->resolve($value);
} catch (DependencyException $e) {
throw $e;
} catch (Exception $e) {
throw new DependencyException(sprintf(
'Error while injecting in %s::%s. %s',
$object::class,
$propertyName,
$e->getMessage()
), 0, $e);
}
}
self::setPrivatePropertyValue($propertyInjection->getClassName(), $object, $propertyName, $value);
}
public static function setPrivatePropertyValue(?string $className, $object, string $propertyName, mixed $propertyValue) : void
{
$className = $className ?: $object::class;
$property = new ReflectionProperty($className, $propertyName);
if (! $property->isPublic() && \PHP_VERSION_ID < 80100) {
$property->setAccessible(true);
}
$property->setValue($object, $propertyValue);
}
}

View File

@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\Definition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\ObjectDefinition\MethodInjection;
use ReflectionMethod;
use ReflectionParameter;
/**
* Resolves parameters for a function call.
*
* @since 4.2
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ParameterResolver
{
/**
* @param DefinitionResolver $definitionResolver Will be used to resolve nested definitions.
*/
public function __construct(
private DefinitionResolver $definitionResolver,
) {
}
/**
* @return array Parameters to use to call the function.
* @throws InvalidDefinition A parameter has no value defined or guessable.
*/
public function resolveParameters(
MethodInjection $definition = null,
ReflectionMethod $method = null,
array $parameters = [],
) : array {
$args = [];
if (! $method) {
return $args;
}
$definitionParameters = $definition ? $definition->getParameters() : [];
foreach ($method->getParameters() as $index => $parameter) {
if (array_key_exists($parameter->getName(), $parameters)) {
// Look in the $parameters array
$value = &$parameters[$parameter->getName()];
} elseif (array_key_exists($index, $definitionParameters)) {
// Look in the definition
$value = &$definitionParameters[$index];
} else {
// If the parameter is optional and wasn't specified, we take its default value
if ($parameter->isDefaultValueAvailable() || $parameter->isOptional()) {
$args[] = $this->getParameterDefaultValue($parameter, $method);
continue;
}
throw new InvalidDefinition(sprintf(
'Parameter $%s of %s has no value defined or guessable',
$parameter->getName(),
$this->getFunctionName($method)
));
}
// Nested definitions
if ($value instanceof Definition) {
// If the container cannot produce the entry, we can use the default parameter value
if ($parameter->isOptional() && ! $this->definitionResolver->isResolvable($value)) {
$value = $this->getParameterDefaultValue($parameter, $method);
} else {
$value = $this->definitionResolver->resolve($value);
}
}
$args[] = &$value;
}
return $args;
}
/**
* Returns the default value of a function parameter.
*
* @throws InvalidDefinition Can't get default values from PHP internal classes and functions
*/
private function getParameterDefaultValue(ReflectionParameter $parameter, ReflectionMethod $function) : mixed
{
try {
return $parameter->getDefaultValue();
} catch (\ReflectionException) {
throw new InvalidDefinition(sprintf(
'The parameter "%s" of %s has no type defined or guessable. It has a default value, '
. 'but the default value can\'t be read through Reflection because it is a PHP internal class.',
$parameter->getName(),
$this->getFunctionName($function)
));
}
}
private function getFunctionName(ReflectionMethod $method) : string
{
return $method->getName() . '()';
}
}

View File

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Resolver;
use DI\Definition\ArrayDefinition;
use DI\Definition\DecoratorDefinition;
use DI\Definition\Definition;
use DI\Definition\EnvironmentVariableDefinition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\FactoryDefinition;
use DI\Definition\InstanceDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\SelfResolvingDefinition;
use DI\Proxy\ProxyFactory;
use Psr\Container\ContainerInterface;
/**
* Dispatches to more specific resolvers.
*
* Dynamic dispatch pattern.
*
* @since 5.0
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class ResolverDispatcher implements DefinitionResolver
{
private ?ArrayResolver $arrayResolver = null;
private ?FactoryResolver $factoryResolver = null;
private ?DecoratorResolver $decoratorResolver = null;
private ?ObjectCreator $objectResolver = null;
private ?InstanceInjector $instanceResolver = null;
private ?EnvironmentVariableResolver $envVariableResolver = null;
public function __construct(
private ContainerInterface $container,
private ProxyFactory $proxyFactory,
) {
}
/**
* Resolve a definition to a value.
*
* @param Definition $definition Object that defines how the value should be obtained.
* @param array $parameters Optional parameters to use to build the entry.
*
* @return mixed Value obtained from the definition.
* @throws InvalidDefinition If the definition cannot be resolved.
*/
public function resolve(Definition $definition, array $parameters = []) : mixed
{
// Special case, tested early for speed
if ($definition instanceof SelfResolvingDefinition) {
return $definition->resolve($this->container);
}
$definitionResolver = $this->getDefinitionResolver($definition);
return $definitionResolver->resolve($definition, $parameters);
}
public function isResolvable(Definition $definition, array $parameters = []) : bool
{
// Special case, tested early for speed
if ($definition instanceof SelfResolvingDefinition) {
return $definition->isResolvable($this->container);
}
$definitionResolver = $this->getDefinitionResolver($definition);
return $definitionResolver->isResolvable($definition, $parameters);
}
/**
* Returns a resolver capable of handling the given definition.
*
* @throws \RuntimeException No definition resolver was found for this type of definition.
*/
private function getDefinitionResolver(Definition $definition) : DefinitionResolver
{
switch (true) {
case $definition instanceof ObjectDefinition:
if (! $this->objectResolver) {
$this->objectResolver = new ObjectCreator($this, $this->proxyFactory);
}
return $this->objectResolver;
case $definition instanceof DecoratorDefinition:
if (! $this->decoratorResolver) {
$this->decoratorResolver = new DecoratorResolver($this->container, $this);
}
return $this->decoratorResolver;
case $definition instanceof FactoryDefinition:
if (! $this->factoryResolver) {
$this->factoryResolver = new FactoryResolver($this->container, $this);
}
return $this->factoryResolver;
case $definition instanceof ArrayDefinition:
if (! $this->arrayResolver) {
$this->arrayResolver = new ArrayResolver($this);
}
return $this->arrayResolver;
case $definition instanceof EnvironmentVariableDefinition:
if (! $this->envVariableResolver) {
$this->envVariableResolver = new EnvironmentVariableResolver($this);
}
return $this->envVariableResolver;
case $definition instanceof InstanceDefinition:
if (! $this->instanceResolver) {
$this->instanceResolver = new InstanceInjector($this, $this->proxyFactory);
}
return $this->instanceResolver;
default:
throw new \RuntimeException('No definition resolver was configured for definition of type ' . $definition::class);
}
}
}

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace DI\Definition;
use Psr\Container\ContainerInterface;
/**
* Describes a definition that can resolve itself.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
interface SelfResolvingDefinition
{
/**
* Resolve the definition and return the resulting value.
*/
public function resolve(ContainerInterface $container) : mixed;
/**
* Check if a definition can be resolved.
*/
public function isResolvable(ContainerInterface $container) : bool;
}

View File

@ -0,0 +1,263 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Source;
use DI\Attribute\Inject;
use DI\Attribute\Injectable;
use DI\Definition\Exception\InvalidAttribute;
use DI\Definition\ObjectDefinition;
use DI\Definition\ObjectDefinition\MethodInjection;
use DI\Definition\ObjectDefinition\PropertyInjection;
use DI\Definition\Reference;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionProperty;
use Throwable;
/**
* Provides DI definitions by reading PHP 8 attributes such as #[Inject] and #[Injectable].
*
* This source automatically includes the reflection source.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class AttributeBasedAutowiring implements DefinitionSource, Autowiring
{
/**
* @throws InvalidAttribute
*/
public function autowire(string $name, ObjectDefinition $definition = null) : ObjectDefinition|null
{
$className = $definition ? $definition->getClassName() : $name;
if (!class_exists($className) && !interface_exists($className)) {
return $definition;
}
$definition = $definition ?: new ObjectDefinition($name);
$class = new ReflectionClass($className);
$this->readInjectableAttribute($class, $definition);
// Browse the class properties looking for annotated properties
$this->readProperties($class, $definition);
// Browse the object's methods looking for annotated methods
$this->readMethods($class, $definition);
return $definition;
}
/**
* @throws InvalidAttribute
* @throws InvalidArgumentException The class doesn't exist
*/
public function getDefinition(string $name) : ObjectDefinition|null
{
return $this->autowire($name);
}
/**
* Autowiring cannot guess all existing definitions.
*/
public function getDefinitions() : array
{
return [];
}
/**
* Browse the class properties looking for annotated properties.
*/
private function readProperties(ReflectionClass $class, ObjectDefinition $definition) : void
{
foreach ($class->getProperties() as $property) {
$this->readProperty($property, $definition);
}
// Read also the *private* properties of the parent classes
/** @noinspection PhpAssignmentInConditionInspection */
while ($class = $class->getParentClass()) {
foreach ($class->getProperties(ReflectionProperty::IS_PRIVATE) as $property) {
$this->readProperty($property, $definition, $class->getName());
}
}
}
/**
* @throws InvalidAttribute
*/
private function readProperty(ReflectionProperty $property, ObjectDefinition $definition, string $classname = null) : void
{
if ($property->isStatic() || $property->isPromoted()) {
return;
}
// Look for #[Inject] attribute
try {
$attribute = $property->getAttributes(Inject::class)[0] ?? null;
if (! $attribute) {
return;
}
/** @var Inject $inject */
$inject = $attribute->newInstance();
} catch (Throwable $e) {
throw new InvalidAttribute(sprintf(
'#[Inject] annotation on property %s::%s is malformed. %s',
$property->getDeclaringClass()->getName(),
$property->getName(),
$e->getMessage()
), 0, $e);
}
// Try to #[Inject("name")] or look for the property type
$entryName = $inject->getName();
// Try using typed properties
$propertyType = $property->getType();
if ($entryName === null && $propertyType instanceof ReflectionNamedType) {
if (! class_exists($propertyType->getName()) && ! interface_exists($propertyType->getName())) {
throw new InvalidAttribute(sprintf(
'#[Inject] found on property %s::%s but unable to guess what to inject, the type of the property does not look like a valid class or interface name',
$property->getDeclaringClass()->getName(),
$property->getName()
));
}
$entryName = $propertyType->getName();
}
if ($entryName === null) {
throw new InvalidAttribute(sprintf(
'#[Inject] found on property %s::%s but unable to guess what to inject, please add a type to the property',
$property->getDeclaringClass()->getName(),
$property->getName()
));
}
$definition->addPropertyInjection(
new PropertyInjection($property->getName(), new Reference($entryName), $classname)
);
}
/**
* Browse the object's methods looking for annotated methods.
*/
private function readMethods(ReflectionClass $class, ObjectDefinition $objectDefinition) : void
{
// This will look in all the methods, including those of the parent classes
foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if ($method->isStatic()) {
continue;
}
$methodInjection = $this->getMethodInjection($method);
if (! $methodInjection) {
continue;
}
if ($method->isConstructor()) {
$objectDefinition->completeConstructorInjection($methodInjection);
} else {
$objectDefinition->completeFirstMethodInjection($methodInjection);
}
}
}
private function getMethodInjection(ReflectionMethod $method) : ?MethodInjection
{
// Look for #[Inject] attribute
$attribute = $method->getAttributes(Inject::class)[0] ?? null;
if ($attribute) {
/** @var Inject $inject */
$inject = $attribute->newInstance();
$annotationParameters = $inject->getParameters();
} elseif ($method->isConstructor()) {
// #[Inject] on constructor is implicit, we continue
$annotationParameters = [];
} else {
return null;
}
$parameters = [];
foreach ($method->getParameters() as $index => $parameter) {
$entryName = $this->getMethodParameter($index, $parameter, $annotationParameters);
if ($entryName !== null) {
$parameters[$index] = new Reference($entryName);
}
}
if ($method->isConstructor()) {
return MethodInjection::constructor($parameters);
}
return new MethodInjection($method->getName(), $parameters);
}
/**
* @return string|null Entry name or null if not found.
*/
private function getMethodParameter(int $parameterIndex, ReflectionParameter $parameter, array $annotationParameters) : ?string
{
// Let's check if this parameter has an #[Inject] attribute
$attribute = $parameter->getAttributes(Inject::class)[0] ?? null;
if ($attribute) {
/** @var Inject $inject */
$inject = $attribute->newInstance();
return $inject->getName();
}
// #[Inject] has definition for this parameter (by index, or by name)
if (isset($annotationParameters[$parameterIndex])) {
return $annotationParameters[$parameterIndex];
}
if (isset($annotationParameters[$parameter->getName()])) {
return $annotationParameters[$parameter->getName()];
}
// Skip optional parameters if not explicitly defined
if ($parameter->isOptional()) {
return null;
}
// Look for the property type
$parameterType = $parameter->getType();
if ($parameterType instanceof ReflectionNamedType && !$parameterType->isBuiltin()) {
return $parameterType->getName();
}
return null;
}
/**
* @throws InvalidAttribute
*/
private function readInjectableAttribute(ReflectionClass $class, ObjectDefinition $definition) : void
{
try {
$attribute = $class->getAttributes(Injectable::class)[0] ?? null;
if (! $attribute) {
return;
}
$attribute = $attribute->newInstance();
} catch (Throwable $e) {
throw new InvalidAttribute(sprintf(
'Error while reading #[Injectable] on %s: %s',
$class->getName(),
$e->getMessage()
), 0, $e);
}
if ($attribute->isLazy() !== null) {
$definition->setLazy($attribute->isLazy());
}
}
}

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Source;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\ObjectDefinition;
/**
* Source of definitions for entries of the container.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
interface Autowiring
{
/**
* Autowire the given definition.
*
* @throws InvalidDefinition An invalid definition was found.
*/
public function autowire(string $name, ObjectDefinition $definition = null) : ObjectDefinition|null;
}

View File

@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Source;
use DI\Definition\Definition;
/**
* Reads DI definitions from a PHP array.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class DefinitionArray implements DefinitionSource, MutableDefinitionSource
{
public const WILDCARD = '*';
/**
* Matches anything except "\".
*/
private const WILDCARD_PATTERN = '([^\\\\]+)';
/** DI definitions in a PHP array. */
private array $definitions;
/** Cache of wildcard definitions. */
private ?array $wildcardDefinitions = null;
private DefinitionNormalizer $normalizer;
public function __construct(array $definitions = [], Autowiring $autowiring = null)
{
if (isset($definitions[0])) {
throw new \Exception('The PHP-DI definition is not indexed by an entry name in the definition array');
}
$this->definitions = $definitions;
$this->normalizer = new DefinitionNormalizer($autowiring ?: new NoAutowiring);
}
/**
* @param array $definitions DI definitions in a PHP array indexed by the definition name.
*/
public function addDefinitions(array $definitions) : void
{
if (isset($definitions[0])) {
throw new \Exception('The PHP-DI definition is not indexed by an entry name in the definition array');
}
// The newly added data prevails
// "for keys that exist in both arrays, the elements from the left-hand array will be used"
$this->definitions = $definitions + $this->definitions;
// Clear cache
$this->wildcardDefinitions = null;
}
public function addDefinition(Definition $definition) : void
{
$this->definitions[$definition->getName()] = $definition;
// Clear cache
$this->wildcardDefinitions = null;
}
public function getDefinition(string $name) : Definition|null
{
// Look for the definition by name
if (array_key_exists($name, $this->definitions)) {
$definition = $this->definitions[$name];
return $this->normalizer->normalizeRootDefinition($definition, $name);
}
// Build the cache of wildcard definitions
if ($this->wildcardDefinitions === null) {
$this->wildcardDefinitions = [];
foreach ($this->definitions as $key => $definition) {
if (str_contains($key, self::WILDCARD)) {
$this->wildcardDefinitions[$key] = $definition;
}
}
}
// Look in wildcards definitions
foreach ($this->wildcardDefinitions as $key => $definition) {
// Turn the pattern into a regex
$key = preg_quote($key, '#');
$key = '#^' . str_replace('\\' . self::WILDCARD, self::WILDCARD_PATTERN, $key) . '#';
if (preg_match($key, $name, $matches) === 1) {
array_shift($matches);
return $this->normalizer->normalizeRootDefinition($definition, $name, $matches);
}
}
return null;
}
public function getDefinitions() : array
{
// Return all definitions except wildcard definitions
$definitions = [];
foreach ($this->definitions as $key => $definition) {
if (! str_contains($key, self::WILDCARD)) {
$definitions[$key] = $definition;
}
}
return $definitions;
}
}

View File

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace DI\Definition\Source;
use DI\Definition\Definition;
/**
* Reads DI definitions from a file returning a PHP array.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class DefinitionFile extends DefinitionArray
{
private bool $initialized = false;
/**
* @param string $file File in which the definitions are returned as an array.
*/
public function __construct(
private string $file,
Autowiring $autowiring = null,
) {
// Lazy-loading to improve performances
parent::__construct([], $autowiring);
}
public function getDefinition(string $name) : Definition|null
{
$this->initialize();
return parent::getDefinition($name);
}
public function getDefinitions() : array
{
$this->initialize();
return parent::getDefinitions();
}
/**
* Lazy-loading of the definitions.
*/
private function initialize() : void
{
if ($this->initialized === true) {
return;
}
$definitions = require $this->file;
if (! is_array($definitions)) {
throw new \Exception("File $this->file should return an array of definitions");
}
$this->addDefinitions($definitions);
$this->initialized = true;
}
}

Some files were not shown because too many files have changed in this diff Show More