Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 172 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ A robust and flexible data sanitization component for PHP, part of the KaririCod
- [Installation](#installation)
- [Usage](#usage)
- [Basic Usage](#basic-usage)
- [Advanced Usage](#advanced-usage)
- [Advanced Usage: Blog Post Sanitization](#advanced-usage-blog-post-sanitization)
- [Available Sanitizers](#available-sanitizers)
- [Configuration](#configuration)
- [Integration with Other KaririCode Components](#integration-with-other-kariricode-components)
- [Development and Testing](#development-and-testing)
- [Contributing](#contributing)
- [License](#license)
- [Support and Community](#support-and-community)

Expand All @@ -27,6 +29,7 @@ A robust and flexible data sanitization component for PHP, part of the KaririCod
- Configurable processors for customized sanitization logic
- Support for fallback values in case of sanitization failures
- Extensible architecture allowing custom sanitizers
- Robust error handling and reporting

## Installation

Expand All @@ -52,10 +55,10 @@ use KaririCode\Sanitizer\Attribute\Sanitize;

class UserProfile
{
#[Sanitize(sanitizers: ['trim', 'html_special_chars'])]
#[Sanitize(processors: ['trim', 'html_special_chars'])]
private string $name = '';

#[Sanitize(sanitizers: ['trim', 'normalize_line_breaks'])]
#[Sanitize(processors: ['trim', 'normalize_line_breaks'])]
private string $email = '';

// Getters and setters...
Expand All @@ -79,74 +82,184 @@ $registry->register('sanitizer', 'normalize_line_breaks', new NormalizeLineBreak
$sanitizer = new Sanitizer($registry);

$userProfile = new UserProfile();
$userProfile->setName(" Walmir Silva ");
$userProfile->setEmail("walmir.silva@example.com\r\n");
$userProfile->setName(" John Doe ");
$userProfile->setEmail("john.doe@example.com\r\n");

$sanitizer->sanitize($userProfile);
$result = $sanitizer->sanitize($userProfile);

echo $userProfile->getName(); // Output: "Walmir Silva"
echo $userProfile->getEmail(); // Output: "walmir.silva@example.com\n"
echo $userProfile->getName(); // Output: "John Doe"
echo $userProfile->getEmail(); // Output: "john.doe@example.com\n"

// Access sanitization results
print_r($result['sanitizedValues']);
print_r($result['messages']);
print_r($result['errors']);
```

### Advanced Usage
### Advanced Usage: Blog Post Sanitization

You can create custom sanitizers by implementing the `Processor` or `ConfigurableProcessor` interfaces:
Here's a more comprehensive example demonstrating how to use the KaririCode Sanitizer in a real-world scenario, such as sanitizing blog post content:

```php
use KaririCode\Contract\Processor\ConfigurableProcessor;
use KaririCode\Sanitizer\Processor\AbstractSanitizerProcessor;
<?php

class CustomSanitizer extends AbstractSanitizerProcessor implements ConfigurableProcessor
{
private $option;

public function configure(array $options): void
{
$this->option = $options['custom_option'] ?? 'default';
}

public function process(mixed $input): string
{
$input = $this->guardAgainstNonString($input);
// Custom sanitization logic here
return $input;
}
}
declare(strict_types=1);

// Register and use the custom sanitizer
$registry->register('sanitizer', 'custom', new CustomSanitizer());
require_once __DIR__ . '/../vendor/autoload.php';

class AdvancedProfile
use KaririCode\ProcessorPipeline\ProcessorRegistry;
use KaririCode\Sanitizer\Attribute\Sanitize;
use KaririCode\Sanitizer\Processor\Domain\HtmlPurifierSanitizer;
use KaririCode\Sanitizer\Processor\Domain\MarkdownSanitizer;
use KaririCode\Sanitizer\Processor\Input\HtmlSpecialCharsSanitizer;
use KaririCode\Sanitizer\Processor\Input\NormalizeLineBreaksSanitizer;
use KaririCode\Sanitizer\Processor\Input\StripTagsSanitizer;
use KaririCode\Sanitizer\Processor\Input\TrimSanitizer;
use KaririCode\Sanitizer\Processor\Security\XssSanitizer;
use KaririCode\Sanitizer\Sanitizer;

class BlogPost
{
#[Sanitize(sanitizers: ['custom' => ['custom_option' => 'value']])]
private string $customField = '';
#[Sanitize(
processors: ['trim', 'html_special_chars', 'xss_sanitizer'],
messages: [
'trim' => 'Title was trimmed',
'html_special_chars' => 'Special characters in title were escaped',
'xss_sanitizer' => 'XSS attempt was removed from title',
]
)]
private string $title = '';

#[Sanitize(
processors: ['trim', 'normalize_line_breaks'],
messages: [
'trim' => 'Slug was trimmed',
'normalize_line_breaks' => 'Line breaks in slug were normalized',
]
)]
private string $slug = '';

#[Sanitize(
processors: ['trim', 'markdown', 'html_purifier'],
messages: [
'trim' => 'Content was trimmed',
'markdown' => 'Markdown in content was processed',
'html_purifier' => 'HTML in content was purified',
]
)]
private string $content = '';

#[Sanitize(
processors: ['trim', 'strip_tags', 'html_special_chars'],
messages: [
'trim' => 'Author name was trimmed',
'strip_tags' => 'HTML tags were removed from author name',
'html_special_chars' => 'Special characters in author name were escaped',
]
)]
private string $authorName = '';

// Getters and setters...
}

// Set up the sanitizer
$registry = new ProcessorRegistry();
$registry->register('sanitizer', 'trim', new TrimSanitizer());
$registry->register('sanitizer', 'html_special_chars', new HtmlSpecialCharsSanitizer());
$registry->register('sanitizer', 'normalize_line_breaks', new NormalizeLineBreaksSanitizer());
$registry->register('sanitizer', 'strip_tags', new StripTagsSanitizer());
$registry->register('sanitizer', 'markdown', new MarkdownSanitizer());
$registry->register('sanitizer', 'xss_sanitizer', new XssSanitizer());

// Configure HTML Purifier with specific settings for blog content
$htmlPurifier = new HtmlPurifierSanitizer();
$htmlPurifier->configure([
'allowedTags' => ['p', 'br', 'strong', 'em', 'u', 'ol', 'ul', 'li', 'a', 'img', 'h2', 'h3', 'blockquote'],
'allowedAttributes' => ['href' => ['a'], 'src' => ['img'], 'alt' => ['img']],
]);
$registry->register('sanitizer', 'html_purifier', $htmlPurifier);

$sanitizer = new Sanitizer($registry);

// Simulating form submission with potentially unsafe data
$blogPost = new BlogPost();
$blogPost->setTitle(" Exploring KaririCode: A Modern PHP Framework <script>alert('xss')</script> ");
$blogPost->setSlug(" exploring-kariricode-a-modern-php-framework \r\n");
$blogPost->setContent("
# Introduction

KaririCode is a **powerful** and _flexible_ PHP framework designed for modern web development.

<script>alert('malicious code');</script>

## Key Features

1. Robust sanitization
2. Efficient routing
3. Powerful ORM

Check out our [official website](https://kariricode.org) for more information!

<img src=\"harmful.jpg\" onerror=\"alert('xss')\" />
");
$blogPost->setAuthorName("<b>John Doe</b> <script>alert('xss')</script>");

$result = $sanitizer->sanitize($blogPost);

// Access sanitized data
echo $blogPost->getTitle(); // Sanitized title
echo $blogPost->getContent(); // Sanitized content

// Access sanitization details
print_r($result['sanitizedValues']);
print_r($result['messages']);
print_r($result['errors']);
```

This example demonstrates how to use the KaririCode Sanitizer to clean and secure blog post data, including handling of Markdown content, HTML purification, and protection against XSS attacks.

## Available Sanitizers

The Sanitizer component provides various built-in sanitizers:

### Input Sanitizers

- TrimSanitizer
- HtmlSpecialCharsSanitizer
- NormalizeLineBreaksSanitizer
- StripTagsSanitizer
- TrimSanitizer: Removes whitespace from the beginning and end of a string
- HtmlSpecialCharsSanitizer: Converts special characters to HTML entities
- NormalizeLineBreaksSanitizer: Standardizes line breaks across different operating systems
- StripTagsSanitizer: Removes HTML and PHP tags from a string

### Domain Sanitizers

- HtmlPurifierSanitizer
- JsonSanitizer
- MarkdownSanitizer
- HtmlPurifierSanitizer: Sanitizes HTML content using the HTML Purifier library
- JsonSanitizer: Validates and prettifies JSON strings
- MarkdownSanitizer: Sanitizes Markdown content

### Security Sanitizers

- FilenameSanitizer
- SqlInjectionSanitizer
- XssSanitizer
- FilenameSanitizer: Ensures filenames are safe for use in file systems
- SqlInjectionSanitizer: Protects against SQL injection attacks
- XssSanitizer: Prevents Cross-Site Scripting (XSS) attacks

For detailed information on each sanitizer, including configuration options and usage examples, please refer to the [documentation](https://kariricode.org/docs/sanitizer).

## Configuration

Each sanitizer is designed to handle specific types of data and security concerns. For detailed information on each sanitizer, please refer to the [documentation](https://kariricode.org/docs/sanitizer).
The Sanitizer component can be configured globally or per-sanitizer basis. Here's an example of how to configure the `HtmlPurifierSanitizer`:

```php
use KaririCode\Sanitizer\Processor\Domain\HtmlPurifierSanitizer;

$htmlPurifier = new HtmlPurifierSanitizer();
$htmlPurifier->configure([
'allowedTags' => ['p', 'br', 'strong', 'em'],
'allowedAttributes' => ['href' => ['a'], 'src' => ['img']],
]);

$registry->register('sanitizer', 'html_purifier', $htmlPurifier);
```

For global configuration options, refer to the `Sanitizer` class constructor.

## Integration with Other KaririCode Components

Expand Down Expand Up @@ -229,6 +342,19 @@ For a full list of available commands, run:
make help
```

## Contributing

We welcome contributions to the KaririCode Sanitizer component! Here's how you can contribute:

1. Fork the repository
2. Create a new branch for your feature or bug fix
3. Write tests for your changes
4. Implement your changes
5. Run the test suite and ensure all tests pass
6. Submit a pull request with a clear description of your changes

Please read our [Contributing Guide](CONTRIBUTING.md) for more details on our code of conduct and development process.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Expand All @@ -237,7 +363,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file

- **Documentation**: [https://kariricode.org/docs/sanitizer](https://kariricode.org/docs/sanitizer)
- **Issue Tracker**: [GitHub Issues](https://github.com/KaririCode-Framework/kariricode-sanitizer/issues)
- **Community**: [KaririCode Club Community](https://kariricode.club)
- **Community Forum**: [KaririCode Club Community](https://kariricode.club)
- **Stack Overflow**: Tag your questions with `kariricode-sanitizer`

---

Expand Down
Loading
Loading