<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\ContactForm;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
                'view' => 'error.twig',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'mellon' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index.twig');
    }

    public function actionContact()
    {
        $model = new ContactForm();

        if (
            $model->load(Yii::$app->request->post()) &&
            $model->contact(Yii::$app->params['adminEmail'])
        ) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }

        return $this->render('contact.twig', ['model' => $model]);
    }

    public function actionAbout()
    {
        return $this->render('about.twig', ['server' => $_SERVER]);
    }
}

<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\ContactForm;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
                'view' => 'error.twig',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'mellon' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index.twig');
    }

    public function actionContact()
    {
        $model = new ContactForm();

        if (
            $model->load(Yii::$app->request->post()) &&
            $model->contact(Yii::$app->params['adminEmail'])
        ) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }

        return $this->render('contact.twig', ['model' => $model]);
    }

    public function actionAbout()
    {
        return $this->render('about.twig');
    }
}

Remove unused variable from `about` view


<?php

namespace Galahad\LaravelAddressing;

/**
 * Class Entity
 *
 * @package Galahad\LaravelAddressing
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class Entity
{
    /**
     * Get property if get method exists
     *
     * @param $name
     * @return mixed
     */
    function __get($name)
    {
        $name = array_walk(explode('_', $name), 'ucfirst'); // some_name => ['Some', 'Name']
        $name = implode('', $name); // SomeName
        $method = 'get'.$name;
        if (method_exists($this, $method)) {
            return $this->$method();
        }
    }
}

<?php

namespace Galahad\LaravelAddressing;

/**
 * Class Entity
 *
 * @package Galahad\LaravelAddressing
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class Entity
{
    /**
     * Get property if get method exists
     *
     * @param $name
     * @return mixed
     */
    function __get($name)
    {
        $name = array_map('ucfirst', explode('_', $name)); // some_name => ['Some', 'Name']
        $name = implode('', $name); // SomeName
        $method = 'get'.$name;
        if (method_exists($this, $method)) {
            return $this->$method();
        }
    }
}

Fix bug in __get method

Fix bug in __get method


<?php

namespace BrianReeve\AssetProxy;

//use BrianReeve\AssetProxy\Asset;

class AssetLoader
{
	protected $_basePath = '/';

	public function __construct($basePath = NULL)
	{
		if (!empty($basePath)) {
			$this->_basePath = $basePath;
		}
	}

	public function getAsset($path)
	{
		if (empty($this->_basePath) || strpos($path,'/') === 0) {
			$fullPath = $path;
		} else {
			$fullPath = $this->_basePath.$path;
		}
		return new Asset($fullPath);
	}

}

<?php

namespace BrianReeve\AssetProxy;

//use BrianReeve\AssetProxy\Asset;

class AssetLoader
{
	protected $_basePath = '/';

	public function __construct($basePath = NULL)
	{
		if (strtoupper(substr(PHP_OS, 0 , 3)) === 'WIN') {
			$this->_basePath = '';
		}

		if (!empty($basePath)) {
			$this->_basePath = $basePath;
		}
	}

	public function getAsset($path)
	{
		if (empty($this->_basePath) || strpos($path,'/') === 0) {
			$fullPath = $path;
		} else {
			$fullPath = $this->_basePath.$path;
		}
		return new Asset($fullPath);
	}

}

Fix base path for WIN so paths don't start with /


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // save whole request to data property
        $request = (array)json_decode(file_get_contents('php://input'));
        if (count($request) > 0) {
            $_POST = $request;
        }
    }

    /**
     * Universal method to return JSON object in response
     *
     * @param boolean
     * @param mixed array | string
     * @return string (json)
     */
    protected function _returnAjax($success, $data = [])
    {
        $return["success"] = $success;
        if ($success === false) {
            // data should be string now
            $return["error"] = ["message" => $data];
        } else {
            $return["data"] = $data;
        }
        print json_encode($return);
        die();
    }

    /**
     * Check if request is sent over proper request method
     * @param string ("get" | "post" | "put" | "delete")
     */
    protected function _access($allowedMethod)
    {
        if ($this->input->method() !== $allowedMethod) {
            $this->_returnAjax(false, "Access restricted due to wrong request method.");
        }
    }

    /**
     * Check if client is authenticated
     */
    protected function _checkAuthentication()
    {
        $loggedIn = $this->session->userdata("loggedIn");
        if (isset($loggedIn) === false) {
            $this->_returnAjax(false, "Please authenticate first.");
        }
    }
}

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // save whole request to data property
        $request = (array)json_decode(file_get_contents('php://input'));
        if (count($request) > 0) {
            $_POST = $request;
        }
    }

    /**
     * Universal method to return JSON object in response
     *
     * @param boolean
     * @param mixed array | string
     * @return string (json)
     */
    protected function _returnAjax($success, $data = [])
    {
        $return["success"] = $success;
        if ($success === false) {
            // data should be string now
            $return["error"] = ["message" => $data];
        } else {
            $return["data"] = $data;
        }
        print json_encode($return);
        exit();
    }

    /**
     * Check if request is sent over proper request method
     * @param string ("get" | "post" | "put" | "delete")
     */
    protected function _access($allowedMethod)
    {
        if ($this->input->method() !== $allowedMethod) {
            $this->_returnAjax(false, "Access restricted due to wrong request method.");
        }
    }

    /**
     * Check if client is authenticated
     */
    protected function _checkAuthentication()
    {
        $loggedIn = $this->session->userdata("loggedIn");
        if (isset($loggedIn) === false) {
            $this->_returnAjax(false, "Please authenticate first.");
        }
    }
}

Exit instead of die for ending json return


<?php namespace Yaim\Mitter;

use Illuminate\Support\ServiceProvider;

class MitterServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	* Bootstrap the application events.
	*
	* @return void
	*/
	public function boot()
	{
		//
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		//
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

}

<?php namespace Yaim\Mitter;

use Illuminate\Support\ServiceProvider;

class MitterServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	* Bootstrap the application events.
	*
	* @return void
	*/
	public function boot()
	{
		$this->publishes([
			__DIR__.'/assets' => public_path('packages/yaim/mitter'),
		], 'public');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		//
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

}

Add publish method for assets to ServiceProvider for L5


<?php

use Interop\Container\ContainerInterface;
use Relay\RelayBuilder;
use Zend\Diactoros\Response\EmitterInterface;
use Zend\Diactoros\Response\SapiEmitter;

return [
    RelayBuilder::class => function (ContainerInterface $c) {
        $resolver = function ($class) use ($c) {
            return $c->get($class);
        };

        $relayBuilder = new RelayBuilder($resolver);

        return $relayBuilder;
    },
    EmitterInterface::class => DI\object(SapiEmitter::class),
];

<?php

use Interop\Container\ContainerInterface;
use Relay\RelayBuilder;
use Zend\Diactoros\Response\EmitterInterface;
use Zend\Diactoros\Response\SapiEmitter;

return [
    RelayBuilder::class => function (ContainerInterface $c) {
        $resolver = function ($middleware) use ($c) {
            if (is_string($middleware)) {
                $middleware = $c->get($middleware);
            }

            return $middleware;
        };

        $relayBuilder = new RelayBuilder($resolver);

        return $relayBuilder;
    },
    EmitterInterface::class => DI\object(SapiEmitter::class),
];

Add support for middleware callables

Add support for middleware callables


<?php

namespace Core;

class Controller
{
	protected $session;
	protected $view;
	protected $auth;
	protected $redirect;
	protected $flash;
	protected $validation;

	/**
	 * Données passées en POST
	 * @var Array
	 */
	protected $data;

	public function __construct()
	{
		$this->session = new \Libs\Session;

		$this->auth = new \Libs\Auth($this->session);
		$this->redirect = new \Libs\Redirect($this->session);
		$this->flash = new \Libs\Flash($this->session);

		$this->view = new View;

		if(isset($_POST))
		{
			$this->data = $_POST;
		}
	}

	/**
	 * Determine si l'appel a été fait en Ajax
	 * @return bool
	 */
	public function isAjax()
	{
		return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
	}
}

<?php

namespace Core;

use \Libs\Session;
use \Libs\Auth;
use \Libs\Redirect;
use \Libs\Flash;

class Controller
{
	protected $session;
	protected $view;
	protected $auth;
	protected $redirect;
	protected $flash;
	protected $validation;

	/**
	 * Données passées en POST
	 * @var Array
	 */
	protected $data;

	public function __construct()
	{
		$this->session = new Session;

		$this->auth = new Auth($this->session);
		$this->redirect = new Redirect($this->session);
		$this->flash = new Flash($this->session);

		$this->view = new View;

		if(isset($_POST))
		{
			$this->data = $_POST;
		}
	}

	/**
	 * Determine si l'appel a été fait en Ajax
	 * @return bool
	 */
	public function isAjax()
	{
		return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
	}
}

Use librairies at the beginning

Use librairies at the beginning


<?php

class Sign2pay_Payment_Block_Form_Sign2pay extends Mage_Payment_Block_Form
{
    protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('sign2pay/form/sign2pay.phtml');
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        // This block might not be constructed
        // with whole magento layout
        if (Mage::app()->getLayout()->getBlock('head')) {
            Mage::app()->getLayout()->getBlock('content')->append(
                Mage::app()->getLayout()->createBlock('sign2pay/riskAssessment')
            );
        }
    }

    public function getOrderId()
    {
        $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
        return $lastOrderId;
    }

    public function getFullOrderID()
    {
        $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
        $order = Mage::getModel('sales/order')->load($lastOrderId);
        $paymentTransactionId = $order->getIncrementId();
        return $paymentTransactionId;
    }
}

<?php

class Sign2pay_Payment_Block_Form_Sign2pay extends Mage_Payment_Block_Form
{
    protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('sign2pay/form/sign2pay.phtml')
            ->setMethodLabelAfterHtml('<img src="https://app.sign2pay.com/api/v2/banks/logo.gif" alt="Sign2pay" height="20" style="margin-right: 0.4em;"/>');
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        // This block might not be constructed
        // with whole magento layout
        if (Mage::app()->getLayout()->getBlock('head')) {
            Mage::app()->getLayout()->getBlock('content')->append(
                Mage::app()->getLayout()->createBlock('sign2pay/riskAssessment')
            );
        }
    }

    public function getOrderId()
    {
        $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
        return $lastOrderId;
    }

    public function getFullOrderID()
    {
        $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
        $order = Mage::getModel('sales/order')->load($lastOrderId);
        $paymentTransactionId = $order->getIncrementId();
        return $paymentTransactionId;
    }
}

Add logo to payment method

Add logo to payment method


<?php

use \Symfony\Component\HttpFoundation\Response;
use \Symfony\Component\HttpFoundation\Request;
use Identicon\Identicon;
use Identicon\Identity\Identity;

/* @var \Silex\Application $app
 * @return Response
 */

$app->get("/", function(\Silex\Application $app) {
    return new Response(
        $app["twig"]->render("index.twig", array("error" => false)),
        200,
        array()
    );
})->bind("index");

$app->post("/", function(Request $request) use ($app) {
    $name = $request->request->get("name");
    if ($name) {
        return $app->redirect("/{$name}");
    }
    return new Response(
        $app["twig"]->render("index.twig", array("error" => $name ? false : true)),
        200,
        array()
    );
});

$app->get("/basic/{name}.png", function(\Silex\Application $app, $name) {
    $identicon = new Identicon($name);
    return new Response($identicon->getContent(), 200, array(
        "Content-Type" => "image/png"
    ));
})->bind("basic");

$app->get("/{name}", function(\Silex\Application $app, $name) {
    $identity = new Identity($name);
    return new Response(
        $app["twig"]->render("profile.twig", array(
            "name" => $identity->getName()
        )),
        200,
        array()
    );
});

<?php

use \Symfony\Component\HttpFoundation\Response;
use \Symfony\Component\HttpFoundation\Request;
use Identicon\Identicon;
use Identicon\Identity\Identity;

/* @var \Silex\Application $app
 * @return Response
 */

$app->match("/", function(Request $request) use ($app) {
    $name = $request->request->get("name");
    if ($name) {
        return $app->redirect("/{$name}");
    }
    return new Response(
        $app["twig"]->render("index.twig", array("error" => $name ? false : true)),
        200,
        array()
    );
})->bind("index");

$app->get("/basic/{name}.png", function(\Silex\Application $app, $name) {
    $identicon = new Identicon($name);
    return new Response($identicon->getContent(), 200, array(
        "Content-Type" => "image/png"
    ));
})->bind("basic");

$app->get("/{name}", function(\Silex\Application $app, $name) {
    $identity = new Identity($name);
    return new Response(
        $app["twig"]->render("profile.twig", array(
            "name" => $identity->getName()
        )),
        200,
        array()
    );
});

Improve controller actions for form.

Improve controller actions for form.


<?php

use Gitiki\Exception\PageNotFoundException;

use Symfony\Component\HttpFoundation\Request,
    Symfony\Component\HttpKernel\Exception\HttpException;

$app->get('/', function () use ($app) {
    try {
        $page = $app->getPage('_index');
    } catch (PageNotFoundException $e) {
        throw new HttpException(404, sprintf('The page "%s" was not found.', $e->getPage()), $e);
    }

    return $app['twig']->render('page.html.twig', [
        'page' => $page,
    ]);
})
->bind('homepage')
;

$app->get('/_menu', function () use ($app) {
    try {
        $page = $app->getPage('_menu');
    } catch (PageNotFoundException $e) {
        return '';
    }

    return $app['twig']->render('menu.html.twig', [
        'menu' => $page->getMetas(),
    ]);
});

$app->get('/{page}', function ($page) use ($app) {
    try {
        $page = $app->getPage($page);
    } catch (PageNotFoundException $e) {
        throw new HttpException(404, sprintf('The page "%s" was not found.', $e->getPage()), $e);
    }

    return $app['twig']->render('page.html.twig', [
        'page' => $page,
    ]);
})
->assert('page', '[\w\d-]+')
->bind('page')
;

<?php

use Gitiki\Exception\PageNotFoundException;

use Symfony\Component\HttpFoundation\Request,
    Symfony\Component\HttpKernel\Exception\HttpException,
    Symfony\Component\HttpKernel\HttpKernelInterface;

$app->get('/', function () use ($app) {
    return $app->handle(Request::create('/_index'), HttpKernelInterface::SUB_REQUEST, false);
})
->bind('homepage')
;

$app->get('/_menu', function () use ($app) {
    try {
        $page = $app->getPage('_menu');
    } catch (PageNotFoundException $e) {
        return '';
    }

    return $app['twig']->render('menu.html.twig', [
        'menu' => $page->getMetas(),
    ]);
});

$app->get('/{page}', function ($page) use ($app) {
    try {
        $page = $app->getPage($page);
    } catch (PageNotFoundException $e) {
        throw new HttpException(404, sprintf('The page "%s" was not found.', $e->getPage()), $e);
    }

    return $app['twig']->render('page.html.twig', [
        'page' => $page,
    ]);
})
->assert('page', '[\w\d-]+')
->bind('page')
;

Make a sub request to generate homepage

Make a sub request to generate homepage


<?php

namespace Libs;

use \Core\Config;
use \Libs\interfaces\SessionInterface;

class Redirect
{
	protected $session;

	public function __construct(SessionInterface $session)
	{
		$this->session = $session;
	}

	public function back()
	{
		if(array_key_exists('HTTP_REFERER', $_SERVER))
		{
			header('Location: ' . $_SERVER['HTTP_REFERER']);
		}
		else
		{
			$this->home();
		}
	}

	public function backWithInput($input)
	{
		$this->session->set('input', $input);
		$this->back();
	}

	public function to($url)
	{
		header('Location: ' . WEBROOT. $url);
	}

	public function home()
	{
		$config = Config::getInstance();
		$this->to($config->get('default_controller') . '/' . $config->get('default_method'));
	}
}

<?php

namespace Libs;

use \Core\App;
use \Core\Config;
use \Libs\interfaces\SessionInterface;

class Redirect
{
	protected $session;

	public function __construct(SessionInterface $session)
	{
		$this->session = $session;
	}

	public function back()
	{
		if(array_key_exists('HTTP_REFERER', $_SERVER))
		{
			header('Location: ' . $_SERVER['HTTP_REFERER']);
		}
		else
		{
			$this->home();
		}
	}

	public function backWithInput($input)
	{
		$this->session->set('input', $input);
		$this->back();
	}

	public function to($url)
	{
		header('Location: ' . WEBROOT. $url);
	}

	public function home()
	{
		$config = App::get('Core\Config');
		$this->to($config->get('home_route'));
	}
}

Use DIC to get home route from config

Use DIC to get home route from config


<?php

namespace Fedeisas\LaravelMailCssInliner;

use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;

class CssInlinerPlugin implements \Swift_Events_SendListener
{
    /**
     * @param Swift_Events_SendEvent $evt
     */
    public function beforeSendPerformed(\Swift_Events_SendEvent $evt)
    {
        $message = $evt->getMessage();

        $converter = new CssToInlineStyles();
        $converter->setEncoding($message->getCharset());
        $converter->setUseInlineStylesBlock();
        $converter->setCleanup();

        if ($message->getContentType() === 'text/html' ||
            ($message->getContentType() === 'multipart/alternative' && $message->getBody())
        ) {
            $converter->setHTML($message->getBody());
            $message->setBody($converter->convert());
        }

        foreach ($message->getChildren() as $part) {
            if (strpos($part->getContentType(), 'text/html') === 0) {
                $converter->setHTML($part->getBody());
                $part->setBody($converter->convert());
            }
        }
    }

    /**
     * Do nothing
     *
     * @param Swift_Events_SendEvent $evt
     */
    public function sendPerformed(\Swift_Events_SendEvent $evt)
    {
        // Do Nothing
    }
}

<?php

namespace Fedeisas\LaravelMailCssInliner;

use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;

class CssInlinerPlugin implements \Swift_Events_SendListener
{
    /**
     * @param Swift_Events_SendEvent $evt
     */
    public function beforeSendPerformed(\Swift_Events_SendEvent $evt)
    {
        $message = $evt->getMessage();

        $converter = new CssToInlineStyles();
        $converter->setUseInlineStylesBlock();
        $converter->setStripOriginalStyleTags();

        $converter->setCleanup();

        if ($message->getContentType() === 'text/html' ||
            ($message->getContentType() === 'multipart/alternative' && $message->getBody())
        ) {
            $converter->setHTML($message->getBody());
            $message->setBody($converter->convert());
        }

        foreach ($message->getChildren() as $part) {
            if (strpos($part->getContentType(), 'text/html') === 0) {
                $converter->setHTML($part->getBody());
                $part->setBody($converter->convert());
            }
        }
    }

    /**
     * Do nothing
     *
     * @param Swift_Events_SendEvent $evt
     */
    public function sendPerformed(\Swift_Events_SendEvent $evt)
    {
        // Do Nothing
    }
}

Feature: Remove deprecated reference + always cleanup the <style> block


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Polyfill\Php54;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 *
 * @internal
 */
class Php54
{
    public static function hex2bin($data)
    {
        $len = strlen($data);

        if (null === $len) {
            return;
        }
        if ($len % 2) {
            trigger_error('hex2bin(): Hexadecimal input string must have an even length', E_USER_WARNING);

            return false;
        }

        $data = pack('H*', $data);

        if (false !== strpos($data, "\0")) {
            return false;
        }

        return $data;
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Polyfill\Php54;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 *
 * @internal
 */
final class Php54
{
    public static function hex2bin($data)
    {
        $len = strlen($data);

        if (null === $len) {
            return;
        }
        if ($len % 2) {
            trigger_error('hex2bin(): Hexadecimal input string must have an even length', E_USER_WARNING);

            return false;
        }

        $data = pack('H*', $data);

        if (false !== strpos($data, "\0")) {
            return false;
        }

        return $data;
    }
}

Mark internal classes final where possible


<?php
declare(strict_types=1);
use \ParagonIE\Halite\HiddenString;
use \ParagonIE\Halite\Password;
use \ParagonIE\Halite\KeyFactory;

// First, manage the keys
if (!\file_exists('01-secret-key.txt')) {
    $secretKey = KeyFactory::generateEncryptionKey();
    KeyFactory::save($secretKey, '01-secret-key.txt');
} else {
    $secretKey = KeyFactory::loadEncryptionKey('01-secret-key.txt');
}

$password = new HiddenString('correct horse battery staple');
$hash = Password::hash($password, $secretKey);

if (Password::verify($password, $hash, $secretKey)) {
    echo 'Access granted', "\n";
} else {
    echo 'Access DENIED!', "\n";
    exit(255);
}

<?php
declare(strict_types=1);
use \ParagonIE\Halite\HiddenString;
use \ParagonIE\Halite\Password;
use \ParagonIE\Halite\KeyFactory;

try {
    // First, manage the keys
    if (!\file_exists('01-secret-key.txt')) {
        $secretKey = KeyFactory::generateEncryptionKey();
        KeyFactory::save($secretKey, '01-secret-key.txt');
    } else {
        $secretKey = KeyFactory::loadEncryptionKey('01-secret-key.txt');
    }

    $password = new HiddenString('correct horse battery staple');
    $hash = Password::hash($password, $secretKey);

    if (Password::verify($password, $hash, $secretKey)) {
        echo 'Access granted', "\n";
    } else {
        echo 'Access DENIED!', "\n";
        exit(255);
    }
} catch (\Throwable $ex) {
    echo $ex->getMessage(), PHP_EOL;
    echo $ex->getTraceAsString(), PHP_EOL;
    exit(127);
}

Put try-catch on the example snippet.

Put try-catch on the example snippet.


<?php

system(sprintf('php %s/bin/vendors', escapeshellarg(__DIR__)));

require_once __DIR__.'/'.$_SERVER['SYMFONY'].'/Symfony/Component/ClassLoader/UniversalClassLoader.php';

use Symfony\Component\ClassLoader\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
    'Symfony' => __DIR__.'/'.$_SERVER['SYMFONY'],
    'Zend'    => __DIR__.'/'.$_SERVER['ZEND'],
    'Ivory'   => __DIR__.'/../../..'
));
$loader->register();

<?php

system(sprintf('php %s', escapeshellarg(__DIR__.'/bin/vendors')));

require_once __DIR__.'/'.$_SERVER['SYMFONY'].'/Symfony/Component/ClassLoader/UniversalClassLoader.php';

use Symfony\Component\ClassLoader\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
    'Symfony' => __DIR__.'/'.$_SERVER['SYMFONY'],
    'Zend'    => __DIR__.'/'.$_SERVER['ZEND']
));
$loader->register();

spl_autoload_register(function($class)
{
    if(strpos($class, 'Ivory\\LuceneSearchBundle\\') === 0)
    {
        $path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 2)).'.php';

        if(!stream_resolve_include_path($path))
            return false;

        require_once $path;
        return true;
    }
});

Update boostrap to allow running the test suite outside a dummy project


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Adds tagged request.param_converter services to converter.manager service
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class AddParamConverterPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (false === $container->hasDefinition('sensio_framework_extra.converter.manager')) {
            return;
        }

        $definition = $container->getDefinition('sensio_framework_extra.converter.manager');

        foreach ($container->findTaggedServiceIds('request.param_converter') as $id => $converters) {
            foreach ($converters as $converter) {
                $name     = isset($converter[0]['converter']) ? $converter[0]['converter'] : null;
                $priority = isset($converter[0]['priority']) ? $converter[0]['priority'] : 0;

                if ($priority == "false") {
                    $priority = null;
                }

                $definition->addMethodCall('add', array(new Reference($id), $priority, $name));
            }
        }
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Adds tagged request.param_converter services to converter.manager service
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class AddParamConverterPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (false === $container->hasDefinition('sensio_framework_extra.converter.manager')) {
            return;
        }

        $definition = $container->getDefinition('sensio_framework_extra.converter.manager');

        foreach ($container->findTaggedServiceIds('request.param_converter') as $id => $converters) {
            foreach ($converters as $converter) {
                $name     = isset($converter['converter']) ? $converter['converter'] : null;
                $priority = isset($converter['priority']) ? $converter['priority'] : 0;

                if ($priority == "false") {
                    $priority = null;
                }

                $definition->addMethodCall('add', array(new Reference($id), $priority, $name));
            }
        }
    }
}

Fix bug introduced with CompilerPass refactoring


<?php
namespace Colorium\Templating;

class Templater implements Contract\TemplaterInterface
{

    /** @var string */
    public $directory;

    /** @var string */
    public $suffix = '.php';

    /** @var array */
    public $vars = [];

    /** @var array */
    public $helpers = [];

    /**
     * Create new engine
     *
     * @param string $directory
     * @param string $suffix
     */
    public function __construct($directory = null, $suffix = '.php')
    {
        $this->directory = $directory;
        $this->suffix = $suffix;

        $this->helpers['render'] = [$this, 'render'];
        $this->helpers['e'] = function($value)
        {
            return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
        };
    }

    /**
     * Generate content from template compilation
     *
     * @param string $template
     * @param array $vars
     * @param array $blocks
     * @return string
     */
    public function render($template, array $vars = [], array $blocks = [])
    {
        $directory = rtrim($this->directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        $file = $directory . trim($template, DIRECTORY_SEPARATOR) . $this->suffix;
        $vars += $this->vars;

        $sandbox = new Template($this, $file, $blocks, $this->helpers);
        return $sandbox->compile($vars);
    }

}

<?php
namespace Colorium\Templating;

class Templater implements Contract\TemplaterInterface
{

    /** @var string */
    public $directory;

    /** @var string */
    public $suffix = '.php';

    /** @var array */
    public $vars = [];

    /** @var array */
    public $helpers = [];

    /**
     * Create new engine
     *
     * @param string $directory
     * @param string $suffix
     */
    public function __construct($directory = null, $suffix = '.php')
    {
        $this->directory = $directory;
        $this->suffix = $suffix;

        $this->helpers['render'] = [$this, 'render'];
        $this->helpers['e'] = function($value)
        {
            return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
        };
    }

    /**
     * Generate content from template compilation
     *
     * @param string $template
     * @param array $vars
     * @param array $blocks
     * @return string
     */
    public function render($template, array $vars = [], array $blocks = [])
    {
        $directory = rtrim($this->directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        $file = $directory . trim($template, DIRECTORY_SEPARATOR) . $this->suffix;

        $sandbox = new Template($this, $file, $blocks, $this->helpers);
        return $sandbox->compile();
    }

}

Revert "Fix merging engine/template vars"

This reverts commit 5e734479094e270bc3abb7d6ebf752fad95576b0.


<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class DashboardController extends Controller
{
    /**
     * @Route("/dashboard/compte", name="dashboard.account")
     * @Method({"GET","POST"})
     */
    public function accountAction(Request $request)
    {
        return $this->render('dashboard/account.html.twig');
    }

    /**
     * @Route("/dashboard/profil", name="dashboard.profil")
     * @Method({"GET"})
     */
    public function profilAction()
    {
        return $this->render('dashboard/profil.html.twig');
    }

    /**
     * @Route("/dashboard/notification", name="dashboard.notification")
     * @Method({"GET"})
     */
    public function notificationAction()
    {
        return $this->render('dashboard/notification.html.twig');
    }
}

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

/**
 * Class DashboardController
 * @package AppBundle\Controller
 * @Route("/dashboard")
 */
class DashboardController extends Controller
{
    /**
     * @Route("/compte", name="dashboard.account")
     * @Method({"GET","POST"})
     */
    public function accountAction(Request $request)
    {
        return $this->render('dashboard/account.html.twig');
    }

    /**
     * @Route("/profil", name="dashboard.profil")
     * @Method({"GET"})
     */
    public function profilAction()
    {
        return $this->render('dashboard/profil.html.twig');
    }

    /**
     * @Route("/notification", name="dashboard.notification")
     * @Method({"GET"})
     */
    public function notificationAction()
    {
        return $this->render('dashboard/notification.html.twig');
    }
}

Refactor (Dashbord): add prefix to dashbord route


<?php

	/*
	 * Inquire all SYSTEM queues from queuemanager PIGEON.
	 * MQWeb runs on localhost and is listening on port 8081.
	 */
	$url = "http://localhost:8081/api/queue/inquire/PIGEON/SYSTEM*";
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	$response = curl_exec($curl);
	$data = json_decode($response, true);
	print_r($data);

<?php
	/*
	 * This sample will show all SYSTEM queues from queuemanager PIGEON and
	 * prints the current queue depth if this property exists for the queue.
	 * MQWeb runs on localhost and is listening on port 8081.
	 */
	$url = "http://localhost:8081/api/queue/inquire/PIGEON/SYSTEM*";

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	if ( ($response = curl_exec($curl)) === false )	{
		$err = curl_error($curl);
		echo "An HTTP error occurred while getting queue information: $err\n";
	}
	else {
		$json = json_decode($response);
		if ( isset($json->error) ) {
			echo "An MQ error occurred while inquiring queues.\n";
			echo "Reason Code: {$json->error->reason->code} - {$json->error->reason->desc}\n";
		}
		else {
			if ( isset($json->queues) && count($json->queues) > 0 ) {
				foreach($json->queues as $queue)
				{
					echo $queue->QName->value;
					if ( isset($queue->CurrentQDepth) ) {
						echo ': ' . $queue->CurrentQDepth->value;
					}
					echo "\n";
				}
			}
			else
			{
				echo "No queues found\n";
			}
		}
	}

Make the example more realistic ...

Make the example more realistic ...


<?php

namespace Stfalcon\Bundle\SponsorBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Stfalcon\Bundle\EventBundle\Entity\Event as Event;

/**
 * SponsorRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SponsorRepository extends EntityRepository
{
    /**
     * Get all sponsors of event
     *
     * @param Event $event
     *
     * @return array List of sponsors
     */
    public function getSponsorsOfEvent(Event $event)
    {
        return $this->getEntityManager()
            ->createQuery('
                SELECT s
                FROM StfalconSponsorBundle:Sponsor s
                JOIN s.events e
                WHERE e.id = :eventId
                ORDER BY s.name ASC
            ')
            ->setParameter('eventId', $event->getId())
            ->getResult();
    }
}

<?php

namespace Stfalcon\Bundle\SponsorBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Stfalcon\Bundle\EventBundle\Entity\Event as Event;

/**
 * SponsorRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SponsorRepository extends EntityRepository
{
    /**
     * Get all sponsors of event
     *
     * @param Event $event
     *
     * @return array List of sponsors
     */
    public function getSponsorsOfEvent(Event $event)
    {
        return $this->getEntityManager()
            ->createQuery('
                SELECT s
                FROM StfalconSponsorBundle:Sponsor s
                JOIN s.events e
                WHERE e.id = :eventId
                ORDER BY s.sortOrder DESC, s.name ASC
            ')
            ->setParameter('eventId', $event->getId())
            ->getResult();
    }
}

Update sorting sponsors by orderSort

Update sorting sponsors by orderSort


<?php

include dirname(__DIR__) . "/vendor/autoload.php";

use Amp\Process\Process;
use function Amp\Promise\all;

function show_process_output(Process $process): \Generator {
    $stream = $process->getStdout();

    while (null !== $chunk = yield $stream->read()) {
        echo $chunk;
    }

    $code = yield $process->join();
    $pid = yield $process->getPid();

    echo "Process {$pid} exited with {$code}\n";
}

Amp\Loop::run(function () {
    $hosts = ['8.8.8.8', '8.8.4.4', 'google.com', 'stackoverflow.com', 'github.com'];

    $promises = [];

    foreach ($hosts as $host) {
        $process = new Process("ping {$host}");
        $process->start();
        $promises[] = new \Amp\Coroutine(show_process_output($process));
    }

    yield all($promises);
});

<?php

include dirname(__DIR__) . "/vendor/autoload.php";

use Amp\Process\Process;
use function Amp\Promise\all;

function show_process_output(Process $process): \Generator {
    $stream = $process->getStdout();

    while (null !== $chunk = yield $stream->read()) {
        echo $chunk;
    }

    $code = yield $process->join();
    $pid = yield $process->getPid();

    echo "Process {$pid} exited with {$code}\n";
}

Amp\Loop::run(function () {
    $hosts = ['8.8.8.8', '8.8.4.4', 'google.com', 'stackoverflow.com', 'github.com'];

    $promises = [];

    foreach ($hosts as $host) {
        $process = new Process("ping -c 5 {$host}");
        $process->start();
        $promises[] = new Amp\Coroutine(show_process_output($process));
    }

    yield all($promises);
});

Add ping count to example

Add ping count to example


<?php

namespace ZfcTwig\View;

use Zend\View\HelperPluginManager as ZendHelperPluginManager;

class HelperPluginManager extends ZendHelperPluginManager
{
    /**
     * Default set of helpers factories
     *
     * @var array
     */
    protected $factories = array(
        'flashmessenger' => 'Zend\View\Helper\Service\FlashMessengerFactory',
    );

    /**
     * Default set of helpers
     *
     * @var array
     */
    protected $invokableClasses = array(
        'declarevars'      => 'Zend\View\Helper\DeclareVars',
        'htmlflash'        => 'Zend\View\Helper\HtmlFlash',
        'htmllist'         => 'Zend\View\Helper\HtmlList',
        'htmlobject'       => 'Zend\View\Helper\HtmlObject',
        'htmlpage'         => 'Zend\View\Helper\HtmlPage',
        'htmlquicktime'    => 'Zend\View\Helper\HtmlQuicktime',
        'layout'           => 'Zend\View\Helper\Layout',
        'renderchildmodel' => 'Zend\View\Helper\RenderChildModel',
    );
}

<?php

namespace ZfcTwig\View;

use Zend\View\HelperPluginManager as ZendHelperPluginManager;

class HelperPluginManager extends ZendHelperPluginManager
{
    /**
     * HelperPluginManager constructor.
     * @param null $configOrContainerInstance
     * @param array $v3config
     */
    public function __construct($configOrContainerInstance = null, array $v3config = [])
    {
        $this->factories['flashmessenger'] = \Zend\View\Helper\Service\FlashMessengerFactory::class;
        parent::__construct($configOrContainerInstance, $v3config);
    }

    /**
     * Default set of helpers
     *
     * @var array
     */
    protected $invokableClasses = array(
        'declarevars'      => 'Zend\View\Helper\DeclareVars',
        'htmlflash'        => 'Zend\View\Helper\HtmlFlash',
        'htmllist'         => 'Zend\View\Helper\HtmlList',
        'htmlobject'       => 'Zend\View\Helper\HtmlObject',
        'htmlpage'         => 'Zend\View\Helper\HtmlPage',
        'htmlquicktime'    => 'Zend\View\Helper\HtmlQuicktime',
        'layout'           => 'Zend\View\Helper\Layout',
        'renderchildmodel' => 'Zend\View\Helper\RenderChildModel',
    );
}

Modify HelperPluginManage not to overwrite parent fields


		LARAVELERATOR

Generate

{{ url('/') }}

		LARAVELERATOR

Generate

Docs

{{ url('/') }}

Add Laravel docs to navbar.

Add Laravel docs to navbar.


<?php

require_once __DIR__ . '/../silex.phar';
require_once __DIR__ . '/../vendor/.composer/autoload.php';

<?php

require_once __DIR__ . '/../silex.phar';
require_once __DIR__ . '/../vendor/autoload.php';

Extend twig instead of instancing it

Extend twig instead of instancing it


<?php

require_once __DIR__ . '/../vendor/autoload.php';

Tester\Environment::setup();

define('TEMP_DIR', __DIR__ . '/tmp/' . getmypid());

@mkdir(TEMP_DIR);
@mkdir(TEMP_DIR . '/sessions');

$params = array('testingsqlitedb' => TEMP_DIR . '/db.sqlite');

$configurator = new Nette\Configurator;
$configurator->setDebugMode(false);
$configurator->setTempDirectory(TEMP_DIR);
$configurator->addParameters($params);
$configurator->createRobotLoader()
    ->addDirectory(__DIR__ . '/../app')
    ->register();

$configurator->addConfig(__DIR__ . '/../app/config/config.neon');
$configurator->addConfig(__DIR__ . '/config/db.neon');

$container = $configurator->createContainer();

$source = __DIR__ . '/db-image.sqlite';
$target = $params['testingsqlitedb'];
Nette\Utils\FileSystem::copy($source, $target);

return $container;

<?php

require_once __DIR__ . '/../vendor/autoload.php';

Tester\Environment::setup();

define('TEMP_DIR', __DIR__ . '/tmp/' . getmypid());

@mkdir(TEMP_DIR);
@mkdir(TEMP_DIR . '/sessions');

$params = array('testingsqlitedb' => TEMP_DIR . '/db.sqlite');

$configurator = new Nette\Configurator;
$configurator->setDebugMode(true);
$configurator->setTempDirectory(TEMP_DIR);
$configurator->addParameters($params);
$configurator->createRobotLoader()
    ->addDirectory(__DIR__ . '/../app')
    ->register();

$configurator->addConfig(__DIR__ . '/../app/config/config.neon');
$configurator->addConfig(__DIR__ . '/config/db.neon');

$container = $configurator->createContainer();

$source = __DIR__ . '/db-image.sqlite';
$target = $params['testingsqlitedb'];
Nette\Utils\FileSystem::copy($source, $target);

return $container;

Enable debug mode for tests

Enable debug mode for tests


<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Models\Unit as Unit;

class UnitTableSeeder extends Seeder {

    /**
     * Run the database seeds.
     * Use php artisan db:seed to run the seed files.
     *
     * @return void
     */
    public function run()
    {
        Unit::create([
            'description' => 'root',
            'comments' => 'Root unit',
        ]);

	DB::table('units_users')->delete();

	DB::table('units_users')->insert(array(
		'user_id' => '1',
		'unit_id' => '1',
	));
    }

}

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Models\Unit as Unit;
use App\Models\User as User;

class UnitTableSeeder extends Seeder {

    /**
     * Run the database seeds.
     * Use php artisan db:seed to run the seed files.
     *
     * @return void
     */
    public function run()
    {
        $unit = Unit::create([
            'description' => 'root',
            'comments' => 'Root unit',
        ]);

        $unit->users()->attach(User::first()->id);
    }

}

Use attach method for units_users seed file.


<?php

namespace Services;

class QrCodeWriter implements TicketPartWriterInterface {
    private $writer;
    private $outputDirectoryPath;

    public function __construct(\BaconQrCode\Writer $writer, $outputDirectoryPath) {
        $this->writer = $writer;
        $this->outputDirectoryPath = $outputDirectoryPath;
    }

    public function write(ExpandedReservationInterface $reservation, array $partFilePaths, $printOrderId, $locale) {
        $filePath = $this->outputDirectoryPath . '/' . $reservation->unique_id . '_qr.png';
        $this->writer->writeFile($reservation->unique_id, $filePath);

        $partFilePaths['qr'] = $filePath;
        return $partFilePaths;
    }
}

<?php

namespace Services;

class QrCodeWriter implements TicketPartWriterInterface {
    private $writer;
    private $outputDirectoryPath;

    public function __construct(\BaconQrCode\Writer $writer, $outputDirectoryPath) {
        $this->writer = $writer;
        $this->outputDirectoryPath = $outputDirectoryPath;
    }

    public function write(ExpandedReservationInterface $reservation, array $partFilePaths, $printOrderId, $locale) {
        $dataUrl = 'data:image/png;base64,' . base64_encode($this->writer->writeString($reservation->unique_id));

        $partFilePaths['qr'] = $dataUrl;
        return $partFilePaths;
    }
}

Embed QR code as Data URL

Embed QR code as Data URL


@include('rapyd::toolbar', array('label'=>$label, 'buttons_right'=>$buttons['TR']))

buildAttributes() !!}>

     @foreach ($dg->columns as $column)
            buildAttributes() !!}>
            @if ($column->orderby)
                @if ($dg->onOrderby($column->orderby_field, 'asc'))

                @else
                    orderbyLink($column->orderby_field,'asc') !!}">

                @endif
                @if ($dg->onOrderby($column->orderby_field, 'desc'))

                @else
                    orderbyLink($column->orderby_field,'desc') !!}">

                @endif
             @endif
                {!! $column->label !!}

     @endforeach

    @foreach ($dg->rows as $row)

buildAttributes() !!}>
            @foreach ($row->cells as $cell)
            buildAttributes() !!}>{!! $cell->value !!}
            @endforeach

    @endforeach

@if ($dg->havePagination())

    {!! $dg->links() !!}

@endif

@include('rapyd::toolbar', array('label'=>$label, 'buttons_right'=>$buttons['TR']))

buildAttributes() !!}>

     @foreach ($dg->columns as $column)
            buildAttributes() !!}>
            @if ($column->orderby)
                @if ($dg->onOrderby($column->orderby_field, 'asc'))

                @else
                    orderbyLink($column->orderby_field,'asc') }}">

                @endif
                @if ($dg->onOrderby($column->orderby_field, 'desc'))

                @else
                    orderbyLink($column->orderby_field,'desc') }}">

                @endif
             @endif
                {!! $column->label !!}

     @endforeach

    @foreach ($dg->rows as $row)

buildAttributes() !!}>
            @foreach ($row->cells as $cell)
            buildAttributes() !!}>{!! $cell->value !!}
            @endforeach

    @endforeach

@if ($dg->havePagination())

    {!! $dg->links() !!}

@endif

Update so order by links are escaped

Update so order by links are escaped


<?php
namespace Kuartet\BI\ExchangeRate;

use \GuzzleHttp\Client;
use \GuzzleHttp\Message\Response;
use \GuzzleHttp\Stream\Stream;
use \GuzzleHttp\Subscriber\Mock;
use \PHPUnit_Framework_TestCase;

class ExchangeRateFinderTest extends PHPUnit_Framework_TestCase
{
    public function testFindAll()
    {
        $responseBody = file_get_contents(__DIR__.'/resources/finder_findAll.html');

        $mock = new Mock([
            new Response(200, Stream::factory($responseBody))
        ]);

        $client = new Client();
        $client->getEmitter()->attach($mock);

        $finder = new ExchangeRateFinder($client);
        $exchangeRates = $finder->findAll();

        $this->assertNotInternalType('array', $exchangeRates);
        $this->assertContainsOnlyInstancesOf(ExchangeRateInterface::class, $exchangeRates);
        $this->assertCount(22, $exchangeRates);
    }
}

<?php
namespace Kuartet\BI\ExchangeRate;

use \GuzzleHttp\Client;
use \GuzzleHttp\Message\Response;
use \GuzzleHttp\Stream\Stream;
use \GuzzleHttp\Subscriber\Mock;
use \PHPUnit_Framework_TestCase;

class ExchangeRateFinderTest extends PHPUnit_Framework_TestCase
{
    public function testFindAll()
    {
        $responseBody = file_get_contents(__DIR__.'/resources/finder_findAll.html');

        $mock = new Mock([
            new Response(200, [], Stream::factory($responseBody))
        ]);

        $client = new Client();
        $client->getEmitter()->attach($mock);

        $finder = new ExchangeRateFinder($client);
        $exchangeRates = $finder->findAll();

        $this->assertInternalType('array', $exchangeRates);
        $this->assertContainsOnlyInstancesOf(ExchangeRateInterface::class, $exchangeRates);
        $this->assertCount(22, $exchangeRates);
    }
}

Add empty headers, change NotInternalType to InternalType


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

Use phpcs as a library.

Use phpcs as a library.


<?php

// Turn on error reporting
error_reporting(E_ALL);

// Require the class
include_once '../gears/Gears.php';

$tplPath = dirname(__FILE__) .'/templates/';

// Set up engine and display
$temp = new Gears($tplPath);
$temp->bind(array(
	'className'		=> 'Gears - Template Engine',
	'version'		=> '2.0',
	'extraInfo'		=> 'Gears is a play on words for: Engine + Gears + Structure.',
	'description'	=> 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.'
));
$temp->setLayout('layout');
echo $temp->display('index');

<?php

// Turn on error reporting
error_reporting(E_ALL);

function debug($var) {
	echo '<pre>'. print_r($var, true) .'</pre>';
}

// Require the class
include_once '../gears/Gears.php';

$tplPath = dirname(__FILE__) .'/templates';

// Set up engine and display
$temp = new Gears($tplPath);
//$temp->setLayout('layouts/default');
$temp->bind(array(
	'className'		=> 'Gears - Template Engine',
	'version'		=> '2.0',
	'extraInfo'		=> 'Gears is a play on words for: Engine + Gears + Structure.',
	'description'	=> 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.',
	1 => 'number check',
	'asd as8dm  0sadmsd asda)*#&$' => 'as'
));

echo $temp->display('index');

debug($temp);

Allow rendering without a layout.

Allow rendering without a layout.


<?php

namespace ApiTest\Controller;

use Zend\Http\Request;

class TableControllerTest extends AbstractController
{
    public function testGetValidChartStructure()
    {
        $this->dispatch('/api/chart', Request::METHOD_GET);

        $this->assertResponseStatusCode(200);

        $data = $this->getJsonResponse();
        $this->assertArrayHasKey('chart', $data);
        $this->assertArrayHasKey('series', $data);
    }
}

<?php

namespace ApiTest\Controller;

use Zend\Http\Request;

class ChartControllerTest extends AbstractController
{
    public function testGetValidChartStructure()
    {
        $this->dispatch('/api/chart', Request::METHOD_GET);

        $this->assertResponseStatusCode(200);

        $data = $this->getJsonResponse();
        $this->assertArrayHasKey('chart', $data);
        $this->assertArrayHasKey('series', $data);
    }
}

Resolve class name conflict in tests

Resolve class name conflict in tests


<?php

namespace PHPSpec2;

use Symfony\Component\Finder\Finder;

use SplFileInfo;
use PHPSpec2\Loader\LoaderInterface;

class Locator
{
    private $loader;

    public function __construct(LoaderInterface $loader)
    {
        $this->loader = $loader;
    }

    public function getSpecifications($path)
    {
        $specs = array();
        if (is_dir($path)) {
            $files = Finder::create()->files()->name('*.php')->in($path);
            foreach ($files as $file) {
                if ($fromFile = $this->getSpecificationsFromFile($file)) {
                    $specs = array_merge($specs, $fromFile);
                }
            }
        } elseif (is_file($path)) {
            $file = new SplFileInfo(realpath($path));
            if ($fromFile = $this->getSpecificationsFromFile($file)) {
                $specs = array_merge($specs, $fromFile);
            }
        }

        return $specs;
    }

    public function getSpecificationsFromFile(SplFileInfo $file)
    {
        return $this->loader->loadFromFile($file->getPathname());
    }
}

<?php

namespace PHPSpec2;

use Symfony\Component\Finder\Finder;

use SplFileInfo;
use PHPSpec2\Loader\LoaderInterface;

class Locator
{
    private $loader;

    public function __construct(LoaderInterface $loader)
    {
        $this->loader = $loader;
    }

    public function getSpecifications($path)
    {
        $line = null;
        if (preg_match('/^(.*)\:(\d+)$/', $path, $matches)) {
            list($_, $path, $line) = $matches;
        }

        $specs = array();
        if (is_dir($path)) {
            $files = Finder::create()->files()->name('*.php')->in($path);
            foreach ($files as $file) {
                if ($fromFile = $this->getSpecificationsFromFile($file, $line)) {
                    $specs = array_merge($specs, $fromFile);
                }
            }
        } elseif (is_file($path)) {
            $file = new SplFileInfo(realpath($path));
            if ($fromFile = $this->getSpecificationsFromFile($file, $line)) {
                $specs = array_merge($specs, $fromFile);
            }
        }

        return $specs;
    }

    public function getSpecificationsFromFile(SplFileInfo $file, $line = null)
    {
        return $this->loader->loadFromFile($file->getPathname(), $line);
    }
}

Add support to run example by line number


<?php
/**
 *
 * PHP.Gt (http://php.gt)
 * @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
 * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
 */
namespace Gt\Page;

use \Michelf\Markdown;

class Transformer {

const TYPE_MARKDOWN	= "md";
const TYPE_HAML		= "haml";

/**
 * @param string $source Plain-text source content
 * @param string $type Type of source content, must be one of this class's
 * type constants
 *
 * @return string HTML source transformed from provided source content
 */
public static function toHtml($source, $type) {
	$type = strtolower($type);

	switch($type) {
	case self::TYPE_MARKDOWN:
		return Markdown::defaultTransform($source);
		break;

	default:
		throw new SourceNotValidException();
		break;
	}
}

}#

<?php
/**
 *
 * PHP.Gt (http://php.gt)
 * @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
 * @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
 */
namespace Gt\Page;

use \Michelf\Markdown;

class Transformer {

const TYPE_MARKDOWN	= "md";
const TYPE_HAML		= "haml";

/**
 * @param string $source Plain-text source content
 * @param string $type Type of source content, must be one of this class's
 * type constants
 *
 * @return string HTML source transformed from provided source content
 */
public static function toHtml($source, $type) {
	$type = strtolower($type);

	switch($type) {
	case self::TYPE_MARKDOWN:
		return Markdown::defaultTransform($source);
	}

	throw new SourceNotValidException();
}

}#

Remove dead code after returns

Remove dead code after returns


<?php

namespace base;

class Controller{

	private $_views = array();
	private $_res = null;
	private $_req = null;
	public $currentPath = null;

	protected function getRequest()
	{
		return Request::getInstance();
	}

	protected function getResponse()
	{
		if(empty($this->_res)){
			$this->_res = new Response();
		}
		return $this->_res;
	}

	protected function getView($tplName, $isNew = false)
	{
		if(!$isNew && !empty($this->_views[$tplName])) {
			return $this->_views[$tplName];
		} else {
			if(empty($this->currentPath) || empty($this->className)) {
				$class_info = new \ReflectionClass($this);
				$this->currentPath = dirname($class_info->getFileName());
				$this->className = $class_info->getShortName();
			}
			$ds = DIRECTORY_SEPARATOR;
			$tplName = $this->currentPath.$ds.$this->className.'.Views'.$ds."{$tplName}.php";
			$this->_views[$tplName] = new View($tplName);
			return $this->_views[$tplName];
		}
	}

	public function getProfile()
	{
		return "Profile";
	}
}

<?php

namespace base;

class Controller{

	private $_views = array();
	private $_res = null;
	private $_req = null;
	public $currentPath = null;

	protected function getRequest()
	{
		return Request::getInstance();
	}

	protected function getResponse()
	{
		if(empty($this->_res)){
			$this->_res = new Response();
		}
		return $this->_res;
	}

	protected function getView($tplName, $isNew = false)
	{
		if(!$isNew && !empty($this->_views[$tplName])) {
			return $this->_views[$tplName];
		} else {
			if(empty($this->currentPath) || empty($this->className)) {
				$class_info = new \ReflectionClass($this);
				$this->currentPath = dirname($class_info->getFileName());
				$this->className = $class_info->getShortName();
			}
			$ds = DIRECTORY_SEPARATOR;
			$tplName = $this->currentPath.$ds.$this->className.'.Views'.$ds."{$tplName}.php";
			$this->_views[$tplName] = new View($tplName);
			return $this->_views[$tplName];
		}
	}

}

Remove public getProfile method to base controller


$('.form-group-url').removeClass('has-error')
    .find('.alert')
    .fadeOut();
$('#input-url').val('{{ $shortUrl }}').select();

{{--$('#btn-copy-url').focus();--}}
{{--$('#input-original-url').val('').focus();--}}

Remove alert box after shorten link

Remove alert box after shorten link


<?php

namespace Tests\AppBundle\Native;

class InsertTest extends ConnectionTestCase
{
    public function testIgnore()
    {
        $connection = $this->getConnection();

        try {
            $connection->exec('
                CREATE TABLE `users` (
                  `id` INT PRIMARY KEY AUTO_INCREMENT,
                  `name` VARCHAR(255),
                  UNIQUE KEY (`name`)
                );
            ');

            $response = $connection->executeUpdate("
                INSERT INTO `users` (`name`)
                VALUE ('Alex');
            ");
            $this->assertSame(1, $response);

            $this->assertSame('1', $connection->lastInsertId());

            $response = $connection->executeUpdate("
                INSERT INTO `users` (`name`)
                VALUE ('Reen');
            ");
            $this->assertSame(1, $response);

            $this->assertSame('2', $connection->lastInsertId());

            $response = $connection->executeUpdate("
                INSERT IGNORE INTO `users` (`name`)
                VALUE ('Alex');
            ");

            $this->assertSame(0, $response);
            $this->assertSame('0', $connection->lastInsertId());

        } finally {
            $this->clear(['users']);
        }
    }
}

<?php

namespace Tests\AppBundle\Native;

class InsertTest extends ConnectionTestCase
{
    public function testIgnore()
    {
        $connection = $this->getConnection();

        try {
            $connection->exec('
                CREATE TABLE `users` (
                  `id` INT PRIMARY KEY AUTO_INCREMENT,
                  `name` VARCHAR(255),
                  UNIQUE KEY (`name`)
                );
            ');

            $response = $connection->executeUpdate("
                INSERT INTO `users` (`name`)
                VALUE ('Alex');
            ");
            $this->assertSame(1, $response);

            $this->assertSame('1', $connection->lastInsertId());

            $response = $connection->executeUpdate("
                INSERT INTO `users` (`name`)
                VALUE ('Reen');
            ");
            $this->assertSame(1, $response);

            $this->assertSame('2', $connection->lastInsertId());

            $response = $connection->executeUpdate("
                INSERT IGNORE INTO `users` (`name`)
                VALUE ('Sky');
            ");
            $this->assertSame(1, $response);

            $this->assertSame('3', $connection->lastInsertId());

            $response = $connection->executeUpdate("
                INSERT IGNORE INTO `users` (`name`)
                VALUE ('Alex');
            ");

            $this->assertSame(0, $response);
            $this->assertSame('0', $connection->lastInsertId());

        } finally {
            $this->clear(['users']);
        }
    }
}

INSERT IGONRE `last insert id` after success insert


<?php

class PingTrackingRedis extends InterProcessRedis {
    const TTL = 3600;
    private $key;

    public function __construct() {
        parent::__construct();
        $this->key = "ZP-PING|" . Request::GetDeviceID() . '|' . Request::GetAuthUser() . '|' . Request::GetAuthDomain();
    }

    /**
     * Checks if there are newer ping requests for the same device & user so
     * the current process could be terminated
     *
     * @access public
     * @return boolean true if the current process is obsolete
     */
    public function DoForcePingTimeout() {
        while (true) {
            self::$redis->watch($this->key);
            $savedtime = self::$redis->get($this->key);
            if ($savedtime === false || $savedtime < $_SERVER['REQUEST_TIME']) {
                $res = self::$redis->multi()->setex($this->key,self::TTL, $_SERVER['REQUEST_TIME'])->exec();
                if ($res === false) {
                    ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout(): set just failed, retrying");
                    continue;
                }
                else {
                    return false;
                }
            }

            if ($savedtime === $_SERVER['REQUEST_TIME']) {
                self::$redis->unwatch();

                return false;
            }
            if ($savedtime > $_SERVER['REQUEST_TIME']) {
                self::$redis->unwatch();

                return true;
            }
        }
    }
}

<?php

class PingTrackingRedis extends InterProcessRedis {
    const TTL = 3600;
    private $key;

    public function __construct() {
        parent::__construct();
        $this->key = "ZP-PING|" . Request::GetDeviceID() . '|' . Request::GetAuthUser() . '|' . Request::GetAuthDomain();
	$this->DoForcePingTimeout();
    }

    /**
     * Checks if there are newer ping requests for the same device & user so
     * the current process could be terminated
     *
     * @access public
     * @return boolean true if the current process is obsolete
     */
    public function DoForcePingTimeout() {
        while (true) {
            self::$redis->watch($this->key);
            $savedtime = self::$redis->get($this->key);
            if ($savedtime === false || $savedtime < $_SERVER['REQUEST_TIME']) {
                $res = self::$redis->multi()->setex($this->key,self::TTL, $_SERVER['REQUEST_TIME'])->exec();
                if ($res === false) {
                    ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout(): set just failed, retrying");
                    ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout() key: ".$this->key);
                    ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout() reqtime: ".$_SERVER['REQUEST_TIME']);
                    ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout() last: ".self::$redis->getLastError());
                    continue;
                }
                else {
                    return false;
                }
            }

            if ($savedtime === $_SERVER['REQUEST_TIME']) {
                self::$redis->unwatch();

                return false;
            }
            if ($savedtime > $_SERVER['REQUEST_TIME']) {
                self::$redis->unwatch();

                return true;
            }
        }
    }
}

chore(ipc): Add extra debug and read DoForcePingTimeout in the
constructor

Signed-off-by: Francisco Miguel Biete <f1d806242fc0bb697f053bcdfc66a36bc885611e@gmail.com>
<fbiete@gmail.com>


<?php

defined('C5_EXECUTE') or die('Access Denied.');
$dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */
echo $this->controller->getOpenTag();
echo $this->controller->getTitle();
try {
    $format = (strlen($this->controller->dateFormat) ? $this->controller->dateFormat : "m/d/y");
    echo $dh->formatCustom($format, $this->controller->getContent());
} catch (\Exception $e) {
    echo $this->controller->getContent();
}
echo $this->controller->getCloseTag();

<?php

defined('C5_EXECUTE') or die('Access Denied.');
$dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */
echo $this->controller->getOpenTag();
echo $this->controller->getTitle();
try {
    if ($this->controller->dateFormat) {
        echo $dh->formatCustom($format, $this->controller->getContent());
    } else {
        echo $dh->formatDateTime($this->controller->getContent());
    }
} catch (Exception $e) {
    echo $this->controller->getContent();
}
echo $this->controller->getCloseTag();

Use standard date/time format if none is specified in page_attribute_display block


<?php

require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/../src/Stencil/stencil.php';

use Stencil\Stencil as Stencil;

class StencilTest extends PHPUnit_Framework_TestCase
{
  public function testVersion()
  {
    $stencil = new Stencil(__DIR__.'/../config.json');

    $this->assertEquals($stencil->version(), VERSION);
  }
}

<?php

require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/../src/Stencil/stencil.php';

use Stencil\Stencil as Stencil;

class StencilTest extends PHPUnit_Framework_TestCase
{
  public function testVersion()
  {
    $stencil = new Stencil(__DIR__.'/testConfig.json');

    $this->assertEquals($stencil->version(), VERSION);
  }
}

Update test for testing config file

Update test for testing config file


<?php

namespace WebthinkSniffer\Helpers;

class Inflector
{
    /**
     * Returns the function name in camelCaps
     *
     * @param string $function The function name
     * @return string
     */
    public static function camelCaps($function)
    {
        return str_replace(' ', '', ucwords(self::humanize($function)));
    }

    /**
     * @param $string
     * @return string|false
     */
    public static function humanize($string)
    {
        return str_replace('_', ' ', $string);
    }
}

<?php

namespace WebthinkSniffer\Helpers;

/**
 * Class Inflector
 *
 * @internal
 */
class Inflector
{
    /**
     * Returns the function name in camelCaps
     *
     * @param string $function The function name
     * @return string
     */
    public static function camelCaps($function)
    {
        return str_replace(' ', '', ucwords(self::humanize($function)));
    }

    /**
     * @param $string
     * @return string|false
     */
    public static function humanize($string)
    {
        return str_replace('_', ' ', $string);
    }
}

Fix docblock of a class

Fix docblock of a class


<?php

namespace League\HTMLToMarkdown\Converter;

use League\HTMLToMarkdown\Configuration;
use League\HTMLToMarkdown\ConfigurationAwareInterface;
use League\HTMLToMarkdown\ElementInterface;

class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface
{
    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @param Configuration $config
     */
    public function setConfig(Configuration $config)
    {
        $this->config = $config;
    }

    /**
     * @param ElementInterface $element
     *
     * @return string
     */
    public function convert(ElementInterface $element)
    {
        $tag = $element->getTagName();
        $value = $element->getValue();

        if ($tag === 'i' || $tag === 'em') {
            $style = $this->config->getOption('italic_style');
        } else {
            $style = $this->config->getOption('bold_style');
        }

        $prefix = ltrim($value) !== $value ? ' ' : '';
        $suffix = rtrim($value) !== $value ? ' ' : '';

        return $prefix . $style . trim($value) . $style . $suffix;
    }

    /**
     * @return string[]
     */
    public function getSupportedTags()
    {
        return array('em', 'i', 'strong', 'b');
    }
}

<?php

namespace League\HTMLToMarkdown\Converter;

use League\HTMLToMarkdown\Configuration;
use League\HTMLToMarkdown\ConfigurationAwareInterface;
use League\HTMLToMarkdown\ElementInterface;

class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface
{
    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @param Configuration $config
     */
    public function setConfig(Configuration $config)
    {
        $this->config = $config;
    }

    /**
     * @param ElementInterface $element
     *
     * @return string
     */
    public function convert(ElementInterface $element)
    {
        $tag = $element->getTagName();
        $value = $element->getValue();

        if (!trim($value)) {
            return '';
        }

        if ($tag === 'i' || $tag === 'em') {
            $style = $this->config->getOption('italic_style');
        } else {
            $style = $this->config->getOption('bold_style');
        }

        $prefix = ltrim($value) !== $value ? ' ' : '';
        $suffix = rtrim($value) !== $value ? ' ' : '';

        return $prefix . $style . trim($value) . $style . $suffix;
    }

    /**
     * @return string[]
     */
    public function getSupportedTags()
    {
        return array('em', 'i', 'strong', 'b');
    }
}

Fix edge case for tags containing only whitespace.

As per previous comment, a tag just containing spaces (or non-breaking spaces) would end up as ** or **** which would produce incorrect rendering.


<?php

/**
 * Hoa Framework
 *
 *
 * @license
 *
 * GNU General Public License
 *
 * This file is part of Hoa Open Accessibility.
 * Copyright (c) 2007, 2008 Ivan ENDERLIN. All rights reserved.
 *
 * HOA Open Accessibility is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * HOA Open Accessibility is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HOA Open Accessibility; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *
 * @category    Framework
 * @package     Hoa_Test
 * @subpackage  Hoa_Test_Urg
 *
 */

/**
 * Hoa_Framework
 */
require_once 'Framework.php';

/**
 * Hoa_Test_Urg_Exception
 */
import('Test.Urg.Exception');

/**
 * Class Hoa_Test_Urg.
 *
 * .
 *
 * @author      Ivan ENDERLIN <ivan.enderlin@hoa-project.net>
 * @copyright   Copyright (c) 2007, 2008 Ivan ENDERLIN.
 * @license     http://gnu.org/licenses/gpl.txt GNU GPL
 * @since       PHP 5
 * @version     0.1
 * @package     Hoa_Test
 * @subpackage  Hoa_Test_Urg
 */

class Hoa_Test_Urg {

    /**
     * Combine a discrete uniform distribution (based on a Mersenne Twister for
     * pseudo-random algorithm).
     *
     * @access  public
     * @param   int     $lower    Lower bound.
     * @param   int     $upper    Upper bound.
     * @return  int
     */
    public static function Ud ( $lower = null, $upper = null ) {

        if(null === $lower)
            $lower = ~PHP_INT_MAX;

        if(null === $upper)
            $upper =  PHP_INT_MAX;

        return mt_rand($lower, $upper);
    }

    /**
     * Combine a continuous uniform distribution (based on a linear
     * congruential generator).
     *
     * @access  public
     * @param   float   $lower    Lower bound.
     * @param   float   $upper    Upper bound.
     * @return  float
     */
    public static function Uc ( $lower = null, $upper = null ) {

        return $lower + lcg_value() * ($upper - $lower);
    }
}

Add Ud() and Uc() static method, respectively for discrete and continous uniform distribution combinator.


<?php
namespace SmoothPhp\CommandBus;

use Rhumsaa\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;

/**
 * Class Command
 * @package SmoothPhp\CommandBus
 * @author Simon Bennett <simon.bennett@smoothphp.com>
 */
abstract class BaseCommand implements Command
{
    /**
     * @var string
     */
    public $commandId;

    /**
     * Give the command a Uuid, Used to logging and auditing
     */
    public function __construct()
    {
        $this->commandId = (string)Uuid::uuid4();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return get_class($this) . ':' . $this->commandId;
    }
}

<?php
namespace SmoothPhp\CommandBus;

use Ramsey\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;

/**
 * Class Command
 * @package SmoothPhp\CommandBus
 * @author Simon Bennett <simon.bennett@smoothphp.com>
 */
abstract class BaseCommand implements Command
{
    /**
     * @var string
     */
    public $commandId;

    /**
     * Give the command a Uuid, Used to logging and auditing
     */
    public function __construct()
    {
        $this->commandId = (string)Uuid::uuid4();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return get_class($this) . ':' . $this->commandId;
    }
}

Swap to the correct Uuid library

Swap to the correct Uuid library


<?php

namespace Realm\Command;

use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
use Realm\Loader\XmlRealmLoader;
use Realm\Model\Project;
use RuntimeException;

class RealmLoadCommand extends Command
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->ignoreValidationErrors();

        $this
            ->setName('realm:load')
            ->setDescription('Load realm, and output contents')
            ->addOption(
                'filename',
                'f',
                InputOption::VALUE_REQUIRED,
                null
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $filename = $input->getOption('filename');
        if (!$filename) {
            $filename = getcwd() . '/realm.xml';
        }
        $output->writeLn("Loading realm file: " . $filename);
        $realm = new Project();
        $realmLoader = new XmlRealmLoader();
        $realm = $realmLoader->loadFile($filename, $realm);
        var_dump($realm);
    }
}

<?php

namespace Realm\Command;

use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
use Realm\Loader\XmlRealmLoader;
use Realm\Model\Project;
use RuntimeException;

class RealmLoadCommand extends Command
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->ignoreValidationErrors();

        $this
            ->setName('realm:load')
            ->setDescription('Load realm, and output contents')
            ->addOption(
                'realm',
                'r',
                InputOption::VALUE_REQUIRED,
                null
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $realmId = $input->getOption('realm');
        if (!$realmId) {
            throw new RuntimeException("Please pass a realm to load");
        }
        $output->writeLn("Loading realm: " . $realmId);
        $realmLoader = new XmlRealmLoader();
        $realm = $realmLoader->load($realmId);
        var_dump($realm);
    }
}

Refactor realm:load to load by realmId vs filename


<?php
/**
 * SiteFilter.php
 *
 * Created By: jonathan
 * Date: 28/09/2017
 * Time: 13:33
 */

namespace Stati\Liquid\Filter;

class SiteFilter
{
    /**
     * Escapes an xml string
     *
     * @param string $input
     *
     * @return string
     */
    public static function xml_escape($input)
    {
        return htmlentities($input);
    }

    /**
     * Counts the number of words in a string
     *
     * @param string $input
     *
     * @return string
     */

    public static function number_of_words($input)
    {
        return str_word_count(strip_tags($input), 0);
    }

    public static function tojson($input)
    {
        return json_encode($input);
    }

    public static function jsonify($input)
    {
        return json_encode($input);
    }
}

<?php
/**
 * SiteFilter.php
 *
 * Created By: jonathan
 * Date: 28/09/2017
 * Time: 13:33
 */

namespace Stati\Liquid\Filter;

class SiteFilter
{
    /**
     * Escapes an xml string
     *
     * @param string $input
     *
     * @return string
     */
    public static function xml_escape($input)
    {
        return htmlentities($input);
    }

    /**
     * Counts the number of words in a string
     *
     * @param string $input
     *
     * @return string
     */

    public static function number_of_words($input)
    {
        return str_word_count(strip_tags($input), 0);
    }

    public static function tojson($input)
    {
        return json_encode($input);
    }

    public static function jsonify($input)
    {
        return json_encode($input);
    }

    public function array_to_sentence_string($input) {
        if (is_array($input)) {
            return implode(' ', $input);
        }
        return $input;
    }
}

Add array to sentence filter

Add array to sentence filter


<?php

namespace Screamz\SecureDownloadBundle\Core\Classes\Response;

use Symfony\Component\HttpFoundation\Response;

/**
 * Class BlobResponse
 *
 * This response should be used when you need to return a blob (Like base64 encoded image).
 *
 * @author Andréas HANSS <ahanss@kaliop.com>
 */
class BlobResponse extends Response
{
    /**
     * BlobResponse constructor.
     *
     * @param string $documentPath The path of the document to encode as B64
     * @param int    $status
     * @param array  $headers
     *
     */
    public function __construct($documentPath, $status = self::HTTP_OK, array $headers = array())
    {
        $content = base64_encode(file_get_contents($documentPath));
        $finfoMineType = finfo_open(FILEINFO_MIME_TYPE);
        $headers['Content-Type'] = finfo_file($finfoMineType, $documentPath);
        parent::__construct($content, $status, $headers);
    }
}

<?php

namespace Screamz\SecureDownloadBundle\Core\Classes\Response;

use Symfony\Component\HttpFoundation\Response;

/**
 * Class BlobResponse
 *
 * This response should be used when you need to return a blob (Like base64 encoded image).
 *
 * @author Andréas HANSS <ahanss@kaliop.com>
 */
class BlobResponse extends Response
{
    /**
     * BlobResponse constructor.
     *
     * @param string $documentPath The path of the document to encode as B64
     * @param int    $status
     * @param array  $headers
     *
     */
    public function __construct($documentPath, $status = 200, array $headers = array())
    {
        $content = base64_encode(file_get_contents($documentPath));
        $finfoMineType = finfo_open(FILEINFO_MIME_TYPE);
        $headers['Content-Type'] = finfo_file($finfoMineType, $documentPath);
        parent::__construct($content, $status, $headers);
    }
}

Add code http 200 as plain integer for compatibility


<?php

/**
 * Elastica searchable interface
 *
 * @category Xodoa
 * @package Elastica
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 */
interface Elastica_Searchable
{
	/**
	 * Searches results for a query
	 *
	 * TODO: Improve sample code
	 * {
	 *	 "from" : 0,
	 *	 "size" : 10,
	 *	 "sort" : {
	 *		  "postDate" : {"reverse" : true},
	 *		  "user" : { },
	 *		  "_score" : { }
	 *	  },
	 *	  "query" : {
	 *		  "term" : { "user" : "kimchy" }
	 *	  }
	 * }
	 *
	 * @param array|Elastica_Query Array with all query data inside or a Elastica_Query object
	 * @return Elastica_ResultSet ResultSet with all results inside
	 */
	function search($query);

	/**
	 * Counts results for a query
	 *
	 * @param array|Elastica_Query Array with all query data inside or a Elastica_Query object
	 * @return int number of documents matching the query
	 */
	function count($query);
}

<?php

/**
 * Elastica searchable interface
 *
 * @category Xodoa
 * @package Elastica
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 */
interface Elastica_Searchable
{
	/**
	 * Searches results for a query
	 *
	 * TODO: Improve sample code
	 * {
	 *	 "from" : 0,
	 *	 "size" : 10,
	 *	 "sort" : {
	 *		  "postDate" : {"reverse" : true},
	 *		  "user" : { },
	 *		  "_score" : { }
	 *	  },
	 *	  "query" : {
	 *		  "term" : { "user" : "kimchy" }
	 *	  }
	 * }
	 *
	 * @param array|Elastica_Query Array with all query data inside or a Elastica_Query object
	 * @return Elastica_ResultSet ResultSet with all results inside
	 */
	public function search($query);

	/**
	 * Counts results for a query
	 *
	 * @param array|Elastica_Query Array with all query data inside or a Elastica_Query object
	 * @return int number of documents matching the query
	 */
	public function count($query);
}

Add public keywords in interface to match ZF conventions


<?php
	$api_path = "https://api.titledb.com/";

	function http_req($data = array("action" => "list"), $endpoint = "v0/") {
		$curl = curl_init($GLOBALS["api_path"].$endpoint);
		$headers = array();
		$headers[] = "Homebr3w/1.0.0 Homebr3w-Proxy/1.0.0";
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}

<?php
	$api_path = "https://api.titledb.com/";

	function http_req($data = array("action" => "list", "fields" => array("id", "titleid", "author", "description", "name", "create_time", "size", "mtime")), $endpoint = "v0/") {
		$curl = curl_init($GLOBALS["api_path"].$endpoint);
		$headers = array();
		$headers[] = "Homebr3w/1.0.0 Homebr3w-Proxy/1.0.0";
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}

Change default list of fields

Change default list of fields

The default list of fields to retrieve has been extended for a few more
pieces of information for each app.


<?php

namespace App\Libs;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Libs\ViewResolver;
use Illuminate\Http\Request;

abstract class Controller extends BaseController{

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct(Request $request,ViewResolver $viewResolver){
    	$this->request = $request;

        $this->view = $viewResolver;

       if(app()->isInstalled()){
            foreach(app()->plugins as $plugin){

                    foreach($plugin->getRegister('injectJs',[]) as $js){
                           $this->view->data['jsplugins'][] = $plugin->getPath().'/'.$js;
                    }

            }
        }

    }

    public function redirect($location){
    	return redirect($location);
    }

    public function redirectToSelf(){
        return redirect()->back();
    }

    public function insideLink($location){
    	return redirect(\Config::get('horizontcms.backend_prefix')."/".$location);
    }

}

<?php

namespace App\Libs;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Libs\ViewResolver;
use Illuminate\Http\Request;

abstract class Controller extends BaseController{

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct(Request $request,ViewResolver $viewResolver){
    	$this->request = $request;

        $this->view = $viewResolver;

       if(app()->isInstalled()){
            foreach(app()->plugins as $plugin){

                    foreach($plugin->getRegister('injectJs',[]) as $js){
                           $this->view->data['jsplugins'][] = str_contains($js,"http")? $js : $plugin->getPath().'/'.$js;
                    }

            }
        }

    }

    public function redirect($location){
    	return redirect($location);
    }

    public function redirectToSelf(){
        return redirect()->back();
    }

    public function insideLink($location){
    	return redirect(\Config::get('horizontcms.backend_prefix')."/".$location);
    }

}

Support for external plugin js script added.


<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', "Cyborg@champ45"); // db password (mention your db password here)
define('DB_DATABASE', "medicate"); // database name
define('DB_SERVER', "localhost"); // db server
?>

<?php
define('DB_USER', "medicate"); // db user
define('DB_PASSWORD', "workload@45"); // db password (mention your db password here)
define('DB_DATABASE', "medicate"); // database name
define('DB_SERVER', "localhost"); // db server
?>

Change User Account on PHPMyAdmin

Change User Account on PHPMyAdmin


<?php

namespace wcf\data\article;

use wcf\data\tag\Tag;
use wcf\system\tagging\TagEngine;

/**
 * Represents a list of tagged articles.
 *
 * @author  Marcel Werk
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Data\Article
 * @since   3.0
 */
class TaggedArticleList extends AccessibleArticleList
{
    /**
     * Creates a new CategoryArticleList object.
     *
     * @param Tag|Tag[] $tags
     */
    public function __construct($tags)
    {
        parent::__construct();

        $this->sqlOrderBy = 'article.time ' . ARTICLE_SORT_ORDER;

        $tagIDs = TagEngine::getInstance()->getTagIDs($tags);
        $this->getConditionBuilder()->add("article.articleID IN (
            SELECT  articleID
            FROM    wcf" . WCF_N . "_article_content
            WHERE   articleContentID IN (
                SELECT      objectID
                FROM        wcf" . WCF_N . "_tag_to_object
                WHERE       objectTypeID = ?
                        AND tagID IN (?)
                GROUP BY    objectID
                HAVING      COUNT(objectID) = ?
            )
        )", [
            TagEngine::getInstance()->getObjectTypeID('com.woltlab.wcf.article'),
            $tagIDs,
            \count($tagIDs),
        ]);
    }
}

<?php

namespace wcf\data\article;

use wcf\data\tag\Tag;
use wcf\system\tagging\TagEngine;

/**
 * Represents a list of tagged articles.
 *
 * @author  Marcel Werk
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Data\Article
 * @since   3.0
 */
class TaggedArticleList extends AccessibleArticleList
{
    /**
     * Creates a new CategoryArticleList object.
     *
     * @param Tag|Tag[] $tags
     */
    public function __construct($tags)
    {
        parent::__construct();

        $this->sqlOrderBy = 'article.time ' . ARTICLE_SORT_ORDER;

        $subselect = TagEngine::getInstance()->getSubselectForObjectsByTags(
            'com.woltlab.wcf.article',
            $tags
        );
        $this->getConditionBuilder()->add("article.articleID IN (
            SELECT  articleID
            FROM    wcf" . WCF_N . "_article_content
            WHERE   articleContentID IN ({$subselect['sql']})
        )", $subselect['parameters']);
    }
}

Make use of TagEngine::getSubselectForObjectsByTags() in TaggedArticleList

Commit c9613f130106f74853fbe9a50f06c00208106b8c is fun.

It renamed the getSqlForObjectsByTags() method that was previously used in
TaggedArticleList to the current name getSubselectForObjectsByTags() and fixed
a bug in the method that prevented it from working correctly.

At the same time the commit edited TaggedArticleList to no longer use this
method and instead copied over the logic.

I'm not sure what exactly happened during the development of that commit, but
we simply should use this (fixed) method.


<?php
namespace AnduFratu\Jwt;

\App::uses('BaseAuthenticate', 'Controller/Component/Auth');

class JwtAuthenticate extends \BaseAuthenticate
{
    private $defaultSettings = array(
        'param' => 'token',
        'key' => 'EMPTY_KEY',
    );

    public function __construct(\ComponentCollection $collection, $settings = array())
    {
        $settings = \Hash::merge(
            $this->defaultSettings,
            $settings
        );

        parent::__construct($collection, $settings);
    }

    public function authenticate(\CakeRequest $request, \CakeResponse $response)
    {
        return false;
    }

    public function getUser(\CakeRequest $request)
    {
        $token = $this->getToken($request);
        $user = false;
        if ($token)
        {
            try
            {
                $payload = (array) \JWT::decode($token, $this->settings['key']);
                $username = $this->_findUser($payload['sub']);

                $user = $this->_findUser($username);
            }
            catch (\UnexpectedValueException $e)
            {
                $user = false;
            }
        }

        return $user;
    }

    private function getToken(\CakeRequest $request)
    {
        $headers = apache_request_headers();
        if (isset($headers['Authorization']))
        {
            $authHeader = $headers['Authorization'];
            $token = preg_replace('/Bearer (.+)$/', '$1', $authHeader);
        }
        else
        {
            $token = $request->param($this->settings['param']);
        }

        return $token;
    }
}

<?php
namespace AnduFratu\Jwt;

\App::uses('BaseAuthenticate', 'Controller/Component/Auth');

class JwtAuthenticate extends \BaseAuthenticate
{
    private $defaultSettings = array(
        'param' => 'token',
        'key' => 'EMPTY_KEY',
    );

    public function __construct(\ComponentCollection $collection, $settings = array())
    {
        $settings = \Hash::merge(
            $this->defaultSettings,
            $settings
        );

        parent::__construct($collection, $settings);
    }

    public function authenticate(\CakeRequest $request, \CakeResponse $response)
    {
        return false;
    }

    public function getUser(\CakeRequest $request)
    {
        $token = $this->getToken($request);
        $user = false;
        if ($token)
        {
            try
            {
                $payload = (array) \JWT::decode($token, $this->settings['key']);
                $username = $this->_findUser($payload['sub']);

                $user = $this->_findUser($username);
            }
            catch (\UnexpectedValueException $e)
            {
                $user = false;
            }
        }

        return $user;
    }

    public function unauthenticated(\CakeRequest $request, \CakeResponse $response)
    {
        throw new \ForbiddenException();
        return true;
    }

    private function getToken(\CakeRequest $request)
    {
        $headers = apache_request_headers();
        if (isset($headers['Authorization']))
        {
            $authHeader = $headers['Authorization'];
            $token = preg_replace('/Bearer (.+)$/', '$1', $authHeader);
        }
        else
        {
            $token = $request->param($this->settings['param']);
        }

        return $token;
    }
}

Throw ForbiddenException on unauthenticated request


<?php

namespace Pinq\Parsing\PHPParser;

/**
 * Placeholder node for a resolved value
 *
 * @property mixed $Value The resolved value
 *
 * @author Elliot Levin <elliot@aanet.com.au>
 */
class PHPParserResolvedValueNode extends \PHPParser_Node_Expr
{
    public function __construct(&$value)
    {
        parent::__construct(['value' => &$value], []);
    }
}

<?php

namespace Pinq\Parsing\PHPParser;

/**
 * Placeholder node for a resolved value
 *
 * @property mixed $value The resolved value
 *
 * @author Elliot Levin <elliot@aanet.com.au>
 */
class PHPParserResolvedValueNode extends \PHPParser_Node_Expr
{
    public function __construct(&$value)
    {
        parent::__construct(['value' => &$value], []);
    }
}

Fix constant php parser node doc block

Fix constant php parser node doc block