<?php

/*
 * This file is part of Laravel Core.
 *
 * (c) Graham Campbell <graham@alt-three.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GrahamCampbell\Tests\Core;

use GrahamCampbell\Core\CoreServiceProvider;
use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test case class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
abstract class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return CoreServiceProvider::class;
    }
}

<?php

/*
 * This file is part of Laravel Core.
 *
 * (c) Graham Campbell <graham@alt-three.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GrahamCampbell\Tests\Core;

use GrahamCampbell\Core\CoreServiceProvider;
use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test case class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
abstract class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Create an empty .env file for us to use.
     *
     * @before
     */
    public function createEnvFile()
    {
        file_put_contents($this->app->environmentFilePath(), "APP_KEY=SomeRandomString\n");
    }

    /**
     * Delete our .env file after use.
     *
     * @after
     */
    {
        unlink($this->app->environmentFilePath());
    }

    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return CoreServiceProvider::class;
    }
}

Deal with the .env file

Deal with the .env file


<?php
/**
 * @author Jaisen Mathai <jaisen@jmathai.com>
 * @copyright Copyright 2015, Jaisen Mathai
 */

namespace S3BucketStreamZipTest;

use S3BucketStreamZip\S3BucketStreamZip;
use PHPUnit_Framework_TestCase;

class S3BucketStreamZipTest extends PHPUnit_Framework_TestCase
{
  /**
  * @expectedException \S3BucketStreamZip\Exception\InvalidParameterException
  */
  public function testInvalidParamsToConstructorKey()
  {
    $client = new S3BucketStreamZip(array(), array());
  }

  /**
  * @expectedException \S3BucketStreamZip\Exception\InvalidParameterException
  */
  public function testInvalidParamsToConstructorSecret()
  {
    $client = new S3BucketStreamZip(array('key' => 'foo'), array());
  }

  /**
  * @expectedException \S3BucketStreamZip\Exception\InvalidParameterException
  */
  public function testInvalidParamsToConstructorBucket()
  {
    $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array());
  }

  public function testValidParamsToConstructor()
  {
    $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array('Bucket' => 'foobar'));
  }
}

<?php
/**
 * @author Jaisen Mathai <jaisen@jmathai.com>
 * @copyright Copyright 2015, Jaisen Mathai
 */

namespace JMathai\S3BucketStreamZipTest;

use JMathai\S3BucketStreamZip\S3BucketStreamZip;
use PHPUnit_Framework_TestCase;

class S3BucketStreamZipTest extends PHPUnit_Framework_TestCase
{
  /**
  * @expectedException \JMathai\S3BucketStreamZip\Exception\InvalidParameterException
  */
  public function testInvalidParamsToConstructorKey()
  {
    $client = new S3BucketStreamZip(array(), array());
  }

  /**
  * @expectedException \JMathai\S3BucketStreamZip\Exception\InvalidParameterException
  */
  public function testInvalidParamsToConstructorSecret()
  {
    $client = new S3BucketStreamZip(array('key' => 'foo'), array());
  }

  /**
  * @expectedException \JMathai\S3BucketStreamZip\Exception\InvalidParameterException
  */
  public function testInvalidParamsToConstructorBucket()
  {
    $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array());
  }

  public function testValidParamsToConstructor()
  {
    $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array('Bucket' => 'foobar'));
  }
}

Fix unit test by adding new namespace

Fix unit test by adding new namespace


<?php
namespace verbb\feedme\fields;

use verbb\feedme\base\Field;
use verbb\feedme\base\FieldInterface;

use Craft;

use Cake\Utility\Hash;

class DefaultField extends Field implements FieldInterface
{
    // Properties
    // =========================================================================

    public static $name = 'Default';
    public static $class = 'craft\fields\Default';

    // Templates
    // =========================================================================

    public function getMappingTemplate()
    {
        return 'feed-me/_includes/fields/default';
    }

    // Public Methods
    // =========================================================================

    public function parseField()
    {
        return $this->fetchValue();
    }
}

<?php
namespace verbb\feedme\fields;

use verbb\feedme\base\Field;
use verbb\feedme\base\FieldInterface;

use Craft;

use Cake\Utility\Hash;

class DefaultField extends Field implements FieldInterface
{
    // Properties
    // =========================================================================

    public static $name = 'Default';
    public static $class = 'craft\fields\Default';

    // Templates
    // =========================================================================

    public function getMappingTemplate()
    {
        return 'feed-me/_includes/fields/default';
    }

    // Public Methods
    // =========================================================================

    public function parseField()
    {
        $value = $this->fetchValue();

        // Default fields expect strings, if its an array for an odd reason, serialise it
        if (is_array($value)) {
            if (empty($value)) {
                $value = '';
            } else {
                $value = json_encode($value);
            }
        }

        return $value;
    }
}

Add array-handling to default fields, preventing errors


<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) 2013 PMG Worldwide
 *
 * @package     PMGQueue
 * @copyright   2013 PMG Worldwide
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace PMG\Queue\Test;

use PMG\Queue\Producer;

class ProducerTest extends \PHPUnit_Framework_TestCase
{
    public function testSetGetAdapter()
    {
        $adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');

        $producer = new Producer($adapter);

        $this->assertSame($producer->getAdapter(), $adapter);

        $new_adapt = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');

        $producer->setAdapter($new_adapt);

        $this->assertSame($producer->getAdapter(), $new_adapt);
    }

    public function testSuccessfulPutReturnsTrue()
    {
        $adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');

        $adapter->expects($this->once())
            ->method('put')
            ->with('say_hello', array('name' => 'Chris'))
            ->will($this->returnValue(true));

        $producer = new Producer($adapter);

        $this->assertTrue($producer->addJob('say_hello', array('name' => 'Chris')));
    }
}

<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) 2013 PMG Worldwide
 *
 * @package     PMGQueue
 * @copyright   2013 PMG Worldwide
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace PMG\Queue\Test;

use PMG\Queue\Producer;

class ProducerTest extends \PHPUnit_Framework_TestCase
{
    public function testSetGetAdapter()
    {
        $adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');

        $producer = new Producer($adapter);

        $this->assertSame($producer->getAdapter(), $adapter);

        $new_adapt = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');

        $producer->setAdapter($new_adapt);

        $this->assertSame($producer->getAdapter(), $new_adapt);
    }

    public function testSuccessfulPutReturnsTrue()
    {
        $adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');

        $adapter->expects($this->once())
            ->method('put')
            ->with('say_hello', array('name' => 'Chris'), 1000, 10)
            ->will($this->returnValue(true));

        $producer = new Producer($adapter);

        $this->assertTrue($producer->addJob('say_hello', array('name' => 'Chris'), 1000, 10));
    }
}

Make sure delay/ttr are passed to the adapter


<?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
/**
 * Render the content of the metabox in the admin post editing form.
 */
$post_id = $GLOBALS['post']->ID;
$parent_id = get_post_meta($post_id, '_persistfork-parent', true);
if ($parent_id): ?>
    Parent:
    <a href="<?= get_permalink($parent_id) ?>">
        <?= get_post($parent_id)->post_title ?>
    </a>
<?php endif ?>

<?php
/**
 * Render the content of the metabox in the admin post editing form.
 */
$post_id = $GLOBALS['post']->ID;
$parent_id = get_post_meta($post_id, '_persistfork-parent', true);
$families = wp_get_object_terms($post_id, 'family');
$family = reset($families);
if ($parent_id): ?>
    Parent:
    <a href="<?= get_permalink($parent_id) ?>">
        <?= get_post($parent_id)->post_title ?>

    <?php if ($family): ?>
        Family:
        <a href="<?= home_url() . '/' . 'index.php/family/' . $family->slug . '/' ?>">
            <?= $family->name ?>

    <?php endif ?>
<?php else: ?>
    No parent
    <?php if ($family): ?>
        (root of family)
    <?php else: ?>
        (not a fork)
    <?php endif ?>
<?php endif ?>

Make admin metabox more informative

Make admin metabox more informative


<?php

/*
 * This file is part of the kompakt/mediameister package.
 *
 * (c) Christian Hoegl <chrigu@sirprize.me>
 *
 */

namespace Kompakt\Mediameister\EventDispatcher;

use Kompakt\Mediameister\EventDispatcher\EventAdapterInterface;

interface EventInterface
{
    public function setAdapter(EventAdapterInterface $adapter);
    public function isPropagationStopped();
    public function stopPropagation($applyToAdapter = true);
}

<?php

/*
 * This file is part of the kompakt/mediameister package.
 *
 * (c) Christian Hoegl <chrigu@sirprize.me>
 *
 */

namespace Kompakt\Mediameister\EventDispatcher;

use Kompakt\Mediameister\EventDispatcher\EventAdapterInterface;

interface EventInterface
{
    public function setAdapter(EventAdapterInterface $adapter);
    public function isPropagationStopped();
    public function stopPropagation($avoidCircularDependency = false);
}

Change default also in interface

Change default also in interface


<?php

use Symfony\Component\HttpFoundation\Response;
use App\Http\Response\MessagePackResponse;

class MessagePackResponseTest extends TestCase
{
    /**
     * Message pack response
     *
     * @var \App\Http\Response\MessagePackResponse
     */
    protected $response;

    /**
     * setUp
     *
     * @return void
     */
    public function setUp()
    {
        $this->response = new MessagePackResponse([
            'hello' => 'lumtify'
        ]);
    }

    /**
     * Test Extends Response
     *
     * @return void
     */
    public function testExtendsResponse()
    {
        $this->assertTrue($this->response instanceof Response);
    }

    /**
     * Test setData.
     *
     * @return void
     */
    public function testSetData()
    {
        $data = $this->response->setData([
            'a' => 'ha'
        ]);

        $this->assertEquals($data, $this->response->getContent()->content);
    }

    /**
     * Test getData.
     *
     * @return void
     */
    public function testGetData()
    {
        $data = $this->response->getData();

        $this->assertEquals([
            'hello' => 'lumtify'
        ], $data);
    }
}

<?php

use Symfony\Component\HttpFoundation\Response;
use App\Http\Response\MessagePackResponse;

class MessagePackResponseTest extends TestCase
{
    /**
     * Message pack response
     *
     * @var \App\Http\Response\MessagePackResponse
     */
    protected $response;

    /**
     * setUp
     *
     * @return void
     */
    public function setUp()
    {
        $this->response = new MessagePackResponse([
            'hello' => 'lumtify'
        ]);
    }

    /**
     * Test Extends Response
     *
     * @return void
     */
    public function testExtendsResponse()
    {
        $this->assertTrue($this->response instanceof Response);
    }

    /**
     * Test setData.
     *
     * @return void
     */
    public function testSetData()
    {
        $origin = $this->response->getContent();
        $data = $this->response->setData([
            'a' => 'ha'
        ]);

        $this->assertNotEquals($data->getContent(), $origin);
    }

    /**
     * Test getData.
     *
     * @return void
     */
    public function testGetData()
    {
        $data = $this->response->getData();

        $this->assertEquals([
            'hello' => 'lumtify'
        ], $data);
    }
}

Change setData test Let setData assert not equals to origin content.


<?php use_helper('Form', 'Validation', 'Decorator'); ?>

<?php decorate_start('SideTabs', ['active' => 'spacedrepetition']) ?>

Spaced Repetition Settings

    See <?= link_to('documentation', '@learnmore#srs') ?> for Kanji Koohii's implementation of the Leitner SRS.
  </p

    Also see <?= link_to('tips for rating cards', '@learnmore#faq') ?> in the F.A.Q.

  <?php echo form_errors() ?>
  <?php echo form_tag('account/spacedrepetition') ?>

      <?php echo submit_tag('Save changes', ['class' => 'ko-Btn ko-Btn--success']) ?>

  </form>

<?php decorate_end() ?>

<?php
  kk_globals_put('ACCOUNT_SRS', $srsSettings);

<?php use_helper('Form', 'Validation', 'Decorator'); ?>

<?php decorate_start('SideTabs', ['active' => 'spacedrepetition']); ?>

Spaced Repetition Settings

    Learn more about Koohii’s <?= link_to('Leitner SRS implementation', '@learnmore#srs'); ?> in the documentation.

    Also see the tips in the <?= link_to('Card Ratings', '@learnmore#rating'); ?> section.

  <?= form_errors(); ?>
  <?= form_tag('account/spacedrepetition'); ?>

      <?= submit_tag('Save changes', ['class' => 'ko-Btn ko-Btn--success']); ?>

  </form>

<?php decorate_end(); ?>

<?php
  kk_globals_put('ACCOUNT_SRS', $srsSettings);

Update intro paragraph & help links in SRS settings page, minor formatting


<?php
namespace wcf\acp\page;
use wcf\data\devtools\project\DevtoolsProjectList;
use wcf\page\AbstractPage;
use wcf\system\WCF;

/**
 * Shows a list of devtools projects.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Acp\Page
 * @since	3.1
 */
class DevtoolsProjectListPage extends AbstractPage {
	/**
	 * @inheritDoc
	 */
	public $activeMenuItem = 'wcf.acp.menu.link.devtools.project.list';

	/**
	 * @inheritDoc
	 */
	public $neededModules = ['ENABLE_DEVELOPER_TOOLS'];

	/**
	 * @inheritDoc
	 */
	public $neededPermissions = ['admin.configuration.package.canInstallPackage'];

	/**
	 * @var DevtoolsProjectList
	 */
	public $objectList;

	/**
	 * @inheritDoc
	 */
	public function readData() {
		parent::readData();

		$this->objectList = new DevtoolsProjectList();
		$this->objectList->readObjects();
	}

	/**
	 * @inheritDoc
	 */
	public function assignVariables() {
		parent::assignVariables();

		WCF::getTPL()->assign([
			'objects' => $this->objectList
		]);
	}
}

<?php
namespace wcf\acp\page;
use wcf\data\devtools\project\DevtoolsProjectList;
use wcf\page\MultipleLinkPage;

/**
 * Shows a list of devtools projects.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Acp\Page
 * @since	3.1
 */
class DevtoolsProjectListPage extends MultipleLinkPage {
	/**
	 * @inheritDoc
	 */
	public $activeMenuItem = 'wcf.acp.menu.link.devtools.project.list';

	/**
	 * @inheritDoc
	 */
	public $itemsPerPage = PHP_INT_MAX;

	/**
	 * @inheritDoc
	 */
	public $objectListClassName = DevtoolsProjectList::class;

	/**
	 * @inheritDoc
	 */
	public $neededModules = ['ENABLE_DEVELOPER_TOOLS'];

	/**
	 * @inheritDoc
	 */
	public $neededPermissions = ['admin.configuration.package.canInstallPackage'];

	/**
	 * @var DevtoolsProjectList
	 */
	public $objectList;
}

Fix undefined `$items` variable in `devtoolsProjectList.tpl`

By simply extending the `MultipleLinkPage` class, the `$items` variable
is automatically set.

See #2354


<?php

namespace Williamson\TPLinkSmartplug\tests;

use ReflectionClass;
use ReflectionMethod;
use Williamson\TPLinkSmartplug\TPLinkCommand;

class TPLinkCommandTest extends \PHPUnit_Framework_TestCase
{

    /** @test checks all commands returned are an array */
    public function it_checks_all_commands_returned_are_an_array()
    {
        $reflector = new ReflectionClass(TPLinkCommand::class);
        $methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);

        foreach ($methods as $method) {
            if ($method->getNumberOfParameters() == 0) {
                $name = $method->getName();
                $this->assertInternalType('array', TPLinkCommand::$name());
            }
        }
    }

    //TODO Methods that require a parameter

}

<?php

namespace Williamson\TPLinkSmartplug\tests;

use Illuminate\Support\Collection;
use ReflectionClass;
use ReflectionMethod;
use Williamson\TPLinkSmartplug\TPLinkCommand;

class TPLinkCommandTest extends \PHPUnit_Framework_TestCase
{

    /** @test checks all commands returned are an array */
    public function it_checks_all_commands_returned_are_an_array()
    {
        $reflector = new ReflectionClass(TPLinkCommand::class);
        $methods = collect($reflector->getMethods(ReflectionMethod::IS_PUBLIC));

        $methods
            ->filter(function (ReflectionMethod $method) {
                return $method->getNumberOfParameters() === 0;
            })
            ->each(function (ReflectionMethod $method) {
                $name = $method->getName();
                $this->assertInternalType('array', TPLinkCommand::$name());
            });
    }

}

Use some collection magic in the tests.

Use some collection magic in the tests.


<?php

namespace Alchemy\RestBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class EncodeJsonResponseListener implements EventSubscriberInterface
{

    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        if (! $event->getRequest()->attributes->get('_rest[encode_response]', false, true)) {
            return;
        }

        $result = $event->getControllerResult();

        if (! is_array($result)) {
            throw new \LogicException('Invalid controller result: array was expected.');
        }

        $event->setResponse(new JsonResponse($result));
    }

    public static function getSubscribedEvents()
    {
        return array(KernelEvents::VIEW => 'onKernelView');
    }
}

<?php

namespace Alchemy\RestBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class EncodeJsonResponseListener implements EventSubscriberInterface
{

    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        if (! $event->getRequest()->attributes->get('_rest[encode_response]', false, true)) {
            return;
        }

        $result = $event->getControllerResult();

        if (! $result instanceof Response) {
            if (!is_array($result)) {
                throw new \LogicException('Invalid controller result: array was expected.');
            }

            $result = new JsonResponse($result);
        }

        $event->setResponse($result);
    }

    public static function getSubscribedEvents()
    {
        return array(KernelEvents::VIEW => 'onKernelView');
    }
}

Set controller result as response if already a response


<?php

class SPM_ShopyMind_Action_GetCategory implements SPM_ShopyMind_Interface_Action
{
    private $scope;
    private $categoryId;
    private $Category;
    private $Formatter;

    public function __construct(SPM_ShopyMind_Model_Scope $scope, $categoryId)
    {
        $this->Category = Mage::getModel('catalog/category');
        $this->Formatter = new SPM_ShopyMind_DataMapper_Category();

        $this->categoryId = $categoryId;
        $this->scope = $scope;
    }

    public function process($formatData = true)
    {
        $storeIds = $this->scope->storeIds();

        ShopymindClient_Callback::startStoreEmulationByStoreId($storeIds[0]);
        $collection = $this->Category->getCollection();
        $this->scope->restrictCategoryCollection($collection);
        $collection->addAttributeToFilter('entity_id', array('eq' => $this->categoryId))
            ->addAttributeToSelect('*');

        $category = $collection->getFirstItem();

        if (is_null($this->categoryId) || !$category->getId()) {
            return array();
        }

        $locale = $this->scope->getConfig('general/locale/code');
        $category->setData('locale', (string) $locale);
        if ($formatData) {
            $data = $this->Formatter->format($category);
        } else {
            $data = $category;
        }

        ShopymindClient_Callback::stopStoreEmulation();

        return $data;
    }
}

<?php

class SPM_ShopyMind_Action_GetCategory implements SPM_ShopyMind_Interface_Action
{
    private $scope;
    private $categoryId;
    private $Category;
    private $Formatter;

    public function __construct(SPM_ShopyMind_Model_Scope $scope, $categoryId)
    {
        $this->Category = Mage::getModel('catalog/category');
        $this->Formatter = new SPM_ShopyMind_DataMapper_Category();

        $this->categoryId = $categoryId;
        $this->scope = $scope;
    }

    public function process($formatData = true)
    {
        $storeIds = $this->scope->storeIds();
        /** @var  $appEmulation Mage_Core_Model_App_Emulation */
        $appEmulation = Mage::getSingleton('core/app_emulation');
        $emulatedEnvironment = $appEmulation->startEnvironmentEmulation($storeIds[0]);
        $collection = $this->Category->getCollection();
        $this->scope->restrictCategoryCollection($collection);
        $collection->addAttributeToFilter('entity_id', array('eq' => $this->categoryId))
            ->addAttributeToSelect('*');

        $category = $collection->getFirstItem();

        if (is_null($this->categoryId) || !$category->getId()) {
            return array();
        }

        $locale = $this->scope->getConfig('general/locale/code');
        $category->setData('locale', (string) $locale);
        if ($formatData) {
            $data = $this->Formatter->format($category);
        } else {
            $data = $category;
        }

        $appEmulation->stopEnvironmentEmulation($emulatedEnvironment);
        return $data;
    }

}

Use directly magento classes to do store emulation.


<?php

namespace Zap\Test;

class Zapv2Test extends \PHPUnit_Framework_TestCase{

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

        $this->proxy = "tcp://localhost:8090";
        $this->target_url = "https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project";
    }

    /**
     * @test
     */
    public function testVersion()
    {
        $zap = new \Zap\Zapv2($this->proxy);
        $version = @$zap->core->version();
        $this->assertSame("2.3.1", $version);
    }

    /**
     * @test
     */
    public function testStatus()
    {
        $zap = new \Zap\Zapv2($this->proxy);
        $res = $zap->statusCode($this->target_url);
        $this->assertSame("200", $res);
    }
}

<?php

namespace Zap\Test;

class Zapv2Test extends \PHPUnit_Framework_TestCase{

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

        $this->proxy = "tcp://localhost:8090";
        $this->target_url = "https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project";
    }

    /**
     * @test
     */
    public function testVersion()
    {
        $zap = new \Zap\Zapv2($this->proxy);
        $version = @$zap->core->version();
        $this->assertSame("2.3.1", $version);
    }

    /**
     * @test
     */
    public function testStatusCode()
    {
        $zap = new \Zap\Zapv2($this->proxy);
        $res = $zap->statusCode($this->target_url);
        $this->assertSame("200", $res);
    }
}

Improve the method name testStatus to testStatusCode


<?php

namespace ProophTest\ServiceBus\Message\ZeroMQ;

use Prooph\ServiceBus\Message\ZeroMQ\ZeroMQSocket;

class ZeroMQSocketTest extends \PHPUnit_Framework_TestCase
{
    /** @var ZeroMQSocket */
    private $zmqClient;

    /** @var \ZMQSocket */
    private $socket;

    /** @var string */
    private $dsn = 'tcp://localhost:5555';

    /** @var string */
    private $storage = __DIR__ . '/zmq-out.log';

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

        $this->socket = new \ZMQSocket(new \ZMQContext, \ZMQ::SOCKET_PUSH);
        $this->zmqClient = new ZeroMQSocket($this->socket, $this->dsn);
    }

    public function tearDown()
    {
        $this->socket->disconnect($this->dsn);
    }

    /**
     * @test
     */
    public function it_sends_message()
    {
        @unlink($this->storage);
        $this->zmqClient->send($message = 'testing-123');

        $contents = trim(file_get_contents($this->storage));

        $this->assertEquals($message, $contents);
    }
}

<?php

namespace ProophTest\ServiceBus\Message\ZeroMQ;

use Prooph\ServiceBus\Message\ZeroMQ\ZeroMQSocket;

class ZeroMQSocketTest extends \PHPUnit_Framework_TestCase
{
    /** @var ZeroMQSocket */
    private $zmqClient;

    /** @var \ZMQSocket */
    private $socket;

    /** @var string */
    private $dsn = 'tcp://localhost:5555';

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

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

        $this->storage = __DIR__ . '/zmq-out.log';
        $this->socket = new \ZMQSocket(new \ZMQContext, \ZMQ::SOCKET_PUSH);
        $this->zmqClient = new ZeroMQSocket($this->socket, $this->dsn);
    }

    public function tearDown()
    {
        $this->socket->disconnect($this->dsn);
    }

    /**
     * @test
     */
    public function it_sends_message()
    {
        @unlink($this->storage);
        $this->zmqClient->send($message = 'testing-123');

        $contents = trim(file_get_contents($this->storage));

        $this->assertEquals($message, $contents);
    }
}

Fix code style errors also support for older PHP (5.5) where default property values cannot contain expressions.


<?php

namespace Project\AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PromotionRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PromotionRepository extends EntityRepository
{
    /**
     * Create a json of a promotion.
     *
     * @param int $promotion id of the promotion to convert to a json.
     * @return string JSON that contain the element of a promotion.
     */
    public function toJson($promotion)
    {
        $qb = $this->createQueryBuilder('p');

        $qb->where('p.id = :id')
            ->setParameter('id', $promotion)
            ->andWhere('p.archive IS NULL')
            ->setMaxResults(1);

        $promotion = $qb->getQuery()
            ->getSingleResult();

        $jsonData = array(
                          'promotion' => $promotion->__toString(),
                          'formation' => $promotion->getFormation()->__toString(),
                          'start'     => $promotion->getStartDate()->format('Y-m-d H:i:s'),
                          'end'       => $promotion->getEndDate()->format('Y-m-d H:i:s')
                          );

        return json_encode($jsonData);
    }
}

<?php

namespace Project\AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PromotionRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PromotionRepository extends EntityRepository
{
    /**
     * Create a json of a promotion.
     *
     * @param int $promotion id of the promotion to convert to a json.
     * @return string JSON that contain the element of a promotion.
     */
    public function toJson($promotion)
    {
        $jsonDate = array();

        $qb = $this->createQueryBuilder('p');

        $qb->where('p.id = :id')
            ->setParameter('id', $promotion)
            ->andWhere('p.archive IS NULL')
            ->setMaxResults(1);

        $promotion = $qb->getQuery()
            ->getSingleResult();

        $jsonData[] = array(
                            'promotion' => $promotion->__toString(),
                            'formation' => $promotion->getFormation()->__toString(),
                            'start'     => $promotion->getStartDate()->format('Y-m-d H:i:s'),
                            'end'       => $promotion->getEndDate()->format('Y-m-d H:i:s')
                            );

        return json_encode($jsonData);
    }
}

Include data in an array in Promotion archive method


<?php

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains('Welcome to Symfony', $crawler->filter('#container h1')->text());
    }
}

<?php

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ApiControllerTest extends WebTestCase
{
    public function testGame()
    {
        $id = $this->doTestNewGame();
        $this->doTestGuess($id);
    }

    public function doTestNewGame()
    {
        $client = static::createClient();

        $container = $client->getContainer();
        $route = $container->get('router')->generate('game');

        // POST to /game
        $client->request('POST', $route);

        // Expect a 201 CREATED status code
        $this->assertEquals(201, $client->getResponse()->getStatusCode());

        $content = $client->getResponse()->getContent();
        // Should not contain an error, but should contain at least data and id
        $this->assertNotContains('error', $content);
        $this->assertContains('data', $content);
        $this->assertContains('id', $content);

        // Get the new game ID
        $data = json_decode($content, true);

        return $data['data']['id'];
    }

    public function doTestGuess($id)
    {
        $client = static::createClient();

        $container = $client->getContainer();
        $route = $container->get('router')->generate('guess', ['id' => $id]);

        // PUT to /game/{id} with a JSON body containing a letter
        $client->request(
            'PUT',
            $route,
            [],
            [],
            ['CONTENT_TYPE' => 'application/json'],
            '{ "letter": "a" }'
        );

        // Expect a 200 OK status code
        $this->assertEquals(200, $client->getResponse()->getStatusCode());

        $content = $client->getResponse()->getContent();
        // Should not contain an error, but should contain at least data, word, tries_left and status
        $this->assertNotContains('error', $content);
        $this->assertContains('data', $content);
        $this->assertContains('word', $content);
        $this->assertContains('tries_left', $content);
        $this->assertContains('status', $content);
    }
}

Add functional tests for the API controller


<?php

return [
    'keys.openpgp.org',
    'keys.fedoraproject.org',
    'keyserver.ubuntu.com',
    'hkps.pool.sks-keyservers.net'
];

<?php

return [
    'keys.openpgp.org',
    'keyserver.ubuntu.com',
    'hkps.pool.sks-keyservers.net'
];

Remove keys.fedoraproject.org from server list


<?php

/*
 * This file is part of the Panda framework Ui component.
 *
 * (c) Ioannis Papikas <papikas.ioan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Panda\Ui\Helpers;

use DOMNode;
use Panda\Ui\Contracts\Handlers\HTMLHandlerInterface;

/**
 * Class TooltipHelper
 *
 * @package Panda\Ui\Helpers
 *
 * @version 0.1
 */
class TooltipHelper
{
    /**
     * Set tooltip handler attribute
     *
     * @param HTMLHandlerInterface $HTMLHandler
     * @param DOMNode              $HTMLElement
     * @param string               $content
     * @param int                  $delay
     */
    public static function set(HTMLHandlerInterface $HTMLHandler, DOMNode $HTMLElement, $content, $delay = 0)
    {
        // Set tooltip attribute array
        $tooltip = [];
        $tooltip['content'] = $content;
        $tooltip['delay'] = $delay;

        $HTMLHandler->data($HTMLElement, 'ui-tooltip', $tooltip);
    }
}

<?php

/*
 * This file is part of the Panda framework Ui component.
 *
 * (c) Ioannis Papikas <papikas.ioan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Panda\Ui\Helpers;

use DOMNode;
use Panda\Ui\Contracts\Handlers\HTMLHandlerInterface;

/**
 * Class TooltipHelper
 *
 * @package Panda\Ui\Helpers
 *
 * @version 0.1
 */
class TooltipHelper
{
    /**
     * Set tooltip handler attribute
     *
     * @param HTMLHandlerInterface $HTMLHandler
     * @param DOMNode              $HTMLElement
     * @param string               $content
     * @param int                  $delay
     * @param string               $position
     */
    public static function set(HTMLHandlerInterface $HTMLHandler, DOMNode $HTMLElement, $content, $delay = 0, $position = '')
    {
        // Set tooltip attribute array
        $tooltip = [
            'content' => $content,
            'delay' => $delay,
            'position' => $position
        ];

        $HTMLHandler->data($HTMLElement, 'ui-tooltip', $tooltip);
    }
}

Include position option for tooltip

Include position option for tooltip


<?php

namespace Oro\Bundle\IntegrationBundle\Exception;

class SoapConnectionException extends TransportException
{
    /**
     * @param string     $response
     * @param \Exception $exception
     * @param string     $request
     * @param string     $headers
     *
     * @return static
     */
    public static function createFromResponse($response, \Exception $exception = null, $request = '', $headers = '')
    {
        $exceptionMessage = null !== $exception ? $exception->getMessage() : '';
        $exceptionCode    = null !== $exception ? $exception->getCode() : 0;
        $code             = !empty($headers['code']) ? $headers['code'] : 'unknown';

        $message = PHP_EOL;
        $message .= str_pad('[message]', 20, ' ', STR_PAD_RIGHT) . $exceptionMessage . PHP_EOL;
        $message .= str_pad('[request]', 20, ' ', STR_PAD_RIGHT) . $request . PHP_EOL;
        $message .= str_pad('[response]', 20, ' ', STR_PAD_RIGHT) . $response . PHP_EOL;
        $message .= str_pad('[code]', 20, ' ', STR_PAD_RIGHT) . $code . PHP_EOL;
        $message .= PHP_EOL;

        $exception = new static($message, $exceptionCode, $exception);
        $exception->setFaultCode($code);

        return $exception;
    }
}

<?php

namespace Oro\Bundle\IntegrationBundle\Exception;

class SoapConnectionException extends TransportException
{
    /**
     * @param string     $response
     * @param \Exception $exception
     * @param string     $request
     * @param string     $headers
     *
     * @return static
     */
    public static function createFromResponse($response, \Exception $exception = null, $request = '', $headers = '')
    {
        $exceptionMessage = null !== $exception ? $exception->getMessage() : '';
        $exceptionCode    = null !== $exception ? $exception->getCode() : 0;
        $code             = !empty($headers['code']) ? $headers['code'] : 'unknown';

        $message = PHP_EOL;
        $message .= str_pad('[message]', 20, ' ', STR_PAD_RIGHT) . $exceptionMessage . PHP_EOL;
        $message .= str_pad('[request]', 20, ' ', STR_PAD_RIGHT) . $request . PHP_EOL;
        $message .= str_pad('[response]', 20, ' ', STR_PAD_RIGHT) . $response . PHP_EOL;
        $message .= str_pad('[code]', 20, ' ', STR_PAD_RIGHT) . $code . PHP_EOL;
        $message .= PHP_EOL;

        $newException = new static($message, $exceptionCode, $exception);
        if ($exception instanceof \SoapFault) {
            $newException->setFaultCode($exception->faultcode);
        }

        return $newException;
    }
}

CRM-2726: Add process for export job once customer was created or updated


<?php

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

class CreateSettings extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('seat_settings', function(Blueprint $table)
		{
		  $table->string('setting')->unique;
		  $table->string('value');

		  $table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::dropIfExists('seat_settings');
	}

}

<?php

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

class CreateSettings extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('seat_settings', function(Blueprint $table)
		{
		  $table->string('setting')->unique();
		  $table->string('value');

		  $table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::dropIfExists('seat_settings');
	}

}

Fix migration to actually be unique.

Fix migration to actually be unique.

This sadly does not fix it for people that have already run it


<?php

namespace Weak;

use Exception;

class NotifierException extends Exception
{
    private $exceptions = [];

    /**
     * Get exceptions thrown from notifiers
     *
     * @return array
     */
    public function getExceptions() : array
    {
        return $this->exceptions;
    }
}

<?php

/*
 * This file is part of the pinepain/php-weak PHP extension.
 *
 * Copyright (c) 2016 Bogdan Padalko <zaq178miami@gmail.com>
 *
 * Licensed under the MIT license: http://opensource.org/licenses/MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code or visit http://opensource.org/licenses/MIT
 */

namespace Weak;

use Exception;

class NotifierException extends Exception
{
    private $exceptions = [];

    /**
     * Get exceptions thrown from notifiers
     *
     * @return array
     */
    public function getExceptions() : array
    {
        return $this->exceptions;
    }
}

Add missed license note to stubs

Add missed license note to stubs [skip ci]


<?php
namespace App\Http\Response\Transformers;

use App\Pool;
use League\Fractal\TransformerAbstract;

class SinglePoolTransformer extends TransformerAbstract
{
    public $defaultIncludes = [
        'matches'
    ];

    public function transform(Pool $pool) {

        return [
            'id'            => $pool->id,
            'idTournament'  => $pool->tournament_id,
            'startTime'     => $pool->start_time,
            'endTime'       => $pool->end_time,
            'name'          => $pool->poolName,
            'idMode'        => $pool->mode_id,
            'stage'         => $pool->stage,
            'idGameType'    => $pool->gameType_id,
            'size'          => $pool->poolSize,
            'isFinished'    => $pool->isFinished,
            'ranking'       => $pool->rankings()
        ];
    }

    public function includeMatches(Pool $pool) {
        return $this->collection($pool->games, new PoolMatchesTransformer);
    }
}

<?php
namespace App\Http\Response\Transformers;

use App\Pool;
use League\Fractal\TransformerAbstract;

class SinglePoolTransformer extends TransformerAbstract
{
    public $defaultIncludes = [
        'matches'
    ];

    public function transform(Pool $pool) {

        return [
            'id'            => $pool->id,
            'idTournament'  => $pool->tournament_id,
            'startTime'     => $pool->start_time,
            'endTime'       => $pool->end_time,
            'name'          => $pool->poolName,
            'idMode'        => $pool->mode_id,
            'stage'         => $pool->stage,
            'idGameType'    => $pool->game_type_id,
            'size'          => $pool->poolSize,
            'isFinished'    => $pool->isFinished,
            'ranking'       => $pool->rankings()
        ];
    }

    public function includeMatches(Pool $pool) {
        return $this->collection($pool->games, new PoolMatchesTransformer);
    }
}

Fix name convention for badly named model/table: GameType


<?php
/**
 * CheckoutApi_Client_Constant
 * A final class that manage constant value for all CheckoutApi_Client_Client instance
 * @package     CheckoutApi_Client
 * @category     Api
 * @author       Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com>
 * @copyright 2014 Integration team (http://www.checkout.com)
 */
final class CheckoutApi_Client_Constant
{
	const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/';
	const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/';
	const APIGW3_URI_PREFIX_SANDBOX= 'http://sandbox.checkout.com/api2/';
	const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/';
	const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_';
	const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_';
	const CHARGE_TYPE = 'card';
	const LOCALPAYMENT_CHARGE_TYPE = 'localPayment';
	const TOKEN_CARD_TYPE = 'cardToken';
	const TOKEN_SESSION_TYPE = 'sessionToken';
	const AUTOCAPUTURE_CAPTURE = 'y';
	const AUTOCAPUTURE_AUTH = 'n';
	const VERSION = 'v2';
    const STATUS_CAPTURE = 'Captured';
    const STATUS_REFUND = 'Refunded';
    const LIB_VERSION = 'v1.2.5';
}

<?php
/**
 * CheckoutApi_Client_Constant
 * A final class that manage constant value for all CheckoutApi_Client_Client instance
 * @package     CheckoutApi_Client
 * @category     Api
 * @author       Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com>
 * @copyright 2014 Integration team (http://www.checkout.com)
 */
final class CheckoutApi_Client_Constant
{
	const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/';
	const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/';
	const APIGW3_URI_PREFIX_SANDBOX= 'https://sandbox.checkout.com/api2/';
	const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/';
	const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_';
	const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_';
	const CHARGE_TYPE = 'card';
	const LOCALPAYMENT_CHARGE_TYPE = 'localPayment';
	const TOKEN_CARD_TYPE = 'cardToken';
	const TOKEN_SESSION_TYPE = 'sessionToken';
	const AUTOCAPUTURE_CAPTURE = 'y';
	const AUTOCAPUTURE_AUTH = 'n';
	const VERSION = 'v2';
    const STATUS_CAPTURE = 'Captured';
    const STATUS_REFUND = 'Refunded';
    const LIB_VERSION = 'v1.2.5';
}

Change client constants sandbox URL to https


<?php

/**
 * (c) FSi sp. z o.o. <info@fsi.pl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace FSi\Bundle\FormExtensionsBundle\Twig;

use Twig_Extension;
use Twig_Extension_GlobalsInterface;

class FSiMapFormExtension extends Twig_Extension implements Twig_Extension_GlobalsInterface
{
    /**
     * @var string
     */
    private $apiKey;

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

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

    public function getGlobals()
    {
        return ['fsi_map_api_key' => $this->apiKey];
    }
}

<?php

/**
 * (c) FSi sp. z o.o. <info@fsi.pl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace FSi\Bundle\FormExtensionsBundle\Twig;

use Twig_Extension;
use Twig_Extension_GlobalsInterface;

class FSiMapFormExtension extends Twig_Extension implements Twig_Extension_GlobalsInterface
{
    /**
     * @var string|null
     */
    private $apiKey;

    public function __construct(?string $apiKey)
    {
        $this->apiKey = $apiKey;
    }

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

    public function getGlobals()
    {
        return ['fsi_map_api_key' => $this->apiKey];
    }
}

Allow empty Google Map API key

Allow empty Google Map API key


<?php

namespace EE\Migration;

use Symfony\Component\Filesystem\Filesystem;

abstract class Base {

	public $status = 'incomplete';
	protected $is_first_execution;
	protected $skip_this_migration;
	protected $backup_dir;
	protected $backup_file;
	protected $fs;

	public function __construct() {
		$this->fs                  = new Filesystem();
		$this->skip_this_migration = false;
		$this->is_first_execution  = ! \EE\Model\Option::get( 'version' );
		$this->backup_dir          = EE_ROOT_DIR . '/.backup';
		$this->fs->mkdir( $this->backup_dir );
	}

	abstract public function up();

	abstract public function down();
}

<?php

namespace EE\Migration;

use Symfony\Component\Filesystem\Filesystem;

abstract class Base {

	public $status = 'incomplete';
	protected $is_first_execution;
	protected $skip_this_migration;
	protected $backup_dir;
	protected $backup_file;
	protected $fs;

	public function __construct() {
		$this->fs                  = new Filesystem();
		$this->skip_this_migration = false;
		$this->is_first_execution  = ! \EE\Model\Option::get( 'version' );
		$this->backup_dir          = EE_BACKUP_DIR;
		$this->fs->mkdir( $this->backup_dir );
	}

	abstract public function up();

	abstract public function down();
}

Update to backup dir constant

Update to backup dir constant

Signed-off-by: Riddhesh Sanghvi <f8c90b0b72a59c76b108f89842786e39e7dc3e58@gmail.com>


<?php

/*
 * This file is part of the Doctrine\OrientDB package.
 *
 * (c) Alessandro Nadalin <alessandro.nadalin@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Class Updates
 *
 * @package     Doctrine\OrientDB
 * @subpackage  Formatter
 * @author      Alessandro Nadalin <alessandro.nadalin@gmail.com>
 */

namespace Doctrine\OrientDB\Query\Formatter\Query;

use Doctrine\OrientDB\Query\Formatter\Query;
use Doctrine\OrientDB\Query\Formatter\String;

class Updates extends Query implements TokenInterface
{
    public static function format(array $values)
    {
        $string = "";

        foreach ($values as $key => $value) {
            if ($key = self::stripNonSQLCharacters($key)) {
                if ($value === null) {
                    $value = 'NULL';
                } else if (is_int($value) || is_float($value)) {
                    // Preserve content of $value as is
                } else if (is_bool($value)) {
                    $value = $value ? 'TRUE' : 'FALSE';
                } elseif(is_array($value)) {
                    $value = '[' . implode(',', $value) . ']';
                } else {
                    $value = '"' . addslashes($value) . '"';
                }

                $string .= " $key = $value,";
            }
        }

        return substr($string, 0, strlen($string) - 1);
    }
}

<?php

/*
 * This file is part of the Doctrine\OrientDB package.
 *
 * (c) Alessandro Nadalin <alessandro.nadalin@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Class Updates
 *
 * @package     Doctrine\OrientDB
 * @subpackage  Formatter
 * @author      Alessandro Nadalin <alessandro.nadalin@gmail.com>
 */

namespace Doctrine\OrientDB\Query\Formatter\Query;

use Doctrine\OrientDB\Query\Formatter\Query;

class Updates extends Query implements TokenInterface
{
    public static function format(array $values)
    {
        $string = "";

        foreach ($values as $key => $value) {
            if ($key = self::stripNonSQLCharacters($key)) {
                if ($value === null) {
                    $value = 'NULL';
                } else if (is_int($value) || is_float($value)) {
                    // Preserve content of $value as is
                } else if (is_bool($value)) {
                    $value = $value ? 'TRUE' : 'FALSE';
                } elseif(is_array($value)) {
                    $value = '[' . implode(',', $value) . ']';
                } else {
                    $value = '"' . addslashes($value) . '"';
                }

                $string .= " $key = $value,";
            }
        }

        return substr($string, 0, strlen($string) - 1);
    }
}

Remove unused class that caused the error


<?php

namespace Oro\Bundle\UserBundle\Form\Handler;

use Oro\Bundle\UserBundle\Entity\User;

class ResetHandler extends AbstractUserHandler
{
    /**
     * {@inheritDoc}
     */
    protected function onSuccess(User $user)
    {
        $user
            ->setPlainPassword($this->form->getData()->plainPassword)
            ->setConfirmationToken(null)
            ->setPasswordRequestedAt(null)
            ->setEnabled(true);

        $this->manager->updateUser($user);
    }
}

<?php

namespace Oro\Bundle\UserBundle\Form\Handler;

use Oro\Bundle\UserBundle\Entity\User;

class ResetHandler extends AbstractUserHandler
{
    /**
     * {@inheritDoc}
     */
    protected function onSuccess(User $user)
    {
        $user
            ->setPlainPassword($this->form->getData()->getPlainPassword())
            ->setConfirmationToken(null)
            ->setPasswordRequestedAt(null)
            ->setEnabled(true);

        $this->manager->updateUser($user);
    }
}

BAP-3151: Reset password does not work
- fix property access


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\UsedKeywordsMemory;

use Broadway\EventHandling\EventBusInterface;
use Broadway\EventSourcing\EventSourcingRepository;
use Broadway\EventStore\EventStoreInterface;

class UsedKeywordsMemoryRepository extends EventSourcingRepository
{

    public function __construct(
        EventStoreInterface $eventStore,
        EventBusInterface $eventBus,
        array $eventStreamDecorators = array()
    ) {
        parent::__construct(
            $eventStore,
            $eventBus,
            '\\CultuurNet\UDB3\\UsedKeywordsMemory',
            $eventStreamDecorators
        );
    }
}

<?php
/**
 * @file
 */

namespace CultuurNet\UDB3\UsedKeywordsMemory;

use Broadway\EventHandling\EventBusInterface;
use Broadway\EventSourcing\EventSourcingRepository;
use Broadway\EventStore\EventStoreInterface;

class UsedKeywordsMemoryRepository extends EventSourcingRepository
{

    public function __construct(
        EventStoreInterface $eventStore,
        EventBusInterface $eventBus,
        array $eventStreamDecorators = array()
    ) {
        parent::__construct(
            $eventStore,
            $eventBus,
            '\\CultuurNet\UDB3\\UsedKeywordsMemory\\UsedKeywordsMemory',
            $eventStreamDecorators
        );
    }
}

Correct class name as used by keywords repository


<?php namespace Laravel\CLI; defined('DS') or die('No direct script access.');

use Laravel\Bundle;
use Laravel\Config;
use Laravel\Request;

/**
 * Fire up the default bundle. This will ensure any dependencies that
 * need to be registered in the IoC container are registered and that
 * the auto-loader mappings are registered.
 */
Bundle::start(DEFAULT_BUNDLE);

/**
 * The default database connection may be set by specifying a value
 * for the "database" CLI option. This allows migrations to be run
 * conveniently for a test or staging database.
 */

if ( ! is_null($database = get_cli_option('db')))
{
	Config::set('database.default', $database);
}

/**
 * We will register all of the Laravel provided tasks inside the IoC
 * container so they can be resolved by the task class. This allows
 * us to seamlessly add tasks to the CLI so that the Task class
 * doesn't have to worry about how to resolve core tasks.
 */
require path('sys').'cli/dependencies'.EXT;

/**
 * We will wrap the command execution in a try / catch block and
 * simply write out any exception messages we receive to the CLI
 * for the developer. Note that this only writes out messages
 * for the CLI exceptions. All others will not be caught
 * and will be totally dumped out to the CLI.
 */
try
{
	Command::run(array_slice($arguments, 1));
}
catch (\Exception $e)
{
	echo $e->getMessage();
}

echo PHP_EOL;

<?php namespace Laravel\CLI; defined('DS') or die('No direct script access.');

use Laravel\Bundle;
use Laravel\Config;
use Laravel\Request;

/**
 * Fire up the default bundle. This will ensure any dependencies that
 * need to be registered in the IoC container are registered and that
 * the auto-loader mappings are registered.
 */
Bundle::start(DEFAULT_BUNDLE);

/**
 * The default database connection may be set by specifying a value
 * for the "database" CLI option. This allows migrations to be run
 * conveniently for a test or staging database.
 */

if ( ! is_null($database = get_cli_option('db')))
{
	Config::set('database.default', $database);
}

/**
 * We will register all of the Laravel provided tasks inside the IoC
 * container so they can be resolved by the task class. This allows
 * us to seamlessly add tasks to the CLI so that the Task class
 * doesn't have to worry about how to resolve core tasks.
 */
require path('sys').'cli/dependencies'.EXT;

/**
 * We will wrap the command execution in a try / catch block and
 * simply write out any exception messages we receive to the CLI
 * for the developer. Note that this only writes out messages
 * for the CLI exceptions. All others will not be caught
 * and will be totally dumped out to the CLI.
 */
try
{
	Command::run(array_slice($arguments, 1));
}
catch (\Exception $e)
{
	echo $e->getMessage().PHP_EOL;
	exit(1);
}

echo PHP_EOL;

Exit with non-zero if command fails, useful in scripting and CI


<?php
namespace HNG\Traits;

trait SlackResponse{

/**
     * Return data in the slack response format.
     *
     * @param       $text
     * @param array $attachments
     * @param bool  $private
     * @return array
     */
    protected function slackResponse($text, array $attachments = [], $private = true)
    {
        return [
            'text'          => $text,
            'attachments'   => $attachments,
            'response_type' => $private ? 'ephemeral' : 'in_channel',
        ];
    }

}

<?php
namespace HNG\Traits;

trait SlackResponse{

/**
     * Return data in the slack response format.
     *
     * @param       $text
     * @param array $attachments
     * @param bool  $private
     * @return array
     */
    protected function slackResponse($text, array $attachments = [], $private = true)
    {
        if (is_array($text) AND (isset($text['text']) OR isset($text['attachments']))) {
            return $text;
        }

        return [
            'text'          => $text,
            'attachments'   => $attachments,
            'response_type' => $private ? 'ephemeral' : 'in_channel',
        ];
    }

}

Allow passing array as slack response for more custom events


<?php
/**
*  Corresponding Class to test Exchangerate class.
*
*
*  @author Ricardo Madrigal <soporte@d3catalyst.com>
*/
class ExchangerateTest extends PHPUnit_Framework_TestCase{

  /**
  * Just check if the YourClass has no syntax error.
  *
  */
  public function testIsThereAnySyntaxError(){
  	$var = new D3Catalyst\Exchangerate\Exchange;
  	$this->assertTrue(is_object($var));
  	unset($var);
  }

  /**
  * Check if the Exchange Rate can retrieve currency info.
  *
  */
  public function testgetExchangeCurrency(){
  	$var = new D3Catalyst\Exchangerate\Exchange;
    $var->setCurrency('USD','MXN');
  	$this->assertTrue(is_numeric($var->getExchangeValue()));
  	unset($var);
  }

}

<?php
/**
*  Corresponding Class to test Exchangerate class.
*
*
*  @author Ricardo Madrigal <soporte@d3catalyst.com>
*/
class ExchangerateTest extends PHPUnit_Framework_TestCase{

  /**
  * Just check if the YourClass has no syntax error.
  *
  */
  public function testIsThereAnySyntaxError(){
  	$var = new D3Catalyst\Exchangerate\Exchangerate;
  	$this->assertTrue(is_object($var));
  	unset($var);
  }

  /**
  * Check if the Exchange Rate can retrieve currency info.
  *
  */
  public function testgetExchangeCurrency(){
  	$var = new D3Catalyst\Exchangerate\Exchangerate;
    $var->setCurrency('USD','MXN');
  	$this->assertTrue(is_numeric($var->getExchangeValue()));
  	unset($var);
  }

}

Fix 'Againgit add *' unit test...

Fix 'Againgit add *' unit test...


<?php
namespace wcf\page;
use wcf\system\menu\user\UserMenu;
use wcf\system\session\Session;
use wcf\system\session\SessionHandler;
use wcf\system\WCF;

/**
 * Shows the account security page.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2020 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Page
 * @since       5.4
 */
class AccountSecurityPage extends AbstractPage {
	/**
	 * @inheritDoc
	 */
	public $loginRequired = true;

	/**
	 * @var Session[]
	 */
	private $activeSessions;

	/**
	 * @inheritDoc
	 */
	public function readData() {
		parent::readData();

		$this->activeSessions = SessionHandler::getInstance()->getUserSessions(WCF::getUser());
	}

	/**
	 * @inheritDoc
	 */
	public function assignVariables() {
		parent::assignVariables();

		WCF::getTPL()->assign([
			'activeSessions' => $this->activeSessions
		]);
	}

	/**
	 * @inheritDoc
	 */
	public function show() {
		// set active tab
		UserMenu::getInstance()->setActiveMenuItem('wcf.user.menu.profile.security');

		parent::show();
	}
}

<?php
namespace wcf\page;
use wcf\system\menu\user\UserMenu;
use wcf\system\session\Session;
use wcf\system\session\SessionHandler;
use wcf\system\WCF;

/**
 * Shows the account security page.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2020 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Page
 * @since       5.4
 */
class AccountSecurityPage extends AbstractPage {
	/**
	 * @inheritDoc
	 */
	public $loginRequired = true;

	/**
	 * @var Session[]
	 */
	private $activeSessions;

	/**
	 * @inheritDoc
	 */
	public function readData() {
		parent::readData();

		$this->activeSessions = SessionHandler::getInstance()->getUserSessions(WCF::getUser());

		usort($this->activeSessions, function ($a, $b) {
			return $b->getLastActivityTime() <=> $a->getLastActivityTime();
		});
	}

	/**
	 * @inheritDoc
	 */
	public function assignVariables() {
		parent::assignVariables();

		WCF::getTPL()->assign([
			'activeSessions' => $this->activeSessions
		]);
	}

	/**
	 * @inheritDoc
	 */
	public function show() {
		// set active tab
		UserMenu::getInstance()->setActiveMenuItem('wcf.user.menu.profile.security');

		parent::show();
	}
}

Sort active sessions by last activity time


<?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\Order\Repository;

use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
    /**
     * @param int $amount
     *
     * @return OrderInterface[]
     */
    public function findRecentOrders($amount = 10);

    /**
     * @param int|string $number
     *
     * @return bool
     */
    public function isNumberUsed($number);
}

<?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\Order\Repository;

use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
    /**
     * @param int $amount
     *
     * @return OrderInterface[]
     */
    public function findRecentOrders($amount = 10);

    /**
     * @param int|string $number
     *
     * @return bool
     */
    public function isNumberUsed($number);

    /**
     * @param string $orderNumber
     *
     * @return OrderInterface|null
     */
    public function findOneByNumber($orderNumber);
}

Add custom repository methods to obtain only placed orders


<?php

class smarty_function_viewTemplateTest extends CMTest_TestCase {

    public function testRender() {
        /** @var CM_Component_Abstract $component */
        $component = $this->mockObject('CM_Component_Abstract');
        $viewResponse = new CM_Frontend_ViewResponse($component);

        $render = $this->mockObject('CM_Frontend_Render');
        $method = $render->mockMethod('fetchViewTemplate')->set(function ($view, $templateName, $data) use ($component) {
            $this->assertSame($component, $view);
            $this->assertSame('jar', $templateName);
            $this->assertArrayContains(['bar' => 'bar', 'foo' => 'foo'], $data);
        });
        /** @var CM_Frontend_Render $render */
        $render->getGlobalResponse()->treeExpand($viewResponse);
        $render->parseTemplateContent('{viewTemplate file="jar" bar="bar"}', ['foo' => 'foo']);
        $this->assertSame(1, $method->getCallCount());
    }
}

<?php

class smarty_function_viewTemplateTest extends CMTest_TestCase {

    public function testRender() {
        /** @var CM_Component_Abstract $component */
        $component = $this->mockObject('CM_Component_Abstract');
        $componentViewResponse = new CM_Frontend_ViewResponse($component);

        /** @var CM_Form_Abstract $form */
        $form = $this->mockObject('CM_Form_Abstract');
        $formViewResponse = new CM_Frontend_ViewResponse($form);

        $render = $this->mockObject('CM_Frontend_Render');
        $method = $render->mockMethod('fetchViewTemplate')
            ->at(0, function ($view, $templateName, $data) use ($form) {
                $this->assertSame($form, $view);
                $this->assertSame('jar', $templateName);
                $this->assertArrayContains(['bar' => 'bar', 'foo' => 'foo'], $data);
            })
            ->at(1, function ($view, $templateName, $data) use ($component) {
                $this->assertSame($component, $view);
                $this->assertSame('foo', $templateName);
            });
        /** @var CM_Frontend_Render $render */
        $render->getGlobalResponse()->treeExpand($componentViewResponse);
        $render->getGlobalResponse()->treeExpand($formViewResponse);

        $render->parseTemplateContent('{viewTemplate file="jar" bar="bar"}', ['foo' => 'foo']);
        $render->parseTemplateContent('{viewTemplate view="CM_Component_Abstract" file="foo"}');

        $this->assertSame(2, $method->getCallCount());
    }
}

Include testing view param for viewTemplate


<?php

namespace AppBundle\Twig;

use Symfony\Bridge\Twig\Extension\RoutingExtension as BaseRoutingExtension;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class RoutingExtension extends BaseRoutingExtension
{
    /**
     * @var UrlGeneratorInterface
     */
    private $generator;

    /**
     * @var RequestStack
     */
    private $requestStack;

    public function __construct(
        UrlGeneratorInterface $generator,
        RequestStack $requestStack
    ) {
        $this->generator = $generator;
        $this->requestStack = $requestStack;
        parent::__construct($generator);
    }

    /**
     * @param string $name
     * @param array  $parameters
     * @param bool   $relative
     *
     * @return string
     */
    public function getPath($name, $parameters = [], $relative = false)
    {
        if (!array_key_exists('redirect', $parameters)) {
            $parameters['redirect'] = '/'.$this->requestStack->getCurrentRequest()->get('url');
        }

        return parent::getPath($name, $parameters, $relative);
    }

    /**
     * @param string $name
     * @param array  $parameters
     * @param bool   $schemeRelative
     *
     * @return string
     */
    public function getUrl($name, $parameters = [], $schemeRelative = false)
    {
        if (!array_key_exists('redirect', $parameters)) {
            $parameters['redirect'] = $this->requestStack->getCurrentRequest()->get('url');
        }

        return parent::getUrl($name, $parameters, $relative);
    }
}

<?php

namespace AppBundle\Twig;

use Symfony\Bridge\Twig\Extension\RoutingExtension as BaseRoutingExtension;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class RoutingExtension extends BaseRoutingExtension
{
    /**
     * @var UrlGeneratorInterface
     */
    private $generator;

    /**
     * @var RequestStack
     */
    private $requestStack;

    public function __construct(
        UrlGeneratorInterface $generator,
        RequestStack $requestStack
    ) {
        $this->generator = $generator;
        $this->requestStack = $requestStack;
        parent::__construct($generator);
    }

    /**
     * @param string $name
     * @param array  $parameters
     * @param bool   $relative
     *
     * @return string
     */
    public function getPath($name, $parameters = [], $relative = false)
    {
        if (!array_key_exists('redirect', $parameters)) {
            $parameters['redirect'] = '/'.$this->requestStack->getMasterRequest()->get('url');
        }

        return parent::getPath($name, $parameters, $relative);
    }

    /**
     * @param string $name
     * @param array  $parameters
     * @param bool   $schemeRelative
     *
     * @return string
     */
    public function getUrl($name, $parameters = [], $schemeRelative = false)
    {
        if (!array_key_exists('redirect', $parameters)) {
            $parameters['redirect'] = $this->requestStack->getCurrentRequest()->get('url');
        }

        return parent::getUrl($name, $parameters, $relative);
    }
}

Fix redirect param in sub-requests

Fix redirect param in sub-requests


<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package WordPress
 * @subpackage Ally
 */
?>
<? get_header(); ?>

Mission

Board

Staff

Jobs

In The News

Press Releases

        <?php while (have_posts()) : the_post(); ?>
          <?php the_content(); ?>
        <?php endwhile; // end of the loop. ?>

<?php get_footer(); ?>

<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package WordPress
 * @subpackage Ally
 */
?>
<? get_header(); ?>

Mission

Staff

Board

        <?php while (have_posts()) : the_post(); ?>
          <?php the_content(); ?>
        <?php endwhile; // end of the loop. ?>

<?php get_footer(); ?>

Remove unneeded links from about menu

Remove unneeded links from about menu


<?php

/**
 * This file is part of Herbie.
 *
 * (c) Thomas Breuss <www.tebe.ch>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace herbie\plugin\feed;

use Herbie;
use Herbie\Loader\FrontMatterLoader;
use Herbie\Menu\Page\Item;

class FeedPlugin extends Herbie\Plugin
{

    /**
     * @var Herbie\Menu\Page
     */
    private $menu;

    /**
     * @param Herbie\Event $event
     */
    public function onPluginsInitialized(Herbie\Event $event)
    {
        if($this->app['config']->isEmpty('plugins.config.feed.no_page')) {
            $this->app['config']->push('pages.extra_paths', '@plugin/feed/pages');
        }
    }

}

<?php

/**
 * This file is part of Herbie.
 *
 * (c) Thomas Breuss <www.tebe.ch>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace herbie\plugin\feed;

use Herbie;
use Herbie\Loader\FrontMatterLoader;
use Herbie\Menu\Page\Item;

class FeedPlugin extends Herbie\Plugin
{

    /**
     * @var Herbie\Menu\Page
     */
    private $menu;

    /**
     * @param Herbie\Event $event
     */
    public function onPluginsInitialized(Herbie\Event $event)
    {
        if($this->config->isEmpty('plugins.config.feed.no_page')) {
            $this->config->push('pages.extra_paths', '@plugin/feed/pages');
        }
    }

}

Use config method from plugin class

Use config method from plugin class


<?php
namespace Payum\Core\Bridge\Symfony\Security;

use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Security\TokenInterface;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TokenFactory extends AbstractGenericTokenFactory
{
    /**
     * @var \Symfony\Component\Routing\RouterInterface
     */
    protected $urlGenerator;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param StorageInterface $tokenStorage
     * @param StorageRegistryInterface $storageRegistry
     * @param string $capturePath
     * @param string $notifyPath
     */
    public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
    {
        $this->urlGenerator = $urlGenerator;

        parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
    }

    /**
     * @param string $path
     * @param array $parameters
     *
     * @return string
     */
    protected function generateUrl($path, array $parameters = array())
    {
        return $this->urlGenerator->generate($path, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
    }
}

<?php
namespace Payum\Core\Bridge\Symfony\Security;

use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TokenFactory extends AbstractGenericTokenFactory
{
    /**
     * @var \Symfony\Component\Routing\RouterInterface
     */
    protected $urlGenerator;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param StorageInterface $tokenStorage
     * @param StorageRegistryInterface $storageRegistry
     * @param string $capturePath
     * @param string $notifyPath
     */
    public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
    {
        $this->urlGenerator = $urlGenerator;

        parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
    }

    /**
     * @param string $path
     * @param array $parameters
     *
     * @return string
     */
    protected function generateUrl($path, array $parameters = array())
    {
        return $this->urlGenerator->generate($path, $parameters, true);
    }
}

[security][symfony] Fix fatal error on old symfony versions.

PHP Fatal error:  Undefined class constant 'ABSOLUTE_URL' in ....


<?php
namespace AppZap\PHPFramework\Mail;

use AppZap\PHPFramework\Configuration\Configuration;

class MailService {

  /**
   * @param MailMessage $message
   */
  public function send(MailMessage $message) {
    $transport = $this->createTransport();
    $mailer = new \Swift_Mailer($transport);
    $mailer->send($message);
  }

  /**
   * @return \Swift_Transport
   */
  protected function createTransport() {
    $mailConfiguration = Configuration::getSection(
        'phpframework',
        'mail',
        [
          'smtp_encryption' => 'ssl',
          'smtp_host' => 'localhost',
          'smtp_password' => '',
          'smtp_port' => FALSE,
          'smtp_user' => FALSE,
        ]
    );
    if (!$mailConfiguration['smtp_user']) {
      return \Swift_MailTransport::newInstance();
    }
    if (!$mailConfiguration['smtp_port']) {
      if ($mailConfiguration['smtp_encryption'] === 'ssl') {
        $mailConfiguration['smtp_port'] = '465';
      } else {
        $mailConfiguration['smtp_port'] = '587';
      }
    }
    $transport = \Swift_SmtpTransport::newInstance(
        $mailConfiguration['smtp_host'],
        $mailConfiguration['smtp_port'],
        $mailConfiguration['smtp_encryption']
    );
    $transport->setUsername($mailConfiguration['smtp_user']);
    $transport->setPassword($mailConfiguration['smtp_password']);
    return $transport;
  }

}

<?php
namespace AppZap\PHPFramework\Mail;

use AppZap\PHPFramework\Configuration\Configuration;

class MailService {

  /**
   * @param MailMessage $message
   */
  public function send(MailMessage $message) {
    $transport = $this->createTransport();
    $mailer = new \Swift_Mailer($transport);
    $mailer->send($message);
  }

  /**
   * @return \Swift_Transport
   */
  protected function createTransport() {
    $mailConfiguration = Configuration::getSection(
        'phpframework',
        'mail',
        [
          'smtp_encryption' => 'ssl',
          'smtp_host' => 'localhost',
          'smtp_password' => '',
          'smtp_port' => FALSE,
          'smtp_user' => FALSE,
        ]
    );
    if (!$mailConfiguration['smtp_user']) {
      return \Swift_MailTransport::newInstance();
    }
    if ($mailConfiguration['smtp_encryption'] === 'none') {
      $mailConfiguration['smtp_encryption'] = NULL;
    }
    if (!$mailConfiguration['smtp_port']) {
      if ($mailConfiguration['smtp_encryption'] === 'ssl') {
        $mailConfiguration['smtp_port'] = '465';
      } else {
        $mailConfiguration['smtp_port'] = '587';
      }
    }
    $transport = \Swift_SmtpTransport::newInstance(
        $mailConfiguration['smtp_host'],
        $mailConfiguration['smtp_port'],
        $mailConfiguration['smtp_encryption']
    );
    $transport->setUsername($mailConfiguration['smtp_user']);
    $transport->setPassword($mailConfiguration['smtp_password']);
    return $transport;
  }

}

Support 'none' as smtp encryption

Support 'none' as smtp encryption


<a href="<?php echo $article->getURL();?>"><?php echo $article->getTitle(); ?>

						<?php if ($image = $article->getImage()) { ?>
								<a href="<?php echo $article->getURL();?>">
									<img alt="<?php echo $image->getTitle();?>" src="<?php echo $image->getURL();?>">

						<?php } else { ?>
								<a href="<?php echo $article->getURL();?>">
									<img alt="" src="<?php echo IMAGE_URL.'650/300/'.DEFAULT_IMG_URI; ?>">

						<?php } ?>

<?php echo $article->getTeaser();?>

<a href="<?php echo $article->getURL();?>"><?php echo $article->getTitle(); ?>

						<?php if ($image = $article->getImage()) { ?>
								<a href="<?php echo $article->getURL();?>">
									<img alt="<?php echo $image->getTitle();?>" src="<?php echo $image->getURL(1200);?>">

						<?php } else { ?>
								<a href="<?php echo $article->getURL();?>">
									<img alt="" src="<?php echo IMAGE_URL.'650/300/'.DEFAULT_IMG_URI; ?>">

						<?php } ?>

<?php echo $article->getTeaser();?>

Fix article size in spinner

Fix article size in spinner


<?php

class Notification extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'radio_notifications';

	/**
	 * Should deleted_at be used
	 *
	 * @var bool
	 */
	protected $softDeletes = true;

	// allow mass-assignment
	protected $fillable = ["notification", "privileges"];

	public static function generate($notification, $level) {
		return static::create([
			"privileges" => $level,
			"notification" => $notification,
		]);
	}

	public static function dev($notification) {
		return static::generate($notification, User::DEV);
	}
	public static function pending($notification) {
		return static::generate($notification, User::PENDING);
	}
	public static function admin($notification) {
		return static::generate($notification, User::ADMIN);
	}
	public static function news($notification) {
		return static::generate($notification, User::NEWS);
	}
	public static function dj($notification) {
		return static::generate($notification, User::DJ);
	}

	public function toArray() {
		$array = parent::toArray();

		$array["notification"] = Markdown::render($array["notification"]);

		return $array;
	}
}

<?php

class Notification extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'radio_notifications';

	/**
	 * Should deleted_at be used
	 *
	 * @var bool
	 */
	protected $softDelete = true;

	// allow mass-assignment
	protected $fillable = ["notification", "privileges"];

	public static function generate($notification, $level) {
		return static::create([
			"privileges" => $level,
			"notification" => $notification,
		]);
	}

	public static function dev($notification) {
		return static::generate($notification, User::DEV);
	}
	public static function pending($notification) {
		return static::generate($notification, User::PENDING);
	}
	public static function admin($notification) {
		return static::generate($notification, User::ADMIN);
	}
	public static function news($notification) {
		return static::generate($notification, User::NEWS);
	}
	public static function dj($notification) {
		return static::generate($notification, User::DJ);
	}

	public static function fetch(User $user) {
		return static::where("privileges", "<", (int) $user->privileges + 1)->orderBy("created_at", "desc")->get();
	}

	public function toArray() {
		$array = parent::toArray();

		$array["notification"] = Markdown::render($array["notification"]);

		return $array;
	}
}

Allow fetching notifications by user

Allow fetching notifications by user


<?php

namespace Mpociot\VatCalculator\Traits;

use Mpociot\VatCalculator\Facades\VatCalculator;

trait BillableWithinTheEU
{
    /**
     * @var int
     */
    protected $stripeTaxPercent = 0;

    /**
     * @var
     */
    protected $userCountryCode;

    /**
     * @var bool
     */
    protected $userIsCompany = false;

    /**
     * @param string     $countryCode
     * @param bool|false $company
     *
     * @return $this
     */
    public function setTaxForCountry($countryCode, $company = false)
    {
        $this->userCountryCode = $countryCode;
        $this->userIsCompany = $company;

        return $this;
    }

    /**
     * @param $countryCode
     *
     * @return $this
     */
    public function useTaxFrom($countryCode)
    {
        $this->userCountryCode = $countryCode;

        return $this;
    }

    /**
     * @return $this
     */
    public function asBusiness()
    {
        $this->userIsCompany = true;

        return $this;
    }

    /**
     * @return $this
     */
    public function asIndividual()
    {
        $this->userIsCompany = false;

        return $this;
    }

    /**
     * Get the tax percentage to apply to the subscription.
     *
     * @return int
     */
    public function getTaxPercent()
    {
        return VatCalculator::getTaxRateForCountry($this->userCountryCode, $this->userIsCompany) * 100;
    }
}

<?php

namespace Mpociot\VatCalculator\Traits;

use Mpociot\VatCalculator\Facades\VatCalculator;

trait BillableWithinTheEU
{
    /**
     * @var int
     */
    protected $stripeTaxPercent = 0;

    /**
     * @var
     */
    protected $userCountryCode;

    /**
     * @var bool
     */
    protected $userIsCompany = false;

    /**
     * @param string     $countryCode
     * @param bool|false $company
     *
     * @return $this
     */
    public function setTaxForCountry($countryCode, $company = false)
    {
        $this->userCountryCode = $countryCode;
        $this->userIsCompany = $company;

        return $this;
    }

    /**
     * @param $countryCode
     *
     * @return $this
     */
    public function useTaxFrom($countryCode)
    {
        $this->userCountryCode = $countryCode;

        return $this;
    }

    /**
     * @return $this
     */
    public function asBusiness()
    {
        $this->userIsCompany = true;

        return $this;
    }

    /**
     * @return $this
     */
    public function asIndividual()
    {
        $this->userIsCompany = false;

        return $this;
    }

    /**
     * Get the tax percentage to apply to the subscription.
     *
     * @return int
     */
    public function getTaxPercent()
    {
        return VatCalculator::getTaxRateForCountry($this->userCountryCode, $this->userIsCompany) * 100;
    }

    /**
     * Get the tax percentage to apply to the subscription for Cashier > 6.0
     *
     * @return int
     */
    public function taxPercentage()
    {
        return $this->getTaxPercent();
    }
}

Add taxPercentage() for Laravel Cashier 6.0

In Laravel Cashier 6.0, the function to get tax rate is now ``taxPercentage()`` instead of ``getTaxPercent()``


<?php
use Michelf\Markdown;

// For basic auth, we want to use the username, not the email address
Route::filter('auth.basic', function()
{
    Config::set('auth.model', 'User');
    return Auth::basic('username');
});

// get the "index" page if we hit the main site
Route::get('/', function()
{
    $page = Page::where('slug', 'index')->first();
    return View::make('page')->with($page->getContent());
});

// Administration functions
Route::group(['prefix' => 'sysop', 'before' => 'auth.basic'], function()
{
    Route::get('/', function()
    {
        return View::make('admin.index');
    });
    Route::resource('pages', 'Admin_PagesController');
});

Route::get('/page/{slug}', function($slug)
{
    $page = Page::where('slug', $slug)->first();
    if (empty($page)) {
        return Response::make('Not Found', 404);
    }
    return View::make('page')->with($page->getContent());
});

<?php
use Michelf\Markdown;

// For basic auth, we want to use the username, not the email address
Route::filter('auth.basic', function()
{
    Config::set('auth.model', 'User');
    return Auth::basic('username');
});

// get the "index" page if we hit the main site
Route::get('/', function()
{
    $page = Page::where('slug', 'index')->first();
    return View::make('page')->with($page->getContent());
});

// Administration functions
Route::group(['prefix' => 'sysop', 'before' => 'auth.basic'], function()
{
    Route::get('/', function()
    {
        return View::make('admin.index');
    });
    Route::resource('pages', 'Admin_PagesController');
});

Route::get('/page/{slug}', function($slug)
{
    $page = Page::where('slug', $slug)->first();
    if (empty($page) || !$page->is_visible) {
        return Response::make('Page not found', 404);
    }
    return View::make('page')->with($page->getContent());
});

Return 404 if page not set visible

Return 404 if page not set visible


<?php

/**
 *
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class CDNFile extends DataExtension {
	public static $db = array(
		'CDNFile'			=> 'FileContent'
	);

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

		if ($this->owner->ParentID && $this->owner->Parent()->StoreInCDN) {
			$path = $this->owner->getFullPath();
			if (is_file($path)) {
				$writer = $this->owner->Parent()->getCDNWriter();
				$writer->write($this->owner->getFullPath(), $this->owner->getFullPath());
				// writer should now have an id
				$this->owner->CDNFile = $writer->getContentId();
			}
		}
	}

	public function updateCMSFields(\FieldList $fields) {
		if ($file = $this->owner->obj('CDNFile')) {
			if (strlen($file->getValue())) {
				$url = $file->URL();
				$fields->addFieldToTab('Root.Main', new LiteralField('CDNUrl', sprintf('%s', $url, $url)));
			}
		}
	}
}

<?php

/**
 *
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class CDNFile extends DataExtension {
	public static $db = array(
		'CDNFile'			=> 'FileContent'
	);

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

		if ($this->owner->ParentID && $this->owner->Parent()->StoreInCDN && !($this->owner instanceof Folder)) {
			$path = $this->owner->getFullPath();
			if (strlen($path) && is_file($path) && file_exists($path)) {
				$writer = $this->owner->Parent()->getCDNWriter();
				$writer->write($this->owner->getFullPath(), $this->owner->getFullPath());
				// writer should now have an id
				$this->owner->CDNFile = $writer->getContentId();
			}
		}
	}

	public function onAfterDelete() {
		if ($this->owner->ParentID && $this->owner->Parent()->StoreInCDN && !($this->owner instanceof Folder)) {
			$obj = $this->owner->obj('CDNFile');
			if ($obj) {
				$writer = $obj->getReader()->getWriter();
				$writer->delete();
			}
		}
	}

	public function updateCMSFields(\FieldList $fields) {
		if ($file = $this->owner->obj('CDNFile')) {
			if (strlen($file->getValue())) {
				$url = $file->URL();
				$fields->addFieldToTab('Root.Main', new LiteralField('CDNUrl', sprintf('%s', $url, $url)));
			}
		}
	}
}

Handle deletion of files against the CDN


<?php

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

class CreateWatches extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('watches', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id')->unsigned();
            $table->string('notifiable_type');
            $table->bigInteger('notifiable_id')->unsigned();
            $table->string('subtype');
            $table->timestampsTz();

            $table->unique(['user_id', 'notifiable_type', 'notifiable_id', 'subtype']);
            $table->index(['notifiable_type', 'notifiable_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('watches');
    }
}

<?php

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

class CreateWatches extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('watches', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id')->unsigned();
            $table->enum('notifiable_type', ['beatmapset', 'build', 'news_post']);
            $table->bigInteger('notifiable_id')->unsigned();
            $table->string('subtype');
            $table->timestampsTz();

            $table->unique(['user_id', 'notifiable_type', 'notifiable_id', 'subtype']);
            $table->index(['notifiable_type', 'notifiable_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('watches');
    }
}

Use enum for the type

Use enum for the type


<?php

/*

Plugin Name: Castlegate IT WP Twitter Redux
Plugin URI: http://github.com/castlegateit/cgit-wp-twitter-redux
Description: Simple, flexible Twitter feed plugin.
Version: 1.5.2
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: MIT

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

define('CGIT_TWITTER_REDUX_PLUGIN', __FILE__);

require_once __DIR__ . '/lib/twitteroauth/autoload.php';
require_once __DIR__ . '/classes/autoload.php';
require_once __DIR__ . '/functions.php';

$plugin = new \Cgit\Twitter\Plugin();

do_action('cgit_twitter_redux_loaded');

<?php

/*

Plugin Name: Castlegate IT WP Twitter Redux
Plugin URI: http://github.com/castlegateit/cgit-wp-twitter-redux
Description: Simple, flexible Twitter feed plugin.
Version: 1.5.2
Author: Castlegate IT
Author URI: http://www.castlegateit.co.uk/
License: AGPL

*/

if (!defined('ABSPATH')) {
    wp_die('Access denied');
}

define('CGIT_TWITTER_REDUX_PLUGIN', __FILE__);

require_once __DIR__ . '/lib/twitteroauth/autoload.php';
require_once __DIR__ . '/classes/autoload.php';
require_once __DIR__ . '/functions.php';

$plugin = new \Cgit\Twitter\Plugin();

do_action('cgit_twitter_redux_loaded');

Switch license from MIT to AGPL in plugin file


<?php
namespace qnd;

/**
 * Loader
 *
 * @param array $attr
 * @param array $item
 *
 * @return mixed
 */
function loader(array $attr, array $item)
{
    $item[$attr['id']] = cast($attr, $item[$attr['id']] ?? null);
    $callback = fqn('loader_' . $attr['type']);

    if (is_callable($callback)) {
        return $callback($attr, $item);
    }

    // Temporary
    if ($attr['multiple']) {
        return loader_json($attr, $item);
    }

    return $item[$attr['id']];
}

/**
 * JSON loader
 *
 * @param array $attr
 * @param array $item
 *
 * @return array
 */
function loader_json(array $attr, array $item): array
{
    if (empty($item[$attr['id']])) {
        return [];
    } elseif (is_array($item[$attr['id']])) {
        return $item[$attr['id']];
    }

    return json_decode($item[$attr['id']], true) ?: [];
}

<?php
namespace qnd;

/**
 * Loader
 *
 * @param array $attr
 * @param array $item
 *
 * @return mixed
 */
function loader(array $attr, array $item)
{
    $item[$attr['id']] = cast($attr, $item[$attr['id']] ?? null);
    $callback = fqn('loader_' . $attr['type']);

    if (is_callable($callback)) {
        return $callback($attr, $item);
    }

    // Temporary
    if ($attr['backend'] === 'json') {
        return loader_json($attr, $item);
    }

    return $item[$attr['id']];
}

/**
 * JSON loader
 *
 * @param array $attr
 * @param array $item
 *
 * @return array
 */
function loader_json(array $attr, array $item): array
{
    if (empty($item[$attr['id']])) {
        return [];
    } elseif (is_array($item[$attr['id']])) {
        return $item[$attr['id']];
    }

    return json_decode($item[$attr['id']], true) ?: [];
}

Use backend type instead of multiple flag


@section('content')

{{ $search }}

@foreach ($items as $item)

$item->id)) }}">{{$item->name}}
{{ $item->featureLabels }}

@endforeach

@stop

Remove the search's list decoration.

Remove the search's list decoration.


<?php

namespace SerendipityHQ\Component\ValueObjects\Address\Bridge\Symfony\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Adamo Crespi <hello@aerendir.me>
 */
class AddressType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('countryCode', CountryType::class, ['label' => 'address.form.country_code.label', 'translation_domain' => 'address'])
            ->add('administrativeArea', TextType::class)
            ->add('locality', TextType::class)
            ->add('dependentLocality', TextType::class)
            ->add('postalCode', TextType::class)
            ->add('street', TextType::class)
            ->add('extraLine', TextType::class);
    }
}

<?php

namespace SerendipityHQ\Component\ValueObjects\Address\Bridge\Symfony\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Adamo Crespi <hello@aerendir.me>
 */
class AddressType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('countryCode', CountryType::class, ['label' => 'address.form.country_code.label', 'translation_domain' => 'address'])
            ->add('administrativeArea', TextType::class)
            ->add('locality', TextType::class)
            ->add('dependentLocality', TextType::class, ['required' => false])
            ->add('postalCode', TextType::class)
            ->add('street', TextType::class)
            ->add('extraLine', TextType::class, ['required' => false]);
    }
}

Make optional `dependentLocality` and `extraLine`.


<?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 library
 */
class PhutilMissingSymbolException extends Exception {
  public function __construct($symbol) {
    parent::__construct(
      "Failed to load symbol '{$symbol}'. ".
      "Your library map may be out of date.");
  }
}

<?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 library
 */
class PhutilMissingSymbolException extends Exception {
  public function __construct($symbol) {
    parent::__construct(
      "Failed to load symbol '{$symbol}'. ".
      "Your library map may be out of date. Try to rebuild it with ".
      "instructions at page http://www.phabricator.com/docs/libphutil/article/".
      "Rebuilding_the_Library_Map.html.");
  }
}

Improve error message when Phabricator fails to load a class.

Summary: add references to documentation into the error message.

Test Plan: modify a class name in a file to trigger the error message.
For example, modify ""ManiphestTaskPriority"" to ""FOO"" in
ManiphestTaskSummaryView.php in directory
phabricator/src/applications/maniphest/view/tasksummary/.

Reviewers: epriestley

CC:

Differential Revision: 49


<?php
/**
 * Created by PhpStorm.
 * User: mirel
 * Date: 04.10.2016
 * Time: 11:26
 */

namespace mpf\helpers;

use mpf\base\LogAwareObject;

class CalendarDay extends LogAwareObject
{
    public $date, $time, $callBacks, $inCurrentMonth, $dayNumber;

    public function __get($name)
    {
        if (isset($this->callBacks[$name]))
            return call_user_func($this->callBacks[$name], $this);
        $this->error("Unknown attribute '$name'!");
    }

    /**
     * @return bool
     */
    public function isToday()
    {
        return date('Y-m-d') == $this->date;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: mirel
 * Date: 04.10.2016
 * Time: 11:26
 */

namespace mpf\helpers;

use mpf\base\LogAwareObject;

class CalendarDay extends LogAwareObject
{
    public $date, $time, $callBacks, $inCurrentMonth, $dayNumber;

    public function __get($name)
    {
        if (isset($this->callBacks[$name]))
            return call_user_func($this->callBacks[$name], $this);
        $this->error("Unknown attribute '$name'!");
    }

    /**
     * @return bool
     */
    public function isToday()
    {
        return date('Y-m-d') == $this->date;
    }

    public function getWeekDay(){
        return date('l', $this->time);
    }
}

Add option to get week day

Add option to get week day