In twig, you can add filter json_encode which internally is using json_encode php function.

http://twig.sensiolabs.org/doc/2.x/filters/json_encode.html

Now to add options just like json_encode in php,


{{ data | json_encode(constant('JSON_HEX_APOS')) | raw }}

to add more than one option you can use b-or operation to have multiple json_encode options:


{{ pageData|json_encode(constant('JSON_HEX_APOS') b-or constant('JSON_HEX_QUOT') ) | raw }}

php elephant 7.1

So I ran into an issue today while debugging a json string which is being produced from serialising an object. The float values had more decimal points than the ones in the object.

For example, consider the following code:

<?php

class MyFloatClass implements \JsonSerializable
{

    /**
     * @var float
     */
    public $value1;

    /**
     * @var float
     */
    public $value2;

    /**
     * myFloatClass constructor.
     * @param float $value1
     * @param float $value2
     */
    public function __construct($value1, $value2)
    {
        $this->value1 = $value1;
        $this->value2 = $value2;
    }

    function jsonSerialize()
    {
        return [
            'value1' => $this->value1,
            'value2' => $this->value2,
        ];
    }
}

$myObject = new MyFloatClass(12.23, 43.99);

echo json_encode($myObject->jsonSerialize());

Running the code above in PHP 7 will give the following output:

{"value1":12.23,"value2":43.99}

If you run the code in PHP 7.1 and you have serialize_precision not equal to -1, it will give totally different output.
Example, consider the following setting:

<?php

ini_set('precision', 14);
ini_set('serialize_precision', 17);


class MyFloatClass implements \JsonSerializable
{

    /**
     * @var float
     */
    public $value1;

    /**
     * @var float
     */
    public $value2;

    /**
     * myFloatClass constructor.
     * @param float $value1
     * @param float $value2
     */
    public function __construct($value1, $value2)
    {
        $this->value1 = $value1;
        $this->value2 = $value2;
    }

    function jsonSerialize()
    {
        return [
            'value1' => $this->value1,
            'value2' => $this->value2,
        ];
    }
}

$myObject = new MyFloatClass(12.23, 43.99);

echo json_encode($myObject->jsonSerialize());

output will be:

{"value1":12.23,"value2":43.990000000000002}

So first thing to check when having PHP 7.1 in your prod environment or even development environment is to check that you have default values for:

precision => 14
serialize_precision => -1

You can check that using CLI by running the following command:

php -i | grep precise

More reading: PHP Wiki – Precise Float Value

Photo Credit PHP Elephant with Christmas Tree Bokeh

Doctrine load fixtures – How to load particular fixture

Symfony has an option to load fixtures from command line:

$ php app/console doctrine:fixtures:load --help
Usage:
 doctrine:fixtures:load [--fixtures[="..."]] [--append] [--em="..."] [--purge-with-truncate]

Options:
 --fixtures             The directory or file to load data fixtures from. (multiple values allowed)
 --append               Append the data fixtures instead of deleting all data from the database first.
 --em                   The entity manager to use for this command.
 --purge-with-truncate  Purge data by using a database-level TRUNCATE statement
 --help (-h)            Display this help message.
 --quiet (-q)           Do not output any message.
 --verbose (-v|vv|vvv)  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug.
 --version (-V)         Display this application version.
 --ansi                 Force ANSI output.
 --no-ansi              Disable ANSI output.
 --no-interaction (-n)  Do not ask any interactive question.
 --shell (-s)           Launch the shell.
 --process-isolation    Launch commands from shell as a separate process.
 --env (-e)             The Environment name. (default: "test")
 --no-debug             Switches off debug mode.

But if you assign the full path to fixture file with --fixtures option, its not going to load it and you’ll end up with error:

[InvalidArgumentException]
Could not find any fixtures to load in:
– full/path/to/file.php

The other option is to load the folder itself by typing the full path to folder where fixture file resides.

php app/console doctrine:fixtures:load --fixture=/src/BundleName/DataFixtures/ORM/

Integrating Symfony monolog with Slack

By using Monolog in Symfony applications, we can log to files, send emails, log to console and many other channels. In this article, I will show the step by step on how to integrate Monolog with Slack.
The good thing is integration is just a matter of some configuration in config without writing any line of code. So it could be easily integrated in any project.
Continue reading

Examples Faker to create fixtures with Alice Bundle

To use inside fixtures, first you need php file inside folder DataFixtures/ORM

namespace MyBundle\DataFixtures\ORM;


use Hautelook\AliceBundle\Alice\DataFixtureLoader;
use Nelmio\Alice\Fixtures;

/**
 * Class AccountFixtures
 *
 * @package MyBundle\DataFixtures\ORM
 */
class AccountFixtures extends DataFixtureLoader
{
    /**
     * @return array
     */
    protected function getFixtures()
    {
        return array(__DIR__ . '/MyFixtures.yml',);
    }
}

Then Entities Fixture file in Yaml format

MyBundle\Entity\Account:
  account_{1...10}:
    username: <lexify('????.name\@php-symfony.uk')>
    password: <password()>
    accountNumber: <regexify('[A-Z]{1}[0-9]{6}')>
    closeForLunch: <boolean(50)>
    earliestTimeToDispatch: <dateTime('now')>
    latestTimeToDispatch: <dateTime('now')>
    specialInstructions: <sentence(5)>


MyBundle\Entity\Authentication:
   authentication_{1...10}:
      account: @account_<numberBetween(1,9)>
      authenticationToken: <regexify('[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{8}')>


MyBundle\Entity\CollectionJob:
   jobs_{1...10}:
      account: @account_<numberBetween(1,9)>
      authentication: @authentication_<numberBetween(1,9)>
      collectionNumber: <regexify('[A-Z]{2}[0-9]{8}')>

Full examples of using
Faker is a PHP library that generates fake data for you

Base

randomDigit             // 7
randomDigitNotNull      // 5
randomNumber($nbDigits = NULL) // 79907610
randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
numberBetween($min = 1000, $max = 9000) // 8567
randomLetter            // 'b'
randomElements($array = array ('a','b','c'), $count = 1) // array('c')
randomElement($array = array ('a','b','c')) // 'b'
shuffle('hello, world') // 'rlo,h eoldlw'
shuffle(array(1, 2, 3)) // array(2, 1, 3)
numerify('Hello ###') // 'Hello 609'
lexify('Hello ???') // 'Hello wgt'
bothify('Hello ##??') // 'Hello 42jz'
asciify('Hello ***') // 'Hello R6+'
regexify('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'); // sm0@y8k96a.ej

Lorem

word                    // 'aut'
words($nb = 3)          // array('porro', 'sed', 'magni')
sentence($nbWords = 6)  // 'Sit vitae voluptas sint non voluptates.'
sentences($nb = 3)      // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.')
paragraph($nbSentences = 3) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.'
paragraphs($nb = 3)     // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.')
text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.'

Person

title($gender = null|'male'|'female')     // 'Ms.'
titleMale                                 // 'Mr.'
titleFemale                               // 'Ms.'
suffix                                    // 'Jr.'
name($gender = null|'male'|'female')      // 'Dr. Zane Stroman'
firstName($gender = null|'male'|'female') // 'Maynard'
firstNameMale                             // 'Maynard'
firstNameFemale                           // 'Rachel'
lastName                                  // 'Zulauf'

Address

cityPrefix              // 'Lake'
secondaryAddress        // 'Suite 961'
state                   // 'NewMexico'
stateAbbr               // 'OH'
citySuffix              // 'borough'
streetSuffix            // 'Keys'
buildingNumber          // '484'
city                    // 'West Judge'
streetName              // 'Keegan Trail'
streetAddress           // '439 Karley Loaf Suite 897'
postcode                // '17916'
address                 // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473'
country                 // 'Falkland Islands (Malvinas)'
latitude                // 77.147489
longitude               // 86.211205

Text

realText($maxNbChars = 200, $indexSize = 2) // "And yet I wish you could manage it?) 'And what are they made of?' Alice asked in a shrill, passionate voice. 'Would YOU like cats if you were never even spoke to Time!' 'Perhaps not,' Alice replied."

DateTime

unixTime($max = 'now')                // 58781813
dateTime($max = 'now')                // DateTime('2008-04-25 08:37:17')
dateTimeAD($max = 'now')              // DateTime('1800-04-29 20:38:49')
iso8601($max = 'now')                 // '1978-12-09T10:10:29+0000'
date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
time($format = 'H:i:s', $max = 'now') // '20:49:42'
dateTimeBetween($startDate = '-30 years', $endDate = 'now') // DateTime('2003-03-15 02:00:49')
dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days') // DateTime('2003-03-15 02:00:49')
dateTimeThisCentury($max = 'now')     // DateTime('1915-05-30 19:28:21')
dateTimeThisDecade($max = 'now')      // DateTime('2007-05-29 22:30:48')
dateTimeThisYear($max = 'now')        // DateTime('2011-02-27 20:52:14')
dateTimeThisMonth($max = 'now')       // DateTime('2011-10-23 13:46:23')
amPm($max = 'now')                    // 'pm'
dayOfMonth($max = 'now')              // '04'
dayOfWeek($max = 'now')               // 'Friday'
month($max = 'now')                   // '06'
monthName($max = 'now')               // 'January'
year($max = 'now')                    // '1993'
century                               // 'VI'
timezone                              // 'Europe/Paris'

Internet

email                   // 'tkshlerin@collins.com'
safeEmail               // 'king.alford@example.org'
freeEmail               // 'bradley72@gmail.com'
companyEmail            // 'russel.durward@mcdermott.org'
freeEmailDomain         // 'yahoo.com'
safeEmailDomain         // 'example.org'
userName                // 'wade55'
password                // 'k&|X+a45*2['
domainName              // 'wolffdeckow.net'
domainWord              // 'feeney'
tld                     // 'biz'
url                     // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html'
slug                    // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum'
ipv4                    // '109.133.32.252'
localIpv4               // '10.242.58.8'
ipv6                    // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c'
macAddress              // '43:85:B7:08:10:CA'