<?php

namespace Common;

use InvalidArgumentException;
use Serializable;

abstract class Locale implements Serializable
{
    /**
     * @var string
     */
    protected $locale;

    /**
     * @param string $locale
     */
    protected function __construct($locale)
    {
        $this->setLocale($locale);
    }

    /**
     * @param $locale
     *
     * @return self
     */
    public static function fromString($locale)
    {
        return new static($locale);
    }

    /**
     * @return array
     */
    abstract protected function getPossibleLanguages();

    /**
     * @param string $locale
     *
     * @throws InvalidArgumentException
     *
     * @return self
     */
    protected function setLocale($locale)
    {
        if (!array_key_exists($locale, $this->getPossibleLanguages())) {
            throw new InvalidArgumentException('Invalid language');
        }

        $this->locale = $locale;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        return $this->locale;
    }

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

    /**
     * @return string
     */
    public function serialize()
    {

        return $this->locale;
    }

    /**
     * @param string $locale
     *
     * @return Locale
     */
    public function unserialize($locale)
    {
        $this->locale = $locale;
    }
}

<?php

namespace Common;

use InvalidArgumentException;
use Serializable;

abstract class Locale implements Serializable
{
    /**
     * @var string
     */
    protected $locale;

    /**
     * @param string $locale
     */
    protected function __construct($locale)
    {
        $this->setLocale($locale);
    }

    /**
     * @param $locale
     *
     * @return self
     */
    public static function fromString($locale)
    {
        return new static($locale);
    }

    /**
     * @return array
     */
    abstract protected function getPossibleLanguages();

    /**
     * @param string $locale
     *
     * @throws InvalidArgumentException
     *
     * @return self
     */
    protected function setLocale($locale)
    {
        if (!array_key_exists($locale, $this->getPossibleLanguages())) {
            throw new InvalidArgumentException('Invalid language');
        }

        $this->locale = $locale;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        return $this->locale;
    }

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

    /**
     * @return string
     */
    public function serialize()
    {

        return $this->locale;
    }

    /**
     * @param string $locale
     *
     * @return Locale
     */
    public function unserialize($locale)
    {
        $this->locale = $locale;
    }

    public function equals(Locale $locale)
    {
        return $this->locale === $locale->locale;
    }
}

Make it more easy to compare locale

Make it more easy to compare locale


<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";

// Sanity checks
$LTI = requireData(array('user_id', 'link_id', 'role','context_id'));
$instructor = isInstructor($LTI);
$user_id = $LTI['user_id'];

$grade = 1.0;

$code = $_POST['code'];
$json = json_encode(array("code" => $code));

$retval = updateGradeJSON($pdo, $json);

$retval = Array("status" => "success");
echo json_encode($retval);

<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";

// Sanity checks
$LTI = requireData(array('user_id', 'link_id', 'role','context_id'));
$instructor = isInstructor($LTI);
$user_id = $LTI['user_id'];

$grade = 1.0;

if ( ! isset($_POST['code']) ) {
    echo(json_encode(array("error" => "Missing code")));
    return;
}
$code = $_POST['code'];
$json = json_encode(array("code" => $code));

$retval = updateGradeJSON($pdo, $json);

$retval = Array("status" => "success");
echo json_encode($retval);

Check for missing code variable.

Check for missing code variable.


@extends('layout')

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

@section('body')

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

            @if (count($spendings))
                @foreach ($spendings as $spending)

{{ $spending->description }}

{{ $spending->formatted_happened_on }}

                            @if ($spending->tag)
                                @include('partials.tag', ['payload' => $spending->tag])
                            @endif

€ {{ $spending->formatted_amount }}

                @endforeach
            @else

You don't have any spendings

            @endif

@endsection

@extends('layout')

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

@section('body')

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

            @if (count($spendings))
                @foreach ($spendings as $spending)

{{ $spending->description }}

{{ $spending->formatted_happened_on }}

                            @if ($spending->tag)
                                @include('partials.tag', ['payload' => $spending->tag])
                            @endif

€ {{ $spending->formatted_amount }}

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

                                </button>
                            </form>

                @endforeach
            @else

You don't have any spendings

            @endif

@endsection

Add ability to delete spending on spendings' index view


<?php

foreach (CM_Db_Db::exec("SHOW TABLES LIKE  'wurfl%'")->fetchAllColumn() as $tableName) {
	CM_Db_Db::exec('DROP IF EXISTS ' . $tableName);
}
CM_Db_Db::exec('DROP PROCEDURE IF EXISTS `wurfl_FallBackDevices`');
CM_Db_Db::exec('DROP PROCEDURE IF EXISTS `wurfl_RIS`');

<?php

foreach (CM_Db_Db::exec("SHOW TABLES LIKE  'wurfl%'")->fetchAllColumn() as $tableName) {
	CM_Db_Db::exec('DROP TABLE IF EXISTS ' . $tableName);
}
CM_Db_Db::exec('DROP PROCEDURE IF EXISTS `wurfl_FallBackDevices`');
CM_Db_Db::exec('DROP PROCEDURE IF EXISTS `wurfl_RIS`');

Add update script - drop table not something


Coming to us from CHA Companies is Jason Rowley, a consultant working for INDOT's New US 31 road project in Hamilton County. Joining Jason is Michelle Kearns from Empower Results.

The New US 31 Hamilton County team will provide IREX members with an overview of the project that will upgrade US 31 to freeway standards from I-465 at the Marion-Hamilton county line, through Carmel and Westfield to SR 38. In terms of dollars, this will be the largest and most aggressive road project ever completed in Hamilton County.

The presentation will include a review of completed and upcoming construction, as well as the opportunity for IREX members to ask specific questions about the project.

Add some more information about the speakers for the 24th.


<?php

use TZK\Taiga\Requests\CurlRequest;
use TZK\Taiga\Service;
use TZK\Taiga\Services\Users;
use TZK\Taiga\Taiga;

describe('ServiceSpec', function () {
    given('url', function () {
        return 'localhost';
    });

    given('request', function () {
        return new CurlRequest();
    });

    given('client', function () {
        return new Taiga($this->request, $this->url);
    });

    given('service', function () {
        return $service = new Users($this->client);
    });

    it('uses the right parameters to send the request', function () {
        allow($this->client)
            ->toReceive('request')
            ->andReturn([]);

        $verb = 'GET';
        $endpoint = 'me';
        $params = [
            'param1' => 'value1',
            'param2' => 'value2',
        ];
        $data = [];

        expect($this->client)
            ->toReceive('request')
            ->with('GET', 'users/'.$endpoint.'?'.http_build_query($params), $data)
            ->once();

        $this->service->get($endpoint, $params, $data);
    });
});

<?php

use TZK\Taiga\Exceptions\RequestException;
use TZK\Taiga\Requests\NullRequest;
use TZK\Taiga\Service;
use TZK\Taiga\Services\Users;
use TZK\Taiga\Taiga;

describe('ServiceSpec', function () {
    given('url', function () {
        return 'localhost';
    });

    given('request', function () {
        return new NullRequest();
    });

    given('client', function () {
        return new Taiga($this->request, $this->url);
    });

    given('service', function () {
        return $service = new Users($this->client);
    });

    it('uses the right parameters to send the request', function () {
        $verb = 'GET';
        $endpoint = 'me';
        $params = [
            'param1' => 'value1',
            'param2' => 'value2',
        ];
        $data = [];

        expect($this->client)
            ->toReceive('request')
            ->with('GET', 'users/'.$endpoint.'?'.http_build_query($params), $data)
            ->once();

        $this->service->get($endpoint, $params, $data);
    });

    it('throws exception if sending request with not allowed verbs', function () {
        $allowedVerbs = Service::$ALLOWED_HTTP_VERBS;

        foreach ($allowedVerbs as $verb) {
            $closure = function () use ($verb) {
                return $this->service->$verb();
            };

            expect($closure)->not->toThrow(new RequestException());
        }

        $closure = function () {
            $notAllowedVerb = 'not_allowed';

            return $this->service->$notAllowedVerb();
        };

        expect($closure)->toThrow(new RequestException());
    });
});

Add test about allowed http verbs when sending request


<?php

namespace Rainbow\Calculation\Operation;

use Rainbow\Calculation\CalculationInterface;
use Rainbow\Rgb;

final class Contrast implements CalculationInterface
{
    public function result()
    {
        return new Rgb();
    }

}

<?php

namespace Rainbow\Calculation\Operation;

use Rainbow\Calculation\CalculationInterface;
use Rainbow\Rgb;

final class Contrast implements CalculationInterface
{
    private $contrast;

    public function __construct(Rgb $color)
    {
        $this->contrast = $this->calculateContrast($color);
    }

    private function calculateContrast(Rgb $color)
    {
        return $color->getRed()->getValue() ? new Rgb(0, 0, 0) : new Rgb(255, 255, 255);
    }

    public function result()
    {
        return $this->contrast->copy();
    }

}

Return white color contrasting a dark color


<?php

/*
 * Copyright 2011 Facebook, Inc.
 *
 * 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.
 */

/**
 * @group markup
 */
class PhabricatorRemarkupRuleDiffusion
  extends PhutilRemarkupRule {

  public function apply($text) {
    return preg_replace_callback(
      '@\br([A-Z]+[a-z0-9]+)\b@',
      array($this, 'markupDiffusionLink'),
      $text);
  }

  public function markupDiffusionLink($matches) {
    return $this->getEngine()->storeText(
      'r'.$matches[1].'');
  }

}

<?php

/*
 * Copyright 2011 Facebook, Inc.
 *
 * 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.
 */

/**
 * @group markup
 */
class PhabricatorRemarkupRuleDiffusion
  extends PhutilRemarkupRule {

  public function apply($text) {
    return preg_replace_callback(
      '@\br([A-Z]+[a-f0-9]+)\b@',
      array($this, 'markupDiffusionLink'),
      $text);
  }

  public function markupDiffusionLink($matches) {
    return $this->getEngine()->storeText(
      'r'.$matches[1].'');
  }

}

Use a stricter regexp in Diffusion remarkup

Summary:
Just minor bookkeeping, but the current regexp is too liberal and
will match things which can't possibly be revision hashes.

Test Plan:
Typed things which should and shouldn't be revision links, they
got handled properly.

Reviewed By: aran
Reviewers: jungejason, tuomaspelkonen, aran
CC: aran
Differential Revision: 185


<?php
/**
 * A block that allows end users to manually build a custom (flat or nested) menu
 * @author Shea Dawson <shea@silverstripe.com.au>
 * @package ba-sis
 **/
class CustomMenuBlock extends Block {

    private static $singular_name = 'Custom Menu Block';
    private static $plural_name = 'Custom Menu Blocks';

	private static $db = array(

	);

	private static $has_many = array(
		'Items' => 'CustomMenuBlockItem'
	);

	public function getCMSFields(){
        $fields = parent::getCMSFields();

        $fields->removeFieldFromTab('Root', 'Items');

        $config = GridFieldConfig_RecordEditor::create()
            ->addComponent(new GridFieldOrderableRows());

        $grid = GridField::create('Items', 'Items', $this->Items()->filter('ParentID', 0), $config);

        $config->getComponentByType('GridFieldDataColumns')
        	->setDisplayFields(array(
				'Title' => 'Menu Item Title',
				'Children.Count' => 'Num Children'
			));

		$fields->addFieldToTab('Root.Main', HeaderField::create('ItemsHeader', 'Menu Items'));
        $fields->addFieldToTab('Root.Main', $grid);

        return $fields;
    }

    /**
     * Method for use in templates to loop over menu items
     * @return DataList
     **/
    public function MenuItems(){
    	return $this->Items()->filter('ParentID', 0);
    }
}

<?php
/**
 * A block that allows end users to manually build a custom (flat or nested) menu
 * @author Shea Dawson <shea@silverstripe.com.au>
 * @package ba-sis
 **/
class CustomMenuBlock extends Block {

    private static $singular_name = 'Custom Menu Block';
    private static $plural_name = 'Custom Menu Blocks';

	private static $db = array(

	);

	private static $has_many = array(
		'Items' => 'CustomMenuBlockItem'
	);

	public function getCMSFields(){
        $fields = parent::getCMSFields();

        $fields->removeFieldFromTab('Root', 'Items');

		if ($this->ID) {
			$config = GridFieldConfig_RecordEditor::create()
				->addComponent(new GridFieldOrderableRows());

			$grid = GridField::create('Items', 'Items', $this->Items()->filter('ParentID', 0), $config);

			$config->getComponentByType('GridFieldDataColumns')
				->setDisplayFields(array(
					'Title' => 'Menu Item Title',
					'Children.Count' => 'Num Children'
				));

			$fields->addFieldToTab('Root.Main', HeaderField::create('ItemsHeader', 'Menu Items'));
			$fields->addFieldToTab('Root.Main', $grid);
		}

        return $fields;
    }

    /**
     * Method for use in templates to loop over menu items
     * @return DataList
     **/
    public function MenuItems(){
    	return $this->Items()->filter('ParentID', 0);
    }
}

FIX Fixed breaking custommenu block that was referencing the Items list prior to saving, if accessed via BlockSet


<?php

namespace DjebbZ\HelloBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('DjebbZHelloBundle:Default:index.html.twig', array('name' => $name));
    }

    public function indexJsonAction($name)
    {
      $json = array('name' => $name );
      $response = new Response(json_encode($json));
      $response->headers->set('Content-Type', 'application/json');

      return $response;
    }
}

<?php

namespace DjebbZ\HelloBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('DjebbZHelloBundle:Default:index.html.twig', array('name' => $name));
    }

    public function indexJsonAction($name, $_route)
    {
      $json = array(
        'name' => $name,
        'route' => $_route
      );
      $response = new Response(json_encode($json));
      $response->headers->set('Content-Type', 'application/json');

      return $response;
    }
}

Add the special _route parameter to the json response


<?php

namespace Hackspace\Bundle\CalciferBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Location
 *
 * @property string $name
 * @property float $lon
 * @property float $lat
 *
 * @ORM\Table(name="locations")
 * @ORM\Entity
 */
class Location extends BaseEntity
{
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;

    /**
     * @var float
     *
     * @ORM\Column(name="lon", type="float", nullable=true)
     */
    protected $lon;

    /**
     * @var float
     *
     * @ORM\Column(name="lat", type="float", nullable=true)
     */
    protected $lat;

}

<?php

namespace Hackspace\Bundle\CalciferBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Location
 *
 * @property string $name
 * @property string $description
 * @property float $lon
 * @property float $lat
 * @property string $streetaddress
 * @property string $streetnumber
 * @property string $zipcode;
 * @property string $city
 *
 * @ORM\Table(name="locations")
 * @ORM\Entity
 */
class Location extends BaseEntity
{
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    protected $description;

    /**
     * @var string
     *
     * @ORM\Column(name="streetaddress", type="string", length=255, nullable=true)
     */
    protected $streetaddress;

    /**
     * @var string
     *
     * @ORM\Column(name="streetnumber", type="string", length=255, nullable=true)
     */
    protected $streetnumber;

    /**
     * @var string
     *
     * @ORM\Column(name="zipcode", type="string", length=255, nullable=true)
     */
    protected $zipcode;

    /**
     * @var string
     *
     * @ORM\Column(name="city", type="string", length=255, nullable=true)
     */
    protected $city;

    /**
     * @var float
     *
     * @ORM\Column(name="lon", type="float", nullable=true)
     */
    protected $lon;

    /**
     * @var float
     *
     * @ORM\Column(name="lat", type="float", nullable=true)
     */
    protected $lat;

    public function hasAddress() {
        return ((strlen($this->streetaddress) > 0) && (strlen($this->city)));
    }

}

Add the model stuff to the location.

Add the model stuff to the location.


<?php

namespace TheGame\MapsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        return $this->render('TheGameMapsBundle:Default:index.html.twig');
    }
}

<?php

namespace TheGame\MapsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
//        return $this->render('TheGameMapsBundle:Default:index.html.twig'); DO NOT USE

        return $this->render('TheGameMapsBundle:Default:index.html.twig',
            array('jsLibrary' => $this->getParameter('js_library'),
                'cssLibrary' => $this->getParameter('css_library'),
                'imgLibrary' => $this->getParameter('img_library'),
            ));
    }
}

Change indexAction to include library variables


<?php

namespace MusicBrainz\Value;

use MusicBrainz\Value;

/**
 * A gender
 */
class Gender implements Value
{
    /**
     * Male
     *
     * @var string
     */
    public const MALE = 'male';

    /**
     * Female
     *
     * @var string
     */
    public const FEMALE = 'female';

    /**
     * Neither male nor female
     *
     * @var string
     */
    public const OTHER = 'other';

    /**
     * Undefined gender
     *
     * @var string
     */
    public const UNDEFINED = '';

    /**
     * A list of valid gender codes
     *
     * @var array
     */
    public const GENDERS = [
        self::MALE,
        self::FEMALE,
        self::OTHER,
        self::UNDEFINED
    ];

    /**
     * The gender code
     *
     * @var string
     */
    private $genderCode;

    /**
     * Constructs a gender.
     *
     * @param string $genderCode The gender
     */
    public function __construct(string $genderCode = self::UNDEFINED)
    {
        $this->genderCode = (in_array($genderCode, self::GENDERS))
            ? $genderCode
            : self::UNDEFINED;
    }

    /**
     * Returns the gender code.
     *
     * @return string
     */
    public function __toString(): string
    {
        return (self::UNDEFINED === $this->genderCode)
            ? $this->genderCode
            : '';
    }
}

<?php

namespace MusicBrainz\Value;

use MusicBrainz\Value;

/**
 * A gender
 */
class Gender implements Value
{
    /**
     * Male
     *
     * @var string
     */
    public const MALE = 'male';

    /**
     * Female
     *
     * @var string
     */
    public const FEMALE = 'female';

    /**
     * Neither male nor female
     *
     * @var string
     */
    public const OTHER = 'other';

    /**
     * Undefined gender
     *
     * @var string
     */
    public const UNDEFINED = '';

    /**
     * A list of valid gender codes
     *
     * @var array
     */
    public const GENDERS = [
        self::MALE,
        self::FEMALE,
        self::OTHER,
        self::UNDEFINED
    ];

    /**
     * The gender code
     *
     * @var string
     */
    private $genderCode;

    /**
     * Constructs a gender.
     *
     * @param string $genderCode The gender
     */
    public function __construct(string $genderCode = self::UNDEFINED)
    {
        $genderCode = strtolower(trim($genderCode));
        $this->genderCode = (in_array($genderCode, self::GENDERS))
            ? $genderCode
            : self::UNDEFINED;
    }

    /**
     * Returns the gender code.
     *
     * @return string
     */
    public function __toString(): string
    {
        return (self::UNDEFINED === $this->genderCode)
            ? $this->genderCode
            : '';
    }
}

Allow upper case and untrimmed gender codes


<?php

namespace Tecnocreaciones\Vzla\GovernmentBundle\Form\Type;

use FOS\UserBundle\Form\Type\ProfileFormType;
use Symfony\Component\Form\FormBuilderInterface;

class ProfileFormType extends ProfileFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
                ->add('firstName',null,array(
                    'label' => 'form.first_name',
                    'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle',
                ))
                ->add('lastName',null,array(
                    'label' => 'form.last_name',
                    'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle',
                ))
                ;
    }

    public function getName()
    {
        return 'tecnocreaciones_vzla_government_user_profile';
    }
}

<?php

namespace Tecnocreaciones\Vzla\GovernmentBundle\Form\Type;

use FOS\UserBundle\Form\Type\ProfileFormType as BaseProfileFormType;
use Symfony\Component\Form\FormBuilderInterface;

class ProfileFormType extends BaseProfileFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
                ->add('firstName',null,array(
                    'label' => 'form.first_name',
                    'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle',
                ))
                ->add('lastName',null,array(
                    'label' => 'form.last_name',
                    'translation_domain' => 'TecnocreacionesVzlaGovernmentBundle',
                ))
                ;
    }

    public function getName()
    {
        return 'tecnocreaciones_vzla_government_user_profile';
    }
}

Fix bug al actualizar perfil

Fix bug al actualizar perfil


<?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\Bundle\FrameworkBundle\Test;

use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
 * WebTestCase is the base class for functional tests.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class WebTestCase extends KernelTestCase
{
    /**
     * Creates a Client.
     *
     * @param array $options An array of options to pass to the createKernel method
     * @param array $server  An array of server parameters
     *
     * @return Client A Client instance
     */
    protected static function createClient(array $options = [], array $server = [])
    {
        $kernel = static::bootKernel($options);

        try {
            $client = $kernel->getContainer()->get('test.client');
        } catch (ServiceNotFoundException $e) {
            throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit".');
        }

        $client->setServerParameters($server);

        return $client;
    }
}

<?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\Bundle\FrameworkBundle\Test;

use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
 * WebTestCase is the base class for functional tests.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class WebTestCase extends KernelTestCase
{
    /**
     * Creates a Client.
     *
     * @param array $options An array of options to pass to the createKernel method
     * @param array $server  An array of server parameters
     *
     * @return Client A Client instance
     */
    protected static function createClient(array $options = [], array $server = [])
    {
        $kernel = static::bootKernel($options);

        try {
            $client = $kernel->getContainer()->get('test.client');
        } catch (ServiceNotFoundException $e) {
            if (class_exists(Client::class)) {
                throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.');
            }
            throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"');
        }

        $client->setServerParameters($server);

        return $client;
    }
}

Check if Client exists when test.client does not exist, to provide clearer exception message


<?php

/*
 * This file is part of the Eulogix\Cool package.
 *
 * (c) Eulogix <http://www.eulogix.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

namespace Eulogix\Cool\Lib\Database\Propel\generator\platform;

/**
 * @author Pietro Baricco <pietro@eulogix.com>
 */

class PgsqlPlatform extends \PgsqlPlatform {

    /**
     * Trivial modifications that avoids spitting an error like
     * psql:/tmp/SQLlMdpMc:317: ERROR:  sequence "XXXX_id_seq" does not exist
     *
     * @param \Table $table
     * @return string
     */
    protected function getDropSequenceDDL(\Table $table)
    {
        if ($table->getIdMethod() == \IDMethod::NATIVE && $table->getIdMethodParameters() != null) {
            $pattern = "
DROP SEQUENCE IF EXISTS %s;
";

            return sprintf($pattern,
                $this->quoteIdentifier(strtolower($this->getSequenceName($table)))
            );
        }
    }

}

<?php

/*
 * This file is part of the Eulogix\Cool package.
 *
 * (c) Eulogix <http://www.eulogix.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

namespace Eulogix\Cool\Lib\Database\Propel\generator\platform;

/**
 * @author Pietro Baricco <pietro@eulogix.com>
 */

class PgsqlPlatform extends \PgsqlPlatform {

    /**
     * Trivial modifications that avoids spitting an error like
     * psql:/tmp/SQLlMdpMc:317: ERROR:  sequence "XXXX_id_seq" does not exist
     *
     * @param \Table $table
     * @return string
     */
    protected function getDropSequenceDDL( $table)
    {
        if ($table->getIdMethod() == \IDMethod::NATIVE && $table->getIdMethodParameters() != null) {
            $pattern = "
DROP SEQUENCE IF EXISTS %s;
";

            return sprintf($pattern,
                $this->quoteIdentifier(strtolower($this->getSequenceName($table)))
            );
        }
    }

}

Fix for adjust parent method definition

Fix for adjust parent method definition


@extends('layouts.app')

@section('content')

Operational notes

    <div class="col input-gropu mb-3"
      <form wire:submit.prevent="getNotes">
        Machine:
        <select wire:model="m">
          <option>Select a machine</option>
          @foreach ($machine as $m)
            <option value="{{$m->id}}">{{$m->description}}</option>
          @endforeach
        </select>
        <button type="submit">Get Notes</button>
      </form>

@endsection

@extends('layouts.app')

@section('content')

Operational notes

    <div class="col input-group mb-3"
      <form wire:submit.prevent="getNotes">
        Machine:
        <select wire:model="m">
          <option>Select a machine</option>
          @foreach ($machine as $m)
            <option value="{{$m->id}}">{{$m->description}}</option>
          @endforeach
        </select>
        <button type="submit">Get Notes</button>
      </form>

    @if(!is_null($opNotes))

      @foreach ($opNotes as $o)

$o->note

      @endforeach

    @endif

@endsection

Work on operational notes page

Work on operational notes page


<?php
namespace engine\controllers;

class HelloController
{

    public function doHelloWorld ($id = false)
    {
        echo 'Hello World ! ' . $id;
    }

    public function doHelloWorldNew()
    {
        echo 'new Hello World !';
    }
}

<?php
namespace engine\controllers;

class HelloController
{
    public function helloHome ()
    {
        echo 'Home';
    }

    public function doHelloWorld ($id = false)
    {
        echo 'Hello World ! ' . $id;
    }

    public function doHelloWorldNew()
    {
        echo 'new Hello World !';
    }
}

Routing: Add home action in HomeController to test default route


Help

Upcoming Visits

Unit Cell Search
                <?php if ($this->staff): ?>

PDB vs Unit Cell

                <?php endif; ?>

Proposals

                <?php echo $prop ?>
                <?php if ($prop): ?>

Visits

Calendar

Prepare Experiment

Shipments

Samples

Proteins

Lab Contacts

Statistics

                <?php endif; ?>

        Menu

Help

Upcoming Visits
                <?php if ($this->staff): ?>

Calendar

                <?php endif; ?>

Unit Cell Search
                <?php if ($this->staff): ?>

PDB vs Unit Cell

                <?php endif; ?>

Proposals

                <?php echo $prop ?>
                <?php if ($prop): ?>

Visits

Calendar

Prepare Experiment

Shipments

Samples

Proteins

Lab Contacts

Statistics

                <?php endif; ?>

        Menu

Add full calendar for staff

Add full calendar for staff


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;
use Auth;

class ItemsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

    public function readItems() {
        $faves = Item::all();
        return $faves;
    }

    public function storeItem(Request $request) {
        $data = new Item();
        $data->name = $request->name;
        $data->user_id = Auth::user()->id;
        $data->save();
        return $data;
    }

    public function deleteItem(Request $request) {
        Item::find($request->id)->delete ();
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;
use Auth;

class ItemsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

    public function readItems() {
        $items = Item::with('category')->get();
        return $items;
    }

    public function storeItem(Request $request) {
        $data = new Item();
        $data->name = $request->name;
        $data->category_id = $request->category_id;
        $data->user_id = Auth::user()->id;
        $data->save();
        return $data;
    }

    public function deleteItem(Request $request) {
        Item::find($request->id)->delete ();
    }
}

Update faves to items, remove guest middleware


<?php declare(strict_types = 1);

namespace Sylius\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20180102140039 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE INDEX IDX_16C8119EE551C011 ON sylius_channel (hostname)');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP INDEX IDX_16C8119EE551C011 ON sylius_channel');
    }
}

<?php

namespace Sylius\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20180102140039 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE INDEX IDX_16C8119EE551C011 ON sylius_channel (hostname)');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP INDEX IDX_16C8119EE551C011 ON sylius_channel');
    }
}

Remove strict declaration on migration

Remove strict declaration on migration


<?php

namespace Wanjee\Shuwee\AdminBundle\Datagrid;

use Symfony\Component\HttpFoundation\Request;

interface DatagridInterface
{
    // add field
    // get fields
    // add filter
    // get filters

    /**
     * @param \Symfony\Component\HttpFoundation\Request $request
     */
    public function setRequest(Request $request);

}

<?php

namespace Wanjee\Shuwee\AdminBundle\Datagrid;

use Symfony\Component\HttpFoundation\Request;

interface DatagridInterface
{
    // Todo define scope...
}

Remove useless defined method from interface, it will not be used


<?php

class Denkmal_Paging_Event_SearchText extends Denkmal_Paging_Event_Abstract {

    /**
     * @param string $text
     */
    public function __construct($text) {
        $query = new Denkmal_Elasticsearch_Query_Event();

        $query->queryText($text);
        $query->sortScore();

        $source = new CM_PagingSource_Search(new Denkmal_Elasticsearch_Type_Event(), $query);

        parent::__construct($source);
    }
}

<?php

class Denkmal_Paging_Event_SearchText extends Denkmal_Paging_Event_Abstract {

    /**
     * @param string $text
     */
    public function __construct($text) {
        $query = new Denkmal_Elasticsearch_Query_Event();

        $query->queryText($text);
        $query->sortFrom();

        $source = new CM_PagingSource_Search(new Denkmal_Elasticsearch_Type_Event(), $query);

        parent::__construct($source);
    }
}

Order searched events in admin by "from"


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

namespace Flarum\Http\Controller;

use Flarum\Event\ConfigureWebApp;
use Flarum\Http\WebApp\AbstractWebApp;
use Illuminate\Contracts\Events\Dispatcher;
use Psr\Http\Message\ServerRequestInterface as Request;

abstract class AbstractWebAppController extends AbstractHtmlController
{
    /**
     * @var AbstractWebApp
     */
    protected $webApp;

    /**
     * @var Dispatcher
     */
    protected $events;

    /**
     * {@inheritdoc}
     */
    public function render(Request $request)
    {
        $view = $this->getView($request);

        $this->events->fire(
            new ConfigureWebApp($this, $view, $request)
        );

        return $view->render($request);
    }

    /**
     * @param Request $request
     * @return \Flarum\Http\WebApp\WebAppView
     */
    protected function getView(Request $request)
    {
        return $this->webApp->getView();
    }
}

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

namespace Flarum\Http\Controller;

use Flarum\Event\ConfigureClientView;
use Flarum\Event\ConfigureWebApp;
use Flarum\Http\WebApp\AbstractWebApp;
use Illuminate\Contracts\Events\Dispatcher;
use Psr\Http\Message\ServerRequestInterface as Request;

abstract class AbstractWebAppController extends AbstractHtmlController
{
    /**
     * @var AbstractWebApp
     */
    protected $webApp;

    /**
     * @var Dispatcher
     */
    protected $events;

    /**
     * {@inheritdoc}
     */
    public function render(Request $request)
    {
        $view = $this->getView($request);

        $this->events->fire(
            new ConfigureClientView($this, $view, $request)
        );
        $this->events->fire(
            new ConfigureWebApp($this, $view, $request)
        );

        return $view->render($request);
    }

    /**
     * @param Request $request
     * @return \Flarum\Http\WebApp\WebAppView
     */
    protected function getView(Request $request)
    {
        return $this->webApp->getView();
    }
}

Make sure deprecated ConfigureClientView event still works


<?php

namespace App\Actions;

use App\Shell\Shell;
use Facades\App\Environment;

class OpenInBrowser
{
    use LamboAction;

    protected $shell;

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

    public function __invoke()
    {
        $this->logStep('Opening in Browser');

        if (Environment::isMac() && $this->browser()) {
            $this->shell->execInProject(sprintf(
                'open -a "%s" "%s"',
                $this->browser(),
                config('lambo.store.project_url')
            ));
            $this->info('[ lambo ] Opened your new site. in ' . $this->browser() . ' Happy coding!');
        } else {
            $this->shell->execInProject("valet open");
        }
    }

    public function browser()
    {
        return config('lambo.store.browser');
    }
}

<?php

namespace App\Actions;

use App\Shell\Shell;
use Facades\App\Environment;

class OpenInBrowser
{
    use LamboAction;

    protected $shell;

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

    public function __invoke()
    {
        $this->logStep('Opening in Browser');

        if (Environment::isMac() && $this->browser()) {
            $this->shell->execInProject(sprintf(
                'open -a "%s" "%s"',
                $this->browser(),
                config('lambo.store.project_url')
            ));
        } else {
            $this->shell->execInProject("valet open");
        }
    }

    public function browser()
    {
        return config('lambo.store.browser');
    }
}

Remove unnecessary console logging since the open browser is all the feedback required.


<?php

namespace Surfnet\StepupBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SurfnetStepupBundle extends Bundle
{
}

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

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SurfnetStepupBundle extends Bundle
{
}

Add license header to StepupBundle.

Add license header to StepupBundle.


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

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

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

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

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

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

Add a link used to clear the purchase date input


<?php

namespace Brick\Math\Tests;

use Brick\Math\BigDecimal;
use Brick\Math\BigInteger;

/**
 * Base class for BigInteger and BigDecimal test cases.
 */
abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @param string     $expected The expected value as a string.
     * @param BigInteger $actual   The BigInteger instance to test.
     */
    protected function assertBigIntegerEquals($expected, BigInteger $actual)
    {
        $this->assertSame($expected, (string) BigInteger::of($actual));
    }

    /**
     * @param string     $unscaledValue The expected unscaled value.
     * @param integer    $scale         The expected scale.
     * @param BigDecimal $actual        The BigDecimal instance to test.
     */
    protected function assertBigDecimalEquals($unscaledValue, $scale, BigDecimal $actual)
    {
        $this->assertSame($unscaledValue, $actual->getUnscaledValue());
        $this->assertSame($scale, $actual->getScale());
    }
}

<?php

namespace Brick\Math\Tests;

use Brick\Math\BigDecimal;
use Brick\Math\BigInteger;

/**
 * Base class for BigInteger and BigDecimal test cases.
 */
abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @param string     $expected The expected value as a string.
     * @param BigInteger $actual   The BigInteger instance to test.
     */
    protected function assertBigIntegerEquals($expected, BigInteger $actual)
    {
        $this->assertSame($expected, (string) $actual);
    }

    /**
     * @param string     $unscaledValue The expected unscaled value.
     * @param integer    $scale         The expected scale.
     * @param BigDecimal $actual        The BigDecimal instance to test.
     */
    protected function assertBigDecimalEquals($unscaledValue, $scale, BigDecimal $actual)
    {
        $this->assertSame($unscaledValue, $actual->getUnscaledValue());
        $this->assertSame($scale, $actual->getScale());
    }
}

Remove useless of() call in tests

Remove useless of() call in tests


<?php

use Dojo\Example;
use PHPUnit\Framework\TestCase;

class ExampleTest extends TestCase
{
    public function testRandom()
    {
        $object = new Example();
        $this->assertEquals(4, $object->random());
    }
}

<?php

use Dojo\Example;
use PHPUnit\Framework\TestCase;

class ExampleTest extends TestCase
{
    // This method will be called *before* each test run.
    public function setUp() {}

    // This method will be called *after* each test run.
    public function tearDown() {}

    public function testRandom()
    {
        $object = new Example();
        $this->assertEquals(4, $object->random());
    }
}

Add setUp and tearDown to test example

Add setUp and tearDown to test example


<?php

namespace PHPMD;

class Fingerprint
{
    const OVERRIDE_RULES = [
      "CyclomaticComplexity",
      "Design/LongClass",
      "Design/LongMethod",
    ];
    private $name;
    private $path;
    private $rule;

    public function __construct($path, $rule, $name)
    {
        $this->path = $path;
        $this->rule = $rule;
        $this->name = $name;
    }

    public function compute()
    {
        $fingerprint = null;

        if (in_array($this->rule, self::OVERRIDE_RULES)) {
            $fingerprint = md5($this->path . $this->rule . $this->name);
        }

        return $fingerprint;
    }
}

<?php

namespace PHPMD;

class Fingerprint
{
    const OVERRIDE_RULES = [
      "CyclomaticComplexity",
      "Design/LongClass",
      "Design/LongMethod",
      "Design/LongParameterList",
      "Design/NpathComplexity",
      "Design/NumberOfChildren",
      "Design/TooManyFields",
      "Design/TooManyMethods",
      "Design/TooManyPublicMethods",
      "Design/WeightedMethodCount",
      "ExcessivePublicCount",
    ];
    private $name;
    private $path;
    private $rule;

    public function __construct($path, $rule, $name)
    {
        $this->path = $path;
        $this->rule = $rule;
        $this->name = $name;
    }

    public function compute()
    {
        $fingerprint = null;

        if (in_array($this->rule, self::OVERRIDE_RULES)) {
            $fingerprint = md5($this->path . $this->rule . $this->name);
        }

        return $fingerprint;
    }
}

Add fingerprint consistency for Complexity issues


<?php

use Emergence\People\User;

User::$fields['Twitter'] = [
    'notnull' => false,
    'unique' => true
];

User::$relationships['Tags'] = [
    'type' => 'many-many',
    'class' => \Tag::class,
    'linkClass' => \TagItem::class,
    'linkLocal' => 'ContextID',
    'conditions' => ['Link.ContextClass = "Emergence\\\\People\\\\Person"']
];

User::$relationships['Comments'] = [
    'type' => 'context-children',
    'class' => \Comment::class,
    'contextClass' => __CLASS__,
    'order' => ['ID' => 'DESC']
];

<?php

use Emergence\People\User;

User::$fields['Twitter'] = [
    'notnull' => false,
    'unique' => true
];

User::$relationships['Tags'] = [
    'type' => 'many-many',
    'class' => \Tag::class,
    'linkClass' => \TagItem::class,
    'linkLocal' => 'ContextID',
    'conditions' => ['Link.ContextClass = "Emergence\\\\People\\\\Person"']
];

User::$relationships['TopicTags'] = [
    'type' => 'many-many',
    'class' => \Tag::class,
    'linkClass' => \TagItem::class,
    'linkLocal' => 'ContextID',
    'conditions' => [
        'Link.ContextClass = "Emergence\\\\People\\\\Person"',
        'Related.Handle LIKE "topic.%"'
    ]
];

User::$relationships['TechTags'] = [
    'type' => 'many-many',
    'class' => \Tag::class,
    'linkClass' => \TagItem::class,
    'linkLocal' => 'ContextID',
    'conditions' => [
        'Link.ContextClass = "Emergence\\\\People\\\\Person"',
        'Related.Handle LIKE "tech.%"'
    ]
];

User::$relationships['Comments'] = [
    'type' => 'context-children',
    'class' => \Comment::class,
    'contextClass' => __CLASS__,
    'order' => ['ID' => 'DESC']
];

Add tech/topic tag relationships to Users


<?php
/**
 * Application.php
 *
 * MIT LICENSE
 *
 * LICENSE: This source file is subject to the MIT license.
 * A copy of the licenses text was distributed alongside this
 * file (usually the repository or package root). The text can also
 * be obtained through one of the following sources:
 * * http://opensource.org/licenses/MIT
 * * https://github.com/suralc/pvra/blob/master/LICENSE
 *
 * @author     suralc <thesurwaveing@gmail.com>
 * @license    http://opensource.org/licenses/MIT  MIT
 */
namespace Pvra\Console;

use Symfony\Component\Console\Application as BaseApplication;

/**
 * Class Application
 *
 * @package Pvra\Console
 */
class Application extends BaseApplication
{
    const APPLICATION_DEFAULT_VERSION = '0.1.0-dev';

    /**
     * @inheritdoc
     */
    public function __construct($name = 'UNKNOWN', $version = '@package_version@')
    {
        if ($version === '@package' . '_version@') {
            $version = static::APPLICATION_DEFAULT_VERSION;
        }

        parent::__construct($name, $version);
    }
}

<?php
/**
 * Application.php
 *
 * MIT LICENSE
 *
 * LICENSE: This source file is subject to the MIT license.
 * A copy of the licenses text was distributed alongside this
 * file (usually the repository or package root). The text can also
 * be obtained through one of the following sources:
 * * http://opensource.org/licenses/MIT
 * * https://github.com/suralc/pvra/blob/master/LICENSE
 *
 * @author     suralc <thesurwaveing@gmail.com>
 * @license    http://opensource.org/licenses/MIT  MIT
 */
namespace Pvra\Console;

use Symfony\Component\Console\Application as BaseApplication;

/**
 * Class Application
 *
 * @package Pvra\Console
 */
class Application extends BaseApplication
{
    const APPLICATION_DEFAULT_VERSION = '0.0.1';

    /**
     * @inheritdoc
     */
    public function __construct($name = 'UNKNOWN', $version = '@package_version@')
    {
        if ($version === '@package' . '_version@') {
            $version = static::APPLICATION_DEFAULT_VERSION;
        }

        parent::__construct($name, $version);
    }
}

Change version to something more appropriate.


<?php namespace Aedart\Scaffold\Console;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Console\Style\Factory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\StyleInterface;

/**
 * Base Command
 *
 * The base command for all scaffold console commands
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Console
 */
abstract class BaseCommand extends Command
{

    /**
     * The input
     *
     * @var InputInterface
     */
    protected $input;

    /**
     * The output
     *
     * @var StyleInterface|OutputInterface
     */
    protected $output;

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $ioc = IoC::getInstance();

        /** @var Factory $factory */
        $factory = $ioc->make(Factory::class);

        $this->input = $input;
        $this->output = $factory->make($input, $output);

        return $this->runCommand();
    }

    /**
     * Execute the command
     *
     * @return int|null
     */
    abstract public function runCommand();
}

<?php namespace Aedart\Scaffold\Console;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Console\Style\Factory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\StyleInterface;

/**
 * Base Command
 *
 * The base command for all scaffold console commands
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Console
 */
abstract class BaseCommand extends Command
{

    /**
     * The input
     *
     * @var InputInterface
     */
    protected $input;

    /**
     * The output
     *
     * @var StyleInterface|OutputInterface
     */
    protected $output;

    public function execute(InputInterface $input, OutputInterface $output)
    {
        // Set input
        $this->input = $input;

        // Set output
        if($output instanceof StyleInterface){
            $this->output = $output;
        } else {
            // Means that we should wrap the output
            /** @var Factory $factory */
            $factory = IoC::getInstance()->make(Factory::class);
            $this->output = $factory->make($input, $output);
        }

        return $this->runCommand();
    }

    /**
     * Execute the command
     *
     * @return int|null
     */
    abstract public function runCommand();
}

Change base command, set output

Change base command, set output

In case that a styled-output is given, then there is no need to wrap the
output.


<?php
declare(strict_types=1);

namespace PerFi\Application\Factory;

use PerFi\Domain\Account\Account;
use PerFi\Domain\Account\AccountId;
use PerFi\Domain\Account\AccountType;

class AccountFactory
{
    /**
     * Create an Account from a row in the database
     *
     * @param array $account
     * @param array $balances
     * @return Account
     */
    public static function fromArray(array $account, array $balances) : Account
    {
        return Account::withId(
            AccountId::fromString($account['id']),
            AccountType::fromString($account['type']),
            $account['title'],
            $balances
        );
    }
}

<?php
declare(strict_types=1);

namespace PerFi\Application\Factory;

use PerFi\Domain\Account\Account;
use PerFi\Domain\Account\AccountId;
use PerFi\Domain\Account\AccountType;
use PerFi\Domain\MoneyFactory;

class AccountFactory
{
    /**
     * Create an Account from a row in the database
     *
     * @param array $account
     * @param array $balances
     * @return Account
     */
    public static function fromArray(array $account, array $balances) : Account
    {
        $balanceAmounts = [];

        foreach ($balances as $balance) {
            $balanceAmounts[$balance['currency']][] = MoneyFactory::centsInCurrency($balance['amount'], $balance['currency']);
        }

        return Account::withId(
            AccountId::fromString($account['id']),
            AccountType::fromString($account['type']),
            $account['title'],
            $balanceAmounts
        );
    }
}

Convert balance records to Money objects


<?php namespace Inkwell
{
	use Affinity;
	use Auryn;

	$loader    = require 'vendor/autoload.php';
	$constants = require 'constants.php';

 	foreach ($constants as $const => $value) {
		define('IW\\' . $const, $value);
	}

	$app  	       = new Core(realpath(__DIR__));
	$broker        = new Auryn\Provider();
	$config_dir    = $app->getDirectory($app->getEnvironment('IW_CONFIG_ROOT', 'config'));
	$action_dir    = $app->getDirectory($app->getEnvironment('IW_ACTION_ROOT', 'include'));
	$environment   = $app->getEnvironment('IW_ENVIRONMENT', 'prod');

	$app['loader'] = $loader;
	$app['engine'] = new Affinity\Engine(
		new Affinity\NativeDriver($config_dir),
		new Affinity\NativeDriver($action_dir)
	);

	$app['engine']->start($environment, $app, $broker);

	return $app;
}

<?php namespace Inkwell
{
	use Affinity;
	use Auryn;

	$loader    = require 'vendor/autoload.php';
	$constants = require 'constants.php';

 	foreach ($constants as $const => $value) {
		define('IW\\' . $const, $value);
	}

	$app  	       = new Core(realpath(__DIR__));
	$broker        = new Auryn\Provider();
	$config_dir    = $app->getDirectory($app->getEnvironment('IW_CONFIG_ROOT', 'config'));
	$action_dir    = $app->getDirectory($app->getEnvironment('IW_ACTION_ROOT', 'include'));
	$environment   = $app->getEnvironment('IW_ENVIRONMENT', 'prod');

	$app['loader'] = $loader;
	$app['engine'] = new Affinity\Engine(
		new Affinity\NativeDriver($config_dir),
		new Affinity\NativeDriver($action_dir)
	);

	$app['engine']->start($environment, ['app' => $app, 'broker' => $broker]);

	return $app;
}

Change how context is passed

Change how context is passed


<?php

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

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

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->index(['is_sticky', 'created_at']);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->dropIndex(['is_sticky', 'created_at']);
        });
    }
];

<?php

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

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

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->index(['is_sticky', 'created_at']);

            Migration::fixIndexNames($schema, $table);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->dropIndex(['is_sticky', 'created_at']);

            Migration::fixIndexNames($schema, $table);
        });
    }
];

Fix index names in migrations

Fix index names in migrations

This can be reverted when we upgrade to Laravel 5.7.


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

namespace Flarum\Embed;

use Flarum\Forum\WebApp;

class EmbedWebApp extends WebApp
{
    /**
     * {@inheritdoc}
     */
    public function getView()
    {
        $view = parent::getView();

        $view->getJs()->addFile(__DIR__.'/../js/forum/dist/extension.js');
        $view->getCss()->addFile(__DIR__.'/../less/forum/extension.less');

        $view->loadModule('flarum/embed/main');
        $view->setLayout(__DIR__.'/../views/embed.blade.php');

        return $view;
    }

    /**
     * {@inheritdoc}
     */
    public function getAssets()
    {
        return $this->assets->make('embed');
    }
}

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

namespace Flarum\Embed;

use Flarum\Forum\WebApp;

class EmbedWebApp extends WebApp
{
    /**
     * {@inheritdoc}
     */
    public function getView()
    {
        $view = parent::getView();

        $view->getJs()->addFile(__DIR__.'/../js/forum/dist/extension.js');
        $view->getCss()->addFile(__DIR__.'/../less/forum/extension.less');

        $view->loadModule('flarum/embed/main');
        $view->layout = __DIR__.'/../views/embed.blade.php';

        return $view;
    }

    /**
     * {@inheritdoc}
     */
    public function getAssets()
    {
        return $this->assets->make('embed');
    }
}

Use new core API for modifying WebAppView properties


<?php

namespace Sioen;

/**
 * Get a translated list of countries
 * Uses this vendor: https://github.com/umpirsky/country-list/
 *
 * @author Wouter Sioen <wouter.sioen@wijs.be>
 */
class Countries
{
    /**
     * @var array
     */
    protected $countries = array();

    /**
     * @param string $language
     * @return array
     */
    protected function getCountries($language)
    {
        if(!isset($this->countries[$language]))
        {
            $this->countries[$language] = include($this->getFilePath($language));
        }

        return $this->countries[$language];
    }

    /**
     * @param string $language
     * @return string
     */
    protected function getFilePath($language)
    {
        // our files with countries are placed in the country-list vendor
        return dirname(__FILE__) . '/../../vendor/umpirsky/country-list/country/icu/' .
            $language . '/country.php'
        ;
    }

    /**
     * @param string $language
     * @return array
     */
    public function getForLanguage($language)
    {
        return $this->getCountries($language);
    }
}

<?php

namespace Sioen;

/**
 * Get a translated list of countries
 * Uses this vendor: https://github.com/umpirsky/country-list/
 *
 * @author Wouter Sioen <wouter.sioen@wijs.be>
 */
class Countries
{
    /**
     * @var array
     */
    protected $countries = array();

    /**
     * @param string $language
     * @return array
     */
    protected function getCountries($language)
    {
        if(!isset($this->countries[$language]))
        {
            $this->countries[$language] = include($this->getFilePath($language));
        }

        return $this->countries[$language];
    }

    /**
     * @param string $language
     * @return string
     */
    protected function getFilePath($language)
    {
        $path = dirname(__FILE__) . '/../../';

        // if our class is loaded from composer, the path to umpirski changes
        if (strpos('/vendor/', dirname(__FILE__)) !== false) {
            $path .= '../../../';
        }

        // our files with countries are placed in the country-list vendor
        return $path . 'vendor/umpirsky/country-list/country/icu/' .
            $language . '/country.php'
        ;
    }

    /**
     * @param string $language
     * @return array
     */
    public function getForLanguage($language)
    {
        return $this->getCountries($language);
    }
}

Make sure path is correct when loaded from composer


<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";
$client = new Client($sid, $token);

// Loop over the list of messages and echo a property for each one
// TODO: Add To, From, DateSent> parameters
foreach ($client->messages->read() as $message) {
    echo $message->body;
}

<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once 'vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";

$client = new Client($sid, $token);

// Loop over the list of messages and echo a property for each one
$params = array('to' => 'to_number', 'from' => 'from_number', 'dateSent' => date('2016-09-06'));
$result = $client->messages->read($params);

foreach ($result as $message) {
    echo $message->body;
}

Add missing params to search

[retrieve-modify-message-history|PHP] Add missing params to search


<?php
class timeoutFilter extends sfFilter
{
  public function execute ($filterChain)
  {

    if($time = sfConfig::get('dw_queryTimeout',null))
    {
      $conn = Doctrine_Manager::connection();
      $conn->exec("SET statement_timeout = ".$time.";");
    }
    $filterChain->execute();
  }
}

<?php
class timeoutFilter extends sfFilter
{
  public function execute ($filterChain)
  {

    if($time = sfConfig::get('dw_queryTimeout',null))
    {
      $conn = Doctrine_Manager::connection();
      $conn->exec("SET statement_timeout = ".$time.";");
    }

    $version = $conn->getAttribute(PDO::ATTR_SERVER_VERSION);
    if(strpos($version,'8.') !== 0) {
      $conn->exec("SET application_name = 'darwin';");
    }

    $filterChain->execute();
  }
}

Add Application name in DB if pg version >= 8


<?php

namespace Yiitter;

/**
 * Creates an exception from a tmhOAuth instance based on its last response data.
 *
 * @author Shiki <bj@basanes.net>
 */
class ClientException extends \Exception
{
  public $statusCode;

  /**
   * Create an instance of self.
   *
   * @param \tmhOAuth $client
   */
  public function __construct(\tmhOAuth $client)
  {
    if (!empty($client->response['response'])) {
      $response = json_decode($client->response['response'], true);
      if (array_key_exists('errors', $response)) {
        $message = $response['errors'][0]['message'];
        $code = $response['errors'][0]['code'];
      }
    }

    if (!isset($message))
      $message = $client->response['error'];
    if (!isset($code))
      $code = $client->response['errno'];

    $this->statusCode = $client->response['info']['http_code'];

    parent::__construct($message, $code);
  }

  /**
   * Creates an instance of self only if the \tmhOAuth instance's response is an error.
   *
   * @param \tmhOAuth $client
   * @return self
   */
  public static function createIfFailed(\tmhOAuth $client)
  {
    if ($client->response['info']['http_code'] == 200
      || $client->response['info']['http_code'] == 201) {
      return null;
    }

    return new self($client);
  }
}

<?php

namespace Yiitter;

/**
 * Creates an exception from a tmhOAuth instance based on its last response data.
 *
 * @author Shiki <bj@basanes.net>
 */
class ClientException extends \Exception
{
  public $statusCode;

  /**
   * Create an instance of self.
   *
   * @param \tmhOAuth $client
   */
  public function __construct(\tmhOAuth $client)
  {
    if (!empty($client->response['response'])) {
      $response = json_decode($client->response['response'], true);
      if (array_key_exists('errors', $response)) {
        $message = $response['errors'][0]['message'];
        $code = $response['errors'][0]['code'];
      }
    }

    if (!isset($message))
      $message = $client->response['error'];
    if (!isset($code))
      $code = $client->response['errno'];

    $this->statusCode = $client->response['info']['http_code'];

    parent::__construct($message, $code);
  }

  /**
   * Creates an instance of self only if the \tmhOAuth instance's response is an error.
   * This only allows non-tmhOAuth for unit testing.
   *
   * @param \tmhOAuth $client
   * @return self
   */
  public static function createIfFailed($client)
  {
    if ($client->response['info']['http_code'] == 200
      || $client->response['info']['http_code'] == 201) {
      return null;
    }

    return new self($client);
  }
}

Allow throwing of exception when yiitter is mocked in unit tests


<?php

spl_autoload_register(function ($classname) {
	$file = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $classname) . '.php';
	if (is_file($file)) {
		require_once $file;
	}
});

// backward compatibility
if (!class_exists('\PHPUnit\Framework\TestCase') && class_exists('\PHPUnit_Framework_TestCase')) {
	class_alias('\PHPUnit_Framework_TestCase', '\PHPUnit\Framework\TestCase');
}

class SwaggerGen_TestCase extends \PHPUnit\Framework\TestCase {
	public function expectException($exception) {
		self::setExpectedException($exception);
	}
}

<?php

spl_autoload_register(function ($classname) {
	$file = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $classname) . '.php';
	if (is_file($file)) {
		require_once $file;
	}
});

// backward compatibility
if (!class_exists('PHPUnit\Framework\TestCase') && class_exists('PHPUnit_Framework_TestCase')) {
	class_alias('PHPUnit_Framework_TestCase', 'PHPUnit\Framework\TestCase');
}

class SwaggerGen_TestCase extends PHPUnit\Framework\TestCase {
	public function expectException($exception) {
		self::setExpectedException($exception);
	}
}

Fix more PHPUnitTest backwards incompatibilities


<?php

class ApiFastTest extends TestCase
{
	protected $baseUrl = '';

	/**
	 * ApiFastTest constructor.
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * A basic functional test example.
	 *
	 * @return void
	 */
	public function testEmotes()
	{
		// WoTlk
		$this->json('GET', '/api/v1/dbc/emotes/')->seeJson(
			["id" => 0, "emote" => "ONESHOT_NONE"]
		);

		$this->json('GET', '/api/v1/dbc/emotes/3')->seeJson(
			["id" => 3, "emote" => "ONESHOT_WAVE(DNR)"]
		);

		// Wod
		$this->json('GET', '/api/v1/dbc/emotes/?version=wod')->seeJson(
			["id" => 577, "emote" => "ONESHOT_ATTACK1H"]
		);

		$this->json('GET', '/api/v1/dbc/emotes//?version=wod')->seeJson(
			["id" => 619, "emote" => "STATE_PARRY_UNARMED"]
		);
	}
}

<?php

class ApiFastTest extends TestCase
{
	protected $baseUrl = '';

	/**
	 * ApiFastTest constructor.
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * A basic functional test example.
	 *
	 * @return void
	 */
	public function testEmotes()
	{
		// WoTlk
		$this->json('GET', '/api/v1/dbc/emotes/')->seeJson(
			["id" => 0, "emote" => "ONESHOT_NONE"]
		);

		$this->json('GET', '/api/v1/dbc/emotes/3')->seeJsonEquals(
			["id" => 3, "emote" => "ONESHOT_WAVE(DNR)"]
		);

		// Wod
		$this->json('GET', '/api/v1/dbc/emotes/?version=wod')->seeJson(
			["id" => 577, "emote" => "ONESHOT_ATTACK1H"]
		);

		$this->json('GET', '/api/v1/dbc/emotes/619/?version=wod')->seeJsonEquals(
			["id" => 619, "emote" => "STATE_PARRY_UNARMED"]
		);
	}
}

Test Emotes: Equals assert for search by id.


<?php

namespace Milax\Mconsole\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Milax\Mconsole\Models\Image as ImageModel;
use Image;
use File;

class ImagesController extends Controller
{
    protected $uploadDir;
    protected $uploadUrl;
    protected $scriptUrl;

    public function __construct()
    {
        $this->uploadDir = storage_path('tmp/images/');
        $this->previewUrl = '/storage/images/';
        $this->scriptUrl = '/mconsole/api/images/delete/';
    }

    /**
     * Get all images for given model and id
     *
     * @return Resposne
     */
    public function get(Request $request)
    {
        $input = $request->all();
        $input['related_class'] = urldecode($input['related']);
        return app('API')->images->get($input['group'], $input['related_class'], $input['related_id'], $this->previewUrl, $this->scriptUrl);
    }

    /**
     * Upload images
     *
     * @param  Request $request
     * @return Response
     */
    public function uploadImage()
    {
        echo app('API')->images->upload();
    }

    /**
     * Delete image
     *
     * @param int $fileName [Image file id]
     * @return Response
     */
    public function deleteImage($id)
    {
        app('API')->images->delete($id);
    }
}

<?php

namespace Milax\Mconsole\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Milax\Mconsole\Models\Image as ImageModel;
use Image;
use File;

class ImagesController extends Controller
{
    protected $uploadDir;
    protected $uploadUrl;
    protected $scriptUrl;

    public function __construct()
    {
        $this->uploadDir = storage_path('tmp/images/');
        $this->previewUrl = '/storage/images/';
        $this->scriptUrl = '/mconsole/api/images/delete/';
    }

    /**
     * Get all images for given model and id
     *
     * @return Resposne
     */
    public function get(Request $request)
    {
        $input = $request->all();
        $input['related_class'] = urldecode($input['related_class']);
        return app('API')->images->get($input['group'], $input['related_class'], $input['related_id'], $this->previewUrl, $this->scriptUrl);
    }

    /**
     * Upload images
     *
     * @param  Request $request
     * @return Response
     */
    public function uploadImage()
    {
        echo app('API')->images->upload();
    }

    /**
     * Delete image
     *
     * @param int $fileName [Image file id]
     * @return Response
     */
    public function deleteImage($id)
    {
        app('API')->images->delete($id);
    }
}

Fix get images array index

Fix get images array index


<?php
namespace CfdiUtilsTests\OpenSSL;

/**
 * This test convert the file CSD01_AAA010101AAA.key as an unprotected key file converted using command:
 * openssl pkcs8 -inform DER -passin pass:12345678a -in CSD01_AAA010101AAA.key -out CSD01_AAA010101AAA.key.pem
 *
 * Is a control test to ensure that PRIVATE KEY is working
 */
class PrivateKeyConvertedTest extends PrivateKeyGenericTestCase
{
    protected function getPrivateKey(): string
    {
        $derkey = $this->utilAsset('certs/CSD01_AAA010101AAA.key');
        $openSSL = $this->getOpenSSL();
        $pemkey = $openSSL->convertPrivateKeyFileDERToPEM($derkey, '12345678a');
        return $pemkey;
    }
}

<?php
namespace CfdiUtilsTests\OpenSSL;

/**
 * This test convert the file CSD01_AAA010101AAA.key as an unprotected key file converted using command:
 * openssl pkcs8 -inform DER -passin pass:12345678a -in CSD01_AAA010101AAA.key -out CSD01_AAA010101AAA.key.pem
 *
 * Is a control test to ensure that PRIVATE KEY is working
 */
class PrivateKeyConvertedTest extends PrivateKeyGenericTestCase
{
    protected function getPrivateKey(): string
    {
        $derkeyFile = $this->utilAsset('certs/CSD01_AAA010101AAA.key');
        $derkey = strval(file_get_contents($derkeyFile));
        $openSSL = $this->getOpenSSL();
        $pemkey = $openSSL->convertPrivateKeyContentsDERToPEM($derkey, '12345678a');
        return $pemkey;
    }
}

Test using the more expensive call

Test using the more expensive call


<!doctype html>
<?php
/*
 * fileopen.php
 * To be used with ext-server_opensave.js for SVG-edit
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */
	// Very minimal PHP file, all we do is Base64 encode the uploaded file and
	// return it to the editor

	$file = $_FILES['svg_file']['tmp_name'];

	$output = file_get_contents($file);

	$type = $_REQUEST['type'];

	$prefix = '';

	// Make Data URL prefix for import image
	if($type == 'import_img') {
		$info = getimagesize($file);
		$prefix = 'data:' . $info['mime'] . ';base64,';
	}
?>
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>

<!DOCTYPE html>
<?php
/*
 * fileopen.php
 * To be used with ext-server_opensave.js for SVG-edit
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */
	// Very minimal PHP file, all we do is Base64 encode the uploaded file and
	// return it to the editor

	$file = $_FILES['svg_file']['tmp_name'];

	$output = file_get_contents($file);

	$type = $_REQUEST['type'];

	$prefix = '';

	// Make Data URL prefix for import image
	if($type == 'import_img') {
		$info = getimagesize($file);
		$prefix = 'data:' . $info['mime'] . ';base64,';
	}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>
</head><body></body>
</html>

Add charset to HTML5 doc (and make more XHTML friendly)

git-svn-id: e52e7dec99011c9686d89c3d3c01e7ff0d333eee@2609 eee81c28-f429-11dd-99c0-75d572ba1ddd


<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;

class QualificationType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('verificationRequired', CheckboxType::class)
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Qualification'
        ));
    }
}

<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;

class QualificationType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('verificationRequired', CheckboxType::class, [
                'required' => false
            ])
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Qualification'
        ));
    }
}

Make verification required field optional


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Database Connections
	|--------------------------------------------------------------------------
	|
	| Here are each of the database connections setup for your application.
	| Of course, examples of configuring each database platform that is
	| supported by Laravel is shown below to make development simple.
	|
	|
	| All database work in Laravel is done through the PHP PDO facilities
	| so make sure you have the driver for your particular database of
	| choice installed on your machine before you begin development.
	|
	*/

	'connections' => array(

		'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => 'homestead',
			'username'  => 'homestead',
			'password'  => 'secret',
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

		'pgsql' => array(
			'driver'   => 'pgsql',
			'host'     => 'localhost',
			'database' => 'homestead',
			'username' => 'homestead',
			'password' => 'secret',
			'charset'  => 'utf8',
			'prefix'   => '',
			'schema'   => 'public',
		),

	),

);

<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Database Connections
	|--------------------------------------------------------------------------
	|
	| Here are each of the database connections setup for your application.
	| Of course, examples of configuring each database platform that is
	| supported by Laravel is shown below to make development simple.
	|
	|
	| All database work in Laravel is done through the PHP PDO facilities
	| so make sure you have the driver for your particular database of
	| choice installed on your machine before you begin development.
	|
	*/

	'connections' => array(

		'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => $_ENV['db_name'],
			'username'  => $_ENV['db_user'],
			'password'  => $_ENV['db_pass'],
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

		'pgsql' => array(
			'driver'   => 'pgsql',
			'host'     => 'localhost',
			'database' => 'homestead',
			'username' => 'homestead',
			'password' => 'secret',
			'charset'  => 'utf8',
			'prefix'   => '',
			'schema'   => 'public',
		),

	),

);

Read the local db config from .env.local.php


<?php

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

namespace Sylius\Component\Core\Context;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\CustomerInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ShopperContextInterface
{
    /**
     * @return ChannelInterface
     */
    public function getChannel();

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

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

    /**
     * @return CustomerInterface|null
     */
    public function getCustomer();
}

<?php

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

namespace Sylius\Component\Core\Context;

use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Currency\Context\CurrencyContextInterface;
use Sylius\Component\Customer\Context\CustomerContextInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ShopperContextInterface extends
    ChannelContextInterface,
    CurrencyContextInterface,
    LocaleContextInterface,
    CustomerContextInterface
{

}

[Core] Make shopper context extend nested context interfaces


<?php

final class PhutilMissingSymbolException extends Exception {

  public function __construct($symbol, $type, $reason) {
    $message = sprintf(
      'Failed to load symbol "%s" (of type "%s").'.
      "\n\n".
      '%s'.
      "\n\n".
      'If you are not a developer, this almost always means that a library '.
      'is out of date. For example, you may have upgraded "phabricator/" '.
      'without upgrading "arcanist/", or vice versa. It might also mean '.
      'that you need to restart Apache or PHP-FPM. Make sure all libraries '.
      'are up to date and all services have been restarted.'.
      "\n\n".
      'If you are a developer and this symbol was recently added or '.
      'moved, your library map may need to be rebuilt. You can rebuild '.
      'the map by running "arc liberate".'.
      "\n\n".
      'For more information, see: https://phurl.io/newclasses',
      $symbol,
      $type,
      $reason);

    parent::__construct($message);
  }

}

<?php

final class PhutilMissingSymbolException extends Exception {

  public function __construct($symbol, $type, $reason) {
    $message = sprintf(
      'Failed to load symbol "%s" (of type "%s").'.
      "\n\n".
      '%s'.
      "\n\n".
      'If you are not a developer, this almost always means that a library '.
      'is out of date. For example, you may have upgraded "phabricator/" '.
      'without upgrading "arcanist/", or vice versa. It might also mean '.
      'that you need to restart Apache or PHP-FPM. Make sure all libraries '.
      'are up to date and all services have been restarted.'.
      "\n\n".
      'If you are a developer and this symbol was recently added or '.
      'moved, your library map may need to be rebuilt. You can rebuild '.
      'the map by running "arc liberate".'.
      "\n\n".
      'For more information, see: https://phurl.io/u/newclasses',
      $symbol,
      $type,
      $reason);

    parent::__construct($message);
  }

}

Correct a mistaken Phurl link in the "missing symbol" exception

Summary: See PHI2022. This link is missing the `/u/` part and currently 404's.

Test Plan: Followed the new link, got documentation.

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


<?php

// this check prevents access to debug front controllers that are deployed by accident to production servers.
// feel free to remove this, extend it or make something more sophisticated.
if (!in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')))
{
  die('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');

$configuration = ProjectConfiguration::getApplicationConfiguration('qubit', 'dev', true);
sfContext::createInstance($configuration)->dispatch();

<?php

// this check prevents access to debug front controllers that are deployed by accident to production servers.
// feel free to remove this, extend it or make something more sophisticated.
//if (!in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')))
//{
//  die('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
//}

require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');

$configuration = ProjectConfiguration::getApplicationConfiguration('qubit', 'dev', true);
sfContext::createInstance($configuration)->dispatch();

Remove restrictions of dev mode for the minute, while we're developing on a VM


@if (is_string($item))

{{ $item }}

@else

            {{ $item['text'] }}
            @if (isset($item['label']))
                {{ $item['label'] }}
            @endif
            @if (isset($item['submenu']) && !isset($item['label']))

            @endif

        @if (isset($item['submenu']))

                @each('adminlte::partials.menu-item', $item['submenu'], 'item')

        @endif

@endif

@if (is_string($item))

{{ $item }}

@else

            {{ $item['text'] }}
            @if (isset($item['label']))
                {{ $item['label'] }}
            @elseif (isset($item['submenu']))

            @endif

        @if (isset($item['submenu']))

                @each('adminlte::partials.menu-item', $item['submenu'], 'item')

        @endif

@endif

Clean up if statement in menu item partial view


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

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

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

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
}

<?php

namespace Application;

class Module extends \ATP\Module
{
	protected $_moduleName = "Application";
}

Move base module class into ATP

Move base module class into ATP


	<form id="newuser" autocomplete="off">
		<input id="newusername" type="text"
			placeholder="<?php p($l->t('Username'))?>"
			autocomplete="off" autocapitalize="none" autocorrect="off" />
		<input
			type="password" id="newuserpassword"
			placeholder="<?php p($l->t('Password'))?>"
			autocomplete="off" autocapitalize="none" autocorrect="off" />
		<input id="newemail" type="text" style="display:none"
			   placeholder="<?php p($l->t('E-Mail'))?>"
			   autocomplete="off" autocapitalize="none" autocorrect="off" />

<div class="groupsListContainer multiselect button" data-placeholder="<?php p($l->t('Groups'))?>">

		<input type="submit" class="button" value="<?php p($l->t('Create'))?>" />
	</form>
	<?php if((bool)$_['recoveryAdminEnabled']): ?>

	<input id="recoveryPassword"
		   type="password"
		   placeholder="<?php p($l->t('Admin Recovery Password'))?>"
		   title="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"
		   alt="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"/>

	<?php endif; ?>

	<form id="newuser" autocomplete="off">
		<input id="newusername" type="text"
			placeholder="<?php p($l->t('Username'))?>"
			autocomplete="off" autocapitalize="none" autocorrect="off" />
		<input
			type="password" id="newuserpassword"
			placeholder="<?php p($l->t('Password'))?>"
			autocomplete="off" autocapitalize="none" autocorrect="off" />
		<input id="newemail" type="email" style="display:none"
			   placeholder="<?php p($l->t('E-Mail'))?>"
			   autocomplete="off" autocapitalize="none" autocorrect="off" />

<div class="groupsListContainer multiselect button" data-placeholder="<?php p($l->t('Groups'))?>">

		<input type="submit" class="button" value="<?php p($l->t('Create'))?>" />
	</form>
	<?php if((bool)$_['recoveryAdminEnabled']): ?>

	<input id="recoveryPassword"
		   type="password"
		   placeholder="<?php p($l->t('Admin Recovery Password'))?>"
		   title="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"
		   alt="<?php p($l->t('Enter the recovery password in order to recover the users files during password change'))?>"/>

	<?php endif; ?>

Correct input type for email

Correct input type for email

Correct input type for email


<?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.

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

class AddBuildIdToSoloScoreTokens extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('solo_score_tokens', function (Blueprint $table) {
            $table->unsignedMediumInteger('build_id')->null(true)->after('ruleset_id');
        });
    }

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

<?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.

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

class AddBuildIdToSoloScoreTokens extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('solo_score_tokens', function (Blueprint $table) {
            $table->unsignedMediumInteger('build_id')->nullable()->after('ruleset_id');
        });
    }

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

Fix incorrect nullable specification in migration


<?php

preg_match("#^/edit(/new|/[0-9a-z]+)?$#", $_SERVER['REQUEST_URI'], $matches);
if (count($matches) > 0) {
    require("edit.php");
    return true;
}

preg_match("#^/watch/([0-9a-z]+)#", $_SERVER['REQUEST_URI'], $matches);
if (count($matches) > 0 && strlen($matches[1]) < 30) {
    $_GET['m'] = $matches[1];
    require("watch.php");
    return true;
}

preg_match("#^(/|/explore(/[0-9a-zA-Z\\- ]+)?)$#", $_SERVER['REQUEST_URI'], $matches);
if ($_SERVER['REQUEST_URI'] == "/" || $_SERVER['REQUEST_URI'] == "" || count($matches) > 0) {
    require("explore.php");
    return true;
}

$development = strstr($_SERVER['SERVER_SOFTWARE'], " Development Server") != false;

if ($development)
    return false;
else
    require("404.html");

<?php

preg_match("#^/edit(/new|/[0-9a-z]+)?$#", $_SERVER['REQUEST_URI'], $matches);
if (count($matches) > 0) {
    require("edit.php");
    return true;
}

preg_match("#^/watch/([0-9a-z]+)#", $_SERVER['REQUEST_URI'], $matches);
if (count($matches) > 0 && strlen($matches[1]) < 30) {
    $_GET['m'] = $matches[1];
    require("watch.php");
    return true;
}

preg_match("#^/explore/([0-9a-zA-Z\\- ]+)?$#", $_SERVER['REQUEST_URI'], $matches);
if ($_SERVER['REQUEST_URI'] == "/" || $_SERVER['REQUEST_URI'] == ""  ||
    $_SERVER['REQUEST_URI'] == "/explore" || count($matches) > 0) {
    if (count($matches) > 1 && $matches[1] != "featured")
        $_GET['p'] = $matches[1];
    else
        $_GET['p'] = "";
    require("explore.php");
    return true;
}

$development = strstr($_SERVER['SERVER_SOFTWARE'], " Development Server") != false;

if ($development)
    return false;
else
    require("404.html");

Change the way the explore section is routed


<?php

namespace CrystalPlanet\Redshift\EventLoop;

class EventLoop
{
    /**
     * @var array
     */
    private $queue = [];

    /**
     * Adds a new task to the queue.
     *
     * @param callable $callback
     * @param mixed ...$args Arguments to be supplied to the $callback
     *                       at the time of execution.
     */
    public function put(callable $callback, ...$args)
    {
        array_push($this->queue, new Task($callback, $args));
    }

    /**
     * Returns the next task in the queue.
     *
     * @return Task
     */
    public function take()
    {
        return array_shift($this->queue);
    }

    /**
     * Starts the event loop.
     * It will run until there are no more tasks sheduled for execution.
     *
     * If a task was blocked/interrupted,
     * it is put back at the end of the queue.
     */
    public function run()
    {
        while (!$this->isEmpty()) {
            $task = $this->take();

            $task->run();

            if ($task->valid()) {
                array_push($this->queue, $task);
            }
        }
    }

    /**
     * Checks if there are no more tasks in the queue.
     *
     * @return boolean
     */
    private function isEmpty()
    {
        return empty($this->queue);
    }
}

<?php

namespace CrystalPlanet\Redshift\EventLoop;

class EventLoop
{
    /**
     * @var array
     */
    private $queue = [];

    /**
     * Adds a new task to the queue.
     *
     * @param callable $callback
     * @param mixed ...$args Arguments to be supplied to the $callback
     *                       at the time of execution.
     */
    public function put(callable $callback, ...$args)
    {
        array_push($this->queue, new Task($callback, ...$args));
    }

    /**
     * Returns the next task in the queue.
     *
     * @return Task
     */
    public function take()
    {
        return array_shift($this->queue);
    }

    /**
     * Starts the event loop.
     * It will run until there are no more tasks sheduled for execution.
     *
     * If a task was blocked/interrupted,
     * it is put back at the end of the queue.
     */
    public function run()
    {
        while (!$this->isEmpty()) {
            $task = $this->take();

            $task->run();

            if ($task->valid()) {
                array_push($this->queue, $task);
            }
        }
    }

    /**
     * Checks if there are no more tasks in the queue.
     *
     * @return boolean
     */
    private function isEmpty()
    {
        return empty($this->queue);
    }
}

Fix passing arguments to async() blocks

Fix passing arguments to async() blocks


<?php

namespace DoctrineExtensions\Query\Mysql;

use Doctrine\ORM\Query\Lexer,
    Doctrine\ORM\Query\QueryException;

/**
 * @author Vas N <phpvas@gmail.com>
 */
class DateSub extends DateAdd
{
    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        $unit = strtoupper(is_string($this->unit) ? $this->unit : $this->unit->value);

        if (!in_array($unit, self::$allowedUnits)) {
            throw QueryException::semanticalError('DATE_SUB() does not support unit "' . $unit . '".');
        }

        return 'DATE_SUB(' .
            $this->firstDateExpression->dispatch($sqlWalker) . ', INTERVAL ' .
            $this->intervalExpression->dispatch($sqlWalker) . ' ' . $unit .
        ')';
    }
}

<?php

namespace DoctrineExtensions\Query\Mysql;

use Doctrine\ORM\Query\QueryException;

/**
 * @author Vas N <phpvas@gmail.com>
 */
class DateSub extends DateAdd
{
    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        $unit = strtoupper(is_string($this->unit) ? $this->unit : $this->unit->value);

        if (!in_array($unit, self::$allowedUnits)) {
            throw QueryException::semanticalError('DATE_SUB() does not support unit "' . $unit . '".');
        }

        return 'DATE_SUB(' .
            $this->firstDateExpression->dispatch($sqlWalker) . ', INTERVAL ' .
            $this->intervalExpression->dispatch($sqlWalker) . ' ' . $unit .
        ')';
    }
}

UPDATE - Unused use class removed.

UPDATE - Unused use class removed.