<?php
/**
 * Factory to create RunSingle object
 *
 * @author    Matthias Gisder <matthias@ingenerator.com>
 * @copyright 2014 inGenerator Ltd
 * @licence   BSD
 */

namespace Ingenerator\RunSingle;

use \Ingenerator\RunSingle\PdoDatabaseObject;

class Factory
{

    const DB_DRIVER_FACTORY_FILE = 'run_single_config.php';

    public static function create()
    {
        $driver_factory_file_path = realpath('./').'/'.self::DB_DRIVER_FACTORY_FILE;
        if (! file_exists($driver_factory_file_path)) {
            throw new \Exception('Please create '.$driver_factory_file_path.' (you can find a template in src/Ingenerator/RunSingle/'.self::DB_DRIVER_FACTORY_FILE.').');
        }

        $logger = new ConsoleLogger;

        $driver = include($driver_factory_file_path);
        $driver->set_logger($logger);

        $lock_holder = new IpLockHolder;

        $runner    = new CommandRunner;
        $runsingle = new RunSingle($driver, $runner, $logger, $lock_holder);

        return $runsingle;
    }

}

<?php
/**
 * Factory to create RunSingle object
 *
 * @author    Matthias Gisder <matthias@ingenerator.com>
 * @copyright 2014 inGenerator Ltd
 * @licence   BSD
 */

namespace Ingenerator\RunSingle;

use \Ingenerator\RunSingle\PdoDatabaseObject;

class Factory
{

    const DB_DRIVER_FACTORY_FILE = 'run_single_config.php';

    public static function create()
    {
        $driver_factory_file_path = realpath('./').'/'.self::DB_DRIVER_FACTORY_FILE;
        if (! file_exists($driver_factory_file_path)) {
            throw new \Exception('Please create '.$driver_factory_file_path.' (you can find a template in src/Ingenerator/RunSingle/'.self::DB_DRIVER_FACTORY_FILE.').');
        }

        $logger = new ConsoleLogger;

        $driver = include($driver_factory_file_path);
        $driver->set_logger($logger);

        $lock_holder = new HostnameLockHolder;

        $runner    = new CommandRunner;
        $runsingle = new RunSingle($driver, $runner, $logger, $lock_holder);

        return $runsingle;
    }

}

Use HostnameLockHolder rather than IpLockHolder.


<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015-2019, 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\AdminBundle\DependencyInjection\Compiler;

use Darvin\Utils\DependencyInjection\TaggedServiceIdsSorter;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Add dashboard widgets compiler pass
 */
class AddDashboardWidgetsPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        $blacklist = $container->getParameter('darvin_admin.dashboard.blacklist');
        $dashboard = $container->getDefinition('darvin_admin.dashboard');
        $ids       = $container->findTaggedServiceIds('darvin_admin.dashboard_widget');

        (new TaggedServiceIdsSorter())->sort($ids);

        foreach (array_keys($ids) as $id) {
            if (!in_array($id, $blacklist)) {
                $dashboard->addMethodCall('addWidget', [new Reference($id)]);
            }
        }
    }
}

<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015-2019, 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\AdminBundle\DependencyInjection\Compiler;

use Darvin\Utils\DependencyInjection\TaggedServiceIdsSorter;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Add dashboard widgets compiler pass
 */
class AddDashboardWidgetsPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        $blacklist = $container->getParameter('darvin_admin.dashboard.blacklist');
        $dashboard = $container->getDefinition('darvin_admin.dashboard');

        foreach (array_keys((new TaggedServiceIdsSorter())->sort($container->findTaggedServiceIds('darvin_admin.dashboard_widget'))) as $id) {
            if (!in_array($id, $blacklist)) {
                $dashboard->addMethodCall('addWidget', [new Reference($id)]);
            }
        }
    }
}

Refactor tagged service IDs sorter.

Refactor tagged service IDs sorter.


<?php
namespace QzPhp;

class DBConGenerator{
    public function generate($host, $database, $user, $password){
        $dsn = 'mysql:dbname=' . $database . ';host=' . $host;
        if(!empty($user)){
            $dsn .= ';username=' . $user;
        }
        if(!empty($password)){
            $dsn .= ';password=' . $password;
        }
        return $dsn;
    }
}

<?php
namespace QzPhp;

class DBConGenerator{
    public function generate($host, $database, $user, $password){
        $dsn = 'mysql:dbname=' . $database . ';host=' . $host;
        return $dsn;
    }
}

Remove additional field not used

Remove additional field not used


<?php

include_once('http.php');

class ResyncURL
{
    public $loc;

    public $lastmod;

    public $metadata = array();

    function __construct($l, $lm = '', $md = []) {
        $this->loc = $l;
        $this->lastmod = $lm;
        $this->metadata = $md;
    }

    function get() {
        return http_get($this->loc);
    }

}

<?php

class ResyncURL {

    private $loc;

    private $xml;

    function __construct($loc, $xml) {
        $this->loc = $loc;
        $this->xml = $xml;
    }

    function getLoc() {
        return $this->loc;
    }

    function getXML() {
        return $this->xml;
    }

}

Update to form basic URL class

Update to form basic URL class


<?php

$app['debug'] = true;
$app['http_cache'] = true;

$app['redis.config'] = array('host' => $_SERVER['CACHE1_HOST'], 'port' => $_SERVER['CACHE1_PORT']);

<?php

$app['debug'] = false;
$app['http_cache'] = true;

$app['redis.config'] = array('host' => $_SERVER['CACHE1_HOST'], 'port' => $_SERVER['CACHE1_PORT']);

Disable debug on Pagoda Box

Disable debug on Pagoda Box


<?php

namespace Maxmind\MinFraud;

class MinFraudResponse
{
    private $isCurlSuccessful;
    private $rawResult;

    /**
     * @param bool $isCurlSuccessful
     * @param string $result
     */
    public function __construct($isCurlSuccessful, $result)
    {
        $this->isCurlSuccessful = $isCurlSuccessful;
        $this->rawResult        = $result;
    }

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

    /**
     * @return string
     */
    public function getRawResult()
    {
        return $this->rawResult;
    }

    /**
     * @return array
     */
    public function getResult()
    {
        $result = array();
        if ($this->getIsCurlSuccessful()) {
            $keyValuePairs = explode(";", $this->getRawResult());
            foreach ($keyValuePairs as $keyValuePair) {
                $keyValue             = explode("=", $keyValuePair);
                $result[$keyValue[0]] = isset($keyValue[1]) ? $keyValue[1] : '';
            }
        }

        return $result;
    }
}

<?php

namespace Maxmind\MinFraud;

class MinFraudResponse
{
    private $isCurlSuccessful;
    private $rawResult;

    /**
     * @param bool $isCurlSuccessful
     * @param string $result
     */
    public function __construct($isCurlSuccessful, $result)
    {
        $this->isCurlSuccessful = $isCurlSuccessful;
        $this->rawResult        = mb_convert_encoding($result, 'UTF-8', 'UTF-8');
    }

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

    /**
     * @return string
     */
    public function getRawResult()
    {
        return $this->rawResult;
    }

    /**
     * @return array
     */
    public function getResult()
    {
        $result = array();
        if ($this->getIsCurlSuccessful()) {
            $keyValuePairs = explode(";", $this->getRawResult());
            foreach ($keyValuePairs as $keyValuePair) {
                $keyValue             = explode("=", $keyValuePair);
                $result[$keyValue[0]] = isset($keyValue[1]) ? $keyValue[1] : '';
            }
        }

        return $result;
    }
}

Convert maxmind raw result to UTF-8

Convert maxmind raw result to UTF-8


    @foreach($lanGames as $lanGame)
        @can('view', $lanGame)
            @php
                if (Auth::user()) {
                    $voted = $lanGame->votes->where('user_id',Auth::user()->id)->count();
                } else {
                    $voted = false;
                }
            @endphp

                    <form>

                            <input type="checkbox"
                                   class="custom-control-input"
                                   id="lan_game_{{ $lanGame->id }}"
                                   {{ $voted ? 'checked' : '' }}
                            >
                            id }}">{{ $lanGame->game_name }}

                    </form>

                    @foreach($lanGame->votes as $vote)
                        @include('pages.users.partials.avatar', ['user' => $vote->user])
                    @endforeach

                    @canany(['update', 'delete'], $lanGame)
                        @include('pages.lan-games.partials.actions-dropdown', ['lanGame' => $lanGame])
                    @endcanany

        @endcan
    @endforeach

    @foreach($lanGames as $lanGame)
        @can('view', $lanGame)
            @php
                if (Auth::user()) {
                    $voted = $lanGame->votes->where('user_id',Auth::user()->id)->count();
                } else {
                    $voted = false;
                }
            @endphp

id }}').checked = ! document.getElementById('lan_game_{{ $lanGame->id }}').checked">

                    <form>

                            <input type="checkbox"
                                   class="custom-control-input"
                                   id="lan_game_{{ $lanGame->id }}"
                                   {{ $voted ? 'checked' : '' }}
                            >
                            id }}">{{ $lanGame->game_name }}

                    </form>

                    @foreach($lanGame->votes as $vote)
                        @include('pages.users.partials.avatar', ['user' => $vote->user])
                    @endforeach

                    @canany(['update', 'delete'], $lanGame)
                        @include('pages.lan-games.partials.actions-dropdown', ['lanGame' => $lanGame])
                    @endcanany

        @endcan
    @endforeach

Allow clicking anywhere in row to toggle checkbox


<?php

namespace spec\Dock\Docker\Dns;

use Dock\Docker\Dns\ContainerAddressResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class DnsDockResolverSpec extends ObjectBehavior
{
    function it_is_a_container_address_resolve()
    {
        $this->shouldImplement(ContainerAddressResolver::class);
    }

    function it_returns_the_resolution_with_just_the_image_name()
    {
        $this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('image.docker');
    }

    function it_returns_the_container_specific_resolution()
    {
        $this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('container.image.docker');
    }

    function it_removes_the_tag_in_image_name()
    {
        $this->getDnsByContainerNameAndImage('container', 'image:latest')->shouldContain('container.image.docker');
    }
}

<?php

namespace spec\Dock\Docker\Dns;

use Dock\Docker\Dns\ContainerAddressResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class DnsDockResolverSpec extends ObjectBehavior
{
    function it_is_a_container_address_resolve()
    {
        $this->shouldImplement('Dock\Docker\Dns\ContainerAddressResolver');
    }

    function it_returns_the_resolution_with_just_the_image_name()
    {
        $this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('image.docker');
    }

    function it_returns_the_container_specific_resolution()
    {
        $this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('container.image.docker');
    }

    function it_removes_the_tag_in_image_name()
    {
        $this->getDnsByContainerNameAndImage('container', 'image:latest')->shouldContain('container.image.docker');
    }
}

Remove the PHP 5.5 `::class` usage

Remove the PHP 5.5 `::class` usage


<?php
namespace Codeception\Lib\Actor\Shared;

trait Comment
{
    public function expectTo($prediction)
    {
        return $this->comment('I expect to ' . $prediction);
    }

    public function expect($prediction)
    {
        return $this->comment('I expect ' . $prediction);
    }

    public function amGoingTo($argumentation)
    {
        return $this->comment('I am going to ' . $argumentation);
    }

    public function am($role) {
	    $role = (string) trim($role);
	    $firstLetter = $role[0];

	    if(preg_match('/[aeiouAEIOU]/i', $firstLetter))
	    {
            return $this->comment('As an ' . $role);
	    }

        return $this->comment('As a ' . $role);
    }

    public function lookForwardTo($achieveValue)
    {
        return $this->comment('So that I ' . $achieveValue);
    }

    public function comment($description)
    {
        $this->scenario->comment($description);
        return $this;
    }
}

<?php
namespace Codeception\Lib\Actor\Shared;

trait Comment
{
    public function expectTo($prediction)
    {
        return $this->comment('I expect to ' . $prediction);
    }

    public function expect($prediction)
    {
        return $this->comment('I expect ' . $prediction);
    }

    public function amGoingTo($argumentation)
    {
        return $this->comment('I am going to ' . $argumentation);
    }

    public function am($role)
    {
        $role = trim($role);

        if (stripos('aeiou', $role[0]) !== false) {
            return $this->comment('As an ' . $role);
        }

        return $this->comment('As a ' . $role);
    }

    public function lookForwardTo($achieveValue)
    {
        return $this->comment('So that I ' . $achieveValue);
    }
}

Fix codestyle and use stripos to check starting with vowel


<?php

add_filter('wpmu_blogs_columns', function ($columns) {
  $columns['2fa'] = '2FA';
  return $columns;
});

add_action('manage_sites_custom_column', function ($column_name, $blawg_id) {
  if ($column_name === '2fa') {
    $enabled = get_blog_option($blawg_id, '2fa_enabled') === 'yes';

    echo $enabled ? 'Enabled' : 'Disabled';
  }
}, 10, 2);

<?php

// Display blog enabled/disabled status in list

add_filter('wpmu_blogs_columns', function ($columns) {
  $columns['2fa'] = '2FA';
  return $columns;
});

add_action('manage_sites_custom_column', function ($column_name, $blawg_id) {
  if ($column_name === '2fa') {
    $enabled = get_blog_option($blawg_id, '2fa_enabled') === 'yes';

    echo $enabled ? 'Enabled' : 'Disabled';
  }
}, 10, 2);

// Enabled/disabled status option

add_action('wpmueditblogaction', function ($id) {
  $enabled = get_option('2fa_enabled') === 'yes';
  ?>

    2FA
    <input name="2fa_enabled" type="checkbox" value="yes" <?php echo $enabled ? 'checked' : '' ?>> Enabled

  <?php
});

// Fired after nonce checks
add_action('wpmu_update_blog_options', function () {
  if (isset($_POST['2fa_enabled']) && $_POST['2fa_enabled'] === 'yes') {
    update_option('2fa_enabled', 'yes');
  } else {
    update_option('2fa_enabled', 'no');
  }
});

Allow changing enabled status for blogs

Allow changing enabled status for blogs


<?php
namespace DreadLabs\VantomasWebsite\SecretSanta\Pair;

use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface;
use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface;

interface RepositoryInterface
{

    /**
     * Finds a pair for the given donor
     *
     * @param DonorInterface $donor
     * @return PairInterface
     */
    public function findPairFor(DonorInterface $donor);

    /**
     * Determines if the given donor/donee pair is mutual
     *
     * @param DonorInterface $donor
     * @param DoneeInterface $donee
     * @return bool
     */
    public function isPairMutually(DonorInterface $donor, DoneeInterface $donee);

    /**
     * Flags if the incoming donor / donee pair is already existing
     *
     * @param DonorInterface $donor
     * @param DoneeInterface $donee
     * @return bool
     */
    public function isPairExisting(DonorInterface $donor, DoneeInterface $donee);

    /**
     * @param PairInterface $pair
     * @return void
     */
    public function add(PairInterface $pair);
}

<?php
namespace DreadLabs\VantomasWebsite\SecretSanta\Pair;

use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface;
use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface;

interface RepositoryInterface
{

    /**
     * Finds a pair for the given donor
     *
     * @param DonorInterface $donor
     * @return PairInterface
     */
    public function findPairFor(DonorInterface $donor);

    /**
     * Determines if the given donor/donee pair is mutual
     *
     * @param DonorInterface $donor
     * @param DoneeInterface $donee
     * @return bool
     */
    public function isPairMutually(DonorInterface $donor, DoneeInterface $donee);

    /**
     * Flags if the incoming donor / donee pair is already existing
     *
     * @param DonorInterface $donor
     * @param DoneeInterface $donee
     * @return bool
     */
    public function isPairExisting(DonorInterface $donor, DoneeInterface $donee);

    /**
     * @param PairInterface $pair
     * @return void
     */
    public function attach(PairInterface $pair);
}

[TASK] Rename repository method `add` to attach in order to not collide with extbase


<?php
/**
 * Drush System configuration
 *
 * This file configures usage of Drush on the build container, in conjunction
 * with configuration and commands placed in /etc/drush.
 */

// On drush sql-dump and other database extraction operations, ignore the data
// in these tables, but keep the table structures.
// Make sure to update the list when new cache tables are added.
// For Atrium sites see the `example.drushrc.php` shipped with the distribution
// for a complete list.
$options['structure-tables']['common'] = array(
  'cache',
  'cache_block',
  'cache_bootstrap',
  'cache_field',
  'cache_filter',
  'cache_form',
  'cache_menu',
  'cache_page',
  'cache_path',
  'cache_token',
  'cache_update',
  'cache_variable',
  'cache_views',
  'cache_views_data',
  'history',
  'search_index',
  'search_node_links',
  'search_total',
  'sessions',
);

// Use the list of cache tables above.
$options['structure-tables-key'] = 'common';

<?php
/**
 * Drush System configuration
 *
 * This file configures usage of Drush on the build container, in conjunction
 * with configuration and commands placed in /etc/drush.
 */

// On drush sql-dump and other database extraction operations, ignore the data
// in these tables, but keep the table structures.
// Make sure to update the list when new cache tables are added.
// For Atrium sites see the `example.drushrc.php` shipped with the distribution
// for a complete list.
$options['structure-tables']['common'] = array(
  'cache',
  'cache_block',
  'cache_bootstrap',
  'cache_config',
  'cache_container',
  'cache_data',
  'cache_default',
  'cache_discovery',
  'cache_entity',
  'cache_field',
  'cache_filter',
  'cache_form',
  'cache_menu',
  'cache_migrate',
  'cache_page',
  'cache_path',
  'cache_render',
  'cache_rest',
  'cache_token',
  'cache_toolbar',
  'cache_update',
  'cache_variable',
  'cache_views',
  'cache_views_data',
  'history',
  'search_index',
  'search_node_links',
  'search_total',
  'sessions',
);

$options['structure-tables']['common-and-logging'] = array_merge($options['structure-tables']['common'], array(
  'watchdog',
));

// Use the list of cache tables above.
$options['structure-tables-key'] = 'common';

Update structure tables with common D8 entries and add option for easily excluding watchdog as well.


<?php $sort_custom = $this->configuration->getValue('get.sort_custom'); ?>
<?php $sort_default = $this->configuration->getValue('get.sort_default'); ?>
<?php if ($sort_custom || $sort_custom): ?>
  /**
   * Add sort clauses from "sort_default" and "sort_custom" fields
   *
   * @param  Doctrine_Query  $query   The query to add joins to
   * @param  array           &$params The filtered parameters for this request
   */
  function querySort(Doctrine_Query $query, array &$params)
  {
<?php if ($sort_default && count($sort_default) == 2): ?>
    $sort = '<?php echo $sort_default[0] ?> <?php echo $sort_default[1] ?>';
<?php endif; ?>
<?php if ($sort_custom): ?>
    if (isset($params['sort_by']))
    {
      $sort = $params['sort_by'];
      unset($params['sort_by']);

      if (isset($params['sort_order']))
      {
        $sort .= ' '.$params['sort_order'];
        unset($params['sort_order']);
      }
    }
<?php endif; ?>

    if (isset($sort))
    {
      $query->orderBy($sort);
    }
  }
<?php else: ?>
  /* querySort function omitted, "sort_default" and "sort_custom" not set in
   * generator config
   */
<?php endif; ?>

<?php $sort_custom = $this->configuration->getValue('get.sort_custom'); ?>
<?php $sort_default = $this->configuration->getValue('get.sort_default'); ?>
<?php if ($sort_default || $sort_custom): ?>
  /**
   * Add sort clauses from "sort_default" and "sort_custom" fields
   *
   * @param  Doctrine_Query  $query   The query to add joins to
   * @param  array           &$params The filtered parameters for this request
   */
  function querySort(Doctrine_Query $query, array &$params)
  {
<?php if ($sort_default && count($sort_default) == 2): ?>
    $sort = '<?php echo $sort_default[0] ?> <?php echo $sort_default[1] ?>';
<?php endif; ?>
<?php if ($sort_custom): ?>
    if (isset($params['sort_by']))
    {
      $sort = $params['sort_by'];
      unset($params['sort_by']);

      if (isset($params['sort_order']))
      {
        $sort .= ' '.$params['sort_order'];
        unset($params['sort_order']);
      }
    }
<?php endif; ?>

    if (isset($sort))
    {
      $query->orderBy($sort);
    }
  }
<?php else: ?>
  /* querySort function omitted, "sort_default" and "sort_custom" not set in
   * generator config
   */
<?php endif; ?>

Test for sort_custom AND sort_default

Test for sort_custom AND sort_default


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

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

return [
    'up' => function (Builder $schema) {
        $schema->create('posts_likes', function (Blueprint $table) {
            $table->integer('post_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->primary(['post_id', 'user_id']);
        });
    },

    'down' => function (Builder $schema) {
        $schema->drop('posts_likes');
    }
];

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

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

return Migration::createTable(
    'posts_likes',
    function (Blueprint $table) {
        $table->integer('post_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->primary(['post_id', 'user_id']);
    }
);

Use new shortcuts for migrations

Use new shortcuts for migrations


<?php

return call_user_func(function () {

    $html = file_get_contents(__DIR__ . '/../../test/test-app/webcarpet.php');
    $filter = new Kibo\Phast\Filters\HTML\ScriptsRearrangement\Filter();
    $doc = new \Kibo\Phast\Common\DOMDocument(new \Kibo\Phast\Parsing\HTML\HTMLStream());
    $doc->loadHTML($html);

    return function () use ($doc, $filter) {
        $filter->transformHTMLDOM($doc);
    };
});

<?php

return call_user_func(function () use ($iterations) {

    $html = file_get_contents(__DIR__ . '/../../test/test-app/webcarpet.php');
    $filter = new Kibo\Phast\Filters\HTML\ScriptsRearrangement\Filter();

    for ($i = 0; $i < $iterations; $i++) {
        $doc = new \Kibo\Phast\Common\DOMDocument(new \Kibo\Phast\Parsing\HTML\HTMLStream());
        $doc->loadHTML($html);
        $documents[] = $doc;
    }

    return function () use (&$documents, $filter) {
        $doc = array_pop($documents);
        $filter->transformHTMLDOM($doc);
    };
});

Use a fresh DOMDocument for each ScriptsRearrangement iteration


<?php
/**
 * Plugin Name: Restrict Content Pro - Restrict WooCommerce Shop Archive
 * Description: Restricts access to the WooCommerce shop archive, using the settings specified in the "Restrict this Content" metabox.
 * Version: 1.0
 * Author: Restrict Content Pro team
 * License: GPL2
 */

/**
 * Restricts access to the WooCommerce shop archive according to the settings specified in the metabox.
 * If the current user doesn't have access, they're redirected to the specified redirect URL in Restrict > Settings > Misc.
 *
 * @since 1.0
 * @return void
 */
function ag_rcp_redirect_woocommerce_shop() {
	if ( ! function_exists( 'is_shop' ) || ! is_shop() ) {
		return;
	}

	global $rcp_options;

	$shop_page_id = wc_get_page_id( 'shop' );
	$member       = new RCP_Member( get_current_user_id() );

	if ( $member->can_access( $shop_page_id ) ) {
		return;
	}

	if( isset( $rcp_options['redirect_from_premium'] ) ) {
		$redirect = get_permalink( $rcp_options['redirect_from_premium'] );
	} else {
		$redirect = home_url();
	}

	wp_redirect( $redirect ); exit;
}
add_action( 'template_redirect', 'ag_rcp_redirect_woocommerce_shop', 999 );

<?php
/**
 * Plugin Name: Restrict Content Pro - Restrict WooCommerce Shop Archive
 * Description: Restricts access to the WooCommerce shop archive, using the settings specified in the "Restrict this Content" metabox.
 * Version: 1.0
 * Author: Restrict Content Pro team
 * License: GPL2
 */

/**
 * Restricts access to the WooCommerce shop archive according to the settings specified in the metabox.
 * If the current user doesn't have access, they're redirected to the specified redirect URL in Restrict > Settings > Misc.
 *
 * @since 1.0
 * @return void
 */
function ag_rcp_redirect_woocommerce_shop() {
	if ( ! function_exists( 'is_shop' ) || ! is_shop() || ! class_exists( 'RCP_Member' ) ) {
		return;
	}

	global $rcp_options;

	$shop_page_id = wc_get_page_id( 'shop' );
	$member       = new RCP_Member( get_current_user_id() );

	if ( $member->can_access( $shop_page_id ) ) {
		return;
	}

	if( isset( $rcp_options['redirect_from_premium'] ) ) {
		$redirect = get_permalink( $rcp_options['redirect_from_premium'] );
	} else {
		$redirect = home_url();
	}

	wp_redirect( $redirect ); exit;
}
add_action( 'template_redirect', 'ag_rcp_redirect_woocommerce_shop', 999 );

Exit if RCP_Member class doesn't exist.

Exit if RCP_Member class doesn't exist.


<?php

use Fhaculty\Graph\Algorithm\Complete;

use Fhaculty\Graph\Algorithm\Directed;

use Fhaculty\Graph\Graph;

use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne()
    {
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected, $graph);
    }

    public function testUndirected()
    {
        $n = 9;

        $loader = new CompleteGraph($n);
        $graph = $loader->createGraph();

        $this->assertEquals($n, count($graph->getVertices()));
        $this->assertEquals($n*($n-1)/2, count($graph->getEdges()));
    }

    public function testDirected()
    {
        $n = 8;

        $loader = new CompleteGraph($n);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals($n, count($graph->getVertices()));
        $this->assertEquals($n*($n-1), count($graph->getEdges())); // n*(n-1) for directed graphs

        $alg = new Directed($graph);
        $this->assertTrue($alg->hasDirected());

        $alg = new Complete($graph);
        $this->assertTrue($alg->isComplete());
    }
}

<?php

use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne()
    {
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected, $graph);
    }

    public function testUndirected()
    {
        $n = 9;

        $loader = new CompleteGraph($n);
        $graph = $loader->createGraph();

        $this->assertEquals($n, count($graph->getVertices()));
        $this->assertEquals($n*($n-1)/2, count($graph->getEdges()));
    }

    public function testDirected()
    {
        $n = 8;

        $loader = new CompleteGraph($n);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals($n, count($graph->getVertices()));
        $this->assertEquals($n*($n-1), count($graph->getEdges())); // n*(n-1) for directed graphs
    }
}

Remove Algorithm namespace (split off into separate repository)


@extends('layout.app')

@section('content')

  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />

id }}" class="designer container">

{{ $designer->getTranslation()->name }}

{!! $designer->getTranslation()->content !!}

@endsection

@extends('layout.app')

@section('content')

@if (!Auth::guest())

    id.'/edit') }}"
        id="edit-button" class="btn btn-default pull-right">Edit

@endif

  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />
  getImage()->getThumbUrl() }}" />

id }}" class="designer container">

{{ $designer->getTranslation()->name }}

{!! $designer->getTranslation()->content !!}

@endsection

Add edit button to designer page.

Add edit button to designer page.


<?php

namespace Stripe;

class RateLimitErrorTest extends TestCase
{
    private function rateLimitErrorResponse()
    {
        return array(
            'error' => array(),
        );
    }

    public function testRateLimit()
    {
        try {
            $this->mockRequest('GET', '/v1/accounts/acct_DEF', array(), $this->rateLimitErrorResponse(), 429);
            Account::retrieve('acct_DEF');
            $this->fail('Did not raise an error.');
        } catch (Error\RateLimit $e) {
            $this->assertSame(429, $e->getHttpStatus());
        }
    }
}

<?php

namespace Stripe;

class RateLimitErrorTest extends TestCase
{
    private function rateLimitErrorResponse()
    {
        return array(
            'error' => array(),
        );
    }

    /**
     * @expectedException Stripe\Error\RateLimit
     */
    public function testRateLimit()
    {
        $this->mockRequest('GET', '/v1/accounts/acct_DEF', array(), $this->rateLimitErrorResponse(), 429);
        Account::retrieve('acct_DEF');
    }
}

Clean up style for rate limit test

Clean up style for rate limit test

CC @jxu577


Past match results

Player 1

Player 2

Winner

Date

                        <?php
                        foreach ($scores as $score) { ?>

<?php echo $score['player1']; ?>

<?php echo $score['player2']; ?>

<?php echo $score['winner']; ?>

<?php echo $score['created_at']; ?>

                        <?php } ?>

Index view now displays all returned results


<?php

use yii\db\Schema;
use yii\db\Migration;

class m140703_123104_page extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%page}}', [
            'id' => Schema::TYPE_PK,
            'alias' => Schema::TYPE_STRING . '(1024) NOT NULL',
            'title' => Schema::TYPE_STRING . '(512) NOT NULL',
            'body' => Schema::TYPE_TEXT . ' NOT NULL',
            'status' => Schema::TYPE_SMALLINT . ' NOT NULL',
            'created_at' => Schema::TYPE_INTEGER,
            'updated_at' => Schema::TYPE_INTEGER,
        ], $tableOptions);

        $this->insert('{{%page}}', [
            'alias'=>'about',
            'title'=>'About',
            'body'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
            'status'=>\common\models\Page::STATUS_PUBLISHED,
            'created_at'=>new \yii\db\Expression('NOW()'),
            'updated_at'=>new \yii\db\Expression('NOW()'),
        ]);
    }

    public function down()
    {
        $this->dropTable('{{%page}}');
    }
}

<?php

use yii\db\Schema;
use yii\db\Migration;

class m140703_123104_page extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%page}}', [
            'id' => Schema::TYPE_PK,
            'alias' => Schema::TYPE_STRING . '(1024) NOT NULL',
            'title' => Schema::TYPE_STRING . '(512) NOT NULL',
            'body' => Schema::TYPE_TEXT . ' NOT NULL',
            'status' => Schema::TYPE_SMALLINT . ' NOT NULL',
            'created_at' => Schema::TYPE_INTEGER,
            'updated_at' => Schema::TYPE_INTEGER,
        ], $tableOptions);

        $this->insert('{{%page}}', [
            'alias'=>'about',
            'title'=>'About',
            'body'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
            'status'=>\common\models\Page::STATUS_PUBLISHED,
            'created_at'=>time(),
            'updated_at'=>time(),
        ]);
    }

    public function down()
    {
        $this->dropTable('{{%page}}');
    }
}

Fix wrong created_at field type

Fix wrong created_at field type


<?php

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

namespace Symfony\Component\HttpFoundation\Session\Storage;

/**
 * NativeSqliteSessionStorage.
 *
 * Session based on native PHP sqlite database handler.
 *
 * @author Drak <drak@zikula.org>
 */
class NativeSqliteSessionStorage extends AbstractSessionStorage
{
    /**
     * @var string
     */
    private $dbPath;

    /**
     * Constructor.
     *
     * @param string                $dbPath     Path to SQLite database file.
     * @param array                 $options    Session configuration options.
     *
     * @see AbstractSessionStorage::__construct()
     */
    public function __construct($dbPath, array $options = array())
    {
        if (!extension_loaded('sqlite')) {
            throw new \RuntimeException('PHP does not have "sqlite" session module registered');
        }

        $this->dbPath = $dbPath;
        parent::__construct($options);
    }

    /**
     * {@inheritdoc}
     */
    protected function registerSaveHandlers()
    {
        ini_set('session.save_handler', 'sqlite');
        ini_set('session.save_path', $this->dbPath);
    }
}

<?php

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

namespace Symfony\Component\HttpFoundation\Session\Storage;

/**
 * NativeSqliteSessionStorage.
 *
 * Session based on native PHP sqlite database handler.
 *
 * @author Drak <drak@zikula.org>
 */
class NativeSqliteSessionStorage extends AbstractSessionStorage
{
    /**
     * @var string
     */
    private $dbPath;

    /**
     * Constructor.
     *
     * @param string $dbPath  Path to SQLite database file.
     * @param array  $options Session configuration options.
     *
     * @see AbstractSessionStorage::__construct()
     */
    public function __construct($dbPath, array $options = array())
    {
        if (!extension_loaded('sqlite')) {
            throw new \RuntimeException('PHP does not have "sqlite" session module registered');
        }

        $this->dbPath = $dbPath;
        parent::__construct($options);
    }

    /**
     * {@inheritdoc}
     */
    protected function registerSaveHandlers()
    {
        ini_set('session.save_handler', 'sqlite');
        ini_set('session.save_path', $this->dbPath);
    }

    /**
     * {@inheritdoc}
     *
     * Sets any values sqlite ini values.
     *
     * @see http://php.net/sqlite.configuration
     */
    protected function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            if (in_array($key, array('sqlite.assoc_case'))) {
                ini_set($key, $value);
            }
        }

        parent::setOptions($options);
    }
}

[HttpFoudation] Add ability to configure sqlite session storage.


<?php
namespace Opg\Lpa\DataModel\Validator\Constraints;

/**
 * This train should be included in any 'Validator\Constraints' class that wants to use
 * its original Symfony Validator (which should be all non-custom ones!).
 *
 * Class ValidatorPathTrait
 * @package Opg\Lpa\DataModel\Validator\Constraints
 */
trait ValidatorPathTrait {

    /**
     * Returns the name of the class that validates this constraint.
     *
     * This has been changed to point back to the original Symfony Validators.
     *
     * @return string
     *
     * @api
     */
    public function validatedBy()
    {
        return 'Symfony\\Component\\Validator\\Constraints\\'.end(explode('\\',get_class($this))).'Validator';
    }

} // trait

<?php
namespace Opg\Lpa\DataModel\Validator\Constraints;

/**
 * This train should be included in any 'Validator\Constraints' class that wants to use
 * its original Symfony Validator (which should be all non-custom ones!).
 *
 * Class ValidatorPathTrait
 * @package Opg\Lpa\DataModel\Validator\Constraints
 */
trait ValidatorPathTrait {

    /**
     * Returns the name of the class that validates this constraint.
     *
     * This has been changed to point back to the original Symfony Validators.
     *
     * @return string
     *
     * @api
     */
    public function validatedBy()
    {
        $pathParts = explode('\\',get_class($this));
        return 'Symfony\\Component\\Validator\\Constraints\\'.end( $pathParts ).'Validator';
    }

} // trait

Update so ony varaibles are passed to end()


<?php

namespace App\Phansible\Provider;

use App\Phansible\Model\GithubAdapter;
use Cache\Adapter\Filesystem\FilesystemCachePool;
use Github\Client;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;

class GithubProviderStaticFactory
{
    /**
     * {@inheritdoc}
     */
    public static function create(): GithubAdapter
    {
        $filesystemAdapter = new Local(__DIR__ . '/../../../app/cache/github-api-cache');
        $filesystem        = new Filesystem($filesystemAdapter);
        $cache             = new FilesystemCachePool($filesystem);

        $client = new Client();
        $client->addCache($cache);

        return new GithubAdapter($client);
    }
}

<?php

namespace App\Phansible\Provider;

use App\Phansible\Model\GithubAdapter;
use Cache\Adapter\Filesystem\FilesystemCachePool;
use Github\Client;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;

class GithubProviderStaticFactory
{
    /**
     * {@inheritdoc}
     */
    public static function create(): GithubAdapter
    {
        $filesystemAdapter = new Local(__DIR__ . '/../../../var/cache/github-api-cache');
        $filesystem        = new Filesystem($filesystemAdapter);
        $cache             = new FilesystemCachePool($filesystem);

        $client = new Client();
        $client->addCache($cache);

        return new GithubAdapter($client);
    }
}

Move cache into common location

Move cache into common location


<?php

namespace Project\AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Project\AppBundle\Entity\User;
use Project\AppBundle\Form\UserType;

class DefaultController extends Controller
{
    /**
     * Lists all User entities.
     *
     * @Secure(roles={"ROLE_MANAGER", "ROLE_SPEAKER", "ROLE_STUDENT"})
     * @Route("/", name="project_app_index")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        // Get logged in user
        $user = $this->getUser();
        $userRoles = $user->getRoles();

        if(in_array('ROLE_MANAGER', $userRoles)) {
            return $this->redirect($this->generateUrl('promotion'));
        } elseif(in_array('ROLE_SPEAKER', $userRoles)) {
            return $this->redirect($this->generateUrl('missing'));
        } elseif(in_array('ROLE_STUDENT', $userRoles)) {
            return $this->redirect($this->generateUrl('project_app_agenda_index'));
        }
    }
}

<?php

namespace Project\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;

class DefaultController extends Controller
{
    /**
     * Routes to the right application part in function of role.
     *
     * @Secure(roles={"ROLE_MANAGER", "ROLE_SPEAKER", "ROLE_STUDENT"})
     * @Route("/", name="project_app_index")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        // Get logged in user
        $user = $this->getUser();
        $userRoles = $user->getRoles();

        if(in_array('ROLE_MANAGER', $userRoles)) {
            // Redirect to promotion gestion
            return $this->redirect($this->generateUrl('promotion'));
        } elseif(in_array('ROLE_SPEAKER', $userRoles)) {
            // Redirect to missing list
            return $this->redirect($this->generateUrl('missing'));
        } elseif(in_array('ROLE_STUDENT', $userRoles)) {
            // Redirect to the agenda
            return $this->redirect($this->generateUrl('project_app_agenda_index'));
        }
    }
}

Implement default controller to redirect in function of role


<?php

final class FeedPublisherHTTPWorker extends FeedPushWorker {

  protected function doWork() {
    if (PhabricatorEnv::getEnvConfig('phabricator.silent')) {
      // Don't invoke hooks in silent mode.
      return;
    }

    $story = $this->loadFeedStory();
    $data = $story->getStoryData();

    $uri = idx($this->getTaskData(), 'uri');
    $valid_uris = PhabricatorEnv::getEnvConfig('feed.http-hooks');
    if (!in_array($uri, $valid_uris)) {
      throw new PhabricatorWorkerPermanentFailureException();
    }

    $post_data = array(
      'storyID'         => $data->getID(),
      'storyType'       => $data->getStoryType(),
      'storyData'       => $data->getStoryData(),
      'storyAuthorPHID' => $data->getAuthorPHID(),
      'storyText'       => $story->renderText(),
      'epoch'           => $data->getEpoch(),
    );

    id(new HTTPSFuture($uri, $post_data))
      ->setMethod('POST')
      ->setTimeout(30)
      ->resolvex();
  }

  public function getWaitBeforeRetry(PhabricatorWorkerTask $task) {
    return max($task->getFailureCount(), 1) * 60;
  }

}

<?php

final class FeedPublisherHTTPWorker extends FeedPushWorker {

  protected function doWork() {
    if (PhabricatorEnv::getEnvConfig('phabricator.silent')) {
      // Don't invoke hooks in silent mode.
      return;
    }

    $story = $this->loadFeedStory();
    $data = $story->getStoryData();

    $uri = idx($this->getTaskData(), 'uri');
    $valid_uris = PhabricatorEnv::getEnvConfig('feed.http-hooks');
    if (!in_array($uri, $valid_uris)) {
      throw new PhabricatorWorkerPermanentFailureException();
    }

    $post_data = array(
      'storyID'         => $data->getID(),
      'storyType'       => $data->getStoryType(),
      'storyData'       => $data->getStoryData(),
      'storyAuthorPHID' => $data->getAuthorPHID(),
      'storyText'       => $story->renderText(),
      'epoch'           => $data->getEpoch(),
    );

    // NOTE: We're explicitly using "http_build_query()" here because the
    // "storyData" parameter may be a nested object with arbitrary nested
    // sub-objects.
    $post_data = http_build_query($post_data, '', '&');

    id(new HTTPSFuture($uri, $post_data))
      ->setMethod('POST')
      ->setTimeout(30)
      ->resolvex();
  }

  public function getWaitBeforeRetry(PhabricatorWorkerTask $task) {
    return max($task->getFailureCount(), 1) * 60;
  }

}

Revert "feed.http-hooks" HTTP request construction to use "http_build_query()" so nested "storyData" is handled correctly

Summary:
See <https://discourse.phabricator-community.org/t/storydata-is-blank-in-outgoing-requests-to-the-configured-feed-http-hooks/2366/>.

This behavior was changed by D20049. I think it's generally good that we not accept/encode nested values in a PHP-specific way, but retain `feed.http-hooks` compatibility for now.

Test Plan: {F6190681}

Reviewers: amckinley

Reviewed By: amckinley

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


<?php declare(strict_types=1);

$session = Smr\Session::getInstance();
$var = $session->getCurrentVar();
$account = $session->getAccount();

// register game_id
$session->updateGame($var['game_id']);

$player = SmrPlayer::getPlayer($account->getAccountID(), $var['game_id']);
$player->updateLastCPLAction();

// Check to see if newbie status has changed
$player->updateNewbieStatus();

// get rid of old plotted course
$player->deletePlottedCourse();
$player->update();

// log
$player->log(LOG_TYPE_GAME_ENTERING, 'Player entered game ' . $player->getGameID());

$container = Page::create('skeleton.php', 'current_sector.php');
$container->go();

<?php declare(strict_types=1);

$session = Smr\Session::getInstance();
$var = $session->getCurrentVar();
$account = $session->getAccount();

// register game_id
$session->updateGame($var['game_id']);

$player = SmrPlayer::getPlayer($account->getAccountID(), $var['game_id']);
acquire_lock($player->getSectorID()); // skip var update in do_voodoo

$player->updateLastCPLAction();

// Check to see if newbie status has changed
$player->updateNewbieStatus();

// get rid of old plotted course
$player->deletePlottedCourse();
$player->update();

// log
$player->log(LOG_TYPE_GAME_ENTERING, 'Player entered game ' . $player->getGameID());

$container = Page::create('skeleton.php', 'current_sector.php');
$container->go();

Fix reloading the wrong session $var

Fix reloading the wrong session $var

In `do_voodoo`, we reload the session var from the database whenever
we're in a game, but don't have a sector lock yet.

When we're joining or entering a game, we're in the unique situation
where we load the original session var outside of a game (so no sector
lock is acquired), but then we forward to a page that is inside a game,
where we reload the session from the database.

The problem is that we have already modified the session var, so the
one in the database is outdated. Loading the outdated session can
cause arbitrary bugs.

In the past, this issue was handled by *always* updating the session
var in the database any time we forwarded to a new page without a
sector lock. This was an overly aggressive strategy, because in most
cases we don't need to update the database session var if we don't
have a sector lock (i.e. anything we do outside of a game). This was
(incorrectly) removed in 13cd14751.

To fix this bug, we do not re-implement the old, generic behavior.
Instead, we simply put a sector lock in game_play_processing.php, as
it is the only place where we transition from not in a game. (This
also fixes the more critical problem with game_join_processing.php.)


#!/usr/bin/env php
<?php
include("NudeDetector.php");

if ($argc == 1)
	exit;

$input_file = $argv[1];

$detector = new NudeDetector($input_file, 'HSV');
echo "map sking pixels\n";
$detector->map_skin_pixels();
echo "determine regions\n";
$detector->determine_regions();
echo "count region populations\n";
$detector->count_region_population();
$detector->sort_regions_by_population();

echo "create colored regions\n";
$img = $detector->create_colored_regions();

imagegif($img, $argv[2]);
imagedestroy($img);

#!/usr/bin/env php
<?php
include("NudeDetector.php");

if ($argc == 1)
	exit;

$input_file = $argv[1];

$detector = new NudeDetector($input_file, 'HSV');
echo "map skin pixels\n";
$detector->map_skin_pixels();
echo "determine regions\n";
$detector->determine_regions();
echo "count region populations\n";
$detector->count_region_population();
$detector->sort_regions_by_population();

echo "create colored regions\n";
$img = $detector->create_colored_regions();

imagegif($img, $argv[2]);
imagedestroy($img);

Fix a typo, make it use HSV at all times.


<?php

class Kohana_Model_Store extends Jam_Model {

	/**
	 * @codeCoverageIgnore
	 */
	public static function initialize(Jam_Meta $meta)
	{
		$meta
			->behaviors(array(
				'paranoid' => Jam::behavior('paranoid'),
			))
			->associations(array(
				'store_purchases' => Jam::association('hasmany', array(
					'inverse_of' => 'store',
					'foreign_model' => 'store_purchase',
				)),
				'purchases' => Jam::association('manytomany', array(
					'foreign_model' => 'purchase',
					'join_table' => 'store_purchases',
				)),
			))
			->fields(array(
				'id' => Jam::field('primary'),
				'name' => Jam::field('string'),
				'currency' => Jam::field('string'),
			))
			->validator('name', array(
				'present' => TRUE
			));
	}

	public function purchases_total_price($types)
	{
		$prices = array_map(function($purchase) use ($types) {
			return $purchase->total_price($types);
		}, $this->purchases->as_array());

		return Jam_Price::sum($prices, $this->currency);
	}
}

<?php

class Kohana_Model_Store extends Jam_Model {

	/**
	 * @codeCoverageIgnore
	 */
	public static function initialize(Jam_Meta $meta)
	{
		$meta
			->behaviors(array(
				'paranoid' => Jam::behavior('paranoid'),
			))
			->associations(array(
				'store_purchases' => Jam::association('hasmany', array(
					'inverse_of' => 'store',
					'foreign_model' => 'store_purchase',
					'delete_on_remove' => Jam_Association::DELETE,
					'dependent' => Jam_Association::DELETE,
				)),
				'purchases' => Jam::association('manytomany', array(
					'foreign_model' => 'purchase',
					'join_table' => 'store_purchases',
				)),
			))
			->fields(array(
				'id' => Jam::field('primary'),
				'name' => Jam::field('string'),
				'currency' => Jam::field('string'),
			))
			->validator('name', array(
				'present' => TRUE
			));
	}

	public function purchases_total_price($types)
	{
		$prices = array_map(function($purchase) use ($types) {
			return $purchase->total_price($types);
		}, $this->purchases->as_array());

		return Jam_Price::sum($prices, $this->currency);
	}
}

Delete store purchases when the related store is deleted


<?php

include_once('config/init.php');

if (isset($_SERVER['HTTP_REFERER'])) {
    if (substr_compare($_SERVER['HTTP_REFERER'], 'login.php', -strlen('login.php'), strlen('login.php')) != 0
        && substr_compare($_SERVER['HTTP_REFERER'], 'register.php', -strlen('register.php'), strlen('register.php')) != 0) {
        $_SESSION['PREV_HTTP_REFERER'] = $_SERVER['HTTP_REFERER'];
    }
}

$smarty->display('members/login.tpl');

<?php

include_once('config/init.php');

if (isset($_SERVER['HTTP_REFERER'])) {
    if (substr_compare($_SERVER['HTTP_REFERER'], 'login.php', -strlen('login.php'), strlen('login.php')) != 0
        && substr_compare($_SERVER['HTTP_REFERER'], 'register.php', -strlen('register.php'), strlen('register.php')) != 0
    ) {
        $_SESSION['PREV_HTTP_REFERER'] = $_SERVER['HTTP_REFERER'];
    }

    if (substr_compare($_SERVER['HTTP_REFERER'], 'forgotpass.php', -strlen('login.php'), strlen('login.php')) != 0) {
        $_SESSION['PREV_HTTP_REFERER'] = $BASE_URL;
    }
}

$smarty->display('members/login.tpl');

Add check to prevent being redirected to a bad request page.


<?php

/*
 * This file is part of Alt Three Throttle.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AltThree\Tests\Throttle;

use AltThree\Throttle\ThrottlingMiddleware;
use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the throttling middleware test class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class ThrottlingMiddlewareTest extends AbstractPackageTestCase
{
    /**
     * @before
     */
    public function setUpDummyRoute()
    {
        $this->app->router->get('/dummy', ['middleware' => ThrottlingMiddleware::class, function () {
            return 'success';
        }]);
    }

    public function testIsInjectable()
    {
        $this->assertIsInjectable(ThrottlingMiddleware::class);
    }

    public function testHandleSuccess()
    {
        for ($i = 1; $i <= 60; $i++) {
            $response = $this->call('GET', '/dummy');
            $this->assertSame(200, $response->status());
        }
    }

    /**
     * @expectedException \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException
     * @expectedExceptionMessage Rate limit exceeded.
     */
    public function testTooManyRequestsHttpException()
    {
        for ($i = 1; $i <= 61; $i++) {
            $this->call('GET', '/dummy');
        }
    }
}

<?php

/*
 * This file is part of Alt Three Throttle.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AltThree\Tests\Throttle;

use AltThree\Throttle\ThrottlingMiddleware;
use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the throttling middleware test class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class ThrottlingMiddlewareTest extends AbstractPackageTestCase
{
    /**
     * @before
     */
    public function setUpDummyRoute()
    {
        $this->app->router->get('/dummy', ['middleware' => ThrottlingMiddleware::class, function () {
            return 'success';
        }]);
    }

    public function testIsInjectable()
    {
        $this->assertIsInjectable(ThrottlingMiddleware::class);
    }

    public function testHandleSuccess()
    {
        for ($i = 59; $i >= 1; $i--) {
            $response = $this->call('GET', '/dummy');
            $this->assertSame(200, $response->status());
            $this->assertSame(60, $response->headers->get('x-ratelimit-limit'));
            $this->assertSame($i, $response->headers->get('x-ratelimit-remaining'));
        }
    }

    /**
     * @expectedException \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException
     * @expectedExceptionMessage Rate limit exceeded.
     */
    public function testTooManyRequestsHttpException()
    {
        for ($i = 1; $i <= 61; $i++) {
            $this->call('GET', '/dummy');
        }
    }
}

Add test for specifics headers presence

Add test for specifics headers presence


<?php

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

class CleanWebArtists extends Migration
{
    public function up()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            $table->renameColumn('datahub_id', 'agent_id');
        });
    }

    public function down()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            $table->renameColumn('agent_id', 'datahub_id');
        });
    }
}

<?php

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

class CleanWebArtists extends Migration
{
    public function up()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            $table->renameColumn('datahub_id', 'agent_id');
            $table->index('agent_id');
        });
    }

    public function down()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            $table->dropIndex(['agent_id']);
            $table->renameColumn('agent_id', 'datahub_id');
        });
    }
}

Add index on `agent_id` to `web_artists` [API-341, API-336]


<?php
/**
 * ActiveRecord for API
 *
 * @link      https://github.com/hiqdev/yii2-hiart
 * @package   yii2-hiart
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
 */

namespace hiqdev\hiart;

class ActiveDataProvider extends \yii\data\ActiveDataProvider
{
    /**
     * @var ActiveQuery the query that is used to fetch data models and [[totalCount]]
     * if it is not explicitly set
     */
    public $query;

    /**
     * To improve performance, implemented grid summary and pager loading via AJAX when this attribute is `false`
     * There is a possibility set this attribute via DI
     * @see \hipanel\base\SearchModelTrait::search()
     *
     * @var bool
     */
    public bool $countSynchronously = false;

    public function enableSynchronousCount(): void
    {
        $this->countSynchronously = true;
    }

    protected function prepareTotalCount()
    {
        return $this->countSynchronously ? parent::prepareTotalCount() : 999999;
    }
}

<?php
/**
 * ActiveRecord for API
 *
 * @link      https://github.com/hiqdev/yii2-hiart
 * @package   yii2-hiart
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
 */

namespace hiqdev\hiart;

class ActiveDataProvider extends \yii\data\ActiveDataProvider
{
    /**
     * @var ActiveQuery the query that is used to fetch data models and [[totalCount]]
     * if it is not explicitly set
     */
    public $query;

    /**
     * To improve performance, implemented grid summary and pager loading via AJAX when this attribute is `false`
     * There is a possibility set this attribute via DI
     * @see \hipanel\base\SearchModelTrait::search()
     *
     * @var bool
     */
    public bool $countSynchronously = false;

    public function enableSynchronousCount(): void
    {
        $this->countSynchronously = true;
    }

    /**
     * When receiving the pager and summary through AJAX, to calculate the limit and offset of Grid,
     * you need to get the maximum possible total count, otherwise the Grid pages will not switch
     *
     * @return int
     * @throws \yii\base\InvalidConfigException
     */
    protected function prepareTotalCount(): int
    {
        return $this->countSynchronously ? parent::prepareTotalCount() : PHP_INT_MAX;
    }
}

Return max possible total count when `countSynchronously` is true, calculate limit and offset


<?php

namespace Gitlist\Util;

use Silex\Application;

class Routing
{
    protected $app;

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

    public function getRepositoryRegex()
    {
        static $regex = null;

        if ($regex === null) {
            $app = $this->app;
            $quoted_paths = array_map(
                function ($repo) use ($app) {
                    return preg_quote($app['util.routing']->getRelativePath($repo['path']), '/');
                },
                $this->app['git']->getRepositories($this->app['git.repos'])
            );
            $regex = '/' . implode('|', $quoted_paths) . '/';
        }

        return $regex;
    }

    /**
     * Strips the base path from a full repository path
     *
     * @param string $repo_path Full path to the repository
     * @return string Relative path to the repository from git.repositories
     */
    public function getRelativePath($repo_path)
    {
        if (strpos($repo_path, $this->app['git.repos']) === 0) {
            $relative_path = substr($repo_path, strlen($this->app['git.repos']));
            return ltrim($relative_path, '/');
        } else {
            throw new \InvalidArgumentException(
                sprintf("Path '%s' does not match configured repository directory", $repo_path)
            );
        }
    }
}

<?php

namespace Gitlist\Util;

use Silex\Application;

class Routing
{
    protected $app;

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

    public function getRepositoryRegex()
    {
        static $regex = null;

        if ($regex === null) {
            $app = $this->app;
            $quoted_paths = array_map(
                function ($repo) use ($app) {
                    return preg_quote($app['util.routing']->getRelativePath($repo['path']), '#');
                },
                $this->app['git']->getRepositories($this->app['git.repos'])
            );
            $regex = '/' . implode('|', $quoted_paths) . '/';
        }

        return $regex;
    }

    /**
     * Strips the base path from a full repository path
     *
     * @param string $repo_path Full path to the repository
     * @return string Relative path to the repository from git.repositories
     */
    public function getRelativePath($repo_path)
    {
        if (strpos($repo_path, $this->app['git.repos']) === 0) {
            $relative_path = substr($repo_path, strlen($this->app['git.repos']));
            return ltrim($relative_path, '/');
        } else {
            throw new \InvalidArgumentException(
                sprintf("Path '%s' does not match configured repository directory", $repo_path)
            );
        }
    }
}

Change delimiter for repository regex

Change delimiter for repository regex

'#' is the default delimiter for route regexes in
`Symfony\Component\Routing\RouteCompiler`, so use this.


<?php

namespace Codeception\Module;

use Codeception\TestInterface;
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\HttpKernel\Client;

/**
 * Change client to follow redirects and keep cookie jar between tests.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class WorkingSilex extends Silex
{
    /** @var CookieJar */
    protected $cookieJar;

    public function _initialize()
    {
        $this->cookieJar = new CookieJar();

        parent::_initialize();
    }

    public function _before(TestInterface $test)
    {
        $this->reloadApp();

        $this->app->finish(function () {
            if ($this->app['mailer.initialized'] && $this->app['swiftmailer.use_spool'] && $this->app['swiftmailer.spooltransport'] instanceof \Swift_Transport_SpoolTransport) {
                $spool = $this->app['swiftmailer.spooltransport']->getSpool();
                $r = new \ReflectionClass($spool);
                $p = $r->getProperty('messages');
                $p->setAccessible(true);
                $p->setValue($spool, []);
            }
        }, 512);
    }

    public function reloadApp()
    {
        $this->loadApp();
        $this->client = new Client($this->app, [], null, $this->cookieJar);
        $this->client->followRedirects();
    }
}

<?php

namespace Codeception\Module;

use Codeception\TestInterface;
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\HttpKernel\Client;

/**
 * Change client to follow redirects and keep cookie jar between tests.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class WorkingSilex extends Silex
{
    /** @var CookieJar */
    protected $cookieJar;

    public function _initialize()
    {
        $this->cookieJar = new CookieJar();

        parent::_initialize();
    }

    public function _before(TestInterface $test)
    {
        $this->reloadApp();
    }

    protected function loadApp()
    {
        parent::loadApp();

        $this->app->finish(function () {
            if ($this->app['mailer.initialized'] && $this->app['swiftmailer.use_spool'] && $this->app['swiftmailer.spooltransport'] instanceof \Swift_Transport_SpoolTransport) {
                $spool = $this->app['swiftmailer.spooltransport']->getSpool();
                $r = new \ReflectionClass($spool);
                $p = $r->getProperty('messages');
                $p->setAccessible(true);
                $p->setValue($spool, []);
            }
        }, 512);
    }

    public function reloadApp()
    {
        $this->loadApp();
        $this->client = new Client($this->app, [], null, $this->cookieJar);
        $this->client->followRedirects();
    }
}

[Codeception] Move mailer hack to `loadApp` method to ensure it's always applied.


<?php

/*
 * This file is part of the eluceo/iCal package.
 *
 * (c) Markus Poerschke <markus@eluceo.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Eluceo\iCal\Util;

class ComponentUtil
{
    /**
     * Folds a single line.
     *
     * According to RFC 5545, all lines longer than 75 characters should be folded
     *
     * @see https://tools.ietf.org/html/rfc5545#section-5
     * @see https://tools.ietf.org/html/rfc5545#section-3.1
     *
     * @param $string
     *
     * @return array
     */
    public static function fold($string)
    {
        $lines = [];
        while (strlen($string) > 0) {
            if (strlen($string) > 75) {
                $lines[] = mb_strcut($string, 0, 75, 'utf-8') . "\r\n";
                $string = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8');
            } else {
                $lines[] = $string;
                $string = '';
                break;
            }
        }
        return $lines;
    }
}

<?php

/*
 * This file is part of the eluceo/iCal package.
 *
 * (c) Markus Poerschke <markus@eluceo.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Eluceo\iCal\Util;

class ComponentUtil
{
    /**
     * Folds a single line.
     *
     * According to RFC 5545, all lines longer than 75 characters should be folded
     *
     * @see https://tools.ietf.org/html/rfc5545#section-5
     * @see https://tools.ietf.org/html/rfc5545#section-3.1
     *
     * @param $string
     *
     * @return array
     */
    public static function fold($string)
    {
        $lines = [];
        while (strlen($string) > 0) {
            if (strlen($string) > 75) {
                $lines[] = mb_strcut($string, 0, 75, 'utf-8');
                $string = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8');
            } else {
                $lines[] = $string;
                $string = '';
                break;
            }
        }
        return $lines;
    }
}

Optimize Performance for long lines (use mb_strcut() instead of preg_split())


<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

/**
 * Migration script for add watching table
 **/
class Migration20130521160001ComForum extends Hubzero_Migration
{
	/**
	 * Up
	 **/
	protected static function up($db)
	{
		$query .= "UPDATE #__forum_posts SET `thread`=id WHERE `scope` IN ('site', 'group') AND `parent`=0;";

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}

		$query .= "UPDATE #__forum_posts SET `thread`=parent WHERE `scope` IN ('site', 'group') AND `parent`!=0;";

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}
	}
}

<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

/**
 * Migration script for add watching table
 **/
class Migration20130521160001ComForum extends Hubzero_Migration
{
	/**
	 * Up
	 **/
	protected static function up($db)
	{
		$query = "UPDATE `#__forum_posts` SET `thread`=id WHERE `scope` IN ('site', 'group') AND `parent`=0;";

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}

		$query = "UPDATE `#__forum_posts` SET `thread`=parent WHERE `scope` IN ('site', 'group') AND `parent`!=0;";

		if (!empty($query))
		{
			$db->setQuery($query);
			$db->query();
		}
	}
}

Fix for undefined var in migration

Fix for undefined var in migration


<?php namespace OpenCFP\Provider;

use HTMLPurifier;
use HTMLPurifier_Config;
use Silex\Application;
use Silex\ServiceProviderInterface;

class HtmlPurifierServiceProvider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Application $app)
    {
        $app['purifier'] = $app->share(function ($app) {
            $config = HTMLPurifier_Config::createDefault();

            if ($app->config('cache.enabled')) {
                $cacheDirectory = $app->config('paths.cache.purifier');

                if (!is_dir($cacheDirectory)) {
                    mkdir($cacheDirectory, 0755, true);
                }

                $config->set('Cache.SerializerPath', $cacheDirectory);
            }

            return new HTMLPurifier($config);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function boot(Application $app)
    {
    }
}

<?php namespace OpenCFP\Provider;

use HTMLPurifier;
use HTMLPurifier_Config;
use Silex\Application;
use Silex\ServiceProviderInterface;

class HtmlPurifierServiceProvider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Application $app)
    {
        $app['purifier'] = $app->share(function ($app) {
            $config = HTMLPurifier_Config::createDefault();

            if ($app->config('cache.enabled')) {
                $cachePermissions = 0755;
                $config->set('Cache.SerializerPermissions', $cachePermissions);
                $cacheDirectory = $app->config('paths.cache.purifier');

                if (!is_dir($cacheDirectory)) {
                    mkdir($cacheDirectory, $cachePermissions, true);
                }

                $config->set('Cache.SerializerPath', $cacheDirectory);
            }

            return new HTMLPurifier($config);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function boot(Application $app)
    {
    }
}

Add missing config for cache folder permissions


<?php

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

namespace Sylius\Component\Product\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Product\Model\ProductVariantInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface ProductVariantRepositoryInterface extends RepositoryInterface
{
    /**
     * @param mixed $productId
     *
     * @return QueryBuilder
     */
    public function createQueryBuilderByProductId($productId);

    /**
     * @param string $name
     * @param string $locale
     *
     * @return ProductVariantInterface[]
     */
    public function findByName($name, $locale);

    /**
     * @param string $name
     * @param string $locale
     * @param ProductInterface $product
     *
     * @return ProductVariantInterface[]
     */
    public function findByNameAndProduct($name, $locale, ProductInterface $product);
}

<?php

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

namespace Sylius\Component\Product\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Product\Model\ProductVariantInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface ProductVariantRepositoryInterface extends RepositoryInterface
{
    /**
     * @param string $locale
     * @param mixed $productId
     *
     * @return QueryBuilder
     */
    public function createQueryBuilderByProductId($locale, $productId);

    /**
     * @param string $name
     * @param string $locale
     *
     * @return ProductVariantInterface[]
     */
    public function findByName($name, $locale);

    /**
     * @param string $name
     * @param string $locale
     * @param ProductInterface $product
     *
     * @return ProductVariantInterface[]
     */
    public function findByNameAndProduct($name, $locale, ProductInterface $product);
}

[ProductVariant] Add locale to product variant query builders


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

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

final class ProductVariantPriceCalculator implements ProductVariantPriceCalculatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int
    {
        Assert::keyExists($context, 'channel');

        $channelPricing = $productVariant->getChannelPricingForChannel($context['channel']);

        if (null === $channelPricing) {
            throw new MissingChannelConfigurationException(sprintf(
                'Channel %s has no price defined for product variant %s',
                $context['channel']->getName(),
                $productVariant->getName()
            ));
        }

        return $channelPricing->getPrice();
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

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

final class ProductVariantPriceCalculator implements ProductVariantPriceCalculatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int
    {
        Assert::keyExists($context, 'channel');

        $channelPricing = $productVariant->getChannelPricingForChannel($context['channel']);

        if (null === $channelPricing) {
            throw new MissingChannelConfigurationException(sprintf(
                'Channel %s has no price defined for product variant %s (%s)',
                $context['channel']->getName(),
                $productVariant->getName(),
                $productVariant->getCode()
            ));
        }

        return $channelPricing->getPrice();
    }
}

Add code to exception message since name can be null


<?php

namespace Purekid\Mongodm\Test\TestCase;

use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;

/**
 * Test Case Base Class for using Phactory *
 */
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
  protected static $db;
  protected static $phactory;

  public static function setUpBeforeClass()
  {
    MongoDB::setConfigBlock('testing', array(
      'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'test_db'
      )
    ));

    self::$db = MongoDB::instance('testing');
    self::$db->connect();

    if (!self::$phactory) {
      self::$phactory = new Phactory(self::$db->getDB());
      self::$phactory->reset();
    }

    //set up Phactory db connection
    self::$phactory->reset();
  }

  public static function tearDownAfterClass()
  {
    foreach (self::$db->getDB()->getCollectionNames() as $collection) {
      self::$db->getDB()->$collection->drop();
    }
  }

  protected function setUp()
  {
  }

  protected function tearDown()
  {
    self::$phactory->recall();
  }
}

<?php

namespace Purekid\Mongodm\Test\TestCase;

use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;

/**
 * Test Case Base Class for using Phactory *
 */
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
  protected static $db;
  protected static $phactory;

  public static function setUpBeforeClass()
  {
    MongoDB::setConfigBlock('testing', array(
      'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'test_db'
      )
    ));

    self::$db = MongoDB::instance('testing');
    self::$db->connect();

    if (!self::$phactory) {
      if (!self::$db->getDB() instanceof \MongoDB) {
        throw new \Exception('Could not connect to MongoDB');
      }

      self::$phactory = new Phactory(self::$db->getDB());
      self::$phactory->reset();
    }

    //set up Phactory db connection
    self::$phactory->reset();
  }

  public static function tearDownAfterClass()
  {
    foreach (self::$db->getDB()->getCollectionNames() as $collection) {
      self::$db->getDB()->$collection->drop();
    }
  }

  protected function setUp()
  {
  }

  protected function tearDown()
  {
    self::$phactory->recall();
  }
}

Throw error on not connected

Throw error on not connected


<?php
require_once __DIR__ . '/../vendor/autoload.php';
if (!defined('PHAST_CONFIG_FILE')) {
    define('PHAST_CONFIG_FILE', __DIR__ . '/config-user.php');
}

<?php
if (!class_exists('\Kibo\Phast\PhastServices')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
if (!defined('PHAST_CONFIG_FILE')) {
    define('PHAST_CONFIG_FILE', __DIR__ . '/config-user.php');
}

Allow using services.php, html-filters.php via Composer


<?php
/**
 * @package plugins.reach
 * @subpackage api.enum
 */
class KalturaCatalogItemLanguage extends KalturaStringEnum
{
	const EN = KalturaLanguage::EN;
	const EN_US = KalturaLanguage::EN_US;
	const EN_GB = KalturaLanguage::EN_GB;
	const NL = KalturaLanguage::NL;
	const FR = KalturaLanguage::FR;
	const DE = KalturaLanguage::DE;
	const IT = KalturaLanguage::IT;
	const ES = KalturaLanguage::ES;
	const AR = KalturaLanguage::AR;
	const ZH = KalturaLanguage::ZH;
	const CMN = KalturaLanguage::CMN;
	const YUE = KalturaLanguage::YUE;
	const HE = KalturaLanguage::HE;
	const HI = KalturaLanguage::HI;
	const JA = KalturaLanguage::JA;
	const KO = KalturaLanguage::KO;
	const PT = KalturaLanguage::PT;
	const RU = KalturaLanguage::RU;
	const TR = KalturaLanguage::TR;
}

<?php
/**
 * @package plugins.reach
 * @subpackage api.enum
 */
class KalturaCatalogItemLanguage extends KalturaStringEnum
{
	const EN = KalturaLanguage::EN;
	const EN_US = KalturaLanguage::EN_US;
	const EN_GB = KalturaLanguage::EN_GB;
	const NL = KalturaLanguage::NL;
	const FR = KalturaLanguage::FR;
	const DE = KalturaLanguage::DE;
	const IT = KalturaLanguage::IT;
	const ES = KalturaLanguage::ES;
	const AR = KalturaLanguage::AR;
	const ZH = KalturaLanguage::ZH;
	const CMN = KalturaLanguage::CMN;
	const YUE = KalturaLanguage::YUE;
	const HE = KalturaLanguage::HE;
	const HI = KalturaLanguage::HI;
	const JA = KalturaLanguage::JA;
	const KO = KalturaLanguage::KO;
	const PT = KalturaLanguage::PT;
	const RU = KalturaLanguage::RU;
	const TR = KalturaLanguage::TR;
	const TH = KalturaLanguage::TH;
}

Add Thai to reach supported languages

PLAT-9061: Add Thai to reach supported languages


<?php

namespace App\Controllers;

use PHLAK\Config\Config;
use Slim\Psr7\Response;
use SplFileInfo;

class FileInfoController
{
    /** @var Config App configuration component */
    protected $config;

    /**
     * Create a new FileInfoController object.
     *
     * @param \PHLAK\Config\Config $config
     */
    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    /**
     * Invoke the FileInfoController.
     *
     * @param \Slim\Psr7\Response $response
     * @param string              $path
     */
    public function __invoke(Response $response, string $path = '.')
    {
        if (! is_file($path)) {
            return $response->withStatus(404, 'File not found');
        }

        $file = new SplFileInfo($path);
        if ($file->getSize() >= $this->config->get('app.max_hash_size', 1000000000)) {
            return $response->withStatus(500, 'File size too large');
        }

        $response->getBody()->write(json_encode([
            'hashes' => [
                'md5' => hash('md5', file_get_contents($file->getPathname())),
                'sha1' => hash('sha1', file_get_contents($file->getPathname())),
                'sha256' => hash('sha256', file_get_contents($file->getPathname())),
            ]
        ]));

        return $response->withHeader('Content-Type', 'application/json');
    }
}

<?php

namespace App\Controllers;

use PHLAK\Config\Config;
use Slim\Psr7\Response;
use SplFileInfo;

class FileInfoController
{
    /** @var Config App configuration component */
    protected $config;

    /**
     * Create a new FileInfoController object.
     *
     * @param \PHLAK\Config\Config $config
     */
    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    /**
     * Invoke the FileInfoController.
     *
     * @param \Slim\Psr7\Response $response
     * @param string              $path
     */
    public function __invoke(Response $response, string $path = '.')
    {
        $file = new SplFileInfo($path);

        if (! $file->isFile()) {
            return $response->withStatus(404, 'File not found');
        }

        if ($file->getSize() >= $this->config->get('app.max_hash_size', 1000000000)) {
            return $response->withStatus(500, 'File size too large');
        }

        $response->getBody()->write(json_encode([
            'hashes' => [
                'md5' => hash('md5', file_get_contents($file->getPathname())),
                'sha1' => hash('sha1', file_get_contents($file->getPathname())),
                'sha256' => hash('sha256', file_get_contents($file->getPathname())),
            ]
        ]));

        return $response->withHeader('Content-Type', 'application/json');
    }
}

Use SplFileInfo::isFile() method for checking if path is a file


<?php

namespace Kanboard\Core\ExternalLink;

/**
 * External Link Provider Interface
 *
 * @package  externalLink
 * @author   Frederic Guillot
 */
interface ExternalLinkProviderInterface
{
    /**
     * Get provider name (label)
     *
     * @access public
     * @return string
     */
    public function getName();

    /**
     * Get link type (will be saved in the database)
     *
     * @access public
     * @return string
     */
    public function getType();

    /**
     * Get a dictionary of supported dependency types by the provider
     *
     * Example:
     *
     * [
     *     'related' => t('Related'),
     *     'child' => t('Child'),
     *     'parent' => t('Parent'),
     *     'self' => t('Self'),
     * ]
     *
     * The dictionary key is saved in the database.
     *
     * @access public
     * @return array
     */
    public function getDependencies();

    /**
     * Set text entered by the user
     *
     * @access public
     * @param  string $input
     */
    public function setUserTextInput($input);

    /**
     * Return true if the provider can parse correctly the user input
     *
     * @access public
     * @return boolean
     */
    public function match();

    /**
     * Get the link found with the properties
     *
     * @access public
     * @return ExternalLinkInterface
     */
    public function getLink();
}

<?php

namespace Kanboard\Core\ExternalLink;

/**
 * External Link Provider Interface
 *
 * @package  externalLink
 * @author   Frederic Guillot
 */
interface ExternalLinkProviderInterface
{
    /**
     * Get provider name (label)
     *
     * @access public
     * @return string
     */
    public function getName();

    /**
     * Get link type (will be saved in the database)
     *
     * @access public
     * @return string
     */
    public function getType();

    /**
     * Get a dictionary of supported dependency types by the provider
     *
     * Example:
     *
     * [
     *     'related' => 'Related',
     *     'child' => 'Child',
     *     'parent' => 'Parent',
     *     'self' => 'Self',
     * ]
     *
     * The dictionary key is saved in the database.
     *
     * @access public
     * @return array
     */
    public function getDependencies();

    /**
     * Set text entered by the user
     *
     * @access public
     * @param  string $input
     */
    public function setUserTextInput($input);

    /**
     * Return true if the provider can parse correctly the user input
     *
     * @access public
     * @return boolean
     */
    public function match();

    /**
     * Get the link found with the properties
     *
     * @access public
     * @return ExternalLinkInterface
     */
    public function getLink();
}

Remove t() from PHPdoc example to avoid confusion


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Formatter;

final class StringInflector
{
    public static function nameToCode(string $value): string
    {
        return str_replace([' ', '-', '\''], '_', $value);
    }

    public static function nameToSlug(string $value): string
    {
        return str_replace([' '], '-', strtolower($value));
    }

    public static function nameToLowercaseCode(string $value): string
    {
        return strtolower(self::nameToCode($value));
    }

    public static function nameToUppercaseCode(string $value): string
    {
        return strtoupper(self::nameToCode($value));
    }

    private function __construct()
    {
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Formatter;

final class StringInflector
{
    public static function nameToCode(string $value): string
    {
        return str_replace([' ', '-', '\''], '_', $value);
    }

    public static function nameToSlug(string $value): string
    {
        return str_replace(['_'], '-', StringInflector::nameToLowercaseCode($value));
    }

    public static function nameToLowercaseCode(string $value): string
    {
        return strtolower(self::nameToCode($value));
    }

    public static function nameToUppercaseCode(string $value): string
    {
        return strtoupper(self::nameToCode($value));
    }

    private function __construct()
    {
    }
}

Add fixes for inflector and tests

Add fixes for inflector and tests


<?php

namespace Northstar\Providers;

use DoSomething\Gateway\Blink;
use Illuminate\Support\ServiceProvider;
use Northstar\Models\User;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::creating(function (User $user) {
            // Set source automatically if not provided.
            $user->source = $user->source ?: client_id();
        });

        User::created(function (User $user) {
            // Send payload to Blink for Customer.io profile.
            if (config('features.blink')) {
                app(Blink::class)->userCreate($user->toBlinkPayload());
            }
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // @TODO: This should be registered in Gateway's service provider!
        $this->app->singleton(Blink::class, function () {
            return new Blink(config('services.blink'));
        });
    }
}

<?php

namespace Northstar\Providers;

use DoSomething\Gateway\Blink;
use Illuminate\Support\ServiceProvider;
use Northstar\Models\User;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::creating(function (User $user) {
            // Set source automatically if not provided.
            $user->source = $user->source ?: client_id();
        });

        User::created(function (User $user) {
            // Send payload to Blink for Customer.io profile.
            if (config('features.blink')) {
                app(Blink::class)->userCreate($user->toBlinkPayload());
            }

            // Send metrics to StatHat.
            app('stathat')->ezCount('user created');
            app('stathat')->ezCount('user created - '.$user->source);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // @TODO: This should be registered in Gateway's service provider!
        $this->app->singleton(Blink::class, function () {
            return new Blink(config('services.blink'));
        });
    }
}

Add StatHat metrics for user creation.

Add StatHat metrics for user creation.


<?php namespace Hybrid;

use \Closure;

class Core
{
	public static function start() { }

	public static function import($file_path, $folder, $scope = 'hybrid')
	{
		switch ($scope)
		{
			case 'hybrid' :
				$scope = Bundle::path('hybrid');
				break;
			case 'app' :
			case 'sys' :
				$scope = path($scope);
			default :
				$scope = __DIR__.DS;
		}

		$file_path = str_replace('/', DS, $path);

		$file = $scope.$folder.DS.$file_path.EXT;

		if (is_file($file))
		{
			require_once $scope.$folder.DS.$file_path.EXT;
		}
	}
}

<?php namespace Hybrid;

use \Closure;

class Core
{
	/**
	 * Start Hybrid
	 *
	 * @static
	 * @access  public
	 * @return  void
	 */
	public static function start()
	{

	}

	/**
	 * Import file
	 *
	 * @static
	 * @access  public
	 * @param   string      $file_path
	 * @param   string      $folder
	 * @param   string      $scope
	 * @return  void
	 */
	public static function import($file_path, $folder, $scope = 'hybrid')
	{
		switch ($scope)
		{
			case 'hybrid' :
				$scope = Bundle::path('hybrid');
				break;
			case 'app' :
			case 'sys' :
				$scope = path($scope);
			default :
				$scope = __DIR__.DS;
		}

		$file_path = str_replace('/', DS, $path);

		$file = $scope.$folder.DS.$file_path.EXT;

		if (is_file($file))
		{
			include $scope.$folder.DS.$file_path.EXT;
		}
	}
}

Update Hybrid\Core::import to use include instead of require_once, and add some docblock


<?php

namespace Phuby;

class Method extends Object {
    protected $unbound;
    protected $receiver;

    function initialize($unbound, $receiver) {
        $this->unbound = $unbound;
        $this->receiver = $receiver;
    }

    function call($args = null) {
        return call_user_func_array($this->to_proc(), func_get_args());
    }

    function inspect() {
        return '<'.get_called_class().': '.get_class($this->receiver).'#'.$this->unbound->name().'>';
    }

    function receiver() {
        return $this->receiver;
    }

    function splat($args) {
        return call_user_func_array([$this, 'call'], $args);
    }

    function to_proc() {
        return $this->unbound->to_proc()->bindTo($this->receiver);
    }

    function unbind() {
        return $this->unbound;
    }
}

<?php

namespace Phuby;

class Method extends Object {
    static function initialized($self) {
        $self->attr_reader('receiver');
    }

    function initialize($unbound, $receiver) {
        $this->{'@unbound'} = $unbound;
        $this->{'@receiver'} = $receiver;
    }

    function call($args = null) {
        return call_user_func_array($this->to_proc(), func_get_args());
    }

    function inspect() {
        return '<'.get_called_class().': '.get_class($this->{'@receiver'}).'#'.$this->{'@unbound'}->name().'>';
    }

    function splat($args) {
        return call_user_func_array([$this, 'call'], $args);
    }

    function to_proc() {
        return $this->{'@unbound'}->to_proc()->bindTo($this->{'@receiver'});
    }

    function unbind() {
        return $this->{'@unbound'};
    }
}

Use ruby style instance variables for Method


James DiGioia

Social Media and Web Development

        <?php if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'left'));
        endif; ?>

Add a bunch of icons for testing

Add a bunch of icons for testing


<?php

namespace Concrete\Core\Express\Entry\Formatter;

use Concrete\Core\Entity\Express\Entry;
use Concrete\Core\Express\Formatter\FormatterInterface;

class LabelFormatter implements EntryFormatterInterface
{

    /** @var \Concrete\Core\Express\Formatter\FormatterInterface */
    protected $formatter;

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

    /**
     * Format a mask given an entry
     * @param string $mask
     * @param \Concrete\Core\Entity\Express\Entry $entry
     * @return string|null
     */
    public function format($mask, Entry $entry)
    {
        return $this->formatter->format($mask, function($key) use ($entry) {
            $attribute = $entry->getAttribute($key);
            if ($attribute) {
                return $attribute;
            }

            $association = $entry->getAssociation($key);
            if (is_object($association)) {
                return $association->getSelectedEntry()->getLabel();
            }
        });
    }

    public function getLabel(Entry $entry)
    {
        foreach($entry->getEntity()->getAttributes() as $ak) {
            if ($ak->getAttributeType()->getAttributeTypeHandle() == 'text') {
                return $entry->getAttribute($ak);
            }
        }

    }

}

<?php

namespace Concrete\Core\Express\Entry\Formatter;

use Concrete\Core\Entity\Express\Entry;
use Concrete\Core\Express\Formatter\FormatterInterface;

class LabelFormatter implements EntryFormatterInterface
{

    /** @var \Concrete\Core\Express\Formatter\FormatterInterface */
    protected $formatter;

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

    /**
     * Format a mask given an entry
     * @param string $mask
     * @param \Concrete\Core\Entity\Express\Entry $entry
     * @return string|null
     */
    public function format($mask, Entry $entry)
    {
        return $this->formatter->format($mask, function($key) use ($entry) {
            if ($key === 'id') {
                return $entry->getID();
            }

            $attribute = $entry->getAttribute($key);
            if ($attribute) {
                return $attribute;
            }

            $association = $entry->getAssociation($key);
            if (is_object($association)) {
                return $association->getSelectedEntry()->getLabel();
            }
        });
    }

    public function getLabel(Entry $entry)
    {
        foreach($entry->getEntity()->getAttributes() as $ak) {
            if ($ak->getAttributeType()->getAttributeTypeHandle() == 'text') {
                return $entry->getAttribute($ak);
            }
        }

    }

}

Make it possible to include the ID in the name mask

For example an entry mask could be "Boat #%id%" and the result would be "Boat #5"


<?php

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

namespace Composer\Package\LinkConstraint;

use Composer\Semver\Constraint\AbstractConstraint;

trigger_error('The ' . __NAMESPACE__ . '\SpecificConstraint abstract class is deprecated, use Composer\Semver\Constraint\AbstractConstraint instead.', E_USER_DEPRECATED);

/**
 * @deprecated use Composer\Semver\Constraint\AbstractConstraint instead
 */
abstract class SpecificConstraint extends AbstractConstraint implements LinkConstraintInterface
{
}

<?php

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

namespace Composer\Package\LinkConstraint;

use Composer\Semver\Constraint\AbstractConstraint;

trigger_error('The ' . __NAMESPACE__ . '\SpecificConstraint abstract class is deprecated, there is no replacement for it.', E_USER_DEPRECATED);

/**
 * @deprecated use Composer\Semver\Constraint\AbstractConstraint instead
 */
abstract class SpecificConstraint extends AbstractConstraint implements LinkConstraintInterface
{
}

Clarify that the abstract constraint should not be relied upon anymore


<?php

uses(Tests\TestCase::class)->in(__DIR__);

uses()->group('components')->in(__DIR__.'/Components');

Add a group name to the Components

Add a group name to the Components