<?php

namespace Drupal\wmcontroller;

use Drupal\Component\Plugin\Factory\FactoryInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\wmcontroller\Annotation\Controller;

class ControllerPluginManager extends DefaultPluginManager
{
    public function __construct(
        \Traversable $namespaces,
        CacheBackendInterface $cacheBackend,
        ModuleHandlerInterface $moduleHandler
    ) {
        parent::__construct(
            'Controller',
            $namespaces,
            $moduleHandler,
            null,
            Controller::class
        );
        $this->alterInfo('wmcontroller_controller_info');
        $this->setCacheBackend($cacheBackend, 'wmcontroller_controller_info');
    }

    protected function getFactory(): FactoryInterface
    {
        if (!$this->factory) {
            $this->factory = new ControllerPluginFactory($this, $this->pluginInterface);
        }

        return $this->factory;
    }
}

<?php

namespace Drupal\wmcontroller;

use Drupal\Component\Plugin\Factory\FactoryInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\wmcontroller\Annotation\Controller;

class ControllerPluginManager extends DefaultPluginManager
{
    public function __construct(
        \Traversable $namespaces,
        CacheBackendInterface $cacheBackend,
        ModuleHandlerInterface $moduleHandler
    ) {
        parent::__construct(
            'Controller',
            $namespaces,
            $moduleHandler,
            null,
            Controller::class
        );
        $this->alterInfo('wmcontroller_controller_info');
        $this->setCacheBackend($cacheBackend, 'wmcontroller_controller_info');
    }

    protected function getFactory()
    {
        if (!$this->factory) {
            $this->factory = new ControllerPluginFactory($this, $this->pluginInterface);
        }

        return $this->factory;
    }
}

Remove return type since it's missing from the parent


<?php

namespace Michaeljennings\Carpenter;

class Laravel4ServiceProvider extends CarpenterServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     * @codeCoverageIgnore
     */
    public function boot()
    {
        $this->package('michaeljennings/carpenter', 'carpenter', realpath(__DIR__ . '/../'));
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('michaeljennings.carpenter', function ($app) {
            return new Carpenter([
                'store' => $app['config']['carpenter::store'],
                'paginator' => $app['config']['carpenter::paginator'],
                'session' => $app['config']['carpenter::session'],
                'view' => $app['config']['carpenter::view'],
            ]);
        });

        $this->app->alias('michaeljennings.carpenter', 'Michaeljennings\Carpenter\Contracts\Carpenter');
    }
}

<?php

namespace Michaeljennings\Carpenter;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     * @codeCoverageIgnore
     */
    public function boot()
    {
        $this->package('michaeljennings/carpenter', 'carpenter', realpath(__DIR__ . '/../'));
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('michaeljennings.carpenter', function ($app) {
            return new Carpenter([
                'store' => $app['config']['carpenter::store'],
                'paginator' => $app['config']['carpenter::paginator'],
                'session' => $app['config']['carpenter::session'],
                'view' => $app['config']['carpenter::view'],
            ]);
        });

        $this->app->alias('michaeljennings.carpenter', 'Michaeljennings\Carpenter\Contracts\Carpenter');
    }
}

Update the laravel 4 service provider so it is not deferred

This fixes issues with the config not loading correctly for laravel 4.


<?php

namespace OpenDominion\Http\Middleware;

use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies;

    /**
     * The headers that should be used to detect proxies.
     *
     * @var string
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

Add Cloudflare IPs to trusted proxies

Add Cloudflare IPs to trusted proxies


<?php

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

class CreateNewEventsTableSchema extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('eventable_id');
            $table->string('eventable_type');
            $table->string('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('events');
    }
}

<?php

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

class CreateNewEventsTableSchema extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('eventable');
            $table->string('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('events');
    }
}

Use morphable command to create polymorphic columns on events table


<?php

namespace Slate\UI;

use Slate;

class Tools implements ILinksSource
{
    public static $weight = -500;
    public static $tools = [];

    public static function __classLoaded()
    {
        // append legacy manage/web tools
        if (!empty(Slate::$manageTools)) {
            static::appendtools(Slate::$manageTools);
        }

        if (!empty(Slate::$webTools)) {
            static::appendtools(Slate::$webTools);
        }
    }

    public static function appendTools(array $tools)
    {
        foreach ($tools AS $key => $value) {
            if (
                is_array($value) &&
                !empty(static::$tools[$key]) &&
                is_array(static::$tools[$key])
            ) {
                static::$tools[$key] = array_merge(static::$tools[$key], $value);
            } else {
                static::$tools[$key] = $value;
            }
        }
    }

    public static function getLinks($context = null)
    {
        return [
            'Tools' => empty($_SESSION['User']) ? null : [
                '_icon' => 'tools',
                '_weight' => -500,
                '_children' => static::$tools
            ]
        ];
    }
}

<?php

namespace Slate\UI;

use Slate;

class Tools implements ILinksSource
{
    public static $enabled = true;
    public static $weight = -500;
    public static $tools = [];

    public static function __classLoaded()
    {
        // append legacy manage/web tools
        if (!empty(Slate::$manageTools)) {
            static::appendtools(Slate::$manageTools);
        }

        if (!empty(Slate::$webTools)) {
            static::appendtools(Slate::$webTools);
        }
    }

    public static function appendTools(array $tools)
    {
        foreach ($tools AS $key => $value) {
            if (
                is_array($value) &&
                !empty(static::$tools[$key]) &&
                is_array(static::$tools[$key])
            ) {
                static::$tools[$key] = array_merge(static::$tools[$key], $value);
            } else {
                static::$tools[$key] = $value;
            }
        }
    }

    public static function getLinks($context = null)
    {
        if (!static::$enabled || empty($_SESSION['User'])) {
            return [];
        }

        return [
            'Tools' => [
                '_icon' => 'tools',
                '_weight' => -500,
                '_children' => static::$tools
            ]
        ];
    }
}

Add config for disabling tools links

Add config for disabling tools links


<?php

namespace iFixit\Matryoshka;

use iFixit\Matryoshka;

/**
 * Ensures that a delete is issued before trying to update an existing key.
 *
 * This layer is useful for working with mcrouter. mcrouter provides a reliable
 * delete stream, but can't guarantee updates are recorded.
 */
class DeleteBeforeUpdate extends BackendWrap {
   public function set($key, $value, $expiration = 0) {
      if ($this->backend->add($key, $value, $expiration) === false) {
         $this->backend->delete($key);
         $this->backend->set($key, $value, $expiration);
      }
   }

   public function setMultiple(array $values, $expiration = 0) {
      foreach ($values as $key => $value) {
         $this->set($key, $value, $expiration);
      }
   }
}

<?php

namespace iFixit\Matryoshka;

use iFixit\Matryoshka;

/**
 * Ensures that a delete is issued before trying to update an existing key.
 *
 * This layer is useful for working with mcrouter. mcrouter provides a reliable
 * delete stream, but can't guarantee updates are recorded.
 */
class DeleteBeforeUpdate extends BackendWrap {
   public function set($key, $value, $expiration = 0) {
      $addResponse = $this->backend->add($key, $value, $expiration);
      if ($addResponse === false) {
         $this->backend->delete($key);
         return $this->backend->set($key, $value, $expiration);
      }
      return $addResponse;
   }

   public function setMultiple(array $values, $expiration = 0) {
      foreach ($values as $key => $value) {
         $this->set($key, $value, $expiration);
      }
      return true;
   }
}

Add return values for BackendWrap

Add return values for BackendWrap

We need to return some values from the BackendWrap. It is not trivial
what we are expecting here, especially from `setMultiple`. Always
returning `true` should be satisfactory for now.


<?php
    namespace Page;

    class User
    {
        public function index()
        {
            $this->router->redirect('user/profile');
        }

        public function profile()
        {
            $this->load->model('Manga');
            $this->load->library('Manga', 'MangaLib');
            $this->load->library('Image');
            $this->load->library('Date');

            $cfg = $this->config->loadInfo('Manga');

            $mangas = $this->manga->getUserManga(
                $this->auth->getUserId(), 0, 36);
            $history = $this->manga->getUserHistory(
                $this->auth->getUserId(), 0, 31);

            $this->load->storeView('User', [
                'mangas'=>$mangas,
                'history'=>$history,
                'mangapath'=>$cfg['path']
            ]);

            $this->load->layout('Fresh', [
                'title'=>'My Reading History'
            ]);
        }

        public function history()
        {
            $this->load->model('Manga');
            $this->load->library('Manga', 'MangaLib');
            $this->load->library('Date');

            $history = $this->manga->getUserHistory(
                $this->auth->getUserId(), 0, 31);

            $this->load->storeView('History', [
                'history'=>$history,
                'single'=>true
            ]);

            $this->load->layout('Fresh', [
                'title'=>'My Reading History'
            ]);
        }
    }

?>

<?php
    namespace Page;

    class User
    {
        public function index()
        {
            $this->router->redirect('user/profile');
        }

        public function profile()
        {
            $this->load->model('Manga');
            $this->load->library('Manga', 'MangaLib');
            $this->load->library('Image');
            $this->load->library('Date');

            $cfg = $this->config->loadInfo('Manga');

            $mangas = $this->manga->getUserManga(
                $this->auth->getUserId(), 0, 36);
            $history = $this->manga->getUserHistory(
                $this->auth->getUserId(), 0, 31);

            $this->load->storeView('User', [
                'mangas'=>$mangas,
                'history'=>$history,
                'mangapath'=>$cfg['path']
            ]);

            $this->load->layout('Fresh', [
                'title'=>'My Reading History'
            ]);
        }

        public function history()
        {
            $this->load->model('Manga');
            $this->load->library('Manga', 'MangaLib');
            $this->load->library('Date');

            $history = $this->manga->getUserHistory(
                $this->auth->getUserId(), 0, 100);

            $this->load->storeView('History', [
                'history'=>$history,
                'single'=>true
            ]);

            $this->load->layout('Fresh', [
                'title'=>'My Reading History'
            ]);
        }
    }

?>

Change history limit to 100 when viewing on single page


    <?php foreach($pager->getResults() as $flight): ?>

            <?php if($flight->getDrafted() && $flight->getStatus() == "new"): ?>
                Drafted
                <?php echo $flight->getId() ?>
                <a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit
            <?php elseif($flight->getDrafted() && $flight->getStatus() == "assess"): ?>
                <?php echo $flight->getTripNumber() ?>(Drafted)
                <a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit
            <?php else: ?>
                <?php echo $flight->getTripNumber() ?>
                <?php echo $flight->getRiskFactorSum() ?>
                <?php echo date('Y-m-d', strtotime($flight->getCreatedAt())) ?>
            <?php endif ?>

    <?php endforeach ?>

    <?php include_partial('dashboard/pager', array('pager' => $pager, 'account' => $account)); ?>

    <?php foreach($pager->getResults() as $flight): ?>

            <?php if($flight->getDrafted() && $flight->getStatus() == "new"): ?>
                <?php if($flight->getTripNumber()): ?>
                    <?php echo $flight->getTripNumber() ?>(Drafted)
                <?php else: ?>
                    Drafted
                    <?php echo $flight->getId() ?>
                <?php endif ?>
                <a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit
            <?php elseif($flight->getDrafted() && $flight->getStatus() == "assess"): ?>
                <?php echo $flight->getTripNumber() ?>(Drafted)
                <a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit
            <?php else: ?>
                <?php echo $flight->getTripNumber() ?>
                <?php echo $flight->getRiskFactorSum() ?>
                <?php echo date('Y-m-d', strtotime($flight->getCreatedAt())) ?>
            <?php endif ?>

    <?php endforeach ?>

    <?php include_partial('dashboard/pager', array('pager' => $pager, 'account' => $account)); ?>

Fix create account validation, Dashboard filters


<?php
$class = $argv[1];
$file = $argv[2];
$rootpath = $argv[3];
$autoloader = $rootpath . '/vendor/autoload.php';
if (file_exists($autoloader)) {
    $loader = require $autoloader;

    require __DIR__ . '/FQCN.php';

    $contents = file_get_contents($file);
    $fqns = new Hkt\FQCN();
    $useClasses = $fqns->getAllUseStatements($contents);
    if (array_key_exists($class, $useClasses)) {
        echo $loader->findFile($useClasses[$class]);
    } else {
        // Get current namespace
        $namespace = $fqns->getNamespace();
        echo $loader->findFile($namespace . '\\' . $class);
    }

}

<?php
$class = $argv[1];
$file = $argv[2];
$rootpath = $argv[3];
$autoloader = $rootpath . '/vendor/autoload.php';
if (file_exists($autoloader)) {
    $loader = require $autoloader;

    require __DIR__ . '/FQCN.php';

    $contents = file_get_contents($file);
    $fqns = new Hkt\FQCN();
    $useClasses = $fqns->getAllUseStatements($contents);
    if (array_key_exists($class, $useClasses)) {
        echo $loader->findFile($useClasses[$class]);
    } else {
        // Get current namespace
        $namespace = $fqns->getNamespace();
        if ($namespace) {
            $class = $namespace . '\\' . $class;
        }
        echo $loader->findFile($class);
    }

}

Fix files that have no namespace, but with psr-0 . Eg Solar, Kohana, Zend_ etc


<?php defined('SYSPATH') OR die('No direct script access.');

/**
 *
 * @package 	Boom
 * @category 	Controllers
 */
class Boom_Controller_Page_Html extends Controller_Page
{
	/**
	 *
	 * @var View
	 */
	public $template;

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

		$this->_save_last_url();
		$template = $this->page->version()->template;
		$this->template = View::factory($template->filename());

		// Set some variables which need to be used globally in the views.
		View::bind_global('auth', $this->auth);
		View::bind_global('editor', $this->editor);
		View::bind_global('page', $this->page);
	}

	public function action_show() {}

	public function after()
	{
		// If we're in the CMS then add the boom editor the the page.
		if ($this->auth->logged_in())
		{
			$content = $this->editor->insert((string) $this->template, $this->page->id);
		}
		else
		{
			$content = (string) $this->template;
		}

		$this->response->body($content);
	}
}

<?php defined('SYSPATH') OR die('No direct script access.');

/**
 *
 * @package 	Boom
 * @category 	Controllers
 */
class Boom_Controller_Page_Html extends Controller_Page
{
	/**
	 *
	 * @var View
	 */
	public $template;

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

		$this->_save_last_url();
		$template = $this->page->version()->template;
		$this->template = View::factory($template->filename());

		// Set some variables which need to be used globally in the views.
		View::bind_global('auth', $this->auth);
		View::bind_global('editor', $this->editor);
		View::bind_global('page', $this->page);
		View::bind_global('request', $this->request);
	}

	public function action_show() {}

	public function after()
	{
		// If we're in the CMS then add the boom editor the the page.
		if ($this->auth->logged_in())
		{
			$content = $this->editor->insert((string) $this->template, $this->page->id);
		}
		else
		{
			$content = (string) $this->template;
		}

		$this->response->body($content);
	}
}

Make the current request object available in views


<?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\Security\Http\EntryPoint;

use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

/**
 * BasicAuthenticationEntryPoint starts an HTTP Basic authentication.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class BasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
    private $realmName;

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

    public function start(Request $request, AuthenticationException $authException = null)
    {
        $response = new Response();
        $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
        $response->setStatusCode(401, $authException->getMessage());

        return $response;
    }
}

<?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\Security\Http\EntryPoint;

use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

/**
 * BasicAuthenticationEntryPoint starts an HTTP Basic authentication.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class BasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
    private $realmName;

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

    public function start(Request $request, AuthenticationException $authException = null)
    {
        $response = new Response();
        $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
        $response->setStatusCode(401, $authException ? $authException->getMessage() : null);

        return $response;
    }
}

[Security] Fix http basic authentication entry point


<?php
/**
 * ACL Roles model
 *
 * @package Core
 * @author Denysenko Dmytro
 * @copyright (c) 2009 CultSoft
 * @license http://cultsoft.org.ua/platform/license.html
 */
class Site_Model_DbTable_Acl_Roles extends App_DB_Table
{

    public function __construct ()
    {
        parent::__construct();
        // Get resources
        return $this->fetchRow($this->select()->where('id = ?', 1));
    }
}

<?php
/**
 * ACL Roles model
 *
 * @package Core
 * @author Denysenko Dmytro
 * @copyright (c) 2009 CultSoft
 * @license http://cultsoft.org.ua/platform/license.html
 */
class Site_Model_DbTable_Acl_Roles extends App_DB_Table
{

    public function __construct ()
    {
        parent::__construct();
    }
}

Remove debug query from ACL db table class


<?php

namespace Nestor\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Nestor\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Nestor\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Nestor\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \Nestor\Http\Middleware\RedirectIfAuthenticated::class,
    ];
}

<?php

namespace Nestor\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Nestor\Http\Middleware\EncryptCookies::class,
        \Nestor\Http\Middleware\ProjectPosition::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Nestor\Http\Middleware\EncryptCookies::class,
            \Nestor\Http\Middleware\ProjectPosition::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Nestor\Http\Middleware\VerifyCsrfToken::class,
        ],
        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

Add new middleware to add header with project id positioned


<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'safetext' => \App\Http\Middleware\SafeText::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'trim' => \App\Http\Middleware\TrimInput::class,
    ];
}

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\Trim::class,
        \App\Http\Middleware\EmptyToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'safetext' => \App\Http\Middleware\SafeText::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

Add trim and emptytonull middleware to global.


<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
//    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the item's queue entry if it has one.
     */
    public function items()
    {
        return $this->hasMany(Item::class);
    }
}

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the item's queue entry if it has one.
     */
    public function items()
    {
        return $this->hasMany(Item::class);
    }
}

Use Notifiable trait on user model

Use Notifiable trait on user model


<?php

namespace Oro\Bundle\AddressBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use BeSimple\SoapBundle\ServiceDefinition\Annotation as Soap;
use JMS\Serializer\Annotation\Exclude;
use Oro\Bundle\AddressBundle\Entity\AddressType;

/**
 * Address
 *
 * @ORM\Table("oro_address_typed")
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Entity(repositoryClass="Oro\Bundle\AddressBundle\Entity\Repository\AddressRepository")
 */
class TypedAddress extends AddressBase
{
    /**
     * @var integer
     *
     * @ORM\ManyToOne(targetEntity="AddressType")
     * @Soap\ComplexType("string", nillable=true)
     */
    protected $type;

    /**
     * @var \Oro\Bundle\FlexibleEntityBundle\Model\AbstractFlexibleValue[]
     *
     * @ORM\OneToMany(targetEntity="Oro\Bundle\AddressBundle\Entity\Value\AddressValue", mappedBy="entity", cascade={"persist", "remove"}, orphanRemoval=true)
     * @Exclude
     */
    protected $values;

    /**
     * @param AddressType $type
     * @return TypedAddress
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @return AddressType
     */
    public function getType()
    {
        return $this->type;
    }
}

<?php

namespace Oro\Bundle\AddressBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use BeSimple\SoapBundle\ServiceDefinition\Annotation as Soap;
use JMS\Serializer\Annotation\Exclude;
use Oro\Bundle\AddressBundle\Entity\AddressType;

/**
 * Address
 *
 * @ORM\Table("oro_address_typed")
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Entity(repositoryClass="Oro\Bundle\AddressBundle\Entity\Repository\AddressRepository")
 */
class TypedAddress extends AddressBase
{
    /**
     * @var AddressType
     *
     * @ORM\ManyToOne(targetEntity="AddressType")
     * @Soap\ComplexType("string", nillable=true)
     */
    protected $type;

    /**
     * @var \Oro\Bundle\FlexibleEntityBundle\Model\AbstractFlexibleValue[]
     *
     * @ORM\OneToMany(targetEntity="Oro\Bundle\AddressBundle\Entity\Value\AddressValue", mappedBy="entity", cascade={"persist", "remove"}, orphanRemoval=true)
     * @Exclude
     */
    protected $values;

    /**
     * @param AddressType $type
     * @return TypedAddress
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @return AddressType
     */
    public function getType()
    {
        return $this->type;
    }
}

CRM-157: Add support of multiAddress to Contact API
 - added processing of contact addresses
 - added cascade validation to contact API form type
 - small code style fixes


<?php

return [

    /**
     * List of folders to be analyzed.
     */
    'paths' => [
        base_path('app'),
    ],

    /**
     * List of files/folders to be excluded from analysis.
     */
    'exclude' => [
        // base_path('app/helpers.php'),
        // base_path('app/Services'),
    ],

];

<?php

return [

    /**
     * List of folders to be analyzed.
     */
    'paths' => [
        base_path('app'),
        base_path('database'),
    ],

    /**
     * List of files/folders to be excluded from analysis.
     */
    'exclude' => [
        // base_path('app/helpers.php'),
        // base_path('app/Services'),
    ],

];

Add database to the default paths array

Add database to the default paths array

Holds Migrations and Seeders


Remove keys. Keys were deleted, so don't mind trying to use them.


<?php

namespace Acd;

/**
* Request Class
* @author Acidvertigo MIT Licence
*/

class Request
{

    private $headers = [];

    /**
     * Check HTTP request headers
     * @return array list of response headers
     * @throws InvalidArgumentException if header is null
     */
    public function getRequestHeaders()
    {
        if (function_exists('getallheaders()'))
        {
            $this->headers = getallheaders();
        } else
        {
            $this->headers = $this->getServerHeaders();
        }
        if ($this->headers !== null)
        {
            return $this->headers;
        } else
        {
            throw new \InvalidArgumentException('Unable to get Request Headers');
        }
    }

    /**
     * Helper function if getallheaders() not available
     * @return array list of response headers
     */
    private function getServerHeaders()
    {
        foreach (array_keys($_SERVER) as $skey) {
            if (strpos($skey, 'HTTP_') !== FALSE)
            {
                $this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey];
            }
        }

        return $this->headers;
    }
}

<?php

namespace Acd;

/**
* Request Class
* @author Acidvertigo MIT Licence
*/

class Request
{

    private $headers = [];

    /**
     * Check HTTP request headers
     * @return array list of response headers
     * @throws InvalidArgumentException if header is null
     */
    public function getRequestHeaders()
    {
        if (function_exists('getallheaders()'))
        {
            $this->headers = getallheaders();
        } else
        {
            $this->headers = $this->getServerHeaders();
        }
        if ($this->headers !== null)
        {
            return $this->headers;
        } else
        {
            throw new \InvalidArgumentException('Unable to get Request Headers');
        }
    }

    /**
     * @return string the actual request method
     */
    public function getReqestMethod()
    {
        return $_SERVER['REQUEST_METHOD'];
    }

    /**
     * Helper function if getallheaders() not available
     * @return array list of response headers
     */
    private function getServerHeaders()
    {
        foreach (array_keys($_SERVER) as $skey) {
            if (strpos($skey, 'HTTP_') !== FALSE)
            {
                $this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey];
            }
        }

        return $this->headers;
    }
}

Add get request method function

Add get request method function


<?php

namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations;

class AssociationStubMonomorphic extends AssociationStubBase
{
    /**
     * @param \AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubBase $otherStub
     *
     * @return bool
     */
    public function isCompatible(AssociationStubBase $otherStub)
    {
        if (!parent::isCompatible($otherStub)) {
            return false;
        }
        $isNull = null == $this->getThroughField();
        $otherNull = null == $otherStub->getThroughField();

        if ($isNull != $otherNull) {
            return false;
        }

        return ($this->getTargType() === $otherStub->getBaseType())
               && ($this->getBaseType() === $otherStub->getTargType())
               && ($this->getForeignField() === $otherStub->getKeyField())
               && ($this->getKeyField() === $otherStub->getForeignField());
    }

    /**
     * {@inheritdoc}
     */
    public function morphicType()
    {
        return 'monomorphic';
    }
}

<?php

namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations;

class AssociationStubMonomorphic extends AssociationStubBase
{
    /**
     * @param \AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubBase $otherStub
     *
     * @return bool
     */
    public function isCompatible(AssociationStubBase $otherStub)
    {
        if (!parent::isCompatible($otherStub)) {
            return false;
        }
        $isNull = null == $this->getThroughField();
        $otherNull = null == $otherStub->getThroughField();

        if ($isNull != $otherNull) {
            return false;
        }
        $thisChain = $this->getThroughFieldChain();
        $otherChain = $otherStub->getThroughFieldChain();
        $thisThroughCount = count($thisChain) - 1;
        $otherThroughCount = count($otherChain) - 1;
        if ($thisThroughCount !== $otherThroughCount) {
            return false;
        }
        for($i=0; $i <= $thisThroughCount;++$i ){
            if($thisChain[$i] !== $otherChain[$otherThroughCount -$i]){
                return false;
            }
        }

        return ($this->getTargType() === $otherStub->getBaseType())
            && ($this->getBaseType() === $otherStub->getTargType())
            && ($this->getForeignField() === $otherStub->getKeyField())
            && ($this->getKeyField() === $otherStub->getForeignField());
    }

    /**
     * {@inheritdoc}
     */
    public function morphicType()
    {
        return 'monomorphic';
    }
}

Extend isCompatible to check the keyPath


<?php
namespace CodeDay\Clear\ModelContracts;

use \CodeDay\Clear\Models;

class Grant extends ModelContract
{
    public static function getFields()
    {
        return [
            'id' => [
                'name'          => 'ID',
                'description'   => 'The ID of the grant. Numeric.',
                'example'       => '1',
                'value'         => function($model) { return $model->id; }
            ],

            'username' => [
                'name'          => 'Username',
                'description'   => 'Username of the user that this grant belongs to.',
                'example'       => 'tylermenezes',
                'value'         => function($model) { return $model->username; }
            ],

            'event' => [
                'name'          => 'Event',
                'description'   => 'The event that this grant gave the user access to.',
                'type'          => 'Event',
                'rich'          => true,
                'value'         => function($model, $permissions) { return new Event($model->event, $permissions, true); }
            ]
        ];
    }
}

<?php
namespace CodeDay\Clear\ModelContracts;

use \CodeDay\Clear\Models;

class Grant extends ModelContract
{
    public static function getFields()
    {
        return [
            'id' => [
                'name'          => 'ID',
                'description'   => 'The ID of the grant. Numeric.',
                'example'       => '1',
                'value'         => function($model) { return $model->id; }
            ],

            'username' => [
                'name'          => 'Username',
                'description'   => 'Username of the user that this grant belongs to.',
                'example'       => 'tylermenezes',
                'value'         => function($model) { return $model->username; }
            ],

            'event' => [
                'name'          => 'Event',
                'description'   => 'The event that this grant gave the user access to.',
                'type'          => 'Event',
                'rich'          => true,
                'value'         => function($model, $permissions) { return new Event($model->event, $permissions, true); }
            ],

            'region' => [
                'name'          => 'Event',
                'description'   => 'The region of the event that this grant gave the user access to.',
                'type'          => 'Event',
                'rich'          => true,
                'value'         => function($model, $permissions) { return new Region($model->event->region, $permissions, true); }
            ]
        ];
    }
}

Add region in the new API route

Add region in the new API route


<?php

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20220210135918 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add by_guest field to mark orders made by guests';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE sylius_order ADD by_guest TINYINT(1) DEFAULT \'1\' NOT NULL');
        $this->addSql('UPDATE sylius_order o SET o.by_guest = 0 WHERE o.customer_id IN (SELECT customer_id FROM sylius_shop_user)');
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE sylius_order DROP by_guest');
    }
}

<?php

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20220210135918 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add by_guest field to mark orders made by guests';
    }

    public function up(Schema $schema): void
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_order ADD by_guest TINYINT(1) DEFAULT \'1\' NOT NULL');
        $this->addSql('UPDATE sylius_order o SET o.by_guest = 0 WHERE o.customer_id IN (SELECT customer_id FROM sylius_shop_user)');
    }

    public function down(Schema $schema): void
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_order DROP by_guest');
    }
}

Add missing mysql check for migrations

[Migrations] Add missing mysql check for migrations


<?php

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

namespace Nietonfir\RaygunBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('nietonfir_raygun');

        $rootNode
            ->children()
                ->scalarNode('api_key')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end() // api_key
                ->booleanNode('async')
                    ->defaultTrue()
                ->end() // async
                ->booleanNode('debug_mode')
                    ->defaultFalse()
                ->end() // debug_mode
            ->end()
            ->validate()
                ->ifTrue(function($v){return $v['debug_mode'];})
                ->then(function($v){$v['async'] = false;return $v;})
            ->end();

        return $treeBuilder;
    }
}

<?php

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

namespace Nietonfir\RaygunBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('nietonfir_raygun');

        $rootNode
            ->children()
                ->scalarNode('api_key')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end() // api_key
                ->booleanNode('async')
                    ->defaultTrue()
                ->end() // async
                ->booleanNode('debug_mode')
                    ->defaultFalse()
                ->end() // debug_mode
                ->booleanNode('ignore_404')
                    ->defaultFalse()
                ->end() // ignore_404
            ->end()
            ->validate()
                ->ifTrue(function($v){return $v['debug_mode'];})
                ->then(function($v){$v['async'] = false;return $v;})
            ->end();

        return $treeBuilder;
    }
}

Add ignore_404 setting to config

Add ignore_404 setting to config


<?php
require_once realpath(__DIR__ . '/../core/slir.class.php');

abstract class SLIRTestCase extends PHPUnit_Framework_TestCase
{
  /**
   * @var SLIR
   */
  protected $slir;

  /**
   * @return void
   */
  protected function setUp()
  {
    $this->slir = new SLIR();
    SLIRConfig::$defaultImagePath   = null;
    SLIRConfig::$forceQueryString   = false;
    SLIRConfig::$enableErrorImages  = false;
    SLIRConfig::$defaultCropper     = SLIR::CROP_CLASS_CENTERED;
    SLIRConfig::$copyEXIF           = false;

    // Try to fix documentRoot for CLI
    SLIRConfig::$documentRoot = realpath(__DIR__ . '/../../');
  }

  /**
   * @return void
   */
  protected function tearDown()
  {
    unset($this->slir);
  }
}

<?php
require_once realpath(__DIR__ . '/../core/slir.class.php');

abstract class SLIRTestCase extends PHPUnit_Framework_TestCase
{
  /**
   * @var SLIR
   */
  protected $slir;

  /**
   * @return void
   */
  protected function setUp()
  {
    $this->slir = new SLIR();
    SLIRConfig::$defaultImagePath     = null;
    SLIRConfig::$forceQueryString     = false;
    SLIRConfig::$enableErrorImages    = false;
    SLIRConfig::$defaultCropper       = SLIR::CROP_CLASS_CENTERED;
    SLIRConfig::$copyEXIF             = false;
    SLIRConfig::$maxMemoryToAllocate  = -1;

    // Try to fix documentRoot for CLI
    SLIRConfig::$documentRoot = realpath(__DIR__ . '/../../');
  }

  /**
   * @return void
   */
  protected function tearDown()
  {
    unset($this->slir);
  }
}

Set memory_limit to be unlimited for tests


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

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

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

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

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

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

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

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

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

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

        $dataSet->raw_query('INSERT INTO tbluser (\'test\', \'$2a$10$KSQ0GxWYv9nUS.TmNSLYnOo/33maFdXhgQ9qU.fLsMSNwtMnwl3FS\');');

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

Add possitive user login test

Add possitive user login test


<?php

namespace DoSomething\Gateway;

trait ForwardsTransactionIds
{
    /**
     * Run custom tasks before making a request.
     *
     * @see RestApiClient@raw
     */
    public function runForwardsTransactionIdsTasks($method, &$path, &$options, &$withAuthorization)
    {
        $transactionId = isset($_SERVER['HTTP_X_REQUEST_ID']) ? $_SERVER['HTTP_X_REQUEST_ID'] : null;

        // If there is no 'X-Request-ID' in the header, create one.
        if (! $transactionId) {
            $newHeader = ['X-Request-ID' => microtime(true) . '-0'];
        } else {
            // Otherwise, if there is a 'X-Request-ID' header, keep the
            // current transaction ID and increment the step by one.
            list($requestId, $step) = explode('-', $transactionId, 2);
            $newHeader = ['X-Request-ID' => $requestId. '-' . ($step + 1)];
        }

        // Add incremented header to downstream API requests.
        $options['headers'] = array_merge($options['headers'], $newHeader);

        // If we have a logger, write details to the log.
        if (! empty($this->logger)) {
            $this->logger->info('Request made.', [
                'method' => $method,
                'uri' => $this->getBaseUri() . $path,
                'transaction_id' => $options['headers']['X-Request-ID'],
            ]);
        }
    }
}

<?php

namespace DoSomething\Gateway;

trait ForwardsTransactionIds
{
    /**
     * Run custom tasks before making a request.
     *
     * @see RestApiClient@raw
     */
    public function runForwardsTransactionIdsTasks($method, &$path, &$options, &$withAuthorization)
    {
        $transactionId = isset($_SERVER['HTTP_X_REQUEST_ID']) ? $_SERVER['HTTP_X_REQUEST_ID'] : null;

        // If there is no 'X-Request-ID' in the header, create one.
        if (! $transactionId) {
            $newHeader = ['X-Request-ID' => uniqid() . '-0'];
        } else {
            // Otherwise, if there is a 'X-Request-ID' header, keep the
            // current transaction ID and increment the step by one.
            list($requestId, $step) = explode('-', $transactionId, 2);
            $newHeader = ['X-Request-ID' => $requestId. '-' . ($step + 1)];
        }

        // Add incremented header to downstream API requests.
        $options['headers'] = array_merge($options['headers'], $newHeader);

        // If we have a logger, write details to the log.
        if (! empty($this->logger)) {
            $this->logger->info('Request made.', [
                'method' => $method,
                'uri' => $this->getBaseUri() . $path,
                'transaction_id' => $options['headers']['X-Request-ID'],
            ]);
        }
    }
}

Use uniqid rather than plain ol timestamp.


<?php

namespace CupOfTea\WordPress\Foundation\Bootstrap;

use Illuminate\Support\Str;
use Illuminate\Contracts\Container\Container;

class RegisterThemeAutoloader
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Container $app)
    {
        if (! $app->bound('composer')) {
            $composer = new \Composer\Autoload\ClassLoader();
            $composer->register(true);

            $app->instance('composer', $composer);
        }

        $composer = $app->make('composer');
        $themeDir = get_template_directory();

        $namespace = Str::studly(wp_get_theme()->Name) . '\\';
        $path = [];

        foreach (['lib', 'library'] as $directory) {
            $fullPath = $themeDir . '/' . $directory;

            if (file_exists($fullPath) && is_dir($fullPath)) {
                $path[] = $fullPath;
            }
        }

        $composer->addPsr4($namespace, $path);
    }
}

<?php

namespace CupOfTea\WordPress\Foundation\Bootstrap;

use Illuminate\Support\Str;
use Illuminate\Contracts\Container\Container;

class RegisterThemeAutoloader
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Container $app)
    {
        if (! $app->bound('composer')) {
            $composer = new \Composer\Autoload\ClassLoader();
            $composer->register(true);

            $app->instance('composer', $composer);
        }

        $composer = $app->make('composer');
        $themeDir = get_template_directory();

        $namespace = Str::studly(wp_get_theme()->Name) . '\\';
        $path = [];

        foreach (['lib', 'library'] as $directory) {
            $fullPath = $themeDir . '/' . $directory;

            if (file_exists($fullPath) && is_dir($fullPath)) {
                $path[] = $fullPath;
            }
        }

        $libcfg = $themeDir . '/.libcfg';

        if (file_exists($libcfg) && is_file($libcfg)) {
            $libcfg = array_filter(array_map('trim', explode(PHP_EOL, $cfg)));

            $path = array_merge($path, $libcfg);
        }

        $composer->addPsr4($namespace, $path);
    }
}

Allow custom theme lib directories using .libcfg


<?php

namespace Frontend\Modules\Mailmotor\Widgets;

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

use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget;

/**
 * This is a widget with the Subscribe form
 */
class Subscribe extends FrontendBaseWidget
{
    /**
     * Execute the extra
     *
     * @return void
     */
    public function execute()
    {
        // call parent
        parent::execute();

        // load template
        $this->loadTemplate();
    }
}

<?php

namespace Frontend\Modules\Mailmotor\Widgets;

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

use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget;
use Frontend\Modules\Mailmotor\Command\Subscription;
use Frontend\Core\Language\Locale;

/**
 * This is a widget with the Subscribe form
 */
class Subscribe extends FrontendBaseWidget
{
    /**
     * Execute the extra
     *
     * @return void
     */
    public function execute()
    {
        // call parent
        parent::execute();

        // load template
        $this->loadTemplate();

        // Create the form
        $form = $this->createForm(
            $this->get('mailmotor.form.subscription'),
            new Subscription(
                Locale::frontendLanguage()
            )
        );

        $form->handleRequest($this->get('request'));

        if (!$form->isValid()) {
            $this->tpl->assign('form', $form->createView());

            if ($form->isSubmitted()) {
                $this->tpl->assign('mailmotorSubscribeHasFormError', true);
            }
            return;
        }
    }
}

Load the form from the subscribe widget.


<?php

namespace JS\Stdlib\Hydrator\Strategy;

use Zend\Stdlib\Hydrator\Strategy\DefaultStrategy;

class DateTimeStrategy extends DefaultStrategy {

    public function extract($value) {
        if ($value instanceof \DateTime) {
            $value = $value->format('Y-m-d');
        }
        return $value;
    }

    public function hydrate($value) {
        if (is_string($value)) {
            $value = new \DateTime(\DateTime::createFromFormat('d/m/Y', $value)->format('Y-m-d'));
        }
        return $value;
    }

}

<?php

namespace JS\Stdlib\Hydrator\Strategy;

use Zend\Stdlib\Hydrator\Strategy\DefaultStrategy;

class DateTimeStrategy extends DefaultStrategy {

    public function extract($value) {
        if ($value instanceof \DateTime) {
            $value = $value->format('d/m/Y');
        }
        return $value;
    }

    public function hydrate($value) {
        if (is_string($value)) {
            $value = new \DateTime(\DateTime::createFromFormat('d/m/Y', $value)->format('Y-m-d'));
        }
        return $value;
    }

}

Change the format date conversion to d/m/Y


<?php

namespace OpenDominion\Nova\Filters;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;

class UserOnline extends Filter
{
    /**
     * The displayable name of the action.
     *
     * @var string
     */
    public $name = 'Online Users';

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @param  mixed $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(Request $request, $query, $value)
    {
        return (($value === 'online')
            ? $query->whereNotNull('last_online')
                ->where('last_online', '>', (new Carbon('-5 minutes'))->format('Y-m-d H:i:s'))
            : $query->whereNull('last_online')
                ->orWhere('last_online', '<=', (new Carbon('-5 minutes'))->format('Y-m-d H:i:s'))
        );
    }

    /**
     * Get the filter's available options.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function options(Request $request)
    {
        return [
            'Online Users' => 'online',
            'Offline Users' => 'offline',
        ];
    }
}

<?php

namespace OpenDominion\Nova\Filters;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;

class UserOnline extends Filter
{
    public const FIELD = 'last_online';
    public const ONLINE_THRESHOLD = '-5 minutes';

    /**
     * The displayable name of the action.
     *
     * @var string
     */
    public $name = 'Online Users';

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @param  mixed $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(Request $request, $query, $value)
    {
        return (($value === 'online')
            ? $query->whereNotNull(static::FIELD)
                ->where(static::FIELD, '>', (new Carbon(static::ONLINE_THRESHOLD))->format('Y-m-d H:i:s'))
            : $query->whereNull(static::FIELD)
                ->orWhere(static::FIELD, '<=', (new Carbon(static::ONLINE_THRESHOLD))->format('Y-m-d H:i:s'))
        );
    }

    /**
     * Get the filter's available options.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function options(Request $request)
    {
        return [
            'Online Users' => 'online',
            'Offline Users' => 'offline',
        ];
    }
}

Move field and online threshold to constants


<?php

abstract class PhabricatorSSHWorkflow extends PhabricatorManagementWorkflow {

  private $user;
  private $iochannel;
  private $errorChannel;

  public function setErrorChannel(PhutilChannel $error_channel) {
    $this->errorChannel = $error_channel;
    return $this;
  }

  public function getErrorChannel() {
    return $this->errorChannel;
  }

  public function setUser(PhabricatorUser $user) {
    $this->user = $user;
    return $this;
  }

  public function getUser() {
    return $this->user;
  }

  public function setIOChannel(PhutilChannel $channel) {
    $this->iochannel = $channel;
    return $this;
  }

  public function getIOChannel() {
    return $this->iochannel;
  }

  public function readAllInput() {
    $channel = $this->getIOChannel();
    while ($channel->update()) {
      PhutilChannel::waitForAny(array($channel));
      if (!$channel->isOpenForReading()) {
        break;
      }
    }
    return $channel->read();
  }

  public function writeIO($data) {
    $this->getIOChannel()->write($data);
    return $this;
  }

  public function writeErrorIO($data) {
    $this->getErrorChannel()->write($data);
    return $this;
  }

  protected function newPassthruCommand() {
    return id(new PhabricatorSSHPassthruCommand())
      ->setErrorChannel($this->getErrorChannel());
  }

}

<?php

abstract class PhabricatorSSHWorkflow extends PhabricatorManagementWorkflow {

  private $user;
  private $iochannel;
  private $errorChannel;

  public function isExecutable() {
    return false;
  }

  public function setErrorChannel(PhutilChannel $error_channel) {
    $this->errorChannel = $error_channel;
    return $this;
  }

  public function getErrorChannel() {
    return $this->errorChannel;
  }

  public function setUser(PhabricatorUser $user) {
    $this->user = $user;
    return $this;
  }

  public function getUser() {
    return $this->user;
  }

  public function setIOChannel(PhutilChannel $channel) {
    $this->iochannel = $channel;
    return $this;
  }

  public function getIOChannel() {
    return $this->iochannel;
  }

  public function readAllInput() {
    $channel = $this->getIOChannel();
    while ($channel->update()) {
      PhutilChannel::waitForAny(array($channel));
      if (!$channel->isOpenForReading()) {
        break;
      }
    }
    return $channel->read();
  }

  public function writeIO($data) {
    $this->getIOChannel()->write($data);
    return $this;
  }

  public function writeErrorIO($data) {
    $this->getErrorChannel()->write($data);
    return $this;
  }

  protected function newPassthruCommand() {
    return id(new PhabricatorSSHPassthruCommand())
      ->setErrorChannel($this->getErrorChannel());
  }

}

Fix an issue where SSH workflows would execute immediately

Summary: rPe397103bf broke this since one of the implementations was `return false;`, not `return true;`.

Auditors: chad


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

use Sylius\Component\Core\Exception\MissingChannelConfigurationException;
use Sylius\Component\Core\Model\ProductVariantInterface;

/**
 * @deprecated
 */
interface ProductVariantPriceCalculatorInterface
{
    /**
     * @throws MissingChannelConfigurationException when price for given channel does not exist
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int;
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

use Sylius\Component\Core\Exception\MissingChannelConfigurationException;
use Sylius\Component\Core\Model\ProductVariantInterface;

/**
 * @deprecated since Sylius 1.8, use ProductVariantPricesCalculatorInterface instead
 */
interface ProductVariantPriceCalculatorInterface
{
    /**
     * @throws MissingChannelConfigurationException when price for given channel does not exist
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int;
}

Add details to price calculator interface deprecation annotation


<?php

/*
 * This file is part of Transfer.
 *
 * For the full copyright and license information, please view the LICENSE file located
 * in the root directory.
 */

namespace Transfer\Adapter\Transaction;

/**
 * Holds data for transaction objects.
 */
class DataAggregate implements \IteratorAggregate
{
    /**
     * @var \Iterator Data iterator
     */
    protected $iterator;

    /**
     * @param array|\Iterator $data Data array or iterator
     */
    public function __construct($data)
    {
        $this->setData($data);
    }

    /**
     * Returns iterator with associated data.
     *
     * If the data aggregate was initialized with an array, an \ArrayIterator will be returned.
     *
     * @return \Iterator Data iterator
     */
    public function getData()
    {
        return $this->iterator;
    }

    /**
     * Assigns data to the aggregate.
     *
     * @param array|\Iterator $object
     */
    public function setData($object)
    {
        if ($object instanceof \Iterator) {
            $this->iterator = $object;
        } elseif (is_array($object)) {
            $this->iterator = new \ArrayIterator($object);
        } else {
            throw new \InvalidArgumentException(sprintf(
                'Expecting object of type array or \Iterator, %s given',
                gettype($object)
            ));
        }
    }

    /**
     * @see self::getData()
     */
    public function getIterator()
    {
        return $this->iterator;
    }
}

<?php

/*
 * This file is part of Transfer.
 *
 * For the full copyright and license information, please view the LICENSE file located
 * in the root directory.
 */

namespace Transfer\Adapter\Transaction;

/**
 * Holds data for transaction objects.
 */
class DataAggregate implements \IteratorAggregate
{
    /**
     * @var \Iterator Data iterator
     */
    protected $iterator;

    /**
     * @param array|\Iterator|\Traversable $data Data array or iterator
     */
    public function __construct($data)
    {
        $this->setData($data);
    }

    /**
     * Returns iterator with associated data.
     *
     * If the data aggregate was initialized with an array, an \ArrayIterator will be returned.
     *
     * @return \Iterator Data iterator
     */
    public function getData()
    {
        return $this->iterator;
    }

    /**
     * Assigns data to the aggregate.
     *
     * @param array|\Iterator $object
     */
    public function setData($object)
    {
        if ($object instanceof \Iterator) {
            $this->iterator = $object;
        } elseif (is_array($object)) {
            $this->iterator = new \ArrayIterator($object);
        } else {
            throw new \InvalidArgumentException(sprintf(
                'Expecting object of type array or \Iterator, %s given',
                gettype($object)
            ));
        }
    }

    /**
     * @see self::getData()
     */
    public function getIterator()
    {
        return $this->iterator;
    }
}

Allow data aggregate contents to be traversable


<?php

	header("Content-Type: text/html; charset=UTF-8");

	require("time.php");

?>
<!DOCTYPE html>

		<title><?php echo $pageMeta["title"]?></title>
		<link rel="stylesheet" href="/wp-content/themes/quis/css/quis.css" type="text/css" />
		<link rel="alternate" type="application/rss+xml" title="quis.cc RSS feed" href="/feed/" />
		<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
		<meta name="description" content="<?php echo $pageMeta["description"]?>" />

				quis.cc is Chris Hill-Scott's photo blog

<?php

	header("Content-Type: text/html; charset=UTF-8");

	require("time.php");

?>
<!DOCTYPE html>

		<title><?php echo $pageMeta["title"]?></title>
    <meta charset="utf-8">
		<link rel="stylesheet" href="/wp-content/themes/quis/css/quis.css" type="text/css" />
		<link rel="alternate" type="application/rss+xml" title="quis.cc RSS feed" href="/feed/" />
		<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
		<meta name="description" content="<?php echo $pageMeta["description"]?>" />

				quis.cc is Chris Hill-Scott's photo blog

Fix charset and lang for serving static page


<?php
namespace Neos\Eel\Helper;

/*
 * This file is part of the Neos.Eel package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;

/**
 * JSON helpers for Eel contexts
 *
 * @Flow\Proxy(false)
 */
class JsonHelper implements ProtectedContextAwareInterface
{
    /**
     * JSON encode the given value
     *
     * @param mixed $value
     * @return string
     */
    public function stringify($value)
    {
        return json_encode($value);
    }

    /**
     * JSON decode the given string
     *
     * @param string $json
     * @param boolean $associativeArrays
     * @return mixed
     */
    public function parse($json, $associativeArrays = true)
    {
        return json_decode($json, $associativeArrays);
    }

    /**
     * All methods are considered safe
     *
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName)
    {
        return true;
    }
}

<?php
namespace Neos\Eel\Helper;

/*
 * This file is part of the Neos.Eel package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;

/**
 * JSON helpers for Eel contexts
 *
 * @Flow\Proxy(false)
 */
class JsonHelper implements ProtectedContextAwareInterface
{
    /**
     * JSON encode the given value
     *
     * @param mixed $value
     * @param array $options Array of option constant names as strings
     * @return string
     */
    public function stringify($value, array $options = []): string
    {
        $optionSum = array_sum(array_map('constant', $options));
        return json_encode($value, $optionSum);
    }

    /**
     * JSON decode the given string
     *
     * @param string $json
     * @param boolean $associativeArrays
     * @return mixed
     */
    public function parse($json, $associativeArrays = true)
    {
        return json_decode($json, $associativeArrays);
    }

    /**
     * All methods are considered safe
     *
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName)
    {
        return true;
    }
}

FEATURE: Add PHPs json_encode options to stringify eel helper


<?php
declare(strict_types=1);

/**
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @copyright     Copyright (c) Brian Nesbitt <brian@nesbot.com>
 * @link          http://cakephp.org CakePHP(tm) Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

if (!\class_exists('Carbon\Carbon') && !\interface_exists('Carbon\CarbonInterface', false)) {
    // Create class aliases for Carbon so applications
    // can upgrade more easily.
    class_alias('Cake\Chronos\Chronos', 'Carbon\MutableDateTime');
    class_alias('Cake\Chronos\ChronosInterface', 'Carbon\CarbonInterface');
}

<?php
declare(strict_types=1);

/**
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @copyright     Copyright (c) Brian Nesbitt <brian@nesbot.com>
 * @link          http://cakephp.org CakePHP(tm) Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

// Check if the interface alias exists and don't redeclare it in case we are in
// a preloaded context.
if (!\class_exists('Carbon\Carbon') && !\interface_exists('Carbon\CarbonInterface', false)) {
    // Create class aliases for Carbon so applications
    // can upgrade more easily.
    class_alias('Cake\Chronos\Chronos', 'Carbon\MutableDateTime');
    class_alias('Cake\Chronos\ChronosInterface', 'Carbon\CarbonInterface');
}

Add comment about preload context.

Add comment about preload context.


<?php namespace Nestor\Repositories;

use Nestor\Model\Execution;

class DbExecutionRepository extends DbBaseRepository implements ExecutionRepository {

	public function __construct(Execution $model)
	{
		parent::__construct($model);
	}

	public function findByTestRunId($test_run_id)
	{
		return $this->model->where('test_run_id', $test_run_id)->get()->toArray();
	}

	public function findByTestCaseVersionId($testCaseVersionId)
	{
		return $this->model->where('test_case_version_id', $testCaseVersionId)->get()->toArray();
	}

	public function findByExecutionStatusId($execution_status_id)
	{
		return $this->model->where('execution_status_id', $execution_status_id)->get()->toArray();
	}

	public function getExecutionsForTestCaseVersion($testRunId, $testCaseVersionId)
	{
		return $this
			->model
			->where('test_case_version_id', '=', $testCaseVersionId)
			->where('test_run_id', '=', $testRunId)
			->orderBy('executions.created_at')
			->with('executionStatus')
			->get()
			->toArray();
	}

}

<?php namespace Nestor\Repositories;

use Nestor\Model\Execution;

class DbExecutionRepository extends DbBaseRepository implements ExecutionRepository {

	public function __construct(Execution $model)
	{
		parent::__construct($model);
	}

	public function findByTestRunId($test_run_id)
	{
		return $this->model->where('test_run_id', $test_run_id)->get()->toArray();
	}

	public function findByTestCaseVersionId($testCaseVersionId)
	{
		return $this->model->where('test_case_version_id', $testCaseVersionId)->get()->toArray();
	}

	public function findByExecutionStatusId($execution_status_id)
	{
		return $this->model->where('execution_status_id', $execution_status_id)->get()->toArray();
	}

	public function getExecutionsForTestCaseVersion($testRunId, $testCaseVersionId)
	{
		return $this
			->model
			->where('test_case_version_id', '=', $testCaseVersionId)
			->where('test_run_id', '=', $testRunId)
			->orderBy('executions.created_at', 'DESC')
			->with('executionStatus')
			->get()
			->toArray();
	}

}

Fix ordering for test executions

Fix ordering for test executions


<?php
/**
 * PHPCI - Continuous Integration for PHP
 *
 * @copyright    Copyright 2014, Block 8 Limited.
 * @license      https://github.com/Block8/PHPCI/blob/master/LICENSE.md
 * @link         https://www.phptesting.org/
 */

namespace PHPCensor\Helper;

/**
* User Helper - Provides access to logged in user information in views.
* @author       Dan Cryer <dan@block8.co.uk>
* @package      PHPCI
* @subpackage   Web
*/
class User
{
    /**
     * Proxies method calls through to the current active user model.
     * @param $method
     * @param array $params
     * @return mixed|null
     */
    public function __call($method, $params = [])
    {
        $user = $_SESSION['php-censor-user'];

        if (!is_object($user)) {
            return null;
        }

        return call_user_func_array([$user, $method], $params);
    }
}

<?php
/**
 * PHPCI - Continuous Integration for PHP
 *
 * @copyright    Copyright 2014, Block 8 Limited.
 * @license      https://github.com/Block8/PHPCI/blob/master/LICENSE.md
 * @link         https://www.phptesting.org/
 */

namespace PHPCensor\Helper;

/**
* User Helper - Provides access to logged in user information in views.
* @author       Dan Cryer <dan@block8.co.uk>
* @package      PHPCI
* @subpackage   Web
*/
class User
{
    /**
     * Proxies method calls through to the current active user model.
     * @param $method
     * @param array $params
     * @return mixed|null
     */
    public function __call($method, $params = [])
    {
        if (empty($_SESSION['php-censor-user'])) {
            return null;
        }

        $user = $_SESSION['php-censor-user'];

        if (!is_object($user)) {
            return null;
        }

        return call_user_func_array([$user, $method], $params);
    }
}

Check session value before use

Check session value before use


<?php
namespace SMVC\Controller;

class Asset extends \Base\Controller {
  public static $mapping = array(
    'scripts' => '\Base\JavascriptAssetView',
    'scriptMap' => '\Base\SourceMapAssetView'
  );
  public function run() {
    $args = func_get_args();
    $section = array_shift($args);
    $fullfilename = array_pop($args);
    $args[] = preg_replace('/\.[a-z]+$/i', '', $fullfilename);
    $path = implode('/', $args);

    if (!array_key_exists($section, static::$mapping)) {
      $this->content = $section;
      // return $this->show_404();
    }

    // Exception ... source maps
    if (preg_match('/\.map$/', $fullfilename)) {
      $section = 'scriptMap';
      if (isProduction()) {
        return $this->content = '{}';
      }
    }

    $viewClass = static::$mapping[$section];
    header('Content-Type: ' . $viewClass::$mime);

    $view = new $viewClass($path);
    echo $view->render();
  }
}

<?php
namespace SMVC\Controller;

class Asset extends \Base\Controller {
  public static $mapping = array(
    'scripts' => '\Base\JavascriptAssetView',
    'images' => '\Base\PngAssetView',
    'scriptMap' => '\Base\SourceMapAssetView'
  );
  public function run() {
    $args = func_get_args();
    $section = array_shift($args);
    $fullfilename = array_pop($args);
    $args[] = preg_replace('/\.[a-z]+$/i', '', $fullfilename);
    $path = implode('/', $args);

    if (!array_key_exists($section, static::$mapping)) {
      $this->content = $section;
      // return $this->show_404();
    }

    // Exception ... source maps
    if (preg_match('/\.map$/', $fullfilename)) {
      $section = 'scriptMap';
      if (isProduction()) {
        return $this->content = '{}';
      }
    }

    $viewClass = static::$mapping[$section];
    header('Content-Type: ' . $viewClass::$mime);

    $view = new $viewClass($path);
    echo $view->render();
  }
}

Add images to the asset pipeline

Add images to the asset pipeline


<?php

namespace Htsl\Parser\Node;

use Htsl\Htsl;
use Htsl\ReadingBuffer\Line;
use Htsl\Parser\Section;

////////////////////////////////////////////////////////////////

class NamelessSectionNode extends SectionNode
{
	/**
	 * Real constructor.
	 *
	 * @access protected
	 *
	 * @return \Htsl\Parser\Node\Contracts\ANode
	 */
	protected function construct():parent
	{
		$this->name= null;

		return $this;
	}
}

<?php

namespace Htsl\Parser\Node;

use Htsl\Htsl;
use Htsl\ReadingBuffer\Line;
use Htsl\Parser\Node\Contracts\ANode;
use Htsl\Parser\Section;

////////////////////////////////////////////////////////////////

class NamelessSectionNode extends SectionNode
{
	/**
	 * Real constructor.
	 *
	 * @access protected
	 *
	 * @return \Htsl\Parser\Node\Contracts\ANode
	 */
	protected function construct():ANode
	{
		$this->name= null;

		return $this;
	}
}

Fix overriding return type for PHP7.1

Fix overriding return type for PHP7.1


@extends('layout')

@section('content')

Create User Group

<form action="{{admin_link('user_role-store')}}" method='POST'>

{{csrf_field()}}

<input type='text' name='group_name' style='color:black;width:100%;' required>

    @foreach($permission_list as $key => $perm_name)

        <?php $perm_name = str_replace("Admin area","Admin area",$perm_name) dsfsdf?>

{!!$perm_name!!}<input type='checkbox' class='pull-right' name='{{$key}}' value='1'>

    @endforeach

<button type='submit' class='btn btn-warning btn-block'>Add user group</button>

</form>

@endsection

@extends('layout')

@section('content')

Create User Group

<form action="{{admin_link('user_role-store')}}" method='POST'>

{{csrf_field()}}

<input type='text' name='group_name' style='color:black;width:100%;' required>

    @foreach($permission_list as $key => $perm_name)

        <?php $perm_name = str_replace("Admin area","Admin area",$perm_name) ?>

{!!$perm_name!!}<input type='checkbox' class='pull-right' name='{{$key}}' value='1'>

    @endforeach

<button type='submit' class='btn btn-warning btn-block'>Add user group</button>

</form>

@endsection

Fix user role create view

Fix user role create view


<?php
namespace Mapbender\DataSourceBundle;

use Mapbender\CoreBundle\Component\MapbenderBundle;

/**
 * DataSource Bundle.
 * y
 * @author Andriy Oblivantsev
 */
class MapbenderDataSourceBundle extends MapbenderBundle
{
    /**
     * @inheritdoc
     */
    public function getElements()
    {
        return array(
            'Mapbender\DataSourceBundle\Element\DataManagerElement',
            'Mapbender\DataSourceBundle\Element\QueryBuilderElement'
        );
    }
}

<?php
namespace Mapbender\DataSourceBundle;

use Mapbender\CoreBundle\Component\MapbenderBundle;

/**
 * DataSource Bundle.
 * y
 * @author Andriy Oblivantsev
 */
class MapbenderDataSourceBundle extends MapbenderBundle
{
    /**
     * @inheritdoc
     */
    public function getElements()
    {
        return array(
            'Mapbender\DataSourceBundle\Element\DataManagerElement',
            'Mapbender\DataSourceBundle\Element\QueryBuilderElement'
        );
    }

    /**
     * @inheritdoc
     */
    public function getManagerControllers()
    {
        $trans = $this->container->get('translator');
        return array(
            array(
                'weight' => 20,
                'title'  => $trans->trans("DataStores"),
                'route'  => 'mapbender_datasource_datastore_index',
                'routes' => array(
                    'mapbender_datasource_datastore',
                ),
            )
        );
    }
}

Add administration data store routing

Add administration data store routing


<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Filesystem\Filesystem;
use Symfony\Component\Yaml\Yaml;

class DevelopersController extends Controller
{
    public function index()
    {
        return view('developers.index', [
            'title' => trans('app.developers.title'),
        ]);
    }

    public function contact()
    {
        return view('developers.contact', [
            'title' => trans('app.contact.title'),
        ]);
    }

    public function redirectToIndex()
    {
        return redirect()->route('developers.index');
    }

    public function endpoints(Filesystem $fs)
    {
        $endpoints = collect(Yaml::parse($fs->get('live/endpoints.yml')))->sortBy('name');

        return view('developers.endpoints', [
            'title'     => trans('app.endpoints.title'),
            'endpoints' => $endpoints,
        ]);
    }
}

<?php

namespace App\Http\Controllers;

use App\Model\Endpoint;
use Illuminate\Contracts\Filesystem\Filesystem;
use Symfony\Component\Yaml\Yaml;

class DevelopersController extends Controller
{
    public function index()
    {
        return view('developers.index', [
            'title' => trans('app.developers.title'),
        ]);
    }

    public function contact()
    {
        return view('developers.contact', [
            'title' => trans('app.contact.title'),
        ]);
    }

    public function redirectToIndex()
    {
        return redirect()->route('developers.index');
    }

    public function endpoints(Filesystem $fs)
    {
        $endpoints = Endpoint::all();

        return view('developers.endpoints', [
            'title'     => trans('app.endpoints.title'),
            'endpoints' => $endpoints,
        ]);
    }
}

Use the endpoints table as datasource for the html list


<?php

class LoaderEdgeListBipartit extends LoaderFile{
    public function createGraph(){

        $graph = new Graph();

        $file = $this->getLines();

        $graph->createVertices($this->readInt($file[0]));

        $countOfAllVertices = $file[0];
        $countOfVerticesInA = $file[1];

        for ($i = 0; $i < $countOfVerticesInA; $i++){
            $graph->getVertex($i)->setBalance(11);
        }

        for($k = $countOfVerticesInA; $k < $countOfAllVertices; $k++){
            $graph->getVertex($k)->setBalance(22);
        }

        unset($file[0]);
        unset($file[1]);
        foreach ($file as $zeile) {
            $parts = $this->readLine($zeile,array('vertex','vertex'),$graph);

            if ($this->directedEdges){
                $edge = $parts[0]->createEdgeTo($parts[1]);
            }
            else {
                $edge = $parts[0]->createEdge($parts[1]);
            }
        }

        return $graph;

    }
}

<?php

class LoaderEdgeListBipartit extends LoaderFile{
    public function createGraph(){

        $graph = new Graph();

        $file = $this->getLines();

        $graph->createVertices($this->readInt($file[0]));

        $countOfAllVertices = $file[0];
        $countOfVerticesInA = $file[1];

        for ($i = 0; $i < $countOfVerticesInA; $i++){
            $graph->getVertex($i)->setLayout('label','A');
        }

        for($k = $countOfVerticesInA; $k < $countOfAllVertices; $k++){
            $graph->getVertex($k)->setLayout('label','B');
        }

        unset($file[0]);
        unset($file[1]);
        foreach ($file as $zeile) {
            $parts = $this->readLine($zeile,array('vertex','vertex'),$graph);

            if ($this->directedEdges){
                $edge = $parts[0]->createEdgeTo($parts[1]);
            }
            else {
                $edge = $parts[0]->createEdge($parts[1]);
            }
        }

        return $graph;

    }
}

Set layout to A & B instead using balance


<?php
/**
 * Unit test class for the DisallowLongArraySyntax sniff.
 *
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 */

namespace PHP_CodeSniffer\Standards\Generic\Tests\Arrays;

use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;

class DisallowShortArraySyntaxUnitTest extends AbstractSniffUnitTest
{

    /**
     * Returns the lines where errors should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of errors that should occur on that line.
     *
     * @return array<int, int>
     */
    public function getErrorList()
    {
        return array(
                3 => 1,
                5 => 1,
                7 => 1,
                8 => 1,
               );

    }//end getErrorList()

    /**
     * Returns the lines where warnings should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of warnings that should occur on that line.
     *
     * @return array<int, int>
     */
    public function getWarningList()
    {
        return array();

    }//end getWarningList()

}//end class

<?php
/**
 * Unit test class for the DisallowShortArraySyntax sniff.
 *
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 */

namespace PHP_CodeSniffer\Standards\Generic\Tests\Arrays;

use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;

class DisallowShortArraySyntaxUnitTest extends AbstractSniffUnitTest
{

    /**
     * Returns the lines where errors should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of errors that should occur on that line.
     *
     * @return array<int, int>
     */
    public function getErrorList()
    {
        return array(
                3 => 1,
                5 => 1,
                7 => 1,
                8 => 1,
               );

    }//end getErrorList()

    /**
     * Returns the lines where warnings should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of warnings that should occur on that line.
     *
     * @return array<int, int>
     */
    public function getWarningList()
    {
        return array();

    }//end getWarningList()

}//end class

Fix file level doc for test class

Fix file level doc for test class

Fix DisallowLongArraySyntax to DisallowShortArraySyntax.


<?php

/**
 * Package Routes
 */

Route::group(['namespace' => 'Taskforcedev\CrudAPI\Http\Controllers'], function () {
    Route::group(['prefix' => 'api'], function () {
        Route::get('{model}/{id}', 'ApiController@show');
        Route::get('{model}', 'ApiController@index');
        Route::post('{model}', 'ApiController@store');
    });

    Route::group(['prefix' => 'admin/crud'], function () {
        Route::get('{model}/{id}', 'AdminController@show');
        Route::get('{model}', 'AdminController@index');
        Route::post('{model}', 'AdminController@store');
    });
});

<?php

/**
 * Package Routes
 */

Route::group(['namespace' => 'Taskforcedev\CrudAPI\Http\Controllers'], function () {
    Route::group(['prefix' => 'api'], function () {
        Route::get('{model}/{id}', 'ApiController@show');
        Route::get('{model}', 'ApiController@index');
        Route::post('{model}', 'ApiController@store');
        Route::delete('{model}/{id}', 'ApiController@destroy');
    });

    Route::group(['prefix' => 'admin/crud'], function () {
        Route::get('{model}/{id}', 'AdminController@show');
        Route::get('{model}', 'AdminController@index');
        Route::post('{model}', 'AdminController@store');
    });
});

Add delete (destroy method) for ApiController.


<?php

namespace Oro\Bundle\SearchBundle\EventListener;

use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\UnitOfWork;
use Oro\Bundle\SearchBundle\Provider\SearchMappingProvider;

/**
 * This trait contains common code that repeats in
 * the listeners used for creating indexes.
 */
trait IndexationListenerTrait
{
    /**
     * @var SearchMappingProvider
     */
    protected $mappingProvider;

    /**
     * @param UnitOfWork $uow
     *
     * @return object[]
     */
    protected function getEntitiesWithUpdatedIndexedFields(UnitOfWork $uow)
    {
        $entitiesToReindex = [];

        foreach ($uow->getScheduledEntityUpdates() as $hash => $entity) {
            $className = ClassUtils::getClass($entity);
            if (!$this->mappingProvider->hasFieldsMapping($className)) {
                continue;
            }

            $entityConfig = $this->mappingProvider->getEntityConfig($className);

            $indexedFields = [];
            foreach ($entityConfig['fields'] as $fieldConfig) {
                $indexedFields[] = $fieldConfig['name'];
            }

            $changeSet = $uow->getEntityChangeSet($entity);
            $fieldsToReindex = array_intersect($indexedFields, array_keys($changeSet));
            if ($fieldsToReindex) {
                $entitiesToReindex[$hash] = $entity;
            }
        }

        return $entitiesToReindex;
    }
}

<?php

namespace Oro\Bundle\SearchBundle\EventListener;

use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\UnitOfWork;

use Oro\Bundle\SearchBundle\Provider\AbstractSearchMappingProvider;

/**
 * This trait contains common code that repeats in
 * the listeners used for creating indexes.
 */
trait IndexationListenerTrait
{
    /**
     * @var AbstractSearchMappingProvider
     */
    protected $mappingProvider;

    /**
     * @param UnitOfWork $uow
     *
     * @return object[]
     */
    protected function getEntitiesWithUpdatedIndexedFields(UnitOfWork $uow)
    {
        $entitiesToReindex = [];

        foreach ($uow->getScheduledEntityUpdates() as $hash => $entity) {
            $className = ClassUtils::getClass($entity);
            if (!$this->mappingProvider->hasFieldsMapping($className)) {
                continue;
            }

            $entityConfig = $this->mappingProvider->getEntityConfig($className);

            $indexedFields = [];
            foreach ($entityConfig['fields'] as $fieldConfig) {
                $indexedFields[] = $fieldConfig['name'];
            }

            $changeSet = $uow->getEntityChangeSet($entity);
            $fieldsToReindex = array_intersect($indexedFields, array_keys($changeSet));
            if ($fieldsToReindex) {
                $entitiesToReindex[$hash] = $entity;
            }
        }

        return $entitiesToReindex;
    }
}

BB-4189: Create listener for all entities in website search
 - used correct mapping provider
 - removed website restriction
 - fixed functional test


<?php

return [

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

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

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

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

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

];

<?php

return [

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

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

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

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

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

];

Add new Stripe webhook config values

Add new Stripe webhook config values

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


<?php
namespace SimpleQuiz\Utils;

class Location {

    protected $_suburb = null;
    protected $_district = null;
    protected $_region = null;
    protected $_state = null;

    public function __construct($suburb) {
        $this->loadBySuburb($suburb);
    }

    public function loadBySuburb($suburb) {
        $this->_suburb = $suburb;

        $location = \ORM::for_table('location')->where('suburb', $suburb)->find_one();

        $this->_district = $location["district"];
        $this->_region = $location["region"];
        $this->_state = $location["state"];
    }

    public function getSuburb() {
        return $this->_suburb;
    }
    public function getDistrict() {
        return $this->_district;
    }
    public function getRegion() {
        return $this->_region;
    }
    public function getState() {
        return $this->_state;
    }

    public function getLowestLevelLocation() {
        if ($this->_suburb) {
            return $this->_suburb;
        }
        else if ($this->_district) {
            return $this->_district;
        }
        else if ($this->_region) {
            return $this->_region;
        }
        else {
            return $this->_state;
        }
    }
}

<?php
namespace SimpleQuiz\Utils;

class Location {

    protected $_suburb = null;
    protected $_district = null;
    protected $_region = null;
    protected $_state = null;

    public function __construct($suburb) {
        $this->loadBySuburb($suburb);
    }

    public function loadBySuburb($suburb) {
        $location = \ORM::for_table('location')->where('suburb', $suburb)->find_one();

        $this->_suburb = trim(strpos($suburb, " (") !== -1 ? substr($suburb, 0, strpos($suburb, " (")) : $suburb);

        $this->_district = $location["district"];
        $this->_region = $location["region"];
        $this->_state = $location["state"];
    }

    public function getSuburb() {
        return $this->_suburb;
    }
    public function getDistrict() {
        return $this->_district;
    }
    public function getRegion() {
        return $this->_region;
    }
    public function getState() {
        return $this->_state;
    }

    public function getLowestLevelLocation() {
        if ($this->_suburb) {
            return $this->_suburb;
        }
        else if ($this->_district) {
            return $this->_district;
        }
        else if ($this->_region) {
            return $this->_region;
        }
        else {
            return $this->_state;
        }
    }
}

Fix for ambiguous suburbs that have brackets and screw some things up.