PHP code example of freema / perspective-api-bundle

1. Go to this page and download the library: Download freema/perspective-api-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

freema / perspective-api-bundle example snippets


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...
    }
}

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;
}

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);
    }
}

// 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.'
]);

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,
        ];
    }
}

// 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]
);

$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;
}

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

// 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();