mysql calendar

SELECT (CURDATE() - INTERVAL c.number DAY) AS date, 
DATE_FORMAT(CURDATE() - INTERVAL c.number DAY,'%a') as week_short,
DATE_FORMAT(CURDATE() - INTERVAL c.number DAY,'%W') as week_long,
DATE_FORMAT(CURDATE() - INTERVAL c.number DAY,'%M') as month_long,
DATE_FORMAT(CURDATE() - INTERVAL c.number DAY,'%b') as month_long,
DATE_FORMAT(CURDATE() - INTERVAL c.number DAY,'%d') as day_with_zero,
DATE_FORMAT(CURDATE() - INTERVAL c.number DAY,'%e') as day_without_zero
FROM (SELECT singles + tens + hundreds number FROM 
( SELECT 0 singles
UNION ALL SELECT   1 UNION ALL SELECT   2 UNION ALL SELECT   3
UNION ALL SELECT   4 UNION ALL SELECT   5 UNION ALL SELECT   6
UNION ALL SELECT   7 UNION ALL SELECT   8 UNION ALL SELECT   9
) singles JOIN 
(SELECT 0 tens
UNION ALL SELECT  10 UNION ALL SELECT  20 UNION ALL SELECT  30
UNION ALL SELECT  40 UNION ALL SELECT  50 UNION ALL SELECT  60
UNION ALL SELECT  70 UNION ALL SELECT  80 UNION ALL SELECT  90
) tens  JOIN 
(SELECT 0 hundreds
UNION ALL SELECT  100 UNION ALL SELECT  200 UNION ALL SELECT  300
UNION ALL SELECT  400 UNION ALL SELECT  500 UNION ALL SELECT  600
UNION ALL SELECT  700 UNION ALL SELECT  800 UNION ALL SELECT  900
) hundreds
ORDER BY number DESC) c  
WHERE c.number BETWEEN 0 and 364
;

Leave a comment

Symfony 2: Sending Email via Swiftmail

$att = \Swift_Attachment::newInstance($content, "blacklist_report_" . date("Y_m_d_H_i_s").".tsv");
$message = \Swift_Message::newInstance()
    ->setSubject('xxxxxx '.date("d/m/Y"))
    ->setFrom('no-replay@xxxx.com')
    ->setTo(array('email addresses'));
$message->attach($att);

$this->getContainer()->get('mailer')->send($message);
$mailer = $this->getContainer()->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $this->getContainer()->get('swiftmailer.transport.real');
$spool->flushQueue($transport);

Leave a comment

Symfony – how it loading bundle extension

Symfony\Component\HttpKernel\Kernal

public function prepareContainer;  look at following one line;

$container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
MergeExtensionConfigurationPass been added to pass config.

then in
Symfony\Component\HttpKernel\Kernal's protected function initializeContainer()
$container->compile(); this method will call
MergeExtensionConfigurationPass's process method.

in the process method,
$extension->load($config, $tmpContainer);
will call registered extension's load method.

Leave a comment

Magento class naming

so in my config file, i have following :

Anru_NZRegion_Helper

pay attention to “Anru_NZRegion_Helper”, “NZR” 3 letters are upper case.

in helpers’ Data file, i have Anru_NZRegion_Helper_Data class. and Magento complains about no class found.

This is because of Magento tried to explode “Anru_NZRegion_Helper” into 3 different parts, then join those parts back, and upper casing each part’s first letter, so class name becomes
“Anru_Nzregion_Helper”.

Also, Magento use Anru_NZRegion as a folder name to auto – include class.

there was a bug wasted so many of mine time, because In my home computer , my Mangento is installed on a vagrant machine, and on a shared folder, and my host machine is windows, which means folder name is case – insensitive. but Linux is case-sensitive.

initially, I had this Anru_Nzregion_Helper , in linux it becomes “Anru/Nzregion” folder name
and worked on my local machine but failed on my linux host.

Leave a comment

Symfony to generate dynamic routing

For dynamic routing, one of problem is Symphony looking for router

from cache file, and dynamic router is not saved into cache, for deal with this problem,

we have to delete Symphony’s router cache file. here is how to do it.

1> we have to build up a service. define service file first

example.cache:
    class: Example\CacheBundle\Service\RouterCacheService
    arguments:
      - @router
      - %kernel.environment%
      - %kernel.cache_dir%

use Symfony\Component\Routing\Router;

class RouterCacheService
{
    private $router;
    private $environment;
    private $cache_dir;
    public function __construct(Router $router, $env, $cacheDir)
    {
        $this->router = $router;
        $this->environment = $env;
        $this->cache_dir = $cacheDir;
    }
    public function clearCache($environment = null)
    {
        if (null === $environment) {
            $environment = $this->environment;
        }

        $this->router->clearCache($this->cache_dir, $environment, $this->environment == $environment);
    }
}

2> overriding cache clean function. In Symphony , there is a
Symfony\Bundle\FrameworkBundle\Routing\Router class, we need to extends this class, and overriding clearCache method. here is code: under bundler’s Routing folder, create this class,
use Symfony\Bundle\FrameworkBundle\Routing\Router as BaseRouter;

class CacheCleanRouter extends BaseRouter
{
    public function clearCache($cache_dir, $environment, $warm_up)
    {
        $environment = ucfirst($environment);

        @unlink($cache_dir .'/app'. $environment .'UrlMatcher.php');
        @unlink($cache_dir .'/app'. $environment .'UrlGenerator.php');

        if ($warm_up) {
            $this->matcher   = null;
            $this->generator = null;
            $this->warmUp($cache_dir);
        }
    }
}

 

So now , we are able to clean our cache, this will make Dynamic URL correctly recognized by Symfony framework.

the next step we have to do is to write class to generate dynamic URL.

Symfony official doc, https://symfony.com/doc/current/routing/custom_route_loader.html

Pay attention to load method,and $routesContainer. under bundler’s Routing folder, create this class,

class RoutesLoader implements LoaderInterface
{
    /**
     * @var EntityManagerInterface
     */
    protected $entityManager;

    /**
     * @var RoutesContainer
     */
    protected $routesContainer;

    public function __construct(EntityManagerInterface $entityManager, RoutesContainer $routesContainer)
    {
        $this->entityManager = $entityManager;
        $this->routesContainer = $routesContainer;
    }

    /**
     * {@inheritdoc}
     */
    public function load($resource, $type = null)
    {
        $examples = $this->entityManager->getRepository('MyExampleBundle:Examples')->findAll();
        $routes = new RouteCollection();

        foreach ($examples as $example) {
            $custom = $this->routesContainer->getCustomRoutes($example->getSlug());

            foreach ($custom as $name => $route) {
                $routes->add($name, $route);
            }
        }

        return $routes;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($resource, $type = null)
    {
        return 'my_example' === $type;
    }

    /**
     * {@inheritdoc}
     */
    public function getResolver()
    {
        //
    }

    /**
     * {@inheritdoc}
     */
    public function setResolver(LoaderResolverInterface $resolver)
    {
        //
    }
}

 

after defined RoutesLoader class, we need to set it up as a service

myexample.loader.routes_loader:
    class: myexample\Routing\RoutesLoader
    arguments:
        - @doctrine.orm.entity_manager
        - @myexample.routing.routes_container
    tags:
        - { name: routing.loader }
now, it time to define a class to generate dynamic url. create the class as a service first,
myexample.routing.routes_container:
    class: myexample\Routing\RoutesContainer
    arguments:
        - @router

under bundler’s Routing folder, create this class, define a examples.list string which represents /{anytext}-example router.

class RoutesContainer
{
    protected $router;
    protected $config = [
'examples.list'                    => [
            'pattern'  => '/%prefix%-example',
            'nested'   => true,
            'methods'  => [
                'GET',
            ],
            'defaults' => [
                '_controller' => 'myexample:Examples:list',
            ],
       ],
       'examples.edit'                    => [
            'pattern'  => '/%prefix%-example/{id}/edit',
            'nested'   => true,
            'methods'  => [
                'GET',
            ],
           'defaults' => [
              '_controller' => 'myexample:Examples:edit',
           ],
      ],
 ];

protected $routesPrefix = 'myexamples.';

public function __construct(RouterInterface $router)
{
    $this->router = $router;
}

public function getCustomRoutes($prefix)
{
    $routes = [];

    foreach ($this->config as $name => $params) {
        list($name, $route) = $this->createRoute($name, $prefix);
        $routes[$name] = $route;
    }

    return $routes;
}

public function getRealRouteName($routeName, $prefix)
{
    if (!isset($this->config[$routeName])) {
        throw new RouteNotFoundException(sprintf('Route %s not found', $routeName));
    }
    $config = $this->config[$routeName];
    $name = implode('.', [$prefix, $routeName]);

    if ($config['nested']) {
        $name = $this->routesPrefix.$name;
    }

    return $name;
}

/** TODO: this should be more explicit */
public function getPrefixFromRoute($name)
{
    $name = str_replace($this->routesPrefix, '', $name);

    return substr($name, 0, strpos($name, '.'));
}

public function checkAvailability($pattern)
{
    $routes = $this->router->getRouteCollection()->all();

    foreach ($routes as $route) {
        if ($route->getPath() === $pattern) {
            return false;
        }
    }

    return true;
}

public function generateRoute($name, $prefix, array $params = [], $absolute = RouterInterface::ABSOLUTE_PATH)
{
    return $this->router->generate($this->getRealRouteName($name, $prefix), $params, $absolute);
}

protected function createRoute($name, $prefix)
{
    $config = $this->config[$name];
    $name = $this->getRealRouteName($name, $prefix);

    $route = new Route(str_replace('%prefix%', $prefix, $config['pattern']), $config['defaults']);
    $route->setMethods($config['methods']);

    return [$name, $route];
}

}

 

now all code is here, but how we going to use it? says, you want to know what is route name for ‘examples.list’ in your controller.

$prefix = 'pen';

$this->get('myexample.routing.routes_container')->getRealRouteName('examples.list', $prefix);

the above code will find out router for pen-example
want redirect to dynamic url in your controller?
$prefix = 'pen';
$id = 2;
$url = $this->get('myexample.routing.routes_container')->getRealRouteName('examples.edit', $prefix);
$this->redirectToRoute(
    $url
    [
     'id' => $id,
    ]
);

			

Leave a comment

signing a powershell script

code signing need to executed in administrator context

0> write a powershell script hello.ps1
1> Set-ExecutionPolicy AllSigned

generates a self signed certificate
2> New-SelfSignedCertificate -DnsName powershell-self-sign -Type CodeSigning

signing a script

3> Set-AuthenticodeSignature C:\t\hello.ps1 @(gci Cert:\LocalMachine\My -DnsName powershell-self-sign -codesigning)[0]

4> run cert from start menu.
5> from Personal/Certificate, find powershell-self-sign cert
6> right click the cert , and copy , then paste the cert to intermediate certificate authoritties/Certificates
7> paste the cert to Trusted Root / certificate.

Leave a comment

PHPStorm 2016, vagrant, Symfony and xdebug

How to set up remote debug for symfony app.

1> go to run -> Edit Configurations

2> Click on ‘+’ symbol, top – left corner

3> adding a PHP web application, now a window popup, and give a name to this application.

4> select a server, if no server set up, following below steps.

4.1> give server a name.

4.2> your host name and port (not xdebug port)

4.3> choose xdebug

4.5> set up mapping.

for example:

if your symfony app is intalled on folder is e:\www\test\dev, and Vagrantfile is under e:\www\test, then on vagrant server,

you will have /vagrant/dev, and Symfony app’s doc root is /vagrant/dev/web/

now, use above information to set up mapping.

e:\www\test mapping to /vagrant

e:\www\test\dev mapping to /vagrant/dev

e:\www\test\dev\web mapping to /vagrant/dev/web

5> start URL set to “/”

6> select a browser.

On vagrant server side, install xdebug.

put following xdebuger content to php config file.

xdebug.max_nesting_level=200
xdebug.remote_enable=on
xdebug.remote_host=127.0.0.1
xdebug.idekey=PHPSTORM

 

restart web server or php5-fpm instance.

 

now, go back to hosting machine. I am use windows 10.

run putty.exe, on Connection->SSH->Tunnels set up ssh tunnel.

tunnel

now login into vagrant. make sure port 9000 is not been occupied.

go to phpstrom. turn on debug listener, on top – right corner.

debug

go to File->Settings->Languages & Frameworks -> PHP -> debug, make sure xdebug port is 9000

debug_port

 

set a break point on Symfony app,and from run -> Debug “you app” to start debugging symfony app.

 

Leave a comment