Samsung Galaxy S5 – Get rid of “white boxes” on numeric PIN keypad

There have been some problems with Samsung Galaxy S5 (possibly other Android devices too) – when you tried to enter your numeric PIN – all the numbers turned into white square boxes.

Here’s how to fix the problem.

Follow these steps to access SysDump and get rid of those white boxes!

1) Key into your dialer *#9900#
2) It should open a page called SysDump
3) Select option 2: DELETE DUMPSTATE/LOGCAT
4) Restart your phone
5) Success!

Setting up your MySQL client with Vagrant over SSH

To setup an external SQL client with your Vagrant instance database, just follow these steps:
1. First you need to know the IP address of your Vagrant box. You will find it in your Vagrantfile.
Look for something like:

config.vm.network :private_network, ip: "192.168.56.101"
  1. Check your Vagrant SSH configuration by typing: vagrant ssh-config
    You should see something like:
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /path/to/your/ssh/id_rsa
  IdentitiesOnly yes
  LogLevel FATAL

These are all the details you need to do SSH tunneling in your SQL client.

From this config you can configure your SQL client over SSH by connecting to:

MySQL Host: 127.0.0.1
Username: <your MySQL username which you already created before>
Password: <your MySQL password>
Database: <optional>
Port: 3306
SSH Host: 192.168.56.101
SSH User: vagrant
SSH Key: /path/to/your/ssh/id_rsa <copy entire path from IdentityFile>
SSH Port: <optional>

And that’s it! If you experience any problems, let me know.

PHP save array to CSV using memory and force download

This is a typical scenario where you have some array with data and you want to create CSV export functionality.
This is the easiest solution for this problem. It also forces a CSV file to download in browser:


//this will be your data array, let's say it has 5 columns for this example
$data = array( ... );

//name of the file
$filename = 'export.csv';

//we will save this to output buffer
$fp = fopen('php://output', 'w');

//create header line
fputcsv($fp, array('col1', 'col2', 'col3', 'col4', 'col5'));

//create body
foreach ($data as $row) {
     fputcsv($fp, array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5']));
}

//close file
fclose($fp);

//set correct Content type
header('Content-type: text/csv');
//set as attachment to force download
header('Content-Disposition: attachment; filename="' . $filename . '"');

And that’s it!

Symfony 2 – Doctrine Association Mapping – One To Many with join table

As explained in Doctrine tutorial:

A unidirectional one-to-many association can be mapped through a join table. From Doctrine’s point of view, it is simply mapped as a unidirectional many-to-many whereby a unique constraint on one of the join columns enforces the one-to-many cardinality.

Imagine that you have these 3 tables:

CREATE TABLE User (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;

CREATE TABLE users_phonenumbers (
    user_id INT NOT NULL,
    phonenumber_id INT NOT NULL,
    UNIQUE INDEX users_phonenumbers_phonenumber_id_uniq (phonenumber_id),
    PRIMARY KEY(user_id, phonenumber_id)
) ENGINE = InnoDB;

CREATE TABLE Phonenumber (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;

ALTER TABLE users_phonenumbers ADD FOREIGN KEY (user_id) REFERENCES User(id);
ALTER TABLE users_phonenumbers ADD FOREIGN KEY (phonenumber_id) REFERENCES Phonenumber(id);

And you want to write a query:

SELECT *
FROM User u
INNER JOIN users_phonenumbers upn ON upn.user_id = u.id
INNER JOIN Phonenumber pn ON pn.id = upn.phonenumber_id

You have 2 options:

  1. Write it as DQL query (we are not going to explore this option here)

  2. Create association in Doctrine objects.

Here’s how:

<?php
/** @Entity **/
class User
{
    // ...

    /**
     * @ManyToMany(targetEntity="Phonenumber")
     * @JoinTable(name="users_phonenumbers",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="phonenumber_id", referencedColumnName="id", unique=true)}
     *      )
     **/
    private $phonenumbers;

    public function __construct()
    {
        $this->phonenumbers = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

/** @Entity **/
class Phonenumber
{
    // ...
}

Note this annotation:

/**
     * @ManyToMany(targetEntity="Phonenumber")
     * @JoinTable(name="users_phonenumbers",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="phonenumber_id", referencedColumnName="id", unique=true)}
     *      )
     **/

We are telling Doctrine that this will be ManyToMany relation with the joining table users_phonenumbers, join columns users_phonenumbers.user_id = user.id and next join columns users_phonenumbers.phonenumber_id = phonenumber.id .

Symfony 2 : Load DB config from external file

One day you may want to secure your Symfony app bit more by moving sensitive info like DB credentials outside your Symfony project and loading it from the external file.

Symfony documentation provides some brief explanation but nothing too concrete to make it a working example.

How to Organize Configuration Files:
http://symfony.com/doc/current/cookbook/configuration/configuration_organization.html

How to Set external Parameters in the Service Container
http://symfony.com/doc/current/cookbook/configuration/external_parameters.html

Scenario #1: Keep DB credentials in external INI file matching parameters names

  1. Create external config file: /etc/sites/your-site/db.ini with the following DB credentials:
[parameters]
database_host = your_db_host
database_name = your_db_name
database_user = your_db_user
database_password = your_db_password

Note the [parameters] group! This has to be called parameters to match the parameters.yml file below. Also note the names of the fields which should match the ones set up in your config.yml.

  1. Change your parameters.yml file and remove the DB credentials:
parameters:
    database_driver:   pdo_mysql
    database_host:     ~
    database_port:     ~
    database_name:     ~
    database_user:     ~
    database_password: ~
  1. Make sure your config.yml file has these fields:
# Doctrine Configuration
doctrine:
    dbal:
        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
  1. Import the external file after importing the parameters.yml file by placing this in your config.yml file at the top:
imports:
    - { resource: parameters.yml }
    - { resource: /etc/sites/your-site/db.ini }

What it does, it firstly imports the YML file and sets the params, then imports your INI file and sets the params overwriting previously set params.

Scenario #2: Keep DB credentials in external INI file – parameters names are different

  1. Create external config file: /etc/sites/your-site/db.ini
[database]
host = your_db_host
name = your_db_name
user = your_db_user
password = your_db_password

Note the [database] group instead of previous parameters name. To give you more flexibility, you can call your group and params whatever you want.

  1. Change your parameters.yml file and remove the DB credentials:
parameters:
    database_driver:   pdo_mysql
    database_host:     ~
    database_port:     ~
    database_name:     ~
    database_user:     ~
    database_password: ~
  1. Make sure your config.yml file has these fields:
# Doctrine Configuration
doctrine:
    dbal:
        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
  1. Create new PHP file called parameters.php and place it in the same place where you store all configs. Load the external INI file and manually set the config values.
$iniArray = parse_ini_file("/etc/sites/your-site/db.ini", true);
$container->setParameter('database_host', $iniArray['database']['host']);
$container->setParameter('database_name', $iniArray['database']['name']);
$container->setParameter('database_user', $iniArray['database']['user']);
$container->setParameter('database_password', $iniArray['database']['password']);
  1. Import the external file after importing the parameters.yml file by placing this in your config.yml file at the top:
imports:
    - { resource: parameters.yml }
    - { resource: parameters.php }

This version is more flexible since you don’t have to rely on the parameter names you placed in your YML files previously, you will set them manually.

This is just one of probably many more solutions and I hope someone will find it useful. I saw some versions which overwrites Kernel byt that is complete overkill. Any feedback is welcome.

Symfony 2 – Doctrine – Unknown Entity namespace alias

Tutorial to follow: http://symfony.com/doc/current/book/doctrine.html

I was following this tutorial and was stuck with this error:

$product = $this->getDoctrine()
            ->getRepository('MyBundle:Product')
            ->find(1);

Unknown Entity namespace alias '...'

The problem was that my bundle had also VENDOR specified, so I had to change the function to:

$product = $this->getDoctrine()
            ->getRepository('MyVendorMyBundle:Product')
            ->find(1);

Don’t get confused to call it with semi colon which is incorrect even though would make more sense in my opinion:

$product = $this->getDoctrine()
            ->getRepository('MyVendor:MyBundle:Product')
            ->find(1);

Unknown Entity namespace alias 'MyVendor'

Unable to login to WordPress with correct username and password

You have these symptoms when trying to login to your WordPress site:

  • you are unable to access the admin screen of your WordPress site even though the login and password are correct
  • when you try to login to your site-url/wp-login.php, you don’t get an ‘incorrect password’ message but it goes back to the login prompt
  • you tried entering the wrong password and that did show an error indicating incorrect password

I had exactly the same problems and they keep occurring quite often so it may be due to some issue with plugins or wrong settings or god know what.

What worked for me was to LOG OUT completely from the site by typing this into your site url:


http://www.yoursite.com/wp-login.php?loggedout=true

After this, try to login again and it should work – at least it did for me!

If it won’t try to follow all the steps here: https://wordpress.org/support/topic/unable-to-login-to-admin-1

Good luck!

Symfony 2 – Doctrine – Possible issues of Camel Case fields when doing JMS serialization

I recently had this problem when data coming from API using Doctrine was not properly serialized and mapped to my object using JMS serializer.

After some research and play around I found the problem.

When using Doctrine directly to fetch all data from the table like:

$query = $this->createQueryBuilder('p')
->select('p');

The serialization was fine.

But when trying to hand pick specific fields I wanted caused a problem.

Here’s a simple example for USER object:

CREATE TABLE `articles` (
   `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
   `first_name` VARCHAR(50) NOT NULL,
   `last_name` VARCHAR(50) NOT NULL,
   `emailAddress` VARCHAR(100) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB;
$query = $this->createQueryBuilder('p')
->select('p.id, p.first_name, p.last_name, p.emailAddress');

The object which I was trying to serialize into:

<?php
namespace My\Bundle\Entity;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\SerializedName;

class User
{
   /**
    * @Type("integer")
    */
    private $id;

    /**
     * @Type("string")
     *
     */
    private $firstName;

    /**
     * @Type("string")
     *
     */
    private $lastName;

    /**
     * @Type("string")
     *
     */
    private $emailAddress;  
}

The data from doctrine was coming as JSON encoded array. For testing purposed, I created this array and converted to JSON:

$inputData[] = array('id' => 1, 'first_name' => 'John', 'last_name' => 'Smith', 'emailAddress' => 'john@smith.com');
$inputData[] = array('id' => 2, 'first_name' => 'Mark', 'last_name' => 'Cox', 'emailAddress' => 'mark@cox.com');
$json = json_encode($inputData);

When I tried to serialize it into my USER object:

//for how to use JSM serializer, read the official documentation
$data = $serializer->deserialize($jsonFromApi, 'array<My\Bundle\Entity\User>', 'json');

The output was:

Array
(
    [0] => My\Bundle\Entity\User Object
        (
            [id:My\Bundle\Entity\Entity\User:private] => 1
            [firstName:My\Bundle\Entity\Entity\User:private] => John
            [lastName:My\Bundle\Entity\Entity\User:private] => Smith
            [emailAddress:My\Bundle\Entity\Entity\User:private] => 
        )

    [1] => My\Bundle\Entity\Entity\User Object
        (
            [id:My\Bundle\Entity\Entity\User:private] => 2
            [firstName:My\Bundle\Entity\Entity\User:private] => Mark
            [lastName:My\Bundle\Entity\Entity\User:private] => Cox
            [emailAddress:My\Bundle\Entity\Entity\User:private] => 
        )

)

Great but where is the email address?

Well turns out that when you query all fields:

$query = $this->createQueryBuilder('p')
->select('p');

Doctrine uses the underscore naming strategy which means that it automatically converts camelCase to underscore_case. So when querying all fields, it converted emailAddress to email_address and then mapped it back to camel case emailAddress. However, if you queried for specific field, Doctrine didn’t convert it to underscores, therefore it wasn’t able to map it properly.

To enable underscore naming strategy, set the naming strategy in the ORM configuration in config.yml:

doctrine:
     orm:
          naming_strategy: doctrine.orm.naming_strategy.underscore 

Solutions to fix it:

When you query for specific field with camelCase, use alias to convert it to underscores like:

$query = $this->createQueryBuilder('p')
->select('p.id, p.first_name, p.last_name, p.emailAddress AS email_address');

OR

In your User class explicitly specify how to map the variable using annotation (http://jmsyst.com/libs/serializer/master/reference/annotations#serializedname)

    /**
     * @Type("string")
     * @SerializedName("emailAddress")
     *
     */
    private $emailAddress;

And that solved the problem!

Here are the expected mapped objects:

Array
(
    [0] => My\Bundle\Entity\User Object
        (
            [id:My\Bundle\Entity\Entity\User:private] => 1
            [firstName:My\Bundle\Entity\Entity\User:private] => John
            [lastName:My\Bundle\Entity\Entity\User:private] => Smith
            [emailAddress:My\Bundle\Entity\Entity\User:private] => john@smith.com
        )

    [1] => My\Bundle\Entity\Entity\User Object
        (
            [id:My\Bundle\Entity\Entity\User:private] => 2
            [firstName:My\Bundle\Entity\Entity\User:private] => Mark
            [lastName:My\Bundle\Entity\Entity\User:private] => Cox
            [emailAddress:My\Bundle\Entity\Entity\User:private] => mark@cox.com
        )

)

So you have to be careful about camel cases and underscore variables and always check how is doctrine returning these variable so you don’t have these nasty surprises.

If I forgot something or you have a better solution just post it in the comments and I’ll update the post.

PHP CodeSniffer – Check code compatibility with PHP 5.4 or 5.5 – Windows

This tutorial includes installation of PHP, PHPUnit on Windows. For other OS just search the net to find your answers.

Original blog post: http://blog.nerdery.com/2013/11/code-compatible-php-5-4-5-5/

1. install PHP to c:\php

(download: http://windows.php.net/download/)

Don’t forget to set your default timezone in php.ini otherwise you’ll get tons of warnings from PHP 5.4 upwards.

date.timezone = "Europe/London"

 2. Set PHP path to Windows.

Temporary solution is to run this in command line:

set PATH=%PATH%;C:\php

Better is to set in the Windows variables so it stays permanently.

3. install PEAR as per the instructions

http://pear.php.net/manual/en/installation.getting.php

Easiest way is to install it directly to c:\php . That way you don’t have to configure PEAR paths later and also the sniffs will get installed inside there.

4. install PHP Codesniffer as per the instructions

http://pear.php.net/package/PHP_CodeSniffer/download

5. Download PHP Compatibility Coding Standard for PHP_CodeSniffer

https://github.com/wimg/PHPCompatibility

Unzip and copy to: C:\php\pear\PHP\CodeSniffer\Standards

6. go to your project you want to test and type

phpcs --standard=PHPCompatibility --extensions=php,inc,phtml --runtime-set testVersion 5.5 . > output.txt

It will run all PHP 5.5 coding standards checks on files with extensions: php,inc,phtml and outputs to TXT file.

Working with PHP_CodeSniffer in Zend Studio

Just follow these steps to setup your Zend Studio to use PHP CodeSniffer:

http://files.zend.com/help/Zend-Studio/content/working_with_php_codesniffer.htm

When going through steps, select the PEAR library you just installed and then it will show you the sniffs installed in it.

Select the one you like and click OK. It will rebuild your projects and from now on you will see notifications inside the Zend Studio editor.