<?php

namespace Backend;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use SpoonFilter;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * This class will initiate the backend-application
 */
class Init extends \Common\Core\Init
{
    /**
     * @param KernelInterface $kernel
     */
    public function __construct(KernelInterface $kernel)
    {
        $this->allowedTypes = array('Backend', 'BackendAjax', 'BackendCronjob', 'Console');

        parent::__construct($kernel);
    }

    /**
     * {@inheritdoc}
     */
    public function initialize($type)
    {
        parent::initialize($type);

        SpoonFilter::disableMagicQuotes();
    }
}

<?php

namespace Backend;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use SpoonFilter;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * This class will initiate the backend-application
 */
class Init extends \Common\Core\Init
{
    /**
     * @param KernelInterface $kernel
     */
    public function __construct(KernelInterface $kernel)
    {
        $this->allowedTypes = array('Backend', 'BackendAjax', 'BackendCronjob', 'Console');

        parent::__construct($kernel);
    }

    /**
     * {@inheritdoc}
     */
    public function initialize(string $type)
    {
        parent::initialize($type);

        SpoonFilter::disableMagicQuotes();
    }
}

Add missing typehing on backend init

Add missing typehing on backend init


<?php

declare(strict_types=1);

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

class CreateAbilitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('rinvex.fort.tables.abilities'), function (Blueprint $table) {
            // Columns
            $table->increments('id');
            $table->string('action');
            $table->string('resource');
            $table->string('policy')->nullable();
            $table->string('name');
            $table->text('description')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Indexes
            $table->unique(['action', 'resource']);
        });
    }

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

<?php

declare(strict_types=1);

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

class CreateAbilitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('rinvex.fort.tables.abilities'), function (Blueprint $table) {
            // Columns
            $table->increments('id');
            $table->string('action');
            $table->string('resource');
            $table->string('policy')->nullable();
            $table->{$this->jsonable()}('name');
            $table->{$this->jsonable()}('description')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Indexes
            $table->unique(['action', 'resource']);
        });
    }

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

    /**
     * Get jsonable column data type.
     *
     * @return string
     */
    protected function jsonable()
    {
        return DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql'
               && version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge')
            ? 'json' : 'text';
    }
}

Fix abilities name/description has wrong field data type -> json


<?php
/**
 * api: cron
 * title: Update `tags` table
 * description: Splits out tags from according column in project `release`.
 * version: 0.2
 *
 * Manually update tags table.
 *   - Splits up comma separated release.tags field
 *   - Maximum of 7 tags each
 *   - Populates separate tags table with name=>tag list.
 *
 */

chdir(dirname(__DIR__));
include("config.php");

/**
 * Scan each project,
 * split up `tags` as CSV and just fille up according tags table.
 *
 */
foreach (db("SELECT * FROM release_versions GROUP BY name")->into() as $entry) {

    print_r($entry);

    $name = $entry->name;
    $tags = array_slice(array_filter(p_csv($entry->tags)), 0, 7);

    db("DELETE FROM tags WHERE name=?", $name);
    foreach ($tags as $t) {
        db("INSERT INTO tags (name, tag) VALUES (?, ?)", $name, $t);
    }

}

<?php
/**
 * api: cron
 * title: Update `tags` table
 * description: Splits out tags from according column in project `release`.
 * version: 0.2
 *
 * Manually update tags table.
 *   - Splits up comma separated release.tags field
 *   - Maximum of 7 tags each
 *   - Populates separate tags table with name=>tag list.
 *
 */

chdir(dirname(__DIR__));
include("config.php");

/**
 * Scan each project,
 * split up `tags` as CSV and just fille up according tags table.
 *
 */
foreach (db("SELECT * FROM release_versions")->into() as $entry) {

    print_r($entry);

    $name = $entry->name;
    $tags = array_slice(array_filter(p_csv($entry->tags)), 0, 7);

    db("DELETE FROM tags WHERE name=?", $name);
    foreach ($tags as $t) {
        db("INSERT INTO tags (name, tag) VALUES (?, ?)", $name, $t);
    }

}

Remove extraneous GROUP BY name, which broken [release_versions] order


<?php namespace Inkwell\HTTP
{
	use Dotink\Flourish\Collection;

	class CookieCollection extends Collection
	{
		/**
		 *
		 */
		public function get($name = NULL, $default = NULL)
		{
			if ($name !== NULL) {
				$value = parent::get($name, $default);

				return is_array($value)
					? $value[0]
					: $value;
			}

			$values = array();

			foreach (array_keys(parent::get()) as $name) {
				$values[$name] = $this->get($name, $default);
			}

			return $values;
		}

		/**
		 *
		 */
		public function set($name, $value = NULL, $expire = 0, $path = NULL, $domain = NULL, $secure = FALSE, $httponly = FALSE)
		{
			if ($value !== NULL) {
				return parent::set($name, array_slice(func_get_args(), 1));
			}

			if (is_array($values = func_get_arg(0))) {
				foreach ($values as $name => $value) {
					$this->set($name, $value);
				}
			}

			return $this;
		}
	}
}

<?php namespace Inkwell\HTTP
{
	use Dotink\Flourish\Collection;

	class CookieCollection extends Collection
	{
		/**
		 *
		 */
		public function get($name = NULL, $default = NULL)
		{
			if ($name !== NULL) {
				$value = parent::get($name, $default);

				return is_array($value)
					? $value[0]
					: $value;
			}

			$values = array();

			foreach (array_keys(parent::get()) as $name) {
				$values[$name] = $this->get($name, $default);
			}

			return $values;
		}

		/**
		 *
		 */
		public function set($name, $value = NULL, $expire = 0, $path = NULL, $domain = NULL, $secure = FALSE, $httponly = FALSE)
		{
			if ($value === NULL && is_array($values = func_get_arg(0))) {
				foreach ($values as $name => $value) {
					$this->set($name, $value);
				}

			} else {
				parent::set($name, array_slice(func_get_args(), 1));
			}

			return $this;
		}
	}
}

Allow for setting NULL value

Allow for setting NULL value


<?php

/**
 * This file is part of the Statistical Classifier package.
 *
 * (c) Cam Spiers <camspiers@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Camspiers\StatisticalClassifier\Transform;

/**
 * @author  Cam Spiers <camspiers@gmail.com>
 * @package Statistical Classifier
 */
class DocumentLength
{
    public function __invoke($tfidf)
    {
        $transform = $tfidf;

        foreach ($tfidf as $category => $documents) {
            foreach ($documents as $documentIndex => $document) {
                $denominator = 0;
                foreach ($document as $count) {
                    $denominator += $count * $count;
                }
                $denominator = sqrt($denominator);
                if ($denominator !== 0) {
                    foreach ($document as $token => $count) {
                        $transform
                            [$category]
                            [$documentIndex]
                            [$token] = $count / $denominator;
                    }
                } else {
                    throw new \RuntimeException("Cannot divide by 0 in DocumentLength transform");
                }
            }
        }

        return $transform;
    }
}

<?php

/**
 * This file is part of the Statistical Classifier package.
 *
 * (c) Cam Spiers <camspiers@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Camspiers\StatisticalClassifier\Transform;

/**
 * @author  Cam Spiers <camspiers@gmail.com>
 * @package Statistical Classifier
 */
class DocumentLength
{
    public function __invoke($tfidf)
    {
        $transform = $tfidf;

        foreach ($tfidf as $category => $documents) {
            foreach ($documents as $documentIndex => $document) {
                $denominator = 0;
                foreach ($document as $count) {
                    $denominator += $count * $count;
                }
                $denominator = sqrt($denominator);
                if ($denominator != 0) {
                    foreach ($document as $token => $count) {
                        $transform
                            [$category]
                            [$documentIndex]
                            [$token] = $count / $denominator;
                    }
                } else {
                    throw new \RuntimeException("Cannot divide by 0 in DocumentLength transform");
                }
            }
        }

        return $transform;
    }
}

UPDATE: Throw exception if we are going to divide by 0


<?php

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

$config = parse_ini_file("app.ini");

$entityUri = isset($config['entity_uri']) ? $config['entity_uri'] : 'https://depot.tent.is';

$clientFactory = new Depot\Api\Client\ClientFactory;
$client = $clientFactory->create();

try {
    $server = $client->discover($entityUri);
} catch (Exception $e)
{
    include "templates/error.php";
}

include "templates/index.php";

<?php

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

if (file_exists('app.ini')) {
    $config = parse_ini_file("app.ini");
} else {
    $config = array();
}

$entityUri = isset($config['entity_uri']) ? $config['entity_uri'] : 'https://tent.tent.is';

$clientFactory = new Depot\Api\Client\ClientFactory;
$client = $clientFactory->create();

try {
    $server = $client->discover($entityUri);
} catch (Exception $e)
{
    include "templates/error.php";
}

include "templates/index.php";

Make config reader more friendly; show tent.tent.is


<?php
/**
 * @package api
 * @subpackage objects
 */
class KalturaAssetParamsResourceContainer extends KalturaResource
{
	/**
	 * The content resource to associate with asset params
	 * @var KalturaContentResource
	 */
	public $resource;

	/**
	 * The asset params to associate with the reaource
	 * @var int
	 */
	public $assetParamsId;

	public function validateEntry(entry $dbEntry)
	{
		parent::validateEntry($dbEntry);
    	$this->validatePropertyNotNull('resource');
    	$this->validatePropertyNotNull('assetParamsId');
	}

	public function toObject ( $object_to_fill = null , $props_to_skip = array() )
	{
		if(!$object_to_fill)
			$object_to_fill = new kAssetParamsResourceContainer();

		$object_to_fill->setResource($this->resource->toObject());
		$object_to_fill->setAssetParamsId($this->assetParamsId);
		return $object_to_fill;
	}
}

<?php
/**
 * @package api
 * @subpackage objects
 */
class KalturaAssetParamsResourceContainer extends KalturaResource
{
	/**
	 * The content resource to associate with asset params
	 * @var KalturaContentResource
	 */
	public $resource;

	/**
	 * The asset params to associate with the reaource
	 * @var int
	 */
	public $assetParamsId;

	public function validateEntry(entry $dbEntry)
	{
		parent::validateEntry($dbEntry);
    	$this->validatePropertyNotNull('resource');
    	$this->validatePropertyNotNull('assetParamsId');
	}

	public function toObject ( $object_to_fill = null , $props_to_skip = array() )
	{
		if(!$object_to_fill)
			$object_to_fill = new kAssetParamsResourceContainer();

		if($this->resource)
			$object_to_fill->setResource($this->resource->toObject());

		$object_to_fill->setAssetParamsId($this->assetParamsId);
		return $object_to_fill;
	}
}

Make sure resource is not null

Make sure resource is not null

git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@60246 6b8eccd3-e8c5-4e7d-8186-e12b5326b719


<?php

/*
 * Test bootstrapper. This leaves out all stuff registering services and
 * related to request dispatching.
 */

// Install base location
if (!defined('TEST_ROOT')) {
    define('TEST_ROOT', realpath(__DIR__ . '/../../'));
}

// PHPUnit's base location
if (!defined('PHPUNIT_ROOT')) {
    define('PHPUNIT_ROOT', realpath(TEST_ROOT . '/tests/phpunit/unit'));
}

if (!defined('BOLT_AUTOLOAD')) {
    if (is_dir(TEST_ROOT . '/../../../vendor/')) {
        // Composer install
        define('BOLT_AUTOLOAD', TEST_ROOT . '/../../autoload.php');
    } else {
        // Git/tarball install
        define('BOLT_AUTOLOAD', TEST_ROOT . '/vendor/autoload.php');
    }

    // Load the autoloader
    global $CLASSLOADER;
    $CLASSLOADER = require_once BOLT_AUTOLOAD;
}

// Load the upload bootstrap
require_once 'unit/bootstraps/upload-bootstrap.php';

<?php

/*
 * Test bootstrapper. This leaves out all stuff registering services and
 * related to request dispatching.
 */

// Define our install type
if (file_exists(__DIR__ . '/../../../../../vendor/bolt/bolt/')) {
    $installType = 'composer';
} else {
    $installType = 'git';
}

// Install base location
if (!defined('TEST_ROOT')) {
    define('TEST_ROOT', realpath(__DIR__ . '/../../'));
}

// PHPUnit's base location
if (!defined('PHPUNIT_ROOT')) {
    define('PHPUNIT_ROOT', realpath(TEST_ROOT . '/tests/phpunit/unit'));
}

if (!defined('BOLT_AUTOLOAD')) {
    if (is_dir(TEST_ROOT . '/../../../vendor/')) {
        // Composer install
        define('BOLT_AUTOLOAD', TEST_ROOT . '/../../autoload.php');
    } else {
        // Git/tarball install
        define('BOLT_AUTOLOAD', TEST_ROOT . '/vendor/autoload.php');
    }

    // Load the autoloader
    global $CLASSLOADER;
    $CLASSLOADER = require_once BOLT_AUTOLOAD;
}

// Path to Nut
if (!defined('NUT_PATH')) {
    if ($installType === 'composer') {
        define('NUT_PATH', realpath(TEST_ROOT . '/vendor/bolt/bolt/app/nut'));
    } elseif ($installType === 'git') {
        define('NUT_PATH', realpath(TEST_ROOT . '/app/nut'));
    }
}

// Load the upload bootstrap
require_once 'unit/bootstraps/upload-bootstrap.php';

Define an install specific Nut path

[PHPUnit] Define an install specific Nut path


<?php

namespace Tests;

use Faker\Factory;

class TestCase extends \Laravel\Lumen\Testing\TestCase
{
    /**
     * Creates the application.
     *
     * @return \Laravel\Lumen\Application
     */
    public function createApplication()
    {
        return require __DIR__.'/../bootstrap/app.php';
    }

    /**
     * Ran before every test.
     */
    public function setUp()
    {
        parent::setUp();

        // Set these super globals since some packages rely on them
        $_SERVER['HTTP_USER_AGENT'] = '';
        $_SERVER['HTTP_HOST'] = '';
        $_SERVER['REQUEST_URI'] = '';

        // Force the top menu to be enabled for now since the tests are written specifically for this condition
        config(['app.top_menu_enabled' => true]);

        // Create a new faker that every test can use
        $this->faker = (new Factory)->create();
    }
}

<?php

namespace Tests;

use Faker\Factory;

class TestCase extends \Laravel\Lumen\Testing\TestCase
{
    /**
     * Creates the application.
     *
     * @return \Laravel\Lumen\Application
     */
    public function createApplication()
    {
        return require __DIR__.'/../bootstrap/app.php';
    }

    /**
     * Ran before every test.
     */
    public function setUp()
    {
        parent::setUp();

        // Set these super globals since some packages rely on them
        $_SERVER['HTTP_USER_AGENT'] = '';
        $_SERVER['HTTP_HOST'] = '';
        $_SERVER['REQUEST_URI'] = '';

        // Force the top menu to be enabled for now since the tests are written specifically for this condition
        config(['app.top_menu_enabled' => true]);

        // Reset the WSU API key so we never make real connections to the API
        config(['app.wsu_api_key' => '']);

        // Create a new faker that every test can use
        $this->faker = (new Factory)->create();
    }
}

Reset the WSU API key so the tests never make a real connection and will error if it tries to.


<?php

use Illuminate\Contracts\Console\Kernel as KernelContract;

abstract class TestCase extends \Orchestra\Testbench\TestCase
{
    protected function setUp()
    {
        parent::setUp();

        $this->setUpDatabase();
        $this->setUpStorage();
    }

    private function setUpDatabase()
    {
        config(['database.default' => 'testing']);
    }

    private function setUpStorage()
    {
        $this->app->useStoragePath(__DIR__ . '/fixture/storage');
    }

    protected function resolveApplicationConsoleKernel($app)
    {
        $app->singleton(KernelContract::class, Kernel::class);
    }
}

<?php

use Illuminate\Contracts\Console\Kernel as KernelContract;
use Symfony\Component\Finder\Finder;

abstract class TestCase extends \Orchestra\Testbench\TestCase
{
    protected function setUp()
    {
        parent::setUp();

        $this->setUpDatabase();
        $this->setUpStorage();
    }

    private function setUpDatabase()
    {
        config(['database.default' => 'testing']);
    }

    private function setUpStorage()
    {
        $this->app->useStoragePath(__DIR__ . '/fixture/storage');
    }

    protected function resolveApplicationConsoleKernel($app)
    {
        $app->singleton(KernelContract::class, Kernel::class);
    }

    protected function tearDown()
    {
        $this->cleanLogsDirectory();

        parent::tearDown();
    }

    private function cleanLogsDirectory()
    {
        $objects = (new Finder)->in(storage_path('logs'))->depth(0);
        foreach ($objects as $object) {
            if (File::isDirectory($object)) {
                File::deleteDirectory($object);
            } else {
                File::delete($object);
            }
        }
    }
}

Clean logs after tests added.

ICL: Clean logs after tests added.


<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

        return $app;
    }
}

<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
     public function setUp()
     {
        parent::setUp();
        $this->prepareForTests();
     }

     public function prepareForTests()
     {
         Config::set('database.default', 'sqlite');
         Artisan::call('migrate:refresh');
     }

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

        return $app;
    }
}

Add call to migrate data into sqlite

chore(tests): Add call to migrate data into sqlite


<?php

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

namespace Symfony\Component\Form\Tests\Resources;

use PHPUnit\Framework\TestCase;
use PHPUnit\Util\Xml\Loader;

class TranslationFilesTest extends TestCase
{
    /**
     * @dataProvider provideTranslationFiles
     */
    public function testTranslationFileIsValid($filePath)
    {
        $loader = class_exists(Loader::class)
            ? [new Loader(), 'loadFile']
            : ['PHPUnit\Util\XML', 'loadfile'];

        $loader($filePath, false, false, true);

        $this->addToAssertionCount(1);
    }

    public function provideTranslationFiles()
    {
        return array_map(
            function ($filePath) { return (array) $filePath; },
            glob(\dirname(__DIR__, 2).'/Resources/translations/*.xlf')
        );
    }

    public function testNorwegianAlias()
    {
        $this->assertFileEquals(
            \dirname(__DIR__, 2).'/Resources/translations/validators.nb.xlf',
            \dirname(__DIR__, 2).'/Resources/translations/validators.no.xlf',
            'The NO locale should be an alias for the NB variant of the Norwegian language.'
        );
    }
}

<?php

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

namespace Symfony\Component\Form\Tests\Resources;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Util\XliffUtils;

class TranslationFilesTest extends TestCase
{
    /**
     * @dataProvider provideTranslationFiles
     */
    public function testTranslationFileIsValid($filePath)
    {
        $document = new \DOMDocument();
        $document->loadXML(file_get_contents($filePath));

        $errors = XliffUtils::validateSchema($document);

        $this->assertCount(0, $errors, sprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message'))));
    }

    public function provideTranslationFiles()
    {
        return array_map(
            function ($filePath) { return (array) $filePath; },
            glob(\dirname(__DIR__, 2).'/Resources/translations/*.xlf')
        );
    }

    public function testNorwegianAlias()
    {
        $this->assertFileEquals(
            \dirname(__DIR__, 2).'/Resources/translations/validators.nb.xlf',
            \dirname(__DIR__, 2).'/Resources/translations/validators.no.xlf',
            'The NO locale should be an alias for the NB variant of the Norwegian language.'
        );
    }
}

Validate XLIFF files in tests using the XSD


<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('users_discussions', function (Blueprint $table) {
            $table->enum('subscription', ['follow', 'ignore'])->nullable();
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('users_discussions', function (Blueprint $table) {
            $table->dropColumn('subscription');
        });
    }
];

<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Database\Migration;

return Migration::addColumns('users_discussions', [
    'subscription' => ['enum', 'allowed' => ['follow', 'ignore'], 'nullable' => true]
]);

Use new shortcuts for migrations

Use new shortcuts for migrations


<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-console',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'console\controllers',
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
    ],
    'params' => $params,
];

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-console',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'console\controllers',
    'controllerMap' => [
        'migrate' => [
            'class' => 'yii\console\controllers\MigrateController',
            'templateFile' => '@console/views/migration.php',
        ],
    ],
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
    ],
    'params' => $params,
];

Adjust migrate console controller to use a new migration template view file.


<?php

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

class AddMessageIdToSentEmailsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('sent_emails', function(Blueprint $table) {
            $table->string('message_id')->nullable();
            $table->text('meta')->default('[]');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('sent_emails', function(Blueprint $table) {
            $table->dropColumn('message_id');
            $table->dropColumn('meta');
        });
    }
}

<?php

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

class AddMessageIdToSentEmailsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('sent_emails', function(Blueprint $table) {
            $table->string('message_id')->nullable();
            $table->text('meta');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('sent_emails', function(Blueprint $table) {
            $table->dropColumn('message_id');
            $table->dropColumn('meta');
        });
    }
}

Fix migration for older mysql versions that do not support default values on blob/text columns


<?php
/**
 * @author Boris Guéry <guery.b@gmail.com>
 */

namespace Bgy\OAuth2;

use Bgy\OAuth2\Utils\Ensure;

class ResourceOwner
{
    private $resourceOwnerId, $resourceOwnerType;

    public function __construct($resourceOwnerId, $resourceOwnerType)
    {
        Ensure::string($resourceOwnerId, $resourceOwnerType);
        $this->resourceOwnerId   = $resourceOwnerId;
        $this->resourceOwnerType = $resourceOwnerType;
    }

    public function getResourceOwnerId()
    {
        return $this->resourceOwnerId;
    }

    public function getResourceOwnerType()
    {
        return $this->resourceOwnerType;
    }
}

<?php
/**
 * @author Boris Guéry <guery.b@gmail.com>
 */

namespace Bgy\OAuth2;

use Bgy\OAuth2\Utils\Ensure;

class ResourceOwner
{
    private $resourceOwnerId;
    private $resourceOwnerType;

    public function __construct($resourceOwnerId, $resourceOwnerType)
    {
        Ensure::string($resourceOwnerId, $resourceOwnerType);
        $this->resourceOwnerId   = $resourceOwnerId;
        $this->resourceOwnerType = $resourceOwnerType;
    }

    public function getResourceOwnerId()
    {
        return $this->resourceOwnerId;
    }

    public function getResourceOwnerType()
    {
        return $this->resourceOwnerType;
    }
}

Declare each attributes on a separate statement


<?php
/**
* Verb      Path                  Action
* GET       /members              index
* GET       /members/create       create
* POST      /members              store
* GET       /members/{id}         show
* GET       /members/{id}/edit    edit
* PUT/PATCH /members/{id}         update
* DELETE    /members/{id}         destroy
*/
class MembersController extends BaseController {

  /**
  * The database table implementation.
  *
  * @var Members
  */
  protected $member_roles;

  /**
  * Set our Member instance.
  *
  * @param Member $member
  * @return void
  */
  public function __construct(MemberRoles $member_roles)
  {
    $this->member_roles = $member_roles;
  }

  /**
  * GET -> /members
  *
  * @return View
  */
  public function index ()
  {
    $roles = $this->member_roles->with(array('members' => function($query)
    {
      $query->orderBy('last_name')->orderBy('first_name');
    }))->get();

    return View::make('members.index')->with('roles', $roles);
  }

}

<?php
/**
* Verb      Path                  Action
* GET       /members              index
* GET       /members/create       create
* POST      /members              store
* GET       /members/{id}         show
* GET       /members/{id}/edit    edit
* PUT/PATCH /members/{id}         update
* DELETE    /members/{id}         destroy
*/
class MembersController extends BaseController {

  /**
  * The database table implementation.
  *
  * @var Members
  */
  protected $member_roles;

  /**
  * Set our Member instance.
  *
  * @param Member $member
  * @return void
  */
  public function __construct(MemberRoles $member_roles)
  {
    $this->member_roles = $member_roles;
  }

  /**
  * GET -> /members
  *
  * @return View
  */
  public function index ()
  {
    $roles = $this->member_roles->with(array('members' => function($query)
    {

      $query->orderBy('last_name')->orderBy('first_name');

    }))
    ->where('id', '<>', 6)->get();

    return View::make('members.index')->with('roles', $roles);
  }

}

Make sure we only fetch the member roles we want to be displayed on the members page.


<?php

namespace Eduardokum\LaravelMailAutoEmbed\Embedder;

use Eduardokum\LaravelMailAutoEmbed\Models\EmbeddableEntity;
use Swift_EmbeddedFile;
use Swift_Image;
use Swift_Message;

class AttachmentEmbedder extends Embedder
{
    /**
     * @var  Swift_Message
     */
    private $message;

    /**
     * AttachmentEmbedder constructor.
     * @param  Swift_Message $message
     */
    public function __construct(Swift_Message $message)
    {
        $this->message = $message;
    }

    /**
     * @param  string  $url
     */
    public function fromUrl($url)
    {
        $filePath = str_replace(url('/'), public_path('/'), $url);

        if (!file_exists($filePath)) {
            return $url;
        }

        return $this->embed(
            Swift_Image::fromPath($filePath)
        );
    }

    /**
     * @param  EmbeddableEntity  $entity
     */
    public function fromEntity(EmbeddableEntity $entity)
    {
        return $this->embed(
            new Swift_EmbeddedFile(
                $entity->getRawContent(),
                $entity->getFileName(),
                $entity->getMimeType()
            )
        );
    }

    /**
     * @param  Swift_EmbeddedFile  $attachment
     * @return string
     */
    private function embed(Swift_EmbeddedFile $attachment)
    {
        return $this->message->embed($attachment);
    }
}

<?php

namespace Eduardokum\LaravelMailAutoEmbed\Embedder;

use Swift_Image;
use Swift_Message;
use Swift_EmbeddedFile;
use Eduardokum\LaravelMailAutoEmbed\Models\EmbeddableEntity;

class AttachmentEmbedder extends Embedder
{
    /**
     * @var  Swift_Message
     */
    protected $message;

    /**
     * AttachmentEmbedder constructor.
     * @param  Swift_Message $message
     */
    public function __construct(Swift_Message $message)
    {
        $this->message = $message;
    }

    /**
     * @param  string  $url
     */
    public function fromUrl($url)
    {
        $filePath = str_replace(url('/'), public_path('/'), $url);

        if (!file_exists($filePath)) {
            return $url;
        }

        return $this->embed(
            Swift_Image::fromPath($filePath)
        );
    }

    /**
     * @param  EmbeddableEntity  $entity
     */
    public function fromEntity(EmbeddableEntity $entity)
    {
        return $this->embed(
            new Swift_EmbeddedFile(
                $entity->getRawContent(),
                $entity->getFileName(),
                $entity->getMimeType()
            )
        );
    }

    /**
     * @param  Swift_EmbeddedFile  $attachment
     * @return string
     */
    protected function embed(Swift_EmbeddedFile $attachment)
    {
        return $this->message->embed($attachment);
    }
}

Change to protected instead private

Change to protected instead private

It's should be like this. No need to make function private.


<?php

namespace OrcaServices\Heartbeat\Heartbeat\Sensor;

use Migrations\Migrations;
use OrcaServices\Heartbeat\Heartbeat\Sensor;

/**
 * DB Up to Date Sensor
 */
class DBUpToDate extends Sensor
{

    /**
     * @inheritdoc
     */
    protected function _getStatus()
    {
        $dbMigrated = true;
        try {
            $migrations = new Migrations();
            $status = $migrations->status();
            $lastStatus = array_pop($status);
            if ($lastStatus['status'] === 'down') {
                $dbMigrated = false;
            }
        } catch (\Exception $e) {
            $dbMigrated = false;
        }

        return $dbMigrated;
    }

}

<?php

namespace OrcaServices\Heartbeat\Heartbeat\Sensor;

use Migrations\Migrations;
use OrcaServices\Heartbeat\Heartbeat\Sensor;

/**
 * DB Up to Date Sensor
 */
class DBUpToDate extends Sensor
{
    /**
     * Migration status indicating the migration was executed successfully
     */
    const MIGRATION_STATUS_UP = 'up';

    /**
     * @inheritdoc
     */
    protected function _getStatus()
    {
        $dbMigrated = true;
        try {
            $migrations = new Migrations();
            $status = $migrations->status();
            $lastStatus = array_pop($status);
            if ($lastStatus['status'] !== self::MIGRATION_STATUS_UP) {
                $dbMigrated = false;
            }
        } catch (\Exception $e) {
            $dbMigrated = false;
        }

        return $dbMigrated;
    }

}

Improve readability and replace magic literal


<?php

namespace Orchestra\Tenanti\Tests\Unit\Migrator;

use Mockery as m;
use Orchestra\Tenanti\Migrator\Creator;
use PHPUnit\Framework\TestCase;

class CreatorTest extends TestCase
{
    /**
     * Teardown the test environment.
     */
    protected function tearDown(): void
    {
        m::close();
    }

    /**
     * Test Orchestra\Tenanti\Migrator\Creator::getStubPath()
     * method.
     *
     * @test
     */
    public function testGetStubPath()
    {
        $files = m::mock('Illuminate\Filesystem\Filesystem');

        $stub = new Creator($files);

        $this->assertStringContainsString('src/Migrator/stubs', $stub->stubPath());
    }
}

<?php

namespace Orchestra\Tenanti\Tests\Unit\Migrator;

use Mockery as m;
use Orchestra\Tenanti\Migrator\Creator;
use PHPUnit\Framework\TestCase;

class CreatorTest extends TestCase
{
    /**
     * Teardown the test environment.
     */
    protected function tearDown(): void
    {
        m::close();
    }

    /**
     * Test Orchestra\Tenanti\Migrator\Creator::getStubPath()
     * method.
     *
     * @test
     */
    public function testGetStubPath()
    {
        $files = m::mock('Illuminate\Filesystem\Filesystem');

        $stub = new Creator($files);

        $path = \realpath(__DIR__.'/../../../');

        $this->assertStringContainsString($path.\DIRECTORY_SEPARATOR.'src/Migrator/stubs', $stub->stubPath());
    }
}

Update test to cover windows environment

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace FD\PrivateMessageBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * ConversationRepository
 */
class ConversationRepository extends EntityRepository
{
    /**
     * Get all conversation of a user where he's involved in as recipient or author.
     *
     * @param UserInterface $user : instance of the user.
     * @return array
     */
    public function getAllByRecipient(UserInterface $user)
    {
        $qb = $this->createQueryBuilder('c')
            ->join('c.recipients', 'r')
            ->where('r.id = :user OR c.author = :user')
            ->setParameter('user', $user)
            ->orderBy('c.created', 'DESC');

        return $qb->getQuery()->getResult();
    }
}

<?php

namespace FD\PrivateMessageBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * ConversationRepository
 */
class ConversationRepository extends EntityRepository
{
    /**
     * Get all conversations of a user being involved in as recipient or author.
     *
     * @param UserInterface $user : instance of the user.
     * @return array
     */
    public function getAllByRecipient(UserInterface $user)
    {
        $qb = $this->createQueryBuilder('c')
            ->join('c.recipients', 'r')
            ->where('r.id = :user OR c.author = :user')
            ->setParameter('user', $user)
            ->orderBy('c.created', 'DESC');

        return $qb->getQuery()->getResult();
    }

    /**
     * Get a conversation by ID.
     * Related private messages, authors, recipients are loaded by a JOIN statement.
     *
     * @param int $cid : technical ID of the conversation.
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function getOneById($cid)
    {
        $qb = $this->createQueryBuilder('c')
            ->join('c.recipients', 'r')
            ->join('c.messages', 'm')
            ->join('m.author', 'a')
            ->addSelect('r')
            ->addSelect('m')
            ->addSelect('a')
            ->where('c.id = :cid')
            ->setParameter('cid', $cid)
            ->orderBy('m.created', 'ASC');

        return $qb->getQuery()->getOneOrNullResult();
    }
}

Add method to Conversation's repository to get one by ID joining related entities (author, messages ...etc)


<?php
/**
 * Created by PhpStorm.
 * User: Zooma
 * Date: 21/09/15
 * Time: 15:58
 */

class Channel_Engine_Order_Complete {

    private $client;

    /**
     * Constructor
     */
    public function __construct($client) {

        $this->client = $client;
        add_action('woocommerce_order_status_completed', array($this,'post_shipment_complete_status') , 0, 1 );
    }

    public function post_shipment_complete_status($wc_order_id){

        require_once(plugin_dir_path(__FILE__) . 'class-channel-engine-api.php');

        $channel_engine_api_client = new Channel_Engine_API($this->client);
        $channel_engine_api_client->post_shipment_complete_status($wc_order_id);
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: Zooma
 * Date: 21/09/15
 * Time: 15:58
 */

class Channel_Engine_Order_Complete {

    private $client;

    /**
     * Constructor
     */
    public function __construct($client) {

        $this->client = $client;
        add_action('woocommerce_order_status_completed', array($this,'post_shipment_complete_status'), 5, 1);
    }

    public function post_shipment_complete_status($wc_order_id){

        require_once(plugin_dir_path(__FILE__) . 'class-channel-engine-api.php');

        $channel_engine_api_client = new Channel_Engine_API($this->client);
        $channel_engine_api_client->post_shipment_complete_status($wc_order_id);
    }

}

Change webhook priority to allow store owners to use the event before us


<?php

namespace App\Providers;

use App\Tag;
use App\Note;
use Validator;
use App\WebMention;
use App\Observers\WebMentionObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Validate photos for a maximum filesize
        Validator::extend('photosize', function ($attribute, $value, $parameters, $validator) {
            if ($value[0] !== null) {
                foreach ($value as $file) {
                    if ($file->getSize() > 5000000) {
                        return false;
                    }
                }
            }

            return true;
        });

        //Add tags for notes
        Note::created(function ($note) {
            $tagsToAdd = [];
            preg_match_all('/#([^\s<>]+)\b/', $note, $tags);
            foreach ($tags[1] as $tag) {
                $tag = Tag::normalizeTag($tag);
            }
            $tags = array_unique($tags[1]);
            foreach ($tags as $tag) {
                $tag = Tag::firstOrCreate(['tag' => $tag]);
                $tagsToAdd[] = $tag->id;
            }
            if (count($tagsToAdd > 0)) {
                $note->tags()->attach($tagsToAdd);
            }
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

<?php

namespace App\Providers;

use App\Tag;
use App\Note;
use Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Validate photos for a maximum filesize
        Validator::extend('photosize', function ($attribute, $value, $parameters, $validator) {
            if ($value[0] !== null) {
                foreach ($value as $file) {
                    if ($file->getSize() > 5000000) {
                        return false;
                    }
                }
            }

            return true;
        });

        //Add tags for notes
        Note::created(function ($note) {
            $tagsToAdd = [];
            preg_match_all('/#([^\s<>]+)\b/', $note, $tags);
            foreach ($tags[1] as $tag) {
                $tag = Tag::normalizeTag($tag);
            }
            $tags = array_unique($tags[1]);
            foreach ($tags as $tag) {
                $tag = Tag::firstOrCreate(['tag' => $tag]);
                $tagsToAdd[] = $tag->id;
            }
            if (count($tagsToAdd > 0)) {
                $note->tags()->attach($tagsToAdd);
            }
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Remove use statements that are no longer needed


<!DOCTYPE html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title><?php wp_title('|', true, 'right'); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <?php wp_head(); ?>

  <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo esc_url(get_feed_link()); ?>">
</head>

<!doctype html>
<html class="no-js" <?php language_attributes(); ?>>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title><?php wp_title('|', true, 'right'); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <?php wp_head(); ?>

  <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo esc_url(get_feed_link()); ?>">
</head>

Use `<!doctype html>` instead of `<!DOCTYPE html>`

See https://github.com/h5bp/html5-boilerplate/commit/e67e9cc7c1b5a395521a6ee43031becc321e605a


<?php
if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('SMF'))
	require_once(dirname(__FILE__) . '/SSI.php');

elseif (!defined('SMF'))
	die('<b>Error:</b> Cannot install - please verify you put this in the same place as SMF\'s index.php.');

global $smcFunc;

// First load the SMF 2's Extra DB Functions
db_extend('packages');

	$smcFunc['db_create_table']('{db_prefix}topic_clones',
	array(
		array(
			'name' => 'id_topic',
			'type' => 'mediumint',
			'size' => 8,
			'null' => false,
		),
		array(
			'name' => 'id_board',
			'type' => 'smallint',
			'size' => 5,
			'null' => false,
		),
	),
	array(
		array(
			'name' => 'id_board',
			'type' => 'index',
			'columns' => array('id_board'),
		),
	), 'update');
?>

<?php
if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('SMF'))
	require_once(dirname(__FILE__) . '/SSI.php');

elseif (!defined('SMF'))
	die('<b>Error:</b> Cannot install - please verify you put this in the same place as SMF\'s index.php.');

global $smcFunc;

// First load the SMF 2's Extra DB Functions
db_extend('packages');

	$smcFunc['db_create_table']('{db_prefix}topic_clones',
	array(
		array(
			'name' => 'id_topic',
			'type' => 'mediumint',
			'size' => 8,
			'null' => false,
		),
		array(
			'name' => 'id_board',
			'type' => 'smallint',
			'size' => 5,
			'null' => false,
		),
	),
	array(
		array(
			'name' => 'id_board',
			'type' => 'index',
			'columns' => array('id_board'),
		),
	), 'update');

	// Repair any old bugs.
	// Delete dupes
	$smcFunc['db_query']('', '
		DELETE c FROM {db_prefix}topic_clones AS c
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
		WHERE t.id_board = c.id_board AND t.id_topic = c.id_topic',
		array()
	);

	// Delete non exists
	$smcFunc['db_query']('', '
		DELETE c FROM {db_prefix}topic_clones AS c
			LEFT JOIN {db_prefix}messages AS m ON (m.id_topic = c.id_topic)
		WHERE m.id_topic IS NULL',
		array()
	);
?>

Fix any prior 0.4.1 errors

Fix any prior 0.4.1 errors

Fix any database errors caused by prior versions.

Signed-off-by: sicommnend <873c68643dbf4e0dfa0840fe4a2fe9c1228e35cd@users.noreply.github.com>


<div class="form_row<?php echo ' form_row_'.implode(' form_row_', $form->vars['block_prefixes']).($required ? ' form_required' : '').($valid && $view['nyrodev']->isPost() ? ' form_valid' : '').(count($errors) > 0 ? ' form_error' : '') ?>">
    <?php echo $view['form']->label($form) ?>
    <?php echo $view['form']->widget($form) ?>
	*
    <?php echo $view['form']->errors($form) ?>

<div class="form_row<?php echo ' form_row_'.implode(' form_row_', $form->vars['block_prefixes']).($required ? ' form_required' : '').($valid && $view['nyrodev']->isPost() ? ' form_valid' : '').(count($errors) > 0 ? ' form_error' : '') ?>">
	<?php
	$help = null;
	if (isset($form->vars['attr']) && isset($form->vars['attr']['help'])) {
		$help = $form->vars['attr']['help'];
		unset($form->vars['attr']['help']);
	}
	?>
    <?php echo $view['form']->label($form) ?>
    <?php echo $view['form']->widget($form) ?>
	*
	<?php if (isset($help) && $help) : ?>
		<?php echo $help ?>
	<?php endif ?>
    <?php echo $view['form']->errors($form) ?>

Add help attr ability in form_row template


<?php

class ZendDbTest extends \PHPUnit_Framework_TestCase
{
    public function testInstantiateDbAdapter()
    {
        $adapter = \Zend_Db::factory(
            'Pdo_Sqlite',
            array(
                'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
            )
        );
        $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter);
    }
}

<?php

class ZendDbTest extends \PHPUnit_Framework_TestCase
{
    public function testInstantiateDbAdapter()
    {
        $adapter = \Zend_Db::factory(
            'Pdo_Sqlite',
            array(
                'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
            )
        );
        $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter);
    }

    public function testZendDbFactoryWithZendConfig()
    {
        $config = new Zend_Config(
            array(
                'database' => array(
                    'adapter' => 'Pdo_Sqlite',
                    'params'  => array(
                        'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite'
                    )
                )
            )
        );

        $adapter = Zend_Db::factory($config->database);
        $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter);
    }
}

Add Zend_Db Test with Zend_Config

Add Zend_Db Test with Zend_Config


<?php
error_reporting(0);

$ts = $_REQUEST['ts'];
$etag = md5($ts);

$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false;
if ($ifNoneMatch == $etag) {
	header('HTTP/1.0 304 Not Modified');
	die; // stop processing
}

header("Etag: " . $etag);

if ( $ifNoneMatch ) {
	echo "OK: " . $etag;
} else {
	echo "FAIL";
}

?>

<?php
error_reporting(0);

$ts = $_REQUEST['ts'];
$etag = md5($ts);

$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : "";
preg_match('/"([^"]+)"/', $ifNoneMatch, $matches);
$ifNoneMatch = isset($matches[1]) ? $matches[1] : false;

if ($ifNoneMatch == $etag) {
	header('HTTP/1.0 304 Not Modified');
	die; // stop processing
}

header("Etag: W/\"" . $etag . "\"");

if ( $ifNoneMatch ) {
	echo "OK: " . $etag;
} else {
	echo "FAIL";
}

?>

Use weak ETag header in tests

Ajax: Use weak ETag header in tests

See http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation

Close gh-1448
(cherry picked from commit d2aa969206aa1b7738b911cdaf29038f249b5066)


<?php

/**
 * @desc - get a plugin
 * @param string $name - the plugin folder name
 * @param string|array $options - options to give plugin
 */
function plugin($name, $options = false) {
	if (file_exists(SITE . "/plugins/$name")) {
		if (!file_exists(SITE . "/plugins/$name/index.php")) {
			die("The plugin \"$name\" does not have an index.php file");
		}

		include SITE . "/plugins/$name/index.php";

        // dash-case into camelCase
        $fnName = str_replace('-', '', ucwords($name, '-'));
        $fnName = lcfirst($fnName);

		if (function_exists($fnName)) {
			$fnName($options);
		} else {
			die("It seems like plugin '$name' misses: '$fnName()' function");
		}
	}
}

?>

<?php

/**
 * @desc - get a plugin
 * @param string $name - the plugin folder name
 * @param string|array $options - options to give plugin
 */
function plugin($name, $options = false) {
	if (is_dir(SITE . "/plugins/$name")) {
		if (!file_exists(SITE . "/plugins/$name/index.php")) {
			die("The plugin \"$name\" does not have an index.php file");
		}

		include SITE . "/plugins/$name/index.php";

        // dash-case into camelCase
        $fnName = str_replace('-', '', ucwords($name, '-'));
        $fnName = lcfirst($fnName);

		if (function_exists($fnName)) {
			$fnName($options);
		} else {
			die("It seems like plugin '$name' misses: '$fnName()' function");
		}
	} else {
		die("No plugin named $name exists in /site/plugins - should be a directory");
	}
}

?>

Use is_dir and add error message

Use is_dir and add error message


<?php

namespace App\Libs;

use \App\Model\Plugin as Plugin;

class ShortCode extends Model{

	public $table = 'plugins';
	private static $widgets = array();

	public static function initalize(){

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

			$namespace = $plugin->getRegisterClass();

			if(Plugin::exists($plugin->root_dir) && method_exists($namespace, 'widget')){
				\View::addNamespace('plugin', [
												'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."View",
												'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."resources".DIRECTORY_SEPARATOR."views"
												]);

				self::$widgets["{[".$plugin->root_dir."]}"] = $namespace::widget();
			}

		}

	}

	public static function getAll(){
		return self::$widgets;
	}

	public static function resolve($shortcode){

		return isset(self::$widgets["{[".$shortcode."]}"])? eval("?>".self::$widgets["{[".$shortcode."]}"]."<?php") : NULL;
	}

	public static function compile($page){

		return count(self::$widgets) === 0? $page : eval("?>".str_replace(array_keys(self::$widgets), array_values(self::$widgets), $page)."<?php");
	}

}

<?php

namespace App\Libs;

use \App\Model\Plugin as Plugin;

class ShortCode extends Model{

	public $table = 'plugins';
	private static $widgets = array();

	public static function initalize(){

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

			$namespace = $plugin->getRegisterClass();

			if(Plugin::exists($plugin->root_dir) && method_exists($namespace, 'widget')){
				\View::addNamespace('plugin', [
												'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."View",
												'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."resources".DIRECTORY_SEPARATOR."views"
												]);

				self::$widgets["{[".$plugin->root_dir."]}"] = $namespace::widget();
			}

		}

	}

	public static function getAll(){
		return self::$widgets;
	}

	public static function resolve($shortcode){

		echo isset(self::$widgets["{[".$shortcode."]}"])? self::$widgets["{[".$shortcode."]}"] : "";
	}

	public static function compile($page){

		echo count(self::$widgets) === 0? $page : str_replace(array_keys(self::$widgets), array_values(self::$widgets), $page);
	}

}

Drop eval from plugin execution

Drop eval from plugin execution


<?php

namespace Tests\CryptoSystem;

use Rosio\EncryptedCookie\CryptoSystem\AES_SHA1;

class AES_SHA1Test extends \PHPUnit_Framework_TestCase
{
	protected $cryptoSystem;

	function setUp ()
	{
		$this->cryptoSystem = new AES_SHA1('symkey', 'hmackey');
	}

	public function testEncryptDecrypt ()
	{
		$data = 'Some data. Special characters: ' . chr(1) . chr(2) . chr(3) . '.';

		$encData = $this->cryptoSystem->encrypt($data, 0);
		$decData = $this->cryptoSystem->decrypt($encData);

		$this->assertEquals($data, $decData);
	}
}

<?php

namespace Tests\CryptoSystem;

use Rosio\EncryptedCookie\CryptoSystem\AES_SHA1;
use Rosio\EncryptedCookie\Exception\InputExpiredException;

class AES_SHA1Test extends \PHPUnit_Framework_TestCase
{
	protected $cryptoSystem;

	function setUp ()
	{
		$this->cryptoSystem = new AES_SHA1('symkey', 'hmackey');
	}

	public function testEncryptDecrypt ()
	{
		$data = 'Some data. Special characters: ' . chr(1) . chr(2) . chr(3) . '.';

		$encData = $this->cryptoSystem->encrypt($data, 0);
		$decData = $this->cryptoSystem->decrypt($encData);

		$this->assertEquals($data, $decData);
	}

	/**
	 * @expectedException \Rosio\EncryptedCookie\Exception\InputExpiredException
	 */
	public function testExpiration ()
	{
		$data = 'Some data.';

		$encData = $this->cryptoSystem->encrypt($data, 1);
		sleep(2);
		$decData = $this->cryptoSystem->decrypt($encData);
	}
}

Add test to check expiration

Add test to check expiration


<?php

/*
 * This file is part of the Integrated package.
 *
 * (c) e-Active B.V. <integrated@e-active.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Integrated\Bundle\ContentBundle\Form\Type\Job;

use Symfony\Component\OptionsResolver\OptionsResolver;

use Braincrafted\Bundle\BootstrapBundle\Form\Type\BootstrapCollectionType;

/**
 * @author Johan Liefers <johan@e-active.nl>
 */
class ContactPersonsType extends BootstrapCollectionType
{
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults([
            'type' => CompanyJobType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'label' => 'Contact persons',
            'delete_button_text' => 'x'
        ]);
    }

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

<?php

/*
 * This file is part of the Integrated package.
 *
 * (c) e-Active B.V. <integrated@e-active.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Integrated\Bundle\ContentBundle\Form\Type\Job;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

use Braincrafted\Bundle\BootstrapBundle\Form\Type\BootstrapCollectionType;

/**
 * @author Johan Liefers <johan@e-active.nl>
 */
class ContactPersonsType extends AbstractType
{
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'type' => CompanyJobType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'label' => 'Contact persons',
            'delete_button_text' => 'x'
        ]);
    }

    public function getParent()
    {
        return BootstrapCollectionType::class;
    }

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

Extend AbstractType and use getParent

Extend AbstractType and use getParent


<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

$loader = require __DIR__ . "/../vendor/autoload.php";
$loader->add('Monolog\\', __DIR__);

date_default_timezone_set('UTC');

Set default timezone to avoid tripping up hhvm


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ContentBundle\Traits;

use Knp\DoctrineBehaviors\Model\Translatable\Translatable;

/**
 * Translatable
 */
trait TranslatableTrait
{
    use Translatable;

    /**
     * {@inheritdoc}
     */
    protected function proxyCurrentLocaleTranslation($method, array $arguments = [])
    {
        $translation = $this->translate($this->getCurrentLocale());

        if (!method_exists($translation, $method) && 0 === strpos($method, 'get')) {
            $method = substr_replace($method, 'is', 0, 3);
        }

        return call_user_func_array(array($translation, $method), $arguments);
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ContentBundle\Traits;

use Knp\DoctrineBehaviors\Model\Translatable\Translatable;

/**
 * Translatable
 */
trait TranslatableTrait
{
    use Translatable;

    /**
     * @param string $property Property name
     * @param mixed  $value    Property value
     *
     * @return mixed
     */
    public function __set($property, $value)
    {
        return $this->proxyCurrentLocaleTranslation('set'.ucfirst($property), array($value));
    }

    /**
     * @param string $property Property name
     *
     * @return mixed
     */
    public function __get($property)
    {
        return $this->proxyCurrentLocaleTranslation('get'.ucfirst($property));
    }

    /**
     * @param string $method Method name
     * @param array  $args   Method arguments
     *
     * @return mixed
     */
    public function __call($method, array $args)
    {
        return $this->proxyCurrentLocaleTranslation($method, $args);
    }

    /**
     * {@inheritdoc}
     */
    protected function proxyCurrentLocaleTranslation($method, array $arguments = array())
    {
        $translation = $this->translate($this->getCurrentLocale());

        if (!method_exists($translation, $method) && 0 === strpos($method, 'get')) {
            $method = substr_replace($method, 'is', 0, 3);
        }

        return call_user_func_array(array($translation, $method), $arguments);
    }
}

Implement __set(), __get() and __call() in translatable trait.


<?php
$pagination_custom_page_size = $this->configuration->getValue('get.pagination_custom_page_size');
$max_items = $this->configuration->getValue('get.max_items');
?>
  /**
   * Returns the list of pagination validators
   * @return  array  an array of validators
   */
  protected function getPaginationValidators()
  {
    $validators = array();
    $validators['page'] = new sfValidatorInteger(array('min' => 1, 'required' => false));
<?php if ($pagination_custom_page_size && ($max_items > 0)): ?>
    $validators['page_size'] = new sfValidatorInteger(array(
      'min' => 1,
      'max' => <?php echo $max_items ?>,
      'required' => false
    ));
<?php endif; ?>
    return $validators;
  }

<?php
$pagination_custom_page_size = $this->configuration->getValue('get.pagination_custom_page_size');
$max_items = $this->configuration->getValue('get.max_items');
?>
  /**
   * Returns the list of pagination validators
   * @return  array  an array of validators
   */
  protected function getPaginationValidators()
  {
    $validators = array();
    $validators['page'] = new sfValidatorInteger(array('min' => 1, 'required' => false));
<?php if ($pagination_custom_page_size): ?>
    $validators['page_size'] = new sfValidatorInteger(array(
      'min' => 1,
<?php if ($max_items > 0): ?>
      'max' => <?php echo $max_items ?>,
<?php endif; ?>
      'required' => false
    ));
<?php endif; ?>
    return $validators;
  }

Add page_size validator even if get.max_items is not set


<?php

use Mockery as m;

class RepositoryTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->mock = m::mock('App\Models\TestEntity')->makePartial();
        $this->app->instance('App\Models\TestEntity', $this->mock);

        $this->repository = $this->app->make('App\Repositories\TestRepository');
    }

    /**
     * Test TestEntity Repository.
     */
    public function testAll()
    {
        $this->mock->shouldReceive('get')
            ->once()
            ->with(m::type('array'))
            ->andReturn([]);

        $result = $this->repository->all();

        $this->assertTrue(is_array($result));
    }

    public function testCreate()
    {
        $this->mock->shouldReceive('create')
            ->once()
            ->with(m::type('array'))
            ->andReturn($this->mock);

        $result = $this->repository->create(['foo' => 'bar']);

        $this->assertTrue(is_object($result));
    }

    public function testFind()
    {
        $this->mock->shouldReceive('findOrFail')
            ->once()
            ->andReturn($this->mock);

        $result = $this->repository->find('foobar');

        $this->assertTrue(is_object($result));
    }

    public function testFailingFind()
    {
        $this->app->instance('App\Models\TestEntity', null);
        $repository = new App\Repositories\TestRepository($this->app);

        $this->setExpectedException('Illuminate\Database\Eloquent\ModelNotFoundException');

        $result = $repository->find(null);
    }
}

<?php

use Mockery as m;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class RepositoryTest extends TestCase
{
    use DatabaseTransactions;

    public function setUp()
    {
        parent::setUp();

        $this->mock = m::mock('App\Models\TestEntity')->makePartial();
        $this->app->instance('App\Models\TestEntity', $this->mock);

        $this->repository = $this->app->make('App\Repositories\TestRepository');
    }

    /**
     * Test TestEntity Repository.
     */
    public function testAll()
    {
        $this->mock->shouldReceive('get')
            ->once()
            ->with(m::type('array'))
            ->andReturn([]);

        $result = $this->repository->all();

        $this->assertTrue(is_array($result));
    }

    public function testCreate()
    {
        $this->mock->shouldReceive('create')
            ->once()
            ->with(m::type('array'))
            ->andReturn($this->mock);

        $result = $this->repository->create(['foo' => 'bar']);

        $this->assertTrue(is_object($result));
    }

    public function testFind()
    {
        $this->mock->shouldReceive('findOrFail')
            ->once()
            ->andReturn($this->mock);

        $result = $this->repository->find('foobar');

        $this->assertTrue(is_object($result));
    }

    public function testFailingFind()
    {
        $this->app->instance('App\Models\TestEntity', null);
        $repository = new App\Repositories\TestRepository($this->app);

        $this->setExpectedException('Illuminate\Database\Eloquent\ModelNotFoundException');

        $result = $repository->find(null);
    }
}

Enable database transactions for these tests


<?php

namespace App\Models\Items;

use Illuminate\Database\Eloquent\Model;

class Vehicle extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'vehicles';

    /**
     * The primary key column.
     *
     * @var string
     */
    protected $primaryKey = 'code';

    /**
     * Indicate if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * Get vehicles with pagination.
     *
     * @param int $perPage
     *
     * @return array
     */
    public static function withPagination($perPage)
    {
        $results = Item::join('vehicles', 'vehicles.code', '=', 'items.code')
        ->select('items.price', 'items.images')
        ->paginate($perPage);

        $data = [];
        if (!$results->isEmpty()) {
            $data['from'] = $results->firstItem();
            $data['to'] = $results->lastItem();
            $data['total'] = $results->total();
            $data['limit'] = $results->perPage();

            foreach ($results as $result) {
                $item = new self();
                $item->price = $result->price;
                $item->image = json_decode($result->images)[0];

                $data['items'][] = $item;
            }
        }

        return $data;
    }
}

<?php

namespace App\Models\Items;

use Illuminate\Database\Eloquent\Model;

class Vehicle extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'vehicles';

    /**
     * The primary key column.
     *
     * @var string
     */
    protected $primaryKey = 'code';

    /**
     * Indicate if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['created_at', 'updated_at'];

    /**
     * Get vehicles with pagination.
     *
     * @param int $perPage
     *
     * @return array
     */
    public static function withPagination($perPage)
    {
        $results = Item::join('vehicles', 'vehicles.code', '=', 'items.code')
        ->select('items.price', 'items.images')
        ->paginate($perPage);

        $data = [];
        if (!$results->isEmpty()) {
            $data['from'] = $results->firstItem();
            $data['to'] = $results->lastItem();
            $data['total'] = $results->total();
            $data['limit'] = $results->perPage();

            foreach ($results as $result) {
                $item = new self();
                $item->price = $result->price;
                $item->image = json_decode($result->images)[0];

                $data['items'][] = $item;
            }
        }

        return $data;
    }
}

Define the attributes that aren't mass assignable


<?php

namespace Frisbee\Controller;

use Frisbee\Bootstrap\BootstrapInterface;
use Frisbee\Exception\Flingable;

abstract class AbstractController extends Flingable implements ControllerInterface
{
    /**
     * @var BootstrapInterface
     */
    private $bootstrap;

    /**
     * @var string
     */
    protected $method;

    public function __construct(BootstrapInterface $bootstrap, $defaultMethod = 'index')
    {
        $this->bootstrap = $bootstrap;
        $this->method = $defaultMethod;
    }

    public function run()
    {
        // You could implement "middleware" here or load dependencies in your controller by using boomerang
    }

    public function next()
    {
        $dispatchMethod = $this->method.'Action';
        if (!method_exists($this, $dispatchMethod)) {
            throw new \Exception(
                sprintf('requested method: %s does not exist in controller %s', $dispatchMethod, get_class($this))
            );
        }

        return $this->$dispatchMethod();
    }
}

<?php

namespace Frisbee\Controller;

use Frisbee\Bootstrap\BootstrapInterface;
use Frisbee\Exception\Flingable;

abstract class AbstractController extends Flingable implements ControllerInterface
{
    /**
     * @var BootstrapInterface
     */
    private $bootstrap;

    /**
     * @var string
     */
    protected $method;

    public function __construct(BootstrapInterface $bootstrap, $defaultMethod = 'index')
    {
        $this->bootstrap = $bootstrap;
        $this->method = $defaultMethod;
    }

    public function run()
    {
        // You could implement "middleware" here or load dependencies in your controller by using boomerang
    }

    public function next()
    {
        $dispatchMethod = $this->method . 'Action';
        if (!method_exists($this, $dispatchMethod)) {
            throw new \Exception(
                sprintf('requested method: %s does not exist in controller %s', $dispatchMethod, get_class($this))
            );
        }

        return $this->$dispatchMethod();
    }
}

Fix codestyle by adding a space between string concatenation


<?php

use WikiLingo\Plugin\Base;
use WikiLingo\Expression\Plugin;

class WikiPluginStub extends Base
{
	public function __construct()
	{
		$this->allowLines = true;
	}

	public function render(WikiLingo\Expression\Plugin &$plugin, &$body, &$parser)
	{
		$element = $parser->element('WikiLingo\\Expression\\Plugin', 'span');
		$element->detailedAttributes['data-plugin-type'] = $plugin->type;
		$element->detailedAttributes['data-plugin-parameters'] = urlencode(json_encode($plugin->parametersRaw));
		$element->useDetailedAttributes = true;
		$element->staticChildren[] = $renderedChildren;
		$output = $element->render();
		return $output;
	}
}

<?php

use WikiLingo\Plugin\Base;
use WikiLingo\Expression\Plugin;

class WikiPluginStub extends Base
{
	public function __construct()
	{
		$this->allowLines = true;
	}

	public function render(WikiLingo\Expression\Plugin &$plugin, &$body = '', &$renderer, &$parser)
	{
		$element = $parser->element('WikiLingo\\Expression\\Plugin', 'span');
		$element->detailedAttributes['data-plugin-type'] = $plugin->type;
		$element->detailedAttributes['data-plugin-parameters'] = urlencode(json_encode($plugin->parametersRaw));
		$element->useDetailedAttributes = true;
		$element->staticChildren[] = $plugin->renderedChildren;
		$output = $element->render();
		return $output;
	}
}

Make stub match extended parent

[FIX] Make stub match extended parent

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@51055 b456876b-0849-0410-b77d-98878d47e9d5


<?php

namespace Soil\QueueHttpEndpointBundle\Controller;

use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Created by PhpStorm.
 * User: fliak
 * Date: 5.2.15
 * Time: 15.14
 */

class EndpointController {

    /**
     * @var GearmanClient
     */
    protected $gearmanClient;

    protected $queueStream;

    public function __construct($gearmanClient, $queueStream) {
        $this->gearmanClient = $gearmanClient;
        $this->queueStream = $queueStream;
    }

    public function putJobAction(Request $request) {
        try {
            $data = $request->getContent();

            $this->gearmanClient->send($this->queueStream, $data);

            $response = new JsonResponse([
                'success' => true
            ]);
        }
        catch(\Exception $e)    {
            $response = new JsonResponse([
                'success' => false,
                'error' => $e->getMessage(),
                'workload' => $data
            ], 500);
        }

        return $response;
    }
}

<?php

namespace Soil\QueueHttpEndpointBundle\Controller;

use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Created by PhpStorm.
 * User: fliak
 * Date: 5.2.15
 * Time: 15.14
 */

class EndpointController {

    /**
     * @var GearmanClient
     */
    protected $gearmanClient;

    protected $queueStream;

    public function __construct($gearmanClient, $queueStream) {
        $this->gearmanClient = $gearmanClient;
        $this->queueStream = $queueStream;
    }

    public function putJobAction(Request $request) {
        $data = null;

        try {
            $data = $request->getContent();

            $job = $this->gearmanClient->send($this->queueStream, $data);

            $response = new JsonResponse([
                'success' => true,
                'stream' => $this->queueStream,
                'job' => $job
            ]);
        }
        catch(\Exception $e)    {
            $response = new JsonResponse([
                'success' => false,
                'error' => $e->getMessage(),
                'workload' => $data
            ], 500);
        }

        return $response;
    }
}

Return job id in response

Return job id in response


<?php

namespace Framework\Components\Model\Interfaces;

defined('CORE_EXEC') or die('Restricted Access');

/**
 *
 * Core Framework
 * Model Interface
 *
 * @author Alexandre Pagé
 *
 */
interface IModel {

	public function __construct ($id_or_array);

	public function save ();

	public function remove ();

	public static function all ();

	public static function find ($id_or_array);

	protected static function create ($inputs);

	protected static function delete ($id);

	protected static function update ($id, $inputs);

}

<?php

namespace Framework\Components\Model\Interfaces;

defined('CORE_EXEC') or die('Restricted Access');

/**
 *
 * Core Framework
 * Model Interface
 *
 * @author Alexandre Pagé
 *
 */
interface IModel {

	public function __construct ($id_or_array);

	public function save ();

	public function remove ();

	public static function all ();

	public static function find ($id_or_array);

}

Fix Model remove protected because interfaces cannot implement protected methods


@extends('layout.master')

@section('main_content')

    @include('layout.header', ['header' => 'API Keys', 'subtitle' => 'Northstar application access & permissions'])

{{ $key->app_id }}

Credentials:

  X-DS-Application-Id: {{ $key->app_id }}
  X-DS-REST-API-Key: {{ $key->api_key }}

Scopes

                    @foreach($key->scope as $scope)

{{ $scope }}

                    @endforeach

api_key]) }}">Edit Key

                        <form action="{{ route('keys.destroy', $key->api_key) }}" method="POST">
                            <input type="hidden" name="_method" value="DELETE">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">
                            <button class="button -secondary -danger">Delete Key</button>
                        </form>

@stop

@extends('layout.master')

@section('main_content')

    @include('layout.header', ['header' => 'API Keys', 'subtitle' => 'Northstar application access & permissions'])

{{ $key->app_id }}

Credentials:

X-DS-REST-API-Key: {{ $key->api_key }}

Send this header with any requests to use this API key.

Scopes

                    @foreach($key->scope as $scope)

{{ $scope }}

                    @endforeach

api_key]) }}">Edit Key

                        <form action="{{ route('keys.destroy', $key->api_key) }}" method="POST">
                            <input type="hidden" name="_method" value="DELETE">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">
                            <button class="button -secondary -danger">Delete Key</button>
                        </form>

@stop

Remove application ID header from example.

This is no longer required, so no need to present it in the admin panel.


<?php
    namespace Page;

    class SignUp
    {
        public function index()
        {
            if ($this->input->hasPost('username'))
            {
                $this->addUser();
            }

            $this->load->storeView('SignUp');

            $this->load->layout('Fresh');
        }

        public function addUser()
        {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $rpassword = $this->input->post('rpassword');

            $msg = $this->load->library('Message');
            $valid = $this->load->library('Validation');

            if ($password !== $rpassword)
            {
                $msg->error('Your retype password is not match with the password you entered.');
            }

            if (!$valid->username($username))
            {
                $msg->error('Your username is not valid, only use alphabet (a-z), number (0-9),'.
                    ' and symbol (_.-). The character length must between 5-16 characters');
            }

            if (!$valid->password($password))
            {
                $msg->error('Your password is not valid, only use alphabet (a-z), number (0-9),'.
                    ' and symbol (@#!$*&~;:,?_.-). The character length must between 5-16 characters');
            }

            if ($msg->count('error') > 0)
            {
                return;
            }

            $msg->success('Your account has been created successfully.'.
                ' Enter with your username and password', true);
            $this->router->redirect('user/signin');
        }
    }

?>

<?php
    namespace Page;

    class SignUp
    {
        public function index()
        {
            if ($this->input->hasPost('username'))
            {
                $this->addUser();
            }

            $this->load->storeView('SignUp');

            $this->load->layout('Fresh');
        }

        public function addUser()
        {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $rpassword = $this->input->post('rpassword');

            $this->load->library('Validation');

            if ($password !== $rpassword)
            {
                $this->message->error('Your retype password is not match with the password you entered.');
            }

            if (!$this->validation->username($username))
            {
                $this->message->error('Your username is not valid, only use alphabet (a-z), number (0-9),'.
                    ' and symbol (_.-). The character length must between 5-16 characters');
            }

            if (!$this->validation->password($password))
            {
                $this->message->error('Your password is not valid, only use alphabet (a-z), number (0-9),'.
                    ' and symbol (@#!$*&~;:,?_.-). The character length must between 5-16 characters');
            }

            if ($this->message->count('error') > 0)
            {
                return;
            }

            $this->message->success('Your account has been created successfully.'.
                ' Enter with your username and password', true);
            $this->router->redirect('user/signin');
        }
    }

?>

Fix sign up to use new load system

Fix sign up to use new load system


<?php

use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;

require dirname(__DIR__).'/config/bootstrap.php';

if ($_SERVER['APP_DEBUG']) {
    umask(0000);

    Debug::enable();
}

if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}

if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
    Request::setTrustedHosts([$trustedHosts]);
}

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use App\Kernel;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;

require dirname(__DIR__).'/config/bootstrap.php';

if ($_SERVER['APP_DEBUG']) {
    umask(0000);

    Debug::enable();
}

if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}

if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
    Request::setTrustedHosts([$trustedHosts]);
}

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Replace Debug class to make Sylius work again :dancer:


<?php

namespace Auth0\SDK\API\Management;

use Auth0\SDK\API\Helpers\ApiClient;
use Auth0\SDK\API\Header\ContentType;

class Jobs extends GenericResource
{
  public function get($id)
  {
    return $this->apiClient->get()
      ->jobs($id)
      ->call();
  }

  public function getErrors($id)
  {
    return $this->apiClient->get()
      ->jobs($id)
      ->errors()
      ->call();
  }

  public function importUsers($file_path, $connection_id)
  {
    return $this->apiClient->post()
      ->jobs()
      ->addPath('users-imports')
      ->addFile('users', $file_path)
      ->addFormParam('connection_id', $connection_id)
      ->call();
  }

  public function sendVerificationEmail($user_id, $result_url = null)
  {
      $body = [
        'user_id' => $user_id
      ];

      if(!is_null($result_url)){
          $body['result_url'] = $result_url;
      }

    return $this->apiClient->post()
      ->jobs()
      ->addPath('verification-email')
      ->withHeader(new ContentType('application/json'))
      ->withBody(json_encode($body))
      ->call();
  }
}

<?php

namespace Auth0\SDK\API\Management;

use Auth0\SDK\API\Helpers\ApiClient;
use Auth0\SDK\API\Header\ContentType;

class Jobs extends GenericResource
{
  public function get($id)
  {
    return $this->apiClient->get()
      ->jobs($id)
      ->call();
  }

  public function getErrors($id)
  {
    return $this->apiClient->get()
      ->jobs($id)
      ->errors()
      ->call();
  }

  public function importUsers($file_path, $connection_id)
  {
    return $this->apiClient->post()
      ->jobs()
      ->addPath('users-imports')
      ->addFile('users', $file_path)
      ->addFormParam('connection_id', $connection_id)
      ->call();
  }

  public function sendVerificationEmail($user_id)
  {
    return $this->apiClient->post()
      ->jobs()
      ->addPath('verification-email')
      ->withHeader(new ContentType('application/json'))
      ->withBody(json_encode([
        'user_id' => $user_id
      ]))
      ->call();
  }
}

Revert "Added support for custom redirect URL when sending verification email…"


<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;

trait HasTimezones
{
    /**
     * Return a timestamp as DateTime object.
     *
     * @param mixed $value
     *
     * @return \Illuminate\Support\Carbon
     */
    protected function asDateTime($value)
    {
        $datetime = parent::asDateTime($value);
        $timezone = app()->bound('request.user') ? optional(app('request.user'))->timezone : null;

        if (! $timezone || $timezone === config('app.timezone')) {
            return $datetime;
        }

        $thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
            return $trace['function'] === 'setAttribute';
        });

        if ($thisIsUpdateRequest) {
            // When updating attributes, we need to reset user timezone to system timezone before saving!
            return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
        }

        return $datetime->setTimezone(new DateTimeZone($timezone));
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;

trait HasTimezones
{
    /**
     * Return a timestamp as DateTime object.
     *
     * @param mixed $value
     *
     * @return \Illuminate\Support\Carbon
     */
    protected function asDateTime($value)
    {
        $datetime = parent::asDateTime($value);
        $timezone = optional(request()->user())->timezone;

        if (! $timezone || $timezone === config('app.timezone')) {
            return $datetime;
        }

        $thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
            return $trace['function'] === 'setAttribute';
        });

        if ($thisIsUpdateRequest) {
            // When updating attributes, we need to reset user timezone to system timezone before saving!
            return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
        }

        return $datetime->setTimezone(new DateTimeZone($timezone));
    }
}

Simplify and utilize request()->user() and request()->guard()


<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use Vinkla\Hashids\Facades\Hashids;

trait HashidsTrait
{
    /**
     * Get the value of the model's route key.
     *
     * @return mixed
     */
    public function getRouteKey()
    {
        $obscure = property_exists($this, 'obscure') && is_array($this->obscure) ? $this->obscure : config('cortex.foundation.obscure');

        return in_array(request()->route('accessarea'), $obscure['areas'])
            ? Hashids::encode($this->getAttribute($this->getKeyName()), $obscure['rotate'] ? random_int(1, 999) : 1)
            : $this->getAttribute($this->getRouteKeyName());
    }

    /**
     * Retrieve the model for a bound value.
     *
     * @param mixed $value
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function resolveRouteBinding($value)
    {
        $obscure = property_exists($this, 'obscure') && is_array($this->obscure) ? $this->obscure : config('cortex.foundation.obscure');

        return in_array(request()->route('accessarea'), $obscure['areas'])
            ? $this->where($this->getKeyName(), optional(Hashids::decode($value))[0])->first()
            : $this->where($this->getRouteKeyName(), $value)->first();
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use Vinkla\Hashids\Facades\Hashids;

trait HashidsTrait
{
    /**
     * Get the value of the model's route key.
     *
     * @throws \Exception
     *
     * @return mixed
     */
    public function getRouteKey()
    {
        $obscure = property_exists($this, 'obscure') && is_array($this->obscure) ? $this->obscure : config('cortex.foundation.obscure');

        return in_array(request()->route('accessarea'), $obscure['areas'])
            ? Hashids::encode($this->getAttribute($this->getKeyName()), $obscure['rotate'] ? random_int(1, 999) : 1)
            : $this->getAttribute($this->getRouteKeyName());
    }

    /**
     * Retrieve the model for a bound value.
     *
     * @param  mixed  $value
     * @param  string|null  $field
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function resolveRouteBinding($value, $field = null)
    {
        $obscure = property_exists($this, 'obscure') && is_array($this->obscure) ? $this->obscure : config('cortex.foundation.obscure');

        return in_array(request()->route('accessarea'), $obscure['areas'])
            ? $this->where($field ?? $this->getKeyName(), optional(Hashids::decode($value))[0])->first()
            : $this->where($field ?? $this->getRouteKeyName(), $value)->first();
    }
}

Update compatibility with Laravel v7.x

Update compatibility with Laravel v7.x


<?php

namespace App\Providers;

use App\Services\CsvGenerator;
use App\Services\Response;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            \App\Solvers\SolverInterface::class,
            \App\Solvers\HatSolver::class
        );
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

<?php

namespace App\Providers;

use App\Services\CsvGenerator;
use App\Services\Response;
use DrawCrypt;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\ServiceProvider;
use Queue;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            \App\Solvers\SolverInterface::class,
            \App\Solvers\HatSolver::class
        );
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Queue::createPayloadUsing(function ($connection, $queue, $payload) {
            return [
                'data' => array_merge($payload['data'], [
                    'iv' => base64_encode(DrawCrypt::getIV())
                ])
            ];
        });

        $this->app['events']->listen(\Illuminate\Queue\Events\JobProcessing::class, function ($event) {
            if (isset($event->job->payload()['data']['iv'])) {
                DrawCrypt::setIV(base64_decode($event->job->payload()['data']['iv']));
            }
        });
    }
}

Add iv in job data when queueing

Add iv in job data when queueing


<?php

/*
Plugin Name: tonik/gin
Plugin URI: http://tonik.pl
Description: Foundation of the Tonik WordPress Starter Theme. Provides all custom functionalities which it offers.
<<<<<<< HEAD
Version: 3.0.0
=======
Version: 3.1.0
>>>>>>> release-3.1.0
Author: Tonik
Author URI: http://tonik.pl
License: GPL-2.0+
License URI: http://www.gnu.org/licenses/gpl-2.0.txt
Domain Path: /resources/lang
Text Domain: tonik.gin
 */

spl_autoload_register(function ($class) {
    // Namespace prefix
    $prefix = 'Tonik\\';

    // Base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // Does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // No, move to the next registered autoloader
        return;
    }

    // Get the relative class name
    $relative_class = substr($class, $len);

    // Replace the namespace prefix with the base
    // directory, replace namespace separators with directory
    // separators in the relative class name, append with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // If the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

<?php

/*
Plugin Name: tonik/gin
Plugin URI: http://tonik.pl
Description: Foundation of the Tonik WordPress Starter Theme. Provides all custom functionalities which it offers.
Version: 3.1.0
Author: Tonik
Author URI: http://tonik.pl
License: GPL-2.0+
License URI: http://www.gnu.org/licenses/gpl-2.0.txt
Domain Path: /resources/lang
Text Domain: tonik.gin
 */

spl_autoload_register(function ($class) {
    // Namespace prefix
    $prefix = 'Tonik\\';

    // Base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // Does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // No, move to the next registered autoloader
        return;
    }

    // Get the relative class name
    $relative_class = substr($class, $len);

    // Replace the namespace prefix with the base
    // directory, replace namespace separators with directory
    // separators in the relative class name, append with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // If the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

fix(): Remove conflict from plugin header comment


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = ['name', 'description'];
    public function assignments()
    {
    	return $this->hasMany('app\Assignment');
    }
}

Create relationship for roles table

refactor(roles): Create relationship for roles table

modified:   app/Role.php

see #97


<?php
/**
 * First stage loader
 *
 * Here we get things started by ensuring the PHP version we're running on
 * is supported by the app.  We'll display a friendly error page if not.
 *
 * Next, we'll check if the script is being run with PHP's built in web
 * server, and make sure static assets are handled gracefully.
 *
 * Last but not least, we pass things off to the second stage loader
 */

/**
 * Version must be greater than 5.3.3.
 * See: https://github.com/bolt/bolt/issues/1531
 */
if (version_compare(PHP_VERSION, '5.3.3', '<')) {
    require __DIR__ . '/legacy.php';

    return false;
}

/**
 * Return false if the requested file is available on the filesystem.
 * See: http://silex.sensiolabs.org/doc/web_servers.html#php-5-4
 */
if (php_sapi_name() == 'cli-server') {
    $filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);

    if (is_file($filename)) {
        return false;
    }
}

/**
 * Bring in the second stage loader.
 */

return require_once __DIR__ . '/bootstrap.php';

<?php
/**
 * First stage loader
 *
 * Here we get things started by ensuring the PHP version we're running on
 * is supported by the app.  We'll display a friendly error page if not.
 *
 * Next, we'll check if the script is being run with PHP's built in web
 * server, and make sure static assets are handled gracefully.
 *
 * Last but not least, we pass things off to the second stage loader
 */

/**
 * Version must be greater than 5.3.3.
 * See: https://github.com/bolt/bolt/issues/1531
 */
if (version_compare(PHP_VERSION, '5.3.3', '<')) {
    require __DIR__ . '/legacy.php';

    return false;
}

/**
 * Return false if the requested file is available on the filesystem.
 * See: http://silex.sensiolabs.org/doc/web_servers.html#php-5-4
 */
if (php_sapi_name() == 'cli-server') {
    $filename = dirname(__DIR__) . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);

    if (is_file($filename)) {
        return false;
    }
}

/**
 * Bring in the second stage loader.
 */

return require_once __DIR__ . '/bootstrap.php';

Fix file path to check

Fix file path to check


<?php

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

use Silex\Application;
use Eyewitness\Router;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;

include __DIR__.'/config.php';

// Basic App Setup Stuff
$app = new Application();
$app['debug'] = $debug;
$router = new Router($app);

// Register service providers
include __DIR__.'/../src/EyeWitness/registerProviders.php';

$app->before(function (Request $request) {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : array());
    }
});

$app->mount('/', $router->setBasicRoutes());

$app->run();

<?php

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

use Silex\Application;
use Eyewitness\Router;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;

include __DIR__.'/config.php';

// Basic App Setup Stuff
$app = new Application();
$app['debug'] = $debug;
$router = new Router($app);

// Register service providers
include __DIR__.'/../src/EyeWitness/registerProviders.php';

$app->before(function (Request $request) {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json'))
    {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : array());
    }
});

$app->mount('/api/', $router->setApiRoutes());

$app->run();

Add support for json decoding

Add support for json decoding


<?php

namespace FluxBB\Actions;

use FluxBB\Core\Action;
use FluxBB\Models\CategoryRepository;
use Illuminate\Support\Str;

class ViewCategory extends Action
{
    protected $categories;

    public function __construct(CategoryRepository $repository)
    {
        $this->categories = $repository;
    }

    protected function run()
    {
        $slug = $this->request->get('slug');
        $slug = '/'.Str::finish(trim($slug, '/'), '/');

        $category = $this->categories->findBySlug($slug);

        $this->data['category'] = $category;
        $this->data['categories'] = $this->categories->getByParent($slug);
        $this->data['conversations'] = $this->categories->getConversationsIn($category);
    }
}

<?php

namespace FluxBB\Actions;

use FluxBB\Core\Action;
use FluxBB\Models\CategoryRepository;

class ViewCategory extends Action
{
    protected $categories;

    public function __construct(CategoryRepository $repository)
    {
        $this->categories = $repository;
    }

    protected function run()
    {
        $slug = $this->request->get('slug');
        $slug = preg_replace('/\/+/', '/', '/'.$slug.'/');

        $category = $this->categories->findBySlug($slug);

        $this->data['category'] = $category;
        $this->data['categories'] = $this->categories->getByParent($slug);
        $this->data['conversations'] = $this->categories->getConversationsIn($category);
    }
}

Remove duplicate slashes from category name.