<?php
/*
 * This file is part of the wpstarter package.
 *
 * (c) Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WCM\WPStarter\Env;

use Dotenv\Loader as DotenvLoader;

/**
 * @author  Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 * @license http://opensource.org/licenses/MIT MIT
 * @package wpstarter
 */
final class Loader extends DotenvLoader
{

    private $allVars = array();

    /**
     * Set variable using Dotenv loader and store the name in class var
     *
     * @param string $name
     * @param mixed  $value
     */
    public function setEnvironmentVariable($name, $value = null)
    {
        parent::setEnvironmentVariable($name, $value);

        $this->allVars[] = $name;
    }

    /**
     * @return array
     */
    public function allVarNames()
    {
        return $this->allVars;
    }

}

<?php
/*
 * This file is part of the wpstarter package.
 *
 * (c) Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WCM\WPStarter\Env;

use Dotenv\Loader as DotenvLoader;

/**
 * @author  Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 * @license http://opensource.org/licenses/MIT MIT
 * @package wpstarter
 */
final class Loader extends DotenvLoader
{

    private $allVars = array();

    /**
     * Set variable using Dotenv loader and store the name in class var
     *
     * @param string $name
     * @param mixed  $value
     */
    public function setEnvironmentVariable($name, $value = null)
    {
        list($name, $value) = $this->normaliseEnvironmentVariable($name, $value);

        if ($this->immutable === true && ! is_null($this->getEnvironmentVariable($name))) {
            return;
        }

        putenv("$name=$value");
        $_ENV[$name] = $value;
        $_SERVER[$name] = $value;
        $this->allVars[] = $name;
    }

    /**
     * @return array
     */
    public function allVarNames()
    {
        return $this->allVars;
    }

}

Fix a bug in loaded that saved not-normalized var

We need to copy & paste setEnvironmentVariable() because there's no
other way to access normalized variable name. - See #14


<?php

function includeIfExists($file)
{
    if (file_exists($file)) {
        return include $file;
    }
}

if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
    echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
        'curl -s http://getcomposer.org/installer | php'.PHP_EOL.
        'php composer.phar install'.PHP_EOL;
    exit(1);
}

$loader->add('Nelmio\Alice\\', __DIR__);

<?php

function includeIfExists($file)
{
    if (file_exists($file)) {
        return include $file;
    }
}

date_default_timezone_set('UTC');

if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
    echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
        'curl -s http://getcomposer.org/installer | php'.PHP_EOL.
        'php composer.phar install'.PHP_EOL;
    exit(1);
}

$loader->add('Nelmio\Alice\\', __DIR__);

Set default timezone to avoid tripping up hhvm


Fix seed code of PHP.

Fix seed code of PHP.


<?php

/*
 * This file is part of Laravel Instagram.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vinkla\Tests\Instagram;

use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return 'Vinkla\Instagram\InstagramServiceProvider';
    }
}

<?php

/*
 * This file is part of Laravel Instagram.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vinkla\Tests\Instagram;

use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
abstract class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return 'Vinkla\Instagram\InstagramServiceProvider';
    }
}

Make abstract test case class abstract

Make abstract test case class abstract


<?php

include_once ('../config.php');

if ( nbt_user_is_logged_in () ) { // User is logged in

	if ( nbt_get_privileges_for_userid ( $_SESSION[INSTALL_HASH . '_nbt_userid'] ) >= 2 ) {

		include ( ABS_PATH . "header.php" );
		include ( ABS_PATH . "export/export.php" );

	} else {

		$nbtErrorText = "You do not have permission to export data.";

		include ( ABS_PATH . "header.php" );
		include ( ABS_PATH . "error.php" );

	}

} else {

	$nbtErrorText = "You are not logged in.";

	include ( ABS_PATH . "header.php" );
	include ( ABS_PATH . "error.php" );

}

include ( ABS_PATH . "footer.php" );

?>

<?php

include_once ('../config.php');

if ( nbt_user_is_logged_in () ) { // User is logged in

	if ( nbt_get_privileges_for_userid ( $_SESSION[INSTALL_HASH . '_nbt_userid'] ) >= 2 ) {

		include ( ABS_PATH . "header.php" );
		include ( ABS_PATH . "export/export.php" );

	} else {

		$nbtErrorText = "You do not have permission to export data.";

		include ( ABS_PATH . "header.php" );
		include ( ABS_PATH . "error.php" );

	}

} else {

	$nbtErrorText = "You are not logged in.";

	include ( ABS_PATH . "header.php" );
	include ( ABS_PATH . "error.php" );

}

unset($formelements);
include ( ABS_PATH . "footer.php" );

?>

Fix bug where exporter fails if there are conditional displays


<?php

namespace Wizbii\PipelineBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Wizbii\PipelineBundle\Service\Pipeline;
use Wizbii\PipelineBundle\Service\PipelineProvider;

class FrontendPipelineCommand extends ContainerAwareCommand
{
    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $consumers = $this->getConsumers($input->getOption('direct'));

        echo join(" ", $consumers->getArrayCopy());
    }

    protected function configure()
    {
        $this
            ->setName('pipeline:frontend:list')
            ->addOption('direct', null, InputOption::VALUE_NONE)
        ;
    }

    protected function getConsumers(bool $directConsumers)
    {
        $serviceId = $directConsumers ? "pipeline.consumers.direct" : "pipeline.consumers";

        return $this->getContainer()->get($serviceId);
    }
}

<?php

namespace Wizbii\PipelineBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Wizbii\PipelineBundle\Service\Pipeline;
use Wizbii\PipelineBundle\Service\PipelineProvider;

class FrontendPipelineCommand extends ContainerAwareCommand
{
    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $consumers = $this->getConsumers($input->getOption('direct'));
        $asJson = $input->getOption('json');

        $output->write($asJson ? json_encode($consumers) : join(" ", $consumers));
    }

    protected function configure()
    {
        $this
            ->setName('pipeline:frontend:list')
            ->addOption('direct', null, InputOption::VALUE_NONE)
            ->addOption('json', null, InputOption::VALUE_NONE)
        ;
    }

    protected function getConsumers(bool $directConsumers)
    {
        $serviceId = $directConsumers ? "pipeline.consumers.direct" : "pipeline.consumers";

        return $this->getContainer()->get($serviceId)->getArrayCopy();
    }
}

Allow to dump frontend consumers in JSON


<?php

use VotingApp\Models\Candidate;

class VotingTest extends TestCase
{

    protected function fillVoteForm()
    {
        $candidate = Candidate::all()->first();

        $this->visit(route('candidates.show', [$candidate->slug]))
             ->fill('Puppet', '#first_name')
             ->fill('1/1/1990', '#birthdate')
             ->fill('test-example-user@example.com', '#email')
             ->press('Count My Vote');

        return $this;
    }

    /**
     * Verify that a user may submit their vote.
     * @test
     */
    public function testSubmitVote()
    {
        $this->fillVoteForm();
        $this->see('Thanks, we got that vote!');

        // If the user tries to vote again, they should see an error
        $this->visit('logout');
        $this->fillVoteForm();
        $this->see('You already voted today!');
    }

}

<?php

use VotingApp\Models\Candidate;
use VotingApp\Models\User;

class VotingTest extends TestCase
{

    protected $candidate;

    protected $userEmail;

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

        $this->candidate = Candidate::all()->first();

        $this->userEmail = 'test-example-user@example.com';
    }

    protected function fillVoteForm($candidate)
    {
        $this->visit(route('candidates.show', [$candidate->slug]))
             ->fill('Puppet', '#first_name')
             ->fill('1/1/1990', '#birthdate')
             ->fill($this->userEmail, '#email')
             ->press('Count My Vote');

        return $this;
    }

    /**
     * Verify that a user may submit their vote.
     * @test
     */
    public function testSubmitVote()
    {
        $this->fillVoteForm($this->candidate);
        $this->see('Thanks, we got that vote!');

        // Check the user & vote were created in the database
        $user = User::where('email', $this->userEmail)->first();
        $this->seeInDatabase('votes', [
            'user_id' => $user->id,
            'candidate_id' => $this->candidate->id
        ]);

        // If the user tries to vote again, they should see an error
        $this->visit('logout');
        $this->fillVoteForm($this->candidate);
        $this->see('You already voted today!');
    }

}

Test that vote is created in database.

Test that vote is created in database.


<?php
// This is global bootstrap for autoloading
$autoloader = require __DIR__.'/../vendor/autoload.php';
$autoloader->add('App', __DIR__.'/../app/library');
$autoloader->addClassMap([
    'CestAbstract' => __DIR__.'/functional/CestAbstract.php',
]);

<?php
// This is global bootstrap for autoloading
$autoloader = require __DIR__.'/../vendor/autoload.php';
$autoloader->add('AzuraCast', __DIR__.'/../app/library');
$autoloader->addClassMap([
    'CestAbstract' => __DIR__.'/functional/CestAbstract.php',
]);

Update mapping of classes in CI script.

Update mapping of classes in CI script.


<?php

namespace Good\Rolemodel\Schema;

use Good\Rolemodel\SchemaVisitor;

class IntMember extends PrimitiveMember
{

    public function acceptSchemaVisitor(SchemaVisitor $visitor)
    {
        // visit this, there are no children to pass visitor on to
        $visitor->visitIntMember($this);
    }

    function getValidParameterTypeModifiers()
    {
        return array('minValue', 'maxValue');
    }

    function getValidNonParameterTypeModifiers()
    {
        return array('nonNegative');
    }

    function processTypeModifiers(array $typeModifiers)
    {
        return $typeModifiers;
    }

    function getDefaultTypeModifierValues()
    {
        // standard int values, also (practically) guaranteed range of php ints
        return array('minValue' => -2147483648, 'maxValue' => 2147483647);
    }
}

?>

<?php

namespace Good\Rolemodel\Schema;

use Good\Rolemodel\SchemaVisitor;

class IntMember extends PrimitiveMember
{

    public function acceptSchemaVisitor(SchemaVisitor $visitor)
    {
        // visit this, there are no children to pass visitor on to
        $visitor->visitIntMember($this);
    }

    function getValidParameterTypeModifiers()
    {
        return array('minValue', 'maxValue');
    }

    function getValidNonParameterTypeModifiers()
    {
        return array('nonNegative');
    }

    function processTypeModifiers(array $typeModifiers)
    {
        if (array_key_exists('minValue', $typeModifiers) &&
            array_key_exists('maxValue', $typeModifiers) &&
            $typeModifiers['minValue'] > $typeModifiers['maxValue'])
        {
            throw new \Exception("The minValue for an int cannot be higher than its maxValue");
        }

        if (array_key_exists('nonNegative', $typeModifiers))
        {
            if ((array_key_exists('minValue', $typeModifiers) && $typeModifiers['minValue'] < 0) ||
                (array_key_exists('maxValue', $typeModifiers) && $typeModifiers['maxValue'] < 0))
            {
                throw new \Exception("If nonNegative is set on an int, its minValue and maxValue can't be negative");
            }

            if (!array_key_exists('minValue', $typeModifiers))
            {
                $typeModifiers['minValue'] = 0;
            }

            unset($typeModifiers['nonNegative']);
        }

        return $typeModifiers;
    }

    function getDefaultTypeModifierValues()
    {
        // standard int values, also (practically) guaranteed range of php ints
        return array('minValue' => -2147483648, 'maxValue' => 2147483647);
    }
}

?>

Add additional processing to int type modifiers

- minValue must be lower than or equal to maxValue.

- if nonNegative is set, neither minValue nor maxValue can be negative

- transform nonNegtative into minValue = 0


<?php

namespace OpenDominion;

use Illuminate\Foundation\Application as LaravelApplication;

class Application extends LaravelApplication
{
    protected $appPath;

    public function __construct($basePath)
    {
        parent::__construct($basePath);

        $this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app');
        $this->bindPathsInContainer();
    }

    public function path($path = '')
    {
        return ($this->basePath . DIRECTORY_SEPARATOR . 'src' . $this->getSuffixPath($path));
    }

    public function bootstrapPath($path = '')
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap' . $this->getSuffixPath($path));
    }

    public function configPath($path = '')
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'config' . $this->getSuffixPath($path));
    }

    public function databasePath($path = '')
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'database' . $this->getSuffixPath($path));
    }

    public function langPath()
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang');
    }

    public function storagePath()
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'storage');
    }

    protected function getSuffixPath($path = '')
    {
        return ($path ? (DIRECTORY_SEPARATOR . $path) : '');
    }
}

<?php

namespace OpenDominion;

use Illuminate\Foundation\Application as LaravelApplication;

class Application extends LaravelApplication
{
    protected $appPath;

    /**
     * Create a new OpenDominion application instance.
     *
     * @param string|null $basePath
     */
    public function __construct($basePath = null)
    {
        parent::__construct($basePath);

        $this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app');
        $this->bindPathsInContainer();
    }

    /**
     * {@inheritdoc}
     */
    public function path($path = '')
    {
        return ($this->basePath . DIRECTORY_SEPARATOR . 'src' . $this->getSuffixPath($path));
    }

    /**
     * {@inheritdoc}
     */
    public function bootstrapPath($path = '')
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap' . $this->getSuffixPath($path));
    }

    /**
     * {@inheritdoc}
     */
    public function configPath($path = '')
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'config' . $this->getSuffixPath($path));
    }

    /**
     * {@inheritdoc}
     */
    public function databasePath($path = '')
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'database' . $this->getSuffixPath($path));
    }

    /**
     * {@inheritdoc}
     */
    public function langPath()
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang');
    }

    /**
     * {@inheritdoc}
     */
    public function storagePath()
    {
        return ($this->appPath . DIRECTORY_SEPARATOR . 'storage');
    }

    /**
     * Get path prefixed by directory separator if not empty.
     *
     * @param string $path
     * @return string
     */
    protected function getSuffixPath($path = '')
    {
        return ($path ? (DIRECTORY_SEPARATOR . $path) : '');
    }
}

Add docs and update constructor signature


<?php
/**
 * @author         Pierre-Henry Soria <hi@ph7.me>
 * @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 / Core / Class
 */

namespace PH7;

class UserMilestoneCore
{
    const NUMBER_USERS = [
        100,
        500,
        1000,
        2500,
        5000,
        7500,
        10000,
        25000,
        50000,
        100000,
        250000,
        500000,
        1000000 // Congrats!
    ];

    /** @var UserCoreModel */
    private $oUserModel;

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

    /**
     * @return bool
     */
    public function isTotalUserReached()
    {
        return in_array($this->oUserModel->total(), self::NUMBER_USERS, true);
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <hi@ph7.me>
 * @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 / Core / Class
 */

namespace PH7;

class UserMilestoneCore
{
    const NUMBER_USERS = [
        100,
        500,
        1000,
        2500,
        5000,
        7500,
        10000,
        25000,
        50000,
        100000,
        250000,
        500000,
        1000000 // Congrats!
    ];

    /** @var UserCoreModel */
    private $oUserModel;

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

    /**
     * @return bool
     */
    public function isTotalUserReached()
    {
        return in_array(
            $this->oUserModel->total(),
            self::NUMBER_USERS,
            true
        );
    }
}

Change indentation; Shorter line length for better readability


<?php

namespace RH;

use RH\Model\PlayItem;

class Playlist
{
    private $items;
    private $baseUrl;

    public function __construct(array $items, $baseUrl = '')
    {
        $this->items = $items;
        $this->baseUrl = $baseUrl;
    }

    public function toArray()
    {
        return array_map(array($this, 'makeItem'), $this->items);
    }

    private function makeItem(PlayItem $playItem)
    {
        $song = $playItem->getSong();
        $attributes = array(
            'id'             => $playItem->getId(),
            'order'          => $playItem->getOrder(),
            'song_id'        => $song->getId(),
            'song_name'      => $song->getName(),
            'song_media_url' => $this->baseUrl.$song->getWebPath()
        );
        if ($artist = $song->getArtist()) {
            $attributes['song_artist_id'] = $artist->getId();
            $attributes['song_artist']    = $artist->getName();
        }
        if ($album = $song->getAlbum()) {
            $attributes['song_album_id'] = $album->getId();
            $attributes['song_album']    = $album->getName();
        }

        return $attributes;
    }
}

<?php

namespace RH;

use RH\Model\PlayItem;

class Playlist
{
    private $items;
    private $baseUrl;

    public function __construct(array $items, $baseUrl = '')
    {
        $this->items = $items;
        $this->baseUrl = $baseUrl;
    }

    public function toArray()
    {
        return array_map(array($this, 'makeItem'), $this->items);
    }

    private function makeItem(PlayItem $playItem)
    {
        $song = $playItem->getSong();
        $attributes = array(
            'id'             => $playItem->getId(),
            'order'          => $playItem->getOrder(),
            'song_id'        => $song->getId(),
            'song_name'      => $song->getName(),
            'song_media_url' => $this->baseUrl.$song->getWebPath()
        );
        if ($artist = $song->getArtist()) {
            $attributes['song_artist_id'] = $artist->getId();
            $attributes['song_artist']    = $artist->getName();
        }
        if ($album = $song->getAlbum()) {
            $attributes['song_album_id'] = $album->getId();
            $attributes['song_album']    = $album->getName();
        }

        return $attributes;
    }

    public static function shift()
    {
        //This function will change when we will implements the historiq
        //We will have to shift all playItem in the negative and keep playItem between -1 and -10.
        //Less than -10 have to be delete.
        $playItem = new PlayItem();
        $playItem = Model\PlayItemQuery::create()
                ->filterByOrder(0, \Criteria::GREATER_THAN)
                ->orderBy('order')
                ->findOne();
        if($playItem != null)
        {
            $playItem->setOrder(-1);
            $playItem->save();

            $song = $playItem->getSong();
        }
    }
}

Add the shift function to be used in the console


<?php
defined('C5_EXECUTE') or die("Access Denied.");
$nh = Loader::helper('navigation');
$parentPage = Page::getByID( $c->getCollectionParentID() );
$this->inc('elements/header.php'); ?>

      <a href='<?=$nh->getCollectionURL($parentPage)?>'>Back to <?=$parentPage->getCollectionName()?> Walks
<?=$parentPage->getCollectionName()?> Walk Blog

      <?php (new Area('Main'))->display($c); ?>

<?php  $this->inc('elements/footer.php'); ?>

<?php
defined('C5_EXECUTE') or die("Access Denied.");
$nh = Loader::helper('navigation');
$parentPage = Page::getByID( $c->getCollectionParentID() );
$this->inc('elements/header.php'); ?>

      <a href='<?=$nh->getCollectionURL($parentPage)?>'>Back to <?=$parentPage->getCollectionName()?> Walks

City Blog

<?=$parentPage->getCollectionName()?>

      <?php (new Area('Main'))->display($c); ?>

<?php  $this->inc('elements/footer.php'); ?>

Change title on city blog

Change title on city blog


<?php

include_once ('../config.php');

if ( nbt_get_privileges_for_userid ( $_SESSION[INSTALL_HASH . '_nbt_userid'] ) >= 2 ) {

    switch ($_POST['elementtype']) {

	case "single_select":

	    if ( $_POST['setnull'] == "TRUE") {
		$_POST['newvalue'] = NULL;
	    }

	    if ( nbt_update_final ( $_POST['fid'], $_POST['rsid'], $_POST['rid'], $_POST['column'], $_POST['newvalue']) ) {

		echo "Changes saved";

	    } else {

		echo "Something went wrong—changes not saved";

	    }

	    break;

	case "multi_select":

	    if ( nbt_update_final ( $_POST['fid'], $_POST['rsid'], $_POST['rid'], $_POST['column'], $_POST['newvalue']) ) {

		echo "Changes saved";

	    } else {

		echo "Something went wrong—changes not saved";

	    }

	    break;

    }

}

?>

<?php

include_once ('../config.php');

if ( nbt_get_privileges_for_userid ( $_SESSION[INSTALL_HASH . '_nbt_userid'] ) >= 2 ) {

    switch ($_POST['elementtype']) {

	case "single_select":

	    if ( $_POST['setnull'] == "TRUE") {
		$_POST['newvalue'] = "";
	    }

	    if ( nbt_update_final ( $_POST['fid'], $_POST['rsid'], $_POST['rid'], $_POST['column'], $_POST['newvalue']) ) {

		echo "Changes saved";

	    } else {

		echo "Something went wrong—changes not saved";

	    }

	    break;

	case "multi_select":

	    if ( nbt_update_final ( $_POST['fid'], $_POST['rsid'], $_POST['rid'], $_POST['column'], $_POST['newvalue']) ) {

		echo "Changes saved";

	    } else {

		echo "Something went wrong—changes not saved";

	    }

	    break;

    }

}

?>

Fix bug where single select override isn't saved in some cases


<?php

class JsonView extends ApiView
{
    /** @var array */
    private $string_fields;

    public function render($content)
    {
        $this->setHeader('Content-Type', 'application/json; charset=utf8');

        return parent::render($content);
    }

    /**
     *  Function to build output, can be used by JSON and JSONP
     */
    public function buildOutput($content)
    {
        $content = $this->addCount($content);
        // need to work out which fields should have been numbers
        // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs)

        // Specify a list of fields to NOT convert to numbers
        $this->string_fields = array("stub", "track_name", "comment");

        $output = $this->numericCheck($content);
        $retval = json_encode($output);

        return $retval;
    }

    protected function numericCheck($data)
    {
        if (! is_array($data)) {
            return $this->scalarNumericCheck('', $data);
        }
        $output = array();
        foreach ($data as $key => $value) {
            // recurse as needed
            if (is_array($value)) {
                $output[$key] = $this->numericCheck($value);
            } else {
                $output[$key] = $this->scalarNumericCheck($key, $value);
            }
        }

        return $output;
    }

    protected function scalarNumericCheck($key, $value)
    {
        if (is_numeric($value) && ! in_array($key, $this->string_fields)) {
            return (float) $value;
        }

        return $value;
    }
}

<?php

class JsonView extends ApiView
{
    /** @var array */
    protected $string_fields;

    public function render($content)
    {
        $this->setHeader('Content-Type', 'application/json; charset=utf8');

        return parent::render($content);
    }

    /**
     *  Function to build output, can be used by JSON and JSONP
     */
    public function buildOutput($content)
    {
        $content = $this->addCount($content);
        // need to work out which fields should have been numbers
        // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs)

        // Specify a list of fields to NOT convert to numbers
        $this->string_fields = array("stub", "track_name", "comment");

        $output = $this->numericCheck($content);
        $retval = json_encode($output);

        return $retval;
    }

    protected function numericCheck($data)
    {
        if (! is_array($data)) {
            return $this->scalarNumericCheck('', $data);
        }
        $output = array();
        foreach ($data as $key => $value) {
            // recurse as needed
            if (is_array($value)) {
                $output[$key] = $this->numericCheck($value);
            } else {
                $output[$key] = $this->scalarNumericCheck($key, $value);
            }
        }

        return $output;
    }

    protected function scalarNumericCheck($key, $value)
    {
        if (is_numeric($value) && ! in_array($key, $this->string_fields)) {
            return (float) $value;
        }

        return $value;
    }
}

Change property visibility so it can be used by subclasses


<?php

use Benrowe\Laravel\Config\Config;

/**
 * Tests to ensure invalid data is not allowed into the config (data that can't be persisted)
 */
class InvalidConfigTest extends PHPUnit_Framework_TestCase
{
    public function testNullData()
    {
        // invalid data
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(null);

    }

    public function testNonScalarData()
    {
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(new stdClass);
    }

    /**
     * Ensure that non-scalar values are not valid
     */
    public function testNonScalarValue()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $cfg->set('newkey', new stdClass);
    }

    /**
     * Ensure that objects in arrays are not allowed
     */
    public function testArrayNonScalar()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $cfg->set('newkey', [new stdClass]);
    }

    public function testMultiDimentionalArrays()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $this->set('newkey', [['invalid']]);
    }
}

<?php

use Benrowe\Laravel\Config\Config;

/**
 * Tests to ensure invalid data is not allowed into the config (data that can't be persisted)
 */
class InvalidConfigTest extends PHPUnit_Framework_TestCase
{
    public function testNullData()
    {
        // invalid data
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(null);

    }

    public function testNonScalarData()
    {
        $this->setExpectedException(InvalidArgumentException::class);
        new Config(new stdClass);
    }

    /**
     * Ensure that non-scalar values are not valid
     */
    public function testNonScalarValue()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $cfg->set('newkey', new stdClass);
    }

    /**
     * Ensure that objects in arrays are not allowed
     */
    public function testArrayNonScalar()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $cfg->set('newkey', [new stdClass]);
    }

    public function testMultiDimentionalArrays()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $cfg->set('newkey', [['string']]);
    }

    public function testAssocArray()
    {
        $cfg = new Config();
        $this->setExpectedException(InvalidArgumentException::class);
        $cfg->set('newkey', ['key' => 'value']);
    }
}

Fix error in invalid data test case

Fix error in invalid data test case


<?php

$conn = mysql_connect("localhost", "root", "passw0rd");
mysql_select_db("eventrecorder", $conn);

$res = mysql_query("select * from Events", $conn);

# print_r($count);
echo "
Summary
\n";
echo "Got " . mysql_num_rows($res) . " events.\n";

$res = mysql_query("select UserName, date(DateTime) as Date from Events where Type=\"login\" group by date(DateTime);");

echo "
Logins
\n";

while ($row = mysql_fetch_assoc($res))
{
  echo "User " . $row['UserName'] . " on " . $row['Date'] . "\n";
}

?>

<?php

$conn = mysql_connect("localhost", "root", "passw0rd");
mysql_select_db("eventrecorder", $conn);

$res = mysql_query("select * from UserRegionEvents", $conn);

# print_r($count);
echo "
Summary
\n";
echo "Got " . mysql_num_rows($res) . " events.\n";

$res = mysql_query("select UserName, date(DateTime) as Date from UserRegionEvents where Type=\"login\" group by date(DateTime);");

echo "
Logins
\n";

while ($row = mysql_fetch_assoc($res))
{
  echo "User " . $row['UserName'] . " on " . $row['Date'] . "
\n";
}

?>

Update sample web page now that Events table has been renamed to UserRegionEvents


<?php

namespace Zeropingheroes\Lanager\Requests;

class StoreLanGameRequest extends Request
{
    use LaravelValidation;

    /**
     * Whether the request is valid
     *
     * @return bool
     */
    public function valid(): bool
    {
        $this->validationRules = [
            'lan_id'    => ['exists:lans,id'],
            'game_name' => ['required', 'max:255'],
        ];

        if (!$this->laravelValidationPasses()) {
            return $this->setValid(false);
        }

        return $this->setValid(true);
    }
}

<?php

namespace Zeropingheroes\Lanager\Requests;

use Zeropingheroes\Lanager\LanGame;

class StoreLanGameRequest extends Request
{
    use LaravelValidation;

    /**
     * Whether the request is valid
     *
     * @return bool
     */
    public function valid(): bool
    {
        $this->validationRules = [
            'lan_id'    => ['exists:lans,id'],
            'game_name' => ['required', 'max:255'],
        ];

        if (!$this->laravelValidationPasses()) {
            return $this->setValid(false);
        }

        $lanGamesWithSameName = LanGame::where([
                ['lan_id', '=', $this->input['lan_id']],
                ['game_name', '=', $this->input['game_name']],
            ])->count();

        if ($lanGamesWithSameName != 0) {
            $this->addError(__('phrase.game-already-submitted'));
            return $this->setValid(false);
        }

        return $this->setValid(true);
    }
}

Check if game has already been submitted


<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

error_reporting(error_reporting() & ~E_USER_DEPRECATED);

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

return $loader;

<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

return $loader;

Remove special care for E_USER_DEPRECATED


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| Application ID from openexchangerates.org
|--------------------------------------------------------------------------
|
| This will be used to load the exchange rates
| Sign up for an application id with a free plan at openexchangerates.org
| NOTE: Free plan limited to 1000 calls per month
|
*/
$config['app_id'] = 'e619241b63934a50a92e9b0a2440b3d9';

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| Application ID from openexchangerates.org
|--------------------------------------------------------------------------
|
| This will be used to load the exchange rates
| Sign up for an application id with a free plan at openexchangerates.org
| NOTE: Free plan limited to 1000 calls per month
|
*/
$config['app_id'] = '';

Remove OpenExchangeRates.org application id from the code


<?php

namespace Oro\Bundle\BatchBundle\Monolog\Handler;

use Akeneo\Bundle\BatchBundle\Monolog\Handler\BatchLogHandler as AkeneoBatchLogHandler;

use Monolog\Logger;

/**
 * Write the log into a separate log file
 */
class BatchLogHandler extends AkeneoBatchLogHandler
{
    /** @var bool */
    protected $isActive = false;

    /**
     * {@inheritDoc}
     */
    public function __construct($logDir)
    {
        $this->logDir = $logDir;

        $this->filePermission = null;
        $this->useLocking = false;

        $this->setLevel(Logger::DEBUG);
        $this->bubble = true;
    }

    /**
     * @param boolean $isActive
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;
    }

    /**
     * @return boolean
     */
    public function isActive()
    {
        return $this->isActive;
    }

    /**
     * {@inheritdoc}
     */
    public function write(array $record)
    {
        if ($this->isActive()) {
            parent::write($record);
        }
    }
}

<?php

namespace Oro\Bundle\BatchBundle\Monolog\Handler;

use Akeneo\Bundle\BatchBundle\Monolog\Handler\BatchLogHandler as AkeneoBatchLogHandler;

use Monolog\Logger;

/**
 * Write the log into a separate log file
 */
class BatchLogHandler extends AkeneoBatchLogHandler
{
    /** @var bool */
    protected $isActive = false;

    /**
     * {@inheritDoc}
     *
     * todo: Remove after update AkeneoBatchBundle to version without call of Monolog\Handler\StreamHandler constructor
     */
    public function __construct($logDir)
    {
        $this->logDir = $logDir;

        $this->filePermission = null;
        $this->useLocking = false;

        $this->setLevel(Logger::DEBUG);
        $this->bubble = true;
    }

    /**
     * @param boolean $isActive
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;
    }

    /**
     * @return boolean
     */
    public function isActive()
    {
        return $this->isActive;
    }

    /**
     * {@inheritdoc}
     */
    public function write(array $record)
    {
        if ($this->isActive()) {
            parent::write($record);
        }
    }
}

BAP-11787: Update monolog/monolog package version at least to 1.17
- added todo about upgrade akeneo batch bundle


<?php

namespace Oro\Bundle\EmailBundle\Tests\Unit\Form\Model;

use Symfony\Component\PropertyAccess\PropertyAccess;

use Oro\Bundle\EmailBundle\Form\Model\Email;

class EmailTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider propertiesDataProvider
     * @param string $property
     * @param mixed  $value
     */
    public function testSettersAndGetters($property, $value)
    {
        $obj = new Email();

        $accessor = PropertyAccess::createPropertyAccessor();
        $accessor->setValue($obj, $property, $value);
        $this->assertEquals($value, $accessor->getValue($obj, $property));
    }

    public function propertiesDataProvider()
    {
        return [
            ['gridName', 'testGridName'],
            ['entityClass', 'testEntityClass'],
            ['entityId', 123],
            ['from', 'test@example.com'],
            ['to', ['testGridName']],
            ['subject', 'testSubject'],
            ['body', 'testBody'],
            ['gridName', 'testGridName'],
            ['gridName', 'testGridName'],
            ['gridName', 'testGridName'],
            ['gridName', 'testGridName'],
        ];
    }

    public function testHasEntity()
    {
        $obj = new Email();
        $this->assertFalse($obj->hasEntity());

        $obj->setEntityClass('Test\Entity');
        $this->assertFalse($obj->hasEntity());

        $obj->setEntityId(123);
        $this->assertTrue($obj->hasEntity());

        $obj->setEntityClass(null);
        $this->assertFalse($obj->hasEntity());
    }
}

<?php

namespace Oro\Bundle\EmailBundle\Tests\Unit\Form\Model;

use Oro\Bundle\EmailBundle\Entity\EmailTemplate;
use Symfony\Component\PropertyAccess\PropertyAccess;

use Oro\Bundle\EmailBundle\Form\Model\Email;

class EmailTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider propertiesDataProvider
     * @param string $property
     * @param mixed  $value
     */
    public function testSettersAndGetters($property, $value)
    {
        $obj = new Email();

        $accessor = PropertyAccess::createPropertyAccessor();
        $accessor->setValue($obj, $property, $value);
        $this->assertEquals($value, $accessor->getValue($obj, $property));
    }

    public function propertiesDataProvider()
    {
        return [
            ['gridName', 'testGridName'],
            ['entityClass', 'testEntityClass'],
            ['entityId', 123],
            ['from', 'test@example.com'],
            ['to', ['testGridName']],
            ['subject', 'testSubject'],
            ['body', 'testBody'],
            ['gridName', 'testGridName'],
            ['template', new EmailTemplate('test')],
        ];
    }

    public function testHasEntity()
    {
        $obj = new Email();
        $this->assertFalse($obj->hasEntity());

        $obj->setEntityClass('Test\Entity');
        $this->assertFalse($obj->hasEntity());

        $obj->setEntityId(123);
        $this->assertTrue($obj->hasEntity());

        $obj->setEntityClass(null);
        $this->assertFalse($obj->hasEntity());
    }
}

CRM-1648: Adjust EmailType form type to use email templates selector
- update unit tests


<?php

namespace Oro\Bundle\EntityMergeBundle\Metadata;

use Doctrine\ORM\Mapping\ClassMetadataInfo;

class DoctrineMetadata extends Metadata implements MetadataInterface
{
    /**
     * @var string
     */
    protected $className;

    /**
     * @param string $className
     * @param array $options
     */
    public function __construct($className, array $options = [])
    {
        $this->className = $className;
        parent::__construct($options);
    }

    /**
     * Checks if this field represents simple doctrine field
     *
     * @return bool
     */
    public function isField()
    {
        return !$this->isAssociation();
    }

    /**
     * Checks if this field represents doctrine association
     *
     * @return bool
     */
    public function isAssociation()
    {
        return $this->has('targetEntity') && $this->has('joinColumns');
    }

    /**
     * Checks if this metadata relates to field that is mapped in entity
     *
     * @return bool
     */
    public function isMappedBySourceEntity()
    {
        return $this->isField() || $this->className == $this->get('sourceEntity');
    }
}

<?php

namespace Oro\Bundle\EntityMergeBundle\Metadata;

class DoctrineMetadata extends Metadata implements MetadataInterface
{
    /**
     * @var string
     */
    protected $className;

    /**
     * @param string $className
     * @param array $options
     */
    public function __construct($className, array $options = [])
    {
        $this->className = $className;
        parent::__construct($options);
    }

    /**
     * Checks if this field represents simple doctrine field
     *
     * @return bool
     */
    public function isField()
    {
        return !$this->isAssociation();
    }

    /**
     * Checks if this field represents doctrine association
     *
     * @return bool
     */
    public function isAssociation()
    {
        return $this->has('targetEntity') && $this->has('joinColumns');
    }

    /**
     * Checks if this metadata relates to field that is mapped in entity
     *
     * @return bool
     */
    public function isMappedBySourceEntity()
    {
        return $this->isField() || $this->className == $this->get('sourceEntity');
    }
}

BAP-3115: Create handler for merge result data
- updated metadata


<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

            <?php

            get_template_part(SNIPPETS_DIR . '/header/entry', 'header');
            get_template_part(SNIPPETS_DIR . '/entry', 'content');

            comments_template();

            ?>

            <?php

            if ('' !== get_the_post_thumbnail() && !is_single()) :
                get_template_part(SNIPPETS_DIR . '/post', 'thumbnail');
            endif;

            keitaro_child_pages_list(get_the_ID());

            get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks');

            ?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

            <?php

            get_template_part(SNIPPETS_DIR . '/header/entry-header');
            get_template_part(SNIPPETS_DIR . '/entry-content');

            comments_template();

            ?>

            <?php

            if ('' !== get_the_post_thumbnail() && !is_single()) :
                get_template_part(SNIPPETS_DIR . '/post-thumbnail');
            endif;

            keitaro_child_pages_list(get_the_ID());

            get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks');

            ?>

Include icon-blocks.php sidebar snippet and clean code


<?php

namespace AppBundle\Controller;

use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseAdminController;

class AdminController extends BaseAdminController
{
    public function createNewFennecUserEntity(){
        return $this->get('fos_user.user_manager')->createUser();
    }

    public function prePersistFennecUserEntity($user){
        $this->get('fos_user.user_manager')->updateUser($user, false);
    }
}

<?php

namespace AppBundle\Controller;

use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseAdminController;

class AdminController extends BaseAdminController
{
    public function createNewFennecUserEntity(){
        return $this->get('fos_user.user_manager')->createUser();
    }

    public function prePersistFennecUserEntity($user){
        $this->get('fos_user.user_manager')->updateUser($user, false);
    }

    public function preUpdateFennecUserEntity($user){
        $this->get('fos_user.user_manager')->updateUser($user, false);
    }
}

Add one more function in order to save all changes which are done with the user manager


has('purchase_date') ? ' has-error' : '' }}">
   {{ trans('general.purchase_date') }}

            <input type="text" class="form-control" placeholder="{{ trans('general.select_date') }}" name="purchase_date" id="purchase_date" value="{{ Input::old('purchase_date', $item->purchase_date) }}">

       {!! $errors->first('purchase_date', ' :message') !!}

has('purchase_date') ? ' has-error' : '' }}">
   {{ trans('general.purchase_date') }}

            <input type="text" class="form-control" placeholder="{{ trans('general.select_date') }}" name="purchase_date" id="purchase_date" value="{{ Input::old('purchase_date', $item->purchase_date->format('Y-m-d')) }}">

       {!! $errors->first('purchase_date', ' :message') !!}

Format expected checkin as Y-m-d in form


<?php declare(strict_types=1);

namespace unit\Formatters;

use Mihaeu\PhpDependencies\DependencyHelper;
use Mihaeu\PhpDependencies\Formatters\DotFormatter;

/**
 * @covers unit\Formatters\DotFormatter
 */
class DotFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function testFormatsSimpleDependencies()
    {
        $expected = 'digraph generated_by_dePHPend {'.PHP_EOL
            ."\tA -> B".PHP_EOL
            ."\tA -> D".PHP_EOL
            ."\tC -> D".PHP_EOL
            .'}'
        ;

        $this->assertEquals($expected, (new DotFormatter())->format(DependencyHelper::map('
            A --> B
            C --> D
            A --> D
        ')));
    }
}

<?php declare(strict_types=1);

namespace unit\Formatters;

use Mihaeu\PhpDependencies\DependencyHelper;
use Mihaeu\PhpDependencies\Formatters\DotFormatter;

/**
 * @covers Mihaeu\PhpDependencies\Formatters\DotFormatter
 */
class DotFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function testFormatsSimpleDependencies()
    {
        $expected = 'digraph generated_by_dePHPend {'.PHP_EOL
            ."\tA -> B".PHP_EOL
            ."\tA -> D".PHP_EOL
            ."\tC -> D".PHP_EOL
            .'}'
        ;

        $this->assertEquals($expected, (new DotFormatter())->format(DependencyHelper::map('
            A --> B
            C --> D
            A --> D
        ')));
    }
}

Fix bad namespace in @covers

Fix bad namespace in @covers


<?php

require_once('../config.php');
require_once('authenticate.php');

if (! isset($_POST['dateTime']) || ! is_string($_POST['dateTime'])) {
    header('HTTP/1.1 400 Bad Request');
    exit;
}

$log_data = file_get_contents(STORAGE_FILEPATH);

$lines = explode("\n", $log_data);
$new_lines = array();
foreach ($lines as $line) {
    if (strpos($line, $_POST['dateTime']) !== FALSE) {
         continue;
    }
    $new_lines[] = $line;
}
$log_data_new = implode("\n", $new_lines);

file_put_contents(STORAGE_FILEPATH, $log_data_new, LOCK_EX);

<?php

require_once('../config.php');
require_once('authenticate.php');

if (! isset($_POST[KEY_DATETIME]) || ! is_string($_POST[KEY_DATETIME])) {
    header('HTTP/1.1 400 Bad Request');
    exit;
}

$log_data = file_get_contents(STORAGE_FILEPATH);

$lines = explode("\n", $log_data);
$new_lines = array();
foreach ($lines as $line) {
    if (strpos($line, $_POST[KEY_DATETIME]) !== FALSE) {
        continue;
    }
    $new_lines[] = $line;
}
$log_data_new = implode("\n", $new_lines);

file_put_contents(STORAGE_FILEPATH, $log_data_new, LOCK_EX);

Refactoring: Use constants instead of hardcoded strings


<?php
 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

$suitecrm_version      = '7.4.1';
$suitecrm_timestamp    = '2015-11-10 18:00pm';

<?php
 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

$suitecrm_version      = '7.4.2';
$suitecrm_timestamp    = '2015-11-17 18:00pm';

Update SuiteCRM Version to 7.4.2.

Update SuiteCRM Version to 7.4.2.


<?php
/*
 * This file is part of the AlphaLemonThemeEngineBundle and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://alphalemon.com
 *
 * @license    MIT License
 */

namespace AlphaLemon\ElFinderBundle\Core\Connector;

/**
 * Configures the connector
 *
 * @author AlphaLemon
 */
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
    protected function configure()
    {
        $request = $this->container->get('request');

        $options = array(
            'roots' => array(
                array(
                    'driver'        => 'LocalFileSystem',   // driver for accessing file system (REQUIRED)
                    'path'          => 'bundles/alphalemonelfinder/files/',         // path to files (REQUIRED)
                    'URL'           => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/files/', // URL to files (REQUIRED)
                    'accessControl' => 'access'             // disable and hide dot starting files (OPTIONAL)
                )
            )
        );

        return $options;
    }
}

<?php
/*
 * This file is part of the AlphaLemonThemeEngineBundle and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://alphalemon.com
 *
 * @license    MIT License
 */

namespace AlphaLemon\ElFinderBundle\Core\Connector;

/**
 * Configures the connector
 *
 * @author AlphaLemon
 */
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
    protected function configure()
    {
        $request = $this->container->get('request');

        $options = array(
            'roots' => array(
                array(
                    'driver'        => 'LocalFileSystem',   // driver for accessing file system (REQUIRED)
                    'path'          => 'bundles/alphalemonelfinder/vendor/ElFinder/files/',         // path to files (REQUIRED)
                    'URL'           => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/vendor/ElFinder/files/', // URL to files (REQUIRED)
                    'accessControl' => 'access'             // disable and hide dot starting files (OPTIONAL)
                )
            )
        );

        return $options;
    }
}

Update the path and the url

Update the path and the url


<?php

namespace Nasyrov\Laravel\Imgix;

use Illuminate\Support\ServiceProvider;
use Imgix\ShardStrategy;
use Imgix\UrlBuilder;

class ImgixServiceProvider extends ServiceProvider
{
    const ALIAS = 'imgix';

    /**
     * Bootstrap any application services.
     */
    public function boot()
    {
        $configFile = dirname(__DIR__) . '/config/imgix.php';

        $this->mergeConfigFrom($configFile, static::ALIAS);

        $this->publishes([
            $configFile => config_path('imgix.php'),
        ], 'imgix');
    }

    /**
     * Register any application services.
     */
    public function register()
    {
        $this->app->singleton(UrlBuilder::class, function () {
            return new UrlBuilder(
                config('imgix.domains', []),
                config('imgix.useHttps', false),
                config('imgix.signKey', ''),
                config('imgix.shardStrategy', ShardStrategy::CRC),
                config('imgix.includeLibraryParam', true)
            );
        });

        $this->app->singleton(Imgix::class, function ($app) {
            return new Imgix($app[UrlBuilder::class]);
        });

        $this->app->alias(Imgix::class, static::ALIAS);
    }
}

<?php

namespace Nasyrov\Laravel\Imgix;

use Illuminate\Support\ServiceProvider;
use Imgix\ShardStrategy;
use Imgix\UrlBuilder;

class ImgixServiceProvider extends ServiceProvider
{
    const ALIAS = 'imgix';

    /**
     * Bootstrap any application services.
     */
    public function boot()
    {
        $configFile = dirname(__DIR__) . '/config/imgix.php';

        $this->mergeConfigFrom($configFile, static::ALIAS);

        $this->publishes([
            $configFile => config_path('imgix.php'),
        ], static::ALIAS);
    }

    /**
     * Register any application services.
     */
    public function register()
    {
        $this->app->singleton(UrlBuilder::class, function () {
            return new UrlBuilder(
                config('imgix.domains'),
                config('imgix.useHttps', false),
                config('imgix.signKey', ''),
                config('imgix.shardStrategy', ShardStrategy::CRC),
                config('imgix.includeLibraryParam', true)
            );
        });

        $this->app->singleton(Imgix::class, function ($app) {
            return new Imgix($app[UrlBuilder::class]);
        });

        $this->app->alias(Imgix::class, static::ALIAS);
    }
}

Remove default value for domain configuration


<?php

namespace Ds\Bundle\PortalBundle\Event\Listener;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\DataCollectorTranslator;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Class LocaleListener
 */
class LocaleListener
{
    /**
     * @var \Symfony\Component\HttpFoundation\RequestStack
     */
    protected $stack;

    /**
     * @var \Symfony\Component\Translation\DataCollectorTranslator
     */
    protected $translator;

    /**
     * Constructor
     *
     * @param \Symfony\Component\HttpFoundation\RequestStack $stack
     * @param \Symfony\Component\Translation\DataCollectorTranslator $translator
     */
    public function __construct(RequestStack $stack, DataCollectorTranslator $translator)
    {
        $this->stack = $stack;
        $this->translator = $translator;
    }

    /**
     * On kernel request
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $this->translator->setLocale($this->stack->getCurrentRequest()->getLocale());
    }
}

<?php

namespace Ds\Bundle\PortalBundle\Event\Listener;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\DataCollectorTranslator;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Class LocaleListener
 */
class LocaleListener
{
    /**
     * @var \Symfony\Component\HttpFoundation\RequestStack
     */
    protected $stack;

    /**
     * @var \Symfony\Component\Translation\DataCollectorTranslator
     */
    protected $translator;

    /**
     * Constructor
     *
     * @param \Symfony\Component\HttpFoundation\RequestStack $stack
     * @param \Symfony\Component\Translation\DataCollectorTranslator $translator
     */
    public function __construct(RequestStack $stack, DataCollectorTranslator $translator)
    {
        $this->stack = $stack;
        $this->translator = $translator;
    }

    /**
     * On kernel request
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $route = $this->stack->getCurrentRequest()->get('_route');

        //@todo change this condition to something appropriate.
        if (!preg_match('/^ds_portal/', $route)) {
            return;
        }

        $this->translator->setLocale($this->stack->getCurrentRequest()->getLocale());
    }
}

Add condition to locale listener to only apply for portal bundles.


<?php
/**
 * Template for displaying the footer
 *
 * Description for template.
 *
 * @Author: Roni Laukkarinen
 * @Date: 2020-05-11 13:33:49
 * @Last Modified by: Roni Laukkarinen
 * @Last Modified time: 2020-05-11 13:33:49
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 * @package air-light
 */

namespace Air_Light;

?>

  <?php get_template_part( 'template-parts/footer/demo-content' ); ?>

  <?php echo esc_html_e( 'Back to top', 'air-light' ); ?><?php include get_theme_file_path( '/svg/chevron-up.svg' ); ?>

<?php wp_footer(); ?>

Hide back to top link from screen readers


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class IndexTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index');
    }

    public function testIndexHasNoItems(Client $client): void
    {
        $this->login($client);

        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/content_blocks/index',
            [
                'There are no items yet.',
                'Add content block',
            ]
        );
    }
}

<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class IndexTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index');
    }

    public function testIndexHasNoItems(Client $client): void
    {
        $this->login($client);

        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/content_blocks/index',
            [
                'There are no content blocks yet.',
                'Add content block',
                'Add a content block',
            ]
        );
    }
}

Fix content block test failing because of layout changes


<?php namespace VotingApp\Providers;

use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider {

    /**
     * The validator instance
     *
     * @var \Illuminate\Validation\Factory
     */
    protected $validator;

	/**
	 * Bootstrap the application services.
	 *
	 * @return void
	 */
	public function boot()
	{
        $this->validator = $this->app->make('validator');

        $this->validator->extend('phone', function($attribute, $value, $parameters)
        {
            $phoneRegex = '/^((1)?([\-\s\.]{1})?)?\(?([0-9]{3})\)?(?:[\-\s\.]{1})?([0-9]{3})(?:[\-\s\.]{1})?([0-9]{4})/';

            return preg_match($phoneRegex, $value);
        }, 'The :attribute must be a valid phone number.');
	}

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

}

<?php namespace VotingApp\Providers;

use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider {

    /**
     * The validator instance
     *
     * @var \Illuminate\Validation\Factory
     */
    protected $validator;

	/**
	 * Bootstrap the application services.
	 *
	 * @return void
	 */
	public function boot()
	{
        $this->validator = $this->app->make('validator');

        $this->validator->extend('phone', function($attribute, $value, $parameters)
        {
            $phoneRegex = '/^(?:\+?([0-9]{1,3})([\-\s\.]{1})?)?\(?([0-9]{3})\)?(?:[\-\s\.]{1})?([0-9]{3})(?:[\-\s\.]{1})?([0-9]{4})/';

            return preg_match($phoneRegex, $value);
        }, 'The :attribute must be a valid phone number.');
	}

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

}

Validate UK phone numbers correctly.

Validate UK phone numbers correctly.


<?php

namespace DB;

abstract class AbstractFillable {
	/**
	 * Makes the class' properties fillable from an array/object for easy instantiation
	 *
	 * @param array|object
	 */
	public function __construct($iteratable = null){
		if (!empty($iteratable)){
			foreach ($iteratable as $k => $v)
				if (property_exists(__CLASS__, $k))
					$this->{$k} = $v;
		}
	}
}

<?php

namespace DB;

abstract class AbstractFillable {
	/**
	 * Makes the class' properties fillable from an array/object for easy instantiation
	 *
	 * @param array|object
	 */
	public function __construct($iteratable = null){
		if (!empty($iteratable)){
			foreach ($iteratable as $k => $v)
				if (property_exists(get_called_class(), $k))
					$this->$k = $v;
		}
	}
}

Make fillable classes actually fillable (__CLASS__ broke it)


<?php
return [
    'module_layouts' => [
        'ZfcUser' => 'layout/layout-small-header.phtml',
        'ZfModule' => 'layout/layout-small-header.phtml',
    ],
    'asset_manager' => [
        'caching' => [
            'default' => [
                'cache'     => 'FilePath',  // Apc, FilePath, FileSystem etc.
                'options' => [
                    'dir' => 'public',
                ],
            ],
        ],
    ],
    'service_manager' => [
        'factories' => [
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ],
        'invokables' => [
            'Zend\Session\SessionManager' => 'Zend\Session\SessionManager',
        ],
    ],
    'db' => [
        'driver'    => 'pdo',
        'dsn'       => 'mysql:dbname=modules;host=localhost',
        'username'  => 'modules',
        'password'  => 'modules',
    ],
];

<?php
return [
    'module_layouts' => [
        'User' => 'layout/layout-small-header.phtml',
        'ZfcUser' => 'layout/layout-small-header.phtml',
        'ZfModule' => 'layout/layout-small-header.phtml',
    ],
    'asset_manager' => [
        'caching' => [
            'default' => [
                'cache'     => 'FilePath',  // Apc, FilePath, FileSystem etc.
                'options' => [
                    'dir' => 'public',
                ],
            ],
        ],
    ],
    'service_manager' => [
        'factories' => [
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ],
        'invokables' => [
            'Zend\Session\SessionManager' => 'Zend\Session\SessionManager',
        ],
    ],
    'db' => [
        'driver'    => 'pdo',
        'dsn'       => 'mysql:dbname=modules;host=localhost',
        'username'  => 'modules',
        'password'  => 'modules',
    ],
];

Use small header layout in User module

Enhancement: Use small header layout in User module


<?php

namespace UoMCS\OpenBadges\Backend;

class Issuer extends Base
{
  public $data = array(
    'id' => null,
    'name' => null,
    'url' => null,
    'description' => null,
    'image' => null,
    'email' => null,
  );

  protected static $table_name = 'issuers';

  /**
   * Get the URL for this badge.
   *
   * @return string
   */
  public function getUrl()
  {
    return WEB_SERVER_BASE_URL . '/issuers/' . $this->data['id'];
  }
}

<?php

namespace UoMCS\OpenBadges\Backend;

class Issuer extends Base
{
  public $data = array(
    'id' => null,
    'name' => null,
    'url' => null,
    'description' => null,
    'image' => null,
    'email' => null,
  );

  protected static $table_name = 'issuers';

  /**
   * Get the URL for this badge.
   *
   * @return string
   */
  public function getUrl()
  {
    return WEB_SERVER_BASE_URL . '/issuers/' . $this->data['id'];
  }

  public function getResponseData()
  {
    $data = $this->data;

    // Remove unnecessary fields
    unset($data['id']);

    if (empty($data['description']))
    {
      unset($data['description']);
    }

    if (empty($data['image']))
    {
      unset($data['image']);
    }

    if (empty($data['email']))
    {
      unset($data['email']);
    }

    return $data;
  }
}

Remove unnecessary fields from response data


<?php

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

use Symfony\Component\VarDumper\VarDumper;

if (!function_exists('dump')) {
    /**
     * @author Nicolas Grekas <p@tchwork.com>
     */
    function dump($var, ...$moreVars)
    {
        VarDumper::dump($var);

        foreach ($moreVars as $v) {
            VarDumper::dump($v);
        }

        if (1 < func_num_args()) {
            return func_get_args();
        }

        return $var;
    }
}

if (!function_exists('dd')) {
    function dd($var, ...$moreVars)
    {
        VarDumper::dump($var);

        foreach ($moreVars as $v) {
            VarDumper::dump($v);
        }

        exit(1);
    }
}

<?php

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

use Symfony\Component\VarDumper\VarDumper;

if (!function_exists('dump')) {
    /**
     * @author Nicolas Grekas <p@tchwork.com>
     */
    function dump($var, ...$moreVars)
    {
        VarDumper::dump($var);

        foreach ($moreVars as $v) {
            VarDumper::dump($v);
        }

        if (1 < func_num_args()) {
            return func_get_args();
        }

        return $var;
    }
}

if (!function_exists('dd')) {
    function dd(...$vars)
    {
        foreach ($vars as $v) {
            VarDumper::dump($v);
        }

        die(1);
    }
}

[VarDumper] Allow dd() to be called without arguments


<?php

class Af_FacebookFeedImages extends Plugin {

	private $host;

	function about() {
		return array(
			1.0,
			"Insert larger images in Facebook feeds.",
			"kuc"
		);
	}

	function api_version() {
		return 2;
	}

	function init($host) {
		$this->host = $host;
		$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
	}

	function hook_article_filter($article) {
		$owner_uid = $article["owner_uid"];

		if (strpos($article["link"], "facebook.com/photo.php") !== FALSE) {
			if (strpos($article["plugin_data"], "facebookfeedimages,$owner_uid:") === FALSE) {
				if (strpos($article["content"], '_s.jpg"') !== FALSE) {
					$article["content"] = str_replace('_s.jpg"', '_n.jpg"', $article["content"]);
					$article["plugin_data"] = "facebookfeedimages,$owner_uid:" . $article["plugin_data"];
				}
			} else if (isset($article["stored"]["content"])) {
				$article["content"] = $article["stored"]["content"];
			}
		}

		return $article;
	}
}

<?php

class Af_FacebookFeedImages extends Plugin {

	private $host;

	function about() {
		return array(
			1.1,
			"Insert larger images in Facebook feeds.",
			"kuc"
		);
	}

	function api_version() {
		return 2;
	}

	function init($host) {
		$this->host = $host;
		$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
	}

	function hook_article_filter($article) {
		$owner_uid = $article["owner_uid"];

		if (strpos($article["link"], "https://www.facebook.com/") === 0) {
			if (strpos($article["plugin_data"], "facebookfeedimages,$owner_uid:") === FALSE) {
				if (strpos($article["content"], '_s.jpg"') !== FALSE) {
					$article["content"] = str_replace('_s.jpg"', '_n.jpg"', $article["content"]);
					$article["plugin_data"] = "facebookfeedimages,$owner_uid:" . $article["plugin_data"];
				}
			} else if (isset($article["stored"]["content"])) {
				$article["content"] = $article["stored"]["content"];
			}
		}

		return $article;
	}
}

Fix bug in detecting facebook feeds

Fix bug in detecting facebook feeds


<?php
namespace DexBarrett\ClockworkSms\Test;

use PHPUnit_Framework_TestCase;
use Mockery;

abstract class AbstractTest extends PHPUnit_Framework_TestCase
{
    protected function tearDown()
    {
        Mockery::close();
    }

    public function getFixtureContent($fixtureName)
    {
        return file_get_contents(__DIR__ . "/fixtures/{$fixtureName}.txt");
    }
}

<?php
namespace DexBarrett\ClockworkSms\Test;

use PHPUnit_Framework_TestCase;
use Mockery;

abstract class AbstractTest extends PHPUnit_Framework_TestCase
{
    protected function tearDown()
    {
        Mockery::close();
    }

    public function getFixtureContent($fixtureName)
    {
        return file_get_contents(__DIR__ . "/Fixtures/{$fixtureName}.txt");
    }
}

Fix folder name reference for fixtures

Fix folder name reference for fixtures


<?php

namespace Checkdomain\Holiday\Provider;

/**
 * Reunion holiday provider
 *
 * @author Julien Tessier <julien@cari.agency>
 * @since 2020-01-29
 */
class RE extends FR
{
    /**
     * @param int $year
     *
     * @return mixed
     */
    public function getHolidaysByYear($year)
    {
        // sames rules as France
        $holidays = parent::getHolidaysByYear($year);
        // but an additional date
        $holidays['12-20'] = $this->createData('Abolition de l\'Esclavage');

        return $holidays;
    }
}

<?php

namespace Checkdomain\Holiday\Provider;

/**
 * Reunion holiday provider
 *
 * @author Julien Tessier <julien@cari.agency>
 * @since 2020-01-29
 */
class RE extends FR
{
    /**
     * @param int $year
     *
     * @return mixed
     */
    public function getHolidaysByYear($year)
    {
        // sames rules as France
        $holidays = parent::getHolidaysByYear($year);

        // remove holidays for specific states
        foreach($holidays as $date => $holiday) {
            if (isset($holiday['states']) && $holiday['states']) unset($holidays[$date]);
        }
        // but an additional date
        $holidays['12-20'] = $this->createData('Abolition de l\'Esclavage');

        return $holidays;
    }
}

Reunion: Remove state-specific data inherited from France


<?php snippet_detect('html_head', array(
	'criticalcss' => false,
	'prev_next' => false,
	'prerender' => false
)); ?>

	<?php snippet('banner'); ?>

<?php echo $page->title()->smartypants()->widont(); ?>

		<?php echo figure($page->images()->first(), array(
			'crop'       => true,
			'cropratio'  => '1/2',
			'quality'    => 40,
			'caption'    => 'This is an image defined in the template, from the figure plugin.',
			'alt'        => 'Alt text defined in template'
		)); ?>

		<?php echo $page->intro()->kirbytext(); ?>
		<?php echo $page->text()->kirbytext(); ?>

		<?php snippet('share_page'); ?>

<?php snippet_detect('footer'); ?>

<?php snippet_detect('html_head', array(
	'criticalcss' => false,
	'prev_next' => false,
	'prerender' => false
)); ?>

	<?php snippet('banner'); ?>

<?php echo $page->title()->smartypants()->widont(); ?>

		<?php echo figure($page->images()->first(), array(
			'crop'       => true,
			'cropratio'  => '1/2',
			'quality'    => 78,
			'caption'    => 'This is an image defined in the template, from the figure plugin.',
			'alt'        => 'Alt text defined in template'
		)); ?>

		<?php echo $page->intro()->kirbytext(); ?>
		<?php echo $page->text()->kirbytext(); ?>

		<?php snippet('share_page'); ?>

<?php snippet_detect('footer'); ?>

Increase quality of (default) figure image.


<?php
require_once('../vendor/autoload.php');
require_once('../vendor/hafriedlander/phockito/Phockito_Globals.php');
Phockito::include_hamcrest(true);

$startTime = microtime(true);
exec('(./exec_test.sh) 2>&1 &');
$endTime = microtime(true);
$sleepTime = (($endTime-$startTime) * 1000);
echo "Took $sleepTime millis to sleep in background exec()\n";
define('EXEC_BLOCKS_ON_OUTPUT', $sleepTime > 5000);

<?php
require_once('../vendor/autoload.php');
require_once('../vendor/hafriedlander/phockito/Phockito_Globals.php');
Phockito::include_hamcrest(true);

// Some systems (e.g. OSX) don't block on commands exec()ed in the below fashion. Other systems (e.g. Travis) do.
// Systems which do block need to have their output redirected from stdout/stderr if the command being exec()ed is
// long running.
// Also, some systems (e.g. OSX) fail the tests if the output of starting WireMock is redirected (possibly because
// they're running tests in parallel?), whereas others (e.g. Travis).
// So far, there's a 1-to-1 mapping between these kinds of systems, but it's unclear if that's just chance or not.
// For now, just check which kind of system we're on, so we know whether to redirect output or not.
$startTime = microtime(true);
exec('(./exec_test.sh) 2>&1 &');
$endTime = microtime(true);
$sleepTime = (($endTime-$startTime) * 1000);
echo "Took $sleepTime millis to sleep in background exec()\n";
define('EXEC_BLOCKS_ON_OUTPUT', $sleepTime > 5000);

Add comment explaining strange exec() redirect hack


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

namespace Darvin\UserBundle\Form\Type\User;

use Darvin\UserBundle\Entity\BaseUser;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * User entity form type
 */
class UserEntityType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'class' => BaseUser::class,
                'roles' => [],
            ])
            ->setAllowedTypes('roles', 'array')
            ->setNormalizer('query_builder', function (Options $options) {
                /** @var \Doctrine\ORM\EntityManager $em */
                $em = $options['em'];
                /** @var \Darvin\UserBundle\Repository\UserRepository $repository */
                $repository = $em->getRepository($options['class']);
                $roles = $options['roles'];

                return !empty($roles) ? $repository->getByRolesBuilder($roles) : $repository->getAllBuilder();
            });
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return EntityType::class;
    }
}

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

namespace Darvin\UserBundle\Form\Type\User;

use Darvin\UserBundle\Entity\BaseUser;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * User entity form type
 */
class UserEntityType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'class'         => BaseUser::class,
                'roles'         => [],
                'query_builder' => function (Options $options) {
                    /** @var \Doctrine\ORM\EntityManager $em */
                    $em = $options['em'];
                    /** @var \Darvin\UserBundle\Repository\UserRepository $repository */
                    $repository = $em->getRepository($options['class']);
                    $roles = $options['roles'];

                    return !empty($roles) ? $repository->getByRolesBuilder($roles) : $repository->getAllBuilder();
                },
            ])
            ->setAllowedTypes('roles', 'array');
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return EntityType::class;
    }
}

Use options resolver defaults instead of normalizer in form types.


<?php

namespace Form\Listener;

use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Form\Shared\UrlResolver;

/**
 * Follows a submitted URL to find the actual protocol and final address
 *
 */
class GetResolvedUrlListener implements EventSubscriberInterface
{

    public function onSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if ($data === '') {
            return;
        }

        if ($data === null) {
            return;
        }

        $resolver = new UrlResolver();
        try {
            $redirectURL = $resolver->resolve($data);
            $event->setData($redirectURL);
        } catch (\Exception $e) {
            // We can do nothing with this now, this will be caught by the constraint
        }
    }

    public static function getSubscribedEvents()
    {
        return array(FormEvents::SUBMIT => 'onSubmit');
    }
}

<?php

namespace Form\Listener;

use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Form\Shared\UrlResolver;

/**
 * Follows a submitted URL to find the actual protocol and final address
 *
 */
class GetResolvedUrlListener implements EventSubscriberInterface
{

    public function onSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if ($data === '') {
            return;
        }

        if ($data === null) {
            return;
        }

        $resolver = new UrlResolver();
        try {
            $redirectURL = $resolver->resolve($data);
            $event->setData($redirectURL);
        } catch (\Exception $e) {
            // We can do nothing with this now, this will be caught by the constraint
        }
    }

    public static function getSubscribedEvents()
    {
        return [FormEvents::SUBMIT => 'onSubmit'];
    }
}

Move from old to new array notation in one file

StyleCI complained about that....


<?php

namespace SumoCoders\FrameworkMultiUserBundle\Form;

use SumoCoders\FrameworkMultiUserBundle\DataTransferObject\RequestPasswordDataTransferObject;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RequestPasswordType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'userName',
                'text',
                [
                    'label' => 'sumocoders.multiuserbundle.form.user',
                    'required' => true,
                ]
            )->add(
                'submit',
                'submit',
                [
                    'label' => 'sumocoders.multiuserbundle.form.request_password',
                ]
            );
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => RequestPasswordDataTransferObject::class,
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'request_password';
    }
}

<?php

namespace SumoCoders\FrameworkMultiUserBundle\Form;

use SumoCoders\FrameworkMultiUserBundle\DataTransferObject\RequestPasswordDataTransferObject;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RequestPasswordType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'userName',
                TextType::class,
                [
                    'label' => 'sumocoders.multiuserbundle.form.user',
                    'required' => true,
                ]
            )->add(
                'submit',
                SubmitType::class,
                [
                    'label' => 'sumocoders.multiuserbundle.form.request_password',
                ]
            );
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => RequestPasswordDataTransferObject::class,
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'request_password';
    }
}

Use class constants instead of strings

Use class constants instead of strings


<?php
namespace Mapbender\DataSourceBundle;

use Mapbender\CoreBundle\Component\MapbenderBundle;

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

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

<?php
namespace Mapbender\DataSourceBundle;

use Mapbender\CoreBundle\Component\MapbenderBundle;

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

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

Remove prototype manager controller routes


<?php
declare(strict_types=1);

namespace Cundd\TestFlight;

interface Constants
{
    const VERSION = '0.2.6';

    const TEST_KEYWORD = '@test';
    const EXAMPLE_KEYWORD = '@example';
    const CODE_KEYWORD = '<code>';
    const MARKDOWN_PHP_CODE_KEYWORD = '```php';

    const TEST_TYPE_DOCUMENTATION = 'documentation';
    const TEST_TYPE_DOC_COMMENT = 'doccomment';
    const TEST_TYPE_METHOD = 'method';
}

<?php
declare(strict_types=1);

namespace Cundd\TestFlight;

interface Constants
{
    const VERSION = '0.3.0';

    const TEST_KEYWORD = '@test';
    const EXAMPLE_KEYWORD = '@example';
    const CODE_KEYWORD = '<code>';
    const MARKDOWN_PHP_CODE_KEYWORD = '```php';

    const TEST_TYPE_DOCUMENTATION = 'documentation';
    const TEST_TYPE_DOC_COMMENT = 'doccomment';
    const TEST_TYPE_METHOD = 'method';
}

Raise version number to 0.3.0

Raise version number to 0.3.0


<?php

namespace jvwp;

use FlorianWolters\Component\Util\Singleton\SingletonTrait;

class Templates
{
    use SingletonTrait;

    private $twigLoader;
    private $twigEnvironment;

    function __construct ()
    {
        $this->twigLoader      = new \Twig_Loader_Filesystem(array());
        $this->twigEnvironment = new \Twig_Environment($this->twigLoader);
    }

    /**
     * Adds a path where templates are stored.
     *
     * @param string $path      A path where to look for templates
     * @param string $namespace The namespace to associate the path with
     *
     * @throws \Twig_Error_Loader
     */
    public static function addPath ($path, $namespace = \Twig_Loader_Filesystem::MAIN_NAMESPACE)
    {
        $twigLoader = self::getInstance()->twigLoader;
        /* @var $twigLoader \Twig_Loader_Filesystem */
        $twigLoader->addPath($path, $namespace);
    }

    /**
     * Gets the template with the given name.
     *
     * @param string $name
     *
     * @return \Twig_Template
     */
    public static function getTemplate ($name)
    {
        return self::getInstance()->getTwigEnvironment()->loadTemplate($name);
    }

    /**
     * @return \Twig_Environment;
     */
    public function getTwigEnvironment ()
    {
        return $this->twigEnvironment;
    }
}

<?php

namespace jvwp;

use FlorianWolters\Component\Util\Singleton\SingletonTrait;

class Templates
{
    use SingletonTrait;

    private $twigLoader;
    private $twigEnvironment;

    function __construct ()
    {
        $this->twigLoader      = new \Twig_Loader_Filesystem(array());
        $this->twigEnvironment = new \Twig_Environment($this->twigLoader);

        self::extendTwig($this->twigEnvironment);
    }

    /**
     * Adds the WP-specific filters and functions to the twig environment
     * @param \Twig_Environment $twig_Environment
     */
    private static function extendTwig (\Twig_Environment $twig_Environment)
    {
        $twig_Environment->addFilter('__', new \Twig_SimpleFilter('__', function ($text, $domain = 'default') {
            return __($text, $domain);
        }));
    }

    /**
     * Adds a path where templates are stored.
     *
     * @param string $path      A path where to look for templates
     * @param string $namespace The namespace to associate the path with
     *
     * @throws \Twig_Error_Loader
     */
    public static function addPath ($path, $namespace = \Twig_Loader_Filesystem::MAIN_NAMESPACE)
    {
        $twigLoader = self::getInstance()->twigLoader;
        /* @var $twigLoader \Twig_Loader_Filesystem */
        $twigLoader->addPath($path, $namespace);
    }

    /**
     * Gets the template with the given name.
     *
     * @param string $name
     *
     * @return \Twig_Template
     */
    public static function getTemplate ($name)
    {
        return self::getInstance()->getTwigEnvironment()->loadTemplate($name);
    }

    /**
     * @return \Twig_Environment;
     */
    public function getTwigEnvironment ()
    {
        return $this->twigEnvironment;
    }
}

Add the WordPress i18n as a filter to twig


<?php

namespace Doctrine\Tests\Common\Annotations\Ticket;

use Doctrine\Tests\Common\Annotations\Fixtures\Controller;

/**
 * @group
 */
class DCOM55Test extends \PHPUnit_Framework_TestCase
{
    public function testIssue()
    {
        $class = new \ReflectionClass(__NAMESPACE__ . '\\Dummy');
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        $annots = $reader->getClassAnnotations($class);

        $this->assertEquals(0, count($annots));
    }
}

/**
 * @Controller
 */
class Dummy
{

}

<?php

namespace Doctrine\Tests\Common\Annotations\Ticket;

use Doctrine\Tests\Common\Annotations\Fixtures\Controller;

/**
 * @group
 */
class DCOM55Test extends \PHPUnit_Framework_TestCase
{
    public function testIssue()
    {
        $class = new \ReflectionClass(__NAMESPACE__ . '\\Dummy');
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        $annots = $reader->getClassAnnotations($class);

        $this->assertEquals(0, count($annots));
    }

    public function testAnnotation()
    {
        $class = new \ReflectionClass(__NAMESPACE__ . '\\DCOM55Consumer');
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        $annots = $reader->getClassAnnotations($class);

        $this->assertEquals(1, count($annots));
        $this->assertInstanceOf(__NAMESPACE__.'\\DCOM55Annotation', $annots[0]);
    }

    public function testParseAnnotationDocblocks()
    {
        $class = new \ReflectionClass(__NAMESPACE__ . '\\DCOM55Annotation');
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        $annots = $reader->getClassAnnotations($class);

        $this->assertEquals(0, count($annots));
    }
}

/**
 * @Controller
 */
class Dummy
{

}

/**
 * @Annotation
 */
class DCOM55Annotation
{

}

/**
 * @DCOM55Annotation
 */
class DCOM55Consumer
{

}

Remove last concept of \\Annotation matching and introduce check for either Doctrine\Common\Annotations\Annotation or for @Annotation in the class level docblock


<?php

/**
 * Use this class to transform a html/a url to a pdf
 *
 * @package Snappy
 * @author Matthieu Bontemps<matthieu.bontemps@knplabs.com>
 */
class SnappyPdf extends SnappyMedia
{
    protected $defaultExtension = 'pdf';
    protected $options = array(
        'ignore-load-errors' => null,                          // old v0.9
        'lowquality' => true,
    );

}

<?php

/**
 * Use this class to transform a html/a url to a pdf
 *
 * @package Snappy
 * @author Matthieu Bontemps<matthieu.bontemps@knplabs.com>
 */
class SnappyPdf extends SnappyMedia
{
    protected $defaultExtension = 'pdf';
    protected $options = array(
        'ignore-load-errors' => null,                          // old v0.9
        'lowquality' => true,
        'username' => null,
        'password' => null,
    );

}

Add http auth in snappy pdf

Add http auth in snappy pdf


<?php

/**
 * Solr data helper
 *
 * @category Asm
 * @package Asm_Solr
 * @author Ingo Renner <ingo@infielddesign.com>
 */
class Asm_Solr_Helper_Data extends Mage_Core_Helper_Abstract
{

	public function getProductDocumentId($productId) {
		// TODO replace ### with site hash
		$documentId = '###/product/' . $productId;

		return $documentId;
	}

}

<?php

/**
 * Solr data helper
 *
 * @category Asm
 * @package Asm_Solr
 * @author Ingo Renner <ingo@infielddesign.com>
 */
class Asm_Solr_Helper_Data extends Mage_Core_Helper_Abstract
{

	public function getProductDocumentId($productId) {
		// TODO replace ### with site hash
		$documentId = '###/' . Mage_Catalog_Model_Product::ENTITY . '/' . $productId;

		return $documentId;
	}

}

Use product entity constant for document Id


<?php
/**
 * mbp-logging-reports.php
 *
 * A producer to create reports based on logged data in mb-logging-api.
 */

use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users;

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/mbp-logging-reports.config.inc';

if (isset($_GET['source'])) {
  $source = $_GET['source'];
}
elseif (isset($argv[1])) {
  $source = $argv[1];
}
else {
  $source = 'all';
}

echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;

try {

  // Kick off
  $mbpLoggingReport = new MBP_LoggingReports_Users();

  // Gather digest message mailing list
  $mbpLoggingReport->report('runningMonth', $source);
}
catch(Exception $e) {
  echo $e->getMessage(), PHP_EOL;
}

echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;

<?php
/**
 * mbp-logging-reports.php
 *
 * A producer to create reports based on logged data in mb-logging-api.
 */

use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users;

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/mbp-logging-reports.config.inc';

if (isset($_GET['source'])) {
  $source[0] = $_GET['source'];
}
elseif (isset($argv[1])) {
  $source[0] = $argv[1];
}
// all
else {
  $source = [
    'niche',
    'afterschool'
  ];
}

echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;

try {

  // Kick off
  $mbpLoggingReport = new MBP_LoggingReports_Users();

  // Gather digest message mailing list
  $mbpLoggingReport->report('runningMonth', $sources);
}
catch(Exception $e) {
  echo $e->getMessage(), PHP_EOL;
}

echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;

Support sources rather than source

Support sources rather than source


<?php

declare(strict_types=1);

namespace Overblog\GraphQLBundle\Config\Parser;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Overblog\GraphQLBundle\Config\Parser\MetadataParser\MetadataParser;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use Reflector;
use RuntimeException;

class AnnotationParser extends MetadataParser
{
    const METADATA_FORMAT = '@%s';

    protected static ?AnnotationReader $annotationReader = null;

    protected static function getMetadatas(Reflector $reflector): array
    {
        $reader = self::getAnnotationReader();

        switch (true) {
            case $reflector instanceof ReflectionClass: return $reader->getClassAnnotations($reflector);
            case $reflector instanceof ReflectionMethod: return $reader->getMethodAnnotations($reflector);
            case $reflector instanceof ReflectionProperty: return $reader->getPropertyAnnotations($reflector);
        }

        return [];
    }

    protected static function getAnnotationReader(): AnnotationReader
    {
        if (null === self::$annotationReader) {
            if (!class_exists(AnnotationReader::class) ||
                !class_exists(AnnotationRegistry::class)) {
                throw new RuntimeException('In order to use graphql annotation, you need to require doctrine annotations');
            }

            AnnotationRegistry::registerLoader('class_exists');
            self::$annotationReader = new AnnotationReader();
        }

        return self::$annotationReader;
    }
}

<?php

declare(strict_types=1);

namespace Overblog\GraphQLBundle\Config\Parser;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Overblog\GraphQLBundle\Config\Parser\MetadataParser\MetadataParser;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use Reflector;
use RuntimeException;

class AnnotationParser extends MetadataParser
{
    const METADATA_FORMAT = '@%s';

    protected static ?AnnotationReader $annotationReader = null;

    protected static function getMetadatas(Reflector $reflector): array
    {
        $reader = self::getAnnotationReader();

        switch (true) {
            case $reflector instanceof ReflectionClass: return $reader->getClassAnnotations($reflector);
            case $reflector instanceof ReflectionMethod: return $reader->getMethodAnnotations($reflector);
            case $reflector instanceof ReflectionProperty: return $reader->getPropertyAnnotations($reflector);
        }

        return [];
    }

    protected static function getAnnotationReader(): AnnotationReader
    {
        if (null === self::$annotationReader) {
            if (!class_exists(AnnotationReader::class) ||
                !class_exists(AnnotationRegistry::class)) {
                // @codeCoverageIgnoreStart
                throw new RuntimeException('In order to use graphql annotation, you need to require doctrine annotations');
                // @codeCoverageIgnoreEnd
            }

            AnnotationRegistry::registerLoader('class_exists');
            self::$annotationReader = new AnnotationReader();
        }

        return self::$annotationReader;
    }
}

Exclude missing annotations from coverage


<?php
namespace Sjoerdmaessen\MachineLearning\Preprocessor;

/**
 * Class Scale
 * @package Sjoerdmaessen\MachineLearning\Preprocessor
 */
class Scale
{
    /**
     * Rescales a number from one scale to a number on another scale
     */
    static public function rescale($value, $currentMin = 0, $currentMax = 100, $newMin = 0, $newMax = 1)
    {
        return $newMin + ($newMax - $newMin) * (($value - $currentMin) / ($currentMax - $currentMin));
    }

}

<?php
namespace Sjoerdmaessen\MachineLearning\Preprocessor;

/**
 * Class Scale
 * @package Sjoerdmaessen\MachineLearning\Preprocessor
 */
class Scale
{
    /**
     * Rescales a number from one scale to a number on another scale
     *
     * @param array|float|int $input
     * @param int $currentMin
     * @param int $currentMax
     * @param int $newMin
     * @param int $newMax
     */
    static public function rescale($input, $currentMin = 0, $currentMax = 100, $newMin = 0, $newMax = 1)
    {
        if (is_array($input)) {
            foreach ($input as &$value) {
                $value = $newMin + ($newMax - $newMin) * (($value - $currentMin) / ($currentMax - $currentMin));
            }
        } else {
            $input = $newMin + ($newMax - $newMin) * (($input - $currentMin) / ($currentMax - $currentMin));
        }

        return $input;
    }

}

Support scaling multiple values at once

Support scaling multiple values at once


<?php
namespace Tev\Commands;

use WP_CLI;
use WP_CLI_Command;
use quick_cache;

/**
 * Manage the Quick Cache plugin.
 */
class QuickCacheCommand extends WP_CLI_Command
{
    /**
     * Clear the cache.
     */
    public function clear($args = array(), $assoc_args = array())
    {
        $wiped = quick_cache::wipe();

        WP_CLI::success("$wiped file(s) were cleared from the cache.");
    }
}

<?php
namespace Tev\Commands;

use WP_CLI;
use WP_CLI_Command;
use quick_cache;

/**
 * Manage the Quick Cache plugin.
 */
class QuickCacheCommand extends WP_CLI_Command
{
    /**
     * Clear the cache.
     */
    public function clear($args = array(), $assoc_args = array())
    {
        if (defined('WP_CACHE') && WP_CACHE && class_exists('\quick_cache')) {
            $wiped = quick_cache::wipe();
            WP_CLI::success("$wiped file(s) were cleared from the cache.");
        } else {
            WP_CLI::warning('Quick Cache is not installed or enabled');
        }
    }
}

Handle case where Quick Cache is not enabled