PHP, Web Development, Yii Framework

Stop Newrelic From Recording Slow AJAX/General Calls in Yii2

<?php

namespace common\components;

use Yii;
use yii\base\Component;
use yii\base\BootstrapInterface;
use yii\web\Application;
use yii\web\Controller;

class Newrelic extends Component implements BootstrapInterface
{
    public $ignoreRoutes = [];

    public function bootstrap($app)
    {
        // delay attaching event handler to the view component after it is fully configured
        $app->on(Controller::EVENT_BEFORE_ACTION, function () use ($app) {
            $this->beforeAction($app);
        });
    }

    public function beforeAction($app)
    {
        if (extension_loaded('newrelic')) {
            if (in_array(Yii::$app->getUrlManager()->parseRequest($app->request)[0], $this->ignoreRoutes)) {
                newrelic_ignore_transaction();
            }
        }
    }
}
Advertisements
CSS, Web Development

Responsive images via background-size

As I was doing some image uploading work on a project recently I decided to understand, truly, if, for image post-processing, I should resize and cut corners off to keep ratio or thumbnail and keep the independent size of the image, but risk making it difficult to put into the page.

As an example, I have an image of 700px x 418px. I have a choice between cutting it down to 400px x 400px, cutting off 300px or bringing it down to about 400px x 238px and make it more difficult to add to a Bootstrap powered gallery.

So, I looked at what Facebook did here and I noticed they actually use the 400×238 image as a background image and then used background-size:cover to fix any problems. Fortunately, despite what caniuse.com (http://caniuse.com/#feat=background-img-opts) says, background-size is supported in IE8 (I actually got a Windows 7 VM with IE8 on it from modern.ie and tested it) but, with no content, the media queries for resizing the columns could not function right.

So I need something to tell both IE8 and later browsers how to size this image.

The CSS solution at this link works perfect: http://www.smashingmagazine.com/2013/07/22/simple-responsive-images-with-css-background-images

In short, here is the post summarised:

<div style="width: 400px">
    <span id="image">
        <span id="image-inner">
        </span>
    </span>
</div>

#image {
    display: inline-block;
    width: 100%;
    font-size: 0;
    line-height: 0;
    vertical-align: middle;
    background-size: 100%;
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-image: url(image.jpg); 
}


#image-inner {
    display: block;
    height: 0;
    padding-top: 63.3%;
}
PHP, Yii Framework

Getting Yii2 Debug to Show on User Role Instead of IP

<?php

namespace common\components;

use Yii;
use yii\debug\Module as DebugModule;
use common\models\User;

class Module extends DebugModule
{
    private $_basePath;

    protected function checkAccess()
    {
        $user = Yii::$app->getUser();

        if (
            $user->identity &&
            $user->can('admin')
        ) {
            return true;
        }
        return parent::checkAccess();
    }

    /**
     * Returns the root directory of the module.
     * It defaults to the directory containing the module class file.
     * @return string the root directory of the module.
     */
    public function getBasePath()
    {
        if ($this->_basePath === null) {
            $class = new \ReflectionClass(new yii\debug\Module('debug'));
            $this->_basePath = dirname($class->getFileName());
        }

        return $this->_basePath;
    }
}
PHP, Yii Framework

Disable Yii2 CSRF on Specific Actions

<?php

namespace common\components;

use Yii;

class Request extends \yii\web\Request
{
    public $noCsrfRoutes = [];

    public function validateCsrfToken()
    {
        if (
            $this->enableCsrfValidation &&
            in_array(Yii::$app->getUrlManager()->parseRequest($this)[0], $this->noCsrfRoutes)
        ) {
            return true;
        }
        return parent::validateCsrfToken();
    }
}

Then, add the request component to your configuration like so:

'request' => [
    'class' => 'common\components\Request',
    'noCsrfRoutes' => [
        'order/calculate-ns-shipping'
    ]
],
PHP, Yii Framework

Using Yii2 RBAC PHP Auth Manager Without Having to Use assign()

<?php

namespace common\components;

use Yii;

class PhpManager extends \yii\rbac\PhpManager
{
    public function init()
    {
        parent::init();
    }

    public function getAssignments($userId)
    {
        if (!Yii::$app->user->isGuest) {
            $assignment = new \yii\rbac\Assignment;
            $assignment->userId = $userId;
            $assignment->roleName = Yii::$app->user->identity->role;
            return [$assignment->roleName => $assignment];
        }
    }
}
PHP

PHP Convert Duration Time Stamp to date() Syntax

I fond out while using:

date('H:i:s', $time);

To display time durations that it actually returns incorrectly. It would keep returning an extra hour. I found this was due to DST. So I quickly put my thinking cap on and botched together this:

function getTimeString()
{
    $time = 3600 + (60 * 32) + (50); // 01:32:50
    $time_string = '';

    $hours = (int)($time / (60 * 60));
    if (strlen($hours) > 1) {
        $time_string = $hours . ':';
    } else {
        $time_string = '0' . $hours . ':';
    }

    $minutes = (int)(($time % (60 * 60)) / (60));
    if ($minutes >= 1) {
        if (strlen($minutes) > 1) {
            $time_string .= $minutes . ':';
        } else {
            $time_string .= '0' . $minutes . ':';
        }

        $seconds = (int)(($time % (60 * 60)) % (60));
        if (strlen($seconds) > 1) {
            $time_string .= $seconds;
        } else {
            $time_string .= '0' . $seconds;
        }
    } else {
        $time = (int)$time;
        if (strlen($time) > 1) {
            $time_string .= '00:' . $time;
        } else {
            $time_string .= '00:0' . $time;
        }
    }
    return $time_string;
}

This function will now correctly convert any timestamp into the needed date notation without fear of DST or other time factors intervening.

Note: This function is without optimisations