Install PHP 7.0 in Mac OS X with MacPorts

I’ve used this process to install PHP 7.0 with MacPorts along side with PHP 5.6.

First make sure Mac OS X included Apache server is stopped:

$ sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist

Install PHP7 and some of its modules (full list here):

$ sudo port install php70
$ sudo port install php70-apache2handler php70-cgi php70-gd php70-curl php70-intl php70-iconv php70-gettext php70-mbstring php70-imap php70-mcrypt php70-xmlrpc php70-mysql php70-openssl php70-sockets php70-zip php70-tidy php70-opcache php70-xsl php70-sqlite

Create the base php.ini file from the development example:

$ sudo cp /opt/local/etc/php70/php.ini-development /opt/local/etc/php70/php.ini

Find current timezone, add a backslash in between and put it in php.ini:

$ TIMEZONE=`sudo systemsetup -gettimezone | awk '{ print $3 }'`
$ TIMEZONE=$(printf "%s\n" "$TIMEZONE" | sed 's/[][\.*^$/]/\\&/g')
$ sudo sed -i.bak "s/;date.timezone =/date.timezone = \"${TIMEZONE}\"/g" /opt/local/etc/php70/php.ini

Update MySQL sockets if you are using it:

$ sudo sed -i.bak "s#pdo_mysql\.default_socket.*#pdo_mysql\.default_socket=`/opt/local/bin/mysql_config --socket`#" /opt/local/etc/php70/php.ini
$ sudo sed -i.bak "s#mysqli\.default_socket.*#mysqli\.default_socket=`/opt/local/bin/mysql_config --socket`#" /opt/local/etc/php70/php.ini

Now with this command you’ll see the installed PHP versions:

$ sudo port select --list php
Available versions for php:
	none
	php56 (active)
	php70

Select php70 as the active PHP version:

$ sudo port select php php70
Selecting 'php70' for 'php' succeeded. 'php70' is now active.

Enable PHP 7 in Apache:

$ cd /opt/local/apache2/modules
$ sudo /opt/local/apache2/bin/apxs -a -e -n php7 mod_php70.so

Restart Apache:

$ sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper restart

You can check in the console the php version:

$ php -v
PHP 7.0.0 (cli) (built: Dec 12 2015 11:18:35) ( NTS )
Copyright (c) 1997-2015 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

If the current version is not 7.0 make sure that /opt/local/bin is defined before /usr/bin in the PATH variable:

$ echo $PATH
/opt/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

Also check that /opt/local/bin/php is pointing to /opt/local/bin/php70:

$ ls -l /opt/local/bin/php
lrwxr-xr-x  1 root  admin    20B Dec  5 23:25 /opt/local/bin/php -> /opt/local/bin/php70

If running phpinfo(); doesn’t show the 7.0 version check that only the module for 7.0 is loaded in /opt/local/apache2/conf/httpd.conf:

#LoadModule php5_module        modules/mod_php56.so
LoadModule php7_module        modules/mod_php70.so

php7

Increase the maximum file size upload in PHP

Sometimes you need to increase the default 2 megabyte maximum upload file size.

php_upload_max_filesize

The maximum size you can upload to a server using PHP is defined by 2 values:

  • Upload max file size: upload_max_filesize
  • Post max size: post_max_size

That’s why you have to make sure both options in php.ini have the correct values:

upload_max_filesize = 32M
post_max_size = 32M

Symfony Forms and Bootstrap Datetimepicker

In this example I’m going to use the spanish locale and the “Europe/Madrid” timezone.

First we need an entity that will hold the DateTime, for example a Booking entity:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="bookings")
 */
class Booking
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $date;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->date = new \DateTime();
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set date
     *
     * @param \Datetime $date
     * @return Booking
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \Datetime 
     */
    public function getDate()
    {
        return $this->date;
    }
}

Our entity uses a DateTime object but the field in the form is going to be an input that can only have text. That’s why we need a DataTransformer. It will transform a DateTime object to string and vice versa when needed:

<?php

namespace AppBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class DateTimeTransformer implements DataTransformerInterface
{
    /**
     * Transforms an object (DateTime) to a string.
     *
     * @param  DateTime|null $datetime
     * @return string
     */
    public function transform($datetime)
    {
        if (null === $datetime) {
            return '';
        }

        return $datetime->format('d/m/Y H:i');
    }

    /**
     * Transforms a string to an object (DateTime).
     *
     * @param  string $datetime
     * @return DateTime|null
     */
    public function reverseTransform($datetime)
    {
        // datetime optional
        if (!$datetime) {
            return;
        }

        return date_create_from_format('d/m/Y H:i', $datetime, new \DateTimeZone('Europe/Madrid'));
    }
}

Now the form class. You can see how addModelTransformer is used to link the form date field with the DataTransformer. When defining the date field it’s important to render it as a text field and use the attr option to add a data-provide and a data-format that will be added in the HTML input field as attributes. Also some CSS classes are needed (form-control input-inline datetimepicker), you can add them with attr here or later in the Twig template. I’ll show both but only one of them is needed.

<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Form\DataTransformer\DateTimeTransformer;

class BookingFormType extends AbstractType
{
    private $class;

    /**
     * @param string $class The Booking class name
     */
    public function __construct($class)
    {
        $this->class = $class;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('date', 'text', array(
                'required' => true,
                'label' => 'form.label.datetime',
                'translation_domain' => 'AppBundle',
                'attr' => array(
                    'class' => 'form-control input-inline datetimepicker',
                    'data-provide' => 'datepicker',
                    'data-format' => 'dd-mm-yyyy HH:ii',
                ),
            ))
            ->add('submit', 'submit')
        ;

        $builder->get('date')
            ->addModelTransformer(new DateTimeTransformer());
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => $this->class,
                'intention'  => 'edit',
            )
        );
    }

    public function getName()
    {
        return 'booking_edit';
    }
}

Let’s register the form as a service:

services:
    app.form.type.booking_edit:
        class: AppBundle\Form\Type\BookingFormType
        arguments: [AppBundle\Entity\Booking]
        tags:
            - { name: form.type, alias: booking_edit }

In the template we’ll include the form and the needed JavaScript and CSS for jQuery, MomentJS, Bootstrap and Bootstrap Datetimepicker. Remember that MomentJS must be loaded BEFORE Bootstrap Datetimepicker. Also just before the body closing tag we have to call the datetimepicker┬ámethod on the input field. It’s very important to add “useCurrent: false” if you want to load a datetime as we do in this example.

<html>
    <head>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker-standalone.min.css" rel="stylesheet">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
        <title>Symfony and Bootstrap Datetimepicker</title>
    </head>
    <body>
        <div class="container">
            <div class="starter-template">
                <h1>Symfony and Bootstrap Datetimepicker</h1>
                <div class="row">
                    {{ form_start(form) }}
                        {{ form_errors(form) }}
                        <div class="form-group">
                            {{ form_label(form.date, null, { 'label_attr': {'class': 'col-sm-2 control-label'} }) }}{{ form_errors(form.date) }}
                            <div class='input-group date' id='datetimepicker'>
                                {{ form_widget(form.date, {'attr': {'class': 'form-control input-inline datetimepicker'}}) }}
                                <span class="input-group-addon">
                                    <span class="glyphicon glyphicon-calendar"></span>
                                </span>
                            </div>
                        </div>
                        <div class="form-group">
                            {{ form_row(form.submit, { 'label': 'OK' }) }}
                        </div>
                        {{ form_end(form) }}
                    </div>
                </div>
            </div>
        </div>

        <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment-with-locales.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
        <script type="text/javascript">
            $('#datetimepicker').datetimepicker({
                locale: 'es',
                useCurrent: false,
                sideBySide: true
            });
        </script>
    </body>
</html>

The controller is very simple (the handling of the form is not shown):

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Entity\Booking;
use AppBundle\Form\Type\BookingFormType;

class MainController extends Controller
{
    /**
     * @Route("/booking/edit/{id}", name="booking_edit")
     * @ParamConverter("id", class="AppBundle:Booking")
     * @param Request $request The Request object
     * @param Booking $booking The Booking object
     * @return Response A Response instance
     */
    public function formAction(Request $request, Booking $booking)
    {
        $form = $this->createForm(new BookingFormType('\AppBundle\Entity\Booking'), $booking);

        $form->handleRequest($request);

        if ($form->isValid()) {
            ...
        }

        return $this->render('form.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}

symfony-bootstrap-datetimepicker

Ref: https://eonasdan.github.io/bootstrap-datetimepicker/
http://ajaxray.com/blog/symfony2-forms-bootstrap-3-datepicker-for-date-field
http://symfony.com/doc/current/reference/forms/types/datetime.html
http://symfony.com/doc/current/cookbook/form/data_transformers.html

Temporary avoid MySQL “Cannot delete or update a parent row: a foreign key constraint fails”

mysql> SET foreign_key_checks = 0;
mysql> DROP table ...;
mysql> SET foreign_key_checks = 1;

Ref: http://stackoverflow.com/questions/2300396/force-drop-mysql-bypassing-foreign-key-constraint

Fix “avrdude: stk500_recv(): programmer is not responding” in Mac OS X Mavericks 10.9 – Arduino

If you get this error while trying to upload an sketch with Arduino IDE in Mac OS X Mavericks 10.9:

avrdude: stk500_recv(): programmer is not responding

The first thing you should be sure is that you have selected a correct USB port (Tools -> Port, which should be something like /dev/cu.usbserial). If even that you are unable to upload an sketch try this process.

– Disable the Apple FTDI USB driver:

$ cd /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns
$ sudo mv AppleUSBFTDI.kext AppleUSBFTDI.kext.disabled

– Restart Mac OS X.
– Install the original FTDI driver from here: http://www.ftdichip.com/Drivers/VCP.htm

arduino-IDE

Ref: http://www.enttec.com/support-center/kb/article/108-OS_X_Mavericks_(10.9)_-_IMPORTANT
https://forum.arduino.cc/index.php?topic=198539.0