<?php

namespace AndrewNovikof\Objects;

use Illuminate\Support\ServiceProvider;

/**
 * Class ObjectsServiceProvider
 * @package Objects
 */
class ObjectsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
            ], 'config');

            $this->publishes([
                __DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
                __DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
            ], 'objects');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../resources/config/objects.php',
            'config'
        );
        $this->app->bind('objects', ObjectsService::class);
    }
}

<?php

namespace AndrewNovikof\Objects;

use Illuminate\Support\ServiceProvider;

/**
 * Class ObjectsServiceProvider
 * @package Objects
 */
class ObjectsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
            ], 'config');

            $this->publishes([
                __DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
                __DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
            ], 'objects');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../resources/config/objects.php',
            'config'
        );
        $this->app->alias('objects', ObjectsService::class);
    }
}

Revert "Change method 'alias' to 'bind' for provide facade"

This reverts commit a65d340


<?php

namespace FluxBB\Markdown\Node;

abstract class Block extends Node implements NodeAcceptorInterface
{

    protected $open = true;

    abstract public function canContain(Node $other);

    public function toString()
    {
        return ($this->isOpen() ? '-> ' : '') . parent::toString();
    }

    public function push(Node $child)
    {
        if ($this->isOpen()) {
            if ($this->canContain($child)) {
                $this->addChild($child);
                return;
            } else {
                $this->close();
            }
        } else {
            $this->getParent()->push($child);
        }
    }

    public function isOpen()
    {
        return $this->open;
    }

    public function close()
    {
        $this->open = false;
    }

    /*
     * Node acceptor methods
     */

    public function acceptParagraph(Paragraph $paragraph)
    {
        return $this->getParent()->acceptParagraph($paragraph);
    }

    public function acceptBlockquote(Blockquote $blockquote)
    {
        return $this->getParent()->acceptBlockquote($blockquote);
    }

}

<?php

namespace FluxBB\Markdown\Node;

abstract class Block extends Node implements NodeAcceptorInterface
{

    protected $open = true;

    abstract public function canContain(Node $other);

    public function toString()
    {
        return ($this->isOpen() ? '-> ' : '') . parent::toString();
    }

    public function push(Node $child)
    {
        if ($this->isOpen()) {
            if ($this->canContain($child)) {
                $this->addChild($child);
                return;
            } else {
                $this->close();
            }
        } else {
            $this->getParent()->push($child);
        }
    }

    public function isOpen()
    {
        return $this->open;
    }

    public function close()
    {
        $this->open = false;
    }

    protected function closeAndBubble(Node $node)
    {
        $this->close();
        return $this->parent->accept($node);
    }

    /*
     * Node acceptor methods
     */

    public function acceptParagraph(Paragraph $paragraph)
    {
        return $this->closeAndBubble($paragraph);
    }

    public function acceptBlockquote(Blockquote $blockquote)
    {
        return $this->closeAndBubble($blockquote);
    }

}

Add helper method for closing node and passing potential children up the chain.


<?php namespace Panlogic\Fonix;
/**
* Fonix helper package by Panlogic Ltd.
*
* NOTICE OF LICENSE
*
* Licensed under the terms from Panlogic Ltd.
*
* @package Fonix
* @version 1.0.0
* @author Panlogic Ltd
* @license GPL3
* @copyright (c) 2015, Panlogic Ltd
* @link http://www.panlogic.co.uk
*/

use Illuminate\Support\ServiceProvider;

class FonixServiceProvider extends ServiceProvider {

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

	/**
	 * Boot the service provider.
	 *
	 * @return void
	 */
	public function boot()
	{

	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['fonix'] = $this->app->share(function($app)
		{
			return new Fonix;
		});

		$this->app->booting(function()
		{
			$loader = \Illuminate\Foundation\AliasLoader::getInstance();
			$loader->alias('Fonix', 'Panlogic\Fonix\Facades\Fonix');
		});
	}

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

<?php namespace Panlogic\Fonix;
/**
* Fonix helper package by Panlogic Ltd.
*
* NOTICE OF LICENSE
*
* Licensed under the terms from Panlogic Ltd.
*
* @package Fonix
* @version 1.0.0
* @author Panlogic Ltd
* @license GPL3
* @copyright (c) 2015, Panlogic Ltd
* @link http://www.panlogic.co.uk
*/

use Illuminate\Support\ServiceProvider;

class FonixServiceProvider extends ServiceProvider {

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

	/**
	 * Boot the service provider.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->publishes([
			__DIR__ . '/../../config/fonix.php' => config_path('fonix.php'),
		]);
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['fonix'] = $this->app->share(function($app)
		{
			return new Fonix;
		});

		$this->app->booting(function()
		{
			$loader = \Illuminate\Foundation\AliasLoader::getInstance();
			$loader->alias('Fonix', 'Panlogic\Fonix\Facades\Fonix');
		});
	}

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

Add publish reference for config

Add publish reference for config


<?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\Request;
class InvalidRequestTypeException extends \Gt\Core\Exception\GtException {}#

Add missing newline after namespace

Add missing newline after namespace


<?php namespace App\Services\Validators;

class SeatUserPasswordValidator extends Validator {

    public static $rules = array(
        'oldPassword' => 'required|min:6',
        'newPassword'  => 'required|min:6|confirmed',
        'newPassword_confirmation' => 'required|min:6'
    );

}

<?php namespace App\Services\Validators;

class SeatUserPasswordValidator extends Validator {

    public static $rules = array(
        'oldPassword' => 'required',
        'newPassword'  => 'required|min:6|confirmed',
        'newPassword_confirmation' => 'required|min:6'
    );

}

Stop assuming the old password is 6 chars long


<?php

namespace Criterion\Test\Model;

class TestModelTest extends \Criterion\Test\TestCase
{

    public function testInit()
    {
        $test = new \Criterion\Model\Test();
        $this->assertTrue(is_object($test));
        $this->assertTrue(isset($test->status));
    }

    public function testGetProject()
    {
        $test = new \Criterion\Model\Test();
        $this->assertTrue(is_object($test));

        $project = new \Criterion\Model\Project();
        $project->save();

        $test->project_id = $project->id;
        $this->assertTrue(is_object($test->getProject()));
    }

    public function testGetLogs()
    {
        $test = new \Criterion\Model\Test();
        $this->assertTrue(is_object($test));
        $test->save();

        $log = new \Criterion\Model\Log();
        $log->test_id = $test->id;
        $log->save();

        $this->assertTrue(is_array($test->getLogs()));
    }
}

<?php

namespace Criterion\Test\Model;

class TestModelTest extends \Criterion\Test\TestCase
{

    public function testInit()
    {
        $test = new \Criterion\Model\Test();
        $this->assertTrue(is_object($test));
        $this->assertTrue(isset($test->status));
    }

    public function testGetProject()
    {
        $test = new \Criterion\Model\Test();
        $this->assertTrue(is_object($test));

        $project = new \Criterion\Model\Project();
        $project->save();

        $test->project_id = $project->id;
        $this->assertTrue(is_object($test->getProject()));
    }

    public function testGetLogs()
    {
        $test = new \Criterion\Model\Test();
        $this->assertTrue(is_object($test));
        $test->save();

        $log = new \Criterion\Model\Log();
        $log->test_id = $test->id;
        $log->internal = false;
        $log->save();

        $this->assertTrue(is_array($test->getLogs()));
    }
}

Use internal logs when testing TestModel::getLogs


<?php

namespace ContentTranslator\Entity;

abstract class Translate
{
    protected $lang;
    protected $db;

    public function __construct()
    {
        global $wpdb;
        $this->db = $wpdb;
        $this->lang = \ContentTranslator\Switcher::$currentLanguage->code;
    }

    /**
     * Creates a language specific meta/options key
     * @param  string $key The meta/option key
     * @return string      Langual meta/option key
     */
    private function createLangualKey(string $key) : string
    {
        if ($this->isLangualOption($key)) {
            return $key;
        }

        return $key . TRANSLATE_DELIMITER . $this->lang;
    }

    /**
     * Check if key is a langual option
     * @param  string  $key Option key
     * @return boolean
     */
    private function isLangualOption($key)
    {
        return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false;
    }
}

<?php

namespace ContentTranslator\Entity;

abstract class Translate
{
    protected $lang;
    protected $db;

    public function __construct()
    {
        global $wpdb;
        $this->db = $wpdb;
        $this->lang = \ContentTranslator\Switcher::$currentLanguage->code;
    }

    /**
     * Creates a language specific meta/options key
     * @param  string $key The meta/option key
     * @return string      Langual meta/option key
     */
    protected function createLangualKey(string $key) : string
    {
        if ($this->isLangualOption($key)) {
            return $key;
        }

        return $key . TRANSLATE_DELIMITER . $this->lang;
    }

    /**
     * Check if key is a langual option
     * @param  string  $key Option key
     * @return boolean
     */
    protected function isLangualOption($key)
    {
        return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false;
    }
}

Revert "Make createLangualKey and isLangualKey private"

This reverts commit 998f7b0f0771359aa26a815b9c16b76742eb0c46.


<?php

namespace DICIT;

class ReferenceResolver
{
    const CONTAINER_REFERENCE = '$container';
    /**
     *
     * @var Container
     */
    private $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function resolve($reference)
    {
        if ($reference === static::CONTAINER_REFERENCE) {
            return $this->container;
        }

        $prefix = substr($reference, 0, 1);

        switch ($prefix) {

            case '@' :
                $toReturn = $this->container->get(substr($reference, 1));
                break;
            case '%' :
                $toReturn = $this->container->getParameter(substr($reference, 1));
                break;
            default :
                $toReturn = $reference;
                break;
        }

        return $toReturn;
    }

    public function resolveMany(array $references)
    {
        $convertedParameters = array();

        foreach ($references as $reference) {
            $convertedValue = $this->resolve($reference);
            $convertedParameters[] = $convertedValue;
        }

        return $convertedParameters;
    }
}

<?php

namespace DICIT;

class ReferenceResolver
{
    const CONTAINER_REFERENCE = '$container';
    /**
     *
     * @var Container
     */
    private $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function resolve($reference)
    {
        if ($reference === static::CONTAINER_REFERENCE) {
            return $this->container;
        }

        if (!is_string($reference)) {
            return $reference;
        }

        $prefix = substr($reference, 0, 1);

        switch ($prefix) {

            case '@' :
                return $this->container->get(substr($reference, 1));
            case '%' :
                return $this->container->getParameter(substr($reference, 1));
            default :
                return $reference;
        }
    }

    public function resolveMany(array $references)
    {
        $convertedParameters = array();

        foreach ($references as $reference) {
            $convertedValue = $this->resolve($reference);
            $convertedParameters[] = $convertedValue;
        }

        return $convertedParameters;
    }
}

Allow to pass other things that string in args


<?php
require_once '../svg.php';
include '../init.php';

if (isset($_GET['id'])) {
    $sql = "SELECT `wm_workers`.`id` as `woker_id`, `user_id`, ".
           "`worker_name`, `description`, `url`, `latest_heartbeat`, ".
           "`display_name` ".
           "FROM `wm_workers` ".
           "JOIN `wm_users` ON `user_id` = `wm_users`.`id`".
           "WHERE `wm_workers`.`id` = :wid";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':wid', $_GET['id'], PDO::PARAM_INT);
    $stmt->execute();
    $worker = $stmt->fetchObject();
}

echo $twig->render('worker.twig', array('heading' => 'Worker',
                                       'file' => "worker",
                                       'logged_in' => is_logged_in(),
                                       'display_name' => $_SESSION['display_name'],
                                       'user_id' => $user->id,
                                       'worker' => $worker
                                       )
                  );

?>

<?php
require_once '../svg.php';
include '../init.php';

if (isset($_GET['id'])) {
    $sql = "SELECT `wm_workers`.`id` as `woker_id`, `user_id`, ".
           "`worker_name`, `wm_workers`.`description`, `url`, ".
           "`latest_heartbeat`, ".
           "`display_name` ".
           "FROM `wm_workers` ".
           "JOIN `wm_users` ON `user_id` = `wm_users`.`id`".
           "WHERE `wm_workers`.`id` = :wid";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':wid', $_GET['id'], PDO::PARAM_INT);
    $stmt->execute();
    $worker = $stmt->fetchObject();
}

echo $twig->render('worker.twig', array('heading' => 'Worker',
                                       'file' => "worker",
                                       'logged_in' => is_logged_in(),
                                       'display_name' => $_SESSION['display_name'],
                                       'user_id' => $user->id,
                                       'worker' => $worker
                                       )
                  );

?>

Fix ambiguity in field of worker

Fix ambiguity in field  of worker


<?php

namespace Sody\View;

/**
 * Sody view locator
 *
 * @author Kenny Damgren <kennydamgren@gmail.com>
 * @package Sody
 */
class ViewLocator
{
    private $paths = array();
    private $extension;

    public function __construct($paths = array(__DIR__), $extension = '.php')
    {
        $this->paths = $paths;
        $this->extension = $extension;
    }

    private function buildPath($view, $path)
    {
        $path = rtrim($path, '/') . '/';

        return $path . $view . $this->extension;
    }

    public function exists($view)
    {
        $this->paths = array(__DIR__ . '/../../../');

        if (!empty($this->paths)) {
            foreach ($this->paths as $path) {
                $file = $this->buildPath($view, $path);

                if (file_exists($file)) {
                    return $file;
                }
            }
        }
    }
}

<?php

namespace Sody\View;

/**
 * Sody view locator
 *
 * @author Kenny Damgren <kennydamgren@gmail.com>
 * @package Sody
 */
class ViewLocator
{
    private $paths = array();
    private $extension;

    public function __construct($paths = array(), $extension = '.php')
    {
        $this->paths = $paths;
        $this->extension = $extension;
    }

    private function buildPath($view, $path = null)
    {
        if (null === $path) {
            return $view . $this->extension;
        } else {
            $path = rtrim($path, '/') . '/';

            return $path . $view . $this->extension;
        }
    }

    public function exists($view)
    {
        if (!empty($this->paths)) {
            foreach ($this->paths as $path) {
                $file = $this->buildPath($view, $path);

                if (file_exists($file)) {
                    return $file;
                }
            }
        } else {
            $file = $this->buildPath($view);

            if (file_exists($file)) {
                return $file;
            }
        }
    }
}

Fix problem when no paths isset

Fix problem when no paths isset


<?php
use yii\helpers\Url;

/* @var $this yii\web\View */
$this->title = 'Articles';
?>

        <a href=<?= Url::to(['article/view', 'id' => $model->id]) ?>><?= $model->title ?>

        Published on <?= date('F j, Y, g:i a', $model->created_at) ?>

<?= $model->summary ?>

    <a class="btn btn-primary" href=<?= Url::to(['article/view', 'id' => $model->id]) ?>>
        Read More

<?php
use yii\helpers\Url;

/* @var $this yii\web\View */
$this->title = 'Articles';
?>

        <a href=<?= Url::to(['article/view', 'id' => $model->id]) ?>><?= $model->title ?>

        <?= Yii::t('app','Published on').' '.date('F j, Y, g:i a', $model->created_at) ?>

<?= $model->summary ?>

    <a class="btn btn-primary" href=<?= Url::to(['article/view', 'id' => $model->id]) ?>>
        <?= yii::t('app','Read more'); ?>

Make use of yii::t() on buttons text

Make use of yii::t() on buttons text


<?php namespace Larapress\Tests\Services;

use Config;
use DB;
use Helpers;
use Lang;
use Log;
use Mockery;
use Larapress\Tests\TestCase;
use Request;
use View;

class HelpersTest extends TestCase
{

    /*
    |--------------------------------------------------------------------------
    | Helpers::setPageTitle() Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the Helpers::setPageTitle() method
    |
    */

    public function test_can_set_page_title()
    {
        Config::shouldReceive('get')->with('larapress.names.cms')->once()->andReturn('foo')->shouldReceive('offsetGet');
        Lang::shouldReceive('get')->with('general.bar')->once()->andReturn('bar');
        View::shouldReceive('share')->with('title', 'foo | bar')->once();

        Helpers::setPageTitle('bar');
    }

    /*
    |--------------------------------------------------------------------------
    | Helpers::logPerformance() Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the Helpers::logPerformance() method
    |
    */

    public function test_can_log_the_applications_performance()
    {
        Log::shouldReceive('info')->once();
        Request::shouldReceive('getRequestUri')->once();
        DB::shouldReceive('getQueryLog')->once();

        Helpers::logPerformance();
    }

}

<?php namespace Larapress\Tests\Services;

use Config;
use DB;
use Helpers;
use Lang;
use Log;
use Mockery;
use Larapress\Tests\TestCase;
use Redirect;
use Request;
use View;

class HelpersTest extends TestCase
{

    /*
    |--------------------------------------------------------------------------
    | Helpers::setPageTitle() Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the Helpers::setPageTitle() method
    |
    */

    public function test_can_set_page_title()
    {
        Config::shouldReceive('get')->with('larapress.names.cms')->once()->andReturn('foo')->shouldReceive('offsetGet');
        Lang::shouldReceive('get')->with('general.bar')->once()->andReturn('bar');
        View::shouldReceive('share')->with('title', 'foo | bar')->once();

        Helpers::setPageTitle('bar');
    }

    /*
    |--------------------------------------------------------------------------
    | Helpers::logPerformance() Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the Helpers::logPerformance() method
    |
    */

    public function test_can_log_the_applications_performance()
    {
        Log::shouldReceive('info')->once();
        Request::shouldReceive('getRequestUri')->once();
        DB::shouldReceive('getQueryLog')->once();

        Helpers::logPerformance();
    }

    /*
    |--------------------------------------------------------------------------
    | Helpers::forceSSL() Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the Helpers::forceSSL() method
    |
    */

    public function test_can_force_ssl()
    {
        Request::shouldReceive('secure')->once()->andReturn(false);
        Request::shouldReceive('getRequestUri')->once()->andReturn('foo');
        Request::shouldReceive('root');
        Redirect::shouldReceive('secure')->with('foo')->once();

        Helpers::forceSSL();
    }

    public function test_can_remain_silent()
    {
        Request::shouldReceive('secure')->once()->andReturn(true);
        Redirect::shouldReceive('secure')->never();

        $this->assertNull(Helpers::forceSSL());
    }

}

Add tests for the forceSSL() helpers method


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class IssueComment extends Model
{

}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class IssueComment extends Model
{
    public $incrementing = false;

    public function comment()
    {
        return $this->belongsTo(Issue::class);
    }
}

Add Issue Comment Model attribute

Add Issue Comment  Model attribute


No credit cards registered, please register a credit card.

No credit cards registered, please <?= l('register a credit card', 'my-credit-card/set'); ?>.

Use 'l' instead of a hardcoded anchor tag.


<?php namespace Modules\Menu\Composers;

use Illuminate\Contracts\View\View;
use Maatwebsite\Sidebar\SidebarGroup;
use Maatwebsite\Sidebar\SidebarItem;
use Modules\Core\Composers\BaseSidebarViewComposer;

class SidebarViewComposer extends BaseSidebarViewComposer
{
    public function compose(View $view)
    {
        $view->sidebar->group(trans('core::sidebar.content'), function (SidebarGroup $group) {
            $group->addItem(trans('menu::menu.title'), function (SidebarItem $item) {
                $item->weight = 3;
                $item->icon = 'fa fa-bars';
                $item->route('admin.menu.menu.index');
                $item->authorize(
                    $this->auth->hasAccess('menu.menus.index')
                );
            });
        });
    }
}

<?php namespace Modules\Menu\Composers;

use Illuminate\Contracts\View\View;
use Maatwebsite\Sidebar\SidebarGroup;
use Maatwebsite\Sidebar\SidebarItem;
use Modules\Core\Composers\BaseSidebarViewComposer;

class SidebarViewComposer extends BaseSidebarViewComposer
{
    public function compose(View $view)
    {
        $view->sidebar->group(trans('core::sidebar.content'), function (SidebarGroup $group) {
            $group->weight = 90;
            $group->addItem(trans('menu::menu.title'), function (SidebarItem $item) {
                $item->weight = 3;
                $item->icon = 'fa fa-bars';
                $item->route('admin.menu.menu.index');
                $item->authorize(
                    $this->auth->hasAccess('menu.menus.index')
                );
            });
        });
    }
}

Set the content group weight to 90

Set the content group weight to 90


<?php

	class Sailen_Short_Menu{

		/**
		 *
		 * @var string A unique string prefix  for properties  to avoid conflict
		 */
		public $prefix = 'ssmSavp_';

		function __construct(){

        	add_shortcode('menu', array($this,'ssmSavpDisplaySc'));

        }

		/**
		 *
		 * @var string A unique string prefix  for properties  to avoid conflict
		 */

		/**
		 * @param array $atts
		 * @return HTML ENTITIES filter applied
		 */
		function ssmSavpDisplaySc($atts) {
			$def=$atts['class'];
			if(!isset($atts['class']) || strlen(trim($atts['class']))<=0 ){
				$def='sailen_short_menu'; //default class to plugin namesapce
			}

			return apply_filters('ssmSavpfilter_style',wp_nav_menu( array('menu' => $atts['name'], 'menu_class'=> $def,'echo' => false )));
		}

	}

<?php

	class Sailen_Short_Menu{

		/**
		 *
		 * @var string A unique string prefix  for properties  to avoid conflict
		 */
		public $prefix = 'ssmSavp_';

		function __construct(){

        	add_shortcode('menu', array($this,'ssmSavpDisplaySc'));

        }

		/**
		 *
		 * @var string A unique string prefix  for properties  to avoid conflict
		 */

		/**
		 * @param array $atts
		 * @return HTML ENTITIES filter applied
		 */
		function ssmSavpDisplaySc($atts) {
			$def=$atts['class']; //ul class
			$con=$atts['con'];//Container class
			if(!isset($atts['class']) || strlen(trim($atts['class']))<=0 ){
				$def='sailen_short_menu'; //default class to plugin namesapce
			}

			if(!isset($atts['con']) || strlen(trim($atts['con']))<=0 ){
				$con='sailen_short_menu_con'; //default class to plugin namesapce
			}

			return apply_filters('ssmSavpfilter_style',wp_nav_menu( array('menu' => $atts['name'], 'menu_class'=> $def,'echo' => false, 'container_class'=>$con )));
		}

	}

Add optional args for container_class for nav-menu container default class is 'sailen_short_menu_con' <code> [menu name="Primary" class="my_custom_class" con="my_custom_class"] </code>


<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAttributesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create(config('rinvex.attributes.tables.attributes'), function (Blueprint $table) {
            // Columns
            $table->increments('id');
            $table->string('slug');
            $table->{$this->jsonable()}('name');
            $table->{$this->jsonable()}('description')->nullable();
            $table->mediumInteger('sort_order')->unsigned()->default(0);
            $table->string('group')->nullable();
            $table->string('type');
            $table->boolean('is_required')->default(false);
            $table->boolean('is_collection')->default(false);
            $table->text('default')->nullable();
            $table->timestamps();

            // Indexes
            $table->unique('slug');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists(config('rinvex.attributes.tables.attributes'));
    }

    /**
     * Get jsonable column data type.
     *
     * @return string
     */
    protected function jsonable(): string
    {
        $driverName = DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME);
        $dbVersion = DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION);
        $isOldVersion = version_compare($dbVersion, '5.7.8', 'lt');

        return $driverName === 'mysql' && $isOldVersion ? 'text' : 'json';
    }
}

<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAttributesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create(config('rinvex.attributes.tables.attributes'), function (Blueprint $table) {
            // Columns
            $table->increments('id');
            $table->string('slug');
            $table->json('name');
            $table->json('description')->nullable();
            $table->mediumInteger('sort_order')->unsigned()->default(0);
            $table->string('group')->nullable();
            $table->string('type');
            $table->boolean('is_required')->default(false);
            $table->boolean('is_collection')->default(false);
            $table->text('default')->nullable();
            $table->timestamps();

            // Indexes
            $table->unique('slug');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists(config('rinvex.attributes.tables.attributes'));
    }
}

Drop old MySQL versions support that doesn't support json columns


<?php

namespace blink\laravel\database\commands;

use \Illuminate\Database\Migrations\DatabaseMigrationRepository;
use \Illuminate\Database\Migrations\MigrationCreator;
use \Illuminate\Database\Migrations\Migrator;
use \Illuminate\Filesystem\Filesystem;
use \Symfony\Component\Console\Input\InputArgument;
use \Symfony\Component\Console\Input\InputInterface;
use \Symfony\Component\Console\Output\OutputInterface;

class ResetCommand extends BaseCommand
{
    public $name = 'migrate:reset';
    public $description = 'Rollback all database migrations';

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        app()->bootstrap();

        $migrator = $this->getMigrator();

        if (!$this->migrator->repositoryExists()) {
            $output->writeln('<comment>Migration table not found.</comment>');
            return;
        }

        $migrator->reset(false);

        foreach ($migrator->getNotes() as $note) {
            $output->writeln($note);
        }
    }
}

<?php

namespace blink\laravel\database\commands;

use \Illuminate\Database\Migrations\DatabaseMigrationRepository;
use \Illuminate\Database\Migrations\MigrationCreator;
use \Illuminate\Database\Migrations\Migrator;
use \Illuminate\Filesystem\Filesystem;
use \Symfony\Component\Console\Input\InputArgument;
use \Symfony\Component\Console\Input\InputInterface;
use \Symfony\Component\Console\Output\OutputInterface;

class ResetCommand extends BaseCommand
{
    public $name = 'migrate:reset';
    public $description = 'Rollback all database migrations';

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        app()->bootstrap();

        $migrator = $this->getMigrator();

        if (!$this->migrator->repositoryExists()) {
            $output->writeln('<comment>Migration table not found.</comment>');
            return;
        }

        $migrator->reset($this->getMigrationPath(), false);

        foreach ($migrator->getNotes() as $note) {
            $output->writeln($note);
        }
    }
}

Fix issues after upgraded dependency

Fix issues after upgraded dependency


<?php

namespace Buster;

use Buster\Provider\JsonResponseProvider;
use Silex\Application as SilexApplication;
use Silex\Provider\MonologServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Buster\Provider\ErrorHandlerProvider;

class Application extends SilexApplication
{
    use SilexApplication\MonologTrait;

    /**
     * Instantiate a new Application.
     *
     * Objects and parameters can be passed as argument to the constructor.
     *
     * @param array $values The parameters or objects.
     */
    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this['debug'] = php_sapi_name() === 'cli-server';

        $this->registerLogging();
        $this->register(new JsonResponseProvider());

        $this->register(new TwigServiceProvider(), array(
            'twig.path' => $this['path.view'],
        ));
    }

    /**
     * @return ErrorHandlerProvider
     */
    protected function registerErrorHandler()
    {
        $errorProvider = new ErrorHandlerProvider;
        $this->register($errorProvider);

        return $errorProvider;
    }

    /**
     *
     */
    protected function registerLogging()
    {
        $this->register(new MonologServiceProvider(), array('monolog.logfile' => 'php://stderr'));
    }
}

<?php

namespace Buster;

use Buster\Provider\JsonResponseProvider;
use Monolog\Logger;
use Silex\Application as SilexApplication;
use Silex\Provider\MonologServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Buster\Provider\ErrorHandlerProvider;

class Application extends SilexApplication
{
    use SilexApplication\MonologTrait;

    /**
     * Instantiate a new Application.
     *
     * Objects and parameters can be passed as argument to the constructor.
     *
     * @param array $values The parameters or objects.
     */
    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this['debug'] = php_sapi_name() === 'cli-server';

        $this->registerLogging();
        $this->register(new JsonResponseProvider());

        $this->register(new TwigServiceProvider(), array(
            'twig.path' => $this['path.view'],
        ));

        $this->registerDatabase();
    }

    /**
     *
     */
    protected function registerDatabase()
    {
        $url = null;

        if (isset($_ENV['HEROKU_POSTGRESQL_GREEN_URL'])) {
            $url = $_ENV['HEROKU_POSTGRESQL_GREEN_URL'];
        }

        $this->log('Url: ' . $url, array(), Logger::DEBUG);
    }

    /**
     * @return ErrorHandlerProvider
     */
    protected function registerErrorHandler()
    {
        $errorProvider = new ErrorHandlerProvider;
        $this->register($errorProvider);

        return $errorProvider;
    }

    /**
     *
     */
    protected function registerLogging()
    {
        $this->register(new MonologServiceProvider(), array('monolog.logfile' => 'php://stderr'));
    }
}

Add in database tst code.

Add in database tst code.


<?php

namespace Flugg\Responder\Exceptions;

use Exception;
use Flugg\Responder\Exceptions\Http\ApiException;
use Flugg\Responder\Traits\HandlesApiErrors;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    use HandlesApiErrors;

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  Exception                $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function render($request, Exception $exception)
    {
        if ($request->expectsJson()) {
            $this->transformException($exception);
        }

        if ($exception instanceof ApiException) {
            return $this->renderApiError($exception);
        }

        return parent::render($request, $exception);
    }
}

<?php

namespace Flugg\Responder\Exceptions;

use Exception;
use Flugg\Responder\Exceptions\Http\ApiException;
use Flugg\Responder\Traits\HandlesApiErrors;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    use HandlesApiErrors;

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  Exception                $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function render($request, Exception $exception)
    {
        if ($request->expectsJson()) {
            $this->transformException($exception);

            if ($exception instanceof ApiException) {
                return $this->renderApiError($exception);
            }
        }

        return parent::render($request, $exception);
    }
}

Revert "Exceptions extending ApiException should always return json."

This reverts commit 1ddd0cfbf0632214ffe5f9c4f1d98ad453e53f3c.


<?php
namespace @@namespace@@\Modules\Frontend;

use Phalcon\DiInterface;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{
    /**
     * Registers an autoloader related to the module
     *
     * @param DiInterface $di
     */
    public function registerAutoloaders(DiInterface $di = null)
    {
        $loader = new Loader();

        $loader->registerNamespaces([
            '@@namespace@@\Modules\Frontend\Controllers' => __DIR__ . '/controllers/',
            '@@namespace@@\Modules\Frontend\Models' => __DIR__ . '/models/',
        ]);

        $loader->register();
    }

    /**
     * Registers services related to the module
     *
     * @param DiInterface $di
     */
    public function registerServices(DiInterface $di)
    {
        /**
         * Setting up the view component
         */
        $di->set('view', function () {
            $view = new View();
            $view->setDI($this);
            $view->setViewsDir(__DIR__ . '/views/');

            $view->registerEngines([
                '.volt'  => 'voltShared',
                '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
            ]);

            return $view;
        });
    }
}

<?php
namespace @@namespace@@\Modules\Frontend;

use Phalcon\DiInterface;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{
    /**
     * Registers an autoloader related to the module
     *
     * @param DiInterface $di
     */
    public function registerAutoloaders(DiInterface $di = null)
    {
        $loader = new Loader();

        $loader->registerNamespaces([
            '@@namespace@@\Modules\Frontend\Controllers' => __DIR__ . '/controllers/',
            '@@namespace@@\Modules\Frontend\Models' => __DIR__ . '/models/',
        ]);

        $loader->register();
    }

    /**
     * Registers services related to the module
     *
     * @param DiInterface $di
     */
    public function registerServices(DiInterface $di)
    {
        /**
         * Setting up the view component
         */
        $di->set('view', function () {
            $view = new View();
            $view->setDI($this);
            $view->setViewsDir(__DIR__ . '/views/');

            $view->registerEngines([
                '.volt'  => 'voltShared'
            ]);

            return $view;
        });
    }
}

Remove PHP template engine from 'modules' project.


<?php namespace Flarum;

use DB;

class Core
{
    public static function isInstalled()
    {
        return file_exists(base_path('../config.php'));
    }

    public static function config($key, $default = null)
    {
        if (! static::isInstalled()) {
            return $default;
        }

        if (is_null($value = app('db')->table('config')->where('key', $key)->pluck('value'))) {
            $value = $default;
        }

        return $value;
    }
}

<?php namespace Flarum;

class Core
{
    public static function isInstalled()
    {
        return file_exists(base_path('../config.php'));
    }

    public static function inDebugMode()
    {
        return env('APP_DEBUG');
    }

    public static function config($key, $default = null)
    {
        if (! static::isInstalled()) {
            return $default;
        }

        if (is_null($value = app('db')->table('config')->where('key', $key)->pluck('value'))) {
            $value = $default;
        }

        return $value;
    }
}

Add method for checking debug mode

Add method for checking debug mode


<?php

function atws_autoload($class) {
    $dirSep = DIRECTORY_SEPARATOR;
    $namespaceParts = explode('\\', $class);
    $className = array_pop($namespaceParts);

    array_shift($namespaceParts);
    require_once __DIR__ . $dirSep . implode($dirSep, $namespaceParts) . "{$className}.php";
}

spl_autoload_register('atws_autoload');

<?php

function atws_autoload($class) {
    $dirSep = DIRECTORY_SEPARATOR;
    $namespaceParts = explode('\\', $class);
    $className = array_pop($namespaceParts);

    array_shift($namespaceParts);
    require_once __DIR__ . $dirSep . implode($dirSep, $namespaceParts) . "{$dirSep}{$className}.php";
}

spl_autoload_register('atws_autoload');

Add in missing directory separator

Add in missing directory separator


<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;

/**
 * ContactForm is the model behind the contact form.
 */
class NewsItem extends ActiveRecord
{
    public function rules()
    {
        return [
            [["id", "date", "title_id", "text_id", "image_url"], "safe"]
        ];
    }

    public function extraFields()
    {
        return ['title', 'text', 'tags'];
    }

    public static function tableName()
    {
        return 'news';
    }

    public function getTitle()
    {
        return $this->hasOne(TranslationString::className(), ['id' => 'title_id']);
    }

    public function getText()
    {
        return $this->hasOne(TranslationText::className(), ['id' => 'text_id']);
    }

    public function getTags()
    {
        return $this
            ->hasMany(NewsTag::className(), ['id' => 'news_tags_id'])
            ->viaTable('news_news_tags', ['news_id' => 'id']);
    }
}

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;

/**
 * ContactForm is the model behind the contact form.
 */
class NewsItem extends ActiveRecord
{
    public function rules()
    {
        return [
            [["id", "date", "title_id", "text_id", "image_url", "published"], "safe"]
        ];
    }

    public function extraFields()
    {
        return ['title', 'text', 'tags'];
    }

    public static function tableName()
    {
        return 'news';
    }

    public function getTitle()
    {
        return $this->hasOne(TranslationString::className(), ['id' => 'title_id']);
    }

    public function getText()
    {
        return $this->hasOne(TranslationText::className(), ['id' => 'text_id']);
    }

    public function getTags()
    {
        return $this
            ->hasMany(NewsTag::className(), ['id' => 'news_tags_id'])
            ->viaTable('news_news_tags', ['news_id' => 'id']);
    }
}

Add published field to news model

Add published field to news model


<?php
/**
 * Created by PhpStorm.
 * User: xandros15
 * Date: 2016-06-19
 * Time: 17:22
 */

namespace Xandros15\SlimPagination;

use Slim\Http\Request;
use Slim\Router;

/**
 * @property Request request
 * @property Router router
 * @property int page
 * @property string name
 */

abstract class Page
{
    /** @var array */
    private $params;

    public function __construct(array $params)
    {
        $this->params = $params;
    }

    public function __get(string $name)
    {
        if (isset($params[$name])) {
            return $params[$name];
        }
        throw new \InvalidArgumentException('Property `' . __CLASS__ . '::' . $name . '` doesn\'t exist');
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: xandros15
 * Date: 2016-06-19
 * Time: 17:22
 */

namespace Xandros15\SlimPagination;

use Slim\Http\Request;
use Slim\Router;

/**
 * @property Request request
 * @property Router router
 * @property int page
 * @property string name
 */

abstract class Page
{
    /** @var array */
    private $params;

    public function __construct(array $params)
    {
        $this->params = $params;
    }

    public function __get(string $name)
    {
        if (isset($this->params[$name])) {
            return $this->params[$name];
        }
        throw new \InvalidArgumentException('Property `' . __CLASS__ . '::' . $name . '` doesn\'t exist');
    }

}

Fix bug when magic method doesn't found any of properties


<?php
/**
 * The template for displaying all single posts.
 *
 * @package Victorian Climbing Club
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">

		<?php while ( have_posts() ) : the_post(); ?>

			<?php get_template_part( 'content', 'single' ); ?>

			<?php the_post_navigation(); ?>

			<?php
				// If comments are open or we have at least one comment, load up the comment template
				if ( comments_open() || get_comments_number() ) :
					comments_template();
				endif;
			?>

		<?php endwhile; // end of the loop. ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

<?php
/**
 * The template for displaying all single posts.
 *
 * @package Victorian Climbing Club
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">

		<?php while ( have_posts() ) : the_post(); ?>

			<?php get_template_part( 'content', 'single' ); ?>

			<?php the_post_navigation(); ?>

		<?php endwhile; // end of the loop. ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php get_footer(); ?>

Remove comments and sidebar from post page.


has($fieldName) ? 'has-error' : '' }}">
    {!! Form::label($elementName, $options['label']) !!}
    {!! Form::text($elementName, $record->$fieldName, [
	    'id' =>  $elementName,
	    'class' => "form-control",
	    'placeholder' => $options['label'],
	] ) !!}

        {{ join($errors->get($fieldName), '
') }}

has($fieldName) ? 'has-error' : '' }}">
    {!! Form::label($elementName, $options['label']) !!}
    {!! Form::text($elementName, $record->$fieldName, array_merge([
    'id' =>  $elementName,
    'class' => "form-control",
    'placeholder' => $options['label'],
], array_get($options, 'attributes', []))) !!}

        {{ join($errors->get($fieldName), '
') }}

Allow attributes for text field

Allow attributes for text field


<?php

namespace Matthias\PhpUnitAsynchronicity;

use Matthias\Polling\CallableProbe;
use Matthias\Polling\Exception\Interrupted;
use Matthias\Polling\Poller;
use Matthias\Polling\ProbeInterface;
use Matthias\Polling\SystemClock;
use Matthias\Polling\Timeout;

class Eventually extends \PHPUnit_Framework_Constraint
{
    private $timeoutMilliseconds;
    private $waitMilliseconds;

    public function __construct($timeoutMilliseconds = 5000, $waitMilliseconds = 500)
    {
        parent::__construct();

        $this->timeoutMilliseconds = $timeoutMilliseconds;
        $this->waitMilliseconds = $waitMilliseconds;
    }

    public function evaluate($probe, $description = '', $returnResult = false)
    {
        if (is_callable($probe)) {
            $probe = new CallableProbe($probe);
        }

        if (!($probe instanceof ProbeInterface)) {
            throw new \InvalidArgumentException('Expected an instance of ProbeInterface');
        }

        try {
            $poller = new Poller();
            $poller->poll(
                $probe,
                new Timeout(new SystemClock(), $this->waitMilliseconds, $this->timeoutMilliseconds)
            );
        } catch (Interrupted $exception) {
            if ($returnResult) {
                return false;
            } else {
                $this->fail($probe, ($description != '' ? $description . "\n" : '') . 'A timeout has occurred');
            }
        }

        return true;
    }

    public function toString()
    {
        return 'was satisfied within the provided timeout';
    }
}

<?php

namespace Matthias\PhpUnitAsynchronicity;

use Matthias\Polling\CallableProbe;
use Matthias\Polling\Exception\Interrupted;
use Matthias\Polling\Poller;
use Matthias\Polling\ProbeInterface;
use Matthias\Polling\SystemClock;
use Matthias\Polling\Timeout;

class Eventually extends \PHPUnit_Framework_Constraint
{
    private $timeoutMilliseconds;
    private $waitMilliseconds;

    public function __construct($timeoutMilliseconds = 5000, $waitMilliseconds = 500)
    {
        // for compatibility with PHPUnit 4
        $parentConstructor = array('parent', '__construct');
        if (is_callable($parentConstructor)) {
            call_user_func($parentConstructor);
        }

        $this->timeoutMilliseconds = $timeoutMilliseconds;
        $this->waitMilliseconds = $waitMilliseconds;
    }

    public function evaluate($probe, $description = '', $returnResult = false)
    {
        if (is_callable($probe)) {
            $probe = new CallableProbe($probe);
        }

        if (!($probe instanceof ProbeInterface)) {
            throw new \InvalidArgumentException('Expected an instance of ProbeInterface');
        }

        try {
            $poller = new Poller();
            $poller->poll(
                $probe,
                new Timeout(new SystemClock(), $this->waitMilliseconds, $this->timeoutMilliseconds)
            );
        } catch (Interrupted $exception) {
            if ($returnResult) {
                return false;
            } else {
                $this->fail($probe, ($description != '' ? $description . "\n" : '') . 'A timeout has occurred');
            }
        }

        return true;
    }

    public function toString()
    {
        return 'was satisfied within the provided timeout';
    }
}

Make library compatible with PHPUnit 4

Make library compatible with PHPUnit 4


<?php

namespace SalvoCanna\RedisNotificationBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('sc_redis_notification_bundle');
        /*$rootNode
            ->children()
            ->scalarNode('notification_class')
            ->cannotBeEmpty()
            ->defaultValue('AppBundle\\Entity\\Notification')
            ->info('Entity for a notification (default: AppBundle\\Entity\\Notification)')
            ->end();
         */

        return $treeBuilder;
    }
}

<?php
namespace SalvoCanna\RedisNotificationBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('rnb');
        $rootNode
            ->children()
            ->scalarNode('redis_connection')
            ->defaultValue('snc_redis.default')
            ->info('Redis connection to use')
            ->end();

        return $treeBuilder;
    }
}

Set a basic config tree

[Config] Set a basic config tree


<?php

namespace JWX\JWE\KeyAlgorithm;

use JWX\JWA\JWA;
use JWX\JWE\KeyManagementAlgorithm;
use JWX\JWT\Parameter\AlgorithmParameter;

/**
 * Algorithm to carry CEK in plaintext.
 *
 * @link https://tools.ietf.org/html/rfc7518#section-4.5
 */
class DirectCEKAlgorithm implements KeyManagementAlgorithm
{
	/**
	 * Content encryption key.
	 *
	 * @var string $_cek
	 */
	protected $_cek;

	/**
	 * Constructor
	 *
	 * @param string $key Content encryption key
	 */
	public function __construct($cek) {
		$this->_cek = $cek;
	}

	/**
	 * Get content encryption key.
	 *
	 * @return string
	 */
	public function cek() {
		return $this->_cek;
	}

	public function encrypt($cek) {
		return "";
	}

	public function decrypt($data) {
		if ($data !== "") {
			throw new \UnexpectedValueException(
				"Encrypted key must be an empty octet sequence.");
		}
		return $this->_cek;
	}

	public function cekForEncryption($length) {
		if (strlen($this->_cek) != $length) {
			throw new \RuntimeException("Invalid key length.");
		}
		return $this->_cek;
	}

	public function algorithmParamValue() {
		return JWA::ALGO_DIR;
	}

	public function headerParameters() {
		return array(AlgorithmParameter::fromAlgorithm($this));
	}
}

<?php

namespace JWX\JWE\KeyAlgorithm;

use JWX\JWA\JWA;
use JWX\JWE\KeyManagementAlgorithm;
use JWX\JWT\Parameter\AlgorithmParameter;

/**
 * Algorithm to carry CEK in plaintext.
 *
 * @link https://tools.ietf.org/html/rfc7518#section-4.5
 */
class DirectCEKAlgorithm implements KeyManagementAlgorithm
{
	/**
	 * Content encryption key.
	 *
	 * @var string $_cek
	 */
	protected $_cek;

	/**
	 * Constructor
	 *
	 * @param string $key Content encryption key
	 */
	public function __construct($cek) {
		$this->_cek = $cek;
	}

	/**
	 * Get content encryption key.
	 *
	 * @return string
	 */
	public function cek() {
		return $this->_cek;
	}

	public function encrypt($cek) {
		return "";
	}

	public function decrypt($data) {
		if ($data !== "") {
			throw new \UnexpectedValueException(
				"Encrypted key must be an empty octet sequence.");
		}
		return $this->_cek;
	}

	public function cekForEncryption($length) {
		if (strlen($this->_cek) != $length) {
			throw new \UnexpectedValueException("Invalid key length.");
		}
		return $this->_cek;
	}

	public function algorithmParamValue() {
		return JWA::ALGO_DIR;
	}

	public function headerParameters() {
		return array(AlgorithmParameter::fromAlgorithm($this));
	}
}

Change exception to more appropriate

Change exception to more appropriate


<?php

namespace App\Entity;

use App\Repository\OAuthStateRepository;
use DateTime;
use Doctrine\ORM\Mapping as ORM;

/**
 * Database table used for storing valid OAuth state tokens and their expiration dates.
 * Definitely not exposed on the API, this is only for internal security checking.
 */
#[ORM\Entity(repositoryClass: OAuthStateRepository::class)]
#[ORM\Index(columns: ['expireTime', 'state'])]
class OAuthState extends BaseEntity {
    #[ORM\Column(type: 'string')]
    public string $state;

    #[ORM\Column(type: 'datetime')]
    public DateTime $expireTime;
}

<?php

namespace App\Entity;

use App\Repository\OAuthStateRepository;
use DateTime;
use Doctrine\ORM\Mapping as ORM;

/**
 * Database table used for storing valid OAuth state tokens and their expiration dates.
 * Definitely not exposed on the API, this is only for internal security checking.
 */
#[ORM\Entity(repositoryClass: OAuthStateRepository::class)]
#[ORM\Index(columns: ['expireTime', 'state'], name: 'IDX_466EF70CD49BE2B9A393D2FB')]
class OAuthState extends BaseEntity {
    #[ORM\Column(type: 'string')]
    public string $state;

    #[ORM\Column(type: 'datetime')]
    public DateTime $expireTime;
}

Work around doctrine bug by specifying index name


<?php

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

$app = new Silex\Application();

require __DIR__.'/../app/config/prod.php';
require __DIR__.'/../app/app.php';
require __DIR__.'/../app/routes.php';

$app->run();

<?php

date_default_timezone_set('UTC');

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

$app = new Silex\Application();

require __DIR__.'/../app/config/prod.php';
require __DIR__.'/../app/app.php';
require __DIR__.'/../app/routes.php';

$app->run();

Set date_default_timezone to UTC (suppress PHP warning)


<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;

class ListingsTest extends TestCase
{
    use WithoutMiddleware;

    /**
     * Test to see that the Listings pages load.
     * @dataProvider listingPages
     * @return void
     */
    public function testListingPagesLoadProperly($routeName, $value)
    {
        $this->get(route($routeName))->assertSee($value);
    }

    public function listingPages()
    {
        return [
            'Machines listing' => ['machines.index', 'Equipment Inventory - Active'],
            'Modality listing' => ['machines.showModalityIndex', 'List equipment by modality'],
            'Location listing' => ['machines.showLocationIndex', 'List equipment by location'],
            'Manufacturer listing' => ['machines.showManufacturerIndex', 'List equipment by manufacturer'],
            'Inactive machines listing' => ['machines.inactive', 'Equipment Inventory - Inactive'],
            'Removed machines listing' => ['machines.removed', 'Equipment Inventory - Removed'],
            'Test equipment listing' => ['testequipment.index', 'Equipment Inventory - Test Equipment'],
            'Test equipment cal dates listing' => ['testequipment.showCalDates', 'Recent Test Equipment Calibration Dates'],
        ];
    }
}

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class ListingsTest extends TestCase
{

    /**
     * Test to see that the Listings pages load.
     * @dataProvider listingRoutes
     * @return void
     */
    public function testListingRoutesLoadProperly($routeName, $value)
    {
        $this->get(route($routeName))->assertSee($value);
    }

    public function listingRoutes()
    {
        return [
            'Machines listing' => ['machines.index', 'Equipment Inventory - Active'],
            'Modality listing' => ['machines.showModalityIndex', 'List equipment by modality'],
            'Location listing' => ['machines.showLocationIndex', 'List equipment by location'],
            'Manufacturer listing' => ['machines.showManufacturerIndex', 'List equipment by manufacturer'],
            'Inactive machines listing' => ['machines.inactive', 'Equipment Inventory - Inactive'],
            'Removed machines listing' => ['machines.removed', 'Equipment Inventory - Removed'],
            'Test equipment listing' => ['testequipment.index', 'Equipment Inventory - Test Equipment'],
            'Test equipment cal dates listing' => ['testequipment.showCalDates', 'Recent Test Equipment Calibration Dates'],
        ];
    }
}

Update tests for Listings pages

Update tests for Listings pages


<?php

namespace Tests\Functional;

class QuoteTest extends BaseTestCase
{
    public function testNumberOfCategories(){
        $quote = new \Quote(null, null);
        $categories = $quote->getCategories();
        $this->assertEquals(5, sizeof($categories));
    }

    public function testCategoryListContainsManagement(){
        $quote = new \Quote(null, null);
        $categories = $quote->getCategories();
        $this->assertTrue(in_array("management", $categories));
    }

    public function testQuoteClientFailsForInvalidCategory(){
        try{
            $quote = new \Quote("Invalid Category", null);
            $this->fail("Shouldn't have come here.");
        }catch(\Exception $e){
            // expected
        }
    }
}

<?php

namespace Tests\Functional;

class QuoteTest extends BaseTestCase
{
    public function testNumberOfCategories(){
        $quote = new \Quote(null, null);
        $categories = $quote->getCategories();
        $this->assertEquals(8, sizeof($categories));
    }

    public function testCategoryListContainsManagement(){
        $quote = new \Quote(null, null);
        $categories = $quote->getCategories();
        $this->assertTrue(in_array("management", $categories));
    }

    public function testQuoteClientFailsForInvalidCategory(){
        try{
            $quote = new \Quote("Invalid Category", null);
            $this->fail("Shouldn't have come here.");
        }catch(\Exception $e){
            // expected
        }
    }
}

Make test failure on purpose

Make test failure on purpose


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @package Zigra
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.7.1';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @package Zigra
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.7.2';
}

Set release version to 0.7.2

Set release version to 0.7.2


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Service / SearchImage
 */

namespace PH7\Framework\Service\SearchImage;

defined('PH7') or exit('Restricted access');

class Url
{
    /**
     * @param string $sUrl
     *
     * @throws InvalidUrlException
     */
    public function __construct($sUrl)
    {
        if (!$this->isValid($sUrl)) {
            throw new InvalidUrlException(sprintf('%s is an invalid URL', $sUrl));
        }

        $this->sUrl = $sUrl;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->sUrl;
    }

    /**
     * @param $sUrl
     *
     * @return bool
     */
    private function isValid($sUrl)
    {
        return filter_var($sUrl, FILTER_VALIDATE_URL) !== false && strlen($sUrl) <= $this->getMaxImageLength();
    }

    /**
     * Images length are longer. It multiples the regular URL length by 2.
     *
     * @return int
     */
    private function getMaxImageLength()
    {
        return PH7_MAX_URL_LENGTH * 2;
    }
}

<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Service / SearchImage
 */

namespace PH7\Framework\Service\SearchImage;

defined('PH7') or exit('Restricted access');

class Url
{
    /** @var string */
    private $sUrl;

    /**
     * @param string $sUrl
     *
     * @throws InvalidUrlException
     */
    public function __construct($sUrl)
    {
        if (!$this->isValid($sUrl)) {
            throw new InvalidUrlException(sprintf('%s is an invalid URL', $sUrl));
        }

        $this->sUrl = $sUrl;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->sUrl;
    }

    /**
     * @param $sUrl
     *
     * @return bool
     */
    private function isValid($sUrl)
    {
        return filter_var($sUrl, FILTER_VALIDATE_URL) !== false && strlen($sUrl) <= $this->getMaxImageLength();
    }

    /**
     * Images length are longer. It multiples the regular URL length by 2.
     *
     * @return int
     */
    private function getMaxImageLength()
    {
        return PH7_MAX_URL_LENGTH * 2;
    }
}

Add missing attribute declaration (was made dynamically)


<?php

namespace Visitmedia\FindologicClient;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;

class FindologicClient
{

    private $client;
    private $domain;
    private $shopKey;

    const ACTION_SEARCH = 'index';
    const ACTION_ISALIVE = 'alivetest';

    public function __construct(ClientInterface $client, $domain, $shopKey)
    {
        $this->client = $client;
        $this->domain = $domain;
        $this->shopKey = $shopKey;
    }

    /**
     * @throws RequestException
     * @return bool
     */
    public function isAlive()
    {
        $response = $this->client->get($this->createRequestUrl(static::ACTION_ISALIVE) . '?shopkey=' . $this->shopKey);
        return (string)$response->getBody() === 'alive';
    }

    /**
     * @throws RequestException
     * @param SearchRequest $searchRequest
     * @return SearchResult
     */
    public function sendSearchRequest(SearchRequest $searchRequest)
    {
        $requestUrl = $this->createRequestUrl(static::ACTION_SEARCH) . '?' . $searchRequest->getQuery();
        $response = $this->client->get($requestUrl);
        return new SearchResult($response->getBody());
    }

    private function createRequestUrl($action)
    {
        return 'https://service.findologic.com/ps/' . $this->domain . '/' . $action . '.php';
    }

}

<?php

namespace Visitmedia\FindologicClient;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;

class FindologicClient
{

    private $client;
    private $domain;
    private $shopKey;

    const ACTION_SEARCH = 'index';
    const ACTION_ISALIVE = 'alivetest';

    public function __construct(ClientInterface $client, $domain, $shopKey)
    {
        $this->client = $client;
        $this->domain = $domain;
        $this->shopKey = $shopKey;
    }

    /**
     * @throws RequestException
     * @return bool
     */
    public function isAlive()
    {
        $response = $this->client->request(
            'GET',
            $this->createRequestUrl(static::ACTION_ISALIVE) . '?shopkey=' . $this->shopKey,
            ['connect_timeout' => 1.0]
        );
        return (string)$response->getBody() === 'alive';
    }

    /**
     * @throws RequestException
     * @param SearchRequest $searchRequest
     * @return SearchResult
     */
    public function sendSearchRequest(SearchRequest $searchRequest)
    {
        $requestUrl = $this->createRequestUrl(static::ACTION_SEARCH) . '?' . $searchRequest->getQuery();
        $response = $this->client->request('GET', $requestUrl, ['connect_timeout' => 3.0]);
        return new SearchResult($response->getBody());
    }

    private function createRequestUrl($action)
    {
        return 'https://service.findologic.com/ps/' . $this->domain . '/' . $action . '.php';
    }

}

Fix missing timeout for request

Fix missing timeout for request


<?php

namespace Wheniwork\OAuth2\Client\Grant;

use League\OAuth2\Client\Grant\GrantInterface;
use League\OAuth2\Client\Token\AccessToken as AccessToken;

class RenewToken implements GrantInterface
{
    /**
     * @var  string
     */
    protected $accessToken;

    /**
     * @param  AccessToken $token
     * @return void
     */
    public function __construct(AccessToken $token = null)
    {
        if ($token) {
            $this->accessToken = $token->accessToken;
        }
    }

    public function __toString()
    {
        return 'renew_token';
    }

    public function prepRequestParams($defaultParams, $params)
    {
        if (empty($params['access_token'])) {
            if (!$this->accessToken) {
                throw new \BadMethodCallException('Missing access_token');
            }
            $params['access_token'] = $this->accessToken;
        }

        return array_merge($defaultParams, $params);
    }

    public function handleResponse($response = [])
    {
        return new AccessToken($response);
    }
}

<?php

namespace Wheniwork\OAuth2\Client\Grant;

use League\OAuth2\Client\Grant\GrantInterface;
use League\OAuth2\Client\Token\AccessToken as AccessToken;

class RenewToken implements GrantInterface
{
    /**
     * @var  string
     */
    protected $accessToken;

    /**
     * @param  AccessToken $token
     */
    public function __construct(AccessToken $token = null)
    {
        if ($token) {
            $this->accessToken = $token->accessToken;
        }
    }

    public function __toString()
    {
        return 'renew_token';
    }

    public function prepRequestParams($defaultParams, $params)
    {
        if (empty($params['access_token'])) {
            if (!$this->accessToken) {
                throw new \BadMethodCallException('Missing access_token');
            }
            $params['access_token'] = $this->accessToken;
        }

        return array_merge($defaultParams, $params);
    }

    public function handleResponse($response = [])
    {
        return new AccessToken($response);
    }
}

Remove unnecessary @return doc for constructor


<?php namespace Vinelab\ITunes;

use Illuminate\Support\ServiceProvider;

class ITunesServiceProvider extends ServiceProvider {

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

	/**
	 * 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 Vinelab\ITunes;

use Illuminate\Support\ServiceProvider;

class ITunesServiceProvider 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->package('vinelab/itunes');
	}

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

		$this->app->register('Vinelab\Http\HttpServiceProvider');
		$this->app['vinelab.itunes'] = $this->app->share(function(){
			return new Agent($this->app['config'], $this->app['cache'], $this->app['vinelab.httpclient']);
		});

		$this->app->booting(function() {

			$loader = \Illuminate\Foundation\AliasLoader::getInstance();
			$loader->alias('ITunes', 'Vinelab\ITunes\Facades\Agent');
		});
	}

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

}

Update Service Provider - Add @method boot and populate the ITunes class


<?php

/**
 * Copyright 2014 SURFnet bv
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\StepupRa\RaBundle\Command;

use Surfnet\StepupRa\RaBundle\VettingProcedure;
use Symfony\Component\Validator\Constraints as Assert;

class VerifyPhoneNumberCommand
{
    /**
     * @Assert\NotBlank(message="ra.verify_phone_number_command.challenge.may_not_be_empty")
     * @Assert\Type(type="string", message="ra.verify_phone_number_command.challenge.must_be_string")
     *
     * @var string
     */
    public $challenge;
}

<?php

/**
 * Copyright 2014 SURFnet bv
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\StepupRa\RaBundle\Command;

use Symfony\Component\Validator\Constraints as Assert;

class VerifyPhoneNumberCommand
{
    /**
     * @Assert\NotBlank(message="ra.verify_phone_number_command.challenge.may_not_be_empty")
     * @Assert\Type(type="string", message="ra.verify_phone_number_command.challenge.must_be_string")
     *
     * @var string
     */
    public $challenge;

    /**
     * @var string
     */
    public $phoneNumber;
}

Implement field that was required in Service


<?php

namespace spec\FluxBB\Core;

use Illuminate\Contracts\Events\Dispatcher;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use FluxBB\Core\Action;

class ActionSpec extends ObjectBehavior
{
    function it_can_raise_events(Dispatcher $dispatcher)
    {
        $this->beAnInstanceOf('spec\FluxBB\Core\EventAction');

        $dispatcher->fire('stdClass', [new \stdClass()])->shouldBeCalled();

        $this->setEvents($dispatcher);
        $this->execute();
    }

    function it_always_returns_responses()
    {
        $this->beAnInstanceOf('spec\FluxBB\Core\EmptyAction');

        $this->execute()->shouldReturnAnInstanceOf('FluxBB\Server\Response');
    }
}

class EmptyAction extends Action
{
    protected function run()
    { }
}

class EventAction extends Action
{
    protected function run()
    {
        $this->raise(new \stdClass());
    }
}

<?php

namespace spec\FluxBB\Core;

use FluxBB\Server\Response;
use Illuminate\Contracts\Events\Dispatcher;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use FluxBB\Core\Action;

class ActionSpec extends ObjectBehavior
{
    function it_always_returns_responses()
    {
        $this->beAnInstanceOf('spec\FluxBB\Core\EmptyAction');

        $this->execute()->shouldReturnAnInstanceOf('FluxBB\Server\Response');
    }

    function it_can_access_input()
    {
        $this->beAnInstanceOf('spec\FluxBB\Core\InputAction');

        $this->execute(['foo' => 'bar', 'baz' => 'bam'])->getData()->shouldReturn(['result' => 'barbam']);
    }

    function it_can_raise_events(Dispatcher $dispatcher)
    {
        $this->beAnInstanceOf('spec\FluxBB\Core\EventAction');

        $dispatcher->fire('stdClass', [new \stdClass()])->shouldBeCalled();

        $this->setEvents($dispatcher);
        $this->execute();
    }
}

class EmptyAction extends Action
{
    protected function run()
    { }
}

class InputAction extends Action
{
    protected function run()
    {
        $foo = $this->get('foo');
        $baz = $this->get('baz');
        $result = $foo.$baz;
        return compact('result');
    }
}

class EventAction extends Action
{
    protected function run()
    {
        $this->raise(new \stdClass());
    }
}

Add one more test to make sure input can be accessed.


<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine;

use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager;

class CacheReloader
{
    private $sourceRoot;
    private $cacheManager;
    private $filterManager;

    public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager)
    {
        $this->sourceRoot    = $sourceRoot;
        $this->cacheManager  = $cacheManager;
        $this->filterManager = $filterManager;
    }

    public function reloadFor($file, $force = false)
    {
        $paths = [];

        stream_is_local($file) && ($file = realpath($file));

        foreach ($this->filterManager->getFilterNames() as $filter) {
            $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot);
            stream_is_local($prefix) && ($prefix = realpath($prefix));

            if (0 !== strpos($file, $prefix)) {
                continue;
            }

            $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force);
        }

        return $paths;
    }
}

<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine;

use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager;

class CacheReloader
{
    private $sourceRoot;
    private $cacheManager;
    private $filterManager;

    public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager)
    {
        $this->sourceRoot    = $sourceRoot;
        $this->cacheManager  = $cacheManager;
        $this->filterManager = $filterManager;
    }

    public function reloadFor($file, $force = false)
    {
        $paths = [];

        stream_is_local($file) && ($file = realpath($file));

        foreach ($this->filterManager->getFilterNames() as $filter) {
            $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot);
            stream_is_local($prefix) && ($prefix = realpath($prefix));

            if (0 !== strpos($file, $prefix)) {
                continue;
            }

            $source = substr($file, strlen($prefix));

            $paths[$filter] = $this->cacheManager->cacheImage('', $source, $filter, $force);
        }

        return $paths;
    }
}

Create new local $source variable

Create new local $source variable

This was done to make clear what we're doing.


<?php

/**
 * Simple support class for reading and writing deploynaut job logs
 */
class DeploynautLogFile {
	protected $logFile;

	public function __construct($logFile) {
		$this->logFile = DEPLOYNAUT_LOG_PATH . '/' . $logFile;
	}

	public function write($message) {
		error_log('['.date('Y-m-d H:i:s').'] ' . $message .PHP_EOL, 3, $this->logFile);
		@chmod($this->logFile, 0666);
	}

	public function exists() {
		return file_exists($this->logFile);
	}

	public function content() {
		return file_get_contents($this->logFile);
	}

}

<?php

/**
 * Simple support class for reading and writing deploynaut job logs
 */
class DeploynautLogFile {
	protected $logFile;

	public function __construct($logFile) {
		$this->logFile = DEPLOYNAUT_LOG_PATH . '/' . $logFile;
	}

	public function getLogFile() {
		return $this->logFile;
	}

	public function write($message) {
		error_log('['.date('Y-m-d H:i:s').'] ' . $message .PHP_EOL, 3, $this->logFile);
		@chmod($this->logFile, 0666);
	}

	public function exists() {
		return file_exists($this->logFile);
	}

	public function content() {
		return file_get_contents($this->logFile);
	}

}

Add getter for retrieving the log file path.


<?php
    /**
     * Main Controller
     *
     * @package     MagicPHP
     * @author      André Ferreira <andrehrf@gmail.com>
     * @link        https://github.com/magicphp/magicphp MagicPHP(tm)
     * @license     MIT License (http://www.opensource.org/licenses/mit-license.php)
     */

    if($_SERVER["REMOTE_ADDR"] == "127.0.0.1" || $_SERVER["REMOTE_ADDR"] == "::1"){
        ini_set("display_errors", "on");
        error_log(E_ERROR);
    }

    if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php"))
        require_once(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php");

    require_once(__DIR__ . DIRECTORY_SEPARATOR . "bootstrap.php");
    Bootstrap::Start();

    if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "routes.php"))
        require_once(__DIR__ . DIRECTORY_SEPARATOR . "routes.php");

    Bootstrap::AutoLoad("settings");
    Routes::Parse();

<?php
    /**
     * Main Controller
     *
     * @package     MagicPHP
     * @author      André Ferreira <andrehrf@gmail.com>
     * @link        https://github.com/magicphp/magicphp MagicPHP(tm)
     * @license     MIT License (http://www.opensource.org/licenses/mit-license.php)
     */

    if($_SERVER["REMOTE_ADDR"] == "127.0.0.1" || $_SERVER["REMOTE_ADDR"] == "::1"){
        ini_set("display_errors", "on");
        error_reporting(E_ERROR);
    }

    if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php"))
        require_once(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php");

    require_once(__DIR__ . DIRECTORY_SEPARATOR . "bootstrap.php");
    Bootstrap::Start();

    if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "routes.php"))
        require_once(__DIR__ . DIRECTORY_SEPARATOR . "routes.php");

    Bootstrap::AutoLoad("settings");
    Routes::Parse();

Change of function to error_reporting

Change of function to error_reporting


Fix the path for generated models.

Fix the path for generated models.


<?php

// IMPORTANT!!! Require composer autoload
require_once 'vendor/autoload.php';
require_once 'vendor/taviroquai/architectphp/aliases.php';

// IMPORTANT!!! Give configuration file and run application
$config = "config/development.xml";
$arch = new \Arch\App($config);
$arch->run();

<?php

// IMPORTANT!!! Require composer autoload
require_once 'vendor/autoload.php';
require_once 'vendor/taviroquai/architectphp/aliases.php';

// IMPORTANT!!! Give configuration file and run application
$config = "config/development.xml";
$arch = new \Arch\App();
$arch->getConfig()->load($config);
$arch->run();

Load configuration manually as of version 0.16.0


<?php

namespace Installer\Handlers;

use Installer\Helpers\File;

final class CleanerHandler extends AbstractHandler implements HandlerInterface
{
    public function execute()
    {
        $this->write('');
        $this->writeHeader('Cleaning up <info>(also something you will forget)</info>.');

        File::remove(File::INSTALLER);

        if($this->askConfirmation('Do you want to remove the \'paragonie/random_compat\' package?'))
        {
            exec(
                escapeshellcmd(
                    sprintf(
                        'composer remove %s -d "%s" ',
                        escapeshellarg('paragonie/random_compat'),
                        escapeshellarg(__DIR__ . '/../../')
                    )
                )
            );
        }

        $this->write('You are ready to rock!');
    }
}

<?php

namespace Installer\Handlers;

use Installer\Helpers\File;

final class CleanerHandler extends AbstractHandler implements HandlerInterface
{
    public function execute()
    {
        $this->write('');
        $this->writeHeader('Cleaning up <info>(also something you will forget)</info>.');

        if($this->askConfirmation('Do you want to remove the \'paragonie/random_compat\' package?'))
        {
            exec(
                escapeshellcmd(
                    sprintf(
                        'composer remove %s -d "%s" ',
                        escapeshellarg('paragonie/random_compat'),
                        escapeshellarg(__DIR__ . '/../../')
                    )
                )
            );
        }

        File::remove(File::INSTALLER);

        $this->write('You are ready to rock!');
    }
}

Move deletion of installer folder to the end


<?php

namespace Tests\SitemapPlugin\Controller;

use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;

/**
 * @author Stefan Doorn <stefan@efectos.nl>
 */
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
    /**
     * @before
     */
    public function setUpDatabase()
    {
        parent::setUpDatabase();

        $root = new Taxon();
        $root->setCurrentLocale('en_US');
        $root->setName('Root');
        $root->setCode('root');
        $root->setSlug('root');
        $this->getEntityManager()->persist($root);

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Test');
        $taxon->setCode('test-code');
        $taxon->setSlug('test');
        $taxon->setParent($root);
        $this->getEntityManager()->persist($taxon);

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Mock');
        $taxon->setCode('mock-code');
        $taxon->setSlug('mock');
        $taxon->setParent($root);
        $this->getEntityManager()->persist($taxon);

        $this->getEntityManager()->flush();
    }

    public function testShowActionResponse()
    {
        $this->client->request('GET', '/sitemap/taxons.xml');

        $response = $this->client->getResponse();

        $this->assertResponse($response, 'show_sitemap_taxons');
    }
}

<?php

namespace Tests\SitemapPlugin\Controller;

use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;

/**
 * @author Stefan Doorn <stefan@efectos.nl>
 */
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
    /**
     * @before
     */
    public function setUpDatabase()
    {
        parent::setUpDatabase();

        $root = new Taxon();
        $root->setCurrentLocale('en_US');
        $root->setName('Root');
        $root->setCode('root');
        $root->setSlug('root');

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Test');
        $taxon->setCode('test-code');
        $taxon->setSlug('test');
        $taxon->setParent($root);
        $this->getEntityManager()->persist($taxon);

        $taxon = new Taxon();
        $taxon->setCurrentLocale('en_US');
        $taxon->setName('Mock');
        $taxon->setCode('mock-code');
        $taxon->setSlug('mock');
        $taxon->setParent($root);
        $this->getEntityManager()->persist($taxon);

        $this->getEntityManager()->persist($root);

        $this->getEntityManager()->flush();
    }

    public function testShowActionResponse()
    {
        $this->client->request('GET', '/sitemap/taxons.xml');

        $response = $this->client->getResponse();

        $this->assertResponse($response, 'show_sitemap_taxons');
    }
}

Save taxon root at end

Save taxon root at end


<?php

declare(strict_types=1);

namespace Roave\Signature;

use Roave\Signature\Encoder\EncoderInterface;
use Roave\Signature\Hasher\HasherInterface;

final class FileContentChecker implements CheckerInterface
{
    /**
     * @var EncoderInterface
     */
    private $encoder;

    /**
     * @var HasherInterface
     */
    private $hasher;

    /**
     * {@inheritDoc}
     */
    public function __construct(EncoderInterface $encoder, HasherInterface $hasher)
    {
        $this->encoder = $encoder;
        $this->hasher  = $hasher;
    }

    /**
     * {@inheritDoc}
     */
    public function check(string $phpCode)
    {
        if (! preg_match('{Roave/Signature:\s+([a-zA-Z0-9\/=]+)}', $phpCode, $matches)) {
            return false;
        }

        // @todo extract this logic for get rid of signature
        $codeWithoutSignature = array_reduce(
            explode(PHP_EOL, $phpCode),
            function (?string $carry, ?string $currentLine): string {

                // if current line is the signature line, we just ignore it
                if (preg_match('{Roave/Signature: (\w)}', $currentLine)) {
                    return $carry;
                }

                if (null === $carry) {
                    return $currentLine;
                }

                if (null !== $currentLine) {
                    return $carry . PHP_EOL . $currentLine;
                }

                return $carry;
            }
        );

        return $this->encoder->verify($codeWithoutSignature, $matches[1]);
    }
}

<?php

declare(strict_types=1);

namespace Roave\Signature;

use Roave\Signature\Encoder\EncoderInterface;
use Roave\Signature\Hasher\HasherInterface;

final class FileContentChecker implements CheckerInterface
{
    /**
     * @var EncoderInterface
     */
    private $encoder;

    /**
     * @var HasherInterface
     */
    private $hasher;

    /**
     * {@inheritDoc}
     */
    public function __construct(EncoderInterface $encoder, HasherInterface $hasher)
    {
        $this->encoder = $encoder;
        $this->hasher  = $hasher;
    }

    /**
     * {@inheritDoc}
     */
    public function check(string $phpCode)
    {
        if (! preg_match('{Roave/Signature:\s+([a-zA-Z0-9\/=]+)}', $phpCode, $matches)) {
            return false;
        }

        // @todo extract this logic for get rid of signature
        $codeWithoutSignature = array_reduce(
            explode(PHP_EOL, $phpCode),
            function (string $carry = null, string $currentLine = null): string {

                // if current line is the signature line, we just ignore it
                if (preg_match('{Roave/Signature: (\w)}', $currentLine)) {
                    return $carry;
                }

                if (null === $carry) {
                    return $currentLine;
                }

                if (null !== $currentLine) {
                    return $carry . PHP_EOL . $currentLine;
                }

                return $carry;
            }
        );

        return $this->encoder->verify($codeWithoutSignature, $matches[1]);
    }
}

Remove php 7.1 `?` operator

Remove php 7.1 `?` operator


<?php
namespace Concrete\Core\Sharing\ShareThisPage;
use Concrete\Core\Sharing\SocialNetwork\Service as SocialNetworkService;

class Service extends SocialNetworkService
{

    public static function getByHandle($ssHandle)
    {
        $services = ServiceList::get();
        foreach($services as $s) {
            if ($s->getHandle() == $ssHandle) {
                return $s;
            }
        }
    }

    public function getServiceLink()
    {
        $c = \Page::getCurrentPage();
        if (is_object($c) && !$c->isError()) {
            $url = urlencode($c->getCollectionLink(true));
            switch($this->getHandle()) {
                case 'facebook':
                    return "https://www.facebook.com/sharer/sharer.php?u=$url";
                case 'twitter':
                    return "https://www.twitter.com/intent/tweet?url=$url";
                case 'linkedin':
                    $title = urlencode($c->getCollectionName());
                    return "https://www.linkedin.com/shareArticle?mini-true&url={$url}&title={$title}";
                case 'reddit':
                    return "https://www.reddit.com/submit?url={$url}";
                case 'email':
                    $body = urlencode(t("Check out this article on %s:\n\n%s\n%s", SITE, $title, urldecode($url)));
                    $subject = urlencode(t('Thought you\'d enjoy this article.'));
                    return "mailto:?body={$body}&subject={$subject}";
            }
        }
    }

}

<?php
namespace Concrete\Core\Sharing\ShareThisPage;
use Concrete\Core\Sharing\SocialNetwork\Service as SocialNetworkService;
use Config;

class Service extends SocialNetworkService
{

    public static function getByHandle($ssHandle)
    {
        $services = ServiceList::get();
        foreach($services as $s) {
            if ($s->getHandle() == $ssHandle) {
                return $s;
            }
        }
    }

    public function getServiceLink()
    {
        $c = \Page::getCurrentPage();
        if (is_object($c) && !$c->isError()) {
            $url = urlencode($c->getCollectionLink(true));
            switch($this->getHandle()) {
                case 'facebook':
                    return "https://www.facebook.com/sharer/sharer.php?u=$url";
                case 'twitter':
                    return "https://www.twitter.com/intent/tweet?url=$url";
                case 'linkedin':
                    $title = urlencode($c->getCollectionName());
                    return "https://www.linkedin.com/shareArticle?mini-true&url={$url}&title={$title}";
                case 'reddit':
                    return "https://www.reddit.com/submit?url={$url}";
                case 'email':
                    $body = rawurlencode(t("Check out this article on %s:\n\n%s\n%s", Config::get('concrete.site'), $c->getCollectionName(), urldecode($url)));
                    $subject = rawurlencode(t('Thought you\'d enjoy this article.'));
                    return "mailto:?body={$body}&subject={$subject}";
            }
        }
    }

}

Fix share via email link

Fix share via email link


<?php

use Cake\Core\Configure;
use Cake\Core\Plugin;

/**
 * Dashboard URL
 */
Configure::write('Croogo.dashboardUrl', array(
	'admin' => true,
	'plugin' => 'extensions',
	'controller' => 'extensions_dashboard',
	'action' => 'index',
));

if (!Plugin::loaded('Migrations')) {
	Plugin::load('Migrations', ['autoload' => true, 'classBase' => false]);
}
if (!Plugin::loaded('Settings')) {
	Plugin::load('Settings', ['bootstrap' => true, 'classBase' => false]);
}
if (!Plugin::loaded('Search')) {
	Plugin::load('Search', ['autoload' => true, 'classBase' => false]);
}

<?php

use Cake\Core\Configure;
use Cake\Core\Plugin;

/**
 * Dashboard URL
 */
Configure::write('Croogo.dashboardUrl', array(
	'admin' => true,
	'plugin' => 'extensions',
	'controller' => 'extensions_dashboard',
	'action' => 'index',
));

if (!Plugin::loaded('Migrations')) {
	Plugin::load('Migrations', ['autoload' => true, 'classBase' => false]);
}
if (!Plugin::loaded('Croogo/Settings')) {
	Plugin::load('Croogo/Settings', ['bootstrap' => true, 'path' => Plugin::path('Croogo/Croogo') . '..' . DS . 'Settings' . DS]);
}
if (!Plugin::loaded('Search')) {
	Plugin::load('Search', ['autoload' => true, 'classBase' => false]);
}

Make the Settings core plugin loadable

Make the Settings core plugin loadable


<?php
/**
 * Index page controller
 *
 * @package    Anqh
 * @author     Antti Qvickström
 * @copyright  (c) 2009 Antti Qvickström
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 */
class Index_Controller extends Website_Controller {

	public function index() {
		$this->page_title = __('Welcome to :site', array(':site' => Kohana::config('site.site_name')));

		// Display news feed
		$newsfeed = new NewsFeed($this->user);
		$newsfeed->max_items = 25;
		widget::add('main', View::factory('generic/newsfeed', array('newsfeed' => $newsfeed->as_array())));

	}

}

<?php
/**
 * Index page controller
 *
 * @package    Anqh
 * @author     Antti Qvickström
 * @copyright  (c) 2009 Antti Qvickström
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 */
class Index_Controller extends Website_Controller {

	/**
	 * Index constructor
	 */
	function __construct() {
		parent::__construct();

		$this->page_id = 'home';
	}

	/**
	 * Home page
	 */
	public function index() {
		$this->page_title = __('Welcome to :site', array(':site' => Kohana::config('site.site_name')));

		// Display news feed
		$newsfeed = new NewsFeed($this->user);
		$newsfeed->max_items = 25;
		widget::add('main', View::factory('generic/newsfeed', array('newsfeed' => $newsfeed->as_array())));

	}

}

Set page id for menu

Set page id for menu


<?php
/**
 * CodeMOOC QuizzleBot
 * ===================
 * UWiClab, University of Urbino
 * ===================
 * Command message processing functionality.
 */

/**
 * Processes commands.
 * @return bool True if the message was handled.
 */
function process_command($context, $text) {
    $command = extract_command($text);

    if($command === 'new' && $context->is_abmin()) {
        $last_open_riddle = get_last_open_riddle_id();
        if($last_open_riddle === null) {
            // New question!
            $new_riddle_id = open_riddle();

            Logger::info("New riddle ID: {$new_riddle_id}", __FILE__, $context);

            $context->reply(QUIZ_CREATED_OK);
        }
        else {
            $context->reply(QUIZ_ALREADY_OPEN);
        }

        return true;
    }
    else if($command === 'help') {
        $context->reply(COMMAND_HELP);

        return true;
    }

    return false;
}

<?php
/**
 * CodeMOOC QuizzleBot
 * ===================
 * UWiClab, University of Urbino
 * ===================
 * Command message processing functionality.
 */

/**
 * Processes commands.
 * @return bool True if the message was handled.
 */
function process_command($context, $text) {
    $command = extract_command($text);

    if($command === 'new' && $context->is_abmin()) {
        $last_open_riddle = get_last_open_riddle_id();
        if($last_open_riddle === null) {
            // New question!
            $new_riddle_data = open_riddle();

            Logger::info("New riddle ID: {$new_riddle_data[0]}", __FILE__, $context);

            $riddle_deeplink_url = get_riddle_qrcode_url($new_riddle_data[0]);

            telegram_send_photo($context->get_telegram_chat_id(), $riddle_deeplink_url,
                QUIZ_CREATED_OK . $new_riddle_data[1]);
        }
        else {
            $context->reply(QUIZ_ALREADY_OPEN);
        }

        return true;
    }
    else if($command === 'help') {
        $context->reply(COMMAND_HELP);

        return true;
    }

    return false;
}

Send QR Code when riddle created

Send QR Code when riddle created


<?php
namespace phtamas\yii2\imagecontroller;

use yii\base\Action as BaseAction;
use yii\web\NotFoundHttpException;

class Action extends BaseAction
{
    /**
     * @var \phtamas\yii2\imageprocessor\Component
     */
    public $imageProcessor;

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

    /**
     * @var bool
     */
    public $save = false;

    /**
     * @var null|string
     */
    public $destinationDir;

    public function run($filename)
    {
        $filename = basename($filename);
        $sourcePath = \Yii::getAlias($this->sourceDir) . '/' . $filename;
        if (!is_file($sourcePath)) {
            throw new NotFoundHttpException();
        }
        if ($this->save) {
            $this->imageProcessor->saveAndSend(
                \Yii::getAlias($this->sourceDir) . '/' . $filename,
                \Yii::getAlias($this->destinationDir) . '/' . $filename,
                pathinfo($filename, PATHINFO_EXTENSION),
                $this->id
            );
        } else {
            $this->imageProcessor->send(
                \Yii::getAlias($this->sourceDir) . '/' . $filename,
                pathinfo($filename, PATHINFO_EXTENSION),
                $this->id
            );
        }
    }
}

<?php
namespace phtamas\yii2\imagecontroller;

use yii\base\Action as BaseAction;
use yii\web\NotFoundHttpException;

class Action extends BaseAction
{
    /**
     * @var \phtamas\yii2\imageprocessor\Component
     */
    public $imageProcessor;

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

    /**
     * @var bool
     */
    public $save = false;

    /**
     * @var null|string
     */
    public $destinationDir;

    public function run($filename)
    {
        $filename = basename($filename);
        $sourceDir = \Yii::getAlias($this->sourceDir);
        $destinationDir = \Yii::getAlias($this->destinationDir);
        $sourcePath = $sourceDir . '/' . $filename;
        if (!is_file($sourcePath)) {
            throw new NotFoundHttpException();
        }
        if ($this->save) {
            if (!is_dir($destinationDir)) {
                mkdir($destinationDir);
            }
            $this->imageProcessor->saveAndSend(
                $sourcePath,
                $destinationDir . '/' . $filename,
                pathinfo($filename, PATHINFO_EXTENSION),
                $this->id
            );
        } else {
            $this->imageProcessor->send(
                $sourcePath,
                pathinfo($filename, PATHINFO_EXTENSION),
                $this->id
            );
        }
    }
}

Create destination directory if not exists