A set of classes to create and manipulate HTML objects abstractions

Overview

HTMLObject

Build Status Latest Stable Version Total Downloads Scrutinizer Quality Score Code Coverage Support via Gittip

HTMLObject is a set of classes to create and manipulate HTML objects abstractions.

Static calls to the classes

echo Element::p('text')->class('foobar');
// <p class="foobar">text</p>
$list = List::ul(array('foo', 'bar'));

$link = Link::create('#', 'Someone');
$list->getChild(0)->addClass('active')->setValue('by '.$link);
// <ul>
//   <li class="active">foo</li>
//   <li>by <a href="#">Someone</a></li>
// </ul>
echo Link::create('#foo', 'link')->class('btn btn-success')->blank();
// <a href="#foo" class="btn btn-primary" target="_blank">link</a>

Extending the core classes

The core classes are meant to be extended and used to create complex patterns. All classes implement tree-crawling properties such as the following :

$element = Element::figure();

$element->nest('content') // <figure>content</figure>

$element->nest('p', 'content') // <figure><p>content</p></figure>

$image = Image::create('img.jpg')->alt('foo'); // <img src="img.jpg" alt="foo" />
$element->setChild($image, 'thumb');

$element->getChild('thumb') // HtmlObject\Image
$element->nest(array(
  'caption' => Element::figcaption()->nest(array(
    'text' => Element::p('foobar'),
  )),
));

$element->getChild('caption.text')->getValue() // foobar
// OR
$element->captionText->getValue() // foobar
$element->captionText->getParent(0) // figure->caption
$element->captionText->getParent(1) // figure

$element->wrap('div') // <div><figure>...</figure></div>
$element->wrapValue('div') // <figure><div>...</div></figure>

You can see examples implementations in the examples folder.

Properties injection

If your class use properties that are at meant to be added to the final array of attributes, you can inject them using the injectProperties method. Say you have a Link class that has an url property, you can overwrite the method like this, and the $this->url will get added in the href attribute :

protected function injectProperties()
{
  return array(
    'href' => $this->url,
  );
}

Or if the property bears the property's name you can simply add it to the array of automatically injected properties :

protected $injectedProperties = array('href', 'title');

// Will be added as href="#foo"
protected $href = '#foo';

// Will be added as title="title"
protected $title = 'title';

Altering a precreated tree

HtmlObject allows to use the open and close to open tags but when your tag has children you sometimes want to open the tree at a particular point to inject data at runtime, you can do it like this :

$mediaObject = Element::div([
  'title' => Element::h2('John Doe'),
  'body'  => Element::div(),
]);

echo $mediaObject->openOn('body').'My name is John Doe'.$mediaObject->close();
<div>
  <h2>John Doe</h2>
  <div>My name is John Doe</div>
</div>

Configuration

You can change whether to follow xHMTL or HTML5 specification by doing the following :

Tag::$config['doctype'] = '{xhtml|html}';
Comments
  • Self closing tags

    Self closing tags

    The self closing tags don't really work... I changed two lines of code and that seems to fix it:

    Tag.php (#109)

    $this->isOpened = !$this->isSelfClosing;
    

    Tag.php (#118)

    return '<'.$this->element.Helpers::parseAttributes($this->attributes) . ($this->isSelfClosing ? ' /' : ''). '>';
    

    PS: Great library!

    opened by rseyferth 8
  • Raw value for data()

    Raw value for data()

    Is it possible to add raw values to data attributes? If I pass a JSON string to Former with Former::text('tags', 'Tags')->dataTags($tags);, the data get's encoded Maybe an extra parameter to specify raw output?

    opened by barryvdh 6
  • Add ability to override isSelfClosing

    Add ability to override isSelfClosing

    If you have a custom tag/custom element that needs different self-closing rules (or one that isn't already defined in the code, such as meta), this PR adds the ability to override that behavior to ensure a tag is or is not self-closing.

    opened by CWSpear 4
  • Recognise cases when a zero attribute value is legitimate

    Recognise cases when a zero attribute value is legitimate

    When tag attributes are parsed, any whose value isn't equivalent to "true" is discarded. However, as the value attribute can legitimately be zero or and empty string, it's white-listed.

    However, it's not the only attribute that can legitimately have a zero value. Min and max for a number type input field may be required to impose a zero bound on the field's input. So these have been added to the white-list, along with some associated tests.

    opened by petercoles 4
  • Tag?

    Tag?

    Please could we have a tag on this project?

    Currently former can't be used in any project with minimum stability "stable" as it depends on this project which doesn't have a stable release.

    opened by petercoles 4
  • Default dynamically set attribute to boolean true vs string 'true'.

    Default dynamically set attribute to boolean true vs string 'true'.

    When an attribute is dynamically set through the magic __call() method, but no parameter is supplied, the attribute is defaulted to the string 'true'. However, the Helpers::parseAttributes() method does a strict type comparison to the boolean true to determine boolean attributes. Due to this, when an attribute is set as $tag->required() or $tag->checked(), it is rendered as required="true" or checked="true", instead of as an actual boolean attribute.

    This pull request changes the default value for dynamically set attributes to a boolean true instead of the string 'true'.

    This also addresses issue formers/former#437.

    opened by patrickcarlohickman 3
  • Fix/wrap children

    Fix/wrap children

    When wrapWith() called by some tree child element, it is expected to return element itself; and also expected that element be actually moved into wrapper element, affecting parent tree.

    It breaks BC in cases when Tag::wrapWith() return value used. But it seems to be more logical and intuitive, like in jQuery

    opened by velosipedist 3
  • Treat attribtues set with boolean values as properties

    Treat attribtues set with boolean values as properties

    When applying a checked state to a checkbox, it is convenient to set the checked attribute with a boolean like the jQuery prop() API.

    $bool = false; // Perhaps the property of a model
    $el = Input::checkbox('foo', 'bar', ['checked' => $bool]);
    

    #14 / #15 broke this by making NULL be the only wait to pass an attribute value that tells html-object not to add the attribute. This PR makes it so setting an attribute value to FALSE will NOT create the attribute. And setting it to TRUE will add the attribute as a property (no value).

    opened by weotch 2
  • Self-closing elements printing close tag when nesting.

    Self-closing elements printing close tag when nesting.

    Consider the following snippet:

    $formGroup = \HtmlObject\Element::div();
    $formGroup->nest(\HtmlObject\Input::text('foo'));
    
    echo htmlentities($formGroup);
    

    What I expect to get printed is:

    <div><input type="text" name="foo"></div>
    

    But, what really gets printed is:

    Input get printed correctly, if I use it alone htmlentities(\HtmlObject\Input::text('foo'))

    <input type="text" name="foo">
    

    The closing tag comes to haunt only when nesting it inside another tag.

    After looking through the code, I think the issue can be solved by modifying the code for close function on the Tag class, as follows:

    foreach ($this->children as $childName => $child) {
      if ($child->isOpened ) { // <-- change condition to if ($child->isOpened && !$child->isSelfClosing) {
        $openedOn = $childName;
        $element .= $child->close();
      } elseif ($openedOn and $child->isAfter($openedOn)) {
        $element .= $child;
      }
    }
    

    The problem is, I am not sure whether this fix will cause any side effects. :(

    opened by jomoos 2
  • Fix backwards incompatibility bug with ->addClass(null)

    Fix backwards incompatibility bug with ->addClass(null)

    Hi @Anahkiasen,

    Sorry for making more work for you today, thanks for releasing 1.4.3.

    It ends up that 1.4.3 changes the behavior of ->addClass(null), which is causing headaches in 20+ Former tests.

    This branch simply demonstrates the change -- feel free to merge a different fix if you like, or let me know if you don't consider this a regression and I will deal with it in former.

    # html-object 1.4.2:
    Element::p('foo')->addClass(null)->__toString(); # <p>foo</p>
    
    # html-object 1.4.3:
    Element::p('foo')->addClass(null)->__toString(); # <p class="">foo</p>
    

    The issue stems from the new strict in_array check in Tag::addClass(). It ends up this call is:

    # html-object 1.4.2:
    in_array(null /* $class */, [""] /* $classes */); # true
    
    # html-object 1.4.3:
    in_array(null, [""], true); # false
    

    To fix this, I simply checked if $class was null or "" and avoided the is_array call in this case.

    opened by claar 1
  • Remove examples from repository auto-generated ZIP archives

    Remove examples from repository auto-generated ZIP archives

    People that install this library via composer don't need the examples, they just need the library itself. This PR removes the sample directories and files from the repository auto-generated ZIP archives. Developers that need some more info can still do a git clone or just look at this repo on GitHub.

    opened by mlocati 1
  • Fix

    Fix "explode(): Passing null to parameter #2 ($string) of type string is deprecated"

    Since PHP 8.1, passing null as the second parameter of explode() raises this deprecation error:

    Deprecated: explode(): Passing null to parameter #2 ($string) of type string is deprecated
    

    Let's fix it.

    opened by mlocati 0
  • Fix removing class

    Fix removing class

    Hi @Anahkiasen,

    This pull request fix a bug when using the HtmlObject\Traits\Tag::removeClass($classes) method.

    Otherwise, when you try to remove a CSS class which isn't present, it'll remove a wrong CSS class, see the testCanRemoveClasses test for more info.

    Because the array_search() PHP function returns the key for needle if it is found in the array, false otherwise. This array_search() function may return Boolean false, but may also return a non-Boolean value which evaluates to false.

    So in the HtmlObject\Traits\Tag::removeClass() method of this package, we need to check if the $exists value is strictly not equals to false instead of using the !is_null($exists) check.

    If this fix is merged and a new release is tagged, I'll update the Former dependency to release the final version of Former 5.0.0 🤞

    By the way, many thanks for all the work you have done on this package and Former 👍

    Have a good day, Tortue Torche

    opened by tortuetorche 2
  • data_foo() behavior changed

    data_foo() behavior changed

    From 1.4.2 to 1.4.4 the behavior of data_foo() changed.

    1.4.2: <input data_foo="true" /> 1.4.4: <input data_foo />

    I saw that there were some changes about false/empty attributes, if it was intentional then disconsider this issue, otherwise it might be interesting to restore this behavior.

    Thanks

    opened by carlosvini 0
  • Wrong nest() behavior

    Wrong nest() behavior

    // add two empty cells into row
    $tr->nest('td', '');
    $tr->nest('td', '');
    
    // but there is only one
    // because it uses empty string as child id o_O
    print $tr; // <tr><td></td></tr>
    

    It is easy predictable side-effect — node string content used as node id will fail at second inserted child with same content.

    opened by velosipedist 0
Releases(1.4.3)
Owner
Emma Fabre
Developer for @madewithlove Mother of Dragibus and Protector of the Realm
Emma Fabre
:date: The VObject library for PHP allows you to easily parse and manipulate iCalendar and vCard objects

sabre/vobject The VObject library allows you to easily parse and manipulate iCalendar and vCard objects using PHP. The goal of the VObject library is

sabre.io 532 Dec 25, 2022
Parse DSN strings into value objects to make them easier to use, pass around and manipulate

DSN parser Parse DSN strings into value objects to make them easier to use, pass around and manipulate. Install Via Composer composer require nyholm/d

Tobias Nyholm 77 Dec 13, 2022
Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Super Simple DTO Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Mohammed Manssour 8 Jun 8, 2023
Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.DeepEqual().

Deeper Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.De

Joubert RedRat 4 Feb 12, 2022
QuidPHP/Main is a PHP library that provides a set of base objects and collections that can be extended to build something more specific.

QuidPHP/Main is a PHP library that provides a set of base objects and collections that can be extended to build something more specific. It is part of the QuidPHP package and can also be used standalone.

QuidPHP 4 Jul 2, 2022
Set of classes and tools to communicate with a Noso wallet using NosoP

NosoPHP Set of classes and tools to communicate with a Noso wallet using NosoP(Noso Protocol) Examples Node Info include __DIR__ . '/vendor/autoload.p

Noso Project 1 Jan 10, 2022
MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query and get result in a fastest way

Mysql Optimizer mysql optimizer also known as MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query

null 2 Nov 20, 2021
A set of PHP classes to let you manage your Dynamic Widget UI programmatically.

Dynamic Widget for Flutter A set of PHP classes to let you manage your Dynamic Widget UI programmatically. Why? Why not? Developing my application I f

Agostino Fiscale 3 Mar 22, 2022
Naive Bayes works by looking at a training set and making a guess based on that set.

Naive Bayes Naive Bayes works by looking at a training set and making a guess based on that set. It uses simple statistics and a bit of math to calcul

Assisted Mindfulness 29 Nov 27, 2022
JSONFinder - a library that can find json values in a mixed text or html documents, can filter and search the json tree, and converts php objects to json without 'ext-json' extension.

JSONFinder - a library that can find json values in a mixed text or html documents, can filter and search the json tree, and converts php objects to json without 'ext-json' extension.

Eboubaker Eboubaker 2 Jul 31, 2022
This package was created to provide simple way to manipulate arrays in PHP

PHP Collections This package was created to provide simple way to manipulate arrays in PHP. The package was inspired by the Laravel Collections.

Wojciech Mleczek 13 Jul 26, 2021
DeepCopy - Create deep copies (clones) of your objects

DeepCopy DeepCopy helps you create deep copies (clones) of your objects. It is designed to handle cycles in the association graph. Table of Contents H

My C-Labs 8.4k Dec 29, 2022
Miniset allows you to create compact sets of fields that either combine into a string of classes, or return a simple array of values

Miniset allows you to create compact sets of fields that either combine into a string of classes, or return a simple array of values. Miniset

Jack Sleight 5 Jun 13, 2022
A set of PHP scripts which leverage MySQL INFORMATION_SCHEMA to create log tables and insert / update triggers

mysql-logtable-php mysql-logtable-php is a set of PHP scripts which leverage MySQL INFORMATION_SCHEMA to create log tables and insert / update trigger

null 3 Feb 27, 2022
html-sanitizer is a library aiming at handling, cleaning and sanitizing HTML sent by external users

html-sanitizer html-sanitizer is a library aiming at handling, cleaning and sanitizing HTML sent by external users (who you cannot trust), allowing yo

Titouan Galopin 381 Dec 12, 2022
Sanitize untrustworthy HTML user input (Symfony integration for https://github.com/tgalopin/html-sanitizer)

html-sanitizer is a library aiming at handling, cleaning and sanitizing HTML sent by external users (who you cannot trust), allowing you to store it and display it safely. It has sensible defaults to provide a great developer experience while still being entierely configurable.

Titouan Galopin 86 Oct 5, 2022
PHP library to create and validate html forms

FormManager Note: this is the documentation of FormManager 6.x For v5.x version Click here Installation: This package requires PHP>=7.1 and is availab

Oscar Otero 145 Sep 20, 2022
This shell script and PHP file create a browseable HTML site from the Zig standard library source.

Browseable Zig standard library This shell script and PHP file create a browseable HTML site from the Zig standard library source. The idea is to inve

Dave Gauer 3 Mar 20, 2022
Learning about - Basic HTML & CSS, JSON, XML, Session & Cookies, CRUD Operations in Php using MySQL and Create MVC from scratch

This Project is based on course CSC 3215. Learning about - Basic HTML & CSS, JSON, XML, Session & Cookies, CRUD Operations in Php using MySQL and Create MVC (Model–View–Controller) from scratch. Just learning about web technologies, Not focusing on UI (Bootstrap or other 3rd-Party UI libraries or frameworks).

Alvi Hasan 5 Sep 21, 2022