<?php

namespace Miaoxing\Config\Service;

use Wei\Env;
use Exception;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Sftp\SftpAdapter;
use League\Flysystem\Filesystem;
use Wei\RetTrait;

/**
 * 配置服务
 *
 * @property Env $env
 */
class ConfigV1 extends \Wei\Config
{
    use RetTrait;

    /**
     * 配置文件的路径
     *
     * @var string
     */
    protected $configFile = 'data/config.php';

    /**
     * {@inheritdoc}
     */
    public function __construct(array $options = [])
    {
        parent::__construct($options);

        // If the config service is not constructed, the service container can't set config for it
        if (!$this->wei->isInstanced('configV1')) {
            $this->wei->set('configV1', $this);
        }

        $this->env->loadConfigFile($this->configFile);
    }
}

<?php

namespace Miaoxing\Config\Service;

use Wei\Env;
use Wei\RetTrait;

/**
 * 配置服务
 *
 * @property Env $env
 */
class ConfigV1 extends \Wei\Config
{
    use RetTrait;

    /**
     * 配置文件的路径
     *
     * @var string
     */
    protected $configFile = 'data/config.php';

    /**
     * {@inheritdoc}
     */
    public function __construct(array $options = [])
    {
        parent::__construct($options);

        // If the config service is not constructed, the service container can't set config for it
        if (!$this->wei->isInstanced('configV1')) {
            $this->wei->set('configV1', $this);
        }

        $this->env->loadConfigFile($this->configFile);
    }
}

Fix coding standard [skip fix]

Fix coding standard [skip fix]


<?php

use Estaty\Application;
use Estaty\Controller\HomepageController;

$app['homepage.controller'] = $app->share(function(Silex\Application $app) {
    return new HomepageController();
});

$app->get('/', 'homepage.controller:show')
    ->bind('homepage');

<?php

use Estaty\Application;
use Estaty\Controller\HomepageController;

$app['homepage.controller'] = $app->share(function() {
    return new HomepageController();
});

$app->get('/', 'homepage.controller:show')
    ->bind('homepage');

Remove unused param from anonymous function


<?php

namespace Outlandish\Wpackagist\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ExceptionListener
{
    public function onKernelException(ExceptionEvent $event)
    {
        $message = 'Something went wrong.';
        $exception = $event->getThrowable();
        $response = new Response();

        if ($exception instanceof HttpExceptionInterface) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());

            if ($exception->getStatusCode() === 404) {
                $message = 'The requested page could not be found.';
            }
        } else {
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        $response->setContent($message);

        $event->setResponse($response);
    }
}

<?php

namespace Outlandish\Wpackagist\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ExceptionListener
{
    public function onKernelException(ExceptionEvent $event)
    {
        // Let Symfony's default error tracing happen in dev.
        if (getenv('APP_ENV') === 'dev') {
            return;
        }

        $message = 'Something went wrong.';
        $exception = $event->getThrowable();
        $response = new Response();

        if ($exception instanceof HttpExceptionInterface) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());

            if ($exception->getStatusCode() === 404) {
                $message = 'The requested page could not be found.';
            }
        } else {
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        $response->setContent($message);

        $event->setResponse($response);
    }
}

Allow normal traces in dev

Allow normal traces in dev


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use PHPUnit\Util\Test as TestUtil;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class DataProviderTestSuite extends TestSuite
{
    /**
     * @var string[]
     */
    private $dependencies = [];

    /**
     * @param string[] $dependencies
     */
    public function setDependencies(array $dependencies): void
    {
        $this->dependencies = $dependencies;

        foreach ($this->tests as $test) {
            if (!$test instanceof TestCase) {
                continue;
            }

            $test->setDependencies($dependencies);
        }
    }

    public function getDependencies(): array
    {
        return $this->dependencies;
    }

    public function hasDependencies(): bool
    {
        return \count($this->dependencies) > 0;
    }

    /**
     * Returns the size of the each test created using the data provider(s)
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function getSize(): int
    {
        [$className, $methodName] = \explode('::', $this->getName());

        /** @psalm-suppress ArgumentTypeCoercion */
        return TestUtil::getSize($className, $methodName);
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use PHPUnit\Util\Test as TestUtil;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class DataProviderTestSuite extends TestSuite
{
    /**
     * @var string[]
     */
    private $dependencies = [];

    /**
     * @param string[] $dependencies
     */
    public function setDependencies(array $dependencies): void
    {
        $this->dependencies = $dependencies;

        foreach ($this->tests as $test) {
            if (!$test instanceof TestCase) {
                continue;
            }

            $test->setDependencies($dependencies);
        }
    }

    public function getDependencies(): array
    {
        return $this->dependencies;
    }

    public function hasDependencies(): bool
    {
        return \count($this->dependencies) > 0;
    }

    /**
     * Returns the size of the each test created using the data provider(s)
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function getSize(): int
    {
        [$className, $methodName] = \explode('::', $this->getName());

        /* @psalm-suppress ArgumentTypeCoercion */
        return TestUtil::getSize($className, $methodName);
    }
}

Revert "Revert "Last codestyle fix (I hope)""

This reverts commit f57f550268ef23ccb74c6b4da6f4e0cb4d515179.


<?php

namespace Parsnick\EloquentJs;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('eloquentjs.applicator', function ($app) {
            return new Applicator($app['request']->input('query'));
        });
    }
}

<?php

namespace Parsnick\EloquentJs;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('eloquentjs.applicator', function ($app) {
            return new Applicator($app['request']->input('query', '[]'));
        });
    }
}

Fix for empty query stack

Fix for empty query stack


<?php

declare(strict_types=1);

namespace Cortex\Fort\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:publish:fort';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Publish Cortex Fort Resources.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->warn('Publish cortex/fort:');
        $this->call('vendor:publish', ['--tag' => 'rinvex-fort-config']);
        $this->call('vendor:publish', ['--tag' => 'cortex-fort-views']);
        $this->call('vendor:publish', ['--tag' => 'cortex-fort-lang']);
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Fort\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:publish:fort {--force : Overwrite any existing files.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Publish Cortex Fort Resources.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->warn('Publish cortex/fort:');
        $this->call('vendor:publish', ['--tag' => 'rinvex-fort-config', '--force' => $this->option('force')]);
        $this->call('vendor:publish', ['--tag' => 'cortex-fort-views', '--force' => $this->option('force')]);
        $this->call('vendor:publish', ['--tag' => 'cortex-fort-lang', '--force' => $this->option('force')]);
    }
}

Add --force option to module:publish command


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * @package   Zend_ModuleManager
 */

namespace Zend\ModuleManager\Listener;

/**
 * Module resolver listener
 *
 * @category   Zend
 * @package    Zend_ModuleManager
 * @subpackage Listener
 */
class ModuleResolverListener extends AbstractListener
{
    /**
     * @param  \Zend\EventManager\EventInterface $e
     * @return object
     */
    public function __invoke($e)
    {
        $moduleName = $e->getModuleName();
        $class      = $moduleName . '\Module';

        if (!class_exists($class)) {
            return false;
        }

        $module = new $class;
        return $module;
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * @package   Zend_ModuleManager
 */

namespace Zend\ModuleManager\Listener;

use Zend\ModuleManager\ModuleEvent;

/**
 * Module resolver listener
 *
 * @category   Zend
 * @package    Zend_ModuleManager
 * @subpackage Listener
 */
class ModuleResolverListener extends AbstractListener
{
    /**
     * @param  ModuleEvent $e
     * @return object|false False if module class does not exist
     */
    public function __invoke(ModuleEvent $e)
    {
        $moduleName = $e->getModuleName();
        $class      = $moduleName . '\Module';

        if (!class_exists($class)) {
            return false;
        }

        $module = new $class;
        return $module;
    }
}

Add missing module event type hint

Add missing module event type hint


<?php namespace Flarum\Core\Support;

use Flarum\Core\Models\User;
use Flarum\Core\Models\Guest;

class Actor
{
    protected $user;

    public function getUser()
    {
        return $this->user ?: new Guest;
    }

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

<?php namespace Flarum\Core\Support;

use Flarum\Core\Models\Guest;

class Actor
{
    protected $user;

    public function getUser()
    {
        return $this->user ?: new Guest;
    }

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

Fix setting user to null, for now

Fix setting user to null, for now

Still need to flesh out the exact purpose/use of the Actor class


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Log Channel
    |--------------------------------------------------------------------------
    |
    | This option defines the default log channel that gets used when writing
    | messages to the logs. The name specified in this option should match
    | one of the channels defined in the "channels" configuration array.
    |
    */

    'default' => env('LOG_CHANNEL', 'stack'),

    /*
    |--------------------------------------------------------------------------
    | Log Channels
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log channels for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Drivers: "single", "daily", "slack", "syslog",
    |                    "errorlog", "custom", "stack"
    |
    */

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 7,
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Log Channel
    |--------------------------------------------------------------------------
    |
    | This option defines the default log channel that gets used when writing
    | messages to the logs. The name specified in this option should match
    | one of the channels defined in the "channels" configuration array.
    |
    */

    'default' => env('LOG_CHANNEL', 'stack'),

    /*
    |--------------------------------------------------------------------------
    | Log Channels
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log channels for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Drivers: "single", "daily", "slack", "syslog",
    |                    "errorlog", "custom", "stack"
    |
    */

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'permission' => 02770,
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 7,
            'permission' => 02770,
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

];

Set the permission of the file logs for daily and single to be 02770


<?php

/*
 * Copyright (c) 2016 Refinery29, Inc.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Refinery29\Piston\Middleware\Request;

use League\Pipeline\StageInterface;
use Refinery29\Piston\Middleware\GetOnlyStage;
use Refinery29\Piston\Middleware\Payload;
use Refinery29\Piston\Request;

class IncludedResource implements StageInterface
{
    use GetOnlyStage;

    /**
     * @param Payload $payload
     *
     * @throws \League\Route\Http\Exception\BadRequestException
     *
     * @return Request
     */
    public function process($payload)
    {
        /** @var Request $request */
        $request = $payload->getRequest();

        if (!isset($request->getQueryParams()['include'])) {
            return $payload;
        }

        $this->ensureGetOnlyRequest($request);

        $include = explode(',', $request->getQueryParams()['include']);

        if (!empty($include)) {
            foreach ((array) $include as $k => $resource) {
                if (strpos($resource, '.') !== false) {
                    $resource = explode('.', $resource);

                    $include[$k] = $resource;
                }
            }

            //$request->setIncludedResources($include);
            $payload->withRequest($request->withIncludedResources($include));
        }

        return $payload;
    }
}

<?php

/*
 * Copyright (c) 2016 Refinery29, Inc.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Refinery29\Piston\Middleware\Request;

use League\Pipeline\StageInterface;
use Refinery29\Piston\Middleware\GetOnlyStage;
use Refinery29\Piston\Middleware\Payload;
use Refinery29\Piston\Request;

class IncludedResource implements StageInterface
{
    use GetOnlyStage;

    /**
     * @param Payload $payload
     *
     * @throws \League\Route\Http\Exception\BadRequestException
     *
     * @return Payload
     */
    public function process($payload)
    {
        /** @var Request $request */
        $request = $payload->getRequest();

        if (!isset($request->getQueryParams()['include'])) {
            return $payload;
        }

        $this->ensureGetOnlyRequest($request);

        $include = explode(',', $request->getQueryParams()['include']);

        if (!empty($include)) {
            foreach ((array) $include as $k => $resource) {
                if (strpos($resource, '.') !== false) {
                    $resource = explode('.', $resource);

                    $include[$k] = $resource;
                }
            }

            $payload = $payload->withRequest(
                $request->withIncludedResources($include)
            );

        }

        return $payload;
    }
}

Correct bug in updating Payload with new Request object


<?php

namespace AppBundle\Form\Type;

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class UserType
 * @package AppBundle\Form\Type
 */
class UserType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', null, [
            'description' => 'The user name'
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'csrf_protection' => false,
        ]);
    }

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

<?php

namespace AppBundle\Form\Type;

use AppBundle\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class UserType
 * @package AppBundle\Form\Type
 */
class UserType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', null, [
            'description' => 'The user name'
        ]);
        $builder->add('userDetails', EntityType::class, [
            'class' => 'AppBundle:UserDetail',
            'description' => 'The user detail id',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'csrf_protection' => false,
        ]);
    }

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

Add the user detail ID to the form validation


<?php

use Carbon\Carbon;
use EklundChristopher\ViewPress\Application;

if (! function_exists('viewpress_view'))
{
    /**
     * Render a view file.
     *
     * @param  string  $template
     * @param  array  $data  []
     * @return string
     */
    function viewpress_view($template, array $data = [])
    {
        if (is_admin()) {
            return;
        }

        return Application::getInstance()->view($template, $data);
    }
}

if (! function_exists('viewpress_directive'))
{
    /**
     * Register a Blade directive.
     *
     * @param  string  $name
     * @param  callable  $closure
     * @return void
     */
    function viewpress_directive($name, callable $closure)
    {
        if (is_admin()) {
            return;
        }

        $compiler = Application::getInstance()->view->getEngineResolver()->resolve('blade')->getCompiler();

        $compiler->directive($name, $closure);
    }
}

if (! function_exists('viewpress_timeago'))
{
    /**
     * Display a more humanly readable date & time.
     *
     * @param  string  $date
     * @return string
     */
    function viewpress_timeago($date)
    {
        $timestamp = strtotime($date);

        return Carbon::createFromTimestamp($timestamp)->diffForHumans();
    }
}

<?php

use Carbon\Carbon;
use EklundChristopher\ViewPress\Application;

if (! function_exists('viewpress_view'))
{
    /**
     * Render a view file.
     *
     * @param  string  $template
     * @param  array  $data  []
     * @return string
     */
    function viewpress_view($template, array $data = [])
    {
        if (is_admin() and ! defined('DOING_AJAX') and ! DOING_AJAX) {
            return;
        }

        return Application::getInstance()->view($template, $data);
    }
}

if (! function_exists('viewpress_directive'))
{
    /**
     * Register a Blade directive.
     *
     * @param  string  $name
     * @param  callable  $closure
     * @return void
     */
    function viewpress_directive($name, callable $closure)
    {
        if (is_admin()) {
            return;
        }

        $compiler = Application::getInstance()->view->getEngineResolver()->resolve('blade')->getCompiler();

        $compiler->directive($name, $closure);
    }
}

if (! function_exists('viewpress_timeago'))
{
    /**
     * Display a more humanly readable date & time.
     *
     * @param  string  $date
     * @return string
     */
    function viewpress_timeago($date)
    {
        $timestamp = strtotime($date);

        return Carbon::createFromTimestamp($timestamp)->diffForHumans();
    }
}

Allow AJAX viewpress view function calls


<?php

namespace Symfony\Upgrade\Fixer;

use Symfony\CS\Tokenizer\Tokens;

abstract class FormTypeFixer extends AbstractFixer
{
    protected $types = [
        'Birthday',
        'Button',
        'Checkbox',
        'Choice',
        'Collection',
        'Country',
        'Currency',
        'DateTime',
        'Email',
        'File',
        'Hidden',
        'Integer',
        'Language',
        'Locale',
        'Money',
        'Number',
        'Password',
        'Percent',
        'Radio',
        'Range',
        'Repeated',
        'Reset',
        'Search',
        'Submit',
        'Text',
        'Textarea',
        'Time',
        'Timezone',
        'Url',
    ];

    protected function isFormType(Tokens $tokens)
    {
        return $this->extendsClass($tokens, ['Symfony', 'Component', 'Form', 'AbstractType']);
    }

    protected function addTypeUse(Tokens $tokens, $name)
    {
        $this->addUseStatement(
            $tokens,
            ['Symfony', 'Component', 'Form', 'Extension', 'Core', 'Type', ucfirst($name).'Type']
        );
    }
}

<?php

namespace Symfony\Upgrade\Fixer;

use Symfony\CS\Tokenizer\Tokens;

abstract class FormTypeFixer extends AbstractFixer
{
    protected $types = [
        'Birthday',
        'Button',
        'Checkbox',
        'Choice',
        'Collection',
        'Country',
        'Currency',
        'DateTime',
        'Date',
        'Email',
        'File',
        'Hidden',
        'Integer',
        'Language',
        'Locale',
        'Money',
        'Number',
        'Password',
        'Percent',
        'Radio',
        'Range',
        'Repeated',
        'Reset',
        'Search',
        'Submit',
        'Text',
        'Textarea',
        'Time',
        'Timezone',
        'Url',
    ];

    protected function isFormType(Tokens $tokens)
    {
        return $this->extendsClass($tokens, ['Symfony', 'Component', 'Form', 'AbstractType']);
    }

    protected function addTypeUse(Tokens $tokens, $name)
    {
        $this->addUseStatement(
            $tokens,
            ['Symfony', 'Component', 'Form', 'Extension', 'Core', 'Type', ucfirst($name).'Type']
        );
    }
}

Add missing Date form type

Add missing Date form type

http://symfony.com/doc/current/reference/forms/types/date.html


<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

$error = NULL;
try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

openid: Fix notice about unititialized variable.

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@3027 44740490-163a-0410-bde0-09ae8108e29a


<?php

namespace JPC\Test\MongoDB\ODM\Factory;

use JPC\MongoDB\ODM\Factory\ClassMetadataFactory;
use JPC\Test\MongoDB\ODM\Framework\TestCase;

class ClassMetadataFactoryTest extends TestCase
{

    /**
     * @var ClassMetadataFactory
     */
    private $classMetadataFactory;

    public function setUp()
    {
        $this->classMetadataFactory = new ClassMetadataFactory();
    }

    public function testGetMetadataForClassInexisting()
    {
        $this->expectException(\Exception::class);

        $this->classMetadataFactory->getMetadataForClass("Inexisting");
    }

    public function testGetMetadataForClass()
    {
        $classMeta = $this->classMetadataFactory->getMetadataForClass("stdClass");

        $this->assertInstanceOf(\JPC\MongoDB\ODM\Tools\ClassMetadata\ClassMetadata::class, $classMeta);

        $this->assertCount(1, $this->getPropertyValue($this->classMetadataFactory, "loadedMetadata"));
    }
}

<?php

namespace JPC\Test\MongoDB\ODM\Factory;

use JPC\MongoDB\ODM\Factory\ClassMetadataFactory;
use JPC\Test\MongoDB\ODM\Framework\TestCase;

class ClassMetadataFactoryTest extends TestCase
{

    /**
     * @var ClassMetadataFactory
     */
    private $classMetadataFactory;

    public function setUp()
    {
        $this->classMetadataFactory = new ClassMetadataFactory();
    }

    public function testGetMetadataForClassInexisting()
    {
        $this->expectException(\Exception::class);

        $this->classMetadataFactory->getMetadataForClass("Inexisting");
    }

    public function testGetMetadataForClass()
    {
        $classMeta = $this->classMetadataFactory->getMetadataForClass("stdClass");

        $this->assertInstanceOf(\JPC\MongoDB\ODM\Tools\ClassMetadata\ClassMetadata::class, $classMeta);
    }
}

Add cache expiration on class metadata

Add cache expiration on class metadata


<?php

namespace Identicon;

use Identicon\Identity\Identity;
use Imagine\Gd\Imagine;

class IdenticonTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateNew()
    {
        $identicon = new Identicon("myidentity");

        $this->assertInstanceOf("\Identicon\Identicon", $identicon);
    }

    public function testGetIdentity()
    {
        $identicon = new Identicon("myidentity");
        $identity = $identicon->getIdentity();
        $expectedIdentity = new Identity("myidentity");
        $this->assertEquals($identity->__toString(), $expectedIdentity->__toString());
    }

    public function testGetContentDefaultSize()
    {
        $identicon = new Identicon("myidentity");
        $filename = sprintf("%s/%s.%s", sys_get_temp_dir(), uniqid("identicon-test-"), "png");
        file_put_contents($filename, $identicon->getContent());
        $this->assertFileExists($filename);

        $mimeType = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filename);
        $this->assertEquals("image/png", $mimeType);

        $imagine = new Imagine();
        $image = $imagine->open($filename);
        $this->assertEquals(420, $image->getSize()->getWidth());
        $this->assertEquals(420, $image->getSize()->getHeight());
    }
}

<?php

namespace Identicon;

use Identicon\Identity\Identity;
use Imagine\Gd\Imagine;

class IdenticonTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateNew()
    {
        $identicon = new Identicon("myidentity");

        $this->assertInstanceOf("\Identicon\Identicon", $identicon);
    }

    public function testGetIdentity()
    {
        $identicon = new Identicon("myidentity");
        $identity = $identicon->getIdentity();
        $expectedIdentity = new Identity("myidentity");
        $this->assertEquals($identity->__toString(), $expectedIdentity->__toString());
    }

    public function testGetContentDefaultSize()
    {
        $identicon = new Identicon("myidentity");
        $filename = sprintf("%s/%s.%s", sys_get_temp_dir(), uniqid("identicon-test-"), "png");
        file_put_contents($filename, $identicon->getContent());
        $this->assertFileExists($filename);

        $mimeType = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filename);
        $this->assertEquals("image/png", $mimeType);

        $imagine = new Imagine();
        $image = $imagine->open($filename);
        $this->assertEquals(420, $image->getSize()->getWidth());
        $this->assertEquals(420, $image->getSize()->getHeight());
        unlink($filename);
    }
}

Remove generated image in tests.

Remove generated image in tests.


<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;

class ClearCompiledCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'clear-compiled';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove the compiled class file';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $compiledPath = $this->laravel->getCachedCompilePath();
        $servicesPath = $this->laravel->getCachedServicesPath();

        if (file_exists($compiledPath)) {
            @unlink($compiledPath);
        }

        if (file_exists($servicesPath)) {
            @unlink($servicesPath);
        }
    }
}

<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;

class ClearCompiledCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'clear-compiled';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove the compiled class file';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $compiledPath = $this->laravel->getCachedCompilePath();
        $servicesPath = $this->laravel->getCachedServicesPath();

        if (file_exists($compiledPath)) {
            @unlink($compiledPath);
        }

        if (file_exists($servicesPath)) {
            @unlink($servicesPath);
        }

        $this->info('Compiled class file removed!');
    }
}

Add success message to clear-compiled command


<?php

namespace Feedbee\Smp\Collection;

class UniqueCollection extends Collection
{
    /**
     * @param array $values
     * @return \Feedbee\Smp\Collection\Collection
     */
    public function setValues(array $values)
    {
        parent::setValues(array_unique($values, SORT_REGULAR));

        return $this;
    }

    /**
     * @param mixed $value
     * @return \Feedbee\Smp\Collection\Collection
     */
    public function addValue($value)
    {
        if (!$this->hasValue($value)) {
            parent::addValue($value);
        }

        return $this;
    }
}

<?php

namespace Feedbee\Smp\Collection;

class UniqueCollection extends Collection
{
    /**
     * @param array $values
     * @return \Feedbee\Smp\Collection\Collection
     */
    public function setValues(array $values)
    {
        foreach ($values as $value) {
            $this->addValue($value);
        }

        return $this;
    }

    /**
     * @param mixed $value
     * @return \Feedbee\Smp\Collection\Collection
     */
    public function addValue($value)
    {
        if (!$this->hasValue($value)) {
            parent::addValue($value);
        }

        return $this;
    }
}

Fix unizue collection object compare bug


@extends('page::page-layouts.default')
@section('title', 'Laravel Pages')
@section('body')

@include('page::shared.header', ["class_name" => "landing bg-5"])

@include('page::shared.nav')

            Just add content...

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est error quae nostrum beatae, iusto accusantium repudiandae accusamus veritatis, voluptatum nesciunt dolorem aspernatur saepe a asperiores.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea doloribus similique officiis laudantium ratione praesentium. Voluptatibus, commodi saepe molestias ea iure optio dignissimos. Non, iusto.

@include('page::shared.footer')

@endsection

@push('styles')

@endpush
@push('scripts')

@endpush

Remove duplicate AOS js call

Remove duplicate AOS js call


<?php

$data = [
    'username' => 'darth',
    'email'    => 'd.vader@theempire.com',
];

// Inserts data and returns inserted row's primary key
$userModel->insert($data);

// Inserts data and returns true on success and false on failure
$userModel->insert($data, false);

// Returns inserted row's primary key
$userModel->getInsertID();

Add line at end of file

Add line at end of file


<?php
/**
 *
 */

namespace Arc5\Facade;

use Mvc5\App;
use Mvc5\Service\Context;
use Mvc5\Service\Facade;
use Mvc5\Service\Service as _Service;

trait Service
{
    /**
     *
     */
    use Facade
    {
        call as public;
        param as public;
        plugin as public;
        service as public;
        shared as public;
        trigger as public;
    }

    /**
     * @param _Service $service
     * @return callable|_Service
     */
    static function bind(_Service $service)
    {
        return Context::bind($service);
    }

    /**
     * @param $config
     * @param callable|null $provider
     * @param bool $scope
     * @return callable|_Service
     */
    static function context($config = [], callable $provider = null, $scope = true)
    {
        return static::bind(new App($config, $provider, $scope));
    }
}

<?php
/**
 *
 */

namespace Arc5\Facade;

use Mvc5\App;
use Mvc5\Service\Context;
use Mvc5\Service\Facade;
use Mvc5\Service\Service as _Service;

trait Service
{
    /**
     *
     */
    use Facade
    {
        call as public;
        param as public;
        plugin as public;
        service as public;
        shared as public;
        trigger as public;
    }

    /**
     * @param _Service $service
     * @return callable|_Service
     */
    static function bind(_Service $service)
    {
        return Context::bind($service);
    }

    /**
     * @param $config
     * @param callable|null $provider
     * @param bool $scope
     * @return callable|_Service
     */
    static function context($config = [], callable $provider = null, $scope = true)
    {
        return static::bind(new App($config, $provider, $scope));
    }

    /**
     * @param $name
     * @param array $args
     * @return mixed
     */
    static function __callStatic($name, array $args)
    {
        return static::service()->call($name, $args);
    }
}

Add call static helper method to service context


<?php

require_once __DIR__ . "/ResolverTestCase.php";

class CanonicalUrlResolverTest extends ResolverTestCase
{

    protected function setUp()
    {
        $this->urlResolver = new \Concrete\Core\Url\Resolver\CanonicalUrlResolver();
    }

    public function testConfig()
    {
        $canonical = "http://example.com:1337";
        $old_value = \Config::get('concrete.seo.canonical_url');
        \Config::set('concrete.seo.canonical_url', $canonical);

        $this->assertEquals(
            (string) \Concrete\Core\Url\Url::createFromUrl($canonical)->setPath(\Core::getApplicationRelativePath()),
            (string) $this->urlResolver->resolve(array()));

        \Config::set('concrete.seo.canonical_url', $old_value);
    }

    public function testFromRequest()
    {
        $mock = $this->getMock('\Concrete\Core\Http\RequestBase');
        $mock->expects($this->once())->method('getScheme')->willReturn('http');
        $mock->expects($this->once())->method('getHost')->willReturn('somehost');

        \Request::setInstance($mock);
        $old_value = \Config::get('concrete.seo.canonical_url');
        \Config::set('concrete.seo.canonical_url', null);

        $this->assertEquals(
            (string) \Concrete\Core\Url\Url::createFromUrl("http://somehost")->setPath(\Core::getApplicationRelativePath()),
            (string) $this->urlResolver->resolve(array()));

        \Config::set('concrete.seo.canonical_url', $old_value);
    }

}

<?php

require_once __DIR__ . "/ResolverTestCase.php";

class CanonicalUrlResolverTest extends ResolverTestCase
{

    protected function setUp()
    {
        $this->urlResolver = new \Concrete\Core\Url\Resolver\CanonicalUrlResolver();
    }

    public function testConfig()
    {
        $canonical = "http://example.com:1337";
        $old_value = \Config::get('concrete.seo.canonical_url');
        \Config::set('concrete.seo.canonical_url', $canonical);

        $this->assertEquals(
            (string) \Concrete\Core\Url\Url::createFromUrl($canonical)->setPath(\Core::getApplicationRelativePath()),
            (string) $this->urlResolver->resolve(array()));

        \Config::set('concrete.seo.canonical_url', $old_value);
    }

    public function testFromRequest()
    {
        $mock = $this->getMock('\Concrete\Core\Http\RequestBase');
        $mock->expects($this->once())->method('getScheme')->willReturn('http');
        $mock->expects($this->once())->method('getHost')->willReturn('somehost');

        $old_instance = \Request::getInstance();
        \Request::setInstance($mock);
        $old_value = \Config::get('concrete.seo.canonical_url');
        \Config::set('concrete.seo.canonical_url', null);

        $this->assertEquals(
            (string) \Concrete\Core\Url\Url::createFromUrl("http://somehost")->setPath(\Core::getApplicationRelativePath()),
            (string) $this->urlResolver->resolve(array()));

        \Config::set('concrete.seo.canonical_url', $old_value);
        \Request::setInstance($old_instance);
    }

}

Reset the request instance after the tests complete


<?php
$db_core = require(__DIR__ . '/db_core.php');
$db_bank = require(__DIR__ . '/db_bank.php');
$db_openerp = require(__DIR__ . '/db_openerp.php');
Yii::setAlias('@base', dirname(dirname(__DIR__)));

return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'extensions' => require(__DIR__ . '/../../vendor/yiisoft/extensions.php'),
    'language' => 'fi',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'db_core' => $db_core,
        'db_bank' => $db_bank,
        'db' => $db_openerp,
        'mail' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => true,
        ],
        'i18n' => [
            'translations' => [
                '*' => [
                    'class' => 'yii\i18n\PhpMessageSource',
                    'basePath' => '@base/messages',
                    'sourceLanguage' => 'en',
                ],
            ],
        ],
    ],
];

<?php
$db_core = require(__DIR__ . '/db_core.php');
$db_bank = require(__DIR__ . '/db_bank.php');
$db_openerp = require(__DIR__ . '/db_openerp.php');
Yii::setAlias('@base', dirname(dirname(__DIR__)));

return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'extensions' => require(__DIR__ . '/../../vendor/yiisoft/extensions.php'),
    'language' => 'fi',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'db_core' => $db_core,
        'db_bank' => $db_bank,
        'db' => $db_openerp,
        'mail' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => true,
        ],
        'i18n' => [
            'translations' => [
                '*' => [
                    'class' => 'yii\i18n\PhpMessageSource',
                    'basePath' => '@base/messages',
                    'sourceLanguage' => 'en',
                ],
            ],
        ],
        'formatter' => [
            'dateFormat' => 'd.m.Y',
        ]
    ],
];

Add a default date format

Add a default date format


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\Log;

use Monolog\Logger;
use Psr\Log\LoggerInterface;

class ContextEnrichingLoggerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_passes_additional_context_to_the_decorated_logger()
    {
        /** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject $decoratedLogger */
        $decoratedLogger = $this->createMock(LoggerInterface::class);
        $additionalContext = array(
            'job_id' => 1,
        );
        $logger = new ContextEnrichingLogger(
            $decoratedLogger,
            $additionalContext
        );

        $decoratedLogger->expects($this->once())
            ->method('log')
            ->with(
                Logger::DEBUG,
                'test',
                [
                    'foo' => 'bar',
                    'job_id' => 1
                ]
            );
        $logger->log(
            Logger::DEBUG,
            'test',
            [
                'foo' => 'bar'
            ]
        );
    }
}

<?php

namespace CultuurNet\UDB3\Log;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

class ContextEnrichingLoggerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_passes_additional_context_to_the_decorated_logger()
    {
        /** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject $decoratedLogger */
        $decoratedLogger = $this->createMock(LoggerInterface::class);
        $additionalContext = array(
            'job_id' => 1,
        );
        $logger = new ContextEnrichingLogger(
            $decoratedLogger,
            $additionalContext
        );

        $decoratedLogger->expects($this->once())
            ->method('log')
            ->with(
                LogLevel::DEBUG,
                'test',
                [
                    'foo' => 'bar',
                    'job_id' => 1
                ]
            );
        $logger->log(
            LogLevel::DEBUG,
            'test',
            [
                'foo' => 'bar'
            ]
        );
    }
}

III-1783: Remove unnecessary dependency on Monolog


<?php

class TemplateOverrideExtensionTest extends SapphireTest {

	protected static $fixture_file = 'template-override/tests/pages.yml';

	public function setUpOnce() {
		parent::setupOnce();
	}

	public function testUpdateCMSFields() {
		$page = $this->objFromFixture('Page', 'page1');
		$fields = $page->getCMSFields();
		$tab = $fields->findOrMakeTab('Root.Template');
		$fields = $tab->FieldList();
		$names = array();
		foreach ($fields as $field) {
			$names[] = $field->getName();
		}
		$expected = array('AlternativeTemplate', 'infofield');
		$this->assertEquals($expected, $names);
	}
}

<?php

class TemplateOverrideExtensionTest extends SapphireTest {

	protected static $fixture_file = 'template-override/tests/pages.yml';

	public function testUpdateCMSFields() {
		$page = $this->objFromFixture('Page', 'page1');
		$fields = $page->getCMSFields();
		$tab = $fields->findOrMakeTab('Root.Template');
		$fields = $tab->FieldList();
		$names = array();
		foreach ($fields as $field) {
			$names[] = $field->getName();
		}
		$expected = array('AlternativeTemplate', 'infofield');
		$this->assertEquals($expected, $names);
	}
}

MINOR: Remove setup method that was not showing in coverage tests


<?php
/**
 * @link http://mikhailmikhalev.ru
 * @author Mikhail Mikhalev
 */

namespace nhkey\arh\managers;

use Yii;
use yii\db\Connection;
use yii\di\Instance;

/**
 * Class DBManager for save history in DB
 * @package nhkey\arh
 */
class DBManager extends BaseManager
{
    public $tableName = '{{%modelhistory}}';

    /**
     * @var string
     */
    public static $db = 'db';

    /**
     * @param array $data
     */
    public function saveField($data)
    {
        self::getDB()->createCommand()
            ->insert($this->tableName, $data)->execute();
    }

    /**
     * @return object Return database connection
     * @throws \yii\base\InvalidConfigException
     */
    private static function getDB()
    {
        return Instance::ensure(self::$db, Connection::className());
    }
}

<?php
/**
 * @link http://mikhailmikhalev.ru
 * @author Mikhail Mikhalev
 */

namespace nhkey\arh\managers;

use Yii;
use yii\db\Connection;
use yii\di\Instance;

/**
 * Class DBManager for save history in DB
 * @package nhkey\arh
 */
class DBManager extends BaseManager
{
    public static $defaultTableName = '{{%modelhistory}}'; // static default for migration
    public $tableName;

    /**
     * @var string
     */
    public static $db = 'db';

    /**
     * @param array $data
     */
    public function saveField($data)
    {
        $table =  isset($this->tableName) ? $this->tableName : $this::$defaultTableName;

        self::getDB()->createCommand()
            ->insert($table, $data)->execute();
    }

    /**
     * @return object Return database connection
     * @throws \yii\base\InvalidConfigException
     */
    private static function getDB()
    {
        return Instance::ensure(self::$db, Connection::className());
    }
}

Fix for Custom Table Name

Fix for Custom Table Name


<?php

namespace Phive\TaskQueue\Tests;

use Phive\Queue\NoItemAvailableException;
use Phive\TaskQueue\Executor;

class ExecutorTest extends \PHPUnit_Framework_TestCase
{
    private $adapter;
    private $queue;
    private $logger;

    /**
     * @var Executor
     */
    private $executor;

    protected function setUp()
    {
        $this->adapter = $this->getMock('\Phive\TaskQueue\ExecutorAdapter\ExecutorAdapter');

        $this->queue = $this->getMock('\Phive\Queue\Queue');
        $this->logger = $this->getMock('\Psr\Log\LoggerInterface');

        $context = $this->getMock('\Phive\TaskQueue\ExecutionContext', [], [], '', false);
        $context->expects($this->any())->method('getQueue')->will($this->returnValue($this->queue));
        $context->expects($this->any())->method('getLogger')->will($this->returnValue($this->logger));

        $this->executor = new Executor($this->adapter, $context);
    }

    public function testExecuteReturnsFalseOnEmptyQueue()
    {
        $exception = new NoItemAvailableException($this->queue);
        $this->queue->expects($this->any())->method('pop')->will($this->throwException($exception));

        $this->assertFalse($this->executor->execute());
    }
}

<?php

namespace Phive\TaskQueue\Tests;

use Phive\Queue\NoItemAvailableException;
use Phive\TaskQueue\Executor;

class ExecutorTest extends \PHPUnit_Framework_TestCase
{
    private $adapter;
    private $queue;
    private $logger;

    /**
     * @var Executor
     */
    private $executor;

    protected function setUp()
    {
        $this->adapter = $this->getMockBuilder('\Phive\TaskQueue\ExecutorAdapter\ExecutorAdapter')->getMock();

        $this->queue = $this->getMockBuilder('\Phive\Queue\Queue')->getMock();
        $this->logger = $this->getMockBuilder('\Psr\Log\LoggerInterface')->getMock();

        $context = $this->getMockBuilder('\Phive\TaskQueue\ExecutionContext')
            ->disableOriginalConstructor()
            ->getMock();

        $context->expects($this->any())->method('getQueue')->will($this->returnValue($this->queue));
        $context->expects($this->any())->method('getLogger')->will($this->returnValue($this->logger));

        $this->executor = new Executor($this->adapter, $context);
    }

    public function testExecuteReturnsFalseOnEmptyQueue()
    {
        $exception = new NoItemAvailableException($this->queue);
        $this->queue->expects($this->any())->method('pop')->will($this->throwException($exception));

        $this->assertFalse($this->executor->execute());
    }
}

Make tests phpunit 5 compatible

Make tests phpunit 5 compatible


<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Doug
 * Date: 28/07/13
 * Time: 12:58
 * To change this template use File | Settings | File Templates.
 */

  namespace DVDoug\BoxPacker;

  class ItemListTest extends \PHPUnit_Framework_TestCase {

    function testCompare() {

      $box1 = new TestItem('Small', 20, 20, 2, 100);
      $box2 = new TestItem('Large', 200, 200, 20, 1000);
      $box3 = new TestItem('Medium', 100, 100, 10, 500);

      $list = new ItemList;
      $list->insert($box1);
      $list->insert($box2);
      $list->insert($box3);

      $list->top();

      $sorted = [];
      while ($list->valid()) {
        $sorted[] = $list->current();
        $list->next();
      }
      self::assertEquals([$box2,$box3,$box1], $sorted);
    }
  }

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Doug
 * Date: 28/07/13
 * Time: 12:58
 * To change this template use File | Settings | File Templates.
 */

  namespace DVDoug\BoxPacker;

  class ItemListTest extends \PHPUnit_Framework_TestCase {

    function testCompare() {

      $box1 = new TestItem('Small', 20, 20, 2, 100);
      $box2 = new TestItem('Large', 200, 200, 20, 1000);
      $box3 = new TestItem('Medium', 100, 100, 10, 500);

      $list = new ItemList;
      $list->insert($box1);
      $list->insert($box2);
      $list->insert($box3);

      $sorted = [];
      while (!$list->isEmpty()) {
        $sorted[] = $list->extract();
      }
      self::assertEquals([$box2,$box3,$box1], $sorted);
    }
  }

Tweak test to use heap more naturally

Tweak test to use heap more naturally


<?php namespace ProcessWire;

$ProcessGraphQL = $modules->get('ProcessGraphQL');
$ProcessGraphQL->GraphQLServerUrl = $config->urls->root . '/graphql/';
echo $ProcessGraphQL->executeGraphiQL();

<?php namespace ProcessWire;

$ProcessGraphQL = $modules->get('ProcessGraphQL');
$ProcessGraphQL->GraphQLServerUrl = '/graphql/';
echo $ProcessGraphQL->executeGraphiQL();

Fix the graphql server url.

Fix the graphql server url.


		<?php if ($content_type = Controller::$view->mime_type): ?>
			<?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?>
			 <meta http-equiv="Content-Type" content="<?php echo $content_type ?>">
		<?php endif; ?>
		<?php if ($author = Backend::getConfig('application.author')): ?>
			<meta name="author" content="<?php echo $author ?>">
		<?php endif; ?>
		<?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?>
			<meta name="description" content="<?php echo $meta_description ?>">
		<?php endif; ?>
		<meta name="generator" content="backend-php.net">
		<?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?>
			<meta name="keywords" content="<?php echo $keywords ?>">
		<?php endif; ?>
		<?php if (!empty($meta_values) && is_array($meta_values)): ?>
			<?php foreach($meta_values as $name => $value): ?>
				<meta name="<?php echo $name ?>" value="<?php echo $value ?>">
			<?php endforeach; ?>
		<?php endif; ?>

		<?php if ($content_type = Controller::$view->mime_type): ?>
			<?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?>
			 <meta http-equiv="Content-Type" content="<?php echo $content_type ?>">
		<?php endif; ?>
		<?php if ($author = Backend::getConfig('application.author')): ?>
			<meta name="author" content="<?php echo $author ?>">
		<?php endif; ?>
		<?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?>
			<meta name="description" content="<?php echo $meta_description ?>">
		<?php endif; ?>
		<meta name="generator" content="backend-php.net">
		<?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?>
			<meta name="keywords" content="<?php echo $keywords ?>">
		<?php endif; ?>
		<?php if (!empty($meta_values) && is_array($meta_values)): ?>
			<?php foreach($meta_values as $name => $value): ?>
				<meta property="<?php echo $name ?>" value="<?php echo $value ?>"/>
			<?php endforeach; ?>
		<?php endif; ?>

Use property instead of name for meta tags


<?php

namespace Northstar\Http\Middleware;

use League\OAuth2\Server\Server as OAuthServer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class ParseOAuthHeader
{
    /**
     * Authenticate constructor.
     * @param OAuthServer $oauth
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     */
    public function __construct(OAuthServer $oauth, ServerRequestInterface $request, ResponseInterface $response)
    {
        $this->oauth = $oauth;
        $this->request = $request;
        $this->response = $response;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $header = $request->header('Authorization');

        // If the 'Authorization' header is set, and it's not the legacy
        // 32 character key (with the "Bearer " prefix = 39 characters)...
        if (! empty($header) && strlen($header) !== 39) {
            $this->request = $this->oauth->validateAuthenticatedRequest($this->request);

            // Add the parsed attributes (oauth_access_token_id, oauth_client_id,
            // oauth_user_id, & oauth_scopes) to the request.
            $request->attributes->add($this->request->getAttributes());
        }

        return $next($request);
    }
}

<?php

namespace Northstar\Http\Middleware;

use League\OAuth2\Server\Server as OAuthServer;
use Psr\Http\Message\ServerRequestInterface;

class ParseOAuthHeader
{
    /**
     * Authenticate constructor.
     * @param OAuthServer $oauth
     * @param ServerRequestInterface $request
     */
    public function __construct(OAuthServer $oauth, ServerRequestInterface $request)
    {
        $this->oauth = $oauth;
        $this->request = $request;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $header = $request->header('Authorization');

        // If the 'Authorization' header is set, and it's not the legacy
        // 32 character key (with the "Bearer " prefix = 39 characters)...
        if (! empty($header) && strlen($header) !== 39) {
            $this->request = $this->oauth->validateAuthenticatedRequest($this->request);

            // Add the parsed attributes (oauth_access_token_id, oauth_client_id,
            // oauth_user_id, & oauth_scopes) to the request.
            $request->attributes->add($this->request->getAttributes());
        }

        return $next($request);
    }
}

Remove PSR-7 response interface from middleware.


<?php

namespace Clastic\SecurityBundle\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/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('clastic_security');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

[User] Remove deprecated implementations of setDefaultOptions.


<?php
/**
 * Created by PhpStorm.
 * User: siciarek
 * Date: 18.09.17
 * Time: 13:59
 */

namespace Siciarek\SymfonyCommonBundle\Model\ExtraData;

use Doctrine\ORM\Mapping as ORM;

/**
* ExtraData trait.
*
* Should be used inside entity where you need to store some extradata (JSON serialized)
*/
trait ExtraDataProperties
{
    /**
     * @ORM\Column(type="json_array")
     */
    protected $data;
}

<?php
/**
 * Created by PhpStorm.
 * User: siciarek
 * Date: 18.09.17
 * Time: 13:59
 */

namespace Siciarek\SymfonyCommonBundle\Model\ExtraData;

use Doctrine\ORM\Mapping as ORM;

/**
* ExtraData trait.
*
* Should be used inside entity where you need to store some extradata (JSON serialized)
*/
trait ExtraDataProperties
{
    /**
     * @ORM\Column(type="json_array")
     */
    protected $data = [];
}

Add default value to ExtraData trait

Add default value to ExtraData trait


<?php
namespace AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

class TaskRepository extends EntityRepository
{
    public function findAllUncompleted()
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT t, l FROM AppBundle:Task t
                JOIN t.list l
                WHERE t.completed = :completed
                ORDER BY l.name ASC, t.task ASC')
            ->setParameter('completed', '0')
            ->getResult();
    }
}

<?php
namespace AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

class TaskRepository extends EntityRepository
{
    public function findAllUncompleted()
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT t, l FROM AppBundle:Task t
                LEFT JOIN t.list l
                WHERE t.completed = :completed
                ORDER BY l.name ASC, t.task ASC')
            ->setParameter('completed', '0')
            ->getResult();
    }
}

Use LEFT JOIN for tasks

Use LEFT JOIN for tasks


<?php

namespace CultuurNet\UDB3\EventExport\Format\HTML;

use Alchemy\Zippy\Zippy;

/**
 * Creates a ZIP archive of a an HTML export and all needed assets.
 *
 * Inside the zip file, all files are located in a 'html' folder.
 */
class ZippedWebArchiveFileWriter extends WebArchiveFileWriter
{
    /**
     * {@inheritdoc}
     */
    public function write($filePath, $events)
    {
        $directory = $this->createWebArchiveDirectory($events);

        $zippy = Zippy::load();
        $zippy->create(
            $filePath,
            [
                'html' => $this->expandTmpPath($directory)
            ]
        );

        $this->removeTemporaryArchiveDirectory($directory);
    }
}

<?php

namespace CultuurNet\UDB3\EventExport\Format\HTML;

use League\Flysystem\Filesystem;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;

/**
 * Creates a ZIP archive of a an HTML export and all needed assets.
 *
 * Inside the zip file, all files are located in a 'html' folder.
 */
class ZippedWebArchiveFileWriter extends WebArchiveFileWriter
{
    /**
     * {@inheritdoc}
     */
    public function write($filePath, $events)
    {
        $directory = $this->createWebArchiveDirectory($events);

        $this->zipDirectory($directory, $filePath);

        $this->removeTemporaryArchiveDirectory($directory);
    }

    protected function zipDirectory($directory, $filePath)
    {
        $zipArchive = new ZipArchiveAdapter(
            $filePath
        );

        $this->mountManager->mountFilesystem(
            'zip',
            new Filesystem(
                $zipArchive
            )
        );

        $webArchiveFiles = $this->mountManager->listContents(
            'tmp://' . $directory,
            true
        );

        foreach ($webArchiveFiles as $file) {
            if ($file['type'] !== 'file') {
                continue;
            }

            $from = $file['filesystem'] . '://' . $file['path'];

            $pathWithoutUpperDirectory = $this->pathWithoutUpperDirectory(
                $file['path']
            );
            $to = 'zip://html/' . $pathWithoutUpperDirectory;

            $this->mountManager->copy($from, $to);
        }

        // Need to close the archive in order to actually save it.
        $zipArchive->getArchive()->close();
    }

    protected function pathWithoutUpperDirectory($file)
    {
        $pos = strpos($file, '/');

        if (false !== $pos) {
            return substr($file, $pos);
        }
    }
}

III-238: Fix Use FlySystem zip adapter instead of Zippy to generate the zip file


<?php

declare(strict_types=1);

namespace Rinvex\Tags\Console\Commands;

use Illuminate\Console\Command;

class RollbackCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rinvex:rollback:tags {--force : Force the operation to run when in production.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback Rinvex Tags Tables.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        if (file_exists($path = 'database/migrations/rinvex/laravel-tags')) {
            $this->call('migrate:reset', [
                '--step' => true,
                '--path' => $path,
                '--force' => $this->option('force'),
            ]);
        } else {
            $this->warn('No migrations found! Consider publish them first: <fg=green>php artisan rinvex:publish:tags</>');
        }

        $this->line('');
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Tags\Console\Commands;

use Illuminate\Console\Command;

class RollbackCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rinvex:rollback:tags {--force : Force the operation to run when in production.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback Rinvex Tags Tables.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        if (file_exists($path = 'database/migrations/rinvex/laravel-tags')) {
            $this->call('migrate:reset', [
                '--path' => $path,
                '--force' => $this->option('force'),
            ]);
        } else {
            $this->warn('No migrations found! Consider publish them first: <fg=green>php artisan rinvex:publish:tags</>');
        }

        $this->line('');
    }
}

Fix `migrate:reset` args as it doesn't accept --step


<?php namespace App\Http\Controllers;

use App\Genre;

class GenreController extends Controller {

    public function index()
    {
        // Only include certain information
        $include = ['id', 'parent_id', 'name'];

        $genres = Genre::root()->getDescendantsAndSelf($include)->toHierarchy();

        $genres = $this->cleanup($genres->toArray());

        return $genres[1];
    }

    /**
     * Recursively renames `name` to `text` and `children` to `nodes`
     *
     * @param array $array
     *
     * @return array
     */
    private function cleanup(array $array)
    {
        foreach($array as &$value)
        {
            $value['text'] = $value['name'];
            $value['nodes'] = $value['children'];
            unset($value['name']);
            unset($value['children']);

            if (empty($value['nodes']))
            {
                unset($value['nodes']);
            }
            else
            {
                $value['nodes'] = $this->cleanup($value['nodes']);
            }
        }

        return $array;
    }

}

<?php namespace App\Http\Controllers;

use App\Genre;

class GenreController extends Controller {

    public function index()
    {
        // Only include certain information
        $include = ['id', 'parent_id', 'name'];

        $genres = Genre::root()->getDescendantsAndSelf($include)->toHierarchy();

        $genres = $this->cleanup($genres->toArray());

        return $genres[1];
    }

    /**
     * Recursively renames `name` to `text` and `children` to `nodes`
     *
     * @param array $array
     *
     * @return array
     */
    private function cleanup(array $array)
    {
        foreach($array as &$value)
        {
            $value['text'] = $value['name'];
            $value['nodes'] = $value['children'];

            unset($value['name']);
            unset($value['children']);
            unset($value['id']);
            unset($value['parent_id']);

            if (empty($value['nodes']))
            {
                unset($value['nodes']);
            }
            else
            {
                $value['nodes'] = $this->cleanup($value['nodes']);
            }
        }

        return $array;
    }

}

Hide more fields in JSON genre response

Hide more fields in JSON genre response


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require(APPPATH.'libraries/REST_Controller.php');

class Users extends REST_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('users_model');
    }

    public function login_post()
    {
        $request = json_decode(file_get_contents('php://input'));
        $email = $request->email;
        $password = $request->password;

        if ($email == NULL || $password == NULL) $this->response(NULL, REST_Controller::HTTP_UNAUTHORIZED);
        else {
            $results = $this->users_model->get_users($email);
            if ( count($results) == 0 ) $this->response(NULL, REST_Controller::HTTP_NOT_FOUND);
            else {
                if ( $results[0]->Email == $email && $this->bcrypt->check_password($password, $results[0]->Password) ) {
                    $this->response($this->users_model->get_users_session($email), REST_Controller::HTTP_OK);
                } else {
                    $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST);
                }
            }
        }
    }

}

/* End of file Users.php */
/* Location: ./application/controllers/api/v1/Users.php */

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require(APPPATH.'libraries/REST_Controller.php');

class Users extends REST_Controller {

    public function __construct()
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        parent::__construct();
        $this->load->model('users_model');
    }

    public function login_post()
    {
        $request = json_decode(file_get_contents('php://input'));
        $email = $request->email;
        $password = $request->password;

        if ($email == NULL || $password == NULL) $this->response(NULL, REST_Controller::HTTP_UNAUTHORIZED);
        else {
            $results = $this->users_model->get_users($email);
            if ( count($results) == 0 ) $this->response(NULL, REST_Controller::HTTP_NOT_FOUND);
            else {
                if ( $results[0]->Email == $email && $this->bcrypt->check_password($password, $results[0]->Password) ) {
                    $this->response($this->users_model->get_users_session($email), REST_Controller::HTTP_OK);
                } else {
                    $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST);
                }
            }
        }
    }

}

/* End of file Users.php */
/* Location: ./application/controllers/api/v1/Users.php */

Add CORS filter to constructor

Add CORS filter to constructor


@extends('layout')

@section('title', __('general.earnings'))

@section('body')

{{ __('general.earnings') }}

            @if (count($earnings))
                @foreach ($earnings as $earning)

{{ $earning->description }}

{{ $earning->formatted_happened_on }}

€ {{ $earning->formatted_amount }}

                @endforeach
            @else

You don't have any earnings

            @endif

@endsection

@extends('layout')

@section('title', __('general.earnings'))

@section('body')

{{ __('general.earnings') }}

            @if (count($earnings))
                @foreach ($earnings as $earning)

{{ $earning->description }}

{{ $earning->formatted_happened_on }}

€ {{ $earning->formatted_amount }}

                            <form method="POST" action="/earnings/{{ $earning->id }}">
                                {{ method_field('DELETE') }}
                                {{ csrf_field() }}
                                <button class="button link">

                                </button>
                            </form>

                @endforeach
            @else

You don't have any earnings

            @endif

@endsection

Add ability to delete earnings from earnings' index view


<?php namespace Anomaly\UsersModule\Http\Controller;

use Anomaly\Streams\Platform\Http\Controller\PublicController;
use Anomaly\UsersModule\User\UserAuthenticator;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Translation\Translator;

/**
 * Class LoginController
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 */
class LoginController extends PublicController
{

    /**
     * Return the login form.
     *
     * @param  Translator $translator
     * @return \Illuminate\Http\RedirectResponse
     */
    public function login(Translator $translator)
    {
        $this->template->set(
            'meta_title',
            $translator->trans('anomaly.module.users::breadcrumb.login')
        );

        return $this->view->make('anomaly.module.users::login');
    }

    /**
     * Logout the active user.
     *
     * @param  UserAuthenticator $authenticator
     * @param  Guard             $auth
     * @return \Illuminate\Http\RedirectResponse
     */
    public function logout(UserAuthenticator $authenticator, Guard $auth)
    {
        if (!$auth->guest()) {
            $authenticator->logout();
        }

        $this->messages->success($this->request->get('message', 'anomaly.module.users::message.logged_out'));

        return $this->response->redirectTo($this->request->get('redirect', '/'));
    }
}

<?php namespace Anomaly\UsersModule\Http\Controller;

use Anomaly\Streams\Platform\Http\Controller\PublicController;
use Anomaly\Streams\Platform\Routing\UrlGenerator;
use Anomaly\UsersModule\User\UserAuthenticator;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Translation\Translator;

/**
 * Class LoginController
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 */
class LoginController extends PublicController
{

    /**
     * Return the login form.
     *
     * @param  Translator $translator
     * @return \Illuminate\Http\RedirectResponse
     */
    public function login(Translator $translator)
    {
        $this->template->set(
            'meta_title',
            $translator->trans('anomaly.module.users::breadcrumb.login')
        );

        return $this->view->make('anomaly.module.users::login');
    }

    /**
     * Logout the active user.
     *
     * @param  UserAuthenticator $authenticator
     * @param  Guard             $auth
     * @return \Illuminate\Http\RedirectResponse
     */
    public function logout(UserAuthenticator $authenticator, Guard $auth, UrlGenerator $url)
    {
        if (!$auth->guest()) {
            $authenticator->logout();
        }

        $this->messages->success($this->request->get('message', 'anomaly.module.users::message.logged_out'));

        return $this->response->redirectTo($this->url->to($this->request->get('redirect', '/')));
    }
}

Fix issue where logout redirects to non-locale URI


<?php
namespace PharIo\Phive;

use PharIo\Phive\Cli\GeneralContext;

class InstallContext extends GeneralContext {

    protected function getKnownOptions() {
        return [
            'target'    => 't',
            'copy'      => 'c',
            'global'    => 'g',
            'temporary' => false
        ];
    }

    public function requiresValue($option) {
        return $option === 'target';
    }

}

<?php
namespace PharIo\Phive;

use PharIo\Phive\Cli\GeneralContext;

class InstallContext extends GeneralContext {

    protected function getKnownOptions() {
        return [
            'target'    => 't',
            'copy'      => 'c',
            'global'    => 'g',
            'temporary' => false
        ];
    }

    protected function getConflictingOptions() {
        return [
            ['global' => 'temporary'],
            ['global' => 'target']
        ];
    }

    public function requiresValue($option) {
        return $option === 'target';
    }

}

Make install options temporary and target conflict with global switch

This fixes #63


<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="api-base-url" content="{{ url('/api') }}">
    <meta name="api-token" content="{{ Auth::user()->api_token }}">

    <title>@yield('title') | {{ config('app.name') }}</title>

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('css/open-iconic-bootstrap.css') }}" rel="stylesheet">
    <link href="{{ asset('css/tempusdominus-bootstrap-4.css') }}" rel="stylesheet">
    <link href="{{ asset('css/font-awesome.css') }}" rel="stylesheet">
</head>
<body>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}"></script>

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="api-base-url" content="{{ url('/api') }}">
    @if(Auth::user())
        <meta name="api-token" content="{{ Auth::user()->api_token }}">
    @endif

    <title>@yield('title') | {{ config('app.name') }}</title>

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('css/open-iconic-bootstrap.css') }}" rel="stylesheet">
    <link href="{{ asset('css/tempusdominus-bootstrap-4.css') }}" rel="stylesheet">
    <link href="{{ asset('css/font-awesome.css') }}" rel="stylesheet">
</head>
<body>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}"></script>

Fix undefined property when no user logged in


<?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\Process;

/**
 * An executable finder specifically designed for the PHP executable.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class PhpExecutableFinder
{
    private $executableFinder;

    public function __construct()
    {
        $this->executableFinder = new ExecutableFinder();
    }

    /**
     * Finds The PHP executable.
     *
     * @return string|false The PHP executable path or false if it cannot be found
     */
    public function find()
    {
        // PHP_BINARY return the current sapi executable
        if (defined('PHP_BINARY') && PHP_BINARY && ('cli' === PHP_SAPI)) {
            return PHP_BINARY;
        }

        if ($php = getenv('PHP_PATH')) {
            if (!is_executable($php)) {
                return false;
            }

            return $php;
        }

        if ($php = getenv('PHP_PEAR_PHP_BIN')) {
            if (is_executable($php)) {
                return $php;
            }
        }

        $dirs = array(PHP_BINDIR);

        return $this->executableFinder->find('php', false, $dirs);
    }
}

<?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\Process;

/**
 * An executable finder specifically designed for the PHP executable.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class PhpExecutableFinder
{
    private $executableFinder;

    public function __construct()
    {
        $this->executableFinder = new ExecutableFinder();
    }

    /**
     * Finds The PHP executable.
     *
     * @return string|false The PHP executable path or false if it cannot be found
     */
    public function find()
    {
        // PHP_BINARY return the current sapi executable
        if (defined('PHP_BINARY') && PHP_BINARY && ('cli' === PHP_SAPI)) {
            return PHP_BINARY;
        }

        if ($php = getenv('PHP_PATH')) {
            if (!is_executable($php)) {
                return false;
            }

            return $php;
        }

        if ($php = getenv('PHP_PEAR_PHP_BIN')) {
            if (is_executable($php)) {
                return $php;
            }
        }

        $dirs = array(PHP_BINDIR);
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $dirs[] = 'C:\xampp\php\\';
        }

        return $this->executableFinder->find('php', false, $dirs);
    }
}

[Process] Add default xampp path to the list of possible paths to check


<?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\Bridge\Twig\Extension;

use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * SecurityExtension exposes security context features.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
final class SecurityExtension extends AbstractExtension
{
    private $securityChecker;

    public function __construct(AuthorizationCheckerInterface $securityChecker = null)
    {
        $this->securityChecker = $securityChecker;
    }

    public function isGranted($role, object $object = null, string $field = null): bool
    {
        if (null === $this->securityChecker) {
            return false;
        }

        if (null !== $field) {
            $object = new FieldVote($object, $field);
        }

        try {
            return $this->securityChecker->isGranted($role, $object);
        } catch (AuthenticationCredentialsNotFoundException $e) {
            return false;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions(): array
    {
        return [
            new TwigFunction('is_granted', [$this, 'isGranted']),
        ];
    }
}

<?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\Bridge\Twig\Extension;

use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * SecurityExtension exposes security context features.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
final class SecurityExtension extends AbstractExtension
{
    private $securityChecker;

    public function __construct(AuthorizationCheckerInterface $securityChecker = null)
    {
        $this->securityChecker = $securityChecker;
    }

    /**
     * @param mixed $object
     */
    public function isGranted($role, $object = null, string $field = null): bool
    {
        if (null === $this->securityChecker) {
            return false;
        }

        if (null !== $field) {
            $object = new FieldVote($object, $field);
        }

        try {
            return $this->securityChecker->isGranted($role, $object);
        } catch (AuthenticationCredentialsNotFoundException $e) {
            return false;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions(): array
    {
        return [
            new TwigFunction('is_granted', [$this, 'isGranted']),
        ];
    }
}

Fix invalid typehint for subject in is_granted Twig function


<?hh

class :test:contexts extends :x:element {
  protected function render(): XHPRoot {
    return

{$this->getContext('heading')}

        {$this->getChildren()}

;
  }
}

class XHPContextsTest extends PHPUnit_Framework_TestCase {
  public function testContextSimple(): void {
    $x = <test:contexts />;
    $x->setContext('heading', 'herp');
    $this->assertSame('

herp

', $x->toString());
  }

  public function testContextInsideHTMLElement(): void {
    $x =
<test:contexts />
;
    $x->setContext('heading', 'herp');
    $this->assertSame('

herp

', $x->toString());
  }

  public function testNestedContexts(): void {
    $x = <test:contexts><test:contexts /></test:contexts>;
    $x->setContext('heading', 'herp');
    $this->assertSame(
      '

herp

herp

',
      $x->toString(),
    );
  }
}

<?hh

class :test:contexts extends :x:element {
  protected function render(): XHPRoot {
    return

{(string) $this->getContext('heading')}

        {$this->getChildren()}

;
  }
}

class XHPContextsTest extends PHPUnit_Framework_TestCase {
  public function testContextSimple(): void {
    $x = <test:contexts />;
    $x->setContext('heading', 'herp');
    $this->assertSame('

herp

', $x->toString());
  }

  public function testContextInsideHTMLElement(): void {
    $x =
<test:contexts />
;
    $x->setContext('heading', 'herp');
    $this->assertSame('

herp

', $x->toString());
  }

  public function testNestedContexts(): void {
    $x = <test:contexts><test:contexts /></test:contexts>;
    $x->setContext('heading', 'herp');
    $this->assertSame(
      '

herp

herp

',
      $x->toString(),
    );
  }
}

Add string cast for 3.24 in tests

Add string cast for 3.24 in tests


<?php

/**
 * @namespace
 */
namespace ZendTest\Http;

use Zend\Http\Client;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    public function testClientRetrievesUppercaseHttpMethodFromRequestObject()
    {
        $client = new Client;
        $client->setMethod('post');
        $this->assertEquals(Client::ENC_URLENCODED, $client->getEncType());
    }

    public function testIfZeroValueCookiesCanBeSet()
    {
        try {
            $client = new Client();
            $client->addCookie("test", 0);
            $client->addCookie("test2", "0");
            $client->addCookie("test3", false);
        } catch (Exception\InvalidArgumentException $e) {
            $this->fail('Zero Values should be valid');
        }
        $this->assertTrue(true);
    }

    /**
    * @expectedException Zend\Http\Exception\InvalidArgumentException
    */
    public function testIfNullValueCookiesThrowsException()
    {
        $client = new Client();
        $client->addCookie("test", null);
    }
}

<?php

/**
 * @namespace
 */
namespace ZendTest\Http;

use Zend\Http\Client,
    Zend\Http\Header\SetCookie;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    public function testClientRetrievesUppercaseHttpMethodFromRequestObject()
    {
        $client = new Client;
        $client->setMethod('post');
        $this->assertEquals(Client::ENC_URLENCODED, $client->getEncType());
    }

    public function testIfZeroValueCookiesCanBeSet()
    {
        try {
            $client = new Client();
            $client->addCookie("test", 0);
            $client->addCookie("test2", "0");
            $client->addCookie("test3", false);
        } catch (Exception\InvalidArgumentException $e) {
            $this->fail('Zero Values should be valid');
        }
        $this->assertTrue(true);
    }

    /**
    * @expectedException Zend\Http\Exception\InvalidArgumentException
    */
    public function testIfNullValueCookiesThrowsException()
    {
        $client = new Client();
        $client->addCookie("test", null);
    }

    public function testIfCookieHeaderCanBeSet()
    {
        $header = new SetCookie('foo');

        $client = new Client();
        $client->addCookie($header);

        $cookies = $client->getCookies();
        $this->assertEquals(1, count($cookies));
        $this->assertEquals($header, $cookies['foo']);
    }

    public function testIfArrayOfHeadersCanBeSet()
    {
        $headers = array(
            new SetCookie('foo'),
            new SetCookie('bar')
        );

        $client = new Client();
        $client->addCookie($headers);

        $cookies = $client->getCookies();
        $this->assertEquals(2, count($cookies));
    }

    public function testIfArrayIteratorOfHeadersCanBeSet()
    {
        $headers = new \ArrayIterator(array(
            new SetCookie('foo'),
            new SetCookie('bar')
        ));

        $client = new Client();
        $client->addCookie($headers);

        $cookies = $client->getCookies();
        $this->assertEquals(2, count($cookies));
    }
}

Add tests for setting cookies with SetCookie header


<?php declare(strict_types=1);

if (
	extension_loaded( 'xdebug' )
	&& version_compare( '2.6.0', phpversion( 'xdebug' ), '<=' )
)
{
	/** @noinspection PhpUndefinedFunctionInspection */
	/** @noinspection PhpUndefinedConstantInspection */
	xdebug_set_filter(
		XDEBUG_FILTER_CODE_COVERAGE,
		XDEBUG_PATH_WHITELIST,
		[dirname( __DIR__ ) . '/src']
	);
}

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

<?php declare(strict_types=1);

if (
	extension_loaded( 'xdebug' )
	&& version_compare( '2.6.0', phpversion( 'xdebug' ), '<=' )
)
{
	/** @noinspection PhpUndefinedFunctionInspection */
	/** @noinspection PhpUndefinedConstantInspection */
	xdebug_set_filter(
		XDEBUG_FILTER_CODE_COVERAGE,
		XDEBUG_PATH_WHITELIST,
		[dirname( __DIR__ ) . '/src']
	);
}

date_default_timezone_set( 'UTC' );

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

Fix timezone for CI build

Fix timezone for CI build


<?php
/**
 * @author Joas Schilling <nickvergessen@owncloud.com>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

if (!defined('PHPUNIT_RUN')) {
	define('PHPUNIT_RUN', 1);
}

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

// Temp fix for the "Path not allowed: .../tests/lib/testcase.php"
\OC::$loader->addValidRoot(OC::$SERVERROOT . '/tests');

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

OC_Hook::clear();

<?php
/**
 * @author Joas Schilling <nickvergessen@owncloud.com>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

if (!defined('PHPUNIT_RUN')) {
	define('PHPUNIT_RUN', 1);
}

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

// Fix for "Autoload path not allowed: .../tests/lib/testcase.php"
\OC::$loader->addValidRoot(OC::$SERVERROOT . '/tests');

// Fix for "Autoload path not allowed: .../notifications/tests/testcase.php"
\OC_App::loadApp('notifications');

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

OC_Hook::clear();

Load the app in tests

Load the app in tests


<?php

  # Grab the Slack post variables
  $token = ($_POST['token'] === 'CxPDeOTKKscdX6nkTi3lOn1d' ? $_POST['token'] : false); # Replace with the token from your slash command config
  $channel = $_POST['channel_name'];
  $text = $_POST['text'];

  # Check pre-requisites for the script to run
  if(!$token){
   $msg = "This token doesn't match the slack command set up.";
   die($msg);
  }

  # Set up Frequently Asked Question (FAQ) array
  $faq = [
    "company information" => "Here is some information about our company...",
    "contact" => "Here are the contact details for our company...",
  ];

  # Check if the user's text has partially matched any of the FAQ keys
  foreach ($faq as $key => $value) {
    if (strpos(strtolower($key), strtolower($text)) !== false) {
      $results[] = "*" . $key . "*\n\n" . $value . "\n\n";
    }
  }

  # Output each of the matched key values
  if (sizeof($results) > 0) {
    foreach ($results as $key => $value) {
      echo $value;
    }
  # or inform the user nothing was matched
  } else if ((sizeof($results) === 0)) {
    echo "We couldn't find a part of the guide related to this search :disappointed:";
  }

<?php

  # Grab the Slack post variables
  $token = ($_POST['token'] === 'CxPDeOTKKscdX6nkTi3lOn1d' ? $_POST['token'] : false); # Replace with the token from your slash command config
  $channel = $_POST['channel_name'];
  $text = $_POST['text'];

  # Check pre-requisites for the script to run
  if(!$token){
   $msg = "This token doesn't match the slack command set up.";
   die($msg);
  }

  # Set up Frequently Asked Question (FAQ) array
  $faq = [
    "company information" => "Here is some information about our company...",
    "contact" => "Here are the contact details for our company...",
  ];

  # Check if the user's text has partially matched any of the FAQ keys
  foreach ($faq as $key => $value) {
    if (strpos(strtolower($key), strtolower($text)) !== false) {
      $results[] = "*" . $key . "*\n\n" . $value . "\n\n";
    }
  }

  # Output each of the matched key values
  if (sizeof($results) > 0) {
    foreach ($results as $key => $value) {
      echo $value;
    }
  # or inform the user nothing was matched
  } else if ((sizeof($results) === 0)) {
    echo "We couldn't find a part of the guide related to the search *" . $text . "* :disappointed:";
  }

Add search text to if not found message

Add search text to if not found message


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Transformers;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Yajra\DataTables\Transformers\DataArrayTransformer as BaseDataArrayTransformer;

class DataArrayTransformer extends BaseDataArrayTransformer
{
    /**
     * Transform row column by collection.
     *
     * @override to return headers as db column names, instead of their language titles.
     *
     * @param array                          $row
     * @param \Illuminate\Support\Collection $columns
     * @param string                         $type
     *
     * @return array
     */
    protected function buildColumnByCollection(array $row, Collection $columns, $type = 'printable')
    {
        $results = [];

        foreach ($columns->all() as $column) {
            if ($column[$type] && in_array($column['name'], request()->get('visible_columns', []))) {
                $title = $column['name'];
                $data = Arr::get($row, $column['data']);

                if ($type === 'exportable') {
                    $title = $this->decodeContent($title);
                    $dataType = gettype($data);
                    $data = $this->decodeContent($data);
                    settype($data, $dataType);
                }

                $results[$title] = $data;
            }
        }

        return $results;
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Transformers;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Yajra\DataTables\Transformers\DataArrayTransformer as BaseDataArrayTransformer;

class DataArrayTransformer extends BaseDataArrayTransformer
{
    /**
     * Transform row column by collection.
     *
     * @override to return headers as db column names, instead of their language titles.
     *
     * @param array                          $row
     * @param \Illuminate\Support\Collection $columns
     * @param string                         $type
     *
     * @return array
     */
    protected function buildColumnByCollection(array $row, Collection $columns, $type = 'printable')
    {
        $results = [];
        $visibleCOlumns = request()->get('visible_columnss', []);

        foreach ($columns->all() as $column) {
            if ($column[$type] && (! $visibleCOlumns || in_array($column['name'], $visibleCOlumns))) {
                $title = $column['name'];
                $data = Arr::get($row, $column['data']);

                if ($type === 'exportable') {
                    $title = $this->decodeContent($title);
                    $dataType = gettype($data);
                    $data = $this->decodeContent($data);
                    settype($data, $dataType);
                }

                $results[$title] = $data;
            }
        }

        return $results;
    }
}

Fix datatables export to export all coumns if no visible columns requested


<?php
/* Staging */
define('DB_NAME', getenv('DB_NAME'));
define('DB_USER', getenv('DB_USER'));
define('DB_PASSWORD', getenv('DB_PASSWORD'));
define('DB_HOST', getenv('DB_HOST') ? getenv('DB_HOST') : 'localhost');

define('WP_HOME', getenv('WP_HOME'));
define('WP_SITEURL', getenv('WP_SITEURL'));

ini_set('display_errors', 0);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', false);
define('DISALLOW_FILE_MODS', true); // this disables all file modifications including updates and update notifications

<?php
/* Staging */
define('DB_NAME', getenv('DB_NAME'));
define('DB_USER', getenv('DB_USER'));
define('DB_PASSWORD', getenv('DB_PASSWORD'));
define('DB_HOST', getenv('DB_HOST') ? getenv('DB_HOST') : 'localhost');

define('WP_HOME', getenv('WP_HOME'));
define('WP_SITEURL', getenv('WP_SITEURL'));

ini_set('display_errors', 0);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', false);
define('DISALLOW_FILE_MODS', false); // this disables all file modifications including updates and update notifications

Allow file modifications on stage environment