Code Monkey home page Code Monkey logo

akismet's Introduction

Akismet Client Library

Continuous Integration Psalm Type Coverage Latest Stable Version Total Downloads

Introduction

Provides a straight-forward way of using the Akismet anti-spam service in any-old PHP application.

Installation & Requirements

Requires PHP ~8.0 || ~8.1 || ~8.2

The library does not include an HTTP client, so if your project does not already have a PSR-18 HTTP Client installed, you will need to install one in order to use it. There are many HTTP clients to choose from, for example the popular libraries Guzzle or HttpPlug.

The library also requires that you have a PSR-17 (HTTP Factories) library installed, again, you can find implementations on Packagist and I personally favour laminas/laminas-diactoros.

composer require laminas/laminas-diactoros
composer require php-http/curl-client
composer require gsteel/akismet

Basic Usage

Construct a client

Once you have the requisite HTTP related libraries installed, they should become discoverable with the shipped discovery library. Provide an Api key, and the default website address that you will be operating with to the constructor, and you’ll have a ready-to-use client:

<?php

use GSteel\Akismet\Client;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;

$client = new Client(
    'myApiKey',
    'https://my-website.example.com',
    Psr18ClientDiscovery::find(),
    Psr17FactoryDiscovery::findRequestFactory(),
    Psr17FactoryDiscovery::findStreamFactory()
);

// Check the validity of your API key

$result = $client->verifyKey();
assert($result === true);

Comment Parameters & Checking Content

The primary concern of the library is to check requests such as comments and form submissions to ascertain whether the content is "Spam" or "Ham".

The Akismet API has a number of parameters available to improve the accuracy of the check which have been encapsulated into an immutable value object \Gsteel\Akismet\CommentParameters.

If you are familiar with the parameter names, you can pass in an array to the constructor of this object, otherwise you can call various methods to build an object to include all the information you wish to provide.

<?php

use GSteel\Akismet\AkismetClient;
use GSteel\Akismet\CommentParameters;
use GSteel\Akismet\CommentType;

assert($client instanceof AkismetClient);

$parameters = (new CommentParameters())
    ->withComment('Some comment Content', CommentType::contactForm())
    ->withRequestParams($_SERVER['REMOTE_ADDR']);
    
$result = $client->check($parameters);

assert($result->isSpam());

There are a considerable number of additional arguments and methods available that can be used to provide as much context as possible to the API, there is also a named constructor that is useful in an environment that utilises PSR-7 Messages:

<?php

use GSteel\Akismet\CommentParameters;
use Psr\Http\Message\ServerRequestInterface;

assert($request instanceof ServerRequestInterface);

$parameters = CommentParameters::fromRequest($request);

Submitting False Positives or False Negatives

Submitting content that was incorrectly classified as Spam can be achieved by sending the same payload used in check() to the method submitHam(). Conversely, you can submit incorrectly classified Ham as actual Spam with submitSpam():

<?php

use GSteel\Akismet\AkismetClient;
use GSteel\Akismet\Result;

assert($client instanceof AkismetClient);

$parameters = CommentParameters::fromRequest($request);
$result = $client->check($parameters);

// Result is incorrectly classified as spam:
$client->submitHam($result->parameters());

// Result is incorrectly classified as ham:
$client->submitSpam($result->parameters());

You can serialise and un-serialise a Result from the clients check() method to a JSON string:

<?php

use GSteel\Akismet\Result;

assert($result instanceof Result);

$jsonString = json_encode($result);

$hydratedResult = Result::fromJsonString($jsonString);

Coupled with your own method of identifying a specific request, you could create a mechanism to store the result in order to submit it as ham or spam based on user feedback.

Error Handling

All errors implement \GSteel\Akismet\GenericException so it is possible to catch any errors thrown by the library with a single type. Notable concrete exceptions include:

  • ApiError - Indicating that an api request failed because of an invalid key for example
  • HttpError - A failure to communicate with the Akismet via HTTP
  • InvalidRequestParameters - Required values missing, or invalid values given to CommentParameters

PSR-11 Containers

A factory is shipped in \GSteel\Akismet\Container\ClientDiscoveryFactory that can be wired up in your DI container of choice that leverages Http Discovery to inject Http clients and factories etc.

It assumes that the container will return an array or something implementing ArrayAccess by asking for config It further assumes that this configuration structure contains the following information:

<?php
$config = [
    'akismet' => [
        'key' => 'Your API Key',
        'website' => 'https://you.example.com',
    ],
];

License

Released under the MIT License - see the LICENSE file for details

akismet's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar gsteel avatar renovate[bot] avatar

Watchers

 avatar  avatar  avatar

akismet's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Pending Branch Automerge

These updates await pending status checks before automerging. Click on a checkbox to abort the branch automerge, and create a PR instead.

  • Lock file maintenance

Warning

Renovate failed to look up the following dependencies: Failed to look up packagist package psr/http-client-implementation, Failed to look up packagist package psr/http-factory-implementation.

Files affected: composer.json


Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1 || ~8.2 || ~8.3
  • myclabs/php-enum ^1.8.3
  • php-http/discovery ^1.14.1
  • psr/container ^1.0 || ^2.0
  • psr/http-client ^1.0.1
  • psr/http-client-implementation *
  • psr/http-factory ^1.0.1
  • psr/http-factory-implementation *
  • webmozart/assert ^1.11
  • doctrine/coding-standard ^12.0.0
  • laminas/laminas-diactoros ^3.3.1
  • php-http/client-common ^2.7.1
  • php-http/curl-client ^2.3.2
  • php-http/mock-client ^1.6
  • phpunit/phpunit ^10.5.30
  • vimeo/psalm ^5.25.0
  • psalm/plugin-phpunit ^0.19.0
github-actions
.github/workflows/continuous-integration.yml
  • laminas/laminas-ci-matrix-action 1.27.1
  • laminas/laminas-continuous-integration-action 1.40.0
.github/workflows/release-on-milestone-closed.yml
.github/workflows/scheduled-unit-tests.yml
  • actions/checkout v4.1.7
  • shivammathur/setup-php 2.31.1

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.