<?php namespace Orchestra\Facile;

use Illuminate\Support\ServiceProvider;

class FacileServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var boolean
     */
    protected $defer = true;

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

            $env->template('default', function () use ($app) {
                return new Template\Base($app);
            });

            return $env;
        });
    }

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

<?php namespace Orchestra\Facile;

use Illuminate\Support\ServiceProvider;

class FacileServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var boolean
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('orchestra.facile', function ($app) {
            $env = new Environment($app);

            $env->template('default', function () use ($app) {
                return new Template\Base($app);
            });

            return $env;
        });
    }

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

Update service provider to use bindShared.

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


<?php

namespace Awesomite\ErrorDumper;

/**
 * @internal
 */
class SyntaxTest extends TestBase
{
    public function testSyntax()
    {
        $path = realpath(implode(DIRECTORY_SEPARATOR, array(__DIR__, '..', '..', '..', 'src')));
        $this->assertInternalType('string', $path);
        $directory = new \RecursiveDirectoryIterator($path);
        $iterator = new \RecursiveIteratorIterator($directory);
        $regex = new \RegexIterator($iterator, '/^.+\.php$/', \RecursiveRegexIterator::GET_MATCH);
        $counter = 0;
        foreach ($regex as $file) {
            $counter++;
            require_once $file[0];
        }
        $this->assertGreaterThan(0, $counter);
    }
}

<?php

namespace Awesomite\ErrorDumper;

/**
 * @internal
 */
class SyntaxTest extends TestBase
{
    public function testSyntax()
    {
        $path = realpath(implode(DIRECTORY_SEPARATOR, array(__DIR__, '..', '..', '..', 'src')));
        $this->assertInternalType('string', $path);

        $counter = 0;
        foreach ($this->getRecursiveFileIterator($path, '/^.+\.php$/') as $file) {
            $counter++;
            require_once $file[0];
        }
        $this->assertGreaterThan(0, $counter);
    }

    public function testTwigSyntax()
    {
        $path = realpath(implode(DIRECTORY_SEPARATOR, array(__DIR__, '..', '..', '..', 'templates')));
        $this->assertInternalType('string', $path);

        $loader = new \Twig_Loader_Filesystem($path);
        $twig = new \Twig_Environment($loader);
        $twig->addFilter(new \Twig_SimpleFilter('strpad', function () {}));
        $twig->addFunction(new \Twig_SimpleFunction('memoryUsage', function () {}));
        $twig->addFunction(new \Twig_SimpleFunction('exportDeclaredValue', function () {}));

        $counter = 0;
        foreach ($this->getRecursiveFileIterator($path, '/^.+\.twig$/') as $file) {
            $fileName = $file[0];

            $counter++;
            try {
                $twig->parse($twig->tokenize(file_get_contents($fileName)));
            } catch (\Twig_Error_Syntax $exception) {
                throw new \RuntimeException(
                    $exception->getMessage() . " in file {$fileName}:{$exception->getTemplateLine()}"
                );
            }
        }
        $this->assertGreaterThan(0, $counter);
    }

    private function getRecursiveFileIterator($path, $pattern)
    {
        $directory = new \RecursiveDirectoryIterator($path);
        $iterator = new \RecursiveIteratorIterator($directory);

        return new \RegexIterator($iterator, $pattern, \RecursiveRegexIterator::GET_MATCH);
    }
}

Check twig syntax in phpunit

Check twig syntax in phpunit


<?php
class Model_Admin_Setting_Index extends ypModel {
	public function updateSetting($data) {
		if (!is_array($data)) {
			return FALSE;
		}

		foreach ($data as $setting_key => $setting_value) {
			$this->Setting->set($setting_key, $setting_value);
		}

		return TRUE;
	}
}

<?php
class Model_Admin_Setting_Index extends ypModel {
	public function updateSetting($data) {
		if (!is_array($data)) {die('here');
			return FALSE;
		}

		foreach ($data as $setting_key => $setting_value) {
			$this->Setting->set($setting_key, $setting_value);
		}

		return TRUE;
	}
}

Fix error caching /setting/site model

Fix error caching /setting/site model


<?php

namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;

use ForkCMS\Bundle\InstallerBundle\Entity\InstallationData;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

/**
 * Base class to validate and save data from the installer form
 */
abstract class InstallerHandler
{
    /**
     * @param Form $form
     * @param Request $request
     *
     * @return bool
     */
    final public function process(Form $form, Request $request): bool
    {
        if (!$request->isMethod('POST')) {
            return false;
        }

        $form->handleRequest($request);

        if ($form->isValid()) {
            $request->getSession()->set('installation_data', $this->processInstallationData($form->getData()));

            return true;
        }

        return false;
    }

    /**
     * @param InstallationData $installationData
     *
     * @return InstallationData
     */
    abstract public function processInstallationData(InstallationData $installationData): InstallationData;
}

<?php

namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;

use ForkCMS\Bundle\InstallerBundle\Entity\InstallationData;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

/**
 * Base class to validate and save data from the installer form
 */
abstract class InstallerHandler
{
    /**
     * @param Form $form
     * @param Request $request
     *
     * @return bool
     */
    final public function process(Form $form, Request $request): bool
    {
        if (!$request->isMethod('POST')) {
            return false;
        }

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $request->getSession()->set('installation_data', $this->processInstallationData($form->getData()));

            return true;
        }

        return false;
    }

    /**
     * @param InstallationData $installationData
     *
     * @return InstallationData
     */
    abstract public function processInstallationData(InstallationData $installationData): InstallationData;
}

Check if form is submitted first

Check if form is submitted first


<?php

$template->assign('PageTopic','Change Log');

$db2 = new SmrMySqlDatabase();

$db->query('SELECT *
			FROM version
			WHERE version_id <= ' . $var['version_id'] . '
			ORDER BY version_id DESC');
while ($db->nextRecord()) {

	$version_id = $db->getField('version_id');
	$version = $db->getField('major_version') . '.' . $db->getField('minor_version') . '.' . $db->getField('patch_level');
	$went_live = $db->getField('went_live');

	// get human readable format for date
	if ($went_live > 0)
		$went_live = date(DATE_FULL_SHORT, $went_live);
	else
		$went_live = 'never';

	$PHP_OUTPUT.=(''.$version.' ('.$went_live.'):');

	$PHP_OUTPUT.=('
');

	$db2->query('SELECT *
				FROM changelog
				WHERE version_id = '.$version_id.'
				ORDER BY changelog_id');
	while ($db2->nextRecord())
		$PHP_OUTPUT.=('
' . stripslashes($db2->getField('change_title')) . '
' . stripslashes($db2->getField('change_message')) . '
');

	$PHP_OUTPUT.=('
');

}

?>

Add a line break between each version in changelog.


getFluidLayout() }}">

        @include ('partials.notification')

          @if ($contact->has_avatar == 'true')
            getAvatarURL(110) }}" width="87">
          @else
            @if (count($contact->getInitials()) == 1)

getAvatarColor() }};">
              {{ $contact->getInitials() }}

            @else

getAvatarColor() }};">
              {{ $contact->getInitials() }}

            @endif
          @endif

            {{ $contact->getCompleteName() }}

            {{-- Last called information --}}

              @if (is_null($contact->getLastCalled(Auth::user()->timezone)))
                {{ trans('people.last_called_empty') }}
              @else
                {{ trans('people.last_called', ['date' => $contact->getLastCalled(Auth::user()->timezone)]) }}
              @endif

            {{-- Last activity information --}}

              @if (is_null($contact->getLastActivityDate(Auth::user()->timezone)))
                {{ trans('people.last_activity_date_empty') }}
              @else
                {{ trans('people.last_activity_date', ['date' => $contact->getLastActivityDate(Auth::user()->timezone)]) }}
              @endif

getFluidLayout() }}">

        @include ('partials.notification')

          @if ($contact->has_avatar == 'true')
            getAvatarURL(110) }}" width="87">
          @else
            @if (count($contact->getInitials()) == 1)

getAvatarColor() }};">
              {{ $contact->getInitials() }}

            @else

getAvatarColor() }};">
              {{ $contact->getInitials() }}

            @endif
          @endif

            {{ $contact->getCompleteName() }}

            {{-- Last activity information --}}

              @if (is_null($contact->getLastActivityDate(Auth::user()->timezone)))
                {{ trans('people.last_activity_date_empty') }}
              @else
                {{ trans('people.last_activity_date', ['date' => $contact->getLastActivityDate(Auth::user()->timezone)]) }}
              @endif

Remove last called information from the profile page


<?php

namespace Niku\Cms;

use Illuminate\Support\ServiceProvider;

class CmsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // Register migrations
        $this->loadMigrationsFrom(__DIR__.'/database/migrations');

        // Register translations
        $this->loadTranslationsFrom(__DIR__.'/translations', 'niku-cms');

        // Register config
        $this->publishes([
            __DIR__.'/../config/'. 'niku-cms.php' => config_path('niku-cms.php'),
        ], 'niku-cms');

        // Register Vue components
        $this->publishes([
            __DIR__.'/../resources/assets/js/' => base_path('resources/assets/js/vendor/niku-cms'),
            __DIR__.'/../resources/assets/css/' => base_path('resources/assets/sass/vendor/niku-cms'),
        ], 'niku-cms');

        // Register views
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'niku-cms');

        // Register copying views
        $this->publishes([
            __DIR__.'/../resources/views' => resource_path('views/vendor/niku-cms'),
        ], 'niku-cms');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        include __DIR__.'/routes.php';
    }
}

<?php

namespace Niku\Cms;

use Illuminate\Support\ServiceProvider;

class CmsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // Register migrations
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');

        // Register translations
        $this->loadTranslationsFrom(__DIR__.'/../translations', 'niku-cms');

        // Register config
        $this->publishes([
            __DIR__.'/../config/'. 'niku-cms.php' => config_path('niku-cms.php'),
        ], 'niku-cms');

        // Register Vue components
        $this->publishes([
            __DIR__.'/../resources/assets/js/' => base_path('resources/assets/js/vendor/niku-cms'),
            __DIR__.'/../resources/assets/css/' => base_path('resources/assets/sass/vendor/niku-cms'),
        ], 'niku-cms');

        // Register views
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'niku-cms');

        // Register copying views
        $this->publishes([
            __DIR__.'/../resources/views' => resource_path('views/vendor/niku-cms'),
        ], 'niku-cms');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        include __DIR__.'/routes.php';
    }
}

Correct paths to database and translations


<?php

/**
 * Copyright (C) 2016 Stratadox
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Stratadox
 * @package Stratadox\Di
 */

namespace Stratadox\Di;

use Closure;

interface ContainerInterface
{
    public function set($name, Closure $factory);
    public function get($name, $type = '');
    public function has($name);
    public function forget($name);
}

<?php

/**
 * Copyright (C) 2016 Stratadox
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Stratadox
 * @package Stratadox\Di
 */

namespace Stratadox\Di;

use Closure;

interface ContainerInterface
{
    public function set($name, Closure $factory, $cache = false);
    public function get($name, $type = '');
    public function has($name);
    public function forget($name);
}

Allow the cache to be turned off

Allow the cache to be turned off


<?php

// app/config/security.php
$container->loadFromExtension('security', [
        'encoders'       => [
            'Tm\UserBundle\Entity\Utilisateur' => 'sha512',
        ],

        'role_hierarchy' => [
            'ROLE_ADMIN'       => 'ROLE_UTILISATEUR',
            'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'],
        ],

        'providers'      => [
            'main' => [
                'id' => 'fos_user.user_provider.username',
            ],
        ],

        'firewalls'      => [
            'dev'  => [
                'pattern'  => '^/(_(profiler|wdt)|css|images|js)/',
                'security' => false,
            ],
            'main' => [
                'pattern'     => '^/',
                'anonymous'   => true,
                'provider'    => 'main',
                'form_login'  => [
                    'login_path' => 'fos_user_security_login',
                    'check_path' => 'fos_user_security_check',
                ],
                'logout'      => [
                    'path'   => 'fos_user_security_logout',
                    'target' => '/',
                ],
                'remember_me' => [
                    'key' => '%secret%',
                ],
            ],
        ],

        'access_control' => [//        array('path' => '^/admin', 'role' => 'ROLE_ADMIN'),
        ]
    ]
);

<?php

// app/config/security.php
$container->loadFromExtension('security', [
        'encoders'       => [
            'Tm\UserBundle\Entity\Utilisateur' => 'sha512',
        ],

        'role_hierarchy' => [
            'ROLE_ADMIN'       => 'ROLE_UTILISATEUR',
            'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'],
        ],

        'providers'      => [
            'main' => [
                'id' => 'fos_user.user_provider.username',
            ],
        ],

        'firewalls'      => [
            'dev'  => [
                'pattern'  => '^/(_(profiler|wdt)|css|images|js)/',
                'security' => false,
            ],
            'main' => [
                'pattern'     => '^/',
                'anonymous'   => true,
                'provider'    => 'main',
                'form_login'  => [
                    'login_path' => 'fos_user_security_login',
                    'check_path' => 'fos_user_security_check',
                ],
                'logout'      => [
                    'path'   => 'fos_user_security_logout',
                    'target' => '/',
                ],
                'remember_me' => [
                    'key' => getenv('SECRET_KEY'),
                ],
            ],
        ],

        'access_control' => [//        array('path' => '^/admin', 'role' => 'ROLE_ADMIN'),
        ]
    ]
);

Test getenv au lieu d'une référence vers un paramètres


<?php

namespace Oro\Bundle\PlatformBundle\Tests\Unit\DependencyInjection;

use Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\LazyServicesCompilerPass;

class LazyServicesCompilerPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcessLazyServicesTag()
    {
        $expectedTags = array();

        $compiler = new LazyServicesCompilerPass();
        $this->assertAttributeEquals($expectedTags, 'lazyServicesTags', $compiler);

        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
        $containerIteration = 0;

        foreach ($expectedTags as $tagName) {
            $testTags = array(
                'first.' . $tagName => array(),
                'second.' . $tagName => array(),
            );
            $container->expects($this->at(++$containerIteration))->method('findTaggedServiceIds')->with($tagName)
                ->will($this->returnValue($testTags));

            foreach (array_keys($testTags) as $serviceId) {
                $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
                $definition->expects($this->once())->method('setLazy')->with(true);

                $container->expects($this->at(++$containerIteration))->method('hasDefinition')->with($serviceId)
                    ->will($this->returnValue(true));
                $container->expects($this->at(++$containerIteration))->method('getDefinition')->with($serviceId)
                    ->will($this->returnValue($definition));
            }
        }

        $compiler->process($container);
    }
}

<?php

namespace Oro\Bundle\PlatformBundle\Tests\Unit\DependencyInjection;

use Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\LazyServicesCompilerPass;

class LazyServicesCompilerPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcessLazyServicesTag()
    {
        $expectedTags = array(
            'doctrine.event_listener'
        );

        $compiler = new LazyServicesCompilerPass();
        $this->assertAttributeEquals($expectedTags, 'lazyServicesTags', $compiler);

        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
        $containerIteration = 0;

        foreach ($expectedTags as $tagName) {
            $testTags = array(
                'first.' . $tagName => array(),
                'second.' . $tagName => array(),
            );
            $container->expects($this->at(++$containerIteration))->method('findTaggedServiceIds')->with($tagName)
                ->will($this->returnValue($testTags));

            foreach (array_keys($testTags) as $serviceId) {
                $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
                $definition->expects($this->once())->method('setLazy')->with(true);

                $container->expects($this->at(++$containerIteration))->method('hasDefinition')->with($serviceId)
                    ->will($this->returnValue(true));
                $container->expects($this->at(++$containerIteration))->method('getDefinition')->with($serviceId)
                    ->will($this->returnValue($definition));
            }
        }

        $compiler->process($container);
    }
}

BAP-4203: Convert doctrine subscribers to listeners, make all doctrine listeners lazy
 - fixed unit test


<?php

namespace React\Filesystem\Node;

interface NodeInterface extends GenericOperationInterface
{
    const DS = DIRECTORY_SEPARATOR;

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

    /**
     * @return NodeInterface|null
     */
    public function getParent();

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

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

    /**
     * @param NodeInterface $node
     * @return \React\Promise\PromiseInterface
     */
    //public function copy(NodeInterface $node);
}

<?php

namespace React\Filesystem\Node;

interface NodeInterface extends GenericOperationInterface
{
    const DS = DIRECTORY_SEPARATOR;

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

    /**
     * @return NodeInterface|null
     */
    public function getParent();

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

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

    /**
     * @param NodeInterface $node
     * @return \React\Promise\PromiseInterface
     */
    public function copy(NodeInterface $node);

    /**
     * @param NodeInterface $node
     * @return ObjectStream
     */
    public function copyStreaming(NodeInterface $node);
}

Copy and copyStreaming are now required node methods


<?php

namespace KVZ\Laravel\SwitchableMail;

use Illuminate\Mail\TransportManager;
use Illuminate\Support\Manager;
use Swift_Mailer;

class SwiftMailerManager extends Manager
{
    /**
     * The mail transport manager.
     *
     * @var \Illuminate\Mail\TransportManager
     */
    protected $transportManager;

    /**
     * Get the mail transport manager.
     *
     * @return \Illuminate\Mail\TransportManager
     */
    public function getTransportManager()
    {
        return $this->transportManager;
    }

    /**
     * Set the mail transport manager.
     *
     * @param  \Illuminate\Mail\TransportManager  $manager
     * @return $this
     */
    public function setTransportManager(TransportManager $manager)
    {
        $this->transportManager = $manager;

        return $this;
    }

    /**
     * Get a swift mailer instance.
     *
     * @param  string|null  $driver
     * @return \Swift_Mailer
     */
    public function mailer($driver = null)
    {
        return $this->driver($driver);
    }

    /**
     * Create a new swift mailer instance.
     *
     * @param  string  $driver
     * @return \Swift_Mailer
     */
    protected function createDriver($driver)
    {
        return new Swift_Mailer($this->transportManager->driver($driver));
    }

    /**
     * Get the default mail driver name.
     *
     * @return string
     */
    public function getDefaultDriver()
    {
        return $this->transportManager->getDefaultDriver();
    }
}

<?php

namespace KVZ\Laravel\SwitchableMail;

use Illuminate\Mail\TransportManager;
use Illuminate\Support\Manager;
use Swift_Mailer;

class SwiftMailerManager extends Manager
{
    /**
     * The mail transport manager.
     *
     * @var \Illuminate\Mail\TransportManager
     */
    protected $transportManager;

    /**
     * Get the mail transport manager.
     *
     * @return \Illuminate\Mail\TransportManager
     */
    public function getTransportManager()
    {
        return $this->transportManager;
    }

    /**
     * Set the mail transport manager.
     *
     * @param  \Illuminate\Mail\TransportManager  $manager
     * @return $this
     */
    public function setTransportManager(TransportManager $manager)
    {
        $this->transportManager = $manager;

        return $this;
    }

    /**
     * Get a swift mailer instance.
     *
     * @param  string|null  $driver
     * @return \Swift_Mailer
     */
    public function mailer($driver = null)
    {
        return $this->driver($driver);
    }

    /**
     * Get all of the created swift mailer instances.
     *
     * @return array
     */
    public function getMailers()
    {
        return $this->drivers;
    }

    /**
     * Create a new swift mailer instance.
     *
     * @param  string  $driver
     * @return \Swift_Mailer
     */
    protected function createDriver($driver)
    {
        return new Swift_Mailer($this->transportManager->driver($driver));
    }

    /**
     * Get the default mail driver name.
     *
     * @return string
     */
    public function getDefaultDriver()
    {
        return $this->transportManager->getDefaultDriver();
    }
}

Add `getMailers` to get all of the created swift mailer instances


<?php

class CM_I18n_Phrase {

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

    /** @var $_variables string[] */
    protected $_variables;

    /**
     * @param string $phrase
     * @param string[] $variables
     */
    public function __construct($phrase, array $variables = []) {
        $this->_phrase = (string) $phrase;
        $this->_variables = $variables;
    }

    /**
     * @param CM_Frontend_Render $render
     * @return string
     */
    public function translate(CM_Frontend_Render $render) {
        return $render->getTranslation($this->_phrase, $this->_variables);
    }
}

<?php

class CM_I18n_Phrase {

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

    /** @var $_variables string[] */
    protected $_variables;

    /**
     * @param string $phrase
     * @param string[]|null $variables
     */
    public function __construct($phrase, array $variables = null) {
        $this->_phrase = (string) $phrase;
        $this->_variables = is_null($variables) ? [] : $variables;
    }

    /**
     * @param CM_Frontend_Render $render
     * @return string
     */
    public function translate(CM_Frontend_Render $render) {
        return $render->getTranslation($this->_phrase, $this->_variables);
    }
}

Change default type to null

Change default type to null


<?php

namespace common\models;

use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\SluggableBehavior;

/**
 * @property integer $id
 *
 * @property string $title
 * @property string $slug
 *
 * @property integer $created_at
 * @property integer $updated_at
 */
class Section extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            ['class' => SluggableBehavior::className(), 'attribute' => 'title'],
        ];
    }
}

<?php

namespace common\models;

use yii\db\ActiveRecord;
use yii\db\ActiveQuery;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\SluggableBehavior;

/**
 * @property integer $id
 *
 * @property string $title
 * @property string $slug
 *
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property integer $section_id
 * @property Section $parent
 * @property Section[] $children
 */
class Section extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            ['class' => SluggableBehavior::className(), 'attribute' => 'title'],
        ];
    }

    /**
     * @return ActiveQuery
     */
    public function getParent()
    {
        return $this->hasOne(Section::className(), ['id' => 'section_id']);
    }

    /**
     * @return ActiveQuery
     */
    public function getChildren()
    {
        return $this->hasMany(Section::className(), ['section_id' => 'id']);
    }
}

Add relations to section model.

Add relations to section model.


<?php

final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery {

  protected function newQueryFuture() {
    $drequest = $this->getRequest();
    $repository = $drequest->getRepository();

    $commit = $this->getAnchorCommit();

    $options = array(
      '-M',
      '-C',
      '--no-ext-diff',
      '--no-color',
      '--src-prefix=a/',
      '--dst-prefix=b/',
      '-U'.(int)$this->getLinesOfContext(),
    );

    $against = $this->getAgainstCommit();
    if ($against === null) {
      // Check if this is the root commit by seeing if it has parents, since
      // `git diff X^ X` does not work if "X" is the initial commit.
      list($parents) = $repository->execxLocalCommand(
        'log -n 1 %s --',
        '--format=%P',
        gitsprintf('%s', $commit));

      if (strlen(trim($parents))) {
        $against = $commit.'^';
      } else {
        $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT;
      }
    }

    $path = $drequest->getPath();
    if (!strlen($path)) {
      $path = '.';
    }

    return $repository->getLocalCommandFuture(
      'diff %Ls %s %s -- %s',
      $options,
      gitsprintf('%s', $against),
      gitsprintf('%s', $commit),
      $path);
  }

}

<?php

final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery {

  protected function newQueryFuture() {
    $drequest = $this->getRequest();
    $repository = $drequest->getRepository();

    $commit = $this->getAnchorCommit();

    $options = array(
      '-M',
      '-C',
      '--no-ext-diff',
      '--no-color',
      '--src-prefix=a/',
      '--dst-prefix=b/',
      '-U'.(int)$this->getLinesOfContext(),
    );

    $against = $this->getAgainstCommit();
    if ($against === null) {
      // Check if this is the root commit by seeing if it has parents, since
      // `git diff X^ X` does not work if "X" is the initial commit.
      list($parents) = $repository->execxLocalCommand(
        'log -n 1 %s %s --',
        '--format=%P',
        gitsprintf('%s', $commit));

      if (strlen(trim($parents))) {
        $against = $commit.'^';
      } else {
        $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT;
      }
    }

    $path = $drequest->getPath();
    if (!strlen($path)) {
      $path = '.';
    }

    return $repository->getLocalCommandFuture(
      'diff %Ls %s %s -- %s',
      $options,
      gitsprintf('%s', $against),
      gitsprintf('%s', $commit),
      $path);
  }

}

Correct a straggling CLI format string after ref selector changes

Summary: Ref T13589. This is missing a "%s" conversion.

Test Plan: Will view a commit with a diff.

Maniphest Tasks: T13589

Differential Revision: https://secure.phabricator.com/D21512


<?php

namespace App\Http\Controllers;

use App\FasetVisit;
use App\Notifications\GeneralInterestNotification;
use Carbon\Carbon;
use Notification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function sendNotification()
    {
        $hours = 0;
        FasetVisit::chunk(30, function ($chunk) use (&$hours) {
            $when = Carbon::now()->addHours($hours);
            Notification::send($chunk, (new GeneralInterestNotification())->delay($when));
            $hours++;
        });
        return response()->json(['status' => 'success']);
    }

    public function sendNotificationManual(Request $request)
    {
        if (!$request->has('emails')) {
            return response()->json(['status' => 'error', 'error' => "Missing parameter 'emails'"], 400);
        }

        $hours = 0;
        $emails = $request->input('emails');
        $chunks = array_chunk($emails, 30);
        foreach ($chunks as $chunk) {
            $when = Carbon::now()->addHours($hours);
            Notification::send($chunk, (new GeneralInterestNotification())->delay($when));
            $hours++;
        }
        return response()->json(['status' => 'success', 'count' => count($emails)]);
    }
}

<?php

namespace App\Http\Controllers;

use App\FasetVisit;
use App\Notifications\GeneralInterestNotification;
use Carbon\Carbon;
use Notification;
use Mail;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function sendNotification()
    {
        $hours = 0;
        FasetVisit::chunk(30, function ($chunk) use (&$hours) {
            $when = Carbon::now()->addHours($hours);
            Notification::send($chunk, (new GeneralInterestNotification())->delay($when));
            $hours++;
        });
        return response()->json(['status' => 'success']);
    }

    public function sendNotificationManual(Request $request)
    {
        if (!$request->has('emails')) {
            return response()->json(['status' => 'error', 'error' => "Missing parameter 'emails'"], 400);
        }

        $hours = 0;
        $emails = $request->input('emails');
        $chunks = array_chunk($emails, 30);
        foreach ($chunks as $chunk) {
            $when = Carbon::now()->addHours($hours);
            foreach ($chunk as $address) {
                Mail::to($address)->later($when, new GeneralInterestNotification());
            }
            $hours++;
        }
        return response()->json(['status' => 'success', 'count' => count($emails)]);
    }
}

Use Email facade instead of Notification since we aren't notifying a Notifiable, just some addresses


<?php
$themeManager = $this->getThemeManager();
$theme = $themeManager->getCurrentTheme();
$stylesheet = $themeManager->getUrlTheme($theme) . $theme->getErrorPageStylesheet();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <link href="<?php echo $stylesheet ?>" rel="stylesheet" type="text/css" />

<?php echo $this->getConfig()->get('hometitle') ?>

            <form action="" method="post">

                    <?php echo $this->t("main.code_request") ?>

                    <input type="password" name="key" id="key" style="width:10em;" />

                    <input type="submit" class="button" style="width:11em;" value="<?php echo $this->t("main.log_in") ?>" />

            </form>

<?php
$themeManager = $this->website->getThemeManager();
$theme = $themeManager->getCurrentTheme();
$stylesheet = $themeManager->getUrlTheme($theme) . $theme->getErrorPageStylesheet();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <link href="<?php echo $stylesheet ?>" rel="stylesheet" type="text/css" />

<?php echo $this->website->getConfig()->get('hometitle') ?>

            <form action="" method="post">

                    <?php echo $this->website->t("main.code_request") ?>

                    <input type="password" name="key" id="key" style="width:10em;" />

                    <input type="submit" class="button" style="width:11em;" value="<?php echo $this->website->t("main.log_in") ?>" />

            </form>

Fix page where site key is entered

Fix page where site key is entered


<?php
class Kwf_Trl_BuildFileMissingException extends Kwf_Exception
{
    public function __construct($message = 'trl build file does not exist')
    {
        parent::__construct($message);
    }

    public function getSettingsNonStaticTrlException()
    {
        $exceptionLocation = null;
        foreach ($this->getTrace() as $trace) {
            if (strpos($trace['file'], 'Kwf/Trl.php') === false
                && (
                    $trace['function'] == 'trlKwf' || $trace['function'] == 'trl'
                    || $trace['function'] == 'trlcKwf' || $trace['function'] == 'trlc'
                    || $trace['function'] == 'trlpKwf' || $trace['function'] == 'trlp'
                    || $trace['function'] == 'trlcpKwf' || $trace['function'] == 'trlcp'
                )
            ) {
                $exceptionLocation = $trace;
                break;
            }
        }
        if ($exceptionLocation) {
            $file = $exceptionLocation['file'];
            $line = $exceptionLocation['line'];
            return new Kwf_Exception("In getSettings-method only static version of trl is allowed $file:$line");
        }
        return false;
    }
}

<?php
class Kwf_Trl_BuildFileMissingException extends Kwf_Exception
{
    public function __construct($message = 'trl build file does not exist')
    {
        parent::__construct($message);
    }

    public function getSettingsNonStaticTrlException()
    {
        $exceptionLocation = null;
        foreach ($this->getTrace() as $trace) {
            if (isset($trace['file']) && strpos($trace['file'], 'Kwf/Trl.php') === false
                && (
                    $trace['function'] == 'trlKwf' || $trace['function'] == 'trl'
                    || $trace['function'] == 'trlcKwf' || $trace['function'] == 'trlc'
                    || $trace['function'] == 'trlpKwf' || $trace['function'] == 'trlp'
                    || $trace['function'] == 'trlcpKwf' || $trace['function'] == 'trlcp'
                )
            ) {
                $exceptionLocation = $trace;
                break;
            }
        }
        if ($exceptionLocation) {
            $file = $exceptionLocation['file'];
            $line = $exceptionLocation['line'];
            return new Kwf_Exception("In getSettings-method only static version of trl is allowed $file:$line");
        }
        return false;
    }
}

Check if file exists in array

Check if file exists in array


<?php
namespace GoalioForgotPassword;

use Zend\Loader\StandardAutoloader;
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\ModuleRouteListener;

class Module {

    public function getAutoloaderConfig() {
        return array(
            AutoloaderFactory::STANDARD_AUTOLOADER => array(
                StandardAutoloader::LOAD_NS => array(
                    __NAMESPACE__ => __DIR__,
                ),
            ),
        );
    }

    public function getConfig() {
        return include __DIR__ . '/../../config/module.config.php';
    }

    public function getModuleDependencies() {
        return array('ZfcUser', 'ZfcBase');
    }

    public function getServiceConfig() {
        return array(
            'invokables' => array(
                'goalioforgotpassword_password_service'            => 'GoalioForgotPassword\Service\Password',
            ),

            'factories' => array(
                'goalioforgotpassword_module_options'  => 'GoalioForgotPassword\Options\Service\ModuleOptionsFactory',
                'goalioforgotpassword_forgot_form'     => 'GoalioForgotPassword\Form\Service\ForgotFactory',
                'goalioforgotpassword_reset_form'      => 'GoalioForgotPassword\Form\Service\ResetFactory',
                'goalioforgotpassword_password_mapper' => 'GoalioForgotPassword\Mapper\Service\PasswordFactory',
            ),
        );
    }
}

<?php
namespace GoalioForgotPassword;

use Zend\Loader\StandardAutoloader;
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\ModuleRouteListener;

class Module {

    public function getAutoloaderConfig() {
        return array(
            AutoloaderFactory::STANDARD_AUTOLOADER => array(
                StandardAutoloader::LOAD_NS => array(
                    __NAMESPACE__ => __DIR__,
                ),
            ),
        );
    }

    public function getConfig() {
        return include __DIR__ . '/../../config/module.config.php';
    }

    public function getModuleDependencies() {
        return array('ZfcUser', 'ZfcBase');
    }

    public function getServiceConfig() {
        return array(
            'invokables' => array(

            ),

            'factories' => array(
                'goalioforgotpassword_module_options'  => 'GoalioForgotPassword\Options\Service\ModuleOptionsFactory',
                'goalioforgotpassword_forgot_form'     => 'GoalioForgotPassword\Form\Service\ForgotFactory',
                'goalioforgotpassword_reset_form'      => 'GoalioForgotPassword\Form\Service\ResetFactory',
                'goalioforgotpassword_password_mapper' => 'GoalioForgotPassword\Mapper\Service\PasswordFactory',
                'goalioforgotpassword_password_service'  => 'GoalioForgotPassword\Factory\Service\PasswordFactory',
            ),
        );
    }
}

Move password service to factories

Move password service to factories


<?php

namespace SearchApi\Builders;

use SearchApi\Builders\QueryBuilder;

/**
 * Class SolrQueryBuilder - Responsible for building a query string for SolrSearch.
 *
 * @method string build_query (SearchTerm[]|null $keywords, SearchApi\Models\SearchOptions|null)
 *   Build a query string from provided search terms and search options
 */
class SolrQueryBuilder implements QueryBuilder {
  function build( $keywords, $options = null ) {
    return null;
  }
}

<?php

namespace SearchApi\Builders;

use SearchApi\Builders\QueryBuilder;

/**
 * Class SolrQueryBuilder - Responsible for building a query string for SolrSearch
 */
class SolrQueryBuilder implements QueryBuilder {
  /**
   * Build a query string from provided search terms and search options
   */
  function build( $keywords, $options = null ) {
    return null;
  }
}

Fix documentation for query builder

Fix documentation for query builder


<?php

namespace Bolt\Database\Migration;

use Bolt\Application;

/**
 * Database records iport class
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Import extends AbstractMigration
{
    /** @var Bolt\Application */
    private $app;

    /**
     * Constructor.
     *
     * @param \Bolt\Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }
}

<?php

namespace Bolt\Database\Migration;

use Bolt\Application;
use Symfony\Component\Yaml\Parser;

/**
 * Database records iport class
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Import extends AbstractMigration
{
    /** @var Bolt\Application */
    private $app;

    /**
     * Constructor.
     *
     * @param \Bolt\Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Read a migration file.
     *
     * This function will determine what type based on extension.
     *
     * @param string $file
     *
     * @return array
     */
    protected function readMigrationFile($file)
    {
        $fileObj = new \SplFileInfo($file);
        $ext = $fileObj->getExtension();

        if (is_readable($file)) {
            if ($ext === 'yml' || $ext === 'yaml') {
                return $this->readYamlFile($file);
            } else {
                return $this->readJsonFile($file);
            }
        } else {
            $this->setError(true)->setErrorMessage("File '$file' not readable!");

            return false;
        }
    }

    /**
     * Read a YAML migration file.
     *
     * @param string $file
     *
     * @return array
     */
    private function readYamlFile($file, $output)
    {
        $parser = new Parser();

        try {
            return $parser->parse(file_get_contents($file) . "\n");
        } catch (ParseException $e) {
            $this->setError(true)->setErrorMessage("File '$file' has invalid YAML!");

            return false;
        }
    }

    /**
     * Read a JSON migration file.
     *
     * @param string $file
     *
     * @return array
     */
    private function readJsonFile($file)
    {
        $json = json_decode(file_get_contents($file), true);
        if ($json === false) {
            $this->setError(true)->setErrorMessage("File '$file' has invalid JSON!");
        }

        return $json;
    }
}

Add migration file read functionality

Add migration file read functionality


<?php

namespace Aztech\Layers\Elements;

use Aztech\Layers\Responses\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class JsonRenderingLayer
{
    private $callable;

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

    public function __invoke(Request $request = null)
    {
        if (! $request) {
            $request = Request::createFromGlobals();
        }

        $callable = $this->callable;

        try {
            $response = $callable($request);
        }
        catch (HttpException $exception) {
            $response = new JsonResponse($exception->getMessage(), $exception->getStatusCode());
        }

        if ($response instanceof Response) {
            return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse();
        }

        if (! $response) {
            $response = [];
        }

        return (new JsonResponse($response, 200))->getResponse();
    }
}

<?php

namespace Aztech\Layers\Elements;

use Aztech\Layers\Responses\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class JsonRenderingLayer
{
    private $callable;

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

    public function __invoke(Request $request = null)
    {
        if (! $request) {
            $request = Request::createFromGlobals();
        }

        $callable = $this->callable;

        try {
            $response = $callable($request);
        }
        catch (HttpException $exception) {
            $response = new JsonResponse([
                'success' => false,
                'message' => $exception->getMessage()
            ],
            $exception->getStatusCode());
        }

        if ($response instanceof Response) {
            return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse();
        }

        if (! $response) {
            $response = [];
        }

        return (new JsonResponse($response, 200))->getResponse();
    }
}

Return exception message in array data

Return exception message in array data


<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Logger;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

trait LoggerTrait
{

    /**
     * Logger instance
     *
     * @var AbstractLogger
     */
    private $logger = null;

    /*
     * (non-PHPdoc)
     * @see \Psr\Log\LoggerAwareInterface::setLogger()
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Initialize the logger instance
     */
    private function initLogger()
    {
        if (null === $this->logger) {
            $this->logger = new NullLogger();
        }
    }

    /**
     * Retrieve the logger instance
     *
     * @return \Generics\Logger\AbstractLogger
     */
    private function getLog()
    {
        $this->initLogger();

        return $this->logger;
    }
}

<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Logger;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

trait LoggerTrait
{

    /**
     * Logger instance
     *
     * @var \Psr\Log\LoggerInterface
     */
    private $logger = null;

    /*
     * (non-PHPdoc)
     * @see \Psr\Log\LoggerAwareInterface::setLogger()
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Initialize the logger instance
     */
    private function initLogger()
    {
        if (null === $this->logger) {
            $this->logger = new NullLogger();
        }
    }

    /**
     * Retrieve the logger instance
     *
     * @return \Psr\Log\LoggerInterface
     */
    private function getLog()
    {
        $this->initLogger();

        return $this->logger;
    }
}

Set correct type to member variable and return value


<?php

namespace Isolate\LazyObjects;

use Isolate\LazyObjects\Proxy\Definition;
use Isolate\LazyObjects\Proxy\Factory;
use Isolate\LazyObjects\Exception\RuntimeException;

class Wrapper
{
    /**
     * @var array|Definition[]
     */
    private $definitions;

    /**
     * @var Factory
     */
    private $factory;

    /**
     * @param Factory $factory
     * @param array $definitions
     */
    public function __construct(Factory $factory, array $definitions = [])
    {
        $this->definitions = $definitions;
        $this->factory = $factory;
    }

    /**
     * @param $object
     * @return bool
     */
    public function canWrap($object)
    {
        foreach ($this->definitions as $proxyDefinition) {
            if ($proxyDefinition->describeProxyFor($object)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param $object
     * @return WrappedObject
     * @throws RuntimeException
     */
    public function wrap($object)
    {
        foreach ($this->definitions as $proxyDefinition) {
            if ($proxyDefinition->describeProxyFor($object)) {
                return $this->factory->createProxy($object, $proxyDefinition);
            }
        }

        throw new RuntimeException("Can\"t wrap objects that does\"t fit any proxy definition.");
    }
}

<?php

namespace Isolate\LazyObjects;

use Isolate\LazyObjects\Exception\InvalidArgumentException;
use Isolate\LazyObjects\Proxy\Definition;
use Isolate\LazyObjects\Proxy\Factory;
use Isolate\LazyObjects\Exception\RuntimeException;

class Wrapper
{
    /**
     * @var array|Definition[]
     */
    private $definitions;

    /**
     * @var Factory
     */
    private $factory;

    /**
     * @param Factory $factory
     * @param array $definitions
     * @throws InvalidArgumentException
     */
    public function __construct(Factory $factory, $definitions = [])
    {
        $this->definitions = [];

        if (!is_array($definitions) && !$definitions instanceof \Traversable) {
            throw new InvalidArgumentException("Lazy objects definitions collection must be traversable.");
        }

        foreach ($definitions as $definition) {
            if (!$definition instanceof Definition) {
                throw new InvalidArgumentException("Lazy object definition must be an instance of Isolate\\LazyObjects\\Proxy\\Definition");
            }

            $this->definitions[] = $definition;
        }

        $this->factory = $factory;
    }

    /**
     * @param $object
     * @return bool
     */
    public function canWrap($object)
    {
        foreach ($this->definitions as $proxyDefinition) {
            if ($proxyDefinition->describeProxyFor($object)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param $object
     * @return WrappedObject
     * @throws RuntimeException
     */
    public function wrap($object)
    {
        foreach ($this->definitions as $proxyDefinition) {
            if ($proxyDefinition->describeProxyFor($object)) {
                return $this->factory->createProxy($object, $proxyDefinition);
            }
        }

        throw new RuntimeException("Can\"t wrap objects that does\"t fit any proxy definition.");
    }
}

Allow to pass lazy objects definitions into wrapper as traversable collection


<?php

/**
 * @license MIT
 * @copyright 2017 Tim Gunter
 */

namespace Kaecyra\AppCommon\Log\Tagged;

/**
 * Tagged log trait
 *
 * @author Tim Gunter <tim@vanillaforums.com>
 * @package app-common
 */
trait TaggedLogTrait {

    /**
     * Log tag
     * @var string|Callable
     */
    protected $logTag = null;

    /**
     * Log tagged message
     *
     * @param string $level
     * @param string $message
     * @param array $context
     */
    public function tLog(string $level, string $message, array $context) {
        $logtag = $this->getLogTag();
        if (is_array($message) || is_object($message)) {
            $message = print_r($message, true);
        }
        $this->log($level, "[{$logtag}] ".$message, $context);
    }

    /**
     * Get log tag
     *
     * @return string
     */
    protected function getLogTag() {
        return is_callable($this->logTag) ? $this->logtag() : $this->logTag;
    }

    /**
     * Set log tag
     *
     * @param string|Callable $logTag
     */
    public function setLogTag($logTag) {
        $this->logTag = $logTag;
    }

    /**
     * Set default logtag callback
     *
     *
     */
    public function setDefaultLogCallback() {
        $this->setLogTag(function(){
            return (new \ReflectionClass($this))->getShortName();
        });
    }

}

<?php

/**
 * @license MIT
 * @copyright 2017 Tim Gunter
 */

namespace Kaecyra\AppCommon\Log\Tagged;

/**
 * Tagged log trait
 *
 * @author Tim Gunter <tim@vanillaforums.com>
 * @package app-common
 */
trait TaggedLogTrait {

    /**
     * Log tag
     * @var string|Callable
     */
    protected $logTag = null;

    /**
     * Log tagged message
     *
     * @param string $level
     * @param string $message
     * @param array $context
     */
    public function tLog(string $level, string $message, array $context = []) {
        $logtag = $this->getLogTag();
        if (is_array($message) || is_object($message)) {
            $message = print_r($message, true);
        }
        $this->log($level, "[{$logtag}] ".$message, $context);
    }

    /**
     * Get log tag
     *
     * @return string
     */
    protected function getLogTag() {
        return is_callable($this->logTag) ? $this->logTag() : $this->logTag;
    }

    /**
     * Set log tag
     *
     * @param string|Callable $logTag
     */
    public function setLogTag($logTag) {
        $this->logTag = $logTag;
    }

    /**
     * Set default logtag callback
     *
     *
     */
    public function setDefaultLogCallback() {
        $this->setLogTag(function(){
            return (new \ReflectionClass($this))->getShortName();
        });
    }

}

Support no context with tLog

Support no context with tLog


<?php

namespace Omnipay\Eway;

use Omnipay\Common\AbstractGateway;

/**
 * eWAY Rapid 3.0 Gateway
 */
class RapidGateway extends AbstractGateway
{
    public function getName()
    {
        return 'eWAY Rapid 3.0';
    }

    public function getDefaultParameters()
    {
        return array(
            'apiKey' => '',
            'password' => '',
            'testMode' => false,
        );
    }

    public function getApiKey()
    {
        return $this->getParameter('apiKey');
    }

    public function setApiKey($value)
    {
        return $this->setParameter('apiKey', $value);
    }

    public function getPassword()
    {
        return $this->getParameter('password');
    }

    public function setPassword($value)
    {
        return $this->setParameter('password', $value);
    }

    public function purchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Eway\Message\RapidPurchaseRequest', $parameters);
    }

    public function completePurchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Eway\Message\RapidCompletePurchaseRequest', $parameters);
    }
}

<?php

namespace Omnipay\Eway;

use Omnipay\Common\AbstractGateway;

/**
 * eWAY Rapid 3.0 Gateway
 */
class RapidGateway extends AbstractGateway
{
    public $transparentRedirect = true;

    public function getName()
    {
        return 'eWAY Rapid 3.0';
    }

    public function getDefaultParameters()
    {
        return array(
            'apiKey' => '',
            'password' => '',
            'testMode' => false,
        );
    }

    public function getApiKey()
    {
        return $this->getParameter('apiKey');
    }

    public function setApiKey($value)
    {
        return $this->setParameter('apiKey', $value);
    }

    public function getPassword()
    {
        return $this->getParameter('password');
    }

    public function setPassword($value)
    {
        return $this->setParameter('password', $value);
    }

    public function purchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Eway\Message\RapidPurchaseRequest', $parameters);
    }

    public function completePurchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Eway\Message\RapidCompletePurchaseRequest', $parameters);
    }
}

Mark gateway as transparent redirect

Mark gateway as transparent redirect


Add cache prefix to config

Add cache prefix to config


<?php

namespace PHPOrchestra\ModelBundle\Validator\Constraints;

use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ODM\MongoDB\DocumentManager;
use PHPOrchestra\ModelBundle\Model\StatusableInterface;

/**
 * Class PreventPublishedDocumentSaveValidator
 */
class PreventPublishedDocumentSaveValidator extends ConstraintValidator
{
    protected $translator;
    /**
     *
     * @param Translator $translator
     */
    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Checks if the passed value is valid.
     *
     * @param mixed      $value The value that should be validated
     * @param Constraint $constraint The constraint for the validation
     */
    public function validate($value, Constraint $constraint)
    {
        if ($value instanceof StatusableInterface) {
            $status = $value->getStatus();
            if (! empty($status) && $status->isPublished()) {
                $this->context->addViolation($this->translator->trans($constraint->message));
            }
        }
    }
}

<?php

namespace PHPOrchestra\ModelBundle\Validator\Constraints;

use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ODM\MongoDB\DocumentManager;
use PHPOrchestra\ModelBundle\Model\StatusableInterface;

/**
 * Class PreventPublishedDocumentSaveValidator
 */
class PreventPublishedDocumentSaveValidator extends ConstraintValidator
{
    protected $translator;
    /**
     *
     * @param Translator $translator
     */
    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Checks if the passed value is valid.
     *
     * @param mixed      $value The value that should be validated
     * @param Constraint $constraint The constraint for the validation
     */
    public function validate($value, Constraint $constraint)
    {
        if ($value instanceof StatusableInterface) {
            $status = $value->getStatus();
            if (!empty($status) && $status->isPublished()) {
                $this->context->addViolation($this->translator->trans($constraint->message));
            }
        }
    }
}

Add read only functionnality on published node


<?php
/**
 * Additional site settings.
 */

// Forcibly disable poorman's cron.
$conf['cron_safe_threshold'] = 0;

// Database connection settings.
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => '<%= machineName %>_drupal',
      'username' => 'admin',
      'password' => 'admin',
      'host' => 'db.<%= projectName %>.vm',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
<% if(cacheLink) { %>
// Add Memcache for internal caching.
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['memcache_servers'] = array(
  'cache.<%= projectName %>.vm:11211' => 'default',
);
$conf['memcache_bins'] = array(
 'cache' => 'default',
);
$conf['memcache_key_prefix'] = '<%= machineName %>_';
<% } -%>

// Include local settings file as an override.
// settings.local.php should not be committed to the Git repository.
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

Add auto-include of local settings override if there is a settings.local.php


@extends('front.layouts.master')

@section('title', 'Create Account')
@section('description', "")

@section('contents')

Create an Account

                There is currently no PCB account registered to your social account.
                Would you like to create a PCB account with these details?

{{ $social['name'] }}

                {{ $social['email'] }}

                     Create & Proceed

@endsection

@extends('front.layouts.master')

@section('title', 'Create Account')
@section('description', "")

@section('contents')

Create an Account

                There is currently no PCB account registered to this social account.
                Would you like to create a PCB account with these details?

                If you wish to associate this social account with an existing PCB account, please log-in to
                PCB first then log-in to your social account from the settings page.

{{ $social['name'] }}

                {{ $social['email'] }}

                     Create & Proceed

@endsection

Update social account registration text for clarity


<?php

namespace Oro\Bundle\EntityMergeBundle\Model\Step;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

use Oro\Bundle\EntityMergeBundle\Data\EntityData;
use Oro\Bundle\EntityMergeBundle\Event\FieldDataEvent;
use Oro\Bundle\EntityMergeBundle\MergeEvents;
use Oro\Bundle\EntityMergeBundle\Model\Strategy\StrategyInterface;

class MergeFieldsStep implements DependentMergeStepInterface
{
    /**
     * @var EventDispatcherInterface
     */
    protected $eventDispatcher;

    /**
     * @param StrategyInterface $strategy
     * @param EventDispatcherInterface $eventDispatcher
     */
    public function __construct(StrategyInterface $strategy, EventDispatcherInterface $eventDispatcher)
    {
        $this->strategy = $strategy;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * Merge fields
     *
     * @param EntityData $data
     */
    public function run(EntityData $data)
    {
        foreach ($data->getFields() as $field) {
            $this->eventDispatcher->dispatch(MergeEvents::BEFORE_MERGE_FIELD, new FieldDataEvent($field));
            $this->strategy->merge($field);
            $this->eventDispatcher->dispatch(MergeEvents::AFTER_MERGE_FIELD, new FieldDataEvent($field));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDependentSteps()
    {
        return array('Oro\\Bundle\\EntityMergeBundle\\Model\\Step\\ValidateStep');
    }
}

<?php

namespace Oro\Bundle\EntityMergeBundle\Model\Step;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

use Oro\Bundle\EntityMergeBundle\Data\EntityData;
use Oro\Bundle\EntityMergeBundle\Event\FieldDataEvent;
use Oro\Bundle\EntityMergeBundle\MergeEvents;
use Oro\Bundle\EntityMergeBundle\Model\Strategy\StrategyInterface;

class MergeFieldsStep implements DependentMergeStepInterface
{
    /**
     * @var EventDispatcherInterface
     */
    protected $eventDispatcher;

    /**
     * @param StrategyInterface $strategy
     * @param EventDispatcherInterface $eventDispatcher
     */
    public function __construct(StrategyInterface $strategy, EventDispatcherInterface $eventDispatcher)
    {
        $this->strategy = $strategy;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * Merge fields
     *
     * @param EntityData $data
     */
    public function run(EntityData $data)
    {
        foreach ($data->getFields() as $field) {
            $fieldMetadata = $field->getMetadata();
            if ($fieldMetadata->has('is_virtual') && $fieldMetadata->get('is_virtual') === true) {
                continue;
            }
            $this->eventDispatcher->dispatch(MergeEvents::BEFORE_MERGE_FIELD, new FieldDataEvent($field));
            $this->strategy->merge($field);
            $this->eventDispatcher->dispatch(MergeEvents::AFTER_MERGE_FIELD, new FieldDataEvent($field));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDependentSteps()
    {
        return array('Oro\\Bundle\\EntityMergeBundle\\Model\\Step\\ValidateStep');
    }
}

CRM-4654: Modify standard step to skip extended merge field


<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Ewallet\ManageWallet;

use Ewallet\Memberships\{MemberId, MembersRepository};
use Symfony\Component\Console\Input\InputInterface;

class TransferFundsConsoleResponder implements TransferFundsResponder
{
    /** @var InputInterface */
    private $input;

    /** @var MembersRepository */
    private $members;

    /** @var TransferFundsConsole */
    private $console;

    public function __construct(
        InputInterface $input,
        MembersRepository $members,
        TransferFundsConsole $console
    ) {
        $this->input = $input;
        $this->members = $members;
        $this->console = $console;
    }

    /**
     * @param string[] $messages
     * @param string[] $values
     */
    public function respondToInvalidTransferInput(array $messages, array $values)
    {
        $this->console->printError($messages);
    }

    public function respondToEnterTransferInformation(MemberId $senderId)
    {
        $this->console->printRecipients($this->members->excluding($senderId));

        $this->input->setArgument('recipientId', $this->console->promptRecipientId());
        $this->input->setArgument('amount', $this->console->promptAmountToTransfer());
    }

    public function respondToTransferCompleted(TransferFundsSummary $summary)
    {
        $this->console->printSummary($summary);
    }
}

<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Ewallet\ManageWallet;

use Ewallet\Memberships\{MemberId, MembersRepository};
use Symfony\Component\Console\Input\InputInterface;

class TransferFundsConsoleResponder implements TransferFundsResponder
{
    /** @var InputInterface */
    private $input;

    /** @var MembersRepository */
    private $members;

    /** @var TransferFundsConsole */
    private $console;

    public function __construct(
        InputInterface $input,
        MembersRepository $members,
        TransferFundsConsole $console
    ) {
        $this->input = $input;
        $this->members = $members;
        $this->console = $console;
    }

    /**
     * @param string[] $messages
     * @param string[] $values
     */
    public function respondToInvalidTransferInput(array $messages, array $values): void
    {
        $this->console->printError($messages);
    }

    public function respondToEnterTransferInformation(MemberId $senderId): void
    {
        $this->console->printRecipients($this->members->excluding($senderId));

        $this->input->setArgument('recipientId', $this->console->promptRecipientId());
        $this->input->setArgument('amount', $this->console->promptAmountToTransfer());
    }

    public function respondToTransferCompleted(TransferFundsSummary $summary): void
    {
        $this->console->printSummary($summary);
    }
}

Add missing void return types in console responder.


<?php

namespace Plummer\Calendar;

class Calendar
{
	protected $events;

	protected $recurrenceTypes;

	protected function __construct(\Iterator $events)
	{
		$this->events = $events;
	}

	public static function make(\Iterator $events)
	{
		return new static($events);
	}

	public function addEvents(array $events)
	{
		foreach($events as $event) {
			$this->addEvent($event);
		}
	}

	public function addEvent(Event $event)
	{
		$event->setCalendar($this);

		$this->events[] = $event;
	}

	public function addRecurrenceTypes(array $recurrenceTypes)
	{
		foreach($recurrenceTypes as $recurrenceType) {
			$this->addRecurrenceType($recurrenceType);
		}
	}

	public function addRecurrenceType(RecurrenceInterface $recurrenceType)
	{
		$this->recurrenceTypes[] = $recurrenceType;
	}
}

<?php

namespace Plummer\Calendar;

class Calendar
{
	protected $events;

	protected $recurrenceTypes;

	protected function __construct(\Iterator $events, $recurrenceTypes)
	{
		$this->events = $events;
		$this->addRecurrenceTypes($recurrenceTypes);
	}

	public static function make(\Iterator $events, $recurrenceTypes = [])
	{
		return new static($events, $recurrenceTypes);
	}

	public function addEvents(array $events)
	{
		foreach($events as $event) {
			$this->addEvent($event);
		}
	}

	public function addEvent(Event $event)
	{
		$event->setCalendar($this);

		$this->events[] = $event;
	}

	public function addRecurrenceTypes(array $recurrenceTypes)
	{
		foreach($recurrenceTypes as $recurrenceType) {
			$this->addRecurrenceType($recurrenceType);
		}
	}

	public function addRecurrenceType(RecurrenceInterface $recurrenceType)
	{
		$this->recurrenceTypes[] = $recurrenceType;
	}
}

Update calendar constructors to take in recurrence types.


<?php

namespace Jadu\Pulsar\Twig\Extension;

class TabsExtension extends \Twig_Extension
{
  public function getName()
  {
    return 'tabs_extension';
  }

  public function getFunctions()
  {
    return array(
      new \Twig_SimpleFunction('get_active_tab', array($this, 'getActiveParentTabID'))
    );
  }

  public function getActiveParentTabID($tabs = null, $active_parent_tab_id = null)
  {
    if ($tabs === null) {
      return false;
    }

    // $tabs passed through Twig is an array rather than a json string
    if (is_array($tabs)) {
      $tabs = json_encode($tabs);
    }

    $ob = json_decode($tabs);

    // If we don't have valid json, abandon ship
    if ($ob === null) {
      return false;
    }

    // Loop through the tab items
    foreach ($ob as $item) {

      // If we have subnavigation
      if ($item->sub_tabs != null) {

        // Loop through its sub tabs
        foreach($item->sub_tabs as $sub_tab) {
          if ($sub_tab->id === $active_parent_tab_id) {
            return $item->id;
          }
        }
      }
    }

    return false;
  }
}

<?php

namespace Jadu\Pulsar\Twig\Extension;

class TabsExtension extends \Twig_Extension
{
  public function getName()
  {
    return 'tabs_extension';
  }

  public function getFunctions()
  {
    return array(
      new \Twig_SimpleFunction('get_active_tab', array($this, 'getActiveParentTabID'))
    );
  }

  public function getActiveParentTabID($tabs = null, $active_parent_tab_id = null)
  {
    if ($tabs === null) {
      return false;
    }

    // $tabs passed through Twig is an array rather than a json string
    if (is_array($tabs)) {
      $tabs = json_encode($tabs);
    }

    $ob = json_decode($tabs);

    // If we don't have valid json, abandon ship
    if ($ob === null) {
      return false;
    }

    // Loop through the tab items
    foreach ($ob as $item) {

      // If we have subnavigation
      if (isset($item->sub_tabs) && $item->sub_tabs != null) {

        // Loop through its sub tabs
        foreach($item->sub_tabs as $sub_tab) {
          if ($sub_tab->id === $active_parent_tab_id) {
            return $item->id;
          }
        }
      }
    }

    return false;
  }
}

Fix issue where the tabs object throws an error if no sub_tabs exist at all


<?php

/**
 * Generates site-wide page chrome.
 * @see https://drupal.org/node/1728148
 **/

?>

<?php if (!empty($tabs['#primary'])): ?><?php print render($tabs); ?><?php endif; ?>
<?php print $messages; ?>

  <?php print $variables['navigation']; ?>
  <?php print $variables['header']; ?>

      <?php print render($page['content']); ?>

  <?php print $variables['footer']; ?>

Add container__block for padding on default pages.


<?php
/**
 * Aliases for special pages for extension Kartographer
 *
 * @file
 * @ingroup Extensions
 */

$specialPageAliases = [];

/** English (English) */
$specialPageAliases['en'] = [
	'Map' => [ 'Map' ],
];

/** Serbian (Cyrillic script) (српски (ћирилица)) */
$specialPageAliases['sr-ec'] = [
	'Map' => [ 'Мапа' ],
];

/** Serbian (Latin script) (srpski (latinica)) */
$specialPageAliases['sr-el'] = [
	'Map' => [ 'Mapa' ],
];

/** Urdu (اردو) */
$specialPageAliases['ur'] = [
	'Map' => [ 'نقشہ' ],
];

Remove LEFT-TO-RIGHT MARK (U+200E) from source code

Change-Id: Iab14a33a24f539b14bbcc00d8e2b8088f1118ee0


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

namespace PH7;

use PH7\Framework\Http\Http;

class MainController extends Controller
{
    const CONTENT_TYPE = 'application/json';
    const JSON_TPL_EXT = '.json.tpl';

    public function manifest()
    {
        $this->setContentType();

        $this->view->bg_color = $this->config->values['module.setting']['background_color'];

        $this->jsonOutput();
    }

    /**
     * @return void
     *
     * @throws Framework\Http\Exception
     * @throws Framework\Layout\Tpl\Engine\PH7Tpl\Exception
     */
    private function jsonOutput()
    {
        /* Compression damages JSON syntax, so disable them */
        $this->view->setHtmlCompress(false);
        $this->view->setPhpCompress(false);

        // Display
        $this->setContentType(); // Header
        $this->view->display($this->httpRequest->currentController() . PH7_DS . $this->registry->action . self::JSON_TPL_EXT);
    }

    /**
     * @return void
     *
     * @throws Framework\Http\Exception
     */
    private function setContentType()
    {
        Http::setContentType(self::CONTENT_TYPE); //Output format
    }
}

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

namespace PH7;

use PH7\Framework\Http\Http;

class MainController extends Controller
{
    const CONTENT_TYPE = 'application/json';
    const JSON_TPL_EXT = '.json.tpl';

    public function manifest()
    {
        $this->setContentType();

        $this->view->bg_color = $this->config->values['module.setting']['background_color'];

        $this->jsonOutput();
    }

    /**
     * @return void
     *
     * @throws Framework\Http\Exception
     * @throws Framework\Layout\Tpl\Engine\PH7Tpl\Exception
     */
    private function jsonOutput()
    {
        /* Compression damages JSON syntax, so disable them */
        $this->view->setHtmlCompress(false);
        $this->view->setPhpCompress(false);

        $this->setContentType(); // Header, output format

        $this->view->display($this->httpRequest->currentController() . PH7_DS . $this->registry->action . self::JSON_TPL_EXT);
    }

    /**
     * @return void
     *
     * @throws Framework\Http\Exception
     */
    private function setContentType()
    {
        Http::setContentType(self::CONTENT_TYPE);
    }
}

Update comments. Remove redundant comment


<?php

/*
 * This file is part of the Assetic package, an OpenSky project.
 *
 * (c) 2010-2014 OpenSky Project Inc
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Assetic\Test\Filter;

use Assetic\Asset\FileAsset;
use Assetic\Filter\JSqueezeFilter;

/**
 * @group integration
 */
class JSqueezeFilterTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!class_exists('JSqueeze')) {
            $this->markTestSkipped('JSqueeze is not installed.');
        }
    }

    public function testRelativeSourceUrlImportImports()
    {
        $asset = new FileAsset(__DIR__.'/fixtures/jsmin/js.js');
        $asset->load();

        $filter = new JSqueezeFilter();
        $filter->filterDump($asset);

        $this->assertEquals(";var a='abc',bbb='u';", $asset->getContent());
    }
}

<?php

/*
 * This file is part of the Assetic package, an OpenSky project.
 *
 * (c) 2010-2014 OpenSky Project Inc
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Assetic\Test\Filter;

use Assetic\Asset\FileAsset;
use Assetic\Filter\JSqueezeFilter;

/**
 * @group integration
 */
class JSqueezeFilterTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!class_exists('JSqueeze') && !class_exists('Patchwork\JSqueeze')) {
            $this->markTestSkipped('JSqueeze is not installed.');
        }
    }

    public function testRelativeSourceUrlImportImports()
    {
        $asset = new FileAsset(__DIR__.'/fixtures/jsmin/js.js');
        $asset->load();

        $filter = new JSqueezeFilter();
        $filter->filterDump($asset);

        $this->assertEquals(";var a='abc',bbb='u';", $asset->getContent());
    }
}

Fix the detection of JSqueeze in tests when using 2.0


<?php

require_once '../moteur/dbconfig.php';

function recover_utilisateurs(int $admin, string $table, array $fields): string {
  return ("update $table as T
  set T.$fields[0] = $admin,
      T.$fields[1] = $admin
  where not exists (select 1
  from utilisateurs U
  where U.id = T.$fields[0]);
");
}

function recover(PDO $bdd, string $database_name, int $admin) {
  $tables = $bdd->query("SELECT table_name FROM information_schema.tables
    where table_schema=\"$database_name\"");

  $fields = [ 'id_createur', 'id_last_hero'];
  foreach ($tables as $t) {
    $name = $t['table_name'];

    if ($name === NULL || $name === 'utilisateurs') {
      continue;
    }

    $sql = recover_utilisateurs($admin, $name, $fields);
    $bdd->query($sql);
  }
}

/*
 * Ce script récupére les utilisateurs supprimées et les réapparentes à un utilisateur
 * administrateur.
 * Modifier la variable $admin pour changer cet utilisateur.
 */
function main() {
  global $bdd;
  global $base;
  $database_name = $base;

  // Note: Cas de la petite rockette
  $admin = $bdd->query("select id from utilisateurs where mail = inconnu@localhost");
  recover($bdd, $database_name, $admin);
}

main();

<?php

require_once '../moteur/dbconfig.php';

function recover_utilisateurs(int $admin, string $table, array $fields): string {
  return ("update $table as T
  set T.$fields[0] = $admin,
      T.$fields[1] = $admin
  where not exists (select 1
  from utilisateurs U
  where U.id = T.$fields[0]);
");
}

function recover(PDO $bdd, string $database_name, int $admin) {
  $tables = $bdd->query("SELECT table_name FROM information_schema.tables
    where table_schema=\"$database_name\"");

  $fields = [ 'id_createur', 'id_last_hero'];
  foreach ($tables as $t) {
    $name = $t['table_name'];

    if ($name === NULL || $name === 'utilisateurs') {
      continue;
    }

    $sql = recover_utilisateurs($admin, $name, $fields);
    $bdd->query($sql);
  }
}

/*
 * Ce script récupére les utilisateurs supprimées et les réapparentes à un utilisateur
 * administrateur.
 * Modifier la variable $admin pour changer cet utilisateur.
 */
function main() {
  global $bdd;
  global $base;
  $database_name = $base;

  // Note: Cas de la petite rockette
  $req = $bdd->query('select id from utilisateurs where mail = "inconnu@localhost"');
  $id = $req->fetch()['id'];
  $req->closeCursor();
  recover($bdd, $database_name, $id);
}

main();

Fix minibug in recover script

Fix minibug in recover script


<?php

namespace PhunkieConsole\IO\Colours;

use const Phunkie\Functions\function1\identity;
const colours = "PhunkieConsole\\IO\\Colours\\colours";
const noColours = "PhunkieConsole\\IO\\Colours\\noColours";

function colours()
{
    $colours = [
        "boldRed" => function($message) use (&$colours) { return $colours['bold']($colours['red']($message)); },
        "red" => function($message) { return "\e[31m$message\e[0m"; },
        "blue" => function($message) { return "\e[34m$message\e[0m"; },
        "bold" => function($message) { return "\e[1m$message\e[21m"; },
        "cyan" => function($message) { return "\e[36m$message\e[0m"; },
        "green" => function($message) { return "\e[32m$message\e[0m"; },
        "magenta" => function($message) { return "\e[35m$message\e[0m"; },
        "purple" => function($message) { return "\e[38;5;57m$message\e[0m"; }
    ];
    return $colours;
}

function noColours()
{
    return [
        "boldRed" => identity,
        "red" => identity,
        "blue" => identity,
        "bold" => identity,
        "cyan" => identity,
        "magenta" => identity,
        "purple" => identity
    ];
}

<?php

namespace PhunkieConsole\IO\Colours;

use const Phunkie\Functions\function1\identity;
const colours = "PhunkieConsole\\IO\\Colours\\colours";
const noColours = "PhunkieConsole\\IO\\Colours\\noColours";

function colours()
{
    $colours = [
        "boldRed" => function($message) use (&$colours) { return $colours['bold']($colours['red']($message)); },
        "red" => function($message) { return "\e[31m$message\e[0m"; },
        "blue" => function($message) { return "\e[34m$message\e[0m"; },
        "bold" => function($message) { return "\e[1m$message\e[0m"; },
        "cyan" => function($message) { return "\e[36m$message\e[0m"; },
        "green" => function($message) { return "\e[32m$message\e[0m"; },
        "magenta" => function($message) { return "\e[35m$message\e[0m"; },
        "purple" => function($message) { return "\e[38;5;57m$message\e[0m"; }
    ];
    return $colours;
}

function noColours()
{
    return [
        "boldRed" => identity,
        "red" => identity,
        "blue" => identity,
        "bold" => identity,
        "cyan" => identity,
        "magenta" => identity,
        "purple" => identity
    ];
}

Fix bug: missing bold end tag

Fix bug: missing bold end tag


<?php

namespace Metrique\Building\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Metrique\Building\Rules\AbsoluteUrlPathRule;

class PageRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'path' => 'Path',
            'published_at' => 'published date',
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'path' => [
                'required',
                'string',
                new AbsoluteUrlPathRule,
                Rule::unique(
                    'pages',
                    'path'
                )->ignore(
                    optional($this->page)->id
                ),
            ],
            'title' => [
                'required',
                'string',
            ],
            'description' => [
                'required',
                'string',
            ],
            'image' => [
                'string',
                'url'
            ],
            'meta' => [
                'array',
            ],
            'params' => [
                'array',
            ],
            'published_at' => [
                'nullable',
                'date',
            ],
        ];
    }
}

<?php

namespace Metrique\Building\Http\Requests;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Metrique\Building\Rules\AbsoluteUrlPathRule;

class PageRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'path' => 'Path',
            'published_at' => 'published date',
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'path' => [
                'required',
                'string',
                new AbsoluteUrlPathRule,
                Rule::unique(
                    'pages',
                    'path'
                )->ignore(
                    optional($this->page)->id
                )->where(function ($query) {
                    return $query->whereNull('deleted_at');
                }),
            ],
            'title' => [
                'required',
                'string',
            ],
            'description' => [
                'required',
                'string',
            ],
            'image' => [
                'string',
                'url'
            ],
            'meta' => [
                'array',
            ],
            'params' => [
                'array',
            ],
            'published_at' => [
                'nullable',
                'date',
            ],
        ];
    }
}

Handle recreating soft deleted pages

Handle recreating soft deleted pages


<?php

namespace Flagrow\Analytics\Listeners;

use DirectoryIterator;
use Flarum\Event\ConfigureClientView;
use Illuminate\Contracts\Events\Dispatcher;
use Flarum\Event\ConfigureLocales;

class AddClientAssets
{
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureClientView::class, [$this, 'addAssets']);
        $events->listen(ConfigureLocales::class, [$this, 'addLocales']);
    }

    public function addAssets(ConfigureClientView $event)
    {
        if($event->isAdmin()) {
            $event->addAssets([
                __DIR__ . '/../../less/admin/analyticsPage.less',
                __DIR__ . '/../../js/admin/dist/extension.js',
            ]);

            $event->addBootstrapper('flagrow/analytics/main');
        } elseif($event->isForum())
        {
            $event->addAssets([
                __DIR__ . '/../../js/forum/dist/extension.js'
            ]);

            $event->addBootstrapper('flagrow/analytics/main');
        }
    }

    public function addLocales(ConfigureLocales $event)
    {
        foreach (new DirectoryIterator(__DIR__.'/../../locale') as $file) {
            if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
                $event->locales->addTranslations($file->getBasename('.'.$file->getExtension()), $file->getPathname());
            }
        }
    }
}

<?php

namespace Flagrow\Analytics\Listeners;

use DirectoryIterator;
use Flarum\Event\ConfigureWebApp;
use Illuminate\Contracts\Events\Dispatcher;
use Flarum\Event\ConfigureLocales;

class AddClientAssets
{
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureWebApp::class, [$this, 'addAssets']);
        $events->listen(ConfigureLocales::class, [$this, 'addLocales']);
    }

    public function addAssets(ConfigureWebApp $event)
    {
        if($event->isAdmin()) {
            $event->addAssets([
                __DIR__ . '/../../less/admin/analyticsPage.less',
                __DIR__ . '/../../js/admin/dist/extension.js',
            ]);

            $event->addBootstrapper('flagrow/analytics/main');
        } elseif($event->isForum())
        {
            $event->addAssets([
                __DIR__ . '/../../js/forum/dist/extension.js'
            ]);

            $event->addBootstrapper('flagrow/analytics/main');
        }
    }

    public function addLocales(ConfigureLocales $event)
    {
        foreach (new DirectoryIterator(__DIR__.'/../../locale') as $file) {
            if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
                $event->locales->addTranslations($file->getBasename('.'.$file->getExtension()), $file->getPathname());
            }
        }
    }
}

Replace deprecated ConfigureClientView with ConfigureWebApp again


<?php

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

class AddHashToNotifications extends Migration
{

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('seat_notifications', function($table)
		{
		    $table->string('hash');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		//
	}

}

<?php

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

class AddHashToNotifications extends Migration
{

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('seat_notifications', function($table)
		{
		    $table->string('hash')->after('read');
		});
	}

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

}

Complete the migration down() method

Complete the migration down() method


<?php
    global $mysqli,$route;
    require_once "Modules/dashboard/dashboard_model.php";
    $dashboard = new Dashboard($mysqli);

    $location = 'view';
    $sess = (isset($session['write']) && $session['write'] ? 'write':(isset($session['read']) && $session['read'] ? 'read':''));
    if (isset($session['profile']) && $session['profile']==1) {
        $dashpath = $session['username'];
        $sess= 'all';
    } else {
        if ($route->action == "edit" && $session['write']) $location = 'edit';
        $dashpath = 'dashboard/'.$location;
    }

    // Contains a list for the drop down with dashboards available for user session type
    $listmenu = $dashboard->build_menu_array($location);

    $domain = "messages";
    bindtextdomain($domain, "Modules/dashboard/locale");
    bind_textdomain_codeset($domain, 'UTF-8');

    $menu_left[] = array('name'=> dgettext($domain, "Dashboards"), 'path'=>$dashpath , 'session'=>$sess, 'order' => 4, 'dropdown'=>$listmenu);

<?php
    global $mysqli,$route,$session;
    require_once "Modules/dashboard/dashboard_model.php";
    $dashboard = new Dashboard($mysqli);

    $location = 'view';
    $sess = (isset($session['write']) && $session['write'] ? 'write':(isset($session['read']) && $session['read'] ? 'read':''));
    if (isset($session['profile']) && $session['profile']==1) {
        $dashpath = $session['username'];
        $sess= 'all';
    } else {
        if ($route->action == "edit" && $session['write']) $location = 'edit';
        $dashpath = 'dashboard/'.$location;
    }

    // Contains a list for the drop down with dashboards available for user session type
    $listmenu = $dashboard->build_menu_array($location);

    $domain = "messages";
    bindtextdomain($domain, "Modules/dashboard/locale");
    bind_textdomain_codeset($domain, 'UTF-8');

    $menu_left[] = array('name'=> dgettext($domain, "Dashboards"), 'path'=>$dashpath , 'session'=>$sess, 'order' => 4, 'dropdown'=>$listmenu);

Fix dashboard menu for older php version.


<?
include '../scat.php';

$id= (int)$_REQUEST['id'];
$name= $_REQUEST['name'];
$slug= $_REQUEST['slug'];

try {
  $product= Model::factory('Product')->find_one($id);

  $old_slug= "";
  if (($product->slug && $_REQUEST['slug'] != $product->slug) ||
      ($product->department_id &&
       $_REQUEST['department_id'] != $product->department_id))
  {
    // XXX handle rename
    $old_slug= '';
  }

  foreach ($_REQUEST as $k => $v) {
    if (in_array($k, array('department_id', 'brand_id', 'name', 'description',
                           'slug', 'image', 'variation_style', 'active')))
    {
      $product->set($k, $v);
    }
  }

  $product->save();

  // XXX Save redirect information
  if ($old_slug) {
  }

} catch (\PDOException $e) {
  die_jsonp($e->getMessage());
}

echo jsonp($product);

<?
include '../scat.php';

$id= (int)$_REQUEST['id'];
$name= $_REQUEST['name'];
$slug= $_REQUEST['slug'];

try {
  $product= Model::factory('Product')->find_one($id);

  $old_slug= "";
  if (($product->slug && $_REQUEST['slug'] != $product->slug) ||
      ($product->department_id &&
       $_REQUEST['department_id'] != $product->department_id))
  {
    $old_slug= $product->full_slug();
  }

  foreach ($_REQUEST as $k => $v) {
    if (in_array($k, array('department_id', 'brand_id', 'name', 'description',
                           'slug', 'image', 'variation_style', 'active')))
    {
      $product->set($k, $v);
    }
  }

  $product->save();

  // Save redirect information
  if ($old_slug) {
    $new_slug= $product->full_slug();
    error_log("Redirecting $old_slug to $new_slug");
    $redir= Model::factory('Redirect')->create();
    $redir->source= $old_slug;
    $redir->dest= $new_slug;
    $redir->save();
  }

} catch (\PDOException $e) {
  die_jsonp($e->getMessage());
}

echo jsonp($product);

Create redirect when a product changes

Create redirect when a product changes


<?php

namespace App\Shop;

use Illuminate\Database\Eloquent\Model;

use App\Scopes\SortByLastUpdatedScope;

use Laravel\Scout\Searchable;

class ShopModel extends Model
{

    use Searchable;

    public $incrementing = false;
    protected $primaryKey = 'shop_id';
    protected $dates = ['source_created_at', 'source_modified_at'];

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

    protected static function boot()
    {

        parent::boot();
        static::addGlobalScope(new SortByLastUpdatedScope());

    }

    protected function searchableModel()
    {

        return kebab_case(class_basename(static::class));

    }

    protected function searchableSource()
    {

        return 'shop';

    }

    protected function searchableId()
    {

        return $this->searchableSource() .'-' .$this->searchableModel() .'-' .$this->shop_id;

    }

}

<?php

namespace App\Shop;

use Illuminate\Database\Eloquent\Model;

use App\Scopes\SortByLastUpdatedScope;

use Laravel\Scout\Searchable;

class ShopModel extends Model
{

    use Searchable;

    public $incrementing = false;
    protected $primaryKey = 'shop_id';
    protected $dates = ['source_created_at', 'source_modified_at'];

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

    protected static function boot()
    {

        parent::boot();
        static::addGlobalScope(new SortByLastUpdatedScope());

    }

    protected function searchableModel()
    {

        return kebab_case(class_basename(static::class));

    }

    protected function searchableSource()
    {

        return 'shop';

    }

    protected function searchableId()
    {

        return $this->searchableSource() .'/' .$this->searchableModel() .'/' .$this->shop_id;

    }

}

Use / as the primary delimiter in compound key

We want to avoid confusion between kebab_case'd model names,
and components of the compound key. If for some reason a dev
wants to parse the compound key (i.e. the Solr key) into parts,
using a different top-level delimiter will ease this process.


<?php

namespace App;

use Carbon\Carbon;

class UserRepository {

    public function getUser($request) {
        $user = $request->user;
        $expiresIn = Carbon::now();
        $expiresIn->addSecond($request->expiresIn);
        return User::updateOrCreate(['id' => $request->id], [
            'id' => $request->id,
            'username' => $user['username'],
            'email' => $request->email,
            'refresh_token' => $request->refreshToken,
            'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope']))? 'NAME_SERVERS' : 'NAME_ONLY',
            'token' => $request->token,
            'expires_in' => $expiresIn->toDateTimeString()
        ]);
    }
}

<?php

namespace App;

use Carbon\Carbon;
use Keygen;

class UserRepository {

    public function getUser($request) {
        $user = $request->user;
        $expiresIn = Carbon::now();
        $expiresIn->addSecond($request->expiresIn);
        return User::updateOrCreate(['id' => $request->id], [
            'id' => $request->id,
            'username' => $user['username'],
            'email' => ($request->email == null) ? 'unverified-' . substr($user['username'], 0, 3) . '-' . Keygen::alphanum(10)->generate() . '@kirbot' : $request->email,
            'refresh_token' => $request->refreshToken,
            'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope'])) ? 'NAME_SERVERS' : 'NAME_ONLY',
            'token' => $request->token,
            'expires_in' => $expiresIn->toDateTimeString()
        ]);
    }
}

Fix error if the user hasn't verified their email

The Discord API returns null for an unverified email. The panel requries an email to be set, therefore we set the email to a randomly generated one based on a pattern if the user doesn't have an email set.