Mitchell McKenna - imported from lifepress http://mitchmckenna.com/feed en-us http://blogs.law.harvard.edu/tech/rss LifePress mitchellmckenna@gmail.com jwt-auth: Deleted Users Causing Errors http://mitchmckenna.com/post/17328/jwt-auth-deleted-users-causing-errors

Recently ran into a situation using jwt-auth for Laravel where deleted users were causing errors because after deleting the user the auth token was still valid in redis, whoever the user no longer existed in the database, so when there was any calls to $auth->user() or Auth::user() it would error out when trying to make calls against that user object because false is returned.

When a user was deleted we should call $jwtAuth->invalidate($token) for that user but that's not gonna help us now that we have a bunch of other users who were deleted or if you need to delete users from DB manually.

I didn't want to have to check that calls to the Auth guard would not return false all over the place where I used the auth guard, so I looked for another answer.

Solution

Well it turns out others must have come across this issue as well because a merged PR to the project added a function to JWTGuard to throw a UserNotDefinedException if the user is not found. They didn't replace what happens when the user() function is called in order to stay compatible with how laravel's default guard returns false if not found. So use userOrFail() any place you normally would have used user.

]]>
Mon, 30 Jan 2017 17:53:25 -0500 http://mitchmckenna.com/post/17328/jwt-auth-deleted-users-causing-errors/jwt-auth-deleted-users-causing-errors
Failed to restart php7.0-fpm.service: Unit php7.0-fpm.service not found. http://mitchmckenna.com/post/17307/failed-to-restart-php70-fpmservice-unit-php70-fpmservice-not-found

You might have this happen to you if you switch back to an old project using Homestead. Basically you have a new version of the laravel/homestead vagrant box (1.0.1) which includes php 7.1 but the package in composer ^3.0 is expecting php 7.0.

Solution

Just add the line version: 0.6.0 to your homestead.yaml to indicate you want that version for the vagrant box which is the last one that includes php 7.0.

]]>
Tue, 24 Jan 2017 17:36:46 -0500 http://mitchmckenna.com/post/17307/failed-to-restart-php70-fpmservice-unit-php70-fpmservice-not-found/failed-to-restart-php70-fpmservice-unit-php70-fpmservice-not-found
SparkPost - Setting up SPF and DKIM with DigitalOcean http://mitchmckenna.com/post/17290/sparkpost-setting-up-spf-and-dkim-with-digitalocean

If you're trying to setup SparkPost to "Verify a Sending Domain" that's hosted on DigitalOcean add the SPF and DKIM records as they instruct except for the key part is the text added for each record must be surrounded in quotes to be accepted. Once this is done you should be able to click the "test" button for each to verify no problem.

]]>
Thu, 19 Jan 2017 03:03:24 -0500 http://mitchmckenna.com/post/17290/sparkpost-setting-up-spf-and-dkim-with-digitalocean/sparkpost-setting-up-spf-and-dkim-with-digitalocean
Laravel Queued Jobs + Doctrine - Fix Objects Not Updating Between Jobs Run http://mitchmckenna.com/post/15632/laravel-queued-jobs-doctrine-fix-objects-not-updating-between-jobs-run

The issue is that doctrine is keeping the objects in local memory because the daemon is basically a php long-running process. In order to allow the objects used by the job to get updated, you need to $em->detach() the objects. But you'd also have to have cacade={"detach"} on all relationships that object has as well. So the best thing is to just call $em->clear() at the end of your job. This will detach all objects from doctrine and it will get a fresh copy of all the objects from the database for the next job run.

]]>
Wed, 10 Feb 2016 07:34:54 -0500 http://mitchmckenna.com/post/15632/laravel-queued-jobs-doctrine-fix-objects-not-updating-between-jobs-run/laravel-queued-jobs-doctrine-fix-objects-not-updating-between-jobs-run
Laravel Queued Jobs + Doctrine - Fix Mysql Has Gone Away Errors http://mitchmckenna.com/post/15630/laravel-queued-jobs-doctrine-fix-mysql-has-gone-away-errors

With long running processes you can get a 2006 MySQL server has gone away error. This adds a class that calls Doctrine's DBAL Connection's $conn->ping() to see if it's gone away, if so close the connection and let DBAL automatically open a new connection on the next query attempt. This is talked about in the Doctrine's Github repo here. Here's some pseudo code on how to do it:

<?php

namespace Acme\Doctrine\ORM;

use Doctrine\ORM\EntityManager;

class ConnectionSaver
{
    /**
     * Ping the DB server, if connection is lost close it and DBAL will
     * automatically reconnect on the next DB call.
     */
    public function checkDatabaseConnection()
    {
        /** @var \Doctrine\DBAL\Connection */
        $conn = app(EntityManager::class)->getConnection();

        try {
            $ping = $conn->ping();
        } catch (\ErrorException $e) {
            $conn->close();
        }
    }
}

Then inside the command handler you just inject the class and call checkDatabaseConnection() function.

<?php

namespace App\Listeners\Commands;

use Acme\Doctrine\ORM\ConnectionSaver;

class FooHandler
{
    public function __construct(ConnectionSaver $connectionSaver) {
        $connectionSaver->checkDatabaseConnection();
    }
]]>
Wed, 20 Jan 2016 03:34:54 -0500 http://mitchmckenna.com/post/15630/laravel-queued-jobs-doctrine-fix-mysql-has-gone-away-errors/laravel-queued-jobs-doctrine-fix-mysql-has-gone-away-errors
Git Pre-commit Hook to Auto Run PHPUnit http://mitchmckenna.com/post/15960/auto-run-phpunit-git-pre-commit-hook

Never push up broken tests again. Using a pre-commit hook for git, when you type in git commit git will automatically run your unit tests to make sure nothing is broken with your recent changes.

Create a file called pre-commit in your project root at ./.git/hooks/ and put the following code inside it:

#!/usr/bin/php
<?php
printf("%sGit pre-commit hook %1\$s", PHP_EOL);
$projectName = basename(getcwd());
exec('vendor/bin/phpunit', $output, $returnCode);
if ($returnCode !== 0) {
    $minimalTestSummary = array_pop($output);
    printf("Test suite for %s failed: ", $projectName);
    printf("( %s ) %s%2\$s", $minimalTestSummary, PHP_EOL);
    return false;
}
printf("All tests for %s passed.%s%2\$s", $projectName, PHP_EOL);
return true;


The above is based on this gist but updated to use the copy of phpunit from your project's composer.

]]>
Fri, 20 Nov 2015 10:53:52 -0500 http://mitchmckenna.com/post/15960/auto-run-phpunit-git-pre-commit-hook/auto-run-phpunit-git-pre-commit-hook
PHPStorm: Auto Run PHPUnit On File Save http://mitchmckenna.com/post/15957/phpstorm-auto-run-phpunit-on-file-save

You can setup PHPStorm to run PHPUnit every time you save a unit test. By doing this you get immediate feedback if your unit tests are passing as you write them. And by running PHPUnit only against the current file you’re editing it can run really fast.

To set this up we need to create a File Watcher:

Preferences > File Watchers

Click (+) sign and select custom to open the new file watcher dialog. Add the following settings:

  • Name: PHPUnit
  • File type: PHP
  • Scope: click the to create a new one called tests and use a pattern like file:tests/*.* if tests is the folder all your unit tests are located in and call it tests or something.
  • Program: $PhpExecutable$
  • Arguments: vendor/bin/phpunit --configuration phpunit.xml.dist $FileDirRelativeToProjectRoot$/$FileName$
  • Working directory: $ProjectFileDir$

]]>
Thu, 19 Nov 2015 15:11:00 -0500 http://mitchmckenna.com/post/15957/phpstorm-auto-run-phpunit-on-file-save/phpstorm-auto-run-phpunit-on-file-save
Disable PHPStorm DQL/SQL Warnings http://mitchmckenna.com/post/15331/disable-phpstorm-dqlsql-warnings

I was getting a lot of yellow warnings for DQL/SQL. Turns out DQL isn't supported yet. You can turn off these warning by going to:

Preferences > Language Injections > and uncheck "SQL select/delete/insert..."

]]>
Tue, 07 Apr 2015 20:16:59 -0400 http://mitchmckenna.com/post/15331/disable-phpstorm-dqlsql-warnings/disable-phpstorm-dqlsql-warnings
Git: How to Squash Commits http://mitchmckenna.com/post/15265/git-squash-commits

Let's say you have several commits you'd like to combine into a single commit. Or an open source project you made a pull request to asked you to squash all your commits into one. You can squash them and they don't even have to have happened one after another.

git rebase -i HEAD~n

Where n is the number of the commits into the commit history to show to pick from.

It will open vim and look something like this

Now just change the word "pick" in front of the commit you want to squash to "squash" or "s". You can re-order commits if you want. Ones you change to "s" will be merged into the commit above it.

Then save and quit like you normally do, and it'll take you to a second page in vim where you can construct the merged commit message from the previous 2 commit messages. Save and exit.

Now just push up the changes: git push --force origin [branch-name]

Done!

For a more detailed explanation see the git manual: http://git-scm.com/docs/git-rebase#_interactive_mode

]]>
Thu, 19 Mar 2015 19:18:38 -0400 http://mitchmckenna.com/post/15265/git-squash-commits/git-squash-commits
Setup PHP CodeSniffer in PHPStorm http://mitchmckenna.com/post/15252/setup-php-codesniffer-in-phpstorm

Install PHP Code Sniffer Using Composer Globally:

composer global require "squizlabs/php_codesniffer=*"

Enable PHP Codesniffer:

Preferences > Languages & Frameworks > PHP > Code Sniffer

path: [get this from running 'which phpcs' in the terminal]

Enable PHPStorm to run Code Sniffer in realtime to detect PSR-2 problems:

Preferences > Inspections > PHP > PHP CodeSniffer validation

]]>
Thu, 12 Mar 2015 17:52:28 -0400 http://mitchmckenna.com/post/15252/setup-php-codesniffer-in-phpstorm/setup-php-codesniffer-in-phpstorm
Setting Up PHPUnit in PHPStorm http://mitchmckenna.com/post/15237/setting-up-phpunit-in-phpstorm

This is more so just notes for how I got PHPUnit running in PHPStorm for my project. There's probably a more optimal way to set this up but this works for now.

Tell PHPStorm to Use Composer's Copy of PHPUnit And Set Default Config

Preferences > PHPUnit

Docs: Loading PHPUnit with Composer.

Edit PHPUnit Configuration to use your custom config file

Run > Edit Configurations

Click the plus (+) sign and select PHPUnit.

Docs: Run/Debug Configuration: PHPUnit.

You can now right click (or use the keyboard shortcut) on files or folders and run unit tests.

Note: It may prompt you to setup the PHP Interpreter, open up terminal and type which php to find out where the php version is that your using then paste that in as the interpreter location (related docs).

Results

PHPStorm now tells how much unit test coverage you have beside each file/folder in the navigation tree and a Coverage panel should slide in from the right.

Setup PHPUnit to Run in Vagrant

You might need to run your phpunit inside Vagrant for some reason, follow this guide to do so.

]]>
Wed, 04 Mar 2015 18:57:06 -0500 http://mitchmckenna.com/post/15237/setting-up-phpunit-in-phpstorm/setting-up-phpunit-in-phpstorm
Doctrine cli-config.php for Laravel 5 http://mitchmckenna.com/post/15205/doctrine-cli-configphp-for-laravel-5

Doctine requires a custom made cli-config.php file for Setting up the Commandline Tool with a Laravel 5 application. The CLI tool is necessary when you need to for example clear Doctrine Cache using php vendor/bin/doctrine orm:clear-cache:metadata.

The following is what you can put in your cli-config.php:

<?php

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Console\ConsoleRunner;

// replace with file to your own project bootstrap
/** @var Illuminate\Foundation\Application $app */
$app = require_once __DIR__ . '/bootstrap/app.php';

/** @var Illuminate\Contracts\Console\Kernel $kernel */
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();

$app->boot();

// replace with mechanism to retrieve EntityManager in your app
$entityManager = $app[EntityManager::class];

return ConsoleRunner::createHelperSet($entityManager);


Note you will need to have already registered the EntityManager with your app through a service provider. You can use a package like mitchellvanw/laravel-doctrine or opensolutions/doctrine2bridge-l5 to setup Doctrine in Laravel 5.

]]>
Tue, 24 Feb 2015 02:53:35 -0500 http://mitchmckenna.com/post/15205/doctrine-cli-configphp-for-laravel-5/doctrine-cli-configphp-for-laravel-5
Fix WordPress' Jetpack Publicize Not Using Correct URL Structure in Permalink http://mitchmckenna.com/post/15187/fix-wordpress-jetpack-publicize-not-using-correct-url-structure-in-permalink

Jetpack's Publicize can be a handy feature to automatically share your post to various social network's like facebook, twitter and google plus.

One of the annoying features is when it shares it on those social networks it posts a http://wp.me... short link. You can fix that by deactivating "WP.me Shortlinks" in Jetpack settings.

Another annoying thing is even if "WP.me Shortlinks" is disabled, it will share the url in the classic http://domain.com/?p=123 permalink structure. In order to fix this, add the following to your theme's functions.php file:

function tweakjp_cust_shortlink() {
    global $post;

    if (!$post) {
        return;
    }

    return get_permalink($post->ID);
}
add_filter( 'get_shortlink', 'tweakjp_cust_shortlink' );


This solution was posted by the Publicize plugin author here: https://wordpress.org/support/topic/publicize-full-url-to-twitter

]]>
Tue, 17 Feb 2015 03:35:50 -0500 http://mitchmckenna.com/post/15187/fix-wordpress-jetpack-publicize-not-using-correct-url-structure-in-permalink/fix-wordpress-jetpack-publicize-not-using-correct-url-structure-in-permalink
How to download HD youtube videos using gPodder http://mitchmckenna.com/post/14198/how-to-download-hd-youtube-videos-using-gpodder

Since miro support for youtube recently broke (I've since posted a fix), I was giving gpodder a try and noticed it was only downloading youtube videos in standard definition. In order to enable HD downloads from youtube, open preferences, click 'edit config' scroll to the bottom where you can set the youtube fmt you'd like to download and change it from 18 to 22.

]]>
Mon, 17 Mar 2014 05:51:43 -0400 http://mitchmckenna.com/post/14198/how-to-download-hd-youtube-videos-using-gpodder/how-to-download-hd-youtube-videos-using-gpodder
Better Environment Detection for Laravel 4 http://mitchmckenna.com/post/14142/better-environment-detection-for-laravel-4

In Laravel's documentation they say you can specify machine names for your app to determine what environment settings to use (determining off url is no longer supported for security reasons). This can be tedious, especially if you have lot of developers using the app, and multiple staging environments. Laravel docs say you can redefine the function as a closure to determine environment however you want.

I wanted it to determine whether it's in local, staging, or production based off a file where the developer can set it in app/config/environment. I modified an idea by Mior Muhammad Zaki on crynobone.com to achieve this.

app/config/environment.php.dist

Create the following file which users will copy to set their environment settings:

<?php

/*
|--------------------------------------------------------------------------
| Application Environment Mode
|--------------------------------------------------------------------------
|
| Set the environment the app should be operating in. The environment name
| will specify which folder of configs to use.
|
| Current options are: local, production.
|
*/
return 'local';

/* End of bootstrap/environment.php */



bootstrap/start.php

Update bootstrap/start.php, move the bindInstallPaths() above the detectEnvironment() call so we can use the app paths inside our detectEnvironment() function, and tell detectEnvironment() to get the environment name from app/config/environment.php

/*
|--------------------------------------------------------------------------
| Bind Paths
|--------------------------------------------------------------------------
|
| Here we are binding the paths configured in paths.php to the app. You
| should not be changing these here. If you need to change these you
| may do so within the paths.php file and they will be bound here.
|
*/

$app->bindInstallPaths(require __DIR__.'/paths.php');

/*
|--------------------------------------------------------------------------
| Detect The Application Environment
|--------------------------------------------------------------------------
|
| Laravel takes a dead simple approach to your application environments
| so you can just specify a machine name for the host that matches a
| given environment, then we will automatically detect it for you.
|
*/

$env = $app->detectEnvironment(function () use ($app) {
    return require $app['path'] . '/config/environment.php';
});



.gitignore

Add the following to your .gitignore:

/app/config/environment.php



readme.md

Add to your readme.md that during installation the developer should run:

cp app/config/environment.php.dist app/config/environment.php
]]>
Wed, 05 Mar 2014 13:37:01 -0500 http://mitchmckenna.com/post/14142/better-environment-detection-for-laravel-4/better-environment-detection-for-laravel-4
NPM Link with Vagrant - Symlinks Not Working? http://mitchmckenna.com/post/13362/npm-link-with-vagrant-symlinks-not-working

NPM Link

It can be handy to use npm link to make npm use a local copy of a node repo if you're working on that other repo at the same time (eg. I'm working on a repo that relies on a npm module I also contribute to). npm link creates a symlink in your npm global modules folder to your local repo, so that npm install/update uses your local copy and doesn't overwrite it.

Vagrant

You used to have to add settings to your config to get symlinks to work in Vagrant (see this issue) but since Vagrant 1.1, Vagrant supports symlinks by default (yay!) (see the commit).

NPM Link Not Working With Vagrant?

If the symlink points to somewhere outside your shared_folder, the symlink won't work though. You have to shared_folder where the symlink points to as well. So just like in the example:

cd ~/projects/node-redis    # go into the package directory
npm link                    # creates global link
cd ~/projects/your-project-repo   # go into some other package directory.
npm link redis              # link-install the package


You have to add to your Vagrant config:

config.vm.synced_folder "/usr/local/lib/node_modules/node-redis", "/usr/local/lib/node_modules/node-redis", :owner => "www-data", :group => "www-data"
]]>
Thu, 05 Sep 2013 14:04:09 -0400 http://mitchmckenna.com/post/13362/npm-link-with-vagrant-symlinks-not-working/npm-link-with-vagrant-symlinks-not-working
mod_rewrite not working MAMP 2.1.4 [FIX] http://mitchmckenna.com/post/13277/mod_rewrite-not-working-mamp-214-fix

As always, setting up MAMP on a new computer and I ran into problems again. In this version of MAMP, mod_rewrite is installed and enabled by default (you can see in http://localhost:8888/MAMP/phpinfo.php ), however it still wasn't working for me. I was able to fix it by opening /Applications/MAMP/conf/apache/httpd.conf and changing line 197 from

<Directory />
  Options Indexes FollowSymLinks
  AllowOverride None
</Directory>


to:

<Directory />
  Options Indexes FollowSymLinks
  AllowOverride All
</Directory>


Source: stackoverflow

]]>
Sun, 18 Aug 2013 20:27:19 -0400 http://mitchmckenna.com/post/13277/mod_rewrite-not-working-mamp-214-fix/mod_rewrite-not-working-mamp-214-fix
"Yahoo paid a billion dollars for our treehouse" - On the Tumblr Deal http://mitchmckenna.com/post/12890/yahoo-paid-a-billion-dollars-for-our-treehouse-on-the-tumblr-deal

Yahoo paid a billion dollars for our treehouse, which is fucking nuts when you think about it, because the treehouse is worthless as soon as the cool kids decide to stop coming. We know it, they know it, and they know we know it. That’s why I’m not worried.

Read the rest of the post here: http://dearcoquette.com/post/51409321890/on-the-sale-of-tumblr

]]>
Sat, 01 Jun 2013 21:26:17 -0400 http://mitchmckenna.com/post/12890/yahoo-paid-a-billion-dollars-for-our-treehouse-on-the-tumblr-deal/yahoo-paid-a-billion-dollars-for-our-treehouse-on-the-tumblr-deal
Firestorm: The story of the bushfire at Dunalley | The Guardian http://mitchmckenna.com/post/12878/firestorm-the-story-of-the-bushfire-at-dunalley-the-guardian

Firestorm, the Guardian's documentary of this year's bushfires in Tasmania using full-screen video & interactive responsive design to create an immersive portrayal of the crisis. #longread

A screenshot of the front 'page' of the Firestorm package

http://www.guardian.co.uk/world/interactive/2013/may/26/firestorm-bushfire-dunalley-holmes-family

]]>
Thu, 30 May 2013 13:57:40 -0400 http://mitchmckenna.com/post/12878/firestorm-the-story-of-the-bushfire-at-dunalley-the-guardian/firestorm-the-story-of-the-bushfire-at-dunalley-the-guardian
Twitter Cards http://mitchmckenna.com/post/12704/twitter-cards

Didn't see the point of Twitter Cards creating a new spec when Open Graph already existed, but with the latest update that includes new markup tags for app links and new types like image galleries which are likely only really specific to a twitter-like experience, I'm starting to see why they decided to start their own.

https://dev.twitter.com/blog/mobile-app-deep-linking-and-new-cards

]]>
Thu, 04 Apr 2013 19:07:03 -0400 http://mitchmckenna.com/post/12704/twitter-cards/twitter-cards