meandering soul

»Eventually, there's always something absurd like eternal love.«

Intro­­du­­cing jnl

jnl is a journ­al­ing tool for terminal-affine people.

 

Get the number of days in a month with moment.js

var date = moment();
var currentMonth = date.month();

var daysInMonth = 31;         // Every month has 31 days
if (currentMonth % 2 == 1) {  // except every other month
    if (currentMonth == 1) {  // and then there is februrary
        if (date.isLeapYear()) { 
            daysInMonth = 29; // which has 29 if it's a leap year
        } else {
            daysInMonth = 28; // and 28 if it isn't.
        }
    } else {
        daysInMonth = 30;
    }
}
 

Using Git Hooks for code style fixes

Pretty much every modern language has an estab­lished Coding Style Guide. For PHP, this is PSR-2. As with other style guides of this sort, there is a tool for auto­mat­ic­ally apply­ing the appro­pri­ate fixes to one’s code.

I only recently finally switched to using PSR-2 and to make sure I wouldn’t acci­dent­ally miss running the style fixer, I added this little snipped to my .git/hooks/pre-commit-Hook:

modified_php=$(git ls-files --modified | grep ".php$")

for f in $modified
do
    php-cs-fixer fix --level psr2 $f
done
 

Lena Rein­hard – A Talk about Noth­ing

This may well be one of the most import­ant talks about the future of our culture.

 

Redir­ect­ing in Lara­vel Form Requests

While Form Request Valid­a­tion in Lara­vel 5 usually does exactly what it’s supposed to do, I recently had to append a loca­tion hash to the redir­ect URL. Turns out that’s as simple as over­writ­ing the FormRequest's getRedirectUrl()-method:

protected function getRedirectUrl()
{
  $url = $this->redirector->getUrlGenerator();
  return $url->previous().'#hash';
}
 

Depend­ency Injec­­­­tion with inher­­­­ited Control­lers in Lara­vel 5

Usually, when setting up my control­lers in a Lara­vel 5 applic­a­tion, I end up creat­ing one or several base control­lers for differ­ent entry points (e.g. APICon­trol­ler, Fron­tendCon­trol­ler, …) While I deem this a good prac­tice, it can lead to prob­lems with Lara­vel’s other­wise fant­astic Depend­ency Injec­tion. To illus­trate, take a look at the follow­ing:

// FrontendController.php

class FrontendController extends Controller
{
  public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher)
  {
    $dispatcher->listen('composing: frontend.base', function ()
      {
        // handle root view compose
      }
    );
  }
}

// BlogController.php

class BlogController extends FrontendController
{
  protected $repo = null;

  public function __construct(TextRepository $repo)
  {
    $this->repo = $repo;
  }
}

As some IDEs and test­ing tools would say: There are multiple prob­lems!

  1. The BlogController's constructor does not call the parent.
  2. The construct­ors do neither match nor can all required para­met­ers be handed down.
  3. Actu­ally there is no number three but lists with two points always seem awkward.

Look at the mess I made!

Not call­ing the parent constructor which prob­ably does import­ant things? Bad idea. Could be fixed with chan­ging the constructor of BlogController to:

public function __construct(TextRepository $repo)
{
  $this->repo = $repo;
  parent::__construct();
}

But then again that’s not quite right too, is it? It should be more along the lines of this:

public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher, TextRepository $repo)
{
  $this->repo = $repo;
  parent::__construct($dispatcher);
}

Which is ugly as hell. Let alone remem­ber­ing that for all of the other descend­ants of the FrontendController.

Let’s make that pretty

Right around the time I real­ized that I didn’t want to write that second version even once, I thought “hey, Eloquent models have this boot() method. That could be a way to go.”

Said and done. I refact­ored my code to this:

// FrontendController.php

...
  public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher)
  {
    // the dispatcher stuff

    if (method_exists($this, 'boot')) $this->boot();
  }

// BlogController.php

public class BlogController extends FrontendController
{
  public function boot(TextRepository $repo)
  {
    $this->repo = $repo;
  }
}

Which, of course, did not work. And – as too often is the case – the error was all too obvi­ous to me once I had commit­ted the crime. So, after a while, I figured that if Lara­vel can resolve class names to inject from type hints, why shouldn’t I. Thus followed some research on method reflec­tion and I ended up with this:

// FrontendController.php

...
  public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher)
  {
    // the dispatcher stuff

    if (method_exists($this, 'boot'))
    {
      // resolve the boot dependencies
      $reflect = new \ReflectionMethod($this, 'boot');
      $reflectedParameters = $reflect->getParameters();

      $bootArguments = [];

      foreach ($reflectedParameters as $reflectedParameter)
      {
        preg_match("/.*<required> (.+) \\\${$reflectedParameter->getName()}/", $reflectedParameter, $typeHint);

        if (count($typeHint) == 2)
        {
          $className = $typeHint[1];
          $resolved = app()->make($className);

          array_push($bootArguments, $resolved);
        } 
      }

      call_user_func_array([&$this, 'boot'], $bootArguments);
    }
  }

And this, finally, works just as expec­ted. One thing to note though: Bad things will happen if you have anything but type-hinted to-be-resolved classes as attrib­utes to the boot() method.

 

Deep Link­ing in Eloquent Models

Some­times, when design­ing data models, it turns out that access to a prop­erty of a related model might be handy from the current model. For the case of one-to-many rela­tions, Lara­vel’s Eloquent already comes with the hasManyThrough()-method. But what if it’s a one-to-one rela­tion? And what if the attrib­ute one wants to have access to is up a few levels in the model hier­archy? Well, turns out that can be pretty easily done, too.

Assum­ing, three models A, B, C all related, e.g. B has a_id, C has b_id and C would bene­fit from direct access to A, that can be achieved through Eloquent with the follow­ing code:


class C extends Model
{
    ...

    public function b()
    {
        return $this->belongsTo('B');
    }

    public function a()
    {
        return $this->belongsTo('A');
    }

    public function getAIDAttribute()
    {
        return $this->b->a_id;
    }

    ...
}

Of course, one might also use this to fetch a specific attrib­ute instead of creat­ing a complete rela­tion. Keep in mind though, that this may cause seri­ous perform­ance issues since the ORM has to fetch all refer­enced entit­ies before it can return anything.

 

Light­­­­­­­weight links for Prism.js

Although Prism.js provides a very good autolinker plugin, it did not quite fit my needs for a recent project. Here’s what I came up with as a stupidly simple replace­ment that’s not as soph­ist­ic­ated (i.e. does not do links in Mark­down and such stuff) but works perfectly well with to-be-high­lighted JSON.

Prism.hooks.add('wrap', function(env) {
    if (env.type == 'string', env.content.match(/http/))
    {
        env.content = "<a href=\"" 
                    + env.content.replace('"', '') 
                    + "\">" 
                    + env.content 
                    + "</a>";
    }
});

Just add this to your site’s scripts and everything will be better.

 

On show­ing tables

Show­ing the exist­ing tables in a data­base can be really handy. Unfor­tu­nately, MySQL’s SHOW TABLES; is not a stand­ard sql command. Although it quite honestly should be. Thus, for quick refer­ence, here goes:

  • MySQL: SHOW TABLES;
  • Post­gres: SELECT name FROM pg_catalog.pg_tables;
  • SQLite: SELECT name FROM sqlite_master WHERE type = 'table';

There prob­ably is a SELECT-Syntax for MySQL too, but who really cares? The one above is so much shorter in any case.

 

Speed­ing up test cycles

Codecep­tion supports several layers of select­ing which tests to actu­ally run when you invoke codecept run. This can – among other times – be extremely useful when you’re trying to fix a bug and you really only need that one single test method to run or when you’re just doing API devel­op­ment and don’t need to check all of your UI integ­ra­tion tests for the time being.

# run all tests in all test suites
$ ./codecept run 

# run all tests in a single test suite
$ ./codecept run <suite> 

# run a single test case in the given suite
$ ./codecept run <suite> <test>          

# run only the given method in the test case
$ ./codecept run <suite> <test>:<method>