[READ-ONLY] Properties define model metadata.

Overview

Charcoal Property

Properties define object's metadata. They provide the building blocks of the Model's definition.

Properties are defined globally for objects (charcoal models) in its metadata. They provide properties definition, storage definition and validation definition.

The metadata() method is defined in \Charcoal\Model\DescribableInterface. The properties() method is defined in \Charcoal\Property\DescribablePropertyInterface.

How to install

The preferred (and only suppported) way of installing charcoal-property is with composer:

★ composer require charcoal/property

For a complete, ready-to-use project, start from the boilerplate:

★ composer create-project charcoal/project-boilerplate:@dev --prefer-source

Dependencies

Property options

The basic property interface (API) requires / provides the following members:

Name (V) Type Description
ident string The property idenfifier (typically, its containing object matching property name).
label Translation ...
l10n bool If true, then the data should be stored in a l10n-aware structure (be translatable).s
hidden bool
multiple bool Multiple values can be held and stored, if true.
required bool
unique bool
storable bool
active bool

(V) indicates options used in validation

All those methods can be accessed either via the setData() method or with a standard PSR-1/PSR-2 getter / setter. (foo would have foo() as a getter and setFoo() as a setter).

Data retrieval

  • To get a normalized value, use the parseVal($val) method.
  • To get a string-safe, displaybale value, use displayVal($val).
  • To get the storage-ready format, use storageVal($val).

Custom data retrieval methods can be further defined in each properties. (For example, formatted date or custom color formats).

Default validation

Validation is provided with a Validator object, from charcoal-core.

  • required
  • unique
  • allow_null

Validation is being rebuilt in a new charcoal-validator package.

Source and storage methods

Properties need 4 method to integrate with a SQL source:

  • sqlEncoding() string The SQL column encoding & collation (ex: utf8mb4)
  • sqlExtra() string Raw SQL string that will be appended to
  • sqlType() string The SQL column type (ex: VARCHAR(16))
  • sqlPdoType() integer The PDO column type (ex: PDO::PARAM_STR)

 Those methods are abstract and therefore must be implemented in actual properties.

Types of properties

Retrieve

Boolean Property

The boolean property is one of the simplest possible: it simply holds boolean (true / false) values.

Boolean Property options

The boolean property adds the following concepts to the basic property options:

Name (V) Type Description
false_label - Translation Label, for "true" value.
true_label - Translation Label, for "false" value.

(V) indicates options used in validation

Boolean properties can not be multiple. (multiple() will always return false). Calling setMultiple(true) on a boolean property will throw an exception.

Color Property

The color property stores a color. If alpha is not supported, it is stored as an hexadecimal value (ex: #5590BA). If alpha is supported, it is stored as a rgba() string value (ex: rgb(85, 144, 186, 0.5)).

Color Property options

The boolean property adds the following concepts to the basic property options:

Name (V) Type Description
support_alpha boolean ...

(V) indicates options used in validation

DateTime Property

The datetime property store a date (and time) value.

DateTime Property options

The datetime property adds the following concepts to the basic property options:

Name (V) Type Description
min DateTime Minimum date value. If 0, empty or null, then there is no minimal constraint.
max DateTime Maximum date value. If 0, empty or null, then there is no maximal constraint.
format string The date format is a string (in PHP's DateTime format()) that manages how to format the date value for display. Defaults to "Y-m-d H:i:s".

(V) indicates options used in validation

DateTime properties can not be multiple. (multiple() will always return false). Calling setMultiple(true) on a date-time property will throw an exception.

ID Property

The ID property holds an ID, typically the main object identifier (unique index key).

The ID value can be generated by many mode:

  • auto-increment is the default mode. It uses the storage engine (mysql) auto-increment feature to keep an auto-incrementing integer index.
  • uniqid creates a 13-char string with PHP's uniqid() function.
  • uuid creates a 36-char string (a RFC-4122 v4 Universally-Unique Identifier, uuidv4).

ID Property options

The ID property adds the following concepts to the basic property options:

Name (V) Type Description
mode string The ID generation mode. Can be auto-increment, uniqid or uuid.

Id properties can not be multiple. (multiple() will always return false). Calling setMultiple(true) on an id property will throw an exception.

ID Property custom save

Upon save($val), the ID property auto-generates and ID if its mode is uniqid or uuid.

Note: The auto-increment mode does not do anything on save; it relies on the storage engine / driver to implement auto-incrementation.

IP Property

The IP property holds an IP address. Only IPv4 addresses are supported for now.

There is 2 different storage modes for IP:

  • string is the default mode. It stores the IP address like 192.168.1.1.
  • int stores the IP as a signed long integer.

Ip properties can not be multiple. (multiple() will always return false). Calling setMultiple(true) on an ip property will throw an exception.

File Property

File property holds an uploadable file.

Values

Note that only a relative1 file path should be stored in the database.

1 Relative to project's ROOT + the property's upload_path.

File Property options

The file property adds the following concepts to the basic property options:

Name (V) Type Description
public_access bool If the public access is true (default) then the file will be stored in a public filesystem. If not, then it will be stored in a private (non-web-accessible) filesystem.
upload_path string The default upload path, relative to base_url, where the uploaded files will be stored.
overwrite bool If true, when a target file already exists on the filesystem it will be overwritten. If false, a new unique name will be generated (with a suffix).
accepted_mimeypes string[] List of accepted mimetypes. Leave empty to accept all types (no mimetype constraint).
max_filesize integer Maximum allowed file size, in bytes. If 0, null or empty, then there are no size constraint.

(V) indicates options used in validation

Additional file methods

  • mimetype() and setMimetype()
  • filesize() and setFilesize()
  • dataUpload()
  • fileUpload()

File Property Custom Save

Upon save($val), the File property attempts to upload the file or create a file from data, if necessary. The uploaded file's path (relative) is returned.

Specialized File properties

Audio File Property

Audio property are specialized file property thay may only contain audio data.

Accepted mimetypes

The AudioProperty extends FileProperty therefore provides "accepted mimetypes".

Default accepted mimetypes are:

  • audio/mp3
  • audio/mpeg
  • audio/wav
  • audio/x-wav.

Audio file Property options

The audio property adds the following concepts to the file property options:

Name (V) Type Description
min_length DateTime Minimum audio length, in seconds. If 0, null or empty, then there is no minimal constraint.
max_length DateTime Maximum audio length, in seconds. If 0, null or empty, then there is no maximal constraint.

(V) indicates options used in validation

Image File Property

Image property are specialized file property thay may only contain image data.

Accepted mimetypes

The ImageProperty extends FileProperty therefore provides "accepted mimetypes".

Default accepted mimetypes are:

  • image/gif
  • image/jpg
  • image/jpeg
  • image/pjpeg
  • image/png
  • image/svg+xml
  • image/webp

Image file Property options

The audio property adds the following concepts to the file property options:

Name (V) Type Description
effects array Array of charcoal-image effects options.

(V) indicates options used in validation

Lang Property

Language properties hold a language value.

The LangProperty implements the SelectablePropertyInterface, but hardcode its choices() method to return the active language (from [charcoal-translator](https://github.com/locomotivemtl/charcoal-translator)).

Number Property

Number properties hold any kind of numeric data.

Object Property

Object properties hold a reference to an external object of a certain type.

Values

The target's identifer (determined by its obj-type's key, which is typically "id") is the only thing held in the value / stored in the database. When displayed (with displayVal()), a string representation of the object should be rendered.

Object Property options

The object property adds the following concepts to the basic property options:

Name (V) Type Description
obj-type string The target object's type. In a string format that can be fetched with a ModelFactory.
pattern string The rendering pattern, used to display the object(s) when necessary.
(V) indicates options used in validation

String Property

String Property options

The string property adds the following concepts to the basic property options:

Name (V) Type Description
max_length integer Maximum allowed length, in (multibytes) characters.
min_length integer Minimum allowed length, in (multibytes) characters.
regexp string A validation regular expression that must be matched exactly.
allow_empty bool If empty strings are allowed.
(V) indicates options used in validation

String default data

By default, the string property is targetted at small string (a maximum length) of 255 characters

Specialized String properties

Html String Property

HTML properties are specialized string property that may only contain HTML strings (instead of plain string).

Password String Property

Password properties are specialized string property that holds (encrypted) password data.

Encryption is performed with PHP's password_hash function.

Password Property Custom Save

Upon save($val), the Password property hashes (or rehashes) the password to be stored safely (encrypted).

Phone String Property

Phone properties are specialized string property that holds a phone number.

Right now, only "north-american" phone number styles are supported.

Text String Property

Text properties are specialized string property thay typically holds longer text strings.

Map Structure Property

Map structure properties hold complex map structure data, which can be points (markers), lines and / or polygons.

Properties table summary, for developers

Name Data type Multiple Custom Save Custom Parse
Audio mixed
Boolean bool No
Color string Yes
DateTime DateTime No Yes
File mixed Yes
Html string
Id mixed No Yes
Image mixed
Ip mixed No
Lang string
MapStructure mixed
Number numeric
Object mixed Yes
Password string Yes
Phone string
String string
Structure mixed Yes
Text string
Url string

Development

To install the development environment:

★ composer install --prefer-source

Run the code checkers and unit tests with:

★ composer test

API documentation

Development dependencies

  • phpunit/phpunit
  • squizlabs/php_codesniffer
  • php-coveralls/php-coveralls

Continuous Integration

Service Badge Description
Travis Build Status Runs code sniff check and unit tests. Auto-generates API documentaation.
Scrutinizer Scrutinizer Code Quality Code quality checker. Also validates API documentation quality.
Coveralls Coverage Status Unit Tests code coverage.
Sensiolabs SensioLabsInsight Another code quality checker, focused on PHP.

Coding Style

The Charcoal-Property module follows the Charcoal coding-style:

Coding style validation / enforcement can be performed with composer phpcs. An auto-fixer is also available with composer phpcbf.

Authors

License

Charcoal is licensed under the MIT license. See LICENSE for details.

Report Issues

In case you are experiencing a bug or want to request a new feature head over to the Charcoal monorepo issue tracker

Contribute

The sources of this package are contained in the Charcoal monorepo. We welcome contributions for this package on charcoalphp/charcoal.

You might also like...
A SilverStripe module for conveniently injecting JSON-LD metadata into the header of each rendered page in SilverStripe

A SilverStripe module for conveniently injecting JSON-LD metadata into the header of each rendered page in Silver

Joole Reflector - used to work with the properties of objects, their changes and merges

Joole Reflector allows you to change protected, as well as private properties of an object.

WordPress plugin renames image filenames to be more SEO friendly, based on the post's data and image metadata.

=== Automatic image Rename === Contributors: wpsunshine Tags: image, images, SEO, rename, optimization Requires at least: 5.0 Tested up to: 6.2.2 Stab

Easily create and read Corona Warn App Check-In URLs

bauer-kirch/cwa-event-registration-url This PHP library allows generating Check-In URLs for the Corona Warn App which can then be used to generate a Q

A PHP library to read and validate EU Digital COVID Certificates

CovPassCheck PHP A PHP library to read and validate EU Digital COVID Certificates. Install composer require stwon/covpasscheck-php Usage Currently, th

Learn how to run WordPress with Docker. Read about our experiences and start off with an easy boilerplate.
Learn how to run WordPress with Docker. Read about our experiences and start off with an easy boilerplate.

Hi! We're Dan and Jay. We're a two person team with a passion for open source products. We created Server Side Up to help share what we learn. Find us

A Magento 2 dashboard to display installed extensions. Read the blog post on some of the thinking behind it:
A Magento 2 dashboard to display installed extensions. Read the blog post on some of the thinking behind it:

Extension Dashboard for Magento 2 This module adds a dashboard to review all installed extensions in the Magento admin (Magento 2.3.0+ for now only).

Read and show values from form valid

read-and-show-values-from-form-valid Escribe un programa PHP que permita al usuario rellenar un formulario de registro con los datos de nombre, contra

Simple loader to send request and read response from address.

Simple loader to send request and read response from address. Uses cURL extension. Composer package.

Owner
The Charcoal PHP Framework
Charcoal is a web framework and content management system that adapts to all your project needs.
The Charcoal PHP Framework
The package provides an expressive "fluent" way to define model attributes.

The package provides an expressive "fluent" way to define model attributes. It automatically builds casts at the runtime and adds a native autocompletion to the models' properties.

Boris Lepikhin 506 Dec 28, 2022
[READ-ONLY] CakePHP Utility classes such as Inflector, Text, Hash, Security and Xml. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Utility Classes This library provides a range of utility classes that are used throughout the CakePHP framework What's in the toolbox? Hash A

CakePHP 112 Feb 15, 2022
WeExpire is an opensource tool for creating emergency notes that can be read by your trusted contacts only after your death or if you are seriously injured

WeExpire is an opensource tool for creating emergency notes that can be read by your trusted contacts only after your death or if you are

Francesco 36 Nov 24, 2022
PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule for validation Japanese string only full-width or only half-width.

Japanese String Helpers PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule f

Deha 54 Mar 22, 2022
Allow composer packages to define compilation steps

Composer Compile Plugin The "Compile" plugin enables developers of PHP libraries to define free-form "compilation" tasks, such as: Converting SCSS to

CiviCRM 11 Aug 3, 2022
Attributes to define PHP language extensions (to be enforced by static analysis)

PHP Language Extensions (currently in BETA) This library provides attributes for extending the PHP language (e.g. adding package visibility). The inte

Dave Liddament 70 Dec 19, 2022
Small utility library that handles metadata minification and expansion.

composer/metadata-minifier Small utility library that handles metadata minification and expansion.

Composer 134 Dec 26, 2022
PHPStan extension to support #[Readonly] constructor properties

icanhazstring/phpstan-readonly-property Support #[Readonly] promoted constructor properties for PHPStan. This library is used to have a full transitio

Andreas Frömer 4 Apr 5, 2022
A small package to add computed properties to any PHP class. 🐘

Computed Properties This package provides a trait and attribute that can provide computed property support. Installation This package can be installed

Ryan Chandler 22 Mar 28, 2022
Validated properties in PHP8.1 and above using attribute rules

PHP Validated Properties Add Rule attributes to your model properties to make sure they are valid. Why this package? When validating external data com

null 23 Oct 18, 2022