PHPackages                             freema/perspective-api-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. freema/perspective-api-bundle

ActiveSymfony-bundle[API Development](/categories/api)

freema/perspective-api-bundle
=============================

Symfony bundle for Google Perspective API - AI-powered content moderation with flexible threshold management, caching support, and multiple usage patterns. Modern alternative to abandoned wrappers.

1.2(9mo ago)0133MITPHPPHP &gt;=8.1CI passing

Since Aug 8Pushed 9mo agoCompare

[ Source](https://github.com/freema/perspective-api-bundle)[ Packagist](https://packagist.org/packages/freema/perspective-api-bundle)[ Docs](https://github.com/freema/perspective-api-bundle)[ RSS](/packages/freema-perspective-api-bundle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (18)Versions (5)Used By (0)

Perspective API Bundle for Symfony
==================================

[](#perspective-api-bundle-for-symfony)

[![Latest Stable Version](https://camo.githubusercontent.com/868687a067b2ae868df8d8948c75e593653ce342616a4b16d5c80333f0a138a3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f667265656d612f70657273706563746976652d6170692d62756e646c652e737667)](https://packagist.org/packages/freema/perspective-api-bundle)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP Version Require](https://camo.githubusercontent.com/812753320cc9c8bf2554b6e29a2c3f87e984b291cc425c1a7e27402516fdb4ee/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f667265656d612f70657273706563746976652d6170692d62756e646c652e737667)](https://packagist.org/packages/freema/perspective-api-bundle)[![Symfony Version](https://camo.githubusercontent.com/aed213b15f09e76ab570d806d0e1f0537cf5a307a2cbd9a57beeac8613e2a160/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73796d666f6e792d253545352e34253743253545362e30253743253545372e302d627269676874677265656e)](https://symfony.com)

A powerful Symfony bundle that integrates Google's Perspective API for content moderation and toxicity detection in your applications. Built with flexibility in mind, it supports multiple threshold management strategies, caching, and can be used as a standalone service or Symfony validator.

🎯 Key Features
--------------

[](#-key-features)

- **🔧 Flexible Threshold Management** - Static config, database-driven, or runtime dynamic thresholds
- **💾 Built-in Caching Support** - Reduce API calls and improve performance
- **🎨 Multiple Usage Patterns** - Use as a service, validator constraint, or command-line tool
- **🌍 Multi-language Support** - Analyze content in multiple languages with automatic detection
- **📊 Rich Analysis Results** - Detailed scoring across multiple toxicity dimensions
- **⚡ Production Ready** - Battle-tested with proper error handling and logging
- **🔄 Easy Migration** - Simple migration path from deprecated libraries like `bredmor/comment-analyzer`

🚀 Why This Bundle?
------------------

[](#-why-this-bundle)

This bundle was created as a modern, maintained alternative to abandoned Perspective API wrappers. It provides a clean, Symfony-native integration that follows best practices and offers the flexibility needed for real-world applications.

Unlike simple API wrappers, this bundle understands that different parts of your application might need different moderation thresholds - a children's section needs stricter controls than a general discussion forum. It allows you to implement context-aware content moderation without sacrificing simplicity.

⚠️ Important Note About Google's Gemini LLM Integration
-------------------------------------------------------

[](#️-important-note-about-googles-gemini-llm-integration)

Google has integrated their Gemini LLM into the Perspective API, which represents a shift from traditional deterministic models to AI-powered analysis. While the API remains fully functional and is actively supported by Google, please be aware that:

- **Consistency**: The same text might receive slightly different scores when analyzed at different times
- **Predictability**: Results may be less deterministic compared to traditional machine learning models
- **Recommendation**: Consider implementing caching to ensure consistent moderation decisions for the same content

This change reflects Google's commitment to improving the API with cutting-edge AI technology, but it's important to understand these characteristics when implementing content moderation.

📋 Requirements
--------------

[](#-requirements)

- PHP 8.1 or higher
- Symfony 5.4, 6.x, or 7.x
- Google Perspective API key ([Get one here](https://developers.perspectiveapi.com/s/docs-get-started))

🔧 Advanced Configuration
------------------------

[](#-advanced-configuration)

### HTTP Client Options

[](#http-client-options)

The bundle supports custom HTTP client configuration for environments that require proxy servers or specific timeouts:

```
# config/packages/perspective_api.yaml
perspective_api:
    api_key: '%env(PERSPECTIVE_API_KEY)%'

    # Configure HTTP client options
    http_client_options:
        # Use proxy server
        proxy: '%env(HTTP_PROXY)%'

        # Request timeout in seconds
        timeout: 30

        # Maximum number of redirects
        max_redirects: 5

        # Custom headers
        headers:
            'User-Agent': 'MyApp/1.0'

        # Any other Symfony HTTP client option
        verify_peer: true
        verify_host: true
```

This is particularly useful for:

- Corporate environments with proxy requirements
- Applications with specific network configurations
- Custom timeout requirements for slow networks
- Adding custom headers for monitoring or tracking

🛠️ Use Cases
------------

[](#️-use-cases)

This bundle is perfect for:

- **Comment Systems** - Automatically moderate user comments before publication
- **Forums &amp; Communities** - Maintain healthy discussion environments
- **Social Platforms** - Filter toxic content in real-time
- **Content Management** - Review and flag potentially problematic content
- **Customer Support** - Filter inappropriate messages in support tickets
- **Educational Platforms** - Ensure safe learning environments

📦 Installation
--------------

[](#-installation)

Install the bundle using Composer:

```
composer require freema/perspective-api-bundle
```

⚙️ Configuration
----------------

[](#️-configuration)

### Basic Configuration

[](#basic-configuration)

```
# config/packages/perspective_api.yaml
perspective_api:
    api_key: '%env(PERSPECTIVE_API_KEY)%'

    # Default thresholds for all attributes
    thresholds:
        TOXICITY: 0.5
        SEVERE_TOXICITY: 0.3
        IDENTITY_ATTACK: 0.5
        INSULT: 0.5
        PROFANITY: 0.5
        THREAT: 0.5

    # Which attributes to analyze
    analyze_attributes:
        - TOXICITY
        - SEVERE_TOXICITY
        - IDENTITY_ATTACK
        - INSULT
        - PROFANITY
        - THREAT

    # Default language for analysis
    default_language: 'en'

    # Allow runtime threshold override
    allow_runtime_override: true

    # Optional: Custom threshold provider service
    # threshold_provider: 'my.custom.threshold.provider'

    # Optional: HTTP client options (proxy, timeout, etc.)
    # http_client_options:
    #     proxy: 'http://proxy.example.com:8080'
    #     timeout: 30
    #     max_redirects: 5
```

### Environment Variables

[](#environment-variables)

```
# .env.local
PERSPECTIVE_API_KEY=your_api_key_here

# Optional: HTTP proxy configuration
HTTP_PROXY=http://proxy.example.com:8080
HTTPS_PROXY=http://proxy.example.com:8080
```

📖 Usage
-------

[](#-usage)

### Basic Service Usage

[](#basic-service-usage)

```
use Freema\PerspectiveApiBundle\Service\PerspectiveApiService;

class CommentController
{
    public function __construct(
        private readonly PerspectiveApiService $perspectiveApi
    ) {}

    public function submitComment(Request $request): Response
    {
        $comment = $request->get('comment');

        // Analyze the comment
        $result = $this->perspectiveApi->analyzeText($comment);

        // Check if content is safe
        if (!$result->isSafe()) {
            // Get specific violations
            $violations = $result->getViolations();

            return $this->json([
                'error' => 'Your comment contains inappropriate content',
                'violations' => $violations
            ], 400);
        }

        // Save the comment...
    }
}
```

### Using as a Validator

[](#using-as-a-validator)

```
use Freema\PerspectiveApiBundle\Validator\PerspectiveContent;
use Symfony\Component\Validator\Constraints as Assert;

class Comment
{
    #[Assert\NotBlank]
    #[PerspectiveContent(
        thresholds: [
            'TOXICITY' => 0.5,
            'PROFANITY' => 0.3
        ],
        message: 'Your comment contains inappropriate content.'
    )]
    private string $content;
}
```

### Using in Symfony Forms

[](#using-in-symfony-forms)

The bundle provides a `PerspectiveTextType` for easy integration into Symfony forms:

```
use Freema\PerspectiveApiBundle\Form\Type\PerspectiveTextType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class CommentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('author', TextType::class)
            ->add('content', PerspectiveTextType::class, [
                'perspective_thresholds' => [
                    'TOXICITY' => 0.7,
                    'PROFANITY' => 0.5,
                ],
                'perspective_language' => 'en',
                'perspective_message' => 'Please keep your comments respectful.',
                'attr' => [
                    'rows' => 5,
                    'placeholder' => 'Write your comment...'
                ]
            ])
            ->add('submit', SubmitType::class);
    }
}
```

#### Form Type Options

[](#form-type-options)

- `perspective_validation` (bool, default: `true`) - Enable/disable Perspective validation
- `perspective_thresholds` (array, default: `[]`) - Custom thresholds for validation
- `perspective_language` (string|null, default: `null`) - Language for analysis
- `perspective_message` (string|null, default: `null`) - Custom validation error message

```
// Disable validation for specific form
$builder->add('content', PerspectiveTextType::class, [
    'perspective_validation' => false
]);

// Use form with custom validation message
$builder->add('message', PerspectiveTextType::class, [
    'perspective_thresholds' => ['TOXICITY' => 0.8],
    'perspective_message' => 'This content violates our community guidelines.'
]);
```

### Custom Threshold Provider

[](#custom-threshold-provider)

Implement dynamic thresholds based on context:

```
use Freema\PerspectiveApiBundle\Contract\ThresholdProviderInterface;

class ContextualThresholdProvider implements ThresholdProviderInterface
{
    public function getThresholds(): array
    {
        // Return different thresholds based on current context
        if ($this->isChildrenSection()) {
            return [
                'TOXICITY' => 0.3,
                'PROFANITY' => 0.1,
                'THREAT' => 0.1,
            ];
        }

        return [
            'TOXICITY' => 0.7,
            'PROFANITY' => 0.5,
            'THREAT' => 0.5,
        ];
    }
}
```

### Using Threshold Resolver

[](#using-threshold-resolver)

```
// Set a custom resolver function
$perspectiveApi->setThresholdResolver(function (string $attribute, array $context) {
    // Custom logic based on attribute and context
    if ($attribute === 'PROFANITY' && $context['strict_mode']) {
        return 0.1;
    }
    return null; // Use default
});

// Use with context
$result = $perspectiveApi->analyzeText(
    $text,
    null,
    null,
    ['strict_mode' => true]
);
```

### Batch Analysis

[](#batch-analysis)

```
$texts = [
    'This is a normal comment',
    'This might be problematic',
    'Another text to analyze'
];

$results = $this->perspectiveApi->analyzeBatch($texts);

foreach ($results as $index => $result) {
    echo "Text {$index}: " . ($result->isSafe() ? 'Safe' : 'Unsafe') . PHP_EOL;
}
```

### Analyzing with Specific Attributes

[](#analyzing-with-specific-attributes)

```
// Analyze only specific attributes
$result = $this->perspectiveApi->analyzeWithAttributes(
    $text,
    ['TOXICITY', 'THREAT'],
    'en'
);
```

🧪 Development
-------------

[](#-development)

For development setup, testing, and contribution guidelines, see:

- [DEVELOP.md](DEVELOP.md) - Development environment setup and testing
- [CONTRIBUTING.md](CONTRIBUTING.md) - Contribution guidelines

🔄 Migration from bredmor/comment-analyzer
-----------------------------------------

[](#-migration-from-bredmorcomment-analyzer)

If you're migrating from the deprecated `bredmor/comment-analyzer` library:

```
// Old way with bredmor/comment-analyzer
$analyzer = new CommentAnalyzer($apiKey);
$response = $analyzer->analyze($text);
$toxicity = $response->toxicity();

// New way with this bundle
$result = $perspectiveApi->analyzeText($text);
$toxicity = $result->getScore('TOXICITY');
$isSafe = $result->isSafe();
```

📊 Available Attributes
----------------------

[](#-available-attributes)

- **TOXICITY** - A rude, disrespectful, or unreasonable comment
- **SEVERE\_TOXICITY** - A very hateful, aggressive, disrespectful comment
- **IDENTITY\_ATTACK** - Negative or hateful comments targeting identity
- **INSULT** - Insulting, inflammatory, or negative comment
- **PROFANITY** - Swear words, curse words, or profane language
- **THREAT** - Describes an intention to inflict pain or violence

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License
---------

[](#-license)

This bundle is released under the MIT License. See the bundled LICENSE file for details.

🙏 Credits
---------

[](#-credits)

- Created and maintained by [Freema](https://github.com/freema)
- Inspired by the need for a modern, maintained Perspective API integration
- Thanks to all contributors

📚 Resources
-----------

[](#-resources)

- [Google Perspective API Documentation](https://developers.perspectiveapi.com/s/docs)
- [Symfony Documentation](https://symfony.com/doc)
- [Bundle Issues &amp; Support](https://github.com/freema/perspective-api-bundle/issues)

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance58

Moderate activity, may be stable

Popularity13

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

3

Last Release

277d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1feadbd856db0d9578f7e3c5221c76bd76d4cdfa745bd748be918b2cd10de70c?d=identicon)[Freema](/maintainers/Freema)

---

Top Contributors

[![freema](https://avatars.githubusercontent.com/u/2912985?v=4)](https://github.com/freema "freema (15 commits)")

---

Tags

googlegoogle-perspective-apisymfonysymfony-bundlesymfonybundlegoogleaicontent moderationmoderationtext analysisperspective-apitoxicitycomment-filtercontent-safety

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/freema-perspective-api-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/freema-perspective-api-bundle/health.svg)](https://phpackages.com/packages/freema-perspective-api-bundle)
```

###  Alternatives

[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[simplesamlphp/simplesamlphp

A PHP implementation of a SAML 2.0 service provider and identity provider.

1.1k12.4M193](/packages/simplesamlphp-simplesamlphp)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
