<?php

namespace Tests\Entities;

use Illuminate\Database\Eloquent\Model;
use Tests\Entities\Post;
use Tests\Entities\Comment;

class ChildPost extends Post
{
    protected $table = 'posts';

    public function comments()
    {
        return $this->hasMany(Comment::class, 'post_id');
    }
}

<?php

namespace Tests\Entities;

use Illuminate\Database\Eloquent\Model;
use Tests\Entities\Post;
use Tests\Entities\Comment;

class ChildPost extends Post
{
    protected $table = 'posts';

    public function comments()
    {
        return $this->hasMany('Tests\Entities\Comment', 'post_id');
    }
}

Remove ::class notation for PHP 5.4 support


<?php

if (!function_exists('isConsole')) {
    /**
     * @return bool
     */
    function isConsole()
    {
        static $isConsole;

        if (is_null($isConsole)) {
            $isConsole = 'cli' == php_sapi_name();
        }

        return $isConsole;
    }
}

if (!function_exists('breakLine')) {
    /**
     * @return string
     */
    function breakLine()
    {
        static $breakLine;

        if (is_null($breakLine)) {
            $breakLine = isConsole() ? PHP_EOL : '<br/>';
        }

        return $breakLine;
    }
}

<?php

if (!function_exists('env')) {
    /**
     * @param $var
     * @param null $default
     * @return array|false|null|string
     */
    function env($var, $default = null)
    {
        static $loaded = null;

        if (!$loaded) {
            $loaded = true;
            try {
                $dotenv = new Dotenv\Dotenv(__DIR__);
                $dotenv->load();
            } finally {
                // File not exist
                return $default;
            }
        }

        return getenv($var);
    }
}

if (!function_exists('isConsole')) {
    /**
     * @return bool
     */
    function isConsole()
    {
        static $isConsole;

        if (is_null($isConsole)) {
            $isConsole = 'cli' == php_sapi_name();
        }

        return $isConsole;
    }
}

if (!function_exists('breakLine')) {
    /**
     * @return string
     */
    function breakLine()
    {
        static $breakLine;

        if (is_null($breakLine)) {
            $breakLine = isConsole() ? PHP_EOL : '<br/>';
        }

        return $breakLine;
    }
}

Reformat env function, use environment vars


<?php

class dbeng_pdo_sqlite extends dbeng_pdo {
	protected $_conn;

	function __construct() {
		/*
		 * sqlite does not support batch inserts
		 */
		$this->_batchInsertChunks = 1;
    } # ctor

	function connect($host, $user, $pass, $db) {
		try {
			if (!$this->_conn instanceof PDO) {
				$this->_conn = new PDO('sqlite:' . $db);
				$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			} # if
		} catch(PDOException $e) {
				throw new DatabaseConnectionException($e->getMessage(), -1);
		} # catch
	} # connect()

} # class

<?php

class dbeng_pdo_sqlite extends dbeng_pdo {
	protected $_conn;

	function __construct() {
		/*
		 * sqlite does not support batch inserts
		 */
		$this->_batchInsertChunks = 1;
    } # ctor

	function connect($host, $user, $pass, $db) {
		try {
			if (!$this->_conn instanceof PDO) {
				$this->_conn = new PDO('sqlite:' . $db);
				$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$this->_conn->setAttribute(PDO::ATTR_TIMEOUT, 300);
			} # if
		} catch(PDOException $e) {
				throw new DatabaseConnectionException($e->getMessage(), -1);
		} # catch
	} # connect()

} # class

Set timeout to 5 minutes for SQLite. (Needed for some actions on a slow Raspberry Pi.)


<?php

/**
 * (c) Gordon Franke <info@nevalon.de>
 * (c) Thibault Duplessis <thibault.duplessis@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bundle\DoctrineUserBundle\DAO;

interface UserRepositoryInterface
{
    /**
     * Find a user by its id
     * @param   mixed  $id
     * @return  User or null if user does not exist
     */
    public function findOneById($id);

    /**
     * Find a user by its username
     * @param   string  $username
     * @return  User or null if user does not exist
     */
    public function findOneByUsername($username);

    /**
     * Find a user by its email
     * @param   string  $email
     * @return  User or null if user does not exist
     */
    public function findOneByEmail($email);

    /**
     * Find a user by its username or email
     * @param   string  $usernameOrEmail
     * @return  User or null if user does not exist
     */
    public function findOneByUsernameOrEmail($usernameOrEmail);
}

<?php

/**
 * (c) Gordon Franke <info@nevalon.de>
 * (c) Thibault Duplessis <thibault.duplessis@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bundle\DoctrineUserBundle\DAO;

interface UserRepositoryInterface
{
    /**
     * Find a user by its username
     * @param   string  $username
     * @return  User or null if user does not exist
     */
    public function findOneByUsername($username);

    /**
     * Find a user by its email
     * @param   string  $email
     * @return  User or null if user does not exist
     */
    public function findOneByEmail($email);

    /**
     * Find a user by its username or email
     * @param   string  $usernameOrEmail
     * @return  User or null if user does not exist
     */
    public function findOneByUsernameOrEmail($usernameOrEmail);

    /**
     * Get the Entity manager or the Document manager, depending on the db driver
     *
     * @return mixed
     **/
    public function getObjectManager();

    /**
     * Get the class of the User Entity or Document, depending on the db driver
     *
     * @return string a model fully qualified class name
     **/
    public function getObjectClass();
}

Simplify and update the repository interface


!= View::make('decoy::shared.form._header', $__data)->render()

%fieldset
	.legend Reset
	%p Hey #{$user->first_name}.  Enter a new password and we'll log you in.

	!=Former::text('email')
	!=Former::password('password')
	!=Former::password('password_confirmation', 'Password, again')

	.form-actions
		%button(type="submit" class="btn btn-primary") Submit
		%a.btn.btn-default(href=route('decoy::account@login')) Cancel

!=Former::close()

!= View::make('decoy::shared.form._header', $__data)->render()

%fieldset
	.legend Reset
	%p Hey #{$user->first_name}.  Enter a new password and we'll log you in.

	!=Former::hidden('token', $token)
	!=Former::text('email')->value($user->email)
	!=Former::password('password')
	!=Former::password('password_confirmation', 'Password, again')

	.form-actions
		%button(type="submit" class="btn btn-primary") Submit
		%a.btn.btn-default(href=route('decoy::account@login')) Cancel

!=Former::close()

Reset form needs token now

Reset form needs token now


<?php namespace GeneaLabs\LaravelCaffeine\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\View\View;

class Test extends Controller
{
    public function drippedForm() : View
    {
        config()->set('session.lifetime', 1);
        config()->set('genealabs-laravel-caffeine.dripIntervalInMilliSeconds', 50000);

        return view('genealabs-laravel-caffeine::tests.form');
    }

    public function expiredForm() : View
    {
        config()->set('session.lifetime', 1);
        config()->set('genealabs-laravel-caffeine.dripIntervalInMilliSeconds', 300000);

        return view('genealabs-laravel-caffeine.tests.form');
    }
}

<?php namespace GeneaLabs\LaravelCaffeine\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\View\View;

class Test extends Controller
{
    public function drippedForm() : View
    {
        config()->set('session.lifetime', 1);
        config()->set('genealabs-laravel-caffeine.dripIntervalInMilliSeconds', 50000);

        return view('genealabs-laravel-caffeine::tests.form');
    }

    // TODO: figure out a way to test ajax drip
}

Remove unused method in controller

Remove unused method in controller


<?php

/**
 * @package elemental
 */
class ElementUserDefinedForm extends BaseElement {

	private static $has_one = array(
		'Form' => 'UserDefinedForm'
	);

	private static $title = "Form Element";

	public function ElementForm() {
		if($this->Form()->exists()) {
			$controller = new UserDefinedForm_Controller($this->Form());

			$form = $controller->Form();

			return $form;
		}
	}
}

<?php

/**
 * @package elemental
 */
class ElementUserDefinedForm extends BaseElement {

	private static $has_one = array(
		'Form' => 'UserDefinedForm'
	);

	private static $title = "Form Element";

	public function ElementForm() {
		if($this->Form()->exists()) {
			$controller = new UserDefinedForm_Controller($this->Form());

			$current = Controller::curr();

			if($current && $current->getAction() == 'finished') {
				return $controller->renderWith('ReceivedFormSubmission');
			}

			$form = $controller->Form();

			return $form;
		}
	}
}

Handle form submission within element widget.


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/login', 'User\LoginController@showLoginPage');

Route::group(['middleware' => 'auth.user'], function(){
    Route::get('/', 'User\UIController@showIndexPage');
});

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/

Route::get('/login', 'User\LoginController@showLoginPage');

Route::group(['middleware' => ['auth.user']], function(){
    Route::get('/', 'User\UIController@showIndexPage');
});

Change middleware to be in array instead


<?php

namespace UoMCS\OpenBadges\Backend;

class BadgeTest extends DatabaseTestCase
{
  const BADGE_EXISTS_ID = 1;
  const BADGE_DOES_NOT_EXIST_ID = 99999;

  public function testBadgeExistsDB()
  {
    $badge = Badge::get(self::BADGE_EXISTS_ID);
    $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Badge', $badge, 'Could not fetch badge');
    $this->assertEquals(self::BADGE_EXISTS_ID, $badge->data['id']);
  }

  public function testBadgeDoesNotExistDB()
  {
    $badge = Badge::get(self::BADGE_DOES_NOT_EXIST_ID);
    $this->assertNull($badge);
  }

  public function testBadgesUrl()
  {
    $url = WEB_SERVER_BASE_URL . '/badges';

    $client = new \Zend\Http\Client();
    $client->setUri($url);
    $response = $client->send();

    $this->assertTrue($response->isOk(), 'Accessing /badges did not return 2xx code');

    $body = $response->getBody();
    $json_body = json_decode($body, true);

    $this->assertNotNull($json_body, 'Body is not valid JSON');
  }
}

<?php

namespace UoMCS\OpenBadges\Backend;

class BadgeTest extends DatabaseTestCase
{
  const BADGE_EXISTS_ID = 1;
  const BADGE_DOES_NOT_EXIST_ID = 99999;

  public function testBadgeExistsDB()
  {
    $badge = Badge::get(self::BADGE_EXISTS_ID);
    $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Badge', $badge, 'Could not fetch badge');
    $this->assertEquals(self::BADGE_EXISTS_ID, $badge->data['id']);
  }

  public function testBadgeDoesNotExistDB()
  {
    $badge = Badge::get(self::BADGE_DOES_NOT_EXIST_ID);
    $this->assertNull($badge);
  }

  public function testToJson()
  {
    $badge = Badge::get(self::BADGE_EXISTS_ID);
    $data = json_decode($badge->toJson());

    $this->assertNotNull($data, 'Badge->toJson() does not return valid JSON');
  }

  public function testBadgesUrl()
  {
    $url = WEB_SERVER_BASE_URL . '/badges';

    $client = new \Zend\Http\Client();
    $client->setUri($url);
    $response = $client->send();

    $this->assertTrue($response->isOk(), 'Accessing /badges did not return 2xx code');

    $body = $response->getBody();
    $json_body = json_decode($body, true);

    $this->assertNotNull($json_body, 'Body is not valid JSON');
  }
}

Test that Badge->toJson() returns JSON

Test that Badge->toJson() returns JSON


<?php

/**
 * Class BasicTest
 */

class BasicTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);

    }
}

<?php

/**
 * Class BasicTest
 */

class BasicTest extends TestCase
{
    /**
     * A basic test example. May take a minute because the test data is being generated.
     *
     * @slowThreshold 60000
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);

    }
}

Allow tests to run very long.

Allow tests to run very long.


<?php

declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';

array_map('unlink', (array) glob(__DIR__ . '/tmp/*.{php,txt}', GLOB_BRACE));

<?php

declare(strict_types=1);

use Koriym\Attributes\AttributeReader;
use Ray\ServiceLocator\ServiceLocator;

require dirname(__DIR__) . '/vendor/autoload.php';

array_map('unlink', (array) glob(__DIR__ . '/tmp/*.{php,txt}', GLOB_BRACE));

// no annotation in PHP 8
if (PHP_MAJOR_VERSION >= 8) {
    ServiceLocator::setReader(new AttributeReader());
}

Test php8 without annotation reader

Test php8 without annotation reader


<?php
/**
 * Test suite bootstrap.
 *
 * This function is used to find the location of CakePHP whether CakePHP
 * has been installed as a dependency of the plugin, or the plugin is itself
 * installed as a dependency of an application.
 */
$findRoot = function ($root) {
    do {
        $lastRoot = $root;
        $root = dirname($root);
        if (is_dir($root . '/vendor/cakephp/cakephp')) {
            return $root;
        }
    } while ($root !== $lastRoot);

    throw new Exception("Cannot find the root of the application, unable to run tests");
};
$root = $findRoot(__FILE__);
unset($findRoot);

chdir($root);
if (file_exists($root . '/config/bootstrap.php')) {
    require $root . '/config/bootstrap.php';
}

require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php';

\Cake\Core\Plugin::getCollection()->add(new \Robotusers\TableInheritance\Plugin());

Fix phpcs issue about no blank line.

Fix phpcs issue about no blank line.


@extends('layouts.default')

@section('title')
Calendar · Indiana Real Estate Exchangors, Inc.
@stop

@section('content')

2013 Meeting Schedule - Indiana Real Estate Exchangors, Inc.

Normal Meeting Time is 9:00 AM to Noon

Meetings listed in orange are for informational purposes only.

      Date
      Title
      Location

    @each('calendar.event', $events, 'event')

Knights of Columbus

@stop

@extends('layouts.default')

@section('title')
Calendar · Indiana Real Estate Exchangors, Inc.
@stop

@section('content')

2013 Meeting Schedule - Indiana Real Estate Exchangors, Inc.

Normal Meeting Time is 9:00 AM to Noon

Meetings listed in orange are for informational purposes only.

      Date
      Title
      Location

    @each('calendar.event', $events, 'event')

@stop

Remove the google map for Knights of Columbus as IREX will no longer be at that location for their meetings.


<?php

// Init owncloud
require_once '../../lib/base.php';
OC_JSON::checkLoggedIn();
OCP\JSON::callCheck();
OC_JSON::verifyUser();

$l=OC_L10N::get('core');

// Get data
if( isset( $_POST['email'] ) && filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL) ) {
	$email=trim($_POST['email']);
	OC_Preferences::setValue(OC_User::getUser(), 'settings', 'email', $email);
	OC_JSON::success(array("data" => array( "message" => $l->t("Email saved") )));
}else{
	OC_JSON::error(array("data" => array( "message" => $l->t("Invalid email") )));
}

<?php

// Init owncloud
require_once '../../lib/base.php';
OC_JSON::checkLoggedIn();
OCP\JSON::callCheck();

$l=OC_L10N::get('core');

// Get data
if( isset( $_POST['email'] ) && filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL) ) {
	$email=trim($_POST['email']);
	OC_Preferences::setValue(OC_User::getUser(), 'settings', 'email', $email);
	OC_JSON::success(array("data" => array( "message" => $l->t("Email saved") )));
}else{
	OC_JSON::error(array("data" => array( "message" => $l->t("Invalid email") )));
}

Revert "Verify user login before changing the password reset mail"

This reverts commit 9aa9110fd906bc9191adbb129bf421ede77ccad7.


        {{ $notifications->count() }}

                    <?php if ($notifications->count() === 0): ?>

                            No notifications

                    <?php endif; ?>
                    <?php foreach ($notifications as $notification): ?>

                        link }}">

                                icon_class }}">

                                {{ $notification->title }}
                                 {{ $notification->time_ago }}

{{ $notification->message }}

                    <?php endforeach; ?>

        {{ $notifications->count() }}

                    <?php if ($notifications->count() === 0): ?>

                            {{ trans('notification::messages.no notifications') }}

                    <?php endif; ?>
                    <?php foreach ($notifications as $notification): ?>

                        link }}">

                                icon_class }}">

                                {{ $notification->title }}
                                 {{ $notification->time_ago }}

{{ $notification->message }}

                    <?php endforeach; ?>

Make empty notifications message localisable


<?php

namespace Grafika\Gd\Filter;

use Grafika\FilterInterface;
use Grafika\Gd\Image;

/**
 * Blurs the image
 */
class Blur implements FilterInterface
{

    protected $amount;

    public function __construct($amount = 1)
    {
        $this->amount = (int) $amount;
    }

    /**
     * @param Image $image
     *
     * @return Image
     */
    public function apply($image)
    {

        // Localize vars
        $width  = $image->getWidth();
        $height = $image->getHeight();

        for ($i=0; $i < $this->amount; $i++) {
            imagefilter($image->getCore(), IMG_FILTER_GAUSSIAN_BLUR);
        }

        $type = $image->getType();
        $file = $image->getImageFile();

        return new Image($image->getCore(), $file, $width, $height, $type); // Create and return new image with updated core
    }
}

<?php

namespace Grafika\Gd\Filter;

use Grafika\FilterInterface;
use Grafika\Gd\Image;

/**
 * Blurs the image
 */
class Blur implements FilterInterface
{

    protected $amount;

    public function __construct($amount = 1)
    {
        $this->amount = (int) $amount;
    }

    /**
     * @param Image $image
     *
     * @return Image
     */
    public function apply($image)
    {
        for ($i=0; $i < $this->amount; $i++) {
            imagefilter($image->getCore(), IMG_FILTER_GAUSSIAN_BLUR);
        }
        return $image;
    }
}

Return image instead of creating a new instance


<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * Helper class to work with Kohana Profiler
 *
 * @package Aurora
 * @author Samuel Demirdjian
 * @copyright (c) 2013, Samuel Demirdjian
 * @license http://license.enov.ws/mit MIT
 *
 */
class Aurora_Aurora_Profiler
{

	/**
	 * @var string The profiling category under which benchmarks will appear
	 */
	protected static $category = 'Aurora';
	/**
	 * Add a profiling mark and start counter
	 *
	 * @param Aurora $aurora
	 * @param string $function
	 * @return string benchmark id in Profiler
	 */
	public static function start($aurora, $function) {
		$name = Aurora_Type::cname($aurora) . '::' . $function;
		$benchmark =
		  (Kohana::$profiling === TRUE) ?
		  Profiler::start(static::$category, $name) :
		  FALSE;
		return $benchmark;
	}
	/**
	 * Stop a profiling mark
	 *
	 * @param string $benchmark
	 */
	public static function stop($benchmark) {
		if (!empty($benchmark)) {
			// Stop the benchmark
			Profiler::stop($benchmark);
		}
	}
	/**
	 * Delete a profiling mark
	 *
	 * @param string $benchmark
	 */
	public static function delete($benchmark) {
		if (!empty($benchmark)) {
			// Delete the benchmark
			Profiler::delete($benchmark);
		}
	}
}

<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * Helper class to work with Kohana Profiler
 *
 * @package Aurora
 * @author Samuel Demirdjian
 * @copyright (c) 2013, Samuel Demirdjian
 * @license http://license.enov.ws/mit MIT
 *
 */
class Aurora_Aurora_Profiler
{

	/**
	 * @var string The profiling category under which benchmarks will appear
	 */
	protected static $category = 'Aurora';
	/**
	 * Add a profiling mark and start counter
	 *
	 * @param Aurora $aurora
	 * @param string $function
	 * @return string benchmark id in Profiler
	 */
	public static function start($aurora, $function) {
		if (empty($aurora) OR empty($function))
			return FALSE;
		$name = Aurora_Type::cname($aurora) . '::' . $function;
		$benchmark =
		  (Kohana::$profiling === TRUE) ?
		  Profiler::start(static::$category, $name) :
		  FALSE;
		return $benchmark;
	}
	/**
	 * Stop a profiling mark
	 *
	 * @param string $benchmark
	 */
	public static function stop($benchmark) {
		if (!empty($benchmark)) {
			// Stop the benchmark
			Profiler::stop($benchmark);
		}
	}
	/**
	 * Delete a profiling mark
	 *
	 * @param string $benchmark
	 */
	public static function delete($benchmark) {
		if (!empty($benchmark)) {
			// Delete the benchmark
			Profiler::delete($benchmark);
		}
	}
}

Throw an error when getting common name instead of FALSE

CNAME or common/resource name is needed to construct instances of
Aurora/Model/Collection. Throwing an error will help us debug our code
sooner.


<?php

require_once dirname(__FILE__) . '/../../bootstrap.php';

class Elastica_LogTest extends Elastica_Test
{
    public function testSetLogConfigPath()
    {
        $logPath = '/tmp/php.log';
        $client = new Elastica_Client(array('log' => $logPath));
        $this->assertEquals($logPath, $client->getConfig('log'));
    }

    public function testSetLogConfigEnable()
    {
        $client = new Elastica_Client(array('log' => true));
        $this->assertTrue($client->getConfig('log'));
    }

    public function testEmptyLogConfig()
    {
        $client = new Elastica_Client();
        $this->assertEmpty($client->getConfig('log'));
    }

    public function testGetLastMessage()
    {
        $client = new Elastica_Client(array('log' => '/tmp/php.log'));
        $log = new Elastica_Log($client);
        $message = 'hello world';

        $log->log($message);

        $this->assertEquals($message, $log->getLastMessage());
    }

    public function testGetLastMessage2()
    {
        $client = new Elastica_Client(array('log' => true));
        $log = new Elastica_Log($client);

        // Set log path temp path as otherwise test fails with output
        $errorLog = ini_get('error_log');
        ini_set('error_log', sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php.log');

        $message = 'hello world';

        $log->log($message);

        ini_set('error_log', $errorLog);

        $this->assertEquals($message, $log->getLastMessage());
    }
}

<?php

require_once dirname(__FILE__) . '/../../bootstrap.php';

class Elastica_LogTest extends Elastica_Test
{
    public function testSetLogConfigPath()
    {
        $logPath = '/tmp/php.log';
        $client = new Elastica_Client(array('log' => $logPath));
        $this->assertEquals($logPath, $client->getConfig('log'));
    }

    public function testSetLogConfigEnable()
    {
        $client = new Elastica_Client(array('log' => true));
        $this->assertTrue($client->getConfig('log'));
    }

    public function testEmptyLogConfig()
    {
        $client = new Elastica_Client();
        $this->assertEmpty($client->getConfig('log'));
    }

    public function testGetLastMessage()
    {
        $log = new Elastica_Log('/tmp/php.log');
        $message = 'hello world';

        $log->log($message);

        $this->assertEquals($message, $log->getLastMessage());
    }

    public function testGetLastMessage2()
    {
        $client = new Elastica_Client(array('log' => true));
        $log = new Elastica_Log($client);

        // Set log path temp path as otherwise test fails with output
        $errorLog = ini_get('error_log');
        ini_set('error_log', sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php.log');

        $message = 'hello world';

        $log->log($message);

        ini_set('error_log', $errorLog);

        $this->assertEquals($message, $log->getLastMessage());
    }
}

Fix Elastica_Log param. Remove Elastica_Client here


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Tests\Api;

use ApiTestCase\JsonApiTestCase as BaseJsonApiTestCase;

abstract class JsonApiTestCase extends BaseJsonApiTestCase
{
    public const CONTENT_TYPE_HEADER = ['CONTENT_TYPE' => 'application/ld+json', 'HTTP_ACCEPT' => 'application/ld+json'];

    public function __construct(?string $name = null, array $data = [], string $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        $this->dataFixturesPath = __DIR__ . '/DataFixtures/ORM';
        $this->expectedResponsesPath = __DIR__ . '/Responses/Expected';
    }

    protected function get($id)
    {
        if (method_exists(static::class, 'getContainer')) {
            return static::getContainer()->get($id);
        }

        return parent::get($id);
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Tests\Api;

use ApiTestCase\JsonApiTestCase as BaseJsonApiTestCase;

abstract class JsonApiTestCase extends BaseJsonApiTestCase
{
    public const CONTENT_TYPE_HEADER = ['CONTENT_TYPE' => 'application/ld+json', 'HTTP_ACCEPT' => 'application/ld+json'];

    public function __construct(?string $name = null, array $data = [], string $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        $this->dataFixturesPath = __DIR__ . '/DataFixtures/ORM';
        $this->expectedResponsesPath = __DIR__ . '/Responses/Expected';
    }

    protected function get($id)
    {
        if (property_exists(static::class, 'container')) {
            return static::$container->get($id);
        }

        return parent::get($id);
    }
}

[API] Fix problem with getting command bus from container in api test case


<?php

declare(strict_types=1);

namespace Becklyn\RouteTreeBundle;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 *
 */
class BecklynRouteTreeBundle extends Bundle
{
    /**
     * @inheritDoc
     */
    public function getContainerExtension ()
    {
        return new class() extends Extension {
            /**
             * @inheritDoc
             */
            public function load(array $configs, ContainerBuilder $container) : void
            {
                $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
                $loader->load('services.yaml');
            }
        };
    }
}

<?php

declare(strict_types=1);

namespace Becklyn\RouteTreeBundle;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 *
 */
class BecklynRouteTreeBundle extends Bundle
{
    /**
     * @inheritDoc
     */
    public function getContainerExtension ()
    {
        return new class() extends Extension {
            /**
             * @inheritDoc
             */
            public function load(array $configs, ContainerBuilder $container) : void
            {
                $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/Resources/config'));
                $loader->load('services.yaml');
            }

            /**
             * @inheritDoc
             */
            public function getAlias ()
            {
                return "becklyn_route_tree";
            }
        };
    }
}

Fix compatibility issues with anonymous classes in bundle


<?php

/**
 * @license MIT
 * @license http://opensource.org/licenses/MIT
 */

namespace Slim\PDO\Clause;

/**
 * Class LimitClause.
 *
 * @author Fabian de Laender <fabian@faapz.nl>
 */
class LimitClause extends ClauseContainer
{
    /**
     * @var null
     */
    private $limit = null;

    /**
     * @param int $number
     * @param int $offset
     */
    public function limit($number, $offset = 0)
    {
        if (!is_int($number) || !is_int($offset)) {
            trigger_error('Expects parameters as integers', E_USER_ERROR);
        }

        if ($offset >= 0) {
            $this->limit = intval($number).' OFFSET '.intval($offset);
        } elseif ($number >= 0) {
            $this->limit = intval($number);
        }
    }

    /**
     * @return string
     */
    public function __toString()
    {
        if (is_null($this->limit)) {
            return '';
        }

        return ' LIMIT '.$this->limit;
    }
}

<?php

/**
 * @license MIT
 * @license http://opensource.org/licenses/MIT
 */

namespace Slim\PDO\Clause;

/**
 * Class LimitClause.
 *
 * @author Fabian de Laender <fabian@faapz.nl>
 */
class LimitClause extends ClauseContainer
{
    /**
     * @var null
     */
    private $limit = null;

    /**
     * @param int $number
     * @param int $offset
     */
    public function limit($number, $offset = 0)
    {
        if (!is_int($number) || (!is_null($offset) && !is_int($offset))) {
            trigger_error('Expects parameters as integers', E_USER_ERROR);
        }

        if (!is_null($offset) && $offset >= 0) {
            $this->limit = intval($number).' OFFSET '.intval($offset);
        } elseif ($number >= 0) {
            $this->limit = intval($number);
        }
    }

    /**
     * @return string
     */
    public function __toString()
    {
        if (is_null($this->limit)) {
            return '';
        }

        return ' LIMIT '.$this->limit;
    }
}

Check whether is null before checking if is integer


<?php

namespace YMLParser\Driver;

class XMLReader implements DriverInterface
{

    private $xml;

    public function getCategories() {
        return [];
    }

    public function getCurrencies() {
        return [];
    }

    public function getOffers(\Closure $filter = null) {
        return [];
    }

    public function open($filename) {

        $this->xml = new \XMLReader();
        return $this->xml->open($filename);
    }

    public function countOffers(\Closure $filter) {
        return 0;
    }
}

<?php

namespace YMLParser\Driver;

class XMLReader implements DriverInterface
{

    private $xml;
    private $filename;

    public function getCategories()
    {

        $out = [];
        $this->moveToStart();
        $xml = $this->xml;

        while ($xml->read()) {
            if ($xml->nodeType==\XMLReader::ELEMENT && $xml->name == 'categories') {
                while ($xml->read() && $xml->name != 'categories') {
                    if ($xml->nodeType == \XMLReader::ELEMENT) {

                        $arr = [];

                        if ($xml->hasAttributes):

                            while ($xml->moveToNextAttribute()):
                                $arr[strtolower($xml->name)] = $xml->value;
                            endwhile;
                        endif;

                        $xml->read();
                        $arr['value'] = $xml->value;
                        $out[] = new \YMLParser\Node\Category($arr);

                        unset($arr);

                    }
                }
            }
        }

        return $out;
    }

    public function getCurrencies()
    {
        return [];
    }

    public function getOffers(\Closure $filter = null)
    {

        $this->moveToStart();
        $xml = $this->xml;

        while ($xml->read()) {
            if ($xml->nodeType == \XMLReader::ELEMENT && $xml->name == 'offers') {
                while ($xml->read() && $xml->name != 'offers') {
                    if ($xml->nodeType == \XMLReader::ELEMENT && $xml->name == 'offer') {

                        $arr = [];
                        $arr['id'] = $xml->getAttribute('id');

                        while ($xml->read() && $xml->name != 'offer'):

                            if ($xml->nodeType == \XMLReader::ELEMENT):

                                $name = strtolower($xml->name);
                                $xml->read();

                                $arr[$name] = $xml->value;
                            endif;
                        endwhile;

                        if(!is_null($filter)):
                            if($filter($arr)):
                                yield $arr;
                            endif;
                        else:
                            yield $arr;
                        endif;
                        //yield $arr;

                    }
                }
            }
        }

    }

    public function open($filename)
    {

        $this->filename = $filename;
        $this->xml = new \XMLReader();
        return $this->xml->open($filename);
    }

    public function countOffers(\Closure $filter)
    {
        return 0;
    }

    /**
     * Rewinds cursor to the first element
     *
     * @return boolean
     */
    private function moveToStart()
    {
        $this->xml->close();
        return $this->xml->open($this->filename);
    }
}

Implement methods: moveToStart, getOffers, getCategories


<?php
/**
 * BoxBilling
 *
 * @copyright BoxBilling, Inc (https://www.boxbilling.org)
 * @license   Apache-2.0
 *
 * Copyright BoxBilling, Inc
 * This source file is subject to the Apache-2.0 License that is bundled
 * with this source code in the file LICENSE
 */

final class Box_Version
{
    const VERSION = '0.0.1';

    const TYPE_FREE = 'free';
    const TYPE_PRO  = 'pro';

    /**
     * Compare the specified BoxBilling version string $version
     * with the current Box_Version::VERSION of BoxBilling.
     *
     * @param  string  $version  A version string (e.g. "0.7.1").
     * @return integer           -1 if the $version is older,
     *                           0 if they are the same,
     *                           and +1 if $version is newer.
     *
     */
    public static function compareVersion($version)
    {
        return version_compare(strtolower($version), strtolower(self::VERSION));
    }
}

<?php
/**
 * BoxBilling
 *
 * @copyright BoxBilling, Inc (https://www.boxbilling.org)
 * @license   Apache-2.0
 *
 * Copyright BoxBilling, Inc
 * This source file is subject to the Apache-2.0 License that is bundled
 * with this source code in the file LICENSE
 */

final class Box_Version
{
    const VERSION = '0.0.1';

    /**
     * Compare the specified BoxBilling version string $version
     * with the current Box_Version::VERSION of BoxBilling.
     *
     * @param  string  $version  A version string (e.g. "0.7.1").
     * @return integer           -1 if the $version is older,
     *                           0 if they are the same,
     *                           and +1 if $version is newer.
     *
     */
    public static function compareVersion($version)
    {
        return version_compare(strtolower($version), strtolower(self::VERSION));
    }
}

Remove TYPE_FREE and TYPE_PRO as we no longer need them


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => env('SES_REGION', 'us-east-1'),
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => App\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => env('SES_REGION', 'us-east-1'),
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => App\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
        'webhook' => [
            'secret' => env('STRIPE_WEBHOOK_SECRET'),
            'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300),
        ],
    ],

];

Add new Stripe webhook config values

Add new Stripe webhook config values

See https://github.com/laravel/cashier/pull/565


<?php namespace Orchestra\Story;

use Orchestra\Contracts\Auth\Guard;
use Orchestra\Contracts\Foundation\Foundation;

class StoryMenuHandler
{
    /**
     * ACL instance.
     *
     * @var \Orchestra\Contracts\Auth\Guard
     */
    protected $auth;

    /**
     * Menu instance.
     *
     * @var \Orchestra\Widget\Handlers\Menu
     */
    protected $menu;

    /**
     * Construct a new handler.
     *
     * @param  \Orchestra\Contracts\Foundation\Foundation  $foundation
     * @param  \Orchestra\Contracts\Auth\Guard  $auth
     */
    public function __construct(Foundation $foundation, Guard $auth)
    {
        $this->menu = $foundation->menu();
        $this->auth = $auth;
    }

    /**
     * Create a handler for `orchestra.ready: admin` event.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->auth->guest()) {
            return ;
        }

        $this->menu->add('storycms', '^:extensions')
            ->title('Story CMS')
            ->link(handles('orchestra::storycms'));
    }
}

<?php namespace Orchestra\Story;

use Orchestra\Contracts\Auth\Guard;
use Orchestra\Contracts\Foundation\Foundation;

class StoryMenuHandler
{
    /**
     * ACL instance.
     *
     * @var \Orchestra\Contracts\Auth\Guard
     */
    protected $auth;

    /**
     * Menu instance.
     *
     * @var \Orchestra\Widget\Handlers\Menu
     */
    protected $menu;

    /**
     * Construct a new handler.
     *
     * @param  \Orchestra\Contracts\Foundation\Foundation  $foundation
     * @param  \Orchestra\Contracts\Auth\Guard  $auth
     */
    public function __construct(Foundation $foundation, Guard $auth)
    {
        $this->menu = $foundation->menu();
        $this->auth = $auth;
    }

    /**
     * Create a handler for `orchestra.ready: admin` event.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->auth->guest()) {
            return ;
        }

        $parent = $this->menu->has('extensions') ? '^:extensions' : '<:home';

        $this->menu->add('storycms', $parent)
            ->title('Story CMS')
            ->link(handles('orchestra::storycms'));
    }
}

Append menu to root menu if extensions is not available.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace App\Entity\OAuth;

use FOS\OAuthServerBundle\Entity\Client as BaseClient;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="ClientRepository")
 */
class Client extends BaseClient
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $name;

    /**
     * @ORM\Column(type="boolean")
     */
    private $preApproved;

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function isPreApproved()
    {
        return $this->preApproved;
    }

    public function setPreApproved($preApproved)
    {
        $this->preApproved = $preApproved;

        return $this;
    }
}

<?php

namespace App\Entity\OAuth;

use FOS\OAuthServerBundle\Entity\Client as BaseClient;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="ClientRepository")
 */
class Client extends BaseClient
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $name;

    /**
     * @ORM\Column(type="boolean")
     */
    private $preApproved;

    public function __construct() {
        parent::__construct();
        $this->allowedGrantTypes[] = \OAuth2\OAuth2::GRANT_TYPE_REFRESH_TOKEN;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function isPreApproved()
    {
        return $this->preApproved;
    }

    public function setPreApproved($preApproved)
    {
        $this->preApproved = $preApproved;

        return $this;
    }
}

Add refresh_token OAuth grant by default


<?php

namespace FluxBB\Markdown\Parser;

use FluxBB\Markdown\Common\Text;
use FluxBB\Markdown\Node\Blockquote;
use FluxBB\Markdown\Node\Node;

class BlockquoteParser implements ParserInterface
{

    public function parseLine(Text $line, Node $target, callable $next)
    {
        $text = $line->getString();
        if ($text[0] == '>') {
            $line = new Text(trim(substr($line, 1)));

            $quote = new Blockquote();
            $target = $target->accept($quote);
        }

        return $next($line, $target);
    }

}

<?php

namespace FluxBB\Markdown\Parser;

use FluxBB\Markdown\Common\Text;
use FluxBB\Markdown\Node\Blockquote;
use FluxBB\Markdown\Node\Node;

class BlockquoteParser implements ParserInterface
{

    public function parseLine(Text $line, Node $target, callable $next)
    {
        $pattern = '/^[ ]{0,3}\>[ ]?/';

        if ($line->match($pattern)) {
            $line->replace($pattern, '');

            $target = $target->accept(new Blockquote());
        }

        return $next($line, $target);
    }

}

Use Text helpers for blockquote parsing.


Welcome to {{ env('DOMAIN') }}, {{ Auth::user()->name }}. Here's everything you need to
            know.

This message will disappear in {{ sprintf(ngettext("%d day", "%d days", $days_registered), $days_registered) }}.

For support, email {{ env('OWNER_EMAIL') }}.

For support or social, hang out in {{ env('IRC_CHANNEL') }} on {{ env('IRC_SERVER') }}.

Max file size per upload is {{ env('UPLOAD_LIMIT') }}.

Do not upload child porn or malware, you'll be banned without mercy.

Scripts and third-party integrations are provided for members,
                    {{ route('account.resources') }}.

Welcome to {{ env('DOMAIN') }}, {{ Auth::user()->name }}. Here's everything you need to
            know.

For support, email {{ env('OWNER_EMAIL') }}.

For support or social, hang out in {{ env('IRC_CHANNEL') }} on {{ env('IRC_SERVER') }}.

Max file size per upload is {{ env('UPLOAD_LIMIT') }}.

Do not upload child porn or malware, you'll be banned without mercy.

Scripts and third-party integrations are provided for members,
                    {{ route('account.resources') }}.

        This message will disappear in {{ sprintf(ngettext("%d day", "%d days", $days_registered), $days_registered) }}.

Improve styling of new member panel a little


@setup
    $deploy_user = $user;
    $deploy_server = $server;
    $deploy_server_string = sprintf('%s@%s', $deploy_user, $deploy_server);
@endsetup

@servers(['web' => $deploy_server_string])

@task('deploy')
    cd /srv/www/chris.mccluskey.us
    git pull origin master
    gulp
    php artisan migrate
@endtask

@setup
    $deploy_user = $user;
    $deploy_server = $server;
    $deploy_server_string = sprintf('%s@%s', $deploy_user, $deploy_server);
@endsetup

@servers(['web' => $deploy_server_string])

@task('deploy')
    cd /srv/www/chris.mccluskey.us
    git pull origin master
    npm install
    gulp
    php artisan migrate
@endtask

Install node project to use gulp

CI: Install node project to use gulp


<?php
namespace Plugin\Model;

trait OptionTrait {
  public static function getOptionList($id, $cond = []) {
    $list = self::create()->getList($cond);

    $ids = [];
    if (is_array($id)) {
      $ids = $id;
    } else {
      $ids = [$id];
    }

    foreach ($list as &$item) {
      $item['selected'] = in_array($item['id'], $ids);
    }

    return $list;
  }
}

<?php
namespace Plugin\Model;

trait OptionTrait {
  public static function getOptionList($id, $cond = [], $sorting = []) {
    $list = self::create()->getList($cond, $sorting);

    $ids = [];
    if (is_array($id)) {
      $ids = $id;
    } else {
      $ids = [$id];
    }

    foreach ($list as &$item) {
      $item['selected'] = in_array($item['id'], $ids);
    }

    return $list;
  }
}

Add possibility to use sorting in option trait


<?php

    require (SYSTEM_PATH . 'core/Common.php');

    $config =& loadClass('Config', 'Core');
    $vendor =& loadClass('Vendor', 'Core');
    $uri =& loadClass('URI', 'Core');
    $router =& loadClass('Router', 'Core');

    $router->routing();
?>

<?php

    require (SYSTEM_PATH . 'core/Common.php');

    $config =& loadClass('Config', 'Core');
    $vendor =& loadClass('Vendor', 'Core');
    $uri =& loadClass('URI', 'Core');
    $router =& loadClass('Router', 'Core');

    $db =& loadClass('DB', 'db');

    $router->routing();

?>

Add database to bootstrap class

Add database to bootstrap class


<?php

namespace Kunstmaan\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;

class WysiwygType extends AbstractType
{
    /**
     * @var DataTransformerInterface
     */
    private $mediaTokenTransformer;

    public function __construct(DataTransformerInterface $mediaTokenTransformer)
    {
        $this->mediaTokenTransformer = $mediaTokenTransformer;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer($this->mediaTokenTransformer);
    }

    /**
     * @return string
     */
    public function getParent()
    {
        return TextareaType::class;
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'wysiwyg';
    }
}

<?php

namespace Kunstmaan\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;

class WysiwygType extends AbstractType
{
    /**
     * @var DataTransformerInterface
     */
    private $mediaTokenTransformer;

    public function __construct(DataTransformerInterface $mediaTokenTransformer)
    {
        $this->mediaTokenTransformer = $mediaTokenTransformer;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer($this->mediaTokenTransformer);
    }

    /**
     * @return string
     */
    public function getParent()
    {
        return TextareaType::class;
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'wysiwyg';
    }
}

Fix codestyle issues after 5.7 upmerge

[AllBundles] Fix codestyle issues after 5.7 upmerge


<?php

namespace ContentTranslator\Entity;

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;
    }
}

<?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;
    }
}

Make the translate entity abstract

Make the translate entity abstract


<?php

namespace GitlabXMPPHook\XMPP;

use XMPPHP_XMPP as Xmpp;
use GitlabXMPPHook\Exception;

class XMPPClient
{

    protected $connection;

    public function __construct($scope)
    {

        if (is_null($scope->host) || is_null($scope->port) || is_null($scope->username) || is_null($scope->password))
            throw new Exception\InvalidXMPPOptions("Missing XMPP Settings");

        $this->connection = new Xmpp(

            $scope->host,
            $scope->port,
            $scope->username,
            $scope->password,
            'GitlabXMPPHook-Bot/' . $scope->version,
            null,   // hostname can be determined from full JID
            $printlog = $scope->debug,
            $loglevel = \XMPPHP_Log::LEVEL_DEBUG
        );

        try {

          $this->connection->connect(1);
          $this->connection->processUntil('session_start');
          $this->connection->presence();
          sleep(0.2);   // Give a few seconds for the dust to settle. Openfire don't like things happening too fast

        } catch (\XMPPHP_Exception $e) {

            throw new Exception\FailedConnection($e);
        }
    }

    public function __destruct()
    {

        $this->connection->disconnect();
    }
}

<?php

namespace GitlabXMPPHook\XMPP;

use XMPPHP_XMPP as Xmpp;
use GitlabXMPPHook\Exception;

class XMPPClient
{

    protected $connection;

    public function __construct($scope)
    {

        if (is_null($scope->host) || is_null($scope->port) || is_null($scope->username) || is_null($scope->password))
            throw new Exception\InvalidXMPPOptions("Missing XMPP Settings");

        $this->connection = new Xmpp(

            $scope->host,
            $scope->port,
            $scope->username,
            $scope->password,
            'GitlabXMPPHook-Bot/' . $scope->version,
            null,   // hostname can be determined from full JID
            $printlog = $scope->debug,
            $loglevel = \XMPPHP_Log::LEVEL_DEBUG
        );

        try {

          $this->connection->connect();
          $this->connection->processUntil('session_start');
          $this->connection->presence();
          sleep(0.2);   // Give a few seconds for the dust to settle. Openfire don't like things happening too fast

        } catch (\XMPPHP_Exception $e) {

            throw new Exception\FailedConnection($e);
        }
    }

    public function __destruct()
    {

        $this->connection->disconnect();
    }
}

Remove 1 sec timeout used in testing

Remove 1 sec timeout used in testing


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    //
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * Get the User associated with the Payment model.
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'recorded_by');
    }

    /**
     * Get the DuesTransaction
     */
    public function duesTransaction()
    {
        return $this->hasOne('App\DuesTransaction');
    }

}

Add 'guarded' to allow for mass assignment via Eloquent; Add User and DuesTransaction Eloquent relationships


<?php

namespace Konsulting\JustGivingApiSdk\Support\Auth;

class BearerAuth implements AuthValue
{
    /**
     * The application ID (also known as API key).
     *
     * @see https://developer.justgiving.com/apidocs/documentation#AppId
     * @var string
     */
    protected $appId;

    /**
     * The bearer token obtained via oAuth.
     *
     * @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/207071499-Getting-a-bearer-token
     * @var string
     */
    protected $token;

    /**
     * The oAuth secret provided by JustGiving (this currently has to be requested manually).
     *
     * @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/115002238925-How-do-I-get-a-secret-key-
     * @var string
     */
    protected $oAuthSecret;

    public function __construct($appId, $oAuthSecret, $token)
    {
        $this->appId = $appId;
        $this->token = $token;
        $this->oAuthSecret = $oAuthSecret;
    }

    /**
     * Get the authentication headers.
     *
     * @return array
     */
    public function getHeaders()
    {
        return [
            'Authorization'     => 'Bearer ' . $this->token,
            'x-api-key'         => $this->appId,
            'x-application-key' => $this->oAuthSecret,
        ];
    }
}

<?php

namespace Konsulting\JustGivingApiSdk\Support\Auth;

class BearerAuth implements AuthValue
{
    /**
     * The application ID (also known as API key).
     *
     * @see https://developer.justgiving.com/apidocs/documentation#AppId
     * @var string
     */
    protected $appId;

    /**
     * The bearer token obtained via oAuth.
     *
     * @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/207071499-Getting-a-bearer-token
     * @var string
     */
    protected $token;

    /**
     * The secret key provided by JustGiving (this currently has to be requested manually).
     *
     * @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/115002238925-How-do-I-get-a-secret-key-
     * @var string
     */
    protected $secretKey;

    public function __construct($appId, $secretKey, $token)
    {
        $this->appId = $appId;
        $this->token = $token;
        $this->secretKey = $secretKey;
    }

    /**
     * Get the authentication headers.
     *
     * @return array
     */
    public function getHeaders()
    {
        return [
            'Authorization'     => 'Bearer ' . $this->token,
            'x-api-key'         => $this->appId,
            'x-application-key' => $this->secretKey,
        ];
    }
}

Rename oAuthSecret -> secretKey in bearer auth object


{{--
    Copyright 2015 ppy Pty. Ltd.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    See the GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}
<?php
    $withReplyLink = authz('ForumTopicReply', $topic)->can();
?>
@foreach($posts as $post)
    <?php
        if (Auth::check()) {
            $withDeleteLink = $post->poster_id === Auth::user()->user_id;
        }

        if (!isset($withDeleteLink) || !$withDeleteLink) {
            $withDeleteLink = authz('ForumPostDelete', $post)->can();
        }
    ?>
    @include('forum.topics._post', [
        'post' => $post,
        'options' => [
            'deleteLink' => $withDeleteLink,
            'editLink' => authz('ForumPostEdit', $post)->can(),
            'postPosition' => $postsPosition[$post->post_id],
            'replyLink' => $withReplyLink,
        ],
    ])
@endforeach

{{--
    Copyright 2015 ppy Pty. Ltd.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    See the GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}
@foreach($posts as $post)
    <?php
        if (Auth::check()) {
            $withDeleteLink = $post->poster_id === Auth::user()->user_id;
        }

        if (!isset($withDeleteLink) || !$withDeleteLink) {
            $withDeleteLink = authz('ForumPostDelete', $post)->can();
        }
    ?>
    @include('forum.topics._post', [
        'post' => $post,
        'options' => [
            'deleteLink' => $withDeleteLink,
            'editLink' => authz('ForumPostEdit', $post)->can(),
            'postPosition' => $postsPosition[$post->post_id],
            'replyLink' => authz('ForumTopicReply', $topic)->can(),
        ],
    ])
@endforeach

Move back since it's now cached

Move back since it's now cached


<?php if ( ! defined('BASEPATH') or !defined('SIMIAN_INSTALLER') ) exit('No direct script access allowed'); ?>
<?php require 'header.tpl.php'; ?>

    <?php
        foreach ( $result['permission'] as $file ) {
            echo "
[" . $file['type'] . "] " . $file['name'] . " - ";
            if ( $file['check'] ) {
                echo "OK";
            } else {
                echo "CHECK";
            }
            echo "
";
        }
    ?>

    Next Step
<?php require 'footer.tpl.php'; ?>

<?php if ( ! defined('BASEPATH') or !defined('SIMIAN_INSTALLER') ) exit('No direct script access allowed'); ?>
<?php require 'header.tpl.php'; ?>
  #

  #  <?php
  #      foreach ( $result['permission'] as $file ) {
  #          echo "
[" . $file['type'] . "] " . $file['name'] . " - ";
  #          if ( $file['check'] ) {
  #              echo "OK";
  #          } else {
  #              echo "CHECK";
  #          }
  #          echo "
";
  #      }
  #  ?>
  #

    Next Step
<?php require 'footer.tpl.php'; ?>

Adjust template file to avoid issuing two sets of error messages when file/directory perms are not rite


<?php

namespace Ivory\LuceneSearchBundle\Tests\Emulation;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;

/**
 * Web test case
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class WebTestCase extends BaseWebTestCase
{
    /**
     * @var boolean TRUE if the web test case has been initialized else FALSE
     */
    protected static $initialize = array();

    /**
     * Remove emulation cache & logs directories
     */
    protected static function initialize($environment)
    {
        if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && self::$initialize[$environment]))
        {
            $filesystem = new Filesystem();
            $filesystem->remove(__DIR__.'/cache/'.$environment);
            $filesystem->remove(__DIR__.'/logs');

            self::$initialize[$environment] = true;
        }
    }

    /**
     *@override
     */
    protected static function getKernelClass()
    {
        $kernelClass = 'AppKernel';

        require_once __DIR__.DIRECTORY_SEPARATOR.$kernelClass.'.php';

        return $kernelClass;
    }

    /**
     * Gets the kernel container
     *
     * @return Symfony\Component\DependencyInjection\ContainerInterface
     */
    public static function createContainer(array $options = array('environment' => 'default'))
    {
        self::initialize($options['environment']);

        $kernel = self::createKernel($options);
        $kernel->boot();

        return $kernel->getContainer();
    }
}

<?php

namespace Ivory\LuceneSearchBundle\Tests\Emulation;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;

/**
 * Web test case
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class WebTestCase extends BaseWebTestCase
{
    /**
     * @var boolean TRUE if the web test case has been initialized else FALSE
     */
    protected static $initialize = array();

    /**
     * Remove emulation cache & logs directories
     */
    protected static function initialize($environment)
    {
        if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
        {
            $filesystem = new Filesystem();
            $filesystem->remove(__DIR__.'/cache/'.$environment);
            $filesystem->remove(__DIR__.'/logs');

            self::$initialize[$environment] = true;
        }
    }

    /**
     *@override
     */
    protected static function getKernelClass()
    {
        $kernelClass = 'AppKernel';

        require_once __DIR__.DIRECTORY_SEPARATOR.$kernelClass.'.php';

        return $kernelClass;
    }

    /**
     * Gets the kernel container
     *
     * @return Symfony\Component\DependencyInjection\ContainerInterface
     */
    public static function createContainer(array $options = array('environment' => 'default'))
    {
        self::initialize($options['environment']);

        $kernel = self::createKernel($options);
        $kernel->boot();

        return $kernel->getContainer();
    }
}

Fix mistake in web test case initilization


<?php

declare(strict_types=1);

/**
 * Copyright (c) 2017 Andreas Möller.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @link https://github.com/localheinz/test-util
 */

namespace Localheinz\Test\Util\Test\Unit;

use Localheinz\Test\Util\Helper;
use Localheinz\Test\Util\Test\Fixture;
use PHPUnit\Framework;

final class ProjectCodeTest extends Framework\TestCase
{
    use Helper;

    public function testProductionClassesAreAbstractOrFinal()
    {
        $this->assertClassesAreAbstractOrFinal(__DIR__ . '/../../src');
    }

    public function testProductionClassesHaveTests()
    {
        $this->assertClassesHaveTests(
            __DIR__ . '/../../src',
            'Localheinz\\Test\\Util\\',
            'Localheinz\\Test\\Util\\Test\\Unit\\'
        );
    }

    public function testTestClassesAreAbstractOrFinal()
    {
        $this->assertClassesAreAbstractOrFinal(__DIR__ . '/..', [
            Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\AlsoNeitherAbstractNorFinal::class,
            Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\NeitherAbstractNorFinal::class,
            Fixture\ClassIsAbstract\ConcreteClass::class,
            Fixture\ClassIsAbstractOrFinal\NeitherAbstractNorFinalClass::class,
            Fixture\ClassIsFinal\NeitherAbstractNorFinalClass::class,
        ]);
    }
}

<?php

declare(strict_types=1);

/**
 * Copyright (c) 2017 Andreas Möller.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @link https://github.com/localheinz/test-util
 */

namespace Localheinz\Test\Util\Test\Unit;

use Localheinz\Test\Util\Helper;
use Localheinz\Test\Util\Test\Fixture;
use PHPUnit\Framework;

final class ProjectCodeTest extends Framework\TestCase
{
    use Helper;

    public function testProductionClassesAreAbstractOrFinal()
    {
        $this->assertClassesAreAbstractOrFinal(__DIR__ . '/../../src');
    }

    public function testProductionClassesHaveTests()
    {
        $this->assertClassesHaveTests(
            __DIR__ . '/../../src',
            'Localheinz\\Test\\Util\\',
            'Localheinz\\Test\\Util\\Test\\Unit\\'
        );
    }

    public function testTestClassesAreAbstractOrFinal()
    {
        $this->assertClassesAreAbstractOrFinal(__DIR__ . '/..', [
            Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\AlsoNeitherAbstractNorFinal::class,
            Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\NeitherAbstractNorFinal::class,
            Fixture\ClassIsAbstract\ConcreteClass::class,
            Fixture\ClassIsFinal\NeitherAbstractNorFinalClass::class,
        ]);
    }
}

Remove reference to non-existent class

Fix: Remove reference to non-existent class


<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-89633670-1', 'auto');
  ga('send', 'pageview');

</script>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
 (adsbygoogle = window.adsbygoogle || []).push({
   google_ad_client: "ca-pub-2506823660780265",
   enable_page_level_ads: true
 });
</script>

Add Google Adwords to blog

Add Google Adwords to blog


<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class SemanticsFacade {

    protected static function getFacadeAccessor() {
	return 'Semantics';
    }

}

<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class SemanticsFacade extends Facade{

    protected static function getFacadeAccessor() {
	return 'Semantics';
    }

}

FIX : Semantic facade étend Facade

FIX : Semantic facade étend Facade


<?php

use SuiteCRM\Search\ElasticSearch\ElasticSearchIndexer as i;

if (i::isEnabled())
    $job_strings[] = 'runElasticSearchIndexerScheduler';

function runElasticSearchIndexerScheduler()
{
    $i = new i();
    $i->log('@', 'Starting scheduled job');

    try {
        $i->setDifferentialIndexingEnabled(true);
        $i->run();
    } catch (Exception $e) {
        $i->getLogger->error('An error has occurred while running a scheduled indexing' . PHP_EOL . $e->getTraceAsString());
        return false;
    }

    return true;
}

<?php

use SuiteCRM\Search\ElasticSearch\ElasticSearchIndexer as i;

if (i::isEnabled())
    $job_strings[] = 'runElasticSearchIndexerScheduler';

function runElasticSearchIndexerScheduler()
{
    $i = new i();
    $i->getLogger()->debug('Starting scheduled job');

    try {
        $i->setDifferentialIndexingEnabled(true);
        $i->run();
    } catch (Exception $e) {
        $i->getLogger->error('An error has occurred while running a scheduled indexing' . PHP_EOL . $e->getTraceAsString());
        return false;
    }

    return true;
}

Fix issue with scheduler calling the wrong log method


<?php

namespace {{ theme.namespace }}\Http;

use function {{ theme.namespace }}\asset_path;

/*
|-----------------------------------------------------------------
| Theme Assets
|-----------------------------------------------------------------
|
| This file is for registering your theme stylesheets and scripts.
| In here you should also deregister all unwanted assets which
| can be shiped with various third-parity plugins.
|
*/

// Manages theme stylesheets.
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('bootstrap', asset_path('css/bootstrap.css'));

    wp_enqueue_style('theme', asset_path('css/theme.css'));
});

// Manages theme scripts.
add_action('wp_enqueue_scripts', function () {
    // wp_enqueue_script('theme-scripts', asset_path('js/all.js'));
});

<?php

namespace {{ theme.namespace }}\Http;

use function {{ theme.namespace }}\asset_path;

/*
|-----------------------------------------------------------------
| Theme Assets
|-----------------------------------------------------------------
|
| This file is for registering your theme stylesheets and scripts.
| In here you should also deregister all unwanted assets which
| can be shiped with various third-parity plugins.
|
*/

// Manages theme stylesheets.
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('theme', asset_path('css/theme.css'));
});

// Manages theme scripts.
add_action('wp_enqueue_scripts', function () {
    // wp_enqueue_script('theme-scripts', asset_path('js/all.js'));
});

Remove enqueue of bootstrap.css asset

Remove enqueue of bootstrap.css asset


<?php
//modify vars below
$db_host = 'localhost';
$db_user = '';
$db_password = '';
$database = 'nflpickem';
$db_prefix = 'nflp_';

$siteUrl = 'http://localhost/personal/phppickem.com/application/';
$allow_signup = true;
$show_signup_link = true;
$user_names_display = 3; // 1 = real names, 2 = usernames, 3 = usernames w/ real names on hover

define('SEASON_YEAR', '2013');

//set timezone offset, hours difference between your server's timezone and eastern
define('SERVER_TIMEZONE_OFFSET', 1);

// ***DO NOT EDIT ANYTHING BELOW THIS LINE***
$dbConnected = false;
error_reporting(0);
if (mysql_connect($db_host, $db_user, $db_password)) {
	if (mysql_select_db($database)) {
		$dbConnected = true;
	}
}
error_reporting(E_ALL ^ E_NOTICE);

<?php
//modify vars below
$db_host = 'localhost';
$db_user = '';
$db_password = '';
$database = 'nflpickem';
$db_prefix = 'nflp_';

$siteUrl = 'http://localhost/personal/phppickem.com/application/';
$allow_signup = true;
$show_signup_link = true;
$user_names_display = 3; // 1 = real names, 2 = usernames, 3 = usernames w/ real names on hover

define('SEASON_YEAR', '2014');

//set timezone offset, hours difference between your server's timezone and eastern
define('SERVER_TIMEZONE_OFFSET', 1);

// ***DO NOT EDIT ANYTHING BELOW THIS LINE***
$dbConnected = false;
error_reporting(0);
if (mysql_connect($db_host, $db_user, $db_password)) {
	if (mysql_select_db($database)) {
		$dbConnected = true;
	}
}
error_reporting(E_ALL ^ E_NOTICE);

Set default SEASON_YEAR to 2014.

Set default SEASON_YEAR to 2014.


<?php

namespace App\Entity\Fixture;

use App\Entity;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Persistence\ObjectManager;

class Settings extends AbstractFixture
{
    public function load(ObjectManager $em): void
    {
        $settings = new Entity\Settings();

        $settings->setBaseUrl(getenv('INIT_BASE_URL') ?? 'docker.local');
        $settings->setInstanceName(getenv('INIT_INSTANCE_NAME') ?? 'local test');
        $settings->setGeoliteLicenseKey(getenv('INIT_GEOLITE_LICENSE_KEY') ?? '');
        $settings->setPreferBrowserUrl(true);
        $settings->updateSetupComplete();
        $settings->setUseRadioProxy(true);
        $settings->setCheckForUpdates(true);
        $settings->setExternalIp('127.0.0.1');

        $isDemoMode = (!empty(getenv('INIT_DEMO_API_KEY') ?? ''));
        if ($isDemoMode) {
            $settings->setAnalytics(Entity\Analytics::LEVEL_NO_IP);
            $settings->setPublicCustomJs(
                <<<'JS'
                $(function() {
                  if ($('body').hasClass('login-content')) {
                    $('input[name="username"]').val('demo@azuracast.com');
                    $('input[name="password"]').val('demo');
                  }
                });
                JS
            );
        }

        $settings = json_decode(json_encode($settings), true);

        foreach ($settings as $setting_key => $setting_value) {
            $record = new Entity\SettingsTable($setting_key);
            $record->setSettingValue($setting_value);
            $em->persist($record);
        }

        $em->flush();
    }
}

<?php

namespace App\Entity\Fixture;

use App\Entity;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Persistence\ObjectManager;

class Settings extends AbstractFixture
{
    public function load(ObjectManager $em): void
    {
        $settings = [
            'baseUrl' => getenv('INIT_BASE_URL') ?? 'docker.local',
            'instanceName' => getenv('INIT_INSTANCE_NAME') ?? 'local test',
            'geoliteLicenseKey' => getenv('INIT_GEOLITE_LICENSE_KEY') ?? '',
            'setupCompleteTime' => time(),
            'preferBrowserUrl' => true,
            'useRadioProxy' => true,
            'checkForUpdates' => true,
            'externalIp' => '127.0.0.1',
        ];

        $isDemoMode = (!empty(getenv('INIT_DEMO_API_KEY') ?? ''));
        if ($isDemoMode) {
            $settings['analytics'] = Entity\Analytics::LEVEL_NO_IP;
            $settings['publicCustomJs'] = <<<'JS'
                $(function() {
                  if ($('body').hasClass('login-content')) {
                    $('input[name="username"]').val('demo@azuracast.com');
                    $('input[name="password"]').val('demo');
                  }
                });
            JS;
        }

        foreach ($settings as $setting_key => $setting_value) {
            $record = new Entity\SettingsTable($setting_key);
            $record->setSettingValue($setting_value);
            $em->persist($record);
        }

        $em->flush();
    }
}

Fix Fixtures to work with settings overhaul.


<?php

namespace Fsalehpour\RabbitMQ\Facades;

use Illuminate\Support\Facades\Facade;
use PhpAmqpLib\Message\AMQPMessage;

class AMQPFacade extends Facade
{
    public static function basic_publish_with_response($channel, $exchange, $routing_key, $body, $headers = [])
    {
        $response = null;
        $corr_id = uniqid();

        list ($callback_queue, ,) = $channel->queue_declare('', false, false, true, false);

        $callback = function ($msg) use ($corr_id, &$response) {
            if ($msg->get('correlation_id') == $corr_id) {
                $response = $msg->body;
            }
        };

        $channel->basic_consume($callback_queue, '', false, false, false, false, $callback);

        $msg = new AMQPMessage($body, array_merge($headers, [
            'correlation_id' => $corr_id,
            'reply_to'       => $callback_queue
        ]));

        $channel->basic_publish($msg, $exchange, $routing_key);

        while (!$response) {
            $channel->wait(null, false, env('RABBITMQ_TIMEOUT', 10));
        }

        return $response;
    }

    protected static function getFacadeAccessor()
    {
        return 'AMQP';
    }

}

<?php

namespace Fsalehpour\RabbitMQ\Facades;

use Illuminate\Support\Facades\Facade;
use PhpAmqpLib\Message\AMQPMessage;

class AMQPFacade extends Facade
{
    public static function basic_publish_with_response($channel, $exchange, $routing_key, $body, $headers = [])
    {
        $response = null;
        $corr_id = uniqid();

        list ($callback_queue, ,) = $channel->queue_declare('', false, false, true, false);

        $callback = function ($msg) use ($corr_id, &$response) {
            if ($msg->get('correlation_id') == $corr_id) {
                $response = $msg->body;
            }
        };

        $channel->basic_consume($callback_queue, '', false, false, false, false, $callback);

        $msg = new AMQPMessage($body, array_merge($headers, [
            'correlation_id' => $corr_id,
            'reply_to'       => $callback_queue
        ]));

        $channel->basic_publish($msg, $exchange, $routing_key);

        while (!$response) {
            $channel->wait(null, false, env('RABBITMQ_TIMEOUT', 0));
        }

        return $response;
    }

    protected static function getFacadeAccessor()
    {
        return 'AMQP';
    }

}

Set default time out for publish with confirm to 0


<?php

namespace RIPS\Connector\Requests;

class SourceRequests extends BaseRequest
{
    /**
     * Build a uri for the request
     *
     * @return string
     */
    protected function uri()
    {
        return '/sources';
    }

    /**
     * Get all directories from the root source directory
     *
     * @param array $queryParams
     * @return \stdClass[]
     */
    public function getAll(array $queryParams = [])
    {
        $response = $this->client->get($this->uri(), [
            'query' => $queryParams,
        ]);

        return $this->handleResponse($response);
    }
}

<?php

namespace RIPS\Connector\Requests;

class SourceRequests extends BaseRequest
{
    /**
     * Build a uri for the request
     *
     * @return string
     */
    protected function uri()
    {
        return '/sources';
    }

    /**
     * Get all directories from the root source directory
     *
     * @param array $queryParams
     * @return string
     */
    public function getAll(array $queryParams = [])
    {
        $response = $this->client->get($this->uri(), [
            'query' => $queryParams,
        ]);

        return $this->handleResponse($response, true);
    }
}

Make source requests return raw response


<?php

namespace NavJobs\Transmit;

use Illuminate\Support\ServiceProvider;
use League\Fractal\Manager;
use League\Fractal\Serializer\SerializerAbstract;

class TransmitServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../resources/config/transmit.php' => config_path('transmit.php'),
        ], 'config');
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../resources/config/transmit.php', 'transmit');

        $this->app->bind(Fractal::class, function () {

            $manager = new Manager();

            $fractal = new Fractal($manager);

            $config = $this->app['config']->get('transmit');

            if (!empty($config['default_serializer'])) {
                $fractal = $this->setDefaultSerializer($fractal, $config['default_serializer']);
            }

            return $fractal;
        });
    }

    /**
     * Set the default serializer.
     *
     * @param $fractal
     * @param string|\League\Fractal\Serializer\SerializerAbstract $serializer
     *
     * @return mixed
     */
    protected function setDefaultSerializer($fractal, $serializer)
    {
        if ($serializer instanceof SerializerAbstract) {
            return $fractal->serializeWith($serializer);
        }

        return $fractal->serializeWith(new $serializer());
    }
}

<?php

namespace NavJobs\Transmit;

use Illuminate\Support\ServiceProvider;
use League\Fractal\Manager;
use League\Fractal\Serializer\SerializerAbstract;
use NavJobs\Transmit\Serializers\DataArraySerializer;

class TransmitServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../resources/config/transmit.php' => config_path('transmit.php'),
        ], 'config');
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../resources/config/transmit.php', 'transmit');

        $this->app->bind(Fractal::class, function () {

            $manager = new Manager();

            $fractal = new Fractal($manager);

            $config = $this->app['config']->get('transmit');

            if (!empty($config['default_serializer'])) {
                $fractal = $this->setDefaultSerializer($fractal, $config['default_serializer']);
            } else {
                $fractal->serializeWith(new DataArraySerializer());
            }

            return $fractal;
        });
    }

    /**
     * Set the default serializer.
     *
     * @param $fractal
     * @param string|\League\Fractal\Serializer\SerializerAbstract $serializer
     *
     * @return mixed
     */
    protected function setDefaultSerializer($fractal, $serializer)
    {
        if ($serializer instanceof SerializerAbstract) {
            return $fractal->serializeWith($serializer);
        }

        return $fractal->serializeWith(new $serializer());
    }
}

Set the default serializer to a our modified dataarrayserializer


<?php
    namespace DB\Driver;

    /**
     * Interface for all database driver. Any database driver must implement
     * this class.
     *
     * @package DB\Driver
     */
    interface IDriver
    {
        /**
         * Connect to selected database host
         *
         * @param  string $host     Database host name
         * @param  string $user     Username for database host
         * @param  string $password Password for database host
         */
        public function connect($host, $user, $password);

        /**
         * Connect to database in the host.
         *
         * @param  string $name         Database name
         * @param  bool   $forceCreate  If set to true, will create database if
         * 								database is not exists
         */
        public function database($name, $forceCreate=false);

        /**
         * Perform Query based on the driver.
         *
         * @param  string $sql SQL that need to be run
         *
         * @return \DB\Result  Database query result
         */
        public function query($sql);

        /**
         * Perform database query by binding the data to query syntax.
         *
         * @param  string $sql  SQL
         * @param  array  $data Data that will be binded to query
         *
         * @return \DB\Result   Database query result
         */
        public function bind($sql, $data=[]);

    }

?>

<?php
    namespace DB\Driver;

    /**
     * Interface for all database driver. Any database driver must implement
     * this class.
     *
     * @package DB\Driver
     */
    interface IDriver
    {
        /**
         * Connect to selected database host
         *
         * @param  string $host     Database host name
         * @param  string $user     Username for database host
         * @param  string $password Password for database host
         */
        public function connect($host, $user, $password);

        /**
         * Connect to database in the host.
         *
         * @param  string $name         Database name
         * @param  bool   $forceCreate  If set to true, will create database if
         * 								database is not exists
         */
        public function database($name, $forceCreate=false);

        /**
         * Perform Query based on the driver.
         *
         * @param  string $sql SQL that need to be run
         *
         * @return \DB\Result  Database query result
         */
        public function query($sql);

        /**
         * Perform database query by binding the data to query syntax.
         *
         * @param  string $sql  SQL
         * @param  array  $data Data that will be binded to query
         *
         * @return \DB\Result   Database query result
         */
        public function bind($sql, $data=[]);

        public function bindAuto($sql, $data=array());
    }

?>

Add bind auto method (bind without key)

Add bind auto method (bind without key)


<?php

// Must be included before any of the other code is run. This file does some
// basic changes to the environment, like setting an autoloader.

// Classloader
require __DIR__ . '/vendor/autoload.php';

// Report all errors
error_reporting(E_ALL);

// Valid HTML please
ini_set('arg_separator.output', '&');

<?php

// Must be included before any of the other code is run. This file does some
// basic changes to the environment, like setting an autoloader.

// Classloader
$composerFile = __DIR__ . '/vendor/autoload.php';
if (!file_exists($composerFile)) {
    die("vendor directory not found. Please run composer install first.");
}
require __DIR__ . '/vendor/autoload.php';

// Report all errors
error_reporting(E_ALL);

// Valid HTML please
ini_set('arg_separator.output', '&');

Add check for vendor directory

Add check for vendor directory


<?php

namespace duncan3dc\Proxy;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class App
{
    public function run(): void
    {
        $client = new Client([
            "http_errors"   =>  false,
        ]);

        $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

        $response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        $this->respond($response);
    }

    private function respond(ResponseInterface $response): void
    {
        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

<?php

namespace duncan3dc\Proxy;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class App
{
    public function run(): void
    {
        $client = new Client([
            "http_errors"   =>  false,
        ]);

        $url = $this->generateUrl();

        $response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        $this->respond($response);
    }

    private function generateUrl(): string
    {
        return "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
    }

    private function respond(ResponseInterface $response): void
    {
        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

Move the URL generation to a separate method


<?php
namespace Codeception\Module;

use Codeception\Module as CodeceptionModule;
use \Codeception\Util\Shared\Asserts as SharedAsserts;

/**
 * Special module for using asserts in your tests.
 *
 */
class Asserts extends CodeceptionModule
{
    use SharedAsserts {
        assertEquals as public;
        assertNotEquals as public;
        assertSame as public;
        assertNotSame as public;
        assertGreaterThan as public;
        assertGreaterThen as public;
        assertGreaterThanOrEqual as public;
        assertGreaterThenOrEqual as public;
        assertLessThan as public;
        assertLessThanOrEqual as public;
        assertContains as public;
        assertNotContains as public;
        assertRegExp as public;
        assertNotRegExp as public;
        assertEmpty as public;
        assertNotEmpty as public;
        assertNull as public;
        assertNotNull as public;
        assertTrue as public;
        assertFalse as public;
        fail as public;
    }
}

<?php
namespace Codeception\Module;

use Codeception\Module as CodeceptionModule;
use \Codeception\Util\Shared\Asserts as SharedAsserts;

/**
 * Special module for using asserts in your tests.
 *
 */
class Asserts extends CodeceptionModule
{
    use SharedAsserts {
        assertEquals as public;
        assertNotEquals as public;
        assertSame as public;
        assertNotSame as public;
        assertGreaterThan as public;
        assertGreaterThen as public;
        assertGreaterThanOrEqual as public;
        assertGreaterThenOrEqual as public;
        assertLessThan as public;
        assertLessThanOrEqual as public;
        assertContains as public;
        assertNotContains as public;
        assertRegExp as public;
        assertNotRegExp as public;
        assertEmpty as public;
        assertNotEmpty as public;
        assertNull as public;
        assertNotNull as public;
        assertTrue as public;
        assertFalse as public;
        assertFileExists as public;
        assertFileNotExists as public;
        fail as public;
    }
}

Include assertFileExists and assertFileNotExists as public.


<?php
define('PHPUNIT_RUN', 1);

$configDir = getenv('CONFIG_DIR');
if ($configDir) {
	define('PHPUNIT_CONFIG_DIR', $configDir);
}

require_once __DIR__ . '/../lib/base.php';

\OC::$loader->addValidRoot(OC::$SERVERROOT . '/tests');

// load all enabled apps
\OC_App::loadApps();

if (!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();

<?php
define('PHPUNIT_RUN', 1);

$configDir = getenv('CONFIG_DIR');
if ($configDir) {
	define('PHPUNIT_CONFIG_DIR', $configDir);
}

require_once __DIR__ . '/../lib/base.php';

\OC::$composerAutoloader->addPsr4('Test\\', OC::$SERVERROOT . '/tests/lib/', true);
\OC::$composerAutoloader->addPsr4('Tests\\', OC::$SERVERROOT . '/tests/', true);
\OC::$loader->addValidRoot(OC::$SERVERROOT . '/tests');

// load all enabled apps
\OC_App::loadApps();

if (!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();

Add PSR-4 loading for Test\ and Tests\

Add PSR-4 loading for Test\ and Tests\


<?php
namespace Croogo\Settings\Configure\Engine;

use Cake\Core\Configure\ConfigEngineInterface;
use Cake\Log\Log;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;

class DatabaseConfig implements ConfigEngineInterface
{

    private $_table;

/**
 * @param Table $table
 */
    function __construct(Table $table = null)
    {
        if (!$table) {
            $table = TableRegistry::get('Croogo/Settings.Settings');
        }

        $this->_table = $table;
    }

/**
 * Read method is used for reading configuration information from sources.
 * These sources can either be static resources like files, or dynamic ones like
 * a database, or other datasource.
 *
 * @param string $key Key to read.
 * @return array An array of data to merge into the runtime configuration
 */
    public function read($key)
    {
        $settings = $this->_table->find('all');
        $config = [];

        foreach ($settings as $setting) {
            $config = Hash::insert($config, $setting->key, $setting->value);
        }

        return $config;
    }

/**
 * Dumps the configure data into source.
 *
 * @param string $key The identifier to write to.
 * @param array $data The data to dump.
 * @return bool True on success or false on failure.
 */
    public function dump($key, array $data)
    {
        Log::debug($key);
        Log::debug($data);

        return true;
    }
}

<?php
namespace Croogo\Settings\Configure\Engine;

use Cake\Core\Configure\ConfigEngineInterface;
use Cake\Log\Log;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;

class DatabaseConfig implements ConfigEngineInterface
{

    private $_table;

/**
 * @param Table $table
 */
    function __construct(Table $table = null)
    {
        if (!$table) {
            $table = TableRegistry::get('Croogo/Settings.Settings');
        }

        $this->_table = $table;
    }

/**
 * Read method is used for reading configuration information from sources.
 * These sources can either be static resources like files, or dynamic ones like
 * a database, or other datasource.
 *
 * @param string $key Key to read.
 * @return array An array of data to merge into the runtime configuration
 */
    public function read($key)
    {
        $settings = $this->_table->find('list', [
            'keyField' => 'key',
            'valueField' => 'value'
        ])->toArray();

        return Hash::expand($settings);
    }

/**
 * Dumps the configure data into source.
 *
 * @param string $key The identifier to write to.
 * @param array $data The data to dump.
 * @return bool True on success or false on failure.
 */
    public function dump($key, array $data)
    {
        Log::debug($key);
        Log::debug($data);

        return true;
    }
}

Improve loading of settings from database


<?php
require_once('Autoload.php');
class SQLAuthTest extends PHPUnit_Framework_TestCase
{
    public function testSQLAuthenticator()
    {
        $GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/travis/helpers';
        if(!isset(FlipsideSettings::$dataset['auth']))
        {
            $params = array('dsn'=>'mysql:host=localhost;dbname=auth', 'host'=>'localhost', 'user'=>'root', 'pass'=>'');
            FlipsideSettings::$dataset['auth'] = array('type'=>'SQLDataSet', 'params'=>$params);
        }

        $dataSet = \DataSetFactory::getDataSetByName('auth');
        $dataSet->raw_query('CREATE TABLE tbluser (uid VARCHAR(255), pass VARCHAR(255));');

        $params = array('current'=>true, 'pending'=>false, 'supplement'=>false, 'current_data_set'=>'auth');
        $auth = new \Auth\SQLAuthenticator($params);

        $this->assertFalse($auth->login('test', 'test'));
    }
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
?>

<?php
require_once('Autoload.php');
class SQLAuthTest extends PHPUnit_Framework_TestCase
{
    public function testSQLAuthenticator()
    {
        $GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/travis/helpers';
        if(!isset(FlipsideSettings::$dataset['auth']))
        {
            $params = array('dsn'=>'mysql:host=localhost;dbname=auth', 'host'=>'localhost', 'user'=>'root', 'pass'=>'');
            FlipsideSettings::$dataset['auth'] = array('type'=>'SQLDataSet', 'params'=>$params);
        }

        $dataSet = \DataSetFactory::getDataSetByName('auth');
        $dataSet->raw_query('CREATE TABLE tbluser (uid VARCHAR(255), pass VARCHAR(255));');

        $params = array('current'=>true, 'pending'=>false, 'supplement'=>false, 'current_data_set'=>'auth');
        $auth = new \Auth\SQLAuthenticator($params);

        $this->assertFalse($auth->login('test', 'test'));

        $dataSet->raw_query('INSERT INTO tbluser (\'test\', \'$2a$04$B5RseAQlJOuAwZzYtSeLY.sehGtBPTlkZUuh2sv9vCwXzAAI7ribO\');');

        $res = $auth->login('test', 'test');
        $this->assertNotFalse($res);
    }
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
?>

Add possitive user login test

Add possitive user login test


<?php

namespace PhpSchool\PhpWorkshop\Exercise;

use PhpSchool\PhpWorkshop\Solution\SolutionInterface;

/**
 * Class ExerciseInterface
 * @package PhpSchool\PhpWorkshop\Exercise
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */

interface ExerciseInterface
{

    /**
     * @return string
     */
    public function getName();

    /**
     * @return ExerciseType
     */
    public function getType();

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @return SolutionInterface
     */
    public function getSolution();

    /**
     * @return string
     */
    public function getProblem();

    /**
     * @return void
     */
    public function tearDown();
}

<?php

namespace PhpSchool\PhpWorkshop\Exercise;

use PhpSchool\PhpWorkshop\ExerciseDispatcher;
use PhpSchool\PhpWorkshop\Solution\SolutionInterface;

/**
 * Class ExerciseInterface
 * @package PhpSchool\PhpWorkshop\Exercise
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */

interface ExerciseInterface
{

    /**
     * @return string
     */
    public function getName();

    /**
     * @return ExerciseType
     */
    public function getType();

    /**
     * @param ExerciseDispatcher $dispatcher
     */
    public function configure(ExerciseDispatcher $dispatcher);

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @return SolutionInterface
     */
    public function getSolution();

    /**
     * @return string
     */
    public function getProblem();

    /**
     * @return void
     */
    public function tearDown();
}

Add method to specify required checks

Add method to specify required checks


    <a href="<?php echo get_home_url(); ?>"><img class="logo" src="<?php bloginfo('template_directory'); ?>/assets/img/logo.png" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>

      <?php
        if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav navbar-nav'));
        endif;
      ?>

        <?php if (is_user_logged_in()) : ?>

              &nbsp&nbsp<?php echo wp_get_current_user()->display_name; ?>
              <?php echo get_avatar(get_current_user_id(), 26); ?>

<a href="<?php echo wp_logout_url(get_permalink()); ?>">Logout

        <?php else : ?>

<a href="<?php echo wp_login_url(get_permalink()); ?>">Login

<a href="<?php echo get_home_url(); ?>/register">Join

        <?php endif; ?>

Add avatar, name, login, join, and logout to menu


<?php

function processBarcode($barcode) {

}

<?php
define('BARCODE_ENDPOINT', 'http://library2.udayton.edu/ray/ohss/barcode_search.php?barcode=%s');

function processBarcode($barcode) {
	if (preg_match('/^[A-Z][0-9]+$/', $barcode)) {
		$result = file_get_contents(sprintf(BARCODE_ENDPOINT, $barcode));

		if ($result) {
			return json_decode($result, true);
		}
	}

	return false;
}

Add function body for processBarcode.

Add function body for processBarcode.