<?php

namespace NemC\IP2LocLite\Commands;

use Illuminate\Console\Config,
    Illuminate\Console\Command,
    NemC\IP2LocLite\Services\IP2LocLiteService,
    NemC\IP2LocLite\Exceptions\NotLoggedInResponseException,
    NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException;

class DownloadCsvCommand extends Command
{
    protected $name = 'ip2loclite:download-csv';
    protected $description = 'Login to IP2Location user panel and download required csv';

    protected $ip2LocLite;

    public function __construct(IP2LocLiteService $IP2LocLiteService)
    {
        parent::__construct();
        $this->ip2LocLite = $IP2LocLiteService;
    }

    public function fire()
    {
        $database = Config::get('ip2loc-lite.database');
        try {
            $this->ip2LocLite->isSupportedDatabase($database);
        } catch (UnsupportedDatabaseCommandException $e) {
            $this->error('Free IP2Location database "' . $database . '"" is not supported by IP2LocLite at this point');
            return false;
        }

        try {
            $this->ip2LocLite->login();
        } catch (NotLoggedInResponseException $e) {
            $this->error('Could not log you in with user authentication details provided');
            return false;
        }

        $this->ip2LocLite->downloadCsv($database);

        $this->info('Latest version of IP2Location database ' . $database . ' has been downloaded');
    }
}

<?php

namespace NemC\IP2LocLite\Commands;

use Illuminate\Support\Facades\Config,
    Illuminate\Console\Command,
    NemC\IP2LocLite\Services\IP2LocLiteService,
    NemC\IP2LocLite\Exceptions\NotLoggedInResponseException,
    NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException;

class DownloadCsvCommand extends Command
{
    protected $name = 'ip2loclite:download-csv';
    protected $description = 'Login to IP2Location user panel and download required csv';

    protected $ip2LocLite;

    public function __construct(IP2LocLiteService $IP2LocLiteService)
    {
        parent::__construct();
        $this->ip2LocLite = $IP2LocLiteService;
    }

    public function fire()
    {
        $database = Config::get('ip2loc-lite.database');
        try {
            $this->ip2LocLite->isSupportedDatabase($database);
        } catch (UnsupportedDatabaseCommandException $e) {
            $this->error('Free IP2Location database "' . $database . '"" is not supported by IP2LocLite at this point');
            return false;
        }

        try {
            $this->ip2LocLite->login();
        } catch (NotLoggedInResponseException $e) {
            $this->error('Could not log you in with user authentication details provided');
            return false;
        }

        $this->ip2LocLite->downloadCsv($database);

        $this->info('Latest version of IP2Location database ' . $database . ' has been downloaded');
    }
}

Fix Config loading in DownloadCsv

Fix Config loading in DownloadCsv


<?php
namespace Saft\Sparql\Test\Result;

class ResultUnitTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Contains an instance of the class to test.
     *
     * @var mixed
     */
    protected $fixture;

    /**
     *
     */
    public function setUp()
    {
        $this->fixture = $this->getMockBuilder('Saft\Store\Result\Result')->getMock();
    }

    /**
     * Tests getResultObject
     */

    public function testGetResultObject()
    {
        $this->assertEquals(
            null,
            $this->fixture->getResultObject()
        );
    }
}

<?php
namespace Saft\Sparql\Test\Result;

class ResultUnitTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Contains an instance of the class to test.
     *
     * @var mixed
     */
    protected $fixture;

    /**
     *
     */
    public function setUp()
    {
        $this->fixture = $this->getMockBuilder('Saft\Sparql\Result\Result')->getMock();
    }

    /**
     * Tests getResultObject
     */

    public function testGetResultObject()
    {
        $this->assertEquals(
            null,
            $this->fixture->getResultObject()
        );
    }
}

Fix namespace in result test

Fix namespace in result test


<?
$DBUSER = '';
$DBPASSWORD = '';
$DBNAME = '';
$DBHOST = 'localhost';
$DBTABLEPREFIX = '';
$CONTACTTO = "pixel@copei.de";
$CONTACTSUBJECT = "Ihre Nachricht an Shop Hope Stamps";
$GALLERYARCHIVEPATH = "/preview/shophope/gallery-images";
$GALLERYPAGESIZE = 12;
$THUMBNAILWIDTH = 200;
$THUMBNAILHEIGHT = 240;
?>

<?
$DBUSER = '';
$DBPASSWORD = '';
$DBNAME = '';
$DBHOST = 'localhost';
$DBTABLEPREFIX = '';
$CONTACTTO = "pixel@copei.de";
$CONTACTSUBJECT = "Your message to Shop Hope Stamps";
$GALLERYARCHIVEPATH = "/preview/shophope/gallery-images";
$GALLERYPAGESIZE = 12;
$THUMBNAILWIDTH = 200;
$THUMBNAILHEIGHT = 240;
?>

Make more clean what needs to be tweaked.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>RockMongo</title>
<script language="javascript" src="js/jquery-1.4.2.min.js"></script>
<script language="javascript" src="js/jquery.textarea.js"></script>
<link rel="stylesheet" href="<?php render_theme_path() ?>/css/global.css" type="text/css" media="all"/>
<?php render_page_header(); ?>
<script language="javascript">
$(function () {
	$(document).click(window.parent.hideMenus);
	if ($("textarea").length > 0) {
		$("textarea").tabby();
	}
});
</script>
</head>
<body>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>RockMongo</title>
<?php if (php_sapi_name() === 'cli-server'): ?>
<base href="/"/>
<?php endif; ?>
<script language="javascript" src="js/jquery-1.4.2.min.js"></script>
<script language="javascript" src="js/jquery.textarea.js"></script>
<link rel="stylesheet" href="<?php render_theme_path() ?>/css/global.css" type="text/css" media="all"/>
<?php render_page_header(); ?>
<script language="javascript">
$(function () {
	$(document).click(window.parent.hideMenus);
	if ($("textarea").length > 0) {
		$("textarea").tabby();
	}
});
</script>
</head>
<body>

Fix routing problem when running in PHP web server.

Before: http://localhost/index.php/themes/default/css/global.css
After: http://localhost/themes/default/css/global.css


<?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\Bundle\UiBundle\Menu\Event;

use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * @author Patrik Karisch <patrik.karisch@abimus.com>
 */
final class MenuBuilderEvent extends Event
{
    /**
     * @var FactoryInterface
     */
    private $factory;

    /**
     * @var ItemInterface
     */
    private $menu;

    /**
     * @param FactoryInterface $factory
     * @param ItemInterface $menu
     */
    public function __construct(FactoryInterface $factory, ItemInterface $menu)
    {
        $this->factory = $factory;
        $this->menu = $menu;
    }

    /**
     * @return FactoryInterface
     */
    public function getFactory()
    {
        return $this->factory;
    }

    /**
     * @return ItemInterface
     */
    public function getMenu()
    {
        return $this->menu;
    }
}

<?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\Bundle\UiBundle\Menu\Event;

use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * @author Patrik Karisch <patrik.karisch@abimus.com>
 */
class MenuBuilderEvent extends Event
{
    /**
     * @var FactoryInterface
     */
    private $factory;

    /**
     * @var ItemInterface
     */
    private $menu;

    /**
     * @param FactoryInterface $factory
     * @param ItemInterface $menu
     */
    public function __construct(FactoryInterface $factory, ItemInterface $menu)
    {
        $this->factory = $factory;
        $this->menu = $menu;
    }

    /**
     * @return FactoryInterface
     */
    public function getFactory()
    {
        return $this->factory;
    }

    /**
     * @return ItemInterface
     */
    public function getMenu()
    {
        return $this->menu;
    }
}

[Admin] Add custom events for order and customer show menu builders


<?php

namespace Lstr\Sprintf;

class ParsedExpression
{
    /**
     * @var string
     */
    private $parsed_format;

    /**
     * @var array
     */
    private $parameter_map;

    /**
     * @param string $parsed_format
     * @param array $parameter_map
     */
    public function __construct($parsed_format, array $parameter_map)
    {
        $this->parsed_format = $parsed_format;
        $this->parameter_map = $parameter_map;
    }

    /**
     * @param array $parameters
     * @param callable|null $middleware
     * @return string
     * @throws Exception
     */
    public function format(array $parameters, callable $middleware = null)
    {
        if (!$middleware) {
            $middleware = function ($name, $value, array $options) {
                return $value;
            };
        }

        $parsed_parameters = [];
        foreach ($this->parameter_map as $param_mapping) {
            $param_name = $param_mapping['name'];

            if (!array_key_exists($param_name, $parameters)) {
                throw new Exception(
                    "The '{$param_name}' parameter was in the format string but was not provided"
                );
            }

            $parsed_parameters[] = $middleware($param_name, $parameters[$param_name], []);
        }

        return vsprintf($this->parsed_format, $parsed_parameters);
    }
}

<?php

namespace Lstr\Sprintf;

class ParsedExpression
{
    /**
     * @var string
     */
    private $parsed_format;

    /**
     * @var array
     */
    private $parameter_map;

    /**
     * @param string $parsed_format
     * @param array $parameter_map
     */
    public function __construct($parsed_format, array $parameter_map)
    {
        $this->parsed_format = $parsed_format;
        $this->parameter_map = $parameter_map;
    }

    /**
     * @param array $parameters
     * @param callable|null $middleware
     * @return string
     * @throws Exception
     */
    public function format(array $parameters, callable $middleware = null)
    {
        if (!$middleware) {
            $middleware = function ($name, $value, array $options) {
                return $value;
            };
        }

        $parsed_parameters = [];
        foreach ($this->parameter_map as $param_mapping) {
            $param_name = $param_mapping['name'];

            if (!array_key_exists($param_name, $parameters)) {
                throw new Exception(
                    "The '{$param_name}' parameter was in the format string but was not provided"
                );
            }

            $parsed_parameters[] = call_user_func(
                $middleware,
                $param_name,
                $parameters[$param_name],
                []
            );
        }

        return vsprintf($this->parsed_format, $parsed_parameters);
    }
}

Allow middleware to also be non-function callables


<?php

namespace Alazjj\SimpleBootstrapBundle\Tests\Form\Extension;

use Alazjj\SimpleBootstrapBundle\Form\Extension\AljjazExtension;
use Symfony\Component\Form\Tests\Extension\Core\Type\TypeTestCase;

class ChoiceTypeTest extends TypeTestCase
{
    private $choices = array(
        1 => 'Ursaff',
        2 => 'Cancras',
        3 => 'Carbalas'
    );

    public function testChoicesOptionExpectsArray()
    {
        $valueBinded = 3;
        $this->checkViewVars($valueBinded, $this->choices[$valueBinded]);
        $this->checkViewVars($valueBinded, $valueBinded, true);
    }

    protected function checkViewVars($valueBinded, $value, $isActive = false)
    {
        $form = $this->factory->create('choice', null, array(
            'choices' => $this->choices,
            'is_active' => $isActive,
        ));
        $form->bind($valueBinded);
        $view = $form->createView();

        $this->assertEquals($value, $view->vars['value']);
    }

    protected function getExtensions()
    {
        return array(
            new AljjazExtension()
        );
    }
}

<?php

namespace Alazjj\SimpleBootstrapBundle\Tests\Form\Extension;

use Alazjj\SimpleBootstrapBundle\Form\Extension\AljjazExtension;
use Symfony\Component\Form\Tests\Extension\Core\Type\TypeTestCase;

class ChoiceTypeTest extends TypeTestCase
{
    private $choices = array(
        1 => 'Ursaff',
        2 => 'Cancras',
        3 => 'Carbalas'
    );

    public function testChoicesOptionExpectsArray()
    {
        $valueBinded = 3;
        $this->checkViewVars($valueBinded, $this->choices[$valueBinded], array(
            'choices' => $this->choices,
            'is_active' => false,
        ));

        $this->checkViewVars($valueBinded, $valueBinded, array(
            'choices' => $this->choices,
            'is_active' => true,
        ));

        $this->checkViewVars($valueBinded, array(false, false, true), array(
            'choices' => $this->choices,
            'is_active' => false,
            'expanded' => true,
            'multiple' => false
        ));

        $this->checkViewVars($valueBinded, array(false, false, true), array(
            'choices' => $this->choices,
            'is_active' => true,
            'expanded' => true,
            'multiple' => false
        ));
    }

    protected function checkViewVars($valueBinded, $value, array $options)
    {
        $form = $this->factory->create('choice', null, $options);
        $form->bind($valueBinded);
        $view = $form->createView();

        $this->assertEquals($value, $view->vars['value'], "Invalid display choix field value");
    }

    protected function getExtensions()
    {
        return array(
            new AljjazExtension()
        );
    }
}

Add news testes to choice field testes

Add news testes to choice field testes


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Middleware;

use App\Libraries\User\DatadogLoginAttempt;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [
        'oauth/authorize',
        'oauth/access_token',
    ];

    public function handle($request, Closure $next)
    {
        try {
            return parent::handle($request, $next);
        } catch (TokenMismatchException $e) {
            $currentRouteData = app('route-section')->getCurrent();
            $currentRoute = "{$currentRouteData['controller']}@{$currentRouteData['action']}";

            if ($currentRoute === 'sessions_controller@store') {
                DatadogLoginAttempt::log('invalid_csrf');
            }

            throw new $e('Reload page and try again');
        }
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Middleware;

use App\Libraries\User\DatadogLoginAttempt;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [
        'home/changelog/github',
        'oauth/access_token',
        'oauth/authorize',
        'payments/centili/callback',
        'payments/paypal/ipn',
        'payments/shopify/callback',
        'payments/xsolla/callback',
        'users',
    ];

    public function handle($request, Closure $next)
    {
        try {
            return parent::handle($request, $next);
        } catch (TokenMismatchException $e) {
            $currentRouteData = app('route-section')->getCurrent();
            $currentRoute = "{$currentRouteData['controller']}@{$currentRouteData['action']}";

            if ($currentRoute === 'sessions_controller@store') {
                DatadogLoginAttempt::log('invalid_csrf');
            }

            throw new $e('Reload page and try again');
        }
    }
}

Exclude more urls from token check

Exclude more urls from token check

Callback url and registrations.


<?php

declare(strict_types=1);

namespace CultuurNet\UDB3\Event\ValueObjects;

use InvalidArgumentException;

final class StatusType
{
    private const SCHEDULED = 'EventScheduled';
    private const POSTPONED = 'EventPostponed';
    private const CANCELLED = 'EventCancelled';

    /**
     * @var string
     */
    private $value;

    /**
     * @var string[]
     */
    private const ALLOWED_VALUES = [
        self::SCHEDULED,
        self::POSTPONED,
        self::CANCELLED,
    ];

    private function __construct(string $value)
    {
        if (!\in_array($value, self::ALLOWED_VALUES, true)) {
            throw new InvalidArgumentException('Status does not support the value "' . $value . '"');
        }
        $this->value = $value;
    }

    public static function scheduled(): StatusType
    {
        return new StatusType(self::SCHEDULED);
    }

    public static function postponed(): StatusType
    {
        return new StatusType(self::POSTPONED);
    }

    public static function cancelled(): StatusType
    {
        return new StatusType(self::CANCELLED);
    }

    public function toNative(): string
    {
        return $this->value;
    }

    public static function fromNative(string $value): StatusType
    {
        return new StatusType($value);
    }

    public function equals(StatusType $status): bool
    {
        return $this->value === $status->toNative();
    }
}

<?php

declare(strict_types=1);

namespace CultuurNet\UDB3\Event\ValueObjects;

use InvalidArgumentException;

final class StatusType
{
    private const AVAILABLE = 'Available';
    private const TEMPORARILY_UNAVAILABLE = 'TemporarilyUnavailable';
    private const UNAVAILABLE = 'Unavailable';

    /**
     * @var string
     */
    private $value;

    /**
     * @var string[]
     */
    private const ALLOWED_VALUES = [
        self::AVAILABLE,
        self::TEMPORARILY_UNAVAILABLE,
        self::UNAVAILABLE,
    ];

    private function __construct(string $value)
    {
        if (!\in_array($value, self::ALLOWED_VALUES, true)) {
            throw new InvalidArgumentException('Status does not support the value "' . $value . '"');
        }
        $this->value = $value;
    }

    public static function scheduled(): StatusType
    {
        return new StatusType(self::AVAILABLE);
    }

    public static function postponed(): StatusType
    {
        return new StatusType(self::TEMPORARILY_UNAVAILABLE);
    }

    public static function cancelled(): StatusType
    {
        return new StatusType(self::UNAVAILABLE);
    }

    public function toNative(): string
    {
        return $this->value;
    }

    public static function fromNative(string $value): StatusType
    {
        return new StatusType($value);
    }

    public function equals(StatusType $status): bool
    {
        return $this->value === $status->toNative();
    }
}

Remove constants and internal value of status types


<?php
/**
 * @file
 * Containt Drupal\AppConsole\Generator\ControllerGenerator.
 */

namespace Drupal\AppConsole\Generator;

class ControllerGenerator extends Generator
{

  public function generate($module, $class_name, $method_name, $route, $test, $services, $class_machine_name)
  {

    $parameters = array(
      'class_name' => $class_name,
      'services' => $services,
      'module' => $module,
      'method_name' => $method_name,
      'route' => $route,
    );

    $this->renderFile(
      'module/module.controller.php.twig',
      $this->getControllerPath($module).'/'.$class_name.'.php',
      $parameters
    );

    $this->renderFile(
      'module/controller-routing.yml.twig',
      $this->getModulePath($module).'/'.$module.'.routing.yml',
      $parameters,
      FILE_APPEND
    );

    if ($test) {
      $this->renderFile(
        'module/module.test.twig',
        $this->getTestPath($module).'/'.$class_name.'Test.php',
        $parameters
      );
    }
  }
}

<?php
/**
 * @file
 * Containt Drupal\AppConsole\Generator\ControllerGenerator.
 */

namespace Drupal\AppConsole\Generator;

class ControllerGenerator extends Generator
{

  public function generate($module, $class_name, $method_name, $route, $test, $services, $class_machine_name)
  {

    $parameters = array(
      'class_name' => $class_name,
      'services' => $services,
      'module' => $module,
      'method_name' => $method_name,
      'class_machine_name' => $class_machine_name,
      'route' => $route,
    );

    $this->renderFile(
      'module/module.controller.php.twig',
      $this->getControllerPath($module).'/'.$class_name.'.php',
      $parameters
    );

    $this->renderFile(
      'module/controller-routing.yml.twig',
      $this->getModulePath($module).'/'.$module.'.routing.yml',
      $parameters,
      FILE_APPEND
    );

    if ($test) {
      $this->renderFile(
        'module/module.test.twig',
        $this->getTestPath($module).'/'.$class_name.'Test.php',
        $parameters
      );
    }
  }
}

Add class_machine_name var to paramaters array


<?php
// src/Acme/UserBundle/Entity/User.php

namespace MarkMx\UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }
}

<?php
// src/Acme/UserBundle/Entity/User.php

namespace MarkMx\UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }
}

Update user base class path following deprecation warning


<?php

namespace OpenDominion\Models;

class Realm extends AbstractModel
{
    public function dominions()
    {
        // todo: hasMany
    }

    public function monarch()
    {
//        return $this->hasOne(Dominion::class, 'id', 'monarch_dominion_id');
    }

    public function round()
    {
        return $this->belongsTo(Round::class);
    }
}

<?php

namespace OpenDominion\Models;

class Realm extends AbstractModel
{
    public function dominions()
    {
        return $this->hasMany(Dominion::class);
    }

    public function monarch()
    {
//        return $this->hasOne(Dominion::class, 'id', 'monarch_dominion_id');
    }

    public function round()
    {
        return $this->belongsTo(Round::class);
    }
}

Add relationship from realm to dominion

Add relationship from realm to dominion


<?php require_once 'config.php';

function print_files($url, $dir)
{
  $hide = ".";

  $myDirectory = opendir($dir);

  while ($entryName = readdir($myDirectory))
  {
    $dirArray[] = $entryName;
  }

  closedir($myDirectory);

  $indexCount = count($dirArray);

  sort($dirArray);

  for ($index = 0; $index < $indexCount; $index++)
  {
    if (substr("$dirArray[$index]", 0, 1) != $hide)
    {
      $name = $dirArray[$index];
      $namehref = $dirArray[$index];
      echo("

          $name

      ");
    }
  }
}

<?php require_once 'config.php';

if ($env == 'production') {
  error_reporting(E_ERROR | E_PARSE);
}

function print_files($url, $dir)
{
  $hide = ".";

  $myDirectory = opendir($dir);

  if ($myDirectory) {
    while ($entryName = readdir($myDirectory))
    {
      $dirArray[] = $entryName;
    }

    closedir($myDirectory);

    $indexCount = count($dirArray);

    sort($dirArray);

    for ($index = 0; $index < $indexCount; $index++)
    {
      if (substr("$dirArray[$index]", 0, 1) != $hide)
      {
        $name = $dirArray[$index];
        $namehref = $dirArray[$index];
        echo("

            $name

        ");
      }
    }
  } else {
    echo("

Couldn't open the directory specified.

    ");
  }
}

Add error message if directory can't be read


<?php namespace Flarum\Api\Serializers;

class DiscussionBasicSerializer extends BaseSerializer
{
    /**
     * The resource type.
     *
     * @var string
     */
    protected $type = 'discussions';

    /**
     * Serialize attributes of a Discussion model for JSON output.
     *
     * @param Discussion $discussion The Discussion model to serialize.
     * @return array
     */
    protected function attributes($discussion)
    {
        $attributes = [
            'title' => $discussion->title
        ];

        return $this->extendAttributes($discussion, $attributes);
    }

    public function startUser()
    {
        return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
    }

    public function startPost()
    {
        return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
    }

    public function lastUser()
    {
        return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
    }

    public function lastPost()
    {
        return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
    }

    public function posts()
    {
        return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
    }

    public function relevantPosts()
    {
        return $this->hasMany('Flarum\Api\Serializers\PostBasicSerializer');
    }

    public function addedPosts()
    {
        return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
    }
}

<?php namespace Flarum\Api\Serializers;

class DiscussionBasicSerializer extends BaseSerializer
{
    /**
     * The resource type.
     *
     * @var string
     */
    protected $type = 'discussions';

    /**
     * Serialize attributes of a Discussion model for JSON output.
     *
     * @param Discussion $discussion The Discussion model to serialize.
     * @return array
     */
    protected function attributes($discussion)
    {
        $attributes = [
            'title' => $discussion->title
        ];

        if (count($discussion->removedPosts)) {
            $attributes['removedPosts'] = $discussion->removedPosts;
        }

        return $this->extendAttributes($discussion, $attributes);
    }

    public function startUser()
    {
        return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
    }

    public function startPost()
    {
        return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
    }

    public function lastUser()
    {
        return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
    }

    public function lastPost()
    {
        return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
    }

    public function posts()
    {
        return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
    }

    public function relevantPosts()
    {
        return $this->hasMany('Flarum\Api\Serializers\PostBasicSerializer');
    }

    public function addedPosts()
    {
        return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
    }
}

Add removed posts as an API attribute

Add removed posts as an API attribute


<?php
namespace Relay;

use ArrayObject;
use InvalidArgumentException;
use Traversable;

class RelayBuilderTest extends \PHPUnit\Framework\TestCase
{
    protected $relayBuilder;

    protected function setUp()
    {
        $this->relayBuilder = new RelayBuilder();
    }

    public function testArray()
    {
        $queue = [];
        $relay = $this->relayBuilder->newInstance($queue);
        $this->assertInstanceOf('Relay\Relay', $relay);
    }

    public function testArrayObject()
    {
        $queue = new ArrayObject([]);
        $relay = $this->relayBuilder->newInstance($queue);
        $this->assertInstanceOf('Relay\Relay', $relay);

        $relay = $this->relayBuilder->newInstance($queue);
        $this->assertInstanceOf('Relay\Relay', $relay);
    }

    public function testTraversable()
    {
        $queue = $this->createMock(Traversable::class);

        $relay = $this->relayBuilder->newInstance($queue);
        $this->assertInstanceOf('Relay\Relay', $relay);
    }

    public function testInvalidArgument()
    {
        $this->expectException('TypeError');
        $this->relayBuilder->newInstance('bad argument');
    }
}

<?php
namespace Relay;

use ArrayObject;
use InvalidArgumentException;
use Traversable;

class RelayBuilderTest extends \PHPUnit\Framework\TestCase
{
    protected $relayBuilder;

    protected function setUp()
    {
        $this->relayBuilder = new RelayBuilder();
    }

    public function testArray()
    {
        $queue = [];
        $relay = $this->relayBuilder->newInstance($queue);
        $this->assertInstanceOf('Relay\Relay', $relay);
    }

    public function testArrayObject()
    {
        $queue = new ArrayObject([]);
        $relay = $this->relayBuilder->newInstance($queue);
        $this->assertInstanceOf('Relay\Relay', $relay);
    }

    public function testTraversable()
    {
        $queue = $this->createMock(Traversable::class);

        $relay = $this->relayBuilder->newInstance($queue);
        $this->assertInstanceOf('Relay\Relay', $relay);
    }

    public function testInvalidArgument()
    {
        $this->expectException('TypeError');
        $this->relayBuilder->newInstance('bad argument');
    }
}

Remove duplicated lines in test

Remove duplicated lines in test


<?php

/**
 * Copyright 2014 SURFnet bv
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\StepupMiddlewareClientBundle\Identity\Dto;

use Surfnet\StepupMiddlewareClientBundle\Dto\CollectionDto;

class RaListingCollection extends CollectionDto
{
    protected static function createElementFromData(array $raListing)
    {
        return RaListing::fromData($raListing);
    }
}

<?php

/**
 * Copyright 2014 SURFnet bv
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\StepupMiddlewareClientBundle\Identity\Dto;

use Surfnet\StepupMiddlewareClientBundle\Dto\CollectionDto;

class RaListingCollection extends CollectionDto
{
    protected static function createElementFromData(array $raListing)
    {
        return RaListing::fromData($raListing);
    }

    /**
     * Checks if a certain institution is listed in the RA listing
     * @param $institution
     * @return bool
     */
    public function isListed($institution)
    {
        /** @var RaListing $raListing */
        foreach ($this->getElements() as $raListing) {
            if ($raListing->institution === $institution) {
                return true;
            }
        }
        return false;
    }
}

Allow testing if institution is listed

Allow testing if institution is listed

This check is used to select the preferred institution for the
authenticating RA(A).


<?php

/**
 * Class ConnectionTest.
 */
class ConnectionTest extends PHPUnit_Framework_TestCase
{
    public function testExceptionIfNoServerFound()
    {
        $this->expectException('\Symfony\Component\Console\Exception\RuntimeException');
        $this->expectExceptionMessage('No server config found.');

        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $connection->getConnection(new \Antwerpes\ADeployer\Model\Target('demo', []));
    }

    public function testExceptionIfNoServerSchemeNotSupported()
    {
        $this->expectException('\Symfony\Component\Console\Exception\RuntimeException');
        $this->expectExceptionMessage('Unsupported connection scheme: fooBar');

        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $connection->getConnection(new \Antwerpes\ADeployer\Model\Target('demo', ['server' => ['scheme' => 'fooBar']]));
    }

    public function testGetSftpConnection()
    {
        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $this->assertInstanceOf('\League\Flysystem\Sftp\SftpAdapter', $connection->createSftpConnection([]));
    }

    public function testGetFtpConnection()
    {
        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $this->assertInstanceOf('\League\Flysystem\Adapter\Ftp', $connection->createFtpConnection([]));
    }

}

<?php

/**
 * Class ConnectionTest.
 */
class ConnectionTest extends PHPUnit_Framework_TestCase
{
    public function testExceptionIfNoServerFound()
    {
        $this->expectException('\Symfony\Component\Console\Exception\RuntimeException');
        $this->expectExceptionMessage('No server config found.');

        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $connection->getConnection(new \Antwerpes\ADeployer\Model\Target('demo', []));
    }

    public function testExceptionIfNoServerSchemeNotSupported()
    {
        $this->expectException('\Symfony\Component\Console\Exception\RuntimeException');
        $this->expectExceptionMessage('Unsupported connection scheme: fooBar');

        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $connection->getConnection(new \Antwerpes\ADeployer\Model\Target('demo', ['server' => ['scheme' => 'fooBar']]));
    }

    public function testGetSftpConnection()
    {
        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $this->assertInstanceOf('\League\Flysystem\Sftp\SftpAdapter', $connection->createSftpConnection([]));
    }

    public function testGetFtpConnection()
    {
        if (defined('FTP_BINARY') === false) {
            define('FTP_BINARY', 2);
        }
        $connection = new \Antwerpes\ADeployer\Service\Connection();
        $this->assertInstanceOf('\League\Flysystem\Adapter\Ftp', $connection->createFtpConnection([]));
    }

}

Fix for tests running on PHP 7.

Fix for tests running on PHP 7.


<?php
require_once __DIR__ . '/deployer/recipe/yii2-app-advanced.php';
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';

if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
  die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');

set('default_stage', 'production');

set('keep_releases', 2);

set('writable_use_sudo', false); // Using sudo in writable commands?

task('deploy:configure_composer', function () {
  $stage = env('app.stage');
  if($stage == 'dev') {
    env('composer_options', 'install --verbose --no-progress --no-interaction');
  }
})->desc('Configure composer');

// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');

before('deploy:vendors', 'deploy:configure_composer');
before('deploy:symlink', 'deploy:configure');

<?php
require_once __DIR__ . '/deployer/recipe/yii2-app-advanced.php';
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';

if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
  die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');

set('default_stage', 'production');

set('keep_releases', 2);

set('writable_use_sudo', false); // Using sudo in writable commands?

task('deploy:configure_composer', function () {
  $stage = env('app.stage');
  if($stage == 'dev') {
    env('composer_options', 'install --verbose --no-progress --no-interaction');
  }
})->desc('Configure composer');

// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');

before('deploy:vendors', 'deploy:configure_composer');
before('inplace:vendors', 'deploy:configure_composer');
before('deploy:symlink', 'deploy:configure');

Fix composer for inplace in dev mode

Fix composer for inplace in dev mode


<?php
namespace Generics\Logger;

use Psr\Log\LogLevel;

/**
 * This class is a standard reference implementation of the PSR LoggerInterface.
 *
 * It logs everything to console. Depending on level it is written to stdout or stderr.
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class ConsoleLogger extends BasicLogger
{
    protected function logImpl($level, $message, array $context = array())
    {
        $channel = STDOUT;

        if($level === LogLevel::ALERT || $level === LogLevel::CRITICAL || $level === LogLevel::EMERGENCY ||
            $level === LogLevel::ERROR || $level === LogLevel::WARNING) {
            $channel = STDERR;
        }

        fwrite($channel, $this->getMessage($level, $message, $context));
    }
}

<?php
namespace Generics\Logger;

use Psr\Log\LogLevel;

/**
 * This class is a standard reference implementation of the PSR LoggerInterface.
 *
 * It logs everything to console. Depending on level it is written to stdout or stderr.
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class ConsoleLogger extends BasicLogger
{
    protected function logImpl($level, $message, array $context = array())
    {
        $channel = STDOUT;

        if($level === LogLevel::ALERT || $level === LogLevel::CRITICAL || $level === LogLevel::EMERGENCY ||
            $level === LogLevel::ERROR || $level === LogLevel::WARNING) {
            $channel = STDERR;
        }

        fwrite($channel, $this->getMessage($level, $message, $context)->read(4096));
    }
}

Read from MemoryStream as output for console


<?php
namespace SlaxWeb\View;

class View
{
    public $view = "";
    public $viewData = [];
    protected $_loader = null;
    protected $_twig = null;
    protected $_rendered = false;

    public function __construct(array $data = [])
    {
        $this->_loader = new \Twig_Loader_Filesystem(TEMPLATEPATH);
        $this->_twig = new \Twig_Environment($this->_loader, ["cache" => TWIGCACHE]);

        $this->view = $this->_getViewClass($this) . ".html";
        $this->viewData = $data;
    }

    public function __destruct()
    {
        if ($this->_rendered === false) {
            echo $this->_twig->render($this->view, $this->viewData);
        }
    }

    public function render()
    {
        $this->_rendered = true;
        return $this->_twig->render($this->view, $this->viewData);
    }

    protected function _getViewClass($obj)
    {
        $classname = get_class($obj);

        if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
            $classname = $matches[1];
        }

        return $classname;
    }
}

<?php
namespace SlaxWeb\View;

class View
{
    public $view = "";
    public $viewData = [];
    protected $_loader = null;
    protected $_twig = null;
    protected $_rendered = false;

    public function __construct(array $data = [], array $options = ["cache" => TWIGCACHE])
    {
        $this->_loader = new \Twig_Loader_Filesystem(TEMPLATEPATH);
        $this->_twig = new \Twig_Environment($this->_loader, $options);

        $this->view = $this->_getViewClass($this) . ".html";
        $this->viewData = $data;
    }

    public function __destruct()
    {
        if ($this->_rendered === false) {
            echo $this->_twig->render($this->view, $this->viewData);
        }
    }

    public function render()
    {
        $this->_rendered = true;
        return $this->_twig->render($this->view, $this->viewData);
    }

    protected function _getViewClass($obj)
    {
        $classname = get_class($obj);

        if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
            $classname = $matches[1];
        }

        return $classname;
    }
}

Make twig options an input param

Make twig options an input param


<?php

/**
 * @package plugins.captionSearch
 * @subpackage Scheduler.Debug
 */

// /opt/kaltura/app/batch
chdir(dirname( __FILE__ ) . "/../../../../../batch");

require_once(__DIR__ . "/../../../../../batch/bootstrap.php");

$iniFile = "batch_config.ini";		// should be the full file path

$kdebuger = new KGenericDebuger($iniFile);
$kdebuger->run('KAsyncParseCaptionAsset');

<?php

/**
 * @package plugins.captionSearch
 * @subpackage Scheduler.Debug
 */

// /opt/kaltura/app/batch
chdir(dirname( __FILE__ ) . "/../../../../../../batch");

require_once(__DIR__ . "/../../../../../../batch/bootstrap.php");

$iniFile = "batch_config.ini";		// should be the full file path

$kdebuger = new KGenericDebuger($iniFile);
$kdebuger->run('KAsyncParseCaptionAsset');

Fix requires: another require fix.

Fix requires: another require fix.


<?php

declare(strict_types=1);

namespace App\Assets;

use App\Environment;
use Intervention\Image\Constraint;
use Intervention\Image\Image;

final class BackgroundCustomAsset extends AbstractCustomAsset
{
    protected function getPattern(): string
    {
        return 'background%s.png';
    }

    protected function getDefaultUrl(): string
    {
        return Environment::getInstance()->getAssetUrl() . '/img/hexbg.png';
    }

    public function upload(Image $image): void
    {
        $newImage = clone $image;
        $newImage->resize(3264, 2160, function (Constraint $constraint) {
            $constraint->upsize();
        });
        $newImage->save($this->getPath());
    }
}

<?php

declare(strict_types=1);

namespace App\Assets;

use App\Environment;
use Intervention\Image\Constraint;
use Intervention\Image\Image;

final class BackgroundCustomAsset extends AbstractCustomAsset
{
    protected function getPattern(): string
    {
        return $this->getPatterns()['default'];
    }

    private function getPatterns(): array
    {
        return [
            'image/png' => 'background%s.png',
            'default' => 'background%s.jpg',
        ];
    }

    private function getPathForPattern(string $pattern): string
    {
        $pattern = sprintf($pattern, '');
        return Environment::getInstance()->getUploadsDirectory() . '/' . $pattern;
    }

    public function getPath(): string
    {
        $patterns = $this->getPatterns();
        foreach ($patterns as $pattern) {
            $path = $this->getPathForPattern($pattern);
            if (is_file($path)) {
                return $path;
            }
        }

        return $patterns['default'];
    }

    protected function getDefaultUrl(): string
    {
        return Environment::getInstance()->getAssetUrl() . '/img/hexbg.png';
    }

    public function delete(): void
    {
        foreach ($this->getPatterns() as $pattern) {
            @unlink($this->getPathForPattern($pattern));
        }
    }

    public function upload(Image $image): void
    {
        $newImage = clone $image;
        $newImage->resize(3264, 2160, function (Constraint $constraint) {
            $constraint->upsize();
        });

        $this->delete();

        $patterns = $this->getPatterns();

        $mimeType = $newImage->mime();
        $pattern = $patterns[$mimeType] ?? $patterns['default'];

        $newImage->save($this->getPathForPattern($pattern), 90);
    }

    public function getUrl(): string
    {
        foreach ($this->getPatterns() as $pattern) {
            $path = $this->getPathForPattern($pattern);

            if (is_file($path)) {
                $mtime = filemtime($path);

                return Environment::getInstance()->getAssetUrl() . self::UPLOADS_URL_PREFIX . '/' . sprintf(
                        $pattern,
                        '.' . $mtime
                    );
            }
        }

        return $this->getDefaultUrl();
    }
}

Support custom backgrounds in PNG or JPG format.


<?php

use Laracasts\Integrated\Extensions\Selenium as IntegrationTest;
# use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserRegistrationProcessTest extends IntegrationTest
{
    # use DatabaseTransactions;

    # protected $baseUrl = 'http://localhost:8000';

    /** @test */
    public function testRegistrationSuccess()
    {
        $this->visit('/lang/en_US.utf8')
             ->visit('/auth/register')
             ->type('John', '#name')
             ->type('test@timegrid.io', '#email')
             ->type('password', '#password')
             ->type('password', '#password_confirmation')
             ->press('Register')
             ->see('I run a business');
    }

    /** @test */
    public function testRegistrationPasswordMissmatch()
    {
        $this->visit('/lang/en_US.utf8')
             ->visit('/auth/register')
             ->type('John', '#name')
             ->type('test@timegrid.io', '#email')
             ->type('password', '#password')
             ->type('wrong', '#password_confirmation')
             ->press('Register')
             ->see('Please confirm your password correctly');
    }
}

<?php

use Laracasts\Integrated\Extensions\Selenium as IntegrationTest;

# use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserRegistrationProcessTest extends IntegrationTest
{
    # use DatabaseTransactions;

    # protected $baseUrl = 'http://localhost:8000';
    protected function setLanguageAndGoToRegister()
    {
        return $this->visit('/lang/en_US.utf8')
             ->visit('/auth/register');
    }

    /** @test */
    public function testRegistrationSuccess()
    {
        $this->setLanguageAndGoToRegister()
             ->type('John', '#name')
             ->type('test@timegrid.io', '#email')
             ->type('password', '#password')
             ->type('password', '#password_confirmation')
             ->press('Register')
             ->see('I run a business');
    }

    /** @test */
    public function testRegistrationPasswordMissmatch()
    {
        $this->setLanguageAndGoToRegister()
             ->type('John', '#name')
             ->type('test@timegrid.io', '#email')
             ->type('password', '#password')
             ->type('wrong', '#password_confirmation')
             ->press('Register')
             ->see('Please confirm your password correctly');
    }
}

Use PageObject pattern to reuse helper function


<?php
	if(!Utility::isBot()) {
		if(!$sidebar) {
			$sidebar = false;
		}

		if($article) {
			$advert = \FelixOnline\Core\Advert::randomPick('articles', $sidebar, $article->getCategory());
		} elseif($category) {
			$advert = \FelixOnline\Core\Advert::randomPick('categories', $sidebar, $category);
		} else {
			$advert = \FelixOnline\Core\Advert::randomPick('frontpage', $sidebar, null);
		}

		if($advert) {
			if(!$sidebar) {
				$class = 'external-img-top advert-area';
			} else {
				$class = 'external-img-side';
			}

			$advert->viewAdvert();

			?>

				<div class="<?php echo $class; ?>">
					<a href="<?php echo $advert->getUrl(); ?>" target="_blank"><img src="<?php echo $advert->getImage()->getUrl(); ?>">

			<?php
		}
	}
?>

<?php
	if(!Utility::isBot()) {
		if(!isset($sidebar)) {
			$sidebar = false;
		}

		if($article) {
			$advert = \FelixOnline\Core\Advert::randomPick('articles', $sidebar, $article->getCategory());
		} elseif($category) {
			$advert = \FelixOnline\Core\Advert::randomPick('categories', $sidebar, $category);
		} else {
			$advert = \FelixOnline\Core\Advert::randomPick('frontpage', $sidebar, null);
		}

		if($advert) {
			if(!$sidebar) {
				$class = 'external-img-top advert-area';
			} else {
				$class = 'external-img-side';
			}

			$advert->viewAdvert();

			?>

				<div class="<?php echo $class; ?>">
					<a href="<?php echo $advert->getUrl(); ?>" target="_blank"><img src="<?php echo $advert->getImage()->getUrl(); ?>">

			<?php
		}
	}
?>

Resolve an unassigned variable error.

Resolve an unassigned variable error.


<?php

namespace App\Handler\Email;

use App\Command\Email\AbstractSendEmailCommand;
use App\Command\Email\SendSignupReceivedEmailCommand;

class SendSignupReceivedEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email, AbstractSendEmailCommand $command): void
    {
        $email
            ->setSubject('Your account has been created')
            ->setBody('Thank you! Your account has been created and you will be contacted in 2 business days when it is active.')
        ;
    }
}

<?php

namespace App\Handler\Email;

use App\Command\Email\AbstractSendEmailCommand;

class SendSignupReceivedEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email, AbstractSendEmailCommand $command): void
    {
        $email
            ->setSubject('Your account has been created')
            ->setBody('Thank you! Your account has been created and you will be contacted in 2 business days when it is active.')
        ;
    }
}

Remove use line for SendSignupReceivedEmailCommand.


<?php

namespace Oro\Bundle\ApiBundle\Tests\Functional\Environment\Entity;

use Oro\Bundle\PricingBundle\Entity\ProductPrice;

class SkippedEntitiesProvider
{
    /**
     * @return array
     */
    public static function getForUpdateAction(): array
    {
        return [
            ProductPrice::class,
        ];
    }

    /**
     * @return array
     */
    public static function getForGetListAction(): array
    {
        return [
            ProductPrice::class,
        ];
    }
}

<?php

namespace Oro\Bundle\ApiBundle\Tests\Functional\Environment\Entity;

class SkippedEntitiesProvider
{
    /**
     * @return array
     */
    public static function getForUpdateAction(): array
    {
        return [
            'Oro\Bundle\PricingBundle\Entity\ProductPrice',
        ];
    }

    /**
     * @return array
     */
    public static function getForGetListAction(): array
    {
        return [
            'Oro\Bundle\PricingBundle\Entity\ProductPrice',
        ];
    }
}

BB-11805: Fix ProductPrice dependency on ApiBundle
 - changed class name to string


<?php

session_start();
if(!isset($_SESSION['user']) && !isset($_SESSION['userId'])) {
	die(header('Location: login.php'));
}

?>
<!DOCTYPE html>
<html>
<head>
	<title>
		Note Keeper
	</title>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">

	<link href='https://fonts.googleapis.com/css?family=Droid+Sans:700,400' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

	<?php include 'links.php'; ?>

	<div class="container-fluid">

<?php

session_start();
if(!isset($_SESSION['user']) && !isset($_SESSION['userId']) || !isset($_SESSION['authentication'])) {
	die(header('Location: login.php'));
}

?>
<!DOCTYPE html>
<html>
<head>
	<title>
		Note Keeper
	</title>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">

	<link href='https://fonts.googleapis.com/css?family=Droid+Sans:700,400' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

	<?php include 'links.php'; ?>

	<div class="container-fluid">

Check that the session authentication isset before loading the page


<!DOCTYPE html>
<html>
<?php
foreach (glob("$root/core/*.php") as $item) {
  require_once($item);
}
include_once "$root/includes/meta.php";
?>
  <body>
    <?php
    echo $content . "\n";
    include_once "$root/includes/footer.php";
    ?>
  </body>
</html>

<!DOCTYPE html>
<html>
<?php
foreach (glob("$root/core/*.php") as $item) {
  require_once($item);
}
include_once "$root/includes/meta.php";
?>
  <body>
    <?php
    echo $content . "\n"; // Add newline to make HTML code more readable
    include_once "$root/includes/footer.php";
    ?>
  </body>
</html>

Add comment to describe adding the '\n'

Add comment to describe adding the '\n'


<?php

namespace Clippings\ParsedownProvider\Test;

use Pimple\Container;
use Clippings\ParsedownProvider\ParsedownServiceProvider;

class ParsedownServiceProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testRegister()
    {
        $app = new Container();
        $app->register(new ParsedownServiceProvider());

        $this->assertArrayHasKey('parsedown.class', $app);
        $this->assertArrayHasKey('parsedown.breaks_enabled', $app);
        $this->assertArrayHasKey('parsedown.markup_escaped', $app);
        $this->assertArrayHasKey('parsedown.urls_linked', $app);
        $this->assertArrayHasKey('parsedown', $app);
        $this->assertArrayHasKey('parsedown.twig_filter', $app);

        $this->assertInstanceOf('Parsedown', $app['parsedown']);
        $this->assertSame($app['parsedown'], $app['parsedown']);

        $this->assertTrue($app['parsedown.breaks_enabled']);
        $this->assertFalse($app['parsedown.markup_escaped']);
        $this->assertTrue($app['parsedown.urls_linked']);

        $this->assertInstanceOf(
            'Twig_SimpleFilter',
            $app['parsedown.twig_filter']
        );
    }
}

<?php

namespace Clippings\ParsedownProvider\Test;

use Pimple\Container;
use Clippings\ParsedownProvider\ParsedownServiceProvider;

/**
 * @coversDefaultClass \Clippings\ParsedownProvider\ParsedownServiceProvider
 */
class ParsedownServiceProviderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers ::register
     */
    public function testRegister()
    {
        $app = new Container();
        $app->register(new ParsedownServiceProvider());

        $this->assertArrayHasKey('parsedown.class', $app);
        $this->assertArrayHasKey('parsedown.breaks_enabled', $app);
        $this->assertArrayHasKey('parsedown.markup_escaped', $app);
        $this->assertArrayHasKey('parsedown.urls_linked', $app);
        $this->assertArrayHasKey('parsedown', $app);
        $this->assertArrayHasKey('parsedown.twig_filter', $app);

        $this->assertInstanceOf('Parsedown', $app['parsedown']);
        $this->assertSame($app['parsedown'], $app['parsedown']);

        $this->assertTrue($app['parsedown.breaks_enabled']);
        $this->assertFalse($app['parsedown.markup_escaped']);
        $this->assertTrue($app['parsedown.urls_linked']);

        $this->assertInstanceOf(
            'Twig_SimpleFilter',
            $app['parsedown.twig_filter']
        );
    }
}

Add covers annotiations to tests

Add covers annotiations to tests


<?php

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

ini_set('error_reporting', E_ALL);

$generator = \KayakDocs\Generator\Generator::create(__DIR__ . '/tmp', __DIR__ . '/docs');
$generator->getPackageManager()->addRepository('https://packagist.drupal-composer.org');
$generator->getPackageManager()->addPackage('guzzlehttp/guzzle:6.2.0');
$generator->getPackageManager()->addPackage('drupal/paragraphs:8.1.0-rc4');
$results = $generator->process();

return;

<?php

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

ini_set('error_reporting', E_ALL);

$generator = \KayakDocs\Generator\Generator::create(__DIR__ . '/tmp', __DIR__ . '/docs');
$results = $generator->process();

return;

Remove lines deprecated by config file.

Remove lines deprecated by config file.


<?php if (is_numeric($cvalue)): ?>
	zend_declare_class_constant_long(php_phongo_<?=strtolower($class)?>_ce, ZEND_STRL("<?=$cname?>"), 0x<?=sprintf("%02s", dechex($cvalue))?> TSRMLS_CC);
<?php else: ?>
	zend_declare_class_constant_string(php_phongo_<?=strtolower($class)?>_ce, ZEND_STRL("<?=$cname?>"), "<?=$cvalue?>" TSRMLS_CC);
<?php endif ?>

<?php if (is_numeric($cvalue)): ?>
	zend_declare_class_constant_long(php_phongo_<?=strtolower($class)?>_ce, ZEND_STRL("<?=$cname?>"), 0x<?=sprintf("%02s", dechex($cvalue))?> TSRMLS_CC);
<?php elseif (defined($cname)): ?>
    zend_declare_class_constant_long(php_phongo_<?=strtolower($class)?>_ce, ZEND_STRL("<?=$cname?>"), <?=constant($cname)?> TSRMLS_CC);
<?php else: ?>
	zend_declare_class_constant_string(php_phongo_<?=strtolower($class)?>_ce, ZEND_STRL("<?=$cname?>"), "<?=$cvalue?>" TSRMLS_CC);
<?php endif ?>

Use a define() for const values if possible


<?php declare(strict_types=1);
namespace Phan\Language\Internal;

/**
 * A list of classes that support dynamic properties. These have
 * been manually entered.
 */
return [
    'stdclass',
    'simplexmlelement',
];

<?php declare(strict_types=1);
namespace Phan\Language\Internal;

/**
 * A list of classes that support dynamic properties. These have
 * been manually entered.
 */
return [
    'stdclass',
    'simplexmlelement',
    'solrobject',
    'v8js',
];

Add SolrObject and V8Js to list of classes with dynamic properties


<?php

namespace Dan\Core;

use Dan\Events\Event;
use Illuminate\Support\ServiceProvider;

class ExceptionServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        events()->subscribe('console.exception')
            ->priority(Event::VeryHigh)
            ->handler(function (\Throwable $exception) {

                $to = formatLocation(config('dan.network_console'));

                $file = relativePath($exception->getFile());

                $to['channel']->message("Exception was thrown. {$exception->getMessage()} - On line {$exception->getLine()} of {$file}");
            });
    }
}

<?php

namespace Dan\Core;

use Dan\Events\Event;
use Illuminate\Support\ServiceProvider;

class ExceptionServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        events()->subscribe('console.exception')
            ->priority(Event::VeryHigh)
            ->handler(function (\Throwable $exception) {

                $to = formatLocation(config('dan.network_console'));

                $file = relativePath($exception->getFile());

                if (empty($to)) {
                    return;
                }

                $to['channel']->message("Exception was thrown. {$exception->getMessage()} - On line {$exception->getLine()} of {$file}");
            });
    }
}

Fix crashing error caused when network_console isn't accessible.


<?php declare(strict_types=1);

namespace DaveRandom\LibDNS\Messages;

use DaveRandom\Enum\Enum;

final class MessageResponseCodes extends Enum
{
    const NO_ERROR = 0;
    const FORMAT_ERROR = 1;
    const SERVER_FAILURE = 2;
    const NAME_ERROR = 3;
    const NOT_IMPLEMENTED = 4;
    const REFUSED = 5;
}

<?php declare(strict_types=1);

namespace DaveRandom\LibDNS\Messages;

use DaveRandom\Enum\Enum;

final class MessageResponseCodes extends Enum
{
    const NO_ERROR = 0;
    const FORMAT_ERROR = 1;
    const SERVER_FAILURE = 2;
    const NAME_ERROR = 3;
    const NOT_IMPLEMENTED = 4;
    const REFUSED = 5;
    const UNEXPECTED_EXTANT_DOMAIN = 6;
    const UNEXPECTED_EXTANT_RRSET = 7;
    const NON_EXISTENT_RRSET = 8;
    const SERVER_NOT_AUTHORITATIVE = 9;
    const NOT_AUTHORIZED = 9;
    const BAD_OPT_VERSION = 16;
    const BAD_SIGNATURE = 16;
    const BAD_KEY = 17;
    const BAD_TIME = 18;
    const BAD_MODE = 19;
    const BAD_NAME = 20;
    const BAD_ALGORITHM = 21;
    const BAD_TRUNCATION = 22;
    const BAD_COOKIE = 23;
}

Add missing message response codes

Add missing message response codes


<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;

class LoginControllerTest extends TestCase
{
    /**
     *
     */
    public function testLogin()
    {
        $userVerifiedData = [
            'email' => 'test@mail.com',
            'password' => Hash::make('password'),
            'activated' => true
        ];

        $this->deleteUser($userVerifiedData);

        factory(User::class)->create($userVerifiedData);

        $response = $this->json('POST', '/api/v1/login',
            [
                'email' => $userVerifiedData['email'],
                'password' => 'password'
            ]
        );

        $response->assertStatus(200);
    }

    /**
     *
     */
    public function testLogout()
    {
        $userVerifiedData = [
            'email' => 'test@mail.com',
            'password' => Hash::make('password'),
            'activated' => true
        ];

        $this->deleteUser($userVerifiedData);

        $user = factory(User::class)->create($userVerifiedData);

        $response = $this->actingAs($user, 'api')->json('GET', '/api/v1/logout',[], $this->headers($user));

        $response->assertStatus(200);
    }

}

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;

class LoginControllerTest extends TestCase
{
    /**
     *
     */
    public function testLogin()
    {
        $userVerifiedData = [
            'email' => 'test@mail.com',
            'password' => Hash::make('password'),
            'activated' => true
        ];

        $this->deleteUser($userVerifiedData);

        factory(User::class)->create($userVerifiedData);

        $response = $this->json('POST', '/api/v1/login',
            [
                'email' => $userVerifiedData['email'],
                'password' => 'password'
            ]
        );

        $response->assertStatus(200);
    }

    /**
     *
     */
    public function testLoginError()
    {
        $userVerifiedData = [
            'email' => 'test@mail.com',
            'password' => Hash::make('password'),
            'activated' => true
        ];

        $this->deleteUser($userVerifiedData);

        factory(User::class)->create($userVerifiedData);

        $response = $this->json('POST', '/api/v1/login',
            [
                'email' => $userVerifiedData['email'],
                'password' => 'password-wrong'
            ]
        );

        $response->assertStatus(401);
    }
}

Add test login error case

Add test login error case


<?php

/**
 * Zim form.
 *
 * @package    openZIM
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ZimForm extends BaseZimForm
{
  public function configure()
  {
	$this->embedRelation('Anlagen');
	$this->widgetSchema['Anlagen'] =
		new sfWidgetFormDoctrineChoice(array(
			'model' => $this->getRelatedModelName('Anlagen'),
			'multiple' => true,
//			'label_associated' => 'Anlagen für dieses ZIM',
//			'label_unassociated' => 'Verfügbare Anlagen',
			'add_empty' => true,
        		'renderer_class' => 'sfWidgetFormSelectDoubleList'));

	$this->validatorSchema['Anlagen'] =
		new sfValidatorDoctrineChoice(array(
			'model' => $this->getRelatedModelName('Anlagen'),
			'required' => false
			));

  }
}

<?php

/**
 * Zim form.
 *
 * @package    openZIM
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ZimForm extends BaseZimForm
{
  public function configure()
  {
	$this->embedRelation('Anlagen');
	$this->widgetSchema['Anlagen'] =
		new sfWidgetFormDoctrineChoice(array(
			'model' => $this->getRelatedModelName('Anlagen'),
			'multiple' => true,
//			'label_associated' => 'Anlagen für dieses ZIM',
//			'label_unassociated' => 'Verfügbare Anlagen',
        		'renderer_class' => 'sfWidgetFormSelectDoubleList'));
	$this->widgetSchema['Anlagen']->setDefault($this->getObject()->getAnlagen());

	$this->validatorSchema['Anlagen'] =
		new sfValidatorDoctrineChoice(array(
			'model' => $this->getRelatedModelName('Anlagen'),
			'multiple' => true,
			'required' => false
			));

  }
}

Fix mutliple anlage select in create

ZimForm: Fix mutliple anlage select in create

Now its possible to add multiple anlagen to a zim
when create/edit.
It still gives an error when a anlage which was
part of a zim is not selected (remove anlage from zim)


<?php

namespace Eris;

class SampleTest extends \PHPUnit_Framework_TestCase
{
    use TestTrait;

    public function testWithGeneratorSize()
    {
        $times         = 100;
        $generatorSize = 100;
        $generator     = Generator\suchThat(function ($n) {
            return $n > 10;
        }, Generator\nat());
        $sample        = $this->sample($generator, $times, $generatorSize);
        $this->assertNotEmpty(count($sample->collected()));
    }
}

Add missing newline at end of file

Add missing newline at end of file


<?php

require_once __DIR__ . '/../silex.phar';
require_once __DIR__ . '/../vendor/.composer/autoload.php';

<?php

require_once __DIR__ . '/../silex.phar';
require_once __DIR__ . '/../vendor/autoload.php';

Extend twig instead of instancing it

Extend twig instead of instancing it


<?php

class UserTableSeeder extends Seeder
{

	public function run()
	{
		DB::table('users')->delete();
		User::create(array(
			'email'    => 'chawkinsuf@gmail.com',
			'password' => '123456',
			'nest_password' => '51gBJAh*yOEN*SK'
		));
	}

}

<?php

class UserTableSeeder extends Seeder
{

	public function run()
	{
		DB::table('users')->delete();
		App\Models\User::create(array(
			'email'    => 'chawkinsuf@gmail.com',
			'password' => '123456',
			'nest_password' => '51gBJAh*yOEN*SK'
		));
	}

}

Update User with its namespace

Update User with its namespace


<?php

namespace Aztech\Sniffs\Formatting;

use Aztech\Sniffs\TokenIterator;

/**
 * Sniff to detect that there are no consecutive blank lines in code.
 *
 * @author thibaud
 */
class NoConsecutiveBlankLinesSniff implements \PHP_CodeSniffer_Sniff
{

    public function register()
    {
        return array(T_FUNCTION);
    }

    public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $function = $tokens[$stackPtr];

        $bodyStartPtr = $function['scope_opener'];
        $bodyEndPtr = $function['scope_closer'];

        $it = new TokenIterator($tokens, $bodyStartPtr - 1, $bodyEndPtr + 1);
        $buffer = '';

        foreach ($it as $ptr => $token) {
            $buffer .= str_replace(' ', '', $token['content']);

            if (strpos($buffer, PHP_EOL . PHP_EOL . PHP_EOL) !== false) {
                $error = 'There should be no consecutive blank lines';
                $phpcsFile->addError($error, $ptr, 'ConsecutiveBlankLines');

                $buffer = str_replace(PHP_EOL . PHP_EOL . PHP_EOL, PHP_EOL, $buffer);
            }
        }
    }
}

<?php

namespace Aztech\Sniffs\Formatting;

use Aztech\Sniffs\TokenIterator;

/**
 * Sniff to detect that there are no consecutive blank lines in code.
 *
 * @author thibaud
 */
class NoConsecutiveBlankLinesSniff implements \PHP_CodeSniffer_Sniff
{

    public function register()
    {
        return array(T_FUNCTION);
    }

    public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $function = $tokens[$stackPtr];

        $bodyStartPtr = $function['scope_opener'];
        $bodyEndPtr = $function['scope_closer'];

        $it = new TokenIterator($tokens, $bodyStartPtr - 1, $bodyEndPtr + 1);
        $buffer = '';

        foreach ($it as $ptr => $token) {
            $buffer .= str_replace(' ', '', $token['content']);

            if (strpos($buffer, PHP_EOL . PHP_EOL . PHP_EOL) !== false) {
                $error = 'There must be no consecutive blank lines';
                $phpcsFile->addError($error, $ptr, 'ConsecutiveBlankLines');

                while (strpos($buffer, PHP_EOL . PHP_EOL . PHP_EOL) !== false) {
                    $buffer = str_replace(PHP_EOL . PHP_EOL . PHP_EOL, PHP_EOL . PHP_EOL, $buffer);
                }
            }
        }
    }
}

Improve new line replace algo

Improve new line replace algo


<?php

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

namespace Symfony\Component\Security\Acl\Model;

/**
 * Provides support for creating and storing ACL instances.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
interface MutableAclProviderInterface extends AclProviderInterface
{
    /**
     * Creates a new ACL for the given object identity.
     *
     * @param ObjectIdentityInterface $oid
     *
     * @throws AclAlreadyExistsException when there already is an ACL for the given
     *                                   object identity
     *
     * @return MutableAclInterface
     */
    public function createAcl(ObjectIdentityInterface $oid);

    /**
     * Deletes the ACL for a given object identity.
     *
     * This will automatically trigger a delete for any child ACLs. If you don't
     * want child ACLs to be deleted, you will have to set their parent ACL to null.
     *
     * @param ObjectIdentityInterface $oid
     */
    public function deleteAcl(ObjectIdentityInterface $oid);

    /**
     * Persists any changes which were made to the ACL, or any associated
     * access control entries.
     *
     * Changes to parent ACLs are not persisted.
     *
     * @param MutableAclInterface $acl
     */
    public function updateAcl(MutableAclInterface $acl);
}

<?php

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

namespace Symfony\Component\Security\Acl\Model;

use Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException;

/**
 * Provides support for creating and storing ACL instances.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
interface MutableAclProviderInterface extends AclProviderInterface
{
    /**
     * Creates a new ACL for the given object identity.
     *
     * @param ObjectIdentityInterface $oid
     *
     * @throws AclAlreadyExistsException when there already is an ACL for the given
     *                                   object identity
     *
     * @return MutableAclInterface
     */
    public function createAcl(ObjectIdentityInterface $oid);

    /**
     * Deletes the ACL for a given object identity.
     *
     * This will automatically trigger a delete for any child ACLs. If you don't
     * want child ACLs to be deleted, you will have to set their parent ACL to null.
     *
     * @param ObjectIdentityInterface $oid
     */
    public function deleteAcl(ObjectIdentityInterface $oid);

    /**
     * Persists any changes which were made to the ACL, or any associated
     * access control entries.
     *
     * Changes to parent ACLs are not persisted.
     *
     * @param MutableAclInterface $acl
     */
    public function updateAcl(MutableAclInterface $acl);
}

Fix phpdoc and coding standards

Fix phpdoc and coding standards

This removes the unused use statements which were not catched by
PHP-CS-Fixer because of string occurences. It also fixes some invalid
phpdoc (scalar is not recognized as a valid type for instance).


<?php

namespace Lc5\Toolbox;

/**
 * Class Timer
 *
 * @author Łukasz Krzyszczak <lukasz.krzyszczak@gmail.com>
 */
class Timer
{

    /**
     * @var float
     */
    private $startTime;

    /**
     * @var float
     */
    private $stopTime;

    /**
     * @var boolean
     */
    private $isStarted;

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

    public function reset()
	{
		$this->startTime = 0.0;
		$this->stopTime  = 0.0;
		$this->isStarted = false;
	}

    public function start()
	{
		if (!$this->isStarted) {
			$this->reset();
			$this->startTime = microtime(true);
			$this->isStarted = true;
		}
	}

    public function stop()
	{
		if ($this->isStarted) {
			$this->stopTime  = microtime(true);
			$this->isStarted = false;
		}
	}

    /**
     * @return float
     */
    public function getTime()
	{
		$stopTime = $this->isStarted ? microtime(true) : $this->stopTime;

		return $stopTime - $this->startTime;
	}
}

Convert some old left-over tabs to spaces


<?php
namespace Omise\Payment\Block\Checkout\Onepage\Success;

class PaynowAdditionalInformation extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        array $data = []
    ) {
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
    }

    /**
     * Adding PayNow Payment Information
     *
     * @return string
     */
    protected function _toHtml()
    {
        $paymentData = $this->_checkoutSession->getLastRealOrder()->getPayment()->getData();
        if (!isset($paymentData['additional_information']['payment_type']) || $paymentData['additional_information']['payment_type'] !== 'paynow') {
            return;
        }
        $orderCurrency = $this->_checkoutSession->getLastRealOrder()->getOrderCurrency()->getCurrencyCode();

        $this->addData([
            'paynow_qrcode' => $paymentData['additional_information']['qr_code_encoded'],
            'order_amount' => number_format($paymentData['amount_ordered'], 2) .' '.$orderCurrency
        ]);

        return parent::_toHtml();
    }
}

<?php
namespace Omise\Payment\Block\Checkout\Onepage\Success;

class PaynowAdditionalInformation extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        array $data = []
    ) {
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
    }

    /**
     * Adding PayNow Payment Information
     *
     * @return string
     */
    protected function _toHtml()
    {
        $paymentData = $this->_checkoutSession->getLastRealOrder()->getPayment()->getData();
        if (isset($paymentData['additional_information']['payment_type']) || $paymentData['additional_information']['payment_type'] === 'paynow') {
            $orderCurrency = $this->_checkoutSession->getLastRealOrder()->getOrderCurrency()->getCurrencyCode();
            $this->addData([
                'paynow_qrcode' => $paymentData['additional_information']['qr_code_encoded'],
                'order_amount' => number_format($paymentData['amount_ordered'], 2) .' '.$orderCurrency
            ]);
        }

        return parent::_toHtml();
    }
}

Change accoring to PR comments. moving code inside if block


<?php

namespace League\Flysystem;

/**
 * @internal
 */
trait ConfigAwareTrait
{
    /**
     * @var Config
     */
    protected $config;

    /**
     * Set the config.
     *
     * @param Config|array $config
     */
    protected function setConfig($config)
    {
        $this->config = $config ? Util::ensureConfig($config) : null;
    }

    /**
     * Get the Config.
     *
     * @return Config config object
     */
    public function getConfig()
    {
        if ($this->config === null) {
            return $this->config = new Config;
        }

        return $this->config;
    }

    /**
     * Convert a config array to a Config object with the correct fallback.
     *
     * @param array $config
     *
     * @return Config
     */
    protected function prepareConfig(array $config)
    {
        $config = new Config($config);
        $config->setFallback($this->getConfig());

        return $config;
    }
}

<?php

namespace League\Flysystem;

/**
 * @internal
 */
trait ConfigAwareTrait
{
    /**
     * @var Config
     */
    protected $config;

    /**
     * Set the config.
     *
     * @param Config|array|null $config
     */
    protected function setConfig($config)
    {
        $this->config = $config ? Util::ensureConfig($config) : null;
    }

    /**
     * Get the Config.
     *
     * @return Config config object
     */
    public function getConfig()
    {
        if ($this->config === null) {
            return $this->config = new Config;
        }

        return $this->config;
    }

    /**
     * Convert a config array to a Config object with the correct fallback.
     *
     * @param array $config
     *
     * @return Config
     */
    protected function prepareConfig(array $config)
    {
        $config = new Config($config);
        $config->setFallback($this->getConfig());

        return $config;
    }
}

Allow null configs in docblock

Allow null configs in docblock


<?php

/*
 * This file is part of the CSBill package.
 *
 * (c) Pierre du Plessis <info@customscripts.co.za>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CSBill\QuoteBundle\Model;

use CSBill\CoreBundle\Model\Status as AbstractStatus;

class Status extends AbstractStatus
{
    /**
     * Contains a list of all the statuses and their corresponding labels
     *
     * @var array
     */
    protected $statusLabels = array(
                                    'draft'     => 'draft',
                                    'pending'   => 'warning',
                                    'accepted'  => 'success',
                                    'declined'  => 'danger',
                                    'cancelled' => 'inverse'
            );
}

<?php

/*
 * This file is part of the CSBill package.
 *
 * (c) Pierre du Plessis <info@customscripts.co.za>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CSBill\QuoteBundle\Model;

use CSBill\CoreBundle\Model\Status as AbstractStatus;

class Status extends AbstractStatus
{
    /**
     * Contains a list of all the statuses and their corresponding labels
     *
     * @var array
     */
    protected $statusLabels = array(
                                    'draft'     => 'draft',
                                    'pending'   => 'warning',
                                    'accepted'  => 'success',
                                    'declined'  => 'important',
                                    'cancelled' => 'inverse'
            );
}

[QuoteBundle] Fix incorrect class for declined status label


<?php
namespace FluxCtrl\App\Controller\Feed;

use Cake\Event\Event;
use FluxCtrl\App\Controller\CrudController;

class ItemsController extends CrudController
{
    /**
     * Use the same views as `FluxCtrl\Controller\ItemsController`.
     *
     * @var string
     */
    public $viewPath = 'Items';

    /**
     * {@inheritdoc}
     */
    public function beforeFilter(Event $event)
    {
        if ($this->request->data) {
            $this->request->data['feed_id'] = $this->request->param('id');
        }
    }

    public function index()
    {
        $this->Crud->on('beforePaginate', function (Event $event) {
            $event->subject()->object = $this->Items->find('unread')
                ->contain('Feeds')
                ->where([$this->Items->alias() . '.feed_id' => $this->request->param('id')]);
        });
        $this->Crud->execute();
    }
}

<?php
namespace FluxCtrl\App\Controller\Feed;

use Cake\Event\Event;
use FluxCtrl\App\Controller\CrudController;

class ItemsController extends CrudController
{
    /**
     * Use the same views as `FluxCtrl\Controller\ItemsController`.
     *
     * @var string
     */
    public $viewPath = 'Items';

    /**
     * {@inheritdoc}
     */
    public function beforeFilter(Event $event)
    {
        if ($this->request->data) {
            $this->request->data['feed_id'] = $this->request->param('id');
        }
    }

    public function index()
    {
        $this->Crud->on('beforePaginate', function (Event $event) {
            $event->subject()->object = $this->Items->find('unread')
                ->contain('Feeds')
                ->where([$this->Items->alias() . '.feed_id' => $this->request->param('id')]);
        });
        $this->Crud->execute();
    }

    public function view()
    {
        $this->Crud->on('afterFind', function (Event $event) {
            $event->subject()->entity->markAsRead();
        });
        $this->Crud->execute();
    }
}

Mark items viewed within a feed as read

Mark items viewed within a feed as read


<select
    <?php echo $view['form']->block($form, 'widget_attributes') ?>
    <?php if ($multiple): ?> multiple="multiple"<?php endif ?>
>
    <?php if (null !== $empty_value): ?><option <?php if ($required):?> disabled="disabled"<?php if (empty($value) && "0" !== $value): ?> selected="selected"<?php endif ?><?php else: ?> value=""<?php endif?>><?php echo $view->escape($view['translator']->trans($empty_value, array(), $translation_domain)) ?></option><?php endif; ?>
    <?php if (count($preferred_choices) > 0): ?>
        <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $preferred_choices)) ?>
        <?php if (count($choices) > 0 && null !== $separator): ?>
            <option disabled="disabled"><?php echo $separator ?></option>
        <?php endif ?>
    <?php endif ?>
    <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $choices)) ?>
</select>

<select
    <?php echo $view['form']->block($form, 'widget_attributes') ?>
    <?php if ($multiple): ?> multiple="multiple"<?php endif ?>
>
    <?php if (null !== $empty_value): ?><option value=""<?php if ($required):?> disabled="disabled"<?php if (empty($value) && "0" !== $value): ?> selected="selected"<?php endif ?><?php endif?>><?php echo $view->escape($view['translator']->trans($empty_value, array(), $translation_domain)) ?></option><?php endif; ?>
    <?php if (count($preferred_choices) > 0): ?>
        <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $preferred_choices)) ?>
        <?php if (count($choices) > 0 && null !== $separator): ?>
            <option disabled="disabled"><?php echo $separator ?></option>
        <?php endif ?>
    <?php endif ?>
    <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $choices)) ?>
</select>

Revert "[Form] Remove "value" attribute on empty_value option"

This reverts commit 9e849eb78bcc668a2b8aad39cb47e2ad32c73a47.

Reasons for the revert:

* https://github.com/symfony/symfony/issues/8478
* https://github.com/symfony/symfony/issues/8526


<?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\Cache\Simple;

use Symfony\Component\Cache\Traits\ApcuTrait;

@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" and type-hint for "%s" instead.', ApcuCache::class, ApcuAdapter::class, CacheInterface::class), E_USER_DEPRECATED);

/**
 * @deprecated since Symfony 4.3, use ApcuAdapter and type-hint for CacheInterface instead.
 */
class ApcuCache extends AbstractCache
{
    use ApcuTrait;

    public function __construct(string $namespace = '', int $defaultLifetime = 0, string $version = null)
    {
        $this->init($namespace, $defaultLifetime, $version);
    }
}

<?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\Cache\Simple;

use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Traits\ApcuTrait;
use Symfony\Contracts\Cache\CacheInterface;

@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" and type-hint for "%s" instead.', ApcuCache::class, ApcuAdapter::class, CacheInterface::class), E_USER_DEPRECATED);

/**
 * @deprecated since Symfony 4.3, use ApcuAdapter and type-hint for CacheInterface instead.
 */
class ApcuCache extends AbstractCache
{
    use ApcuTrait;

    public function __construct(string $namespace = '', int $defaultLifetime = 0, string $version = null)
    {
        $this->init($namespace, $defaultLifetime, $version);
    }
}

[Cache] Fix wrong classname in deprecation message


<?php

namespace Oro\Bundle\FormBundle\Form\Handler;

use Doctrine\Common\Persistence\ObjectManager;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;

use OroCRM\Bundle\TaskBundle\Entity\Task;

class ApiFormHandler
{
    /**
     * @var FormInterface
     */
    protected $form;

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var ObjectManager
     */
    protected $manager;

    /**
     * @param Request       $request
     * @param ObjectManager $manager
     */
    public function __construct(Request $request, ObjectManager $manager)
    {
        $this->request = $request;
        $this->manager = $manager;
    }

    /**
     * @param FormInterface $form
     */
    public function setForm(FormInterface $form)
    {
        $this->form = $form;
    }

    /**
     * Process form
     *
     * @param  object $entity
     *
     * @return bool True on successful processing, false otherwise
     */
    public function process($entity)
    {
        $this->form->setData($entity);

        if (in_array($this->request->getMethod(), ['POST', 'PUT'])) {
            $this->form->submit($this->request);

            if ($this->form->isValid()) {
                $this->onSuccess($entity);

                return true;
            }
        }

        return false;
    }

    /**
     * "Success" form handler
     *
     * @param object $entity
     */
    protected function onSuccess($entity)
    {
        $this->manager->persist($entity);
        $this->manager->flush();
    }
}

<?php

namespace Oro\Bundle\FormBundle\Form\Handler;

use Doctrine\Common\Persistence\ObjectManager;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;

class ApiFormHandler
{
    /**
     * @var FormInterface
     */
    protected $form;

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var ObjectManager
     */
    protected $manager;

    /**
     * @param Request       $request
     * @param ObjectManager $manager
     */
    public function __construct(Request $request, ObjectManager $manager)
    {
        $this->request = $request;
        $this->manager = $manager;
    }

    /**
     * @param FormInterface $form
     */
    public function setForm(FormInterface $form)
    {
        $this->form = $form;
    }

    /**
     * Process form
     *
     * @param  object $entity
     *
     * @return bool True on successful processing, false otherwise
     */
    public function process($entity)
    {
        $this->form->setData($entity);

        if (in_array($this->request->getMethod(), ['POST', 'PUT'])) {
            $this->form->submit($this->request);

            if ($this->form->isValid()) {
                $this->onSuccess($entity);

                return true;
            }
        }

        return false;
    }

    /**
     * "Success" form handler
     *
     * @param object $entity
     */
    protected function onSuccess($entity)
    {
        $this->manager->persist($entity);
        $this->manager->flush();
    }
}

CRM-2136: Convert Marketing List connection from workflow to controllers


<?php

namespace Stripe;

class ApplicationFee extends ApiResource
{
    /**
     * This is a special case because the application fee endpoint has an
     *    underscore in it. The parent `className` function strips underscores.
     *
     * @return string The name of the class.
     */
    public static function className()
    {
        return 'application_fee';
    }

    /**
     * @param string $id The ID of the application fee to retrieve.
     * @param array|string|null $opts
     *
     * @return ApplicationFee
     */
    public static function retrieve($id, $opts = null)
    {
        return self::_retrieve($id, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return Collection of ApplicationFees
     */
    public static function all($params = null, $opts = null)
    {
        return self::_all($params, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return ApplicationFee The refunded application fee.
     */
    public function refund($params = null, $opts = null)
    {
        $url = $this->instanceUrl() . '/refunds';
        list($response, $opts) = static::_staticRequest('post', $url, $params, $opts);
        $obj = Util\Util::convertToStripeObject($response->json, $opts);
        $obj->setLastResponse($response);
        return $obj;
    }
}

<?php

namespace Stripe;

class ApplicationFee extends ApiResource
{
    /**
     * This is a special case because the application fee endpoint has an
     *    underscore in it. The parent `className` function strips underscores.
     *
     * @return string The name of the class.
     */
    public static function className()
    {
        return 'application_fee';
    }

    /**
     * @param string $id The ID of the application fee to retrieve.
     * @param array|string|null $opts
     *
     * @return ApplicationFee
     */
    public static function retrieve($id, $opts = null)
    {
        return self::_retrieve($id, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return Collection of ApplicationFees
     */
    public static function all($params = null, $opts = null)
    {
        return self::_all($params, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return ApplicationFee The refunded application fee.
     */
    public function refund($params = null, $opts = null)
    {
        $this->refunds->create();
        $this->refresh();
        return $this;
    }
}

Create backward-compatible helper that uses new endpoint


<?php

namespace Bitcoin\Signature\K;

use Bitcoin\Util\Buffer;
use Bitcoin\Crypto\Hash;
use Bitcoin\Crypto\DRBG\HMACDRBG;
use Bitcoin\Crypto\DRBG\RFC6979;
use Bitcoin\Key\PrivateKeyInterface;
use Mdanter\Ecc\GeneratorPoint;

/**
 * Class DeterministicK
 * @package Bitcoin\Signature\K
 * @author Thomas Kerin
 */
class DeterministicK implements KInterface
{

    /**
     * @var HMACDRBG
     */
    protected $drbg;

    /**
     * @param PrivateKeyInterface $privateKey
     * @param Buffer $messageHash
     * @param string $algo
     * @param GeneratorPoint $generator
     */
    public function __construct(PrivateKeyInterface $privateKey, Buffer $messageHash, $algo = 'sha256')
    {
        $entropy         = new Buffer($privateKey->serialize() . $messageHash->serialize());
        $this->drbg      = new HMACDRBG($algo, $entropy);
    }

    /**
     * Return a K value deterministically derived from the private key
     *  and data
     */
    public function getK()
    {
        $deterministicK = $this->drbg->bytes(32);
        return $deterministicK;
    }
}

<?php

namespace Bitcoin\Signature\K;

use Bitcoin\Util\Buffer;
use Bitcoin\Crypto\DRBG\HMACDRBG;
use Bitcoin\Key\PrivateKeyInterface;
use Mdanter\Ecc\GeneratorPoint;

/**
 * Class DeterministicK
 * @package Bitcoin\Signature\K
 * @author Thomas Kerin
 * Todo: refactor so this class accepts an initialized DRBGInterface
 */
class DeterministicK implements KInterface
{

    /**
     * @var HMACDRBG
     */
    protected $drbg;

    /**
     * @var Buffer
     */
    protected $k;

    /**
     * @param PrivateKeyInterface $privateKey
     * @param Buffer $messageHash
     * @param string $algo
     * @param GeneratorPoint $generator
     */
    public function __construct(PrivateKeyInterface $privateKey, Buffer $messageHash, $algo = 'sha256')
    {
        $entropy         = new Buffer($privateKey->serialize() . $messageHash->serialize());
        $this->drbg      = new HMACDRBG($algo, $entropy);
    }

    /**
     * Return a K value deterministically derived from the private key
     *  and data
     */
    public function getK()
    {
        if (is_null($this->k)) {
            $this->k = $this->drbg->bytes(32);
        }

        return $this->k;
    }
}

Store K so it can be returned again later


<?php namespace Picqer\Financials\Exact\Query;

class Resultset
{
    protected $connection;

    protected $url;

    protected $class;

    protected $params;

    public function __construct($connection, $url, $class, $params)
    {
        $this->connection = $connection;
        $this->url = $url;
        $this->class = $class;
        $this->params = $params;
    }

    public function next()
    {
        $result = $this->connection->get($this->url, $this->params);
        $this->url = $this->connection->nextUrl;
        $this->params = null;
        return $this->collectionFromResult($result, $this->class);
    }

    public function hasMore()
    {
        return $this->url !== null;
    }

    protected function collectionFromResult($result)
    {
        // If we have one result which is not an assoc array, make it the first element of an array for the
        // collectionFromResult function so we always return a collection from filter
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
            $result = [ $result ];
        }

        $class = $this->class;
        $collection = [];

        foreach ($result as $r) {
            $collection[] = new $class($this->connection, $r);
        }

        return $collection;
    }
}

<?php namespace Picqer\Financials\Exact\Query;

class Resultset
{
    protected $connection;

    protected $url;

    protected $class;

    protected $params;

    public function __construct($connection, $url, $class, $params)
    {
        $this->connection = $connection;
        $this->url = $url;
        $this->class = $class;
        $this->params = $params;
    }

    public function next()
    {
        $result = $this->connection->get($this->url, $this->params);
        $this->url = $this->connection->nextUrl;
        $this->params = null;
        return $this->collectionFromResult($result);
    }

    public function hasMore()
    {
        return $this->url !== null;
    }

    protected function collectionFromResult($result)
    {
        // If we have one result which is not an assoc array, make it the first element of an array for the
        // collectionFromResult function so we always return a collection from filter
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
            $result = [ $result ];
        }

        $class = $this->class;
        $collection = [];

        foreach ($result as $r) {
            $collection[] = new $class($this->connection, $r);
        }

        return $collection;
    }
}

Correct function call to no longer pass one parameter to many


<?php
// use this to display a message across the whole site; should be used sparingly.
?>

LATEST NEWS:

We're running a C++ game development project to mimic the development of a AAA game project!

Read all about it!

<?php
// use this to display a message across the whole site; should be used sparingly.
?>

LATEST NEWS:

The multi science bar crawl is coming up soon; it's always one of the best nights out of the year and is definitely not to be missed.

Keep your eyes on our Facebook group for details! You'll be able to order your t-shirts on this site when they're available.

Change C++ message to bar crawl message

Change C++ message to bar crawl message