cognetif / perch-cms-utilities
Cognetif Perch CMS Utilities
Requires
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^8.5
This package is auto-updated.
Last update: 2024-02-26 14:51:22 UTC
README
This is a library of Utilities primarily for use with Perch CMS
Installation
The recommended installation is via Composer with the require command as follows :
$ composer require cognetif/perch-cms-utlities
Development Requirements
- PHP 7.2
- Composer
- PHP Unit 8+
- XDebug : for code coverage report
Testing
To run tests on the application from the project root run: $ ./phpunit
Tests are run with PHP Unit and a build report can be found under: /Tests/Report/index.html
.
Tests against PHP 7.2, and PHP 7.3 are run automatically as part of the CI pipeline when a commit is pushed to either develop or master.
License
This project is licensed under the MIT license. It is free, open source, and GPL friendly. You can use it for commercial projects, open source projects, or really almost whatever you want.
The maintainers of this project will assume no liability for loss of any kind as a result of using this software.
Usage
Most utilities in this project can just be included via regular composer auto loading. There are some exceptions:
Template Filters
To include a specific template filter you need to enable Template Filters in the perch config.php
file :
define('PERCH_TEMPLATE_FILTERS', true);
And register each template filter in perch/addons/templates/filters.php
:
# Rot13Filter
PerchSystem::register_template_filter('rot13', '\Cognetif\PerchCms\TemplateFilters\Rot13Filter');
Then to use the template filter on a template field:
<perch:content id="email" type="text" filter="rot13" label="Email" />
Collection
Instead of using arrays, for everything, try using a Collection object, its much less memory intensive. Plus it can be used pretty much like an array anyway. They're typed so you don't need to worry if the element is an instance of the right class or primitive type
$typeCollection = Cognetif\PerchCms\App\Collection::forType('My\Application\Namespace\MyTypeClass');
// or
$intCollection = Cognetif\PerchCms\App\Collection::forInt();
// or
$floatCollection = Cognetif\PerchCms\App\Collection::forFloat();
// or
$boolCollection = Cognetif\PerchCms\App\Collection::forBoolean();
// or
$stringCollection = Cognetif\PerchCms\App\Collection::forString();
Collection Functions
Each collection has the following API:
Collection::add($value, $key = null): self
: Adds an item to the collection, optionally with a key.Colleciton::has($key):bool
: Returns true if an item is found by the key in the collection.Colleciton::get($key)
: Returns the item by key if an item is found by the key in the collection, returns null if not found.
Counting & Iterating Collections
Collections implement the \Countable
interface and the IteratorAggregate
interface so they can be used in a foreach loop and with the count function just like arrays.
That's mainly what you're doing with arrays anyway right?
Perch CMS Factory Wrappers
Two classes exist in this library that are meant to help implementation of the Perch Factory method for custom apps.
use Cognetif\PerchCms\App\Factory;
use Cognetif\PerchCms\App\ValidatedModel;
The Factory class is a wrapper for the PerchAPI_Factory
class but includes the standard_restrictions()
function to populate the where
clause of the sql statements.
To use within a Factory extended child class, simply set the $this->where
property to something like AND ...
which will use as the first part of the sql statement used in the PerchFactory.
Note that the where condition gets reset to '' on each call to standard_restrictions()
, so if you need something static for all queries, you can override the standard_restrictions()
function to provide that functionality.
The ValidatedModel class provides a method of validating the data to be used for a PerchAPI_Base
object. In the class you write that extends the ValidatedModel
class,
you can use the ValidatedModel::addValidator(string $field, ValidatorAbstract $validator)
function. This will apply the given validation rules to the given field.
To validate the model, add your field validators in the constructor:
/** MyModel.php */
use \Cognetif\PerchCms\App\ValidatedModel;
use Cognetif\PerchCms\App\Validation\Validators\Required;
use Cognetif\PerchCms\App\Validation\Validators\MaxLength;
use Cognetif\PerchCms\App\Validation\Validators\Multi;
class MyModel extends ValidatedModel
{
public function __construct() {
parent::__construct();
/**
* Adds a required validator to the 'email' field
* Adds a required AND max length of 45 chars validators to the 'first_name' field.
*/
$this->addValidator('email', new Required('Property 1 is required'))
->addValidator('first_name',
(new Multi())->addValidator(new Required('First name is required'))
->addValidator(new MaxLength(45, 'First name must be at most 45 characters'))
);
}
}
Then elsewhere in your app, you can create validate with an instance:
$model = new MyModel();
$response = $model->validateData(['email' => 'me@email.com']);
Or validate statically:
$response = MyModel::Validate(['email' => 'me@email.com']);
Or Validate Self:
$model = new MyModel(['email' => 'me@email.com']);
$response = $model->validateSelf();
Both the validateData and Validate functions return a ValidationResponse object from which you can verify if the model validated and retrieve from the response body, the error message of each of the fields that did not pass validation.
/** @var Cognetif\PerchCms\App\Validation\ValidationResponse $response */
if (!$response->isValid()){
foreach($response->getBody as $field => $message) {
echo "Field: {$field} Error: {$message}";
}
}
Validation Module
The validators shown above in the ValidatedModel object can also be used individually:
Note on the $inclusive flag: Default true, when testing a range, inclusive will include the bounds in the range, when false the bounds will be out of range. Note on the $strict flag: Default true, when testing a numeric validator, if strict mode is on, the validator will take into consideration type. If off, a numeric representation of any type will pass, for example: 10, 10.0, '10' will all pass FloatValue and IntegerValue validators when strict mode is off.
Validating a value:
All validators implement a ValidationInterface which requires a validate($value):bool
function to be implemented by the validator. The should also extend the ValidatorAbstract validator to inherit the messaging and strict functionality.
Required validator example:
$value = $_GET['param'];
$validator = new Required('Please enter a value for param');
if (!$validator->validate($value)) {
echo $validator->getMessage();
}
Chaining Validators For a single value:
There is a special type of validator which itself is a collection of validators:
Cognetif\PerchCms\App\Validation\Validators\Multi
This Validator once instantiated, can chain its own Multi::addValidator(ValidatorAbstract $validator) method to add multiple validators to the same value:
$value = $_GET['param'];
$validator= new Multi();
$validator->addValidator(new Required('Param is required'))
->addValidator(new MaxLength(45, 'Param must be at most 45 characters'));
if (!$validator->validate($value)) {
echo $validator->getMessage();
}
Note that the Multi validator will stop validating on the first failure and the message will represent that of the failed validator.
Validator Types:
All from within the Cognetif\PerchCms\App\Validation\Validators
namespace:
Between($min, $max, bool $inclusive = true, string $message = '')
: Validates a integer or float value is between a min and max value. Null and other types will return false.FloatValue(string $message = '', bool $strict = true)
: Validates the type of a value to be Float.IntegerValue(string $message = '', bool $strict = true)
: Validates the type of a value to be Integer.MaxValue($max, bool $inclusive = true, string $message = '')
: Validate the value is less than the max bound.MinValue($min, bool $inclusive = true, string $message = '')
: Validate the value is greater than the min bound.MaxLength(int $length = 0, string $message = '')
: Validates the value is no longer than the given length.MinLength(int $length = 0, string $message = '')
: Validates the value is longer than the given length.Multi()
: Chains multiple validators together to validate in sequence. Stops validating at the first failure.Regexp(string $pattern = '', string $message = '')
: Validates the value against the Regular Expression pattern.Required(string $message = '')
: Validates the values exists.