<?php

namespace Fhaculty\Graph\Algorithm;

use Fhaculty\Graph\Algorithm\BaseGraph;
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Algorithm\Degree;

class Eulerian extends BaseGraph
{
    /**
     * check whether this graph has an eulerian cycle
     *
     * @return boolean
     * @uses Graph::isConnected()
     * @uses Degree::getDegreeVertex()
     * @todo isolated vertices should be ignored
     * @todo definition is only valid for undirected graphs
     */
    public function hasCycle()
    {
        if ($this->graph->isConnected()) {
            $alg = new Degree($this->graph);

            foreach ($this->graph->getVertices() as $vertex) {
                // uneven degree => fail
                if ($alg->getDegreeVertex($vertex) & 1) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
}

<?php

namespace Fhaculty\Graph\Algorithm;

use Fhaculty\Graph\Algorithm\BaseGraph;
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Algorithm\Degree;

class Eulerian extends BaseGraph
{
    /**
     * check whether this graph has an eulerian cycle
     *
     * @return boolean
     * @uses ConnectedComponents::isSingle()
     * @uses Degree::getDegreeVertex()
     * @todo isolated vertices should be ignored
     * @todo definition is only valid for undirected graphs
     */
    public function hasCycle()
    {
        $components = new ConnectedComponents($this->graph);
        if ($components->isSingle()) {
            $alg = new Degree($this->graph);

            foreach ($this->graph->getVertices() as $vertex) {
                // uneven degree => fail
                if ($alg->getDegreeVertex($vertex) & 1) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
}

Fix outdated refernce to connected components


<?php
/**
 * HTTP request object factory
 *
 * This factory should be used in index.php for request object initialization.
 * Example:
 *
 * $validator = (new Validator)->setAdapter(new PhpFilters);
 * $request = RequestFactory::create($_SERVER['CONTENT_TYPE'])->setValidator($validator);
 *
 * @file      RequestFactory.php
 *
 * PHP version 7.0+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2020 Alexander Yancharuk <alex at itvault at info>
 * @date      2017-04-23 16:12
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Veles\Request;

class RequestFactory
{
	/**
	 * Create HTTP-request object depending on Content-type HTTP-header
	 *
	 * @param string $type Value of Content-type HTTP-header
	 *
	 * @return HttpRequestAbstract
	 */
	public static function create($type)
	{
		if (empty($type) || 0 === strpos($type, 'text/html')) {
			return new HttpGetRequest;
		}

		return new HttpPostRequest;
	}
}

<?php
/**
 * HTTP request object factory
 *
 * This factory should be used in index.php for request object initialization.
 * Example:
 *
 * $validator = (new Validator)->setAdapter(new PhpFilters);
 * $request = RequestFactory::create($_SERVER['CONTENT_TYPE'])->setValidator($validator);
 *
 * @file      RequestFactory.php
 *
 * PHP version 7.0+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2020 Alexander Yancharuk <alex at itvault at info>
 * @date      2017-04-23 16:12
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Veles\Request;

class RequestFactory
{
	/**
	 * Create HTTP-request object depending on Content-type HTTP-header
	 *
	 * @param string $type Value of Content-type HTTP-header
	 *
	 * @return HttpRequestAbstract
	 */
	public static function create($type)
	{
		if (empty($type) || 0 === strpos($type, 'text/html')) {
			return new HttpGetRequest;
		}

		if (0 === strpos($type, 'application/json')) {
			return new HttpJsonRequest;
		}

		return new HttpPostRequest;
	}
}

Handle json-request in request factory

fix: Handle json-request in request factory


<?php
use \SlaxWeb\Hooks\Hooks;

/**
 * Example hook
 */
Hooks::setHook(["name" => "Hook name", "class" => "\\Hooks\\Sample"]);

<?php
use SlaxWeb\Hooks\Hooks;

/**
 * Example hook
 */
Hooks::set(["name" => "Hook name", "class" => "\\Hooks\\Sample"]);

Rename method for setting a hook

Rename method for setting a hook


<?php

class Properties_Taxonomy_Type extends Papi_Taxonomy_Type {

	/**
	 * Define our Page Type meta data.
	 *
	 * @return array
	 */
	public function meta() {
		return [
			'name'        => 'Properties taxonomy type',
			'description' => 'This is a properties taxonomy page',
			'template'    => 'pages/properties-taxonomy-page.php',
			'taxonomy'    => 'post_tag'
		];
	}

	/**
	 * Remove meta boxes.
	 *
	 * @return array
	 */
	public function remove() {
		return ['editor', 'commentsdiv', 'commentstatusdiv', 'authordiv', 'slugdiv'];
	}

	/**
	 * Define our properties.
	 */
	public function register() {
		$this->box( papi_template( __DIR__ . '/../page-types/boxes/properties.php' ) );
	}
}

<?php

class Properties_Taxonomy_Type extends Papi_Taxonomy_Type {

	/**
	 * Define our Page Type meta data.
	 *
	 * @return array
	 */
	public function meta() {
		return [
			'name'        => 'Properties taxonomy',
			'description' => 'This is a properties taxonomy',
			'template'    => 'pages/properties-taxonomy.php',
			'taxonomy'    => 'post_tag'
		];
	}

	/**
	 * Remove meta boxes.
	 *
	 * @return array
	 */
	public function remove() {
		return ['editor', 'commentsdiv', 'commentstatusdiv', 'authordiv', 'slugdiv'];
	}

	/**
	 * Define our properties.
	 */
	public function register() {
		$this->box( papi_template( __DIR__ . '/../page-types/boxes/properties.php' ) );
	}
}

Update properties taxonomy type meta data


<?php

namespace Illuminate\Http\Resources;

use JsonSerializable;
use Illuminate\Support\Collection;

class MergeValue
{
    /**
     * The data to be merged.
     *
     * @var array
     */
    public $data;

    /**
     * Create new merge value instance.
     *
     * @param  \Illuminate\Support\Collection|JsonSerializable|array  $data
     * @return void
     */
    public function __construct($data)
    {
        if ($data instanceof Collection) {
            $this->data = $data->all();
        } elseif ($data instanceof JsonSerializable) {
            $this->data = $data->jsonSerialize();
        } else {
            $this->data = $data;
        }
    }
}

<?php

namespace Illuminate\Http\Resources;

use JsonSerializable;
use Illuminate\Support\Collection;

class MergeValue
{
    /**
     * The data to be merged.
     *
     * @var array
     */
    public $data;

    /**
     * Create new merge value instance.
     *
     * @param  \Illuminate\Support\Collection|\JsonSerializable|array  $data
     * @return void
     */
    public function __construct($data)
    {
        if ($data instanceof Collection) {
            $this->data = $data->all();
        } elseif ($data instanceof JsonSerializable) {
            $this->data = $data->jsonSerialize();
        } else {
            $this->data = $data;
        }
    }
}

Add leading slash to `JsonSerializable` on docblock

Co-Authored-By: rodrigopedra <9ab0a48cbad7071f1c06b52d0c74cf226c5339e9@gmail.com>


<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) 2015 David Yang <daworld.ny@gmail.com>
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Validate\Input\Constraint;

final class Uppercase extends AbstractConstraint
{
	/**
	 * Target charset
	 *
	 * @var string
	 */
	private $charset;

	/**
	 * {@inheritDoc}
	 */
	protected $message = 'A string must be in uppercase';

	/**
	 * State initialization
	 *
	 * @param string $charset
	 * @return void
	 */
	public function __construct($charset = 'UTF-8')
	{
		$this->charset = $charset;
	}

	/**
	 * {@inheritDoc}
	 */
	public function isValid($target)
	{
		if (mb_strtouuper($target, $this->charset) === $target) {
			return true;
		} else {
			$this->violate($this->message);
			return false;
		}
	}
}

<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) 2015 David Yang <daworld.ny@gmail.com>
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Validate\Input\Constraint;

final class Uppercase extends AbstractConstraint
{
	/**
	 * {@inheritDoc}
	 */
	protected $message = 'A string must be in uppercase';

	/**
	 * {@inheritDoc}
	 */
	public function isValid($target)
	{
		if (mb_strtouuper($target, 'UTF-8') === $target) {
			return true;
		} else {
			$this->violate($this->message);
			return false;
		}
	}
}

Remove ability to set different charset

Remove ability to set different charset


<?php

/*
 * Copyright © 2017 Jesse Nicholson
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

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

/**
 * This table manages groups, to which users and filtering data can be assigned.
 * Users that belong to a group are able to pull data assigned to that group,
 * and use it in-application client side.
 */
class CreateGroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->bigIncrements('id');

            // Name of the group.
            $table->string('name');

            // The app config for users in this group.
            $table->mediumText('app_cfg');

            // The sha1 sum of the group's current data payload.
            $table->char('data_sha1', 40);

            // Whether or not the group is activated.
            $table->boolean('isactive');

            // Created at/modified at.
            $table->timestamps();
        });
    }

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

<?php

/*
 * Copyright © 2017 Jesse Nicholson
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

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

/**
 * This table manages groups, to which users and filtering data can be assigned.
 * Users that belong to a group are able to pull data assigned to that group,
 * and use it in-application client side.
 */
class CreateGroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->bigIncrements('id');

            // Name of the group.
            $table->string('name');

            // The app config for users in this group.
            $table->mediumText('app_cfg');

            // The sha1 sum of the group's current data payload.
            $table->char('data_sha1', 40)->default('');

            // Whether or not the group is activated.
            $table->boolean('isactive')->default(true);

            // Created at/modified at.
            $table->timestamps();
        });
    }

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

Set defaults on group table

Set defaults on group table

Fixes #6


<?php

namespace Napp\Core\Api\Exceptions\Exceptions;

use Symfony\Component\HttpFoundation\Response;

class ApiInternalCallException extends \RuntimeException
{
    /**
     * @var Response
     */
    protected $response;

    /**
     * @var string
     */
    protected $exceptionMessage;

    /**
     * @param Response $response
     * @param string $message
     */
    public function __construct(Response $response, $message = 'There was an error while processing your request')
    {
        $this->response = $response;
        $this->exceptionMessage = $message;
    }

    /**
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }

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

<?php

namespace Napp\Core\Api\Exceptions\Exceptions;

use Symfony\Component\HttpFoundation\Response;

class ApiInternalCallException extends \RuntimeException
{
    /**
     * @var Response
     */
    protected $response;

    /**
     * @var string
     */
    protected $exceptionMessage;

    /**
     * @var \Exception
     */
    protected $previousException;

    /**
     * @param Response $response
     * @param string $message
     */
    public function __construct(Response $response, $message = 'There was an error while processing your request')
    {
        $this->response = $response;
        $this->exceptionMessage = $message;
        $this->message = $message;
        $this->previousException = $response->exception;
    }

    /**
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }

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

    /**
     * @return \Exception
     */
    public function getPreviousException()
    {
        return $this->previousException;
    }
}

Improve the internalCallException to use Exception chaining


<?php
/*
 * Copyright (c) 2014-2016 Nicolas Braquart
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
$autoloader = require dirname(__DIR__) . '/vendor/autoload.php';

return $autoloader;

<?php

/*
 * Copyright (c) 2014-2016 Nicolas Braquart
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

$autoloader = require dirname(__DIR__) . '/vendor/autoload.php';
$autoloader->add('Ngames\\', __DIR__);

return $autoloader;

Add namespace for test autoloader

Add namespace for test autoloader

Useful to allow loading of classes in test package that are not test
cases (mocks, dummy implementations, etc.).


<?php

namespace N98\Magento\Command\Cache;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class FlushCommand extends AbstractCacheCommand
{
    protected function configure()
    {
        $this
            ->setName('cache:flush')
            ->setDescription('Flush magento cache storage')
        ;
    }

    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return int|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->detectMagento($output, true);
        if ($this->initMagento()) {

            \Mage::app()->loadAreaPart(\Mage_Core_Model_App_Area::AREA_ADMINHTML, \Mage_Core_Model_App_Area::PART_EVENTS);
            \Mage::dispatchEvent('adminhtml_cache_flush_all', array('output' => $output));
            \Mage::app()->getCacheInstance()->flush();
            $output->writeln('<info>Cache cleared</info>');

            if ($this->_magentoEnterprise) {
                \Enterprise_PageCache_Model_Cache::getCacheInstance()->flush();
                $output->writeln('<info>FPC cleared</info>');
            }

        }
    }
}

<?php

namespace N98\Magento\Command\Cache;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class FlushCommand extends AbstractCacheCommand
{
    protected function configure()
    {
        $this
            ->setName('cache:flush')
            ->setDescription('Flush magento cache storage')
        ;
    }

    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return int|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->detectMagento($output, true);
        if ($this->initMagento()) {

            \Mage::app()->loadAreaPart('adminhtml', 'events');
            \Mage::dispatchEvent('adminhtml_cache_flush_all', array('output' => $output));
            \Mage::app()->getCacheInstance()->flush();
            $output->writeln('<info>Cache cleared</info>');

            if ($this->_magentoEnterprise) {
                \Enterprise_PageCache_Model_Cache::getCacheInstance()->flush();
                $output->writeln('<info>FPC cleared</info>');
            }

        }
    }
}

[BUGFIX] Build failed. Constants are not available in magento 1.4.2.0


<?php
declare(strict_types=1);

namespace PerFi\Domain\Transaction;

use Ramsey\Uuid\Uuid;

class TransactionId
{
    /**
     * @var Uuid
     */
    private $id;

    /**
     * Create an transaction ID
     *
     * @param Uuid $id
     */
    private function __construct(Uuid $id)
    {
        $this->id = $id;
    }

    /**
     * Create an transaction ID from an UUID
     *
     * @param Uuid $id
     * @return TransactionId
     */
    public static function fromUuid(Uuid $id) : self
    {
        return new self($id);
    }

    /**
     * String representation of the transaction ID
     *
     * @return string
     */
    public function __toString() : string
    {
        return (string) $this->id;
    }
}

<?php
declare(strict_types=1);

namespace PerFi\Domain\Transaction;

use Ramsey\Uuid\Uuid;

class TransactionId
{
    /**
     * @var Uuid
     */
    private $id;

    /**
     * Create an transaction ID
     *
     * @param Uuid $id
     */
    private function __construct(Uuid $id)
    {
        $this->id = $id;
    }

    /**
     * Create an transaction ID from an UUID
     *
     * @param Uuid $id
     * @return TransactionId
     */
    public static function fromUuid(Uuid $id) : self
    {
        return new self($id);
    }

    /**
     * Create a transaction ID from a string UUID
     *
     * @param string $id
     * @return AccountId
     */
    public static function fromString(string $id) : self
    {
        return new self(
            Uuid::fromString($id)
        );
    }

    /**
     * String representation of the transaction ID
     *
     * @return string
     */
    public function __toString() : string
    {
        return (string) $this->id;
    }
}


<?php
namespace Concrete\Controller\SinglePage\Dashboard\System\Conversations;
use \Concrete\Core\Page\Controller\DashboardPageController;
use Loader;
use \Concrete\Core\Conversation\Rating\Type as ConversationRatingType;

class Points extends DashboardPageController
{
    public function view()
    {
        $ratingTypes = array_reverse(ConversationRatingType::getList());
        $this->set('ratingTypes', $ratingTypes);
    }
    public function success() {
        $this->view();
        $this->set('message', t('Rating type updated.'));
    }
    public function save() {
        $db = Loader::db();
        foreach (ConversationRatingType::getList() as $crt) {
            $rtID = $crt->getConversationRatingTypeID();
            $rtPoints = $this->post('rtPoints_' . $rtID);
            if (is_string($rtPoints) && is_numeric($rtPoints)) {
                $db->Execute('UPDATE ConversationRatingTypes SET cnvRatingTypeCommunityPoints = ? WHERE cnvRatingTypeID = ? LIMIT 1', array($rtPoints, $rtID));
            }
        }
        $this->redirect('/dashboard/system/conversations/points', 'success');
    }
}

<?php
namespace Concrete\Controller\SinglePage\Dashboard\System\Conversations;
use \Concrete\Core\Page\Controller\DashboardPageController;
use Loader;
use \Concrete\Core\Conversation\Rating\Type as ConversationRatingType;

class Points extends DashboardPageController
{
    public function view()
    {
        $ratingTypes = array_reverse(ConversationRatingType::getList());
        $this->set('ratingTypes', $ratingTypes);
    }
    public function success() {
        $this->view();
        $this->set('message', t('Rating types updated.'));
    }
    public function save() {
        $db = Loader::db();
        foreach (ConversationRatingType::getList() as $crt) {
            $rtID = $crt->getConversationRatingTypeID();
            $rtPoints = $this->post('rtPoints_' . $rtID);
            if (is_string($rtPoints) && is_numeric($rtPoints)) {
                $db->Execute('UPDATE ConversationRatingTypes SET cnvRatingTypeCommunityPoints = ? WHERE cnvRatingTypeID = ? LIMIT 1', array($rtPoints, $rtID));
            }
        }
        $this->redirect('/dashboard/system/conversations/points', 'success');
    }
}

Fix rating types updated message

Fix rating types updated message

Now we save all the rating types (before we were saving one type at once).


<?php

global $gds_image_licences;

$gds_image_licences = [
  'ogl' => 'OGL',
  'cc-by' => 'Attribution',
  'cc-by-sa' => 'Attribution-ShareAlike',
  'cc-by-nd' => 'Attribution-NoDerivs',
  'cc-by-nc' => 'Attribution-NonCommercial',
  'cc-by-nc-sa' => 'Attribution-NonCommercial-ShareAlike',
  'cc-by-nc-nd' => 'Attribution-NonCommercial-NoDerivs',
  'other' => 'Other',
];

add_filter('image_send_to_editor', function ($html, $id, $caption, $title, $align, $url, $size, $alt) {
  global $gds_image_licences;

  $_licence = get_post_meta($id, 'licence', true);
  $licence = $gds_image_licences[$_licence];
  $copyright_holder = get_post_meta($id, 'copyright_holder', true);
  $link_to_source = get_post_meta($id, 'link_to_source', true);

  $caption = 'Licence: '.esc_html($licence).' '.esc_html($copyright_holder).'';

  return '
'.$html.'
'.$caption.'

';
}, 10, 8);

<?php

global $gds_image_licences;

$gds_image_licences = [
  'ogl' => 'OGL',
  'cc-by' => 'Attribution',
  'cc-by-sa' => 'Attribution-ShareAlike',
  'cc-by-nd' => 'Attribution-NoDerivs',
  'cc-by-nc' => 'Attribution-NonCommercial',
  'cc-by-nc-sa' => 'Attribution-NonCommercial-ShareAlike',
  'cc-by-nc-nd' => 'Attribution-NonCommercial-NoDerivs',
  'other' => 'Other',
];

add_filter('image_send_to_editor', function ($html, $id, $caption, $title, $align, $url, $size, $alt) {
  global $gds_image_licences;

  $_licence = get_post_meta($id, 'licence', true);
  $licence = $gds_image_licences[$_licence];
  $copyright_holder = get_post_meta($id, 'copyright_holder', true);
  $link_to_source = get_post_meta($id, 'link_to_source', true);

  $caption = 'Licence: '.esc_html($licence).' '.esc_html($copyright_holder).'';

  return '
'.$html.'
'.$caption.'

';
}, 999, 8);

Add licencing info after captions

Add licencing info after captions


<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Testing\Fluent\AssertableJson;
use Tests\TestCase;

class SimpleRequestsTest extends TestCase
{
    /**
     * Test simple, non-CAS requests load without any authentication.
     */
    public function testUnauthenticatedRequests(): void
    {
        $response = $this->get('/privacy');
        $response->assertStatus(200);

        $response = $this->get('/attendance/kiosk');
        $response->assertStatus(200);
    }

    /**
     * Test that the home page loads successfully.
     */
    public function testHome(): void
    {
        $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/');
        $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent());

        $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/');
        $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent());
    }

    /**
     * Test the info endpoint.
     */
    public function testInfo(): void
    {
        $response = $this->get('/api/v1/info');
        $response->assertStatus(200);
        $response->assertJson(static function (AssertableJson $json): void {
            $json->where('status', 'success')
                 ->has('info', static function (AssertableJson $json): void {
                     $json->where('appName', 'TESTING Apiary')
                          ->where('appEnv', 'testing');
                 });
        });
    }
}

<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Testing\Fluent\AssertableJson;
use Tests\TestCase;

class SimpleRequestsTest extends TestCase
{
    /**
     * Test simple, non-CAS requests load without any authentication.
     */
    public function testUnauthenticatedRequests(): void
    {
        $this->withoutMix();

        $response = $this->get('/privacy');
        $response->assertStatus(200);

        $response = $this->get('/attendance/kiosk');
        $response->assertStatus(200);
    }

    /**
     * Test that the home page loads successfully.
     */
    public function testHome(): void
    {
        $this->withoutMix();

        $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/');
        $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent());

        $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/');
        $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent());
    }

    /**
     * Test the info endpoint.
     */
    public function testInfo(): void
    {
        $response = $this->get('/api/v1/info');
        $response->assertStatus(200);
        $response->assertJson(static function (AssertableJson $json): void {
            $json->where('status', 'success')
                 ->has('info', static function (AssertableJson $json): void {
                     $json->where('appName', 'TESTING Apiary')
                          ->where('appEnv', 'testing');
                 });
        });
    }
}

Disable Mix for page load tests

Disable Mix for page load tests


<?php namespace App\Exceptions;

use Exception;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }

}

<?php namespace App\Exceptions;

use Exception;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {

            return response()->json([ 'error' => [
                'message' => 'Resource Not Found!',
                'code'     => 404
                ]],404);
        }

        return parent::render($request, $e);
    }

}

Add ModelNotFound Exception in exception handler


<?php

/**
 * @file
 * Contains \Eloqua\HttpClient\Listener\ErrorListener.
 */

namespace Eloqua\HttpClient\Listener;

use Eloqua\HttpClient\Message\ResponseMediator;
use Guzzle\Common\Event;
use Guzzle\Http\Message\Response;

use Eloqua\Exception\ErrorException;
use Eloqua\Exception\RuntimeException;

class ErrorListener {
  /**
   * @var array
   */
  private $options;

  /**
   * @param array $options
   */
  public function __construct(array $options) {
    $this->options = $options;
  }

  /**
   * {@inheritDoc}
   */
  public function onRequestError(Event $event) {
    /** @var $request \Guzzle\Http\Message\Request */
    $request = $event['request'];
    $response = $request->getResponse();

    if ($response->isClientError() || $response->isServerError()) {
      $content = ResponseMediator::getContent($response);

      if (is_array($content)) {
        $error = $content[0];
        if (400 == $response->getStatusCode()) {
          throw new ErrorException(sprintf('%s - %s (%s)', $error['type'], $error['property'], $error['requirement']['type']), 400);
        }
      }
      else {
        throw new RuntimeException(json_encode($content), $response->getStatusCode());
      }
    }
  }
}

<?php

/**
 * @file
 * Contains \Eloqua\HttpClient\Listener\ErrorListener.
 */

namespace Eloqua\HttpClient\Listener;

use Eloqua\HttpClient\Message\ResponseMediator;
use Guzzle\Common\Event;
use Guzzle\Http\Message\Response;

use Eloqua\Exception\ErrorException;
use Eloqua\Exception\RuntimeException;

class ErrorListener {
  /**
   * @var array
   */
  private $options;

  /**
   * @param array $options
   */
  public function __construct(array $options) {
    $this->options = $options;
  }

  /**
   * {@inheritDoc}
   */
  public function onRequestError(Event $event) {
    /** @var $request \Guzzle\Http\Message\Request */
    $request = $event['request'];
    $response = $request->getResponse();

    if ($response->isClientError() || $response->isServerError()) {
      $content = ResponseMediator::getContent($response);

      if (is_array($content)) {
        $error = $content[0];
        if (400 == $response->getStatusCode()) {
          if (isset($error['property']) && isset($error['requirement'])) {
            throw new ErrorException(sprintf('%s - %s (%s)', $error['type'], $error['property'], $error['requirement']['type']), 400);
          }
          else {
            throw new ErrorException(sprintf('%s - %s', $error['type'], $error['message'] ? $error['message'] : json_encode($content)), 400);
          }
        }
      }
      else {
        throw new RuntimeException(json_encode($content), $response->getStatusCode());
      }
    }
  }
}

Update onRequestError for handling generic errors


<?php
namespace PureMachine\Bundle\WebServiceBundle\WebService;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use Symfony\Component\DependencyInjection\ContainerInterface;

class SymfonyBaseWebService extends BaseWebService implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container = null;

    /**
     * @InjectParams({
     *     "container" = @Inject("service_container")
     * })
     * @param  ContainerInterface $container
     * @return void
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Returns the symfony application container
     *
     * @return ContainerInteface
     */
    protected function getContainer()
    {
        return $this->container;
    }

    protected function get($service)
    {
        return $this->getContainer()->get($service);
    }

    protected function getManager()
    {
        return $this->getContainer()->get('doctrine.orm.entity_manager');
    }

    protected function getEntityManager()
    {
        return $this->getManager();
    }

    protected function getRepository($repo)
    {
        return $this->getContainer()->get('doctrine.orm.entity_manager')->getRepository($repo);
    }

}

<?php
namespace PureMachine\Bundle\WebServiceBundle\WebService;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use Symfony\Component\DependencyInjection\ContainerInterface;
use JMS\DiExtraBundle\Annotation\Service;// new Service() // PHP Bug

class SymfonyBaseWebService extends BaseWebService implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container = null;

    /**
     * @InjectParams({
     *     "container" = @Inject("service_container")
     * })
     * @param  ContainerInterface $container
     * @return void
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Returns the symfony application container
     *
     * @return ContainerInteface
     */
    protected function getContainer()
    {
        return $this->container;
    }

    protected function get($service)
    {
        return $this->getContainer()->get($service);
    }

    protected function getManager()
    {
        return $this->getContainer()->get('doctrine.orm.entity_manager');
    }

    protected function getEntityManager()
    {
        return $this->getManager();
    }

    protected function getRepository($repo)
    {
        return $this->getContainer()->get('doctrine.orm.entity_manager')->getRepository($repo);
    }

}

Add a 'use' statement for PHP 5.3 bug.

Add a 'use' statement for PHP 5.3 bug.


<?php

namespace Backend\Modules\Tags\Domain\ModuleTag;

use Backend\Modules\Tags\Domain\Tag\Tag;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="Backend\Modules\Tags\Domain\Tag\TagRepository")
 * @ORM\Table(name="TagsModuleTag", options={"collate"="utf8_general_ci", "charset"="utf8"})
 */
class ModuleTag
{
    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\Column(type="string")
     */
    private $moduleName;

    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    private $moduleId;

    /**
     * @var Tag
     *
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Backend\Modules\Tags\Domain\Tag\Tag", inversedBy="moduleTags")
     */
    private $tag;

    public function toArray(): array
    {
        return [
            'module' => $this->moduleName,
            'other_id' => $this->moduleId,
            'tag_id' => $this->tag->getId(),
        ];
    }
}

<?php

namespace Backend\Modules\Tags\Domain\ModuleTag;

use Backend\Modules\Tags\Domain\Tag\Tag;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="Backend\Modules\Tags\Domain\Tag\TagRepository")
 * @ORM\Table(name="TagsModuleTag", options={"collate"="utf8_general_ci", "charset"="utf8"})
 */
class ModuleTag
{
    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\Column(type="string")
     */
    private $moduleName;

    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    private $moduleId;

    /**
     * @var Tag
     *
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Backend\Modules\Tags\Domain\Tag\Tag", inversedBy="moduleTags")
     */
    private $tag;

    public function __construct(string $moduleName, int $moduleId, Tag $tag)
    {
        $this->moduleName = $moduleName;
        $this->moduleId = $moduleId;
        $this->tag = $tag;
    }

    public function toArray(): array
    {
        return [
            'module' => $this->moduleName,
            'other_id' => $this->moduleId,
            'tag_id' => $this->tag->getId(),
        ];
    }
}

Add constructor for module tags

Add constructor for module tags


@php
    //php here
@endphp

            <input name="notes_title" class="col-fluid {{ $errors->first('notes_title', 'error') }}"
                   placeholder="Add the title of the Note here.."
                   value="{{ old('notes_title', (isset($note->notes_title) ? $note->notes_title : '')) }}">

     <textarea name="{{ $notes['selector'] or "notes_content" }}" id="adv-notes" class="notes">{{ old('notes_content', (isset($note->notes_content) ? $note->notes_content : '')) }}</textarea>

        <button class="btn btn-lg btn-primary" type="submit">Save Note</button>

@push('scripts')
@include('notes::partials.smart-notes-js')
@endpush

@php
    //php here
@endphp

            <input type="text" name="notes_title" class="col-fluid {{ $errors->first('notes_title', 'error') }}"
                   placeholder="What the title of this note?"
                   value="{{ old('notes_title', (isset($note->notes_title) ? $note->notes_title : '')) }}">

     <textarea name="{{ $notes['selector'] or "notes_content" }}" id="adv-notes" class="notes">{!!  old('notes_content', (isset($note->notes_content) ? $note->notes_content : '')) !!}</textarea>

        <button class="btn btn-lg btn-primary" type="submit">Save Note</button>

@push('scripts')
@include('notes::partials.smart-notes-js')
@endpush

Change textarea vaule t output raw data

Change textarea vaule t output raw data


<?php
namespace Eusonlito\LaravelPacker;

use Illuminate\Support\ServiceProvider;

class PackerServiceProvider extends ServiceProvider
{
    /**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
    protected $defer = true;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../../config/config.php' => config_path('packer.php')
        ]);
    }

    /**
	 * Register the service provider.
	 *
	 * @return void
	 */
    public function register()
    {
        $this->app->singleton('packer', function($app) {
            return new Packer($this->config());
        });
    }

    /**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
    public function provides()
    {
        return ['packer'];
    }

    /**
     * Get the base settings from config file
     *
     * @return array
     */
    public function config()
    {
        $config = config('packer');

        if (empty($config['environment'])) {
            $config['environment'] = app()->environment();
        }

        $config['public_path'] = public_path();
        $config['asset'] = asset('');

        return $config;
    }
}

<?php
namespace Eusonlito\LaravelPacker;

use Illuminate\Support\ServiceProvider;

class PackerServiceProvider extends ServiceProvider
{
    /**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
    protected $defer = true;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../../config/config.php' => config_path('packer.php')
        ]);
    }

    /**
	 * Register the service provider.
	 *
	 * @return void
	 */
    public function register()
    {
        $this->app->singleton('packer', function($app) {
            return new Packer($this->config());
        });
    }

    /**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
    public function provides()
    {
        return ['packer'];
    }

    /**
     * Get the base settings from config file
     *
     * @return array
     */
    public function config()
    {
        $config = config('packer');

        if (empty($config['environment'])) {
            $config['environment'] = app()->environment();
        }

        if (empty($config['public_path'])) {
            $config['public_path'] = public_path();
        }

        if (empty($config['asset'])) {
            $config['asset'] = asset('');
        }

        return $config;
    }
}

Allow to overwrite default Laravel parameters


<?php

namespace Oro\Bundle\UIBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormView;

use Twig_Environment;

class BeforeListRenderEvent extends Event
{
    /**
     * @var \Twig_Environment
     */
    protected $environment;

    /**
     * @var array
     */
    protected $data;

    /**
     * @var FormView|null
     */
    protected $formView;

    /**
     * @param \Twig_Environment $environment
     * @param array $data
     * @param FormView $formView
     */
    public function __construct(Twig_Environment $environment, array $data, FormView $formView = null)
    {
        $this->formView    = $formView;
        $this->data        = $data;
        $this->environment = $environment;
    }

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

    /**
     * @return FormView
     */
    public function getFormView()
    {
        return $this->formView;
    }

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

    /**
     * @param array $data
     * @return BeforeListRenderEvent
     */
    public function setData(array $data)
    {
        $this->data = $data;

        return $this;
    }
}

<?php

namespace Oro\Bundle\UIBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormView;

use Twig_Environment;

class BeforeListRenderEvent extends Event
{
    /**
     * @var \Twig_Environment
     */
    protected $environment;

    /**
     * @var array
     */
    protected $data;

    /**
     * @var FormView|null
     */
    protected $formView;

    /**
     * @param \Twig_Environment $environment
     * @param array $data
     * @param FormView|null $formView
     */
    public function __construct(Twig_Environment $environment, array $data, FormView $formView = null)
    {
        $this->formView    = $formView;
        $this->data        = $data;
        $this->environment = $environment;
    }

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

    /**
     * @return FormView|null
     */
    public function getFormView()
    {
        return $this->formView;
    }

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

    /**
     * @param array $data
     * @return BeforeListRenderEvent
     */
    public function setData(array $data)
    {
        $this->data = $data;

        return $this;
    }
}

BB-562: Add possibility to inject code into forms and view templates

- CR fixes


<?php

/*
 * This file is part of the php-phantomjs.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JonnyW\PhantomJs\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;

/**
 * PHP PhantomJs
 *
 * @author Jon Wenmoth <contact@jonnyw.me>
 */
class ServiceContainer extends ContainerBuilder
{
    /**
     * Service container instance
     *
     * @var \JonnyW\PhantomJs\DependencyInjection\ServiceContainer
     * @access private
     */
    private static $instance;

    /**
     * Get singleton instance
     *
     * @access public
     * @return \JonnyW\PhantomJs\Client
     */
    public static function getInstance()
    {
        if (!self::$instance instanceof ServiceContainer) {

            self::$instance = new ServiceContainer();
            self::$instance->load();
        }

        return self::$instance;
    }

    /**
     * Load service container.
     *
     * @access public
     * @return void
     */
    public function load()
    {
        $loader = new YamlFileLoader($this, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('config.yml');
        $loader->load('services.yml');

        $this->setParameter('phantomjs.cache_dir', sys_get_temp_dir());
        $this->setParameter('phantomjs.resource_dir', __DIR__.'/../Resources');
    }
}

<?php

/*
 * This file is part of the php-phantomjs.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JonnyW\PhantomJs\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;

/**
 * PHP PhantomJs
 *
 * @author Jon Wenmoth <contact@jonnyw.me>
 */
class ServiceContainer extends ContainerBuilder
{
    /**
     * Service container instance
     *
     * @var static
     * @access private
     */
    private static $instance;

    /**
     * Get singleton instance
     *
     * @access public
     * @return static
     */
    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new static();

            $loader = new YamlFileLoader(self::$instance, new FileLocator(__DIR__.'/../Resources/config'));
            $loader->load('config.yml');
            $loader->load('services.yml');

            self::$instance->setParameter('phantomjs.cache_dir', sys_get_temp_dir());
            self::$instance->setParameter('phantomjs.resource_dir', __DIR__.'/../Resources');
        }

        return self::$instance;
    }
}

Remove wrongly overridden "load()" method but preserve the logic


<?php

use Phinx\Migration\AbstractMigration;

class InvPrices extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     */
    public function change()
    {
        $invPrices = $this->table("invPrices", array("engine" => "TokuDB"));
        $invPrices
            ->addColumn("typeID", "integer", array("limit" => 11))
            ->addColumn("price", "float", array("limit" => 255))
            ->addColumn("created", "datetime", array("default" => "CURRENT_TIMESTAMP"))
            ->addIndex(array("typeID"), array())
            ->save();
    }
}

<?php

use Phinx\Migration\AbstractMigration;

class InvPrices extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     */
    public function change()
    {
        $invPrices = $this->table("invPrices", array("engine" => "TokuDB"));
        $invPrices
            ->addColumn("typeID", "integer", array("limit" => 11))
            ->addColumn("avgSell", "float", array("limit" => 255))
            ->addColumn("avgBuy", "float", array("limit" => 255))
            ->addColumn("lowSell", "float", array("limit" => 255))
            ->addColumn("lowBuy", "float", array("limit" => 255))
            ->addColumn("highSell", "float", array("limit" => 255))
            ->addColumn("highBuy", "float", array("limit" => 255))
            ->addColumn("created", "datetime", array("default" => "CURRENT_TIMESTAMP"))
            ->addIndex(array("typeID"), array())
            ->save();
    }
}

Fix the invPrices table to actually contain the needed data..


@extends('layouts.app')

@section('content')
    <form action="{{ route('domain.store') }}" method="post">

                Domain Name:
                <input class="form-control" id="domain_name" name="domain_name" type="text">

                <input id="is_word_press" name="is_word_press" type="checkbox">  Is this a WordPress site?

                <button type="submit" class="btn btn-success">Register Site</button>

    </form>
@endsection

@extends('layouts.app')

@section('content')
    <form action="{{ route('domain.store') }}" method="post">
        <input type="hidden" id="_token" name="_token" value="{{ csrf_token() }}">

                Domain Name:
                <input class="form-control" id="domain_name" name="domain_name" type="text">

                <input id="is_word_press" name="is_word_press" type="checkbox">  Is this a WordPress site?

                <button type="submit" class="btn btn-success">Register Site</button>

    </form>
@endsection

Add CSRF token to domain-creating form and add spacers.


<?php
class Kwf_View_Helper_FileSize
{
    public static function fileSize($filesize)
    {
        if (!is_int($filesize) && file_exists($filesize)) {
            $filesize = filesize($filesize);
        }

        $shortcuts = array("Bytes", "KB", "MB", "GB", "TB", "PB");

        $i = 0;
        while ($filesize > 1024 && isset($shortcuts[$i+1])) {
            $filesize = $filesize / 1024;
            $i++;
        }

        if ($filesize < 10) {
            $ret = number_format($filesize, 1, ",", ".");
        } else {
            $ret = number_format($filesize, 0, ",", ".");
        }

        $ret .= ' '.$shortcuts[$i];
        return $ret;
    }
}

<?php
class Kwf_View_Helper_FileSize
{
    public function fileSize($filesize)
    {
        if (!is_int($filesize) && file_exists($filesize)) {
            $filesize = filesize($filesize);
        }

        $shortcuts = array("Bytes", "KB", "MB", "GB", "TB", "PB");

        $i = 0;
        while ($filesize > 1024 && isset($shortcuts[$i+1])) {
            $filesize = $filesize / 1024;
            $i++;
        }

        if ($filesize < 10) {
            $ret = number_format($filesize, 1, ",", ".");
        } else {
            $ret = number_format($filesize, 0, ",", ".");
        }

        $ret .= ' '.$shortcuts[$i];
        return $ret;
    }
}

Revert "Function is used statically, changed function definition to fix error"

This reverts commit d4bfa121e6a028f0a8d239e8a4806e44b553e737.


<?php

class Sign2pay_Payment_Model_Sign2pay extends Mage_Payment_Model_Method_Abstract
{
    protected $_code = 'sign2pay';
    protected $_formBlockType = 'sign2pay/form_sign2pay';
    protected $_infoBlockType = 'sign2pay/info_sign2pay';
    protected $_isInitializeNeeded      = true;
    protected $_canUseInternal          = true;
    protected $_canUseForMultishipping  = false;

    public function getOrderPlaceRedirectUrl()
    {
        $session = Mage::getSingleton('checkout/session');
        $order = Mage::getModel('sales/order')->loadByIncrementId($session->getLastRealOrderId());

        Mage::helper('sign2pay')->setStatusOnOrder(
            $order, Mage::getStoreConfig('payment/sign2pay/order_status', Mage::app()->getStore()));

        //return Mage::getModel('sign2pay/processor')->_verifyResponse('5648f8b20652686ecf0003e5');
        //return Mage::getModel('sign2pay/processor')->processPaymentCaptureResponse(array('purchase_id' => '5649a6a90652686ecf000638'));
        return Mage::helper('sign2pay')->getSign2PayInitialRequest();
    }

    /**
     * Check method for processing with base currency
     *
     * @param string $currencyCode
     * @return boolean
     */
    public function canUseForCurrency($currencyCode)
    {
        return $currencyCode == 'EUR';
    }
}

<?php

class Sign2pay_Payment_Model_Sign2pay extends Mage_Payment_Model_Method_Abstract
{
    protected $_code = 'sign2pay';
    protected $_formBlockType = 'sign2pay/form_sign2pay';
    protected $_infoBlockType = 'sign2pay/info_sign2pay';
    protected $_isInitializeNeeded      = true;
    protected $_canUseInternal          = true;
    protected $_canUseForMultishipping  = false;

    public function getOrderPlaceRedirectUrl()
    {
        $session = Mage::getSingleton('checkout/session');
        $order = Mage::getModel('sales/order')->loadByIncrementId($session->getLastRealOrderId());

        Mage::helper('sign2pay')->setStatusOnOrder(
            $order, Mage::getStoreConfig('payment/sign2pay/order_status', Mage::app()->getStore()));
        $order->save();

        //return Mage::getModel('sign2pay/processor')->_verifyResponse('5648f8b20652686ecf0003e5');
        //return Mage::getModel('sign2pay/processor')->processPaymentCaptureResponse(array('purchase_id' => '5649a6a90652686ecf000638'));
        return Mage::helper('sign2pay')->getSign2PayInitialRequest();
    }

    /**
     * Check method for processing with base currency
     *
     * @param string $currencyCode
     * @return boolean
     */
    public function canUseForCurrency($currencyCode)
    {
        return $currencyCode == 'EUR';
    }
}

Add missing order save after state change before payment redirect


<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ $title }}</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
    <meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}">

    @foreach ($styles as $file)
      <link rel="stylesheet" href="{{ str_replace(public_path(), '', $file) }}">
    @endforeach

    {!! $head !!}

    {!! $layout !!}

    @if (! $noJs)
        @foreach ($scripts as $file)

        @endforeach

    @endif

    {!! $foot !!}

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ $title }}</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
    <meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}">

    @foreach ($styles as $file)
      <link rel="stylesheet" href="{{ $forum->attributes->baseUrl . str_replace(public_path(), '', $file) }}">
    @endforeach

    {!! $head !!}

    {!! $layout !!}

    @if (! $noJs)
        @foreach ($scripts as $file)

        @endforeach

    @endif

    {!! $foot !!}

Prepend base URL to assets

Prepend base URL to assets


<?php

namespace Bauhaus\Container;

require __DIR__ . '/../bootstrap.php';

class RegistrableContainerUserContext extends ContainerUserBaseContext
{
    /**
     * @When I register an item with label :label and value :value
     */
    public function iRegisterANewItemWithLabelAndValue($label, $value)
    {
        $this->container->register($label, $value);
    }

    /**
     * @When I try to register an item with label :label already taken
     */
    public function iTryToRegisterAnItemWithLabelAndValue($label)
    {
        try {
            $this->container->register($label, 'someValue');
        } catch (\Exception $e) {
            $this->outcome = $e;
        }
    }
}

<?php

namespace Bauhaus\Container;

require __DIR__ . '/../bootstrap.php';

class RegistrableContainerUserContext extends ContainerUserBaseContext
{
    /**
     * @When I register an item with label :label and value :value
     */
    public function iRegisterANewItemWithLabelAndValue($label, $value)
    {
        $this->container->register($label, $value);
    }

    /**
     * @When I try to register an item with label :label already taken
     */
    public function iTryToRegisterAnItemWithLabelAlreadyTaken($label)
    {
        try {
            $this->container->register($label, 'someValue');
        } catch (\Exception $e) {
            $this->outcome = $e;
        }
    }
}

Fix name of step method of a behat test

Fix name of step method of a behat test


<?php

namespace App\Http\Middleware;

use Closure;

use App\IpBlacklist;
use Log;

class IPBasedBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        /*$blacklist = IpBlacklist
                ::where('ip_address', $ip)
                ->first();*/

        $blacklistedIps = explode(',', env('BLACKLISTED_IPS', ''));

        if (!in_array($ip, $blacklistedIps)) {
            return $next($request);
        }

        Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), $blacklist->reason));
        abort(503);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;

use App\IpBlacklist;
use Log;

class IPBasedBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        /*$blacklist = IpBlacklist
                ::where('ip_address', $ip)
                ->first();*/

        $blacklistedIps = explode(',', env('BLACKLISTED_IPS', ''));

        if (!in_array($ip, $blacklistedIps)) {
            return $next($request);
        }

        Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), 'Not set.'));
        abort(503);
    }
}

Fix reason for logging blacklist

Fix reason for logging blacklist


<?php
class Kwc_Root_Category_Trl_Update_20151116UpdatePageNames extends Kwf_Update
{
    public function update()
    {
        $root = Kwf_Component_Data_Root::getInstance();
        $model = Kwf_Model_Abstract::getInstance('Kwc_Root_Category_Trl_GeneratorModel');
        $select = $model->select()->where(new Kwf_Model_Select_Expr_Like('filename', '%_%'));
        foreach ($model->getRows($select) as $row) {
            if ($root->getComponentById($row->component_id, array('ignoreVisible' => true))) {
                $row->save();
            }
        }
    }
}

<?php
class Kwc_Root_Category_Trl_Update_20151116UpdatePageNames extends Kwf_Update
{
    public function postUpdate()
    {
        $root = Kwf_Component_Data_Root::getInstance();
        $model = Kwf_Model_Abstract::getInstance('Kwc_Root_Category_Trl_GeneratorModel');
        $select = $model->select()->where(new Kwf_Model_Select_Expr_Like('filename', '%_%'));
        foreach ($model->getRows($select) as $row) {
            if ($root->getComponentById($row->component_id, array('ignoreVisible' => true))) {
                $row->save();
            }
        }
    }
}

Move to postUpdate, like in non-trl

Move to postUpdate, like in non-trl


<?php

class EnsureIndexes extends Seeder
{
  public function run()
  {
    Log::ensureIndex(array(
      'text' => 'text'
    ));
  }
}

<?php

class EnsureIndexes extends Seeder
{
  public function run()
  {
    Log::ensureIndex(array(
      'text' => 'text',
      'time' => 1,
    ));
  }
}

Add index on time field

Add index on time field


<?php

namespace Oro\Bundle\CurrencyBundle\Provider;

use Oro\Bundle\OrganizationBundle\Entity\Organization;

interface RepositoryCurrencyProviderInterface
{
    /**
     * Returns list of unique currency codes from entity that contains multi-currency fields
     *
     * @param Organization|null $organization
     * @return string[]
     */
    public function getCurrencyList(Organization $organization = null);
}

<?php

namespace Oro\Bundle\CurrencyBundle\Provider;

use Oro\Bundle\OrganizationBundle\Entity\Organization;

interface RepositoryCurrencyProviderInterface
{
    /**
     * Return translated label of entity
     *
     * @return string
     */
    public function getEntityLabel();

    /**
     * @param array             $availableCurrencies
     * @param Organization|null $organization
     *
     * @return bool
     */
    public function hasRecordsInUnavailableCurrencies(
        array $availableCurrencies,
        Organization $organization = null
    );
}

OEE-1164: Add multi-curency validator to available currency form


<?php
use Symfony\Component\HttpKernel\Kernel;
use Doctrine\Common\Annotations\AnnotationRegistry;

abstract class Kwf_SymfonyKernel extends Kernel
{
    public function __construct()
    {
        $env = Kwf_Config::getValue('symfony.environment');
        if (in_array($env, array('test', 'dev'))) {
            $environment = $env;
            $debug = true;
            //Debug::enable();
        } else {
            $environment = 'prod';
            $debug = false;
        }
        parent::__construct($environment, $debug);

        AnnotationRegistry::registerLoader(array('Kwf_Loader', 'loadClass'));
    }

    public function locateResource($name, $dir = null, $first = true)
    {
        if (substr($name, 0, 4) == '@Kwc') {
            if (!$first) throw new \Kwf_Exception_NotYetImplemented();
            $componentClass = substr($name, 4, strpos($name, '/')-4);
            $name = substr($name, strpos($name, '/')+1);
            $paths = \Kwc_Abstract::getSetting($componentClass, 'parentFilePaths');
            foreach ($paths as $path=>$cls) {
                if (file_exists($path.'/'.$name)) {
                    return $path.'/'.$name;
                }
            }
            throw new \Kwf_Exception();
        } else {
            return parent::locateResource($name, $dir, $first);
        }
    }

}

<?php
use Symfony\Component\HttpKernel\Kernel;
use Doctrine\Common\Annotations\AnnotationRegistry;

abstract class Kwf_SymfonyKernel extends Kernel
{
    private static $_instance;

    public function __construct()
    {
        $env = Kwf_Config::getValue('symfony.environment');
        if (in_array($env, array('test', 'dev'))) {
            $environment = $env;
            $debug = true;
            //Debug::enable();
        } else {
            $environment = 'prod';
            $debug = false;
        }
        parent::__construct($environment, $debug);

        AnnotationRegistry::registerLoader(array('Kwf_Loader', 'loadClass'));
    }

    public function locateResource($name, $dir = null, $first = true)
    {
        if (substr($name, 0, 4) == '@Kwc') {
            if (!$first) throw new \Kwf_Exception_NotYetImplemented();
            $componentClass = substr($name, 4, strpos($name, '/')-4);
            $name = substr($name, strpos($name, '/')+1);
            $paths = \Kwc_Abstract::getSetting($componentClass, 'parentFilePaths');
            foreach ($paths as $path=>$cls) {
                if (file_exists($path.'/'.$name)) {
                    return $path.'/'.$name;
                }
            }
            throw new \Kwf_Exception();
        } else {
            return parent::locateResource($name, $dir, $first);
        }
    }

    /**
     * Don't use this method in Symfony context
     */
    public static function getInstance()
    {
        if (!isset(self::$_instance)) {
            $cls = Kwf_Config::getValue('symfony.kernelClass');
            self::$_instance = new $cls();
            self::$_instance->boot(); //make sure it is booted (won't do it twice)
        }
        return self::$_instance;
    }
}

Add getInstance method for symfony kernel

this allows us using symfony services everywhere.


<?php

namespace Plinth\Entity;

use Plinth\Connector;
use Plinth\Exception\PlinthException;

class EntityRepository extends Connector
{
	/**
	 * @var EntityRepository[]
	 */
	private $repositories;

	/**
	 * @param $fqcn
	 * @return EntityRepository
	 * @throws PlinthException
	 */
	public function getRepository($fqcn)
	{
		if (!in_array(self::class, class_parents($fqcn))) {
			$fqcn .= 'Repository'; // Legacy check
			if (!in_array(self::class, class_parents($fqcn))) {
				throw new PlinthException("Your repository, $fqcn, must extend " . self::class);
			}
		}

		if (!isset($this->repositories[$fqcn])) {
			$this->repositories[$fqcn] = new $fqcn($this->main);
		}

		return $this->repositories[$fqcn];
	}
}

<?php

namespace Plinth\Entity;

use Plinth\Connector;
use Plinth\Exception\PlinthException;

class EntityRepository extends Connector
{
	/**
	 * @var EntityRepository[]
	 */
	private $repositories;

	/**
	 * @param $fqcn
	 * @return EntityRepository
	 * @throws PlinthException
	 */
	public function getRepository($fqcn)
	{
		$fqcnLegacy = $fqcn . 'Repository';
		if (class_exists($fqcnLegacy)) {
			$fqcn = $fqcnLegacy;
		} elseif (!class_exists($fqcn)) {
			throw new PlinthException("Your repository, $fqcn, cannot be found.");
		}

		if (!in_array(self::class, class_parents($fqcn))) {
			throw new PlinthException("Your repository, $fqcn, must extend " . self::class . ".");
		}

		if (!isset($this->repositories[$fqcn])) {
			$this->repositories[$fqcn] = new $fqcn($this->main);
		}

		return $this->repositories[$fqcn];
	}
}

Fix for new entity repository implementation


<?php

use Rudolf\Component\Routing;
use Rudolf\Component\Modules;

$module = new Modules\Module('dashboard');
$config = $module->getConfig();

$collection->add('user/login', new Routing\Route(
    'user/login(/redirect-to/<page>)?',
    'Rudolf\Modules\Users\Login\Controller::login',
    array( // wyrazenia regularne dla parametrow
        'page' => '.*$',
    ),
    array( // wartosci domyslne
        'page' => 'dashboard',
    )
));

$collection->add('user/logout', new Routing\Route(
    'user/logout',
    'Rudolf\Modules\Users\Login\Controller::logout'
));

$collection->add('user/profile', new Routing\Route(
    'user/profile',
    'Rudolf\Modules\Users\Profile\Controller::profile'
));

<?php

use Rudolf\Component\Routing\Route;

$collection->add('user/login', new Route(
    'user/login(/redirect-to/<page>)?',
    'Rudolf\Modules\Users\Login\Controller::login',
    ['page' => '.*$'],
    ['page' => 'dashboard']
));

$collection->add('user', new Route(
    'user([\/])?',
    'Rudolf\Modules\Users\Profile\Controller::redirectTo',
    [],
    ['target' => DIR.'/user/profile']
));
$collection->add('user/logout', new Route(
    'user/logout',
    'Rudolf\Modules\Users\Login\Controller::logout'
));
$collection->add('user/profile', new Route(
    'user/profile',
    'Rudolf\Modules\Users\Profile\Controller::profile'
));

Add redirectTo - user -> user/profile

Add redirectTo - user -> user/profile


<?php

declare(strict_types=1);

namespace mcordingley\Regression\Linkings;

use InvalidArgumentException;
use mcordingley\Regression\Helpers;

final class Logistic extends Linking
{
    public function delinearize(float $value): float
    {
        return 1.0 / (1.0 + exp(-$value));
    }

    public function linearize(float $value): float
    {
        if ($value <= 0 || $value >= 1) {
            throw new InvalidArgumentException('Unable to linearize values outside of the range (0, 1).');
        }

        return -log(1.0 / $value - 1.0);
    }

    public function loss(array $coefficients, array $observations, float $outcome, int $index): float
    {
        $hypothesis = $this->delinearize(Helpers::sumProduct($coefficients, $observations));
        $error = $outcome - $hypothesis;

        // 0.5 will maximize the gradient, since we're on the wrong side.
        if ($error < -0.5 || $error > 0.5) {
            $hypothesis = 0.5;
        }

        return -2 * $error * $hypothesis * (1.0 - $hypothesis) * $observations[$index];
    }
}

<?php

declare(strict_types=1);

namespace mcordingley\Regression\Linkings;

use InvalidArgumentException;
use mcordingley\Regression\Helpers;

final class Logistic extends Linking
{
    public function delinearize(float $value): float
    {
        return 1.0 / (1.0 + exp(-$value));
    }

    public function linearize(float $value): float
    {
        if ($value <= 0 || $value >= 1) {
            throw new InvalidArgumentException('Unable to linearize values outside of the range (0, 1).');
        }

        return -log(1.0 / $value - 1.0);
    }

    public function loss(array $coefficients, array $observations, float $outcome, int $index): float
    {
        $hypothesis = $this->delinearize(Helpers::sumProduct($coefficients, $observations));

        return -2.0 * ($outcome - $hypothesis) * $hypothesis * (1.0 - $hypothesis) * $observations[$index];
    }
}

Remove attempts to force corrections on the gradient.


<?php

/**
 * Description of DataChangeTrackService
 *
 * @author Stephen McMahon <stephen@silverstripe.com.au>
 */
class DataChangeTrackService {

	protected $dcr_cache = array();

	public function track(DataObject $object, $type = 'Change') {

		if (!isset($this->dcr_cache["{$object->ID}-{$object->Classname}"])) {
			$this->dcr_cache["{$object->ID}-{$object->Classname}"] = DataChangeRecord::create();
		}

		$this->dcr_cache["{$object->ID}-{$object->Classname}"]->track($object, $type);
	}
}

<?php

/**
 * Description of DataChangeTrackService
 *
 * @author Stephen McMahon <stephen@silverstripe.com.au>
 */
class DataChangeTrackService {

	protected $dcr_cache = array();

	public function track(DataObject $object, $type = 'Change') {

		if (!isset($this->dcr_cache["{$object->ID}-{$object->Classname}"])) {
			$this->dcr_cache["{$object->ID}-{$object->Classname}"] = DataChangeRecord::create();
		}

		$this->dcr_cache["{$object->ID}-{$object->Classname}"]->track($object, $type);
	}

	public function __toString() {
		return '';
	}
}

FIX Ensure that if the dataChangeTracker gets serialized, it can still be string converted later


<?php namespace Orchestra;

use \Closure, \IoC;

class Mail {

	/**
	 * Make a new Orchestra\Mail instance.
	 *
	 * <code>
	 * 		Orchestra\Mail::send('view.file', array(), function ($mail)
	 * 		{
	 * 			$mail->to('example@test.com', "Username")
	 * 				->subject("An awesome title")
	 * 				->send();
	 * 		});
	 * </code>
	 *
	 * @static
	 * @access public
	 * @param  string   $view
	 * @param  mixed    $data
	 * @param  Closure  $callback
	 * @return self
	 */
	public static function send($view, $data = array(), Closure $callback)
	{
		$instance = new static($view, $data, $callback);

		return $instance->mailer;
	}

	/**
	 * Swiftmailer mail instance.
	 *
	 * @var  Object
	 */
	private $mailer = null;

	/**
	 * Construct a new instance.
	 *
	 * @access public
	 * @param  string   $view
	 * @param  mixed    $data
	 * @param  Closure  $callback
	 * @return void
	 */
	public function __construct($view, $data = array(), Closure $callback)
	{
		$view         = View::make($view, $data);
		$this->mailer = IoC::resolve('orchestra.mailer');

		$this->mailer->body($view->render(), 'text/html');

		call_user_func($callback, $this->mailer);
	}
}

<?php namespace Orchestra;

use \Closure, \IoC;

class Mail {

	/**
	 * Make a new Orchestra\Mail instance.
	 *
	 * <code>
	 * 		Orchestra\Mail::send('view.file', array(), function ($mail)
	 * 		{
	 * 			$mail->to('example@test.com', "Username")
	 * 				->subject("An awesome title")
	 * 				->send();
	 * 		});
	 * </code>
	 *
	 * @static
	 * @access public
	 * @param  string   $view
	 * @param  mixed    $data
	 * @param  Closure  $callback
	 * @return self
	 */
	public static function send($view, $data = array(), Closure $callback)
	{
		$instance = new static($view, $data, $callback);

		return $instance->mailer;
	}

	/**
	 * Swiftmailer mail instance.
	 *
	 * @var  Object
	 */
	private $mailer = null;

	/**
	 * Construct a new instance.
	 *
	 * @access public
	 * @param  string   $view
	 * @param  mixed    $data
	 * @param  Closure  $callback
	 * @return void
	 */
	public function __construct($view, $data = array(), Closure $callback)
	{
		$view         = View::make($view, $data);
		$this->mailer = IoC::resolve('orchestra.mailer');

		$this->mailer->body($view);
		$this->mailer->html(true);

		call_user_func($callback, $this->mailer);
	}
}

Update Orchestra\Mail to follow latest update on Messages bundle

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace Lily\Test\Application;

use Lily\Application\MiddlewareApplication;
use Lily\Mock\Application;
use Lily\Mock\Middleware;

class MiddlewareApplicationTest extends \PHPUnit_Framework_TestCase
{
    public function testMiddlewareOrder()
    {
        $expectedCalledOrder = array(1, 2, 3);
        $calledOrder = array();

        $handler =
            new MiddlewareApplication(array(
                new Application(function () use (& $calledOrder) {
                    $calledOrder[] = 3;
                }),
                new Middleware(function () use (& $calledOrder) {
                    $calledOrder[] = 2;
                }),
                new Middleware(function () use (& $calledOrder) {
                    $calledOrder[] = 1;
                }),
            ));
        $handler(array());

        $this->assertSame($expectedCalledOrder, $calledOrder);
    }

    public function testWithoutMiddleware()
    {
        $called = FALSE;

        $handler =
            new MiddlewareApplication(array(
                new Application(function () use (& $called) {
                    $called = TRUE;
                }),
            ));
        $handler(array());

        $this->assertTrue($called);
    }
}

<?php

namespace Lily\Test\Application;

use Lily\Application\MiddlewareApplication;

use Lily\Util\Response;

class MiddlewareApplicationTest extends \PHPUnit_Framework_TestCase
{
    public function testMiddlewareOrder()
    {
        $expectedCalledOrder = array(1, 2, 3);
        $calledOrder = array();

        $handler =
            new MiddlewareApplication(array(
                function ($request) use (& $calledOrder) {
                    $calledOrder[] = 3;
                    return Response::ok();
                },

                function ($handler) use (& $calledOrder) {
                    return function ($request) use ($handler, & $calledOrder) {
                        $calledOrder[] = 2;
                        return $handler($request);
                    };
                },

                function ($handler) use (& $calledOrder) {
                    return function ($request) use ($handler, & $calledOrder) {
                        $calledOrder[] = 1;
                        return $handler($request);
                    };
                },
            ));
        $handler(array());

        $this->assertSame($expectedCalledOrder, $calledOrder);
    }

    public function testWithoutMiddleware()
    {
        $called = FALSE;

        $handler =
            new MiddlewareApplication(array(
                function () use (& $called) {
                    $called = TRUE;
                },
            ));
        $handler(array());

        $this->assertTrue($called);
    }
}

Remove use of mocks since we can use functions on their own now


<?php
/**
 * Created by PhpStorm.
 * User: bmeism
 * Date: 13.05.2015
 * Time: 16:44
 */

namespace ThePost\Controller\Output;

use ThePost\View\EntryErrorView;
use ThePost\View\EntryView;

/**
 * Class MainController
 * @package ThePost\Controller
 */
class EntryController extends MainController
{
    /**
     * @param $param
     */
    public function index($param)
    {
        $stmt = $this->model->pdo->prepare('SELECT * FROM Entry WHERE id=:param OR slug=:param;');
        $stmt->bindValue(':param', (isset($param['slug']))?$param['slug']:$param['id']);
        $stmt->execute();
        if($stmt->rowCount()<1){
            $this->view = new EntryErrorView(array('msg' => (isset($param['slug']))?$param['slug']:$param['id']));
        }else{
            $entry = $stmt->fetchObject('ThePost\Model\Entity\Entry');
            $this->view = new EntryView($entry);
        }
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: bmeism
 * Date: 13.05.2015
 * Time: 16:44
 */

namespace ThePost\Controller\Output;

use ThePost\Model\Repository\EntryRepository;
use ThePost\View\EntryErrorView;
use ThePost\View\EntryView;

/**
 * Class MainController
 * @package ThePost\Controller
 */
class EntryController extends MainController
{
    /**
     * @param $input
     */
    public function index($input)
    {
        $param = (isset($input['slug'])) ? $input['slug'] : $input['id'];
        $entries_repository = new EntryRepository($this->model->pdo);
        if (!$entry = $entries_repository->findByParam($param)) {
            $this->view = new EntryErrorView(array('page' => $param, 'msg' => 'not found!'));
        } else {
            $this->view = new EntryView($entry);
        }
    }

}

Use EntryRepository Better error messages


<?php

namespace haqqi\storm;

use yii\base\Application;
use yii\base\BootstrapInterface;
use yii\base\Event;
use yii\console\Controller;
use yii\web\View;

class Bootstrap implements BootstrapInterface {

  public function bootstrap($app) {

    $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) {
      /**
       * @var $event Event
       */

      /*
       * Setup the config of asset bundles
       */
      if(!$event->action->controller instanceof Controller) {
        $bundles =& $event->sender->assetManager->bundles;

        $bundles['yii\web\JqueryAsset']['js']        = ['jquery.min.js'];
        $bundles['yii\web\JqueryAsset']['jsOptions'] = ['position' => View::POS_HEAD];

        $bundles['yii\bootstrap\BootstrapAsset']['css'] = ['css/bootstrap.min.css'];

        $bundles['yii\bootstrap\BootstrapPluginAsset']['js']        = ['js/bootstrap.min.js'];
        $bundles['yii\bootstrap\BootstrapPluginAsset']['jsOptions'] = ['position' => View::POS_HEAD];

        $bundles['mimicreative\assets\MetisMenuAsset']['css'] = [];

//        \FB::log($event->sender->assetManager->bundles);
      }
    });
  }

}

<?php

namespace haqqi\storm;

use yii\base\Application;
use yii\base\BootstrapInterface;
use yii\base\Event;
use yii\console\Controller;
use yii\web\View;

class Bootstrap implements BootstrapInterface {

  public function bootstrap($app) {

    $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) {
      /**
       * @var $event Event
       */

    \Yii::$container->set('yii\web\JqueryAsset', [
      'js' => ['jquery.min.js'],
      'jsOptions' => ['position' => View::POS_HEAD]
    ]);

    \Yii::$container->set('yii\bootstrap\BootstrapAsset', [
      'css' => ['css/bootstrap.min.css']
    ]);

    \Yii::$container->set('yii\bootstrap\BootstrapPluginAsset', [
      'js' => ['js/bootstrap.min.js'],
      'jsOptions' => ['position' => View::POS_HEAD]
    ]);

    \Yii::$container->set('mimicreative\assets\MetisMenuAsset', [
      'css' => []
    ]);

    });
  }

}

Fix DI container when using console controller


<?php // vim:ts=4:sw=4:et:fdm=marker

namespace atk4\core;

/**
 * All exceptions generated by Agile Toolkti will use this class
 *
 * @license MIT
 * @copyright Agile Toolkit (c) http://agiletoolkit.org/
 */
class Exception extends \Exception
{
    /**
     * Most exceptions would be a cause by some other exception, DSQL
     * will encapsulate them and allow you to access them anyway.
     */
    private $params = [];

    public function __construct(
        $message = "",
        $code = 0,
        \Throwable $previous = null
    ) {
        if (is_array($message)) {
            // message contain additional parameters
            $this->params = $message;
            $message = array_shift($this->params);
        }

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

    /**
     * Follow the getter-style of PHP Exception
     */
    public function getParams()
    {
        return $this->params;
    }
}

<?php // vim:ts=4:sw=4:et:fdm=marker

namespace atk4\core;

/**
 * All exceptions generated by Agile Toolkti will use this class
 *
 * @license MIT
 * @copyright Agile Toolkit (c) http://agiletoolkit.org/
 */
class Exception extends \Exception
{
    /**
     * Most exceptions would be a cause by some other exception, DSQL
     * will encapsulate them and allow you to access them anyway.
     */
    private $params = [];

    public function __construct(
        $message = "",
        $code = 0,
        \Exception $previous = null
    ) {
        if (is_array($message)) {
            // message contain additional parameters
            $this->params = $message;
            $message = array_shift($this->params);
        }

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

    /**
     * Follow the getter-style of PHP Exception
     */
    public function getParams()
    {
        return $this->params;
    }
}

Fix compatibilitp with PHP <7

Fix compatibilitp with PHP <7


<?php
/**
 * @author    USAMI Kenta
 * @copyright 2016 USAMI Kenta
 * @license   WTFPL
 */

/**
 * @return \PDO
 */
function db()
{
    static $db;

    if (!$db) {
        $db = new \PDO(getenv('DB_DSN'), null, null, [PDO::ATTR_PERSISTENT => true]);
    }

    return $db;
}

<?php
/**
 * @author    USAMI Kenta
 * @copyright 2016 USAMI Kenta
 * @license   WTFPL
 */

/**
 * @return \PDO
 */
function db()
{
    static $db;

    if (!$db) {
        $db = new \PDO(getenv('DB_DSN'), '', '', [PDO::ATTR_PERSISTENT => true]);
    }

    return $db;
}

Use '' instead of null

Use '' instead of null


<?php

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

require sprintf('%s/bootstrap.php', dirname(__DIR__));

use Kompakt\B3d\Details\Endpoint\Resource\Artist\Endpoint as ArtistEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Label\Endpoint as LabelEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Product\Endpoint as ProductEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\ProductTrack\Endpoint as ProductTrackEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Release\Endpoint as ReleaseEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Track\Endpoint as TrackEndpoint;

$endpoints = [
    new ArtistEndpoint($client),
    new LabelEndpoint($client),
    new ProductEndpoint($client),
    new ProductTrackEndpoint($client),
    new ReleaseEndpoint($client),
    new TrackEndpoint($client)
];

foreach ($endpoints as $endpoint)
{
    echo sprintf("%s\n", get_class($endpoint));

    foreach ($endpoint->fetchAll() as $item)
    {
        print_r($item);
        break;
    }
}

<?php

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

require sprintf('%s/bootstrap.php', dirname(__DIR__));

use Kompakt\B3d\Details\Endpoint\Resource\Artist\Endpoint as ArtistEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Label\Endpoint as LabelEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Product\Endpoint as ProductEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\ProductTrack\Endpoint as ProductTrackEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Release\Endpoint as ReleaseEndpoint;
use Kompakt\B3d\Details\Endpoint\Resource\Track\Endpoint as TrackEndpoint;

$endpoints = [
    new ArtistEndpoint($client),
    new LabelEndpoint($client),
    new ProductEndpoint($client),
    new ProductTrackEndpoint($client),
    new ReleaseEndpoint($client),
    new TrackEndpoint($client)
];

foreach ($endpoints as $endpoint)
{
    echo sprintf("%s\n", get_class($endpoint));

    foreach ($endpoint->fetchAll() as $item)
    {
        $fields = [];

        foreach ($item as $k => $v)
        {
            $fields[] = $k;
        }

        sort($fields, SORT_NATURAL);

        foreach ($fields as $field)
        {
            echo sprintf("+ %s\n", $field);
        }

        break;
    }
}

Sort fields in alphabetical order

Sort fields in alphabetical order


<?php
class UsersController extends AppController {

    public function index()
    {
        $this->loadModel('User');
//        $result = $this->User->find('count');

        $result = $this->User->getInfo();
        $this->set('data', $result);
    }
}

<?php
class UsersController extends AppController {

    public function index()
    {
        $this->loadModel('User');
//        $result = $this->User->find('count');

        $result = $this->User->getInfo();
        $this->set('data', $result);
    }

    public function form()
    {
        if($this->request->is('post')){
            $this->User->save($this->request->data);
        }
        $result = $this->User->getInfo();
        $this->set('data', $result);
    }
}

Save data to database whats are submitted by index.ctp form


<?php

class Sign2pay_Payment_Model_Observer
{
    /**
     * Modifies block html.
     *
     * @event core_block_abstract_to_html_after
     */
    public function afterBlockHtml($observer)
    {
        $block = $observer->getBlock();
        $transport = $observer->getTransport();

        if ($block instanceof Mage_Checkout_Block_Onepage_Shipping_Method_Available) {
            if (Mage::getModel('sign2pay/sign2pay')->isApplicableToQuote(
                    $block->getQuote(),
                    Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
                    | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
                    | Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX
                    | Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL
                ))
            {
                $html = '<script type="text/javascript">initializeRiskAssessment();</script>';
                $transport->setHtml($transport->getHtml() . $html);
            }
        }
    }
}

<?php

class Sign2pay_Payment_Model_Observer
{
    /**
     * Modifies block html.
     *
     * @event core_block_abstract_to_html_after
     */
    public function afterBlockHtml($observer)
    {
        $block = $observer->getBlock();
        $transport = $observer->getTransport();

        if ($block instanceof Mage_Checkout_Block_Onepage_Shipping_Method_Available) {
            $payment = Mage::getModel('sign2pay/sign2pay');

            if (method_exists($payment, 'isApplicableToQuote')) {
                try {
                    if ($payment->isApplicableToQuote(
                            $block->getQuote(),
                            Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
                            | Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
                            | Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX
                            | Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL
                        ))
                    {
                        $this->_addInitializeRiskAssessment($transport);
                    }
                } catch (Exception $e) {
                    // Add anyway
                    $this->_addInitializeRiskAssessment($transport);
                }
            } else {
                // Add anyway
                $this->_addInitializeRiskAssessment($transport);
            }
        }
    }

    /**
     * Add riska assessment trigger to transport
     */
    protected function _addInitializeRiskAssessment($transport)
    {
        $html = '<script type="text/javascript">if (typeof initializeRiskAssessment === \'function\') initializeRiskAssessment();</script>';
        $transport->setHtml($transport->getHtml() . $html);
    }
}

Fix observer compatybility for magento 1.7.0.2 or less


<?php
class Kwf_Controller_Action_Component_PreviewController extends Kwf_Controller_Action
{
    public function indexAction()
    {
        $this->view->config = Kwf_Registry::get('config')->preview->toArray();
        $this->view->xtype = 'kwf.component.preview';
        $this->view->initialUrl = $this->_getParam('url');
        if (!$this->view->initialUrl) {
            $this->view->initialUrl = 'http://'.$_SERVER['HTTP_HOST'].Kwf_Setup::getBaseUrl().'/';
        }
    }

    public function redirectAction()
    {
        Kwf_Util_Redirect::redirect($this->_getParam('url'));
    }
}

<?php
class Kwf_Controller_Action_Component_PreviewController extends Kwf_Controller_Action
{
    public function indexAction()
    {
        $this->view->config = Kwf_Registry::get('config')->preview->toArray();
        $this->view->xtype = 'kwf.component.preview';
        $this->view->initialUrl = null;
        if (preg_match('#^https?://#', $this->view->initialUrl)) {
            $this->view->initialUrl = $this->_getParam('url');
        }
        if (!$this->view->initialUrl) {
            $this->view->initialUrl = 'http://'.$_SERVER['HTTP_HOST'].Kwf_Setup::getBaseUrl().'/';
        }
    }

    public function redirectAction()
    {
        Kwf_Util_Redirect::redirect($this->_getParam('url'));
    }
}

Fix XSS Issue in preview

Fix XSS Issue in preview

fixes #337


							 IFSP

							 123 - CEP: 15161-216 - Telefone: +55 (16) 5122-0626

							 Desenvolvimento ACME & Brains Working

Add caminho do script js

Add caminho do script js


<?php

namespace webignition\CssValidatorWrapper\Configuration;

class VendorExtensionSeverityLevel {

    const LEVEL_ERROR = 'error';
    const LEVEL_WARN = 'warn';

    /**
     *
     * @var array
     */
    private static $validValues = array(
        self::LEVEL_ERROR,
        self::LEVEL_WARN
    );

    /**
     *
     * @param string $severityLevel
     * @return boolean
     */
    public static function isValid($severityLevel) {
        return in_array($severityLevel, self::$validValues);
    }

    /**
     *
     * @return array
     */
    public static function getValidValues() {
        return self::$validValues;
    }
}

<?php

namespace webignition\CssValidatorWrapper\Configuration;

class VendorExtensionSeverityLevel {

    const LEVEL_IGNORE = 'ignore';
    const LEVEL_ERROR = 'error';
    const LEVEL_WARN = 'warn';

    /**
     *
     * @var array
     */
    private static $validValues = array(
        self::LEVEL_ERROR,
        self::LEVEL_WARN,
        self::LEVEL_IGNORE
    );

    /**
     *
     * @param string $severityLevel
     * @return boolean
     */
    public static function isValid($severityLevel) {
        return in_array($severityLevel, self::$validValues);
    }

    /**
     *
     * @return array
     */
    public static function getValidValues() {
        return self::$validValues;
    }
}

Allow 'ignore' as valid vendor extension severity level


<?php

namespace Pinq;

/**
 * Enum for ordering direction
 *
 * @author Elliot Levin <elliot@aanet.com.au>
 */
final class Direction
{
    private function __construct()
    {

    }

    const ASCENDING = 1;
    const DESCENDING = 2;
}

<?php

namespace Pinq;

/**
 * Enum for ordering direction
 *
 * @author Elliot Levin <elliot@aanet.com.au>
 */
final class Direction
{
    private function __construct()
    {

    }

    const ASCENDING = SORT_ASC;
    const DESCENDING = SORT_DESC;
}

Redefine order direction constants as native sort constants for convenience


<?php
/**
 * Silktide Nibbler. Copyright 2013-2014 Silktide Ltd. All Rights Reserved.
 */
namespace Silktide\LazyBoy\Provider;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Enables application to handles CORS requests
 */
class JsonPostServiceProvider implements ServiceProviderInterface
{
    public function register(Container $app) {
        if ($app instanceof Application) {
            //accepting JSON

            $app->before(function (Request $request) {
                if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
                    $data = json_decode($request->getContent(), true);
                    $request->request->replace(is_array($data) ? $data : []);
                }
            });
        }
    }
}

<?php

namespace Silktide\LazyBoy\Provider;

use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Converts a request body to an array if it is in JSON format
 */
class JsonPostServiceProvider implements ServiceProviderInterface
{
    public function register(Container $app) {
        if ($app instanceof Application) {

            $app->before(function (Request $request) {
                // check if the content type is JSON
                if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
                    // decode and check for errors
                    $data = json_decode($request->getContent(), true);
                    if (empty($data) && json_last_error() != JSON_ERROR_NONE) {
                        return new Response('{"error": "The request body was not in JSON format"}');
                    }
                    // modify the request with the decoded data
                    $request->request->replace(is_array($data) ? $data : []);
                }
            }, Application::EARLY_EVENT + 1); // set priority to be almost always first to run
        }
    }
}

Add error checking to the JsonPost service provider after decoding request content


<?php

namespace Templates;

use \Diarmuidie\ImageRack\Image\TemplateInterface;

/**
 * Sample template to fit and image to 300px x 240px
 */
class Small implements TemplateInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(\Intervention\Image\Image $image)
    {
        $image->fit(320, 240);
        return $image;
    }
}

<?php

namespace Templates;

use \Diarmuidie\ImageRack\Image\TemplateInterface;

/**
 * Sample template to fit and image to 300px x 240px
 */
class Small implements TemplateInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(\Intervention\Image\Image $image)
    {
        $image->fit(320, 240);
        $image->encode();
        return $image;
    }
}

Move encode call to template

Move encode call to template


    @foreach($roles as $role)

            @include('components.custom-checkbox', [
                'name' => $name . '[' . $role->name . ']',
                'label' => $role->display_name,
                'value' => $role->id,
                'checked' => old($name . '.' . $role->name) || (!old('name') && isset($model) && $model->hasRole($role->name))
            ])

    @endforeach

@if($errors->has($name))

{{ $errors->first($name) }}

@endif

    @foreach($roles as $role)

            @include('components.custom-checkbox', [
                'name' => $name . '[' . str_replace('.', 'DOT', $role->name) . ']',
                'label' => $role->display_name,
                'value' => $role->id,
                'checked' => old($name . '.' . str_replace('.', 'DOT', $role->name)) || (!old('name') && isset($model) && $model->hasRole($role->name))
            ])

    @endforeach

@if($errors->has($name))

{{ $errors->first($name) }}

@endif

Replace dots with something else on user create and edit screens