Skip to content

Commit 168e5fb

Browse files
authored
feat(di): Add new Dependency Injection interfaces (#37)
* add size method * feat: Normalize Interfaces - Refined and standardized interface definitions across the project - Applied Single Responsibility Principle (SRP) to ensure each interface has a clear, singular purpose - Consistent naming conventions were implemented for better readability and maintainability - Added thorough documentation for each interface, including method descriptions and expected behaviors - Organized interfaces within appropriate namespaces to prevent naming collisions and maintain a logical structure - Ensured parameter names in interface methods are consistent with implementing classes - Avoided including constructors in interfaces to maintain flexibility These changes enhance the overall clarity, maintainability, and professional quality of the codebase. * Refactor and Normalize Collection Interface and Implementation - Refactored `Collection` interface for consistency and adherence to best practices. - Ensured all tests are comprehensive and validate the expected behavior. * feat: Add BinaryHeap implementation and comprehensive tests - Implemented BinaryHeap class with support for both min-heap and max-heap operations. - Methods include: add, poll, peek, size, isEmpty, heapifyUp, heapifyDown, swap, and compare. - Created unit tests for BinaryHeap class ensuring 100% coverage. - Tested all key operations: add, poll, peek, heapifyUp, heapifyDown, swap, and compare. - Included edge case tests for min-heap and max-heap scenarios. - Ensured compliance with type safety and PHP 8.0+ features. - Added comprehensive documentation and examples for BinaryHeap usage. This commit enhances the KaririCode Framework by providing a robust, type-safe, and efficient BinaryHeap data structure with extensive unit tests. * docs: Update README files in English and Portuguese - Enhanced the overview and key features sections for clarity and completeness. - Added detailed descriptions for all implemented data structures: - TreeSet - ArrayDeque - ArrayQueue - TreeMap - LinkedList - BinaryHeap - HashMap - Included complexity analysis and key methods for each data structure. - Provided usage examples for each data structure to demonstrate functionality. - Updated installation instructions and requirements. - Updated acknowledgments and roadmap sections. * style: Normalize code formatting and style * feat: Create Container interface and add unit tests - Define the Container interface with methods: `set`, `get`, and `has`. - Implement unit tests for `set` method to ensure services are registered correctly. - Add unit tests for `get` method to verify correct retrieval of services by identifier. - Include unit tests for `has` method to check existence of services in the container. - Normalize the `@category` comments in the interface documentation for consistency. These changes establish a foundational contract for dependency injection within the KaririCode project and ensure robust and reliable functionality through comprehensive testing * feat: Add logging interfaces and corresponding tests - Created Configurable interface for managing configuration settings. - Created Loggable interface to define logging methods for various log levels. - Created ContextAware interface for managing context information in logs. - Created FormatterAware interface for handling log formatter settings. - Created HandlerAware interface for managing log handlers. - Created ProcessorAware interface for managing log processors. - Created LoggingManager interface that combines various logging functionalities. - Created LogFormatter interface for defining log formatters. - Created LogHandler interface for handling log records. - Created LogLevel interface for defining log levels. - Created LogProcessor interface for processing log records before handling. - Created LogRotator interface for managing log file rotation. - Added unit tests for each interface to ensure correct functionality: - ConfigurableTest: Tests for setConfig and getConfig methods. - LoggableTest: Tests for various logging level methods. - ContextAwareTest: Tests for withContext and getContext methods. - FormatterAwareTest: Tests for setFormatter and getFormatter methods. - HandlerAwareTest: Tests for addHandler, pushHandler, popHandler, and getHandlers methods. - ProcessorAwareTest: Tests for addProcessor and getProcessors methods. - LoggingManagerTest: Comprehensive tests for all LoggingManager methods. - LogFormatterTest: Test for the format method. - LogHandlerTest: Test for the handle method. - LogLevelTest: Test for the getLevel method. - LogProcessorTest: Test for the process method. - LogRotatorTest: Test for the rotate method. * feat: Update logging interfaces Add tests for LoggerAware and LoggerConfigurable interfaces - Revised and enhanced logging interfaces for better consistency and flexibility. - Implemented new methods to support asynchronous logging. - Improved documentation of the interfaces to facilitate integration. - Added unit tests to ensure the robustness of the new implementations. - Added unit test for LoggerAware interface to verify setLogger method. - Added unit test for LoggerConfigurable interface to verify configure method. - Ensured proper mock setup and expectations in tests. * feat(logging): improve log rotation and update log handler - Removed .phpcs-cache for cleaner repository - Updated src/Logging/LogHandler.php to enhance log handling capabilities - Modified src/Logging/LogLevel.php for better log level management - Enhanced src/Logging/LogRotator.php with improved file rotation logic - Updated src/Logging/Logger.php to integrate changes in log handling and rotation * Refactor:Indexable interface and LogLevel class - Modified the Indexable.php interface to enhance functionality. - Updated the LogLevel.php class to add new log levels. - Made lint adjustments in LogRotator class. * feat(contract): Add Processor interfaces and tests - Introduce new interfaces: Processor, ConfigurableProcessor, Pipeline - Add comprehensive PHPUnit tests for each interface - Enhance code documentation with detailed PHP DocBlocks - Ensure consistency with existing KaririCode coding standards * feat: add ProcessorRegistry interface and unit tests - Introduced `ProcessorRegistry` interface to standardize processor registration and retrieval across contexts. - Added `ProcessorRegistryTest` class to ensure correctness of the new interface, covering scenarios like processor registration, retrieval, and error handling. * feat(processor): add ProcessorBuilder interface and test suite - Add ProcessorBuilder interface in KaririCode\Contract\Processor namespace - Define build() method for constructing individual processors - Define buildPipeline() method for assembling processor pipelines - Create ProcessorBuilderTest class in KaririCode\Contract\Tests\Processor namespace - Implement tests for build() and buildPipeline() methods - Cover success scenarios and exception handling - Ensure proper interaction with ProcessorRegistry * feat(contract): add PHPDoc for ProcessableAttribute interface and create unit tests - Add PHPDoc comments for ProcessableAttribute interface, including method descriptions and author/license information - Create unit tests for ProcessableAttribute interface, testing `getProcessors` and `getFallbackValue` methods * feat(contract): add Sanitizer, Serializer, and Validator interfaces with unit tests - Add `Sanitizer` interface for sanitizing input data in `src/Sanitizer/` - Add `Validator` interface for validating input data in `src/Validator/` - Add `Serializer` interface for serializing and deserializing data in `src/Serializer/` - Create unit tests for each interface to ensure expected behavior * fix(validator): correct return type of Validator interface * feat(contract): add CustomizableMessageAttribute interface - Introduce CustomizableMessageAttribute interface in KaririCode\Contract\Processor\Attribute namespace - Add method getMessage(string $validatorName): ?string to the interface - Create unit tests for CustomizableMessageAttribute in CustomizableMessageAttributeTest - Update existing ProcessableAttribute interface documentation for consistency * feat: add BaseProcessorAttribute abstract class * refactor: adjusty filterValidProcessors in BaseProcessorAttribute * feat(processor): add ProcessorValidator and ValidatableProcessor interfaces with unit tests - Added ProcessorValidator interface to define contract for validating processors in a pipeline. - Added ValidatableProcessor interface to define contract for processors with validation capabilities. - Created unit tests for ProcessorValidator and ValidatableProcessor to ensure proper validation behavior. * feat(validator): Add reset method to ValidatableProcessor interface The reset method is added to ensure proper state reset between validations. This change helps prevent state leakage between multiple validation cycles by allowing processors to clear their validation state before reuse. - Add reset() method with proper PHPDoc - Maintain consistent documentation style - Keep backward compatibility with existing implementations * feat(validator): Add reset method to ValidatableProcessor interface The reset method is added to ensure proper state reset between validations. This change helps prevent state leakage between multiple validation cycles by allowing processors to clear their validation state before reuse. - Add reset() method with proper PHPDoc - Maintain consistent documentation style - Keep backward compatibility with existing implementations * test(processor): add unit tests for ProcessingResult interface - Add test cases for all ProcessingResult interface methods - Include setUp with mock creation - Validate error handling and data processing - Ensure proper type declarations * refactor: add professional comments to BaseProcessorAttribute and update register return in ProcessorRegistry - Change `register` method in `ProcessorRegistry` interface to return `self` instead of `void` for fluent interface support - Add professional comments to `BaseProcessorAttribute` abstract class, clarifying property roles and method responsibilities - Document `filterValidProcessors` and other methods for clearer functionality understanding * feat: add Transformer interface and initial test - Created `Transformer` interface in `src/Contract/Transformer/Transformer.php`: - Defines the `transform` method for transforming input data, ensuring consistent implementation across transformers. - Added `TransformerTest` in `tests/Contract/Transformer/TransformerTest.php`: - Includes a test for the `transform` method using a mock object. - Verifies that the method is called correctly and returns the expected output. * feat: extend Container with resolve, bind, and singleton methods test: enhance Container unit tests for clarity and conciseness * feat(di): standardize interface docs and add unit tests - Standardize PHPDoc comments across all DI interfaces - Complete Container interface tests - Add unit tests for Definition, Provider and Compiler interfaces - Ensure consistent documentation style and test coverage --------- Co-authored-by: GrowthCode <142913591+growthcodeoficial@users.noreply.github.com>
1 parent 40cfdff commit 168e5fb

File tree

10 files changed

+610
-89
lines changed

10 files changed

+610
-89
lines changed

src/DI/Compiler.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace KaririCode\Contract\DI;
6+
7+
/**
8+
* Interface Compiler.
9+
*
10+
* Defines the contract for compiling container definitions and handling caching mechanisms.
11+
*
12+
* @category DependencyInjection
13+
*
14+
* @author Walmir Silva <walmir.silva@kariricode.org>
15+
*/
16+
interface Compiler
17+
{
18+
/**
19+
* Compiles the container definitions.
20+
*
21+
* @param Container $container The container to compile
22+
*
23+
* @return Container Compiled container
24+
*/
25+
public function compile(Container $container): Container;
26+
27+
/**
28+
* Writes compiled container to a file.
29+
*
30+
* @param string $path Path to the file where compiled container will be written
31+
*/
32+
public function writeToFile(string $path): void;
33+
34+
/**
35+
* Loads compiled container definitions from a file.
36+
*
37+
* @param string $path Path to the file containing compiled container definitions
38+
*
39+
* @return Container Loaded container instance
40+
*/
41+
public function loadFromFile(string $path): Container;
42+
}

src/DI/Container.php

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace KaririCode\Contract\DI;
6+
7+
/**
8+
* Interface Container.
9+
*
10+
* Defines the contract for a dependency injection container that manages the creation and resolution of services.
11+
*
12+
* @category DependencyInjection
13+
*
14+
* @author Walmir Silva <walmir.silva@kariricode.org>
15+
*/
16+
interface Container
17+
{
18+
/**
19+
* Sets a service in the container.
20+
*
21+
* @param string $id Identifier of the service
22+
* @param callable $service The callable that returns the service instance
23+
*/
24+
public function set(string $id, callable $service): void;
25+
26+
/**
27+
* Retrieves a service by its identifier.
28+
*
29+
* @param string $id Identifier of the service to retrieve
30+
*
31+
* @return mixed The service instance
32+
*/
33+
public function get(string $id): mixed;
34+
35+
/**
36+
* Checks if the container can return a service for the given identifier.
37+
*
38+
* @param string $id Identifier of the service to check
39+
*
40+
* @return bool True if the service is found, false otherwise
41+
*/
42+
public function has(string $id): bool;
43+
44+
/**
45+
* Resolves and returns an instance of the given abstract type.
46+
*
47+
* @param string $abstract The abstract type or identifier to resolve
48+
*
49+
* @return object Resolved instance of the given abstract
50+
*/
51+
public function resolve(string $abstract): object;
52+
53+
/**
54+
* Binds a concrete implementation to an abstract type with optional parameters.
55+
*
56+
* @param string $abstract The abstract type or identifier
57+
* @param mixed $concrete The concrete implementation (class name or closure)
58+
* @param array $parameters Optional parameters for instantiation
59+
*/
60+
public function bind(string $abstract, mixed $concrete, array $parameters = []): void;
61+
62+
/**
63+
* Registers a singleton binding, ensuring the instance is created only once.
64+
*
65+
* @param string $abstract The abstract type or identifier
66+
* @param mixed $concrete The concrete implementation (class name or closure)
67+
* @param array $parameters Optional parameters
68+
*/
69+
public function singleton(string $abstract, mixed $concrete, array $parameters = []): void;
70+
71+
/**
72+
* Registers a factory binding, creating a new instance upon each resolution.
73+
*
74+
* @param string $abstract The abstract type or identifier
75+
* @param mixed $concrete The concrete implementation (class name or closure)
76+
* @param array $parameters Optional parameters
77+
*/
78+
public function factory(string $abstract, mixed $concrete, array $parameters = []): void;
79+
80+
/**
81+
* Assigns multiple abstracts to a specific tag.
82+
*
83+
* @param string $tag Tag name
84+
* @param array $abstracts List of abstract identifiers
85+
*/
86+
public function tag(string $tag, array $abstracts): void;
87+
88+
/**
89+
* Retrieves abstracts associated with a specific tag.
90+
*
91+
* @param string $tag Tag name
92+
*
93+
* @return array Abstract identifiers tagged
94+
*/
95+
public function tagged(string $tag): array;
96+
97+
/**
98+
* Executes a callable or method with provided parameters.
99+
*
100+
* @param callable|string $callback The callable or method name
101+
* @param array $parameters Parameters to pass
102+
*
103+
* @return mixed Result of the callable execution
104+
*/
105+
public function call(callable|string $callback, array $parameters = []): mixed;
106+
107+
/**
108+
* Extends an existing binding.
109+
*
110+
* @param string $abstract Abstract identifier to extend
111+
* @param \Closure $extender Closure to extend functionality
112+
*/
113+
public function extend(string $abstract, \Closure $extender): void;
114+
115+
/**
116+
* Creates an alias for an abstract identifier.
117+
*
118+
* @param string $abstract Original abstract identifier
119+
* @param string $alias Alias to use
120+
*/
121+
public function alias(string $abstract, string $alias): void;
122+
}

src/DI/Definition.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace KaririCode\Contract\DI;
6+
7+
/**
8+
* Interface Definition.
9+
*
10+
* Defines the contract for service definitions managed by the dependency injection container.
11+
*
12+
* @category DependencyInjection
13+
*
14+
* @author Walmir Silva <walmir.silva@kariricode.org>
15+
*/
16+
interface Definition
17+
{
18+
/**
19+
* Gets the concrete implementation.
20+
*
21+
* @return mixed The concrete implementation of the service
22+
*/
23+
public function getConcrete(): mixed;
24+
25+
/**
26+
* Gets the instantiation parameters.
27+
*
28+
* @return array Parameters used for service instantiation
29+
*/
30+
public function getParameters(): array;
31+
32+
/**
33+
* Gets tags associated with the definition.
34+
*
35+
* @return array List of tags associated with this definition
36+
*/
37+
public function getTags(): array;
38+
39+
/**
40+
* Checks if definition is a singleton.
41+
*
42+
* @return bool True if the definition is a singleton, false otherwise
43+
*/
44+
public function isSingleton(): bool;
45+
46+
/**
47+
* Checks if definition is a factory.
48+
*
49+
* @return bool True if the definition is a factory, false otherwise
50+
*/
51+
public function isFactory(): bool;
52+
}

src/DI/Provider.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace KaririCode\Contract\DI;
6+
7+
/**
8+
* Interface Provider.
9+
*
10+
* Defines the contract for service providers responsible for registering and bootstrapping services.
11+
*
12+
* @category DependencyInjection
13+
*
14+
* @author Walmir Silva <walmir.silva@kariricode.org>
15+
*/
16+
interface Provider
17+
{
18+
/**
19+
* Registers services into the container.
20+
*
21+
* @param Container $container The dependency injection container
22+
*/
23+
public function register(Container $container): void;
24+
25+
/**
26+
* Boots services after registration.
27+
*
28+
* @param Container $container The dependency injection container
29+
*/
30+
public function boot(Container $container): void;
31+
}

src/DependencyInjection/Container.php

Lines changed: 0 additions & 46 deletions
This file was deleted.

tests/DI/CompilerTest.php

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace KaririCode\Contract\Tests\DI;
6+
7+
use KaririCode\Contract\DI\Compiler;
8+
use KaririCode\Contract\DI\Container;
9+
use PHPUnit\Framework\MockObject\MockObject;
10+
use PHPUnit\Framework\TestCase;
11+
12+
final class CompilerTest extends TestCase
13+
{
14+
private Compiler|MockObject $compiler;
15+
private Container|MockObject $container;
16+
17+
protected function setUp(): void
18+
{
19+
$this->compiler = $this->createMock(Compiler::class);
20+
$this->container = $this->createMock(Container::class);
21+
}
22+
23+
public function testCompile(): void
24+
{
25+
$compiledContainer = $this->createMock(Container::class);
26+
27+
$this->compiler->expects($this->once())
28+
->method('compile')
29+
->with($this->container)
30+
->willReturn($compiledContainer);
31+
32+
$result = $this->compiler->compile($this->container);
33+
34+
$this->assertInstanceOf(Container::class, $result);
35+
$this->assertSame($compiledContainer, $result);
36+
}
37+
38+
public function testWriteToFile(): void
39+
{
40+
$path = '/path/to/compiled/container.php';
41+
42+
$this->compiler->expects($this->once())
43+
->method('writeToFile')
44+
->with($path);
45+
46+
$this->compiler->writeToFile($path);
47+
}
48+
49+
public function testLoadFromFile(): void
50+
{
51+
$path = '/path/to/compiled/container.php';
52+
$loadedContainer = $this->createMock(Container::class);
53+
54+
$this->compiler->expects($this->once())
55+
->method('loadFromFile')
56+
->with($path)
57+
->willReturn($loadedContainer);
58+
59+
$result = $this->compiler->loadFromFile($path);
60+
61+
$this->assertInstanceOf(Container::class, $result);
62+
$this->assertSame($loadedContainer, $result);
63+
}
64+
65+
public function testCompileAndWriteWorkflow(): void
66+
{
67+
$compiledContainer = $this->createMock(Container::class);
68+
$path = '/path/to/compiled/container.php';
69+
70+
// Usando um array para rastrear a ordem das chamadas
71+
$callOrder = [];
72+
73+
$this->compiler->expects($this->once())
74+
->method('compile')
75+
->with($this->container)
76+
->willReturnCallback(function () use ($compiledContainer, &$callOrder) {
77+
$callOrder[] = 'compile';
78+
79+
return $compiledContainer;
80+
});
81+
82+
$this->compiler->expects($this->once())
83+
->method('writeToFile')
84+
->with($path)
85+
->willReturnCallback(function () use (&$callOrder) {
86+
$callOrder[] = 'writeToFile';
87+
});
88+
89+
$result = $this->compiler->compile($this->container);
90+
$this->compiler->writeToFile($path);
91+
92+
// Verifica se os métodos foram chamados na ordem correta
93+
$this->assertEquals(['compile', 'writeToFile'], $callOrder);
94+
$this->assertSame($compiledContainer, $result);
95+
}
96+
}

0 commit comments

Comments
 (0)