<?php namespace Shanhaijing\SentryExt;

use Shanhaijing\SentryExt\Users\Eloquent\Provider as UserProvider;
use Cartalyst\Sentry\SentryServiceProvider;

class SentryExtServiceProvider extends SentryServiceProvider {

    protected function registerUserProvider()
    {
        $this->app['sentry.user'] = $this->app->share(function($app)
        {
            $model = $app['config']['cartalyst/sentry::users.model'];

            // We will never be accessing a user in Sentry without accessing
            // the user provider first. So, we can lazily setup our user
            // model's login attribute here. If you are manually using the
            // attribute outside of Sentry, you will need to ensure you are
            // overriding at runtime.
            if (method_exists($model, 'setLoginAttribute'))
            {
                $loginAttribute = $app['config']['cartalyst/sentry::users.login_attribute'];

                forward_static_call_array(
                    array($model, 'setLoginAttribute'),
                    array($loginAttribute)
                );
            }

            return new UserProvider($app['sentry.hasher'], $model);
        });
    }

}

<?php namespace Shanhaijing\SentryExt;

use Shanhaijing\SentryExt\Users\Eloquent\Provider as UserProvider;
use Cartalyst\Sentry\SentryServiceProvider;

class SentryExtServiceProvider extends SentryServiceProvider {

    protected function registerUserProvider()
    {
        $this->app['sentry.user'] = $this->app->share(function($app)
        {
            $model = $app['config']['cartalyst/sentry::users.model'];

            // We will never be accessing a user in Sentry without accessing
            // the user provider first. So, we can lazily setup our user
            // model's login attribute here. If you are manually using the
            // attribute outside of Sentry, you will need to ensure you are
            // overriding at runtime.
            if (method_exists($model, 'setLoginAttributeName')) {
                $loginAttribute = $app['config']['cartalyst/sentry::users.login_attribute'];

                forward_static_call_array(
                    array($model, 'setLoginAttributeName'),
                    array($loginAttribute)
                );
            }

            return new UserProvider($app['sentry.hasher'], $model);
        });
    }

}

Adjust function name for setLoginAttributeName.

This is not my fault, cause sentry changed this name.


<?php

/*
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Entities;

use Longman\TelegramBot\Exception\TelegramException;

class UserProfilePhotos extends Entity
{

    protected $total_count;
    protected $photos;

    public function __construct(array $data)
    {

        $this->total_count = isset($data['total_count']) ? $data['total_count'] : null;
        if (empty($this->total_count)) {
            throw new TelegramException('total_count is empty!');
        }
        $this->photos = isset($data['photos']) ? $data['photos'] : null;
        if (empty($this->photos)) {
            throw new TelegramException('photos is empty!');
        }

        $photos = [];
        foreach ($this->photos as $key => $photo) {
            if (is_array($photo)) {
                foreach ($photo as $photo_size) {
                    $photos[$key][] = new PhotoSize($photo_size);
                }
            } else {
                throw new TelegramException('photo is not an array!');
            }
        }

        $this->photos = $photos;
    }

    public function getTotalCount()
    {
        return $this->total_count;
    }

    public function getPhotos()
    {
        return $this->photos;
    }
}

<?php

/*
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Entities;

use Longman\TelegramBot\Exception\TelegramException;

class UserProfilePhotos extends Entity
{

    protected $total_count;
    protected $photos;

    public function __construct(array $data)
    {

        $this->total_count = isset($data['total_count']) ? $data['total_count'] : null;
        if ($this->total_count === null && !is_numeric($this->total_count) ) {
            throw new TelegramException('total_count is empty!');
        }
        $this->photos = isset($data['photos']) ? $data['photos'] : null;
        if ($this->photos === null || !is_array($data['photos']) ) {
            throw new TelegramException('photos is empty!');
        }

        $photos = [];
        foreach ($this->photos as $key => $photo) {
            if (is_array($photo)) {
                foreach ($photo as $photo_size) {
                    $photos[$key][] = new PhotoSize($photo_size);
                }
            } else {
                throw new TelegramException('photo is not an array!');
            }
        }

        $this->photos = $photos;
    }

    public function getTotalCount()
    {
        return $this->total_count;
    }

    public function getPhotos()
    {
        return $this->photos;
    }
}

Fix for /whoami with a user who doesn't have a profile picture


<?php
use \Entity\Station;
use \Entity\Song;
use \Entity\Schedule;

class Api_NowplayingController extends \PVL\Controller\Action\Api
{
    public function indexAction()
    {
        $file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json';
        $np_raw = file_get_contents($file_path_api);

        // Sanity check for now playing data.
        if (empty($np_raw))
        {
            $this->returnError('Now Playing data has not loaded into the cache. Wait for file reload.');
            return;
        }

        if ($this->hasParam('id') || $this->hasParam('station'))
        {
            $np_arr = @json_decode($np_raw, TRUE);
            $np = $np_arr['result'];

            if ($this->hasParam('id'))
            {
                $id = (int)$this->getParam('id');
                foreach($np as $key => $station) {
                    if($station->id === $id) {
                        $sc = $key;
                        break;
                    }
                }
                return $this->returnError('Station not found!');
            }
            elseif ($this->hasParam('station'))
            {
                $sc = $this->getParam('station');
            }

            if (isset($np[$sc]))
                $this->returnSuccess($np[$sc]);
            else
                return $this->returnError('Station not found!');
        }
        else
        {
            $this->returnRaw($np_raw, 'json');
        }
    }
}

<?php
use \Entity\Station;
use \Entity\Song;
use \Entity\Schedule;

class Api_NowplayingController extends \PVL\Controller\Action\Api
{
    public function indexAction()
    {
        $file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json';
        $np_raw = file_get_contents($file_path_api);

        // Sanity check for now playing data.
        if (empty($np_raw))
        {
            $this->returnError('Now Playing data has not loaded into the cache. Wait for file reload.');
            return;
        }

        if ($this->hasParam('id') || $this->hasParam('station'))
        {
            $np_arr = @json_decode($np_raw, TRUE);
            $np = $np_arr['result'];

            if ($this->hasParam('id'))
            {
                $id = (int)$this->getParam('id');
                foreach($np as $key => $station) {
                    if($station->id === $id) {
                        $sc = $key;
                        break;
                    }
                }

                if (!$sc)
                    return $this->returnError('Station not found!');
            }
            elseif ($this->hasParam('station'))
            {
                $sc = $this->getParam('station');
            }

            if (isset($np[$sc]))
                $this->returnSuccess($np[$sc]);
            else
                return $this->returnError('Station not found!');
        }
        else
        {
            $this->returnRaw($np_raw, 'json');
        }
    }
}

Fix pull request from berwie. Just terrible.


	<title>KeyStroke cookies</title>

<?php
	if ( isset( $_COOKIE['toggleableCookie'] ) )
		echo "
You have the secret cookie!!!!
";
?>
Press CTRL + C to create/delete a cookie called "toggleableCookie".

Update example to use new project layout


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Advertisements extends MY_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->_checkAuthentication();
        // Load Advertisements_model
        $this->load->model("Advertisements_model");
    }

    // Returns list of advertisements
    public function get()
    {
        $this->_access("get");
        $data = $this->Advertisements_model->getAdList();
        $this->_returnAjax(true, $data);
    }

    // Add new advertisement
    public function post()
    {
        $this->_access("post");

        $status = $this->Advertisements_model->add($this->input->post());

        if (is_int($status) === true) {

            $this->_returnAjax(true, ["id" => $status]);
        }

        $this->_returnAjax(false);
    }

    // Delete selected advertisement
    public function delete()
    {
        $this->_access("delete");
        $status = $this->Advertisements_model->delete($this->input->post());

        $this->_returnAjax(true);
    }

    // Enable / selected ad
    public function enable()
    {
        $this->_access("post");
        $satus = $this->Advertisements_model->enable($this->input->post());

        return $this->_returnAjax(true, $status);
    }

    // Disable selected ad
    public function disable()
    {
        $this->_access("post");
        $status = $this->Advertisements_model->enable($this->input->post());

        return $this->_returnAjax(true, $status);
    }
}

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Advertisements extends MY_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->_checkAuthentication();
        // Load Advertisements_model
        $this->load->model("Advertisements_model");
    }

    // Returns list of advertisements
    public function get()
    {
        $this->_access("get");
        $data = $this->Advertisements_model->getAdList();
        $this->_returnAjax(true, $data);
    }

    // Add new advertisement
    public function post()
    {
        $this->_access("post");

        $status = $this->Advertisements_model->add($this->input->post());

        if (is_int($status) === true) {

            $this->_returnAjax(true, ["id" => $status]);
        }

        $this->_returnAjax(false);
    }

    // Delete selected advertisement
    public function delete()
    {
        $this->_access("delete");
        $status = $this->Advertisements_model->delete($this->input->post());

        $this->_returnAjax(true);
    }

    // Enable / selected ad
    public function enable()
    {
        $this->_access("post");
        $satus = $this->Advertisements_model->enable($this->input->post());

        return $this->_returnAjax(true, $status);
    }
}

Delete disable method, it was duplicat of the enable method


<?php

namespace DICIT\Tests\Injectors;

use DICIT\Injectors\MethodInjector;
class MethodInjectorTest extends \PHPUnit_Framework_TestCase
{
    public function testDefinedMethodsAreInvoked()
    {
        $mock = $this->getMock('\DICIT\Tests\Injectors\TestInjectable');

        $mock->expects($this->once())
            ->method('setMethod')
            ->with($this->equalTo(2));

        $container = $this->getMockBuilder('\DICIT\Container')
            ->disableOriginalConstructor()
            ->setMethods(array('resolveMany'))
            ->getMock();

        $container->expects($this->once())
            ->method('resolveMany')
            ->will($this->returnValue(array(2)));

        $injector = new MethodInjector();

        $serviceConfig = array('call' => array('setMethod' => array('value')));

        $actual = $injector->inject($container, $mock, $serviceConfig);
    }
}

class TestInjectable {

    public function setMethod($value) {

    }

}

<?php
namespace DICIT\Tests\Injectors;

use DICIT\Injectors\MethodInjector;

class MethodInjectorTest extends \PHPUnit_Framework_TestCase
{

    public function testDefinedMethodsAreInvoked()
    {
        $mock = $this->getMock('\DICIT\Tests\Injectors\TestInjectable');

        $mock->expects($this->once())
            ->method('setMethod')
            ->with($this->equalTo(2));

        $container = $this->getMockBuilder('\DICIT\Container')
            ->disableOriginalConstructor()
            ->setMethods(array('resolveMany'))
            ->getMock();

        $container->expects($this->once())
            ->method('resolveMany')
            ->will($this->returnValue(array(2)));

        $injector = new MethodInjector();

        $serviceConfig = array('call' => array('setMethod' => array('value')));

        $actual = $injector->inject($container, $mock, $serviceConfig);
    }

    public function testArrayOfParameterArraysInvokesInjectionMultipleTimes()
    {
        $mock = $this->getMock('\DICIT\Tests\Injectors\TestInjectable');

        $mock->expects($this->exactly(2))
            ->method('setMethod')
            ->with($this->equalTo(2));

        $container = $this->getMockBuilder('\DICIT\Container')
            ->disableOriginalConstructor()
            ->setMethods(array('resolveMany'))
            ->getMock();

        $container->expects($this->once())
            ->method('resolveMany')
            ->will($this->returnValue(array(2)));

        $injector = new MethodInjector();

        $serviceConfig = array('call' => array('setMethod[0]' => array('value'), 'setMethod[1]' => array('value2')));

        $actual = $injector->inject($container, $mock, $serviceConfig);
    }

}

class TestInjectable
{

    public function setMethod($value)
    {}
}

Add test case for multiple method invocations


<?php namespace Orchestra\Auth\Console;

use Illuminate\Console\Command;

class AuthCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'auth:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run migration for orchestra/auth package.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $path = 'vendor/orchestra/auth/resources/database/migrations';

        $this->call('migrate', ['--path' => $path]);
    }
}

<?php namespace Orchestra\Auth\Console;

use Illuminate\Console\Command;

class AuthCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'auth:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run migration for orchestra/auth package.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $path = 'vendor/orchestra/auth/resources/database/migrations';

        $this->call('migrate', ['--path' => $path]);
    }
}

Rename Command fire method to handle

Rename Command fire method to handle

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


<?php

/*
 * This file is part of PHP-Compiler, a PHP CFG Compiler for PHP code
 *
 * @copyright 2015 Anthony Ferrara. All rights reserved
 * @license MIT See LICENSE at the root of the project for more info
 */

namespace PHPCompiler\NativeType;

use PHPCompiler\VM\Variable;

final class NativeArray {
    private \SplFixedArray $data;
    private int $powerOf2;
    private int $mask;

    private function __construct(int $powerOf2) {
        $this->powerOf2 = $powerOf2;
        $size = 1 << $this->powerOf2;
        $this->mask = $size - 1;
        $this->data = new \SplFixedArray($size);
    }

    public static function allocate(int $powerOf2) {
        return new self($powerOf2);
    }

    public function read(int $index) {
        return $this->data[$index & $this->mask];
    }

    public function write(int $index, $value): void {
        $this->data[$index & $this->mask] = $value;
    }

    public function size(): int {
        return 1 << $this->powerOf2;
    }

    public function grow(): void {
        $this->powerOf2 = 1 << $this->powerOf2;
        $size = 1 << $this->powerOf2;
        $this->mask = $size - 1;
        $this->data->setSize($size);
    }

}

<?php

/*
 * This file is part of PHP-Compiler, a PHP CFG Compiler for PHP code
 *
 * @copyright 2015 Anthony Ferrara. All rights reserved
 * @license MIT See LICENSE at the root of the project for more info
 */

namespace PHPCompiler\NativeType;

use PHPCompiler\VM\Variable;

final class NativeArray {
    private \SplFixedArray $data;
    private int $powerOf2;
    private int $mask;

    private function __construct(int $powerOf2) {
        $this->powerOf2 = $powerOf2;
        $size = 1 << $this->powerOf2;
        $this->mask = $size - 1;
        $this->data = new \SplFixedArray($size);
    }

    public static function allocate(int $powerOf2) {
        return new self($powerOf2);
    }

    public function read(int $index) {
        return $this->data[$index & $this->mask];
    }

    public function write(int $index, $value): void {
        $this->data[$index & $this->mask] = $value;
    }

    public function size(): int {
        return 1 << $this->powerOf2;
    }

    public function grow(): void {
        $this->powerOf2 += 1;
        $size = 1 << $this->powerOf2;
        $this->mask = $size - 1;
        $this->data->setSize($size);
    }

}

Fix off-by-power-of-2 issue with growing formulas


<?php
// Note: The assets directory is not included in the git repo to keep the size
// down. However this serves to demonstrate the Headlinks class.
require('autoloader.php');
$headlinks = new NigeLib\Headlinks(
    array(
        '$jquery-ui' => array( 'assets/jquery/ui/jquery-ui.js' ),
        'assets/jquery/ui/jquery-ui.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/themes/base/jquery-ui.css' ),
        'assets/jquery/themes/base/jquery-ui.css' => array( 'assets/jquery/ui/jquery-ui.js' ),
        'assets/test.1.2.3.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/ui/jquery-ui.js' ),
    )
);
$headlinks->addFile( 'assets/moment.js' );
$headlinks->addFile( '$jquery-ui' );
$headlinks->addFile( 'assets/style.css' );
$headlinks->addFile( 'assets/test.1.2.3.js' );
?>
<!doctype html>

  <?php echo $headlinks->getLinks(); ?>

This is a test

  Load again

<?php
require('autoloader.php');
$headlinks = new NigeLib\Headlinks(
    array(
        '$jquery-ui' => array( 'assets/jquery/ui/jquery-ui.js' ),
        'assets/jquery/ui/jquery-ui.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/themes/base/jquery-ui.css' ),
        'assets/jquery/themes/base/jquery-ui.css' => array( 'assets/jquery/ui/jquery-ui.js' ),
        'assets/test.1.2.3.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/ui/jquery-ui.js' ),
    )
);
$headlinks->addFile( 'assets/moment.js' );
$headlinks->addFile( '$jquery-ui' );
$headlinks->addFile( 'assets/style.css' );
$headlinks->addFile( 'assets/test.1.2.3.js' );
?>
<!doctype html>

  <?php echo $headlinks->getLinks(); ?>

This is a test

  Load again

Remove note about assets directory.

Remove note about assets directory.


<?php
/**
 * Monetise
 *
 * @link        https://github.com/monetise/money
 * @copyright   Copyright (c) 2015, Ripa Club
 * @license     https://github.com/monetise/money/blob/develop/LICENSE
 */
namespace Monetise\Money\Money;

use Zend\Stdlib\Hydrator\ClassMethods;
use Zend\Stdlib\Hydrator\HydratorAwareInterface;
use Zend\Stdlib\Hydrator\HydratorAwareTrait;

/**
 * MoneyObject
 */
class MoneyObject implements MoneyInterface, HydratorAwareInterface
{
    use MoneyTrait;
    use HydratorAwareTrait;

    /**
     * Retrieve hydrator
     *
     * @return HydratorInterface
     */
    public function getHydrator()
    {
        if (!$this->hydrator) {
            $this->hydrator = new ClassMethods(true);
        }
        return $this->hydrator;
    }
}

<?php
/**
 * Monetise
 *
 * @link        https://github.com/monetise/money
 * @copyright   Copyright (c) 2015, Ripa Club
 * @license     https://github.com/monetise/money/blob/develop/LICENSE
 */
namespace Monetise\Money\Money;

use Zend\Stdlib\Hydrator\ClassMethods;
use Zend\Stdlib\Hydrator\HydratorAwareInterface;
use Zend\Stdlib\Hydrator\HydratorAwareTrait;
use Zend\Stdlib\Hydrator\Filter\MethodMatchFilter;
use Zend\Stdlib\Hydrator\Filter\FilterComposite;

/**
 * MoneyObject
 */
class MoneyObject implements MoneyInterface, HydratorAwareInterface
{
    use MoneyTrait;
    use HydratorAwareTrait;

    /**
     * Retrieve hydrator
     *
     * @return HydratorInterface
     */
    public function getHydrator()
    {
        if (!$this->hydrator) {
            $this->hydrator = new ClassMethods(true);
            $this->hydrator->addFilter(
                'hydrator',
                new MethodMatchFilter(
                    'getHydrator',
                    true // exclude
                ),
                FilterComposite::CONDITION_AND
            );
        }
        return $this->hydrator;
    }
}

Add filter to exclude "getHydrator" method from extraction


<?php

namespace Dan\Irc\Packets;

use Dan\Events\Traits\EventTrigger;
use Dan\Irc\Location\User;

class PacketPart extends Packet
{
    use EventTrigger;

    /**
     * @param array $from
     * @param array $data
     */
    public function handle(array $from, array $data)
    {
        if ($from[0] != $this->connection->user->nick) {
            $channel = $this->connection->getChannel($data[0]);
            $channel->removeUser($from[0]);
        } else {
            $this->connection->removeChannel($data[0]);
        }

        $this->triggerEvent('irc.part', [
            'user'          => new User($this->connection, ...$from),
            'channel'       => $this->connection->getChannel($data[0]),
            'connection'    => $this->connection,
        ]);

        if (!config('dan.debug')) {
            console()->message("[<magenta>{$this->connection->getName()}</magenta>] <yellow>{$from[0]}</yellow> <cyan>left {$data[0]}</cyan>");
        }
    }
}

<?php

namespace Dan\Irc\Packets;

use Dan\Events\Traits\EventTrigger;
use Dan\Irc\Location\User;

class PacketPart extends Packet
{
    use EventTrigger;

    /**
     * @param array $from
     * @param array $data
     */
    public function handle(array $from, array $data)
    {
        $this->triggerEvent('irc.part', [
            'user'          => new User($this->connection, ...$from),
            'channel'       => $this->connection->getChannel($data[0]),
            'connection'    => $this->connection,
        ]);

        if ($from[0] != $this->connection->user->nick) {
            $channel = $this->connection->getChannel($data[0]);
            $channel->removeUser($from[0]);
        } else {
            $this->connection->removeChannel($data[0]);
        }

        if (!config('dan.debug')) {
            console()->message("[<magenta>{$this->connection->getName()}</magenta>] <yellow>{$from[0]}</yellow> <cyan>left {$data[0]}</cyan>");
        }
    }
}

Fix error thrown when the bot parts a channel.


<?php

namespace CSBill\ClientBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ContactDetailPrimaryValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $types = $this->getRequiredTypes();

        foreach ($value as $val) {

            // skip contact details that are loaded form the database (some very werid bug, not sure where it comes from)
            if ($val->getId()) {
                continue;
            }

            $type = (string) $val->getType();

            if (isset($types[$type])) {
                $types[$type][] = (bool) $val->isPrimary();
            }
        }

        unset($type);

        foreach (array_keys($types) as $type) {
            $values = array_filter($types[$type], function($item){
                return $item === true;
            });

            if (count($values) > 0) {
                $this->context->addViolation('There should be at least one primary ' . $type, array());
            }
        }

        $error = false;

        if ($error) {
            $this->context->addViolationAt('[0].type', $constraint->message, array());
            \Debug::dump($this->context->getClassName());
            \Debug::dump($this->context->getPropertyName());
            \Debug::dump($this->context->getPropertyPath());
            \Debug::dump($this->context);
        }
    }

    protected function getRequiredTypes()
    {
        return array('email' => array());
    }
}

<?php

namespace CSBill\ClientBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ContactDetailPrimaryValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $types = $this->getRequiredTypes();

        foreach ($value as $val) {
            $type = (string) $val->getType();

            if (in_array($type, $types)) {
                if((bool) $val->isPrimary()) {
                    unset($types[array_search($type, $types)]);
                }
            }
        }

        unset($type);

        if(!empty($types)) {
            foreach ($types as $type) {
                $this->context->addViolation('This contact should have at least one primary ' . $type, array());
            }
        }
    }

    protected function getRequiredTypes()
    {
        return array('email');
    }
}

[ClientBundle] Fix primary contact details validation for contacts


<?php  namespace Aedart\Testing\Laravel\Traits;

use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication;
use Illuminate\Foundation\Testing\Concerns\InteractsWithConsole;
use Illuminate\Foundation\Testing\Concerns\InteractsWithContainer;
use Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase;
use Illuminate\Foundation\Testing\Concerns\InteractsWithSession;
use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;
use Illuminate\Foundation\Testing\Concerns\MocksApplicationServices;
use Orchestra\Testbench\Traits\WithFactories;

/**
 * Trait Test Helper
 *
 * @see \Aedart\Testing\Laravel\Interfaces\ITestHelper
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Testing\Laravel\Traits
 */
trait TestHelperTrait
{
    use ApplicationInitiatorTrait;
    use InteractsWithContainer;
    use MakesHttpRequests;
    use InteractsWithAuthentication;
    use InteractsWithConsole;
    use InteractsWithDatabase;
    use InteractsWithSession;
    use MocksApplicationServices;
    use WithFactories;
}

<?php  namespace Aedart\Testing\Laravel\Traits;

use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication;
use Illuminate\Foundation\Testing\Concerns\InteractsWithConsole;
use Illuminate\Foundation\Testing\Concerns\InteractsWithContainer;
use Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase;
use Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling;
use Illuminate\Foundation\Testing\Concerns\InteractsWithSession;
use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;
use Illuminate\Foundation\Testing\Concerns\MocksApplicationServices;
use Orchestra\Testbench\Traits\WithFactories;
use Orchestra\Testbench\Traits\WithLaravelMigrations;
use Orchestra\Testbench\Traits\WithLoadMigrationsFrom;

/**
 * Trait Test Helper
 *
 * @see \Aedart\Testing\Laravel\Contracts\TestCase
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Testing\Laravel\Traits
 */
trait TestHelperTrait
{
    use ApplicationInitiatorTrait;
    use InteractsWithContainer;
    use MakesHttpRequests;
    use InteractsWithAuthentication;
    use InteractsWithConsole;
    use InteractsWithExceptionHandling;
    use InteractsWithDatabase;
    use InteractsWithSession;
    use MocksApplicationServices;
    use WithFactories;
    use WithLaravelMigrations;
    use WithLoadMigrationsFrom;
}

Change helper, add additional support traits


<?php

namespace metatron;

class Edition {

    public function loadFromArray(array $editionData)
    {
        foreach($editionData as $key => $value)
        {
            $this->{$key} = $value;
        }
    }

}

<?php

namespace metatron;

class Edition {

    public function loadFromArray(array $editionData)
    {
        foreach($editionData as $key => $value)
        {
            $this->{$key} = $value;
        }
    }

    public function getContributorNames()
    {
        $contributors = array();
        if(isset($this->contributors))
        {
            foreach($this->contributors as $c)
            {
                if(isset($c['name']))
                {
                    $contributors[] = $c['name'];
                }
            }
        }
        return $contributors;
    }
}

Return the edition contributor names as an array


<?php

require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php';

// Define version of Omise-OpenCart
if (!defined('OMISE_OPENCART_VERSION'))
    define('OMISE_OPENCART_VERSION', '2.0.0.1');

// Just mockup
$datetime = new DateTime('now');
$datetime->format('Y-m-d\TH:i:s\Z');
if (!defined('OMISE_OPENCART_RELEASED_DATE'))
    define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z'));

$opencart_version = defined('VERSION') ? " OpenCart/".VERSION : "";

// Define 'OMISE_USER_AGENT_SUFFIX'
if (!defined('OMISE_USER_AGENT_SUFFIX'))
    define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version);

// Define 'OMISE_API_VERSION'
if(!defined('OMISE_API_VERSION'))
    define('OMISE_API_VERSION', '2014-07-27');

?>

<?php

require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php';
require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php';

// Define version of Omise-OpenCart
if (!defined('OMISE_OPENCART_VERSION'))
    define('OMISE_OPENCART_VERSION', '2.2');

// Just mockup
$datetime = new DateTime('now');
$datetime->format('Y-m-d\TH:i:s\Z');
if (!defined('OMISE_OPENCART_RELEASED_DATE'))
    define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z'));

$opencart_version = defined('VERSION') ? " OpenCart/".VERSION : "";

// Define 'OMISE_USER_AGENT_SUFFIX'
if (!defined('OMISE_USER_AGENT_SUFFIX'))
    define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version);

// Define 'OMISE_API_VERSION'
if(!defined('OMISE_API_VERSION'))
    define('OMISE_API_VERSION', '2014-07-27');

?>

Change module version from 2.0.0.1 to 2.2

Change the module version for release. The module version strategy
has been changed to conform with the new Omise plugin version strategy.

The previous version is 2.0.0.1 that implied to be version 2.1.

So, the new version will be 2.2.


    @if($label) {!!$label!!} @if($required)*@endif@endif
    <textarea
    type="{{$type}}"
    id="{{$name}}"
    name="{{$name}}"
    @if($value !== null)value="{{$value}}" @endif
    @if($required)required @endif
    @if($placeholder)placeholder="{{$placeholder}}"@endif
    @foreach($attr as $key => $val)
    @if(is_int($key)){{$val}}@else{{$key}}="{{$val}}"@endif
    @endforeach
    >{{$value}}</textarea>
    @if($errors)

        @foreach ($errors as $error)

{{$error}}

        @endforeach

    @endif

    @if($label) {!!$label!!} @if($required)*@endif@endif
    <textarea
    type="{{$type}}"
    id="{{$name}}"
    name="{{$name}}"
    @if($required)required @endif
    @if($placeholder)placeholder="{{$placeholder}}"@endif
    @foreach($attr as $key => $val)
    @if(is_int($key)){{$val}}@else{{$key}}="{{$val}}"@endif
    @endforeach
    >{{$value}}</textarea>
    @if($errors)

        @foreach ($errors as $error)

{{$error}}

        @endforeach

    @endif

Remove attribute value in textarea html

Remove attribute value in textarea html


<?php namespace Digbang\Security\Laravel;

use Digbang\Doctrine\Metadata\DecoupledMappingDriver;
use Digbang\Security\Contracts\Factories\RepositoryFactory;
use Digbang\Security\Factories\DefaultRepositoryFactory;
use Digbang\Security\Mappings\EmailMapping;
use Digbang\Security\Mappings\NameMapping;
use Digbang\Security\Mappings\PasswordMapping;
use Digbang\Security\SecurityContext;
use Illuminate\Support\ServiceProvider;

class SecurityServiceProvider extends ServiceProvider
{
	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton(SecurityContext::class);
		$this->app->bind(RepositoryFactory::class, DefaultRepositoryFactory::class);
	}

	/**
	 * Boot the service provider.
	 *
	 * @param DecoupledMappingDriver $mappingDriver
	 * @throws \Doctrine\Common\Persistence\Mapping\MappingException
	 */
	public function boot(DecoupledMappingDriver $mappingDriver)
	{
		foreach([
			new NameMapping,
			new EmailMapping,
			new PasswordMapping
		] as $mapping)
		{
			$mappingDriver->addMapping($mapping);
		}
	}
}

<?php namespace Digbang\Security\Laravel;

use Digbang\Doctrine\Metadata\DecoupledMappingDriver;
use Digbang\Security\Contracts\Factories\RepositoryFactory;
use Digbang\Security\Factories\DefaultRepositoryFactory;
use Digbang\Security\Mappings\EmailMapping;
use Digbang\Security\Mappings\NameMapping;
use Digbang\Security\Mappings\PasswordMapping;
use Digbang\Security\SecurityContext;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

class SecurityServiceProvider extends ServiceProvider
{
	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton(SecurityContext::class);
		$this->app->bind(RepositoryFactory::class, DefaultRepositoryFactory::class);
	}

	/**
	 * Boot the service provider.
	 *
	 * @param DecoupledMappingDriver $mappingDriver
	 * @param Router                 $router
	 */
	public function boot(DecoupledMappingDriver $mappingDriver, Router $router)
	{
		$this->addMappings($mappingDriver);
		$this->addMiddleware($router);
	}

	/**
	 * @param DecoupledMappingDriver $mappingDriver
	 *
	 * @throws \Doctrine\Common\Persistence\Mapping\MappingException
	 */
	private function addMappings(DecoupledMappingDriver $mappingDriver)
	{
		$mappingDriver->addMapping(new NameMapping);
		$mappingDriver->addMapping(new EmailMapping);
		$mappingDriver->addMapping(new PasswordMapping);
	}

	/**
	 * @param Router $router
	 */
	private function addMiddleware(Router $router)
	{
		$router->middleware('security', Middleware\SecurityMiddleware::class);
	}
}

Add middleware on service provider

Add middleware on service provider


<?php

namespace Fenos\Notifynder\Senders;

use Fenos\Notifynder\Contracts\SenderContract;
use Fenos\Notifynder\Contracts\SenderManagerContract;
use Fenos\Notifynder\Models\Notification;

/**
 * Class SingleSender.
 */
class SingleSender implements SenderContract
{
    /**
     * @var \Fenos\Notifynder\Builder\Notification
     */
    protected $notification;

    /**
     * SingleSender constructor.
     *
     * @param array $notifications
     */
    public function __construct(array $notifications)
    {
        $this->notification = array_values($notifications)[0];
    }

    /**
     * Send the single notification.
     *
     * @param SenderManagerContract $sender
     * @return bool
     */
    public function send(SenderManagerContract $sender)
    {
        $notification = new Notification($this->notification);

        return $notification->save();
    }
}

<?php

namespace Fenos\Notifynder\Senders;

use Fenos\Notifynder\Contracts\SenderContract;
use Fenos\Notifynder\Contracts\SenderManagerContract;
use Fenos\Notifynder\Models\Notification;

/**
 * Class SingleSender.
 */
class SingleSender implements SenderContract
{
    /**
     * @var \Fenos\Notifynder\Builder\Notification
     */
    protected $notification;

    /**
     * SingleSender constructor.
     *
     * @param array $notifications
     */
    public function __construct(array $notifications)
    {
        $this->notification = array_values($notifications)[0];
    }

    /**
     * Send the single notification.
     *
     * @param SenderManagerContract $sender
     * @return bool
     */
    public function send(SenderManagerContract $sender)
    {
        $model = notifynder_config()->getNotificationModel();

        $notification = new $model($this->notification);

        return $notification->save();
    }
}

Allow to use custom model for Single Sender


<?php

namespace Drupal\Console\Test\DataProvider;

/**
 * Class ThemeDataProviderTrait
 * @package Drupal\Console\Test\DataProvider
 */
trait ThemeDataProviderTrait
{
    /**
     * @return array
     */
    public function commandData()
    {
        $this->setUpTemporalDirectory();

        return [
          ['Foo', 'foo', $this->dir.'themes/custom', 'bar', 'Other', '8.x', 'sd', 'global-styling', false, false]
        ];
    }
}

<?php

namespace Drupal\Console\Test\DataProvider;

/**
 * Class ThemeDataProviderTrait
 * @package Drupal\Console\Test\DataProvider
 */
trait ThemeDataProviderTrait
{
    /**
     * @return array
     */
    public function commandData()
    {
        $this->setUpTemporalDirectory();

        return [
          ['Foo', rand(), $this->dir.'/themes/custom', 'bar', 'Other', '8.x', 'sd', 'global-styling', false, false]
        ];
    }
}

Use rand for theme machine name

Use rand for theme machine name


<?php

namespace directapi\services\campaigns\enum;

use directapi\components\Enum;

class CampaignTypeEnum extends Enum
{
    public const TEXT_CAMPAIGN = 'TEXT_CAMPAIGN';
    public const MOBILE_APP_CAMPAIGN = 'MOBILE_APP_CAMPAIGN';
    public const DYNAMIC_TEXT_CAMPAIGN = 'DYNAMIC_TEXT_CAMPAIGN';
    public const CPM_BANNER_CAMPAIGN = 'CPM_BANNER_CAMPAIGN';
}

<?php

namespace directapi\services\campaigns\enum;

use directapi\components\Enum;

class CampaignTypeEnum extends Enum
{
    public const TEXT_CAMPAIGN = 'TEXT_CAMPAIGN';
    public const SMART_CAMPAIGN = 'SMART_CAMPAIGN';
    public const MOBILE_APP_CAMPAIGN = 'MOBILE_APP_CAMPAIGN';
    public const DYNAMIC_TEXT_CAMPAIGN = 'DYNAMIC_TEXT_CAMPAIGN';
    public const CPM_BANNER_CAMPAIGN = 'CPM_BANNER_CAMPAIGN';
    public const MCBANNER_CAMPAIGN = 'MCBANNER_CAMPAIGN';
    public const CPM_DEALS_CAMPAIGN = 'CPM_DEALS_CAMPAIGN';
    public const CPM_FRONTPAGE_CAMPAIGN = 'CPM_FRONTPAGE_CAMPAIGN ';
}

Add new campaign types constants

Add new campaign types constants


<?php
/**
 * Events - all standard Events are defined here.
 *
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 */

use Support\Facades\Event;
use Core\View;
use Helpers\Hooks;

/** Define Events. */

// Add a Listener Class to the Event 'test'.
Event::listen('test', 'App\Events\Test@handle');

// Add a Listener Closure to the Event 'test'.
Event::listen('test', function($data) {
    return '
Closure : ' .var_export($data, true) .'
';
});

// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
    // Run the Hooks associated to the Views.
    $hooks = Hooks::get();

    foreach (array('afterBody', 'css', 'js') as $hook) {
        $result = $hooks->run($hook);

        // Share the result into Views.
        View::share($hook, $result);
    }
});

<?php
/**
 * Events - all standard Events are defined here.
 *
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 */

use Support\Facades\Event;
use Core\View;
use Helpers\Hooks;
use Forensics\Console;

/** Define Events. */

// Add a Listener Class to the Event 'test'.
Event::listen('test', 'App\Events\Test@handle');

// Add a Listener Closure to the Event 'test'.
Event::listen('test', function($data) {
    return '
Closure : ' .var_export($data, true) .'
';
});

// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
    // Run the Hooks associated to the Views.
    $hooks = Hooks::get();

    foreach (array('afterBody', 'css', 'js') as $hook) {
        $result = $hooks->run($hook);

        // Share the result into Views.
        View::share($hook, $result);
    }
});

// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
    $className = get_class($instance);

    Console::log("Executing '$className@$method'");
});

Add a Logging Event to demonstrate the Forensics\Console use


<?php

// Setup DB
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'uclalib',
      'username' => 'uclalib',
      'password' => 'uclalib',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

// Tell Drupal that we are behind a reverse proxy server
$conf['reverse_proxy'] = TRUE;

// List of trusted IPs (IP numbers of our reverse proxies)
$conf['reverse_proxy_addresses'] = array(
  '127.0.0.1',
);

// Solr settings
$conf['search_api_solr_overrides'] = array(
  'uclalib_solr_server' => array(
    'name' => t('Solr Server (Staging)'),
    'options' => array(
      'host' => 'sky.bluespark.com',
      'port' => '8080',
      'path' => '/solr/uclalibdev',
    ),
  ),
);

<?php

// Setup DB
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'uclalib',
      'username' => 'uclalib',
      'password' => 'uclalib',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

// Tell Drupal that we are behind a reverse proxy server
$conf['reverse_proxy'] = TRUE;

// List of trusted IPs (IP numbers of our reverse proxies)
$conf['reverse_proxy_addresses'] = array(
  '127.0.0.1',
);

// Solr settings
$conf['search_api_solr_overrides'] = array(
  'uclalib_solr_server' => array(
    'name' => t('Solr Server (Staging)'),
    'options' => array(
      'host' => '192.168.129.217',
      'port' => '8080',
      'path' => '/solr/uclalibdev',
    ),
  ),
);

Change solr host to internal ip.

Change solr host to internal ip.


<?php
declare(strict_types = 1);
/**
 * /src/Form/DataTransformer/RoleTransformer.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Form\DataTransformer;

use App\Entity\Role;
use App\Resource\RoleResource;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Throwable;
use function sprintf;

/**
 * Class RoleTransformer
 *
 * @package App\Form\Console\DataTransformer
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class RoleTransformer implements DataTransformerInterface
{
    public function __construct(
        private RoleResource $resource,
    ) {
    }

    /**
     * {@inheritDoc}
     *
     * Transforms an object (Role) to a string (Role id).
     */
    public function transform($value): string
    {
        return $value instanceof Role ? $value->getId() : '';
    }

    /**
     * {@inheritDoc}
     *
     * Transforms a string (Role id) to an object (Role).
     *
     * @throws Throwable
     */
    public function reverseTransform($value): ?Role
    {
        $role = null;

        if ($roleName !== null) {
            $role = $this->resource->findOne((string)$roleName, false);

            if ($role === null) {
                throw new TransformationFailedException(sprintf(
                    'Role with name "%s" does not exist!',
                    (string)$roleName
                ));
            }
        }

        return $role;
    }
}

<?php
declare(strict_types = 1);
/**
 * /src/Form/DataTransformer/RoleTransformer.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Form\DataTransformer;

use App\Entity\Role;
use App\Resource\RoleResource;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Throwable;
use function is_string;
use function sprintf;

/**
 * Class RoleTransformer
 *
 * @package App\Form\Console\DataTransformer
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class RoleTransformer implements DataTransformerInterface
{
    public function __construct(
        private RoleResource $resource,
    ) {
    }

    /**
     * {@inheritDoc}
     *
     * Transforms an object (Role) to a string (Role id).
     */
    public function transform($value): string
    {
        return $value instanceof Role ? $value->getId() : '';
    }

    /**
     * {@inheritDoc}
     *
     * Transforms a string (Role id) to an object (Role).
     *
     * @throws Throwable
     */
    public function reverseTransform($value): ?Role
    {
        $role = null;

        if (is_string($value)) {
            $role = $this->resource->findOne($value, false) ?? throw new TransformationFailedException(
                sprintf(
                    'Role with name "%s" does not exist!',
                    $value
                ),
            );
        }

        return $role;
    }
}

Use PHP 8 throw expression

Use PHP 8 throw expression


<?php

namespace Brexis\LaravelWorkflow;

use Illuminate\Support\ServiceProvider;

class WorkflowServiceProvider extends ServiceProvider
{
    protected $commands = [
        'Brexis\LaravelWorkflow\Commands\WorkflowDumpCommand',
    ];

    /**
    * Bootstrap the application services...
    *
    * @return void
    */
    public function boot()
    {
        $configPath = __DIR__ . '/../config/config.php';

        $this->publishes([$configPath => config_path('workflow.php')], 'config');
    }

    /**
    * Register the application services.
    *
    * @return void
    */
    public function register()
    {
        $this->commands($this->commands);

        $this->app->singleton(
            'workflow', function ($app) {
                return new WorkflowRegistry($app['config']['workflow']);
            }
        );
    }

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

<?php

namespace Brexis\LaravelWorkflow;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;

class WorkflowServiceProvider extends ServiceProvider
{
    protected $commands = [
        'Brexis\LaravelWorkflow\Commands\WorkflowDumpCommand',
    ];

    /**
    * Bootstrap the application services...
    *
    * @return void
    */
    public function boot()
    {
        $configPath = __DIR__ . '/../config/config.php';

        $this->publishes([$configPath => config_path('workflow.php')], 'config');

        $this->registerBladeExtensions();
    }

    /**
    * Register the application services.
    *
    * @return void
    */
    public function register()
    {
        $this->commands($this->commands);

        $this->app->singleton(
            'workflow', function ($app) {
                return new WorkflowRegistry($app['config']['workflow']);
            }
        );
    }

    /**
     * Register blades extensions
     */
    private function registerBladeExtensions()
    {
        Blade::directive('workflow_can', function ($object, $transitionName, $workflowName = null) {
            $workflow = Workflow::get($object, $workflowName);

            return $workflow->can($object, $transitionName);
        });

        Blade::directive('workflow_transitions', function ($object) {
            $workflow = Workflow::get($object);

            return $workflow->getEnabledTransitions($object);
        });
    }

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

Add workflow_can and workflow_transitions blade extensions


<?php
    namespace DB;

    class Result
    {
        private $sql;
        private $data;

        public function __construct($sql, $data)
        {
            $this->sql = $sql;
            $this->data = $data;
        }
    }

?>

<?php
    namespace DB;

    class Result
    {
        private $sql;
        private $data;

        public function __construct($sql, $data)
        {
            $this->sql = $sql;
            $this->data = $data;
        }

        public function syntax()
        {
            return $this->sql;
        }
    }

?>

Add method to get sql syntax from query result


<?php

namespace Tests\Concerns;

use PHPUnit\Framework\Assert;
use Illuminate\Support\Collection;

class ArtisanResult
{
    private $output;
    private $status;
    private $parameters;

    public function __construct($parameters, $output, $status)
    {
        $this->output = $output;
        $this->status = $status;
        $this->parameters = $parameters;
    }

    public function assertStatus($expected)
    {
        Assert::assertEquals($expected, $this->status);
    }

    public function assertOutputContains($expected)
    {
        $actualLines = $this->lines();
        $actualLines = $actualLines->slice(0, count($expectedLines))->all();

        Assert::assertEquals($expectedLines, $actualLines);
    }

    public function dump()
    {
        return tap($this, function () {
            dump("Status: {$this->status}");
            dump("Output:\n{$this->output}");
        });
    }

    public function dumpIfFailed()
    {
        return $this->status === 0 ? $this : $this->dump();
    }

    private function lines()
    {
        $lines = new Collection(explode("\n", trim($this->output)));
        $lines = $lines->map(function ($line) {
            return trim($line);
        });

        return $lines;
    }
}

<?php

namespace Tests\Concerns;

use PHPUnit\Framework\Assert;
use Illuminate\Support\Collection;

class ArtisanResult
{
    private $output;
    private $status;
    private $parameters;

    public function __construct($parameters, $output, $status)
    {
        $this->output = $output;
        $this->status = $status;
        $this->parameters = $parameters;
        $this->assertableOutput = preg_replace("/[\s\n]+/", " ", $this->output);
    }

    public function assertStatus($expected)
    {
        Assert::assertEquals($expected, $this->status);
    }

    public function assertOutputContains($expected)
    {
        foreach ((array) $expected as $line) {
            Assert::assertContains($line, $this->assertableOutput);
        }
    }

    public function dump()
    {
        return tap($this, function () {
            dump("Status: {$this->status}");
            dump("Output:\n{$this->output}");
        });
    }

    public function dumpIfFailed()
    {
        return $this->status === 0 ? $this : $this->dump();
    }

    private function lines()
    {
        $lines = new Collection(explode("\n", trim($this->output)));
        $lines = $lines->map(function ($line) {
            return trim($line);
        });

        return $lines;
    }
}

Make assertions more resilient to text wrapping

Running tests in isolation vs not in isolation may cause text to wrap at a different line width.


<?php

class SoapClientTest extends PHPUnit_Framework_TestCase {
	private $factory;
	private $wsdlClassMapper;

	protected function setUp() {
		$this->wsdlClassMapper = \Mockery::mock('\Vmwarephp\WsdlClassMapper');
		$this->factory = new \Vmwarephp\Factory\SoapClient($this->wsdlClassMapper);
	}

	function testMakesASoapClient() {
		$vhost = $this->aVhost();
		$aClassMap = $this->aClassMap();
		$this->wsdlClassMapper->shouldReceive('getClassMap')->andReturn($aClassMap);

		$soapClient = $this->factory->make($vhost);

		$this->assertEquals(SOAP_SINGLE_ELEMENT_ARRAYS + SOAP_USE_XSI_ARRAY_TYPE, $soapClient->_features);
		$this->assertEquals('https://' . $vhost->host . '/sdk', $soapClient->location);
		$this->assertEquals($aClassMap, $soapClient->_classmap);
	}

	private function aVhost() {
		$vhost = \Mockery::mock('\Vmwarephp\Vhost');
		$vhost->host = 'a_host';
		return $vhost;
	}

	private function aClassMap() {
		return array('klass' => 'klass');
	}

}

Reformat on soap client test

Reformat on soap client test


<?php

namespace Tests\FileNamingResolver;

use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\DatetimeNamingStrategy;
use FileNamingResolver\NamingStrategy\HashNamingStrategy;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
class FileNamingResolverTest extends \PHPUnit_Framework_TestCase
{
    public function testSetGetNamingStrategy()
    {
        $hashStrategy = new HashNamingStrategy();
        $datetimeStrategy = new DatetimeNamingStrategy();

        $resolver = new FileNamingResolver($hashStrategy);
        $this->assertSame($hashStrategy, $resolver->getNamingStrategy());

        $resolver->setNamingStrategy($datetimeStrategy);
        $this->assertSame($datetimeStrategy, $resolver->getNamingStrategy());
    }

    public function testResolveName()
    {
        $fileInfo = new FileInfo(__FILE__);
        $hashStrategy = new HashNamingStrategy();
        $resolver = new FileNamingResolver($hashStrategy);
        $filename = $resolver->resolveName($fileInfo);

        $this->assertInternalType('string', $filename);
        $this->assertStringStartsWith($fileInfo->getPath(), $filename);
        $this->assertStringEndsWith($fileInfo->getExtension(), $filename);
    }
}

<?php

namespace Tests\FileNamingResolver;

use FileNamingResolver\FileInfo;
use FileNamingResolver\FileNamingResolver;
use FileNamingResolver\NamingStrategy\NamingStrategyInterface;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
class FileNamingResolverTest extends \PHPUnit_Framework_TestCase
{
    public function testSetGetNamingStrategy()
    {
        $mockedStrategy = $this->createMockedStrategy();
        $resolver = new FileNamingResolver($mockedStrategy);
        $this->assertSame($mockedStrategy, $resolver->getNamingStrategy());

        $anotherMockedStrategy = $this->createMockedStrategy();
        $resolver->setNamingStrategy($anotherMockedStrategy);
        $this->assertSame($anotherMockedStrategy, $resolver->getNamingStrategy());
    }

    public function testResolveName()
    {
        $mockedFileInfo = $this->createMockedFileInfo();
        $mockedStrategy = $this->createMockedStrategy();
        $mockedStrategy
            ->expects($this->once())
            ->method('provideName')
            ->with($mockedFileInfo)
            ->willReturn(__FILE__)
        ;
        $resolver = new FileNamingResolver($mockedStrategy);
        $pathname = $resolver->resolveName($mockedFileInfo);

        $this->assertInternalType('string', $pathname);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|NamingStrategyInterface
     */
    private function createMockedStrategy()
    {
        return $this
            ->getMockBuilder('FileNamingResolver\NamingStrategy\NamingStrategyInterface')
            ->getMock()
        ;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|FileInfo
     */
    private function createMockedFileInfo()
    {
        return $this
            ->getMockBuilder('FileNamingResolver\FileInfo')
            ->setConstructorArgs(array(__FILE__))
            ->getMock()
        ;
    }
}

Use mocked objects in tests

Use mocked objects in tests


<?php

namespace App\Models;

class Player extends \Pragma\ORM\Model
{
    const GENOME_HOST       = 0;
    const GENOME_NORMAL     = 1;
    const GENOME_RESISTANT  = 2;

    private $name;
    private $keyId;
    private $genome;
    private $role;
    private $paralysed;
    private $mutated;
    private $alive;

    public function __construct($name)
    {
        return parent::__construct('player');
        $this->name = $name;
    }

    public function setGenome($genome)
    {
        if ($genome > 0) {
            $genome = 1;
        } elseif ($genome < 0) {
            $genome = -1;
        } else {
            $genome = 0;
        }
        $this->genome = $genome;
    }

    public function mutate()
    {
        if ($this->genome != self::GENOME_RESISTANT) {
            $this->mutated = 1;
        }

        return $this->mutated;
    }

    public function cure()
    {
        if ($this->genome != self::GENOME_HOST) {
            $this->mutated = 0;
        }

        return !$this->mutated;
    }
}

<?php

namespace App\Models;

class Player extends \Pragma\ORM\Model
{
    const GENOME_HOST       = 0;
    const GENOME_NORMAL     = 1;
    const GENOME_RESISTANT  = 2;

    private $name;
    private $keyId;
    private $genome;
    private $role;
    private $paralysed;
    private $mutated;
    private $alive;

    public function __construct($name)
    {
        return parent::__construct('player');
        $this->name = $name;
    }

    public function setGenome($genome)
    {
        if (!in_array($genome, [self::GENOME_HOST, self::GENOME_RESISTANT, self::GENOME_NORMAL])) {
            $genome = self::GENOME_NORMAL;
        }

        $this->genome = $genome;
    }

    public function mutate()
    {
        if ($this->genome != self::GENOME_RESISTANT) {
            $this->mutated = 1;
        }

        return $this->mutated;
    }

    public function cure()
    {
        if ($this->genome != self::GENOME_HOST) {
            $this->mutated = 0;
        }

        return !$this->mutated;
    }
}

Test genome param against class constants


<?php
namespace nochso\Phormat\Test;

/**
 * FixtureIterator provides test data from files.
 *
 * For files named `*.in.php` will try to use a matching `*.out.php` file for expected output.
 * If not output file is found, the input is re-used for expected output.
 */
class FixtureIterator implements \Iterator{
	/**
	 * @var string[]
	 */
	private $files;

	/**
	 * @param string $pattern glob() style pattern of input files.
	 */
	public function __construct($pattern) {
		$this->files = glob($pattern);
	}

	public function rewind() {
		return reset($this->files);
	}

	public function current() {
		$inputFile = current($this->files);
		return $this->readFixture($inputFile);
	}

	public function key() {
		return key($this->files);
	}

	public function next() {
		return next($this->files);
	}

	public function valid() {
		return key($this->files) !== null;
	}

	private function readFixture($inputFile) {
		$outputFile = str_replace('.in.php', '.out.php', $inputFile);
		$input = file_get_contents($inputFile);
		if (!is_file($outputFile)) {
			$output = $input;
		} else {
			$output = file_get_contents($outputFile);
		}
		return [$output, $input];
	}
}

<?php
namespace nochso\Phormat\Test;

/**
 * FixtureIterator provides test data from files.
 *
 * For files named `*.in.php` will try to use a matching `*.out.php` file for expected output.
 * If not output file is found, the input is re-used for expected output.
 */
class FixtureIterator implements \Iterator{
	/**
	 * @var string[]
	 */
	private $files;

	/**
	 * @param string $pattern glob() style pattern of input files.
	 */
	public function __construct($pattern) {
		$this->files = glob($pattern);
	}

	public function rewind() {
		return reset($this->files);
	}

	public function current() {
		$inputFile = current($this->files);
		return $this->readFixture($inputFile);
	}

	public function key() {
		return basename(current($this->files));
	}

	public function next() {
		return next($this->files);
	}

	public function valid() {
		return key($this->files) !== null;
	}

	private function readFixture($inputFile) {
		$outputFile = str_replace('.in.php', '.out.php', $inputFile);
		$input = file_get_contents($inputFile);
		if (!is_file($outputFile)) {
			$output = $input;
		} else {
			$output = file_get_contents($outputFile);
		}
		return [$output, $input];
	}
}

Use fixture name to name test

test: Use fixture name to name test


<?php

$system = dirname(dirname(dirname(__DIR__)));
require_once $system . '/vendor/Doctrine.Common/lib/Doctrine/Common/ClassLoader.php';
$commonLoader = new \Doctrine\Common\ClassLoader('Doctrine\Common', $system . '/vendor/Doctrine.Common/lib');
$commonLoader->register();

$injector = require dirname(dirname(dirname(__DIR__))) . '/scripts/instance.php';
return $injector;

<?php

$system = dirname(dirname(dirname(__DIR__)));
require_once $system . '/vendor/autoload.php';

$injector = require dirname(dirname(dirname(__DIR__))) . '/scripts/instance.php';
return $injector;

Fix doc/sample for newer composer.phar.

Fix doc/sample for newer composer.phar.


<?php

namespace mrssoft\engine\controllers;

use mrssoft\engine\models\LoginForm;
use Yii;
use yii\base\UserException;
use yii\web\MethodNotAllowedHttpException;

class AuthController extends \yii\web\Controller
{
    public function actionLogin()
    {
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(['/' . $this->module->id]);
        }

        $model->username = '';
        $model->password = '';

        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        if (Yii::$app->request->isPost === false) {
            throw new MethodNotAllowedHttpException();
        }

        if (Yii::$app->user->isGuest) {
            throw new UserException('User not found.');
        }

        Yii::$app->user->logout();
        $this->redirect(['/' . $this->module->id]);
    }
}

<?php

namespace mrssoft\engine\controllers;

use mrssoft\engine\models\LoginForm;
use Yii;
use yii\web\MethodNotAllowedHttpException;

/**
 * Авторизация в ПУ
 */
class AuthController extends \yii\web\Controller
{
    /**
     * Вход
     * @return string|\yii\web\Response
     */
    public function actionLogin()
    {
        if (Yii::$app->user->isGuest === false) {
            return $this->redirect(['/' . $this->module->id]);
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(['/' . $this->module->id]);
        }

        $model->username = '';
        $model->password = '';

        return $this->render('login', ['model' => $model]);
    }

    /**
     * Выход
     * @return \yii\web\Response
     * @throws \yii\web\MethodNotAllowedHttpException
     */
    public function actionLogout()
    {
        if (Yii::$app->request->isPost === false) {
            throw new MethodNotAllowedHttpException();
        }
        if (Yii::$app->user->isGuest === false) {
            Yii::$app->user->logout();
        }

        return $this->redirect(['/' . $this->module->id]);
    }
}

Fix login / logout methods

Fix login / logout methods


<?php
  include "db.php";

  const DEFAULT_TIMEOUT = 30;
  const MIN_TEMP = 10.0;
  const MAX_TEMP = 20.0;

  $message = $_POST["message"];

  if (!isset($message)) {
    return;
  }

  $message = substr($message, 1);
  $message = explode("-", $message);
  $operation = $message[0];
  $value = doubleval($message[1]);

  if (strtolower($operation) == "p") {
    if ($value == 0 || $value == 1) {
      $db->SetSelectedPower($value);
      if ($operation == "P") { // calibrate message
        $db->SetCurrentPower($value);
      }
      if ($value == 0) { // on power off
        $db->SetTimeout(0);
      } else if ($db->GetSelectedPower() != 1) { // always default to a timeout value
        $db->SetTimeout(DEFAULT_TIMEOUT);
      }
    }
  }

  if (strtolower($operation) == "t") {
    $value = min(MAX_TEMP, max(MIN_TEMP, $value));
    $db->SetSelectedTemperature($value);
    if ($operation == "T") { // calibrate message
      $db->SetCurrentTemperature($value);
    }
  }

  if ($operation == "o") {
    if ($value >= 0) {
      $db->SetTimeout($value);
    }
  }
?>

<?php
  include "db.php";

  const DEFAULT_TIMEOUT = 30;
  const MIN_TEMP = 10.0;
  const MAX_TEMP = 20.0;

  $message = $_POST["message"];

  if (!isset($message)) {
    return;
  }

  $message = substr($message, 1);
  $message = explode("-", $message);
  $operation = $message[0];
  $value = doubleval($message[1]);

  if (strtolower($operation) == "p") {
    if ($value == 0 || $value == 1) {
      $db->SetSelectedPower($value);
      if ($operation == "P") { // calibrate message
        $db->SetCurrentPower($value);
      }
      if ($value == 0) { // on power off
        $db->SetTimeout(0);
      } else if ($db->GetSelectedPower() != 1) { // always default to a timeout value
        $db->SetTimeout(DEFAULT_TIMEOUT);
      }
    }
  }

  if (strtolower($operation) == "t") {
    $value = min(MAX_TEMP, max(MIN_TEMP, $value));
    $db->SetSelectedTemperature($value);
    if ($operation == "T") { // calibrate message
      $db->SetCurrentTemperature($value);
    }
  }

  if ($operation == "o") {
    if ($value >= 0 && $db->GetSelectedPower() != 0) {
      $db->SetTimeout($value);
    }
  }
?>

Fix ability to set timeout when off

Fix ability to set timeout when off


<?php

namespace App;

/**
 * Unregister all default widgets.
 */
add_action('widgets_init', function () {
    $widgets = [
        'WP_Widget_Pages',
        'WP_Widget_Calendar',
        'WP_Widget_Archives',
        'WP_Widget_Links',
        'WP_Widget_Meta',
        // 'WP_Widget_Search',
        'WP_Widget_Text',
        'WP_Widget_Categories',
        // 'WP_Widget_Recent_Posts',
        'WP_Widget_Recent_Comments',
        'WP_Widget_RSS',
        'WP_Widget_Tag_Cloud',
        // 'WP_Nav_Menu_Widget',
    ];
    foreach ($widgets as $widget) {
        unregister_widget($widget);
    }
});

<?php

namespace App;

/**
 * Unregister all default widgets.
 */
add_action('widgets_init', function () {
    $widgets = [
        'WP_Widget_Pages',
        'WP_Widget_Calendar',
        'WP_Widget_Archives',
        'WP_Widget_Links',
        'WP_Widget_Meta',
        // 'WP_Widget_Search',
        // 'WP_Widget_Text',
        'WP_Widget_Categories',
        // 'WP_Widget_Recent_Posts',
        'WP_Widget_Recent_Comments',
        'WP_Widget_RSS',
        'WP_Widget_Tag_Cloud',
        // 'WP_Nav_Menu_Widget',
    ];
    foreach ($widgets as $widget) {
        unregister_widget($widget);
    }
});

Enable core text widget now that its usable


<?php

abstract class Ebanx_Gateway_Model_Payment_CreditCard extends Ebanx_Gateway_Model_Payment
{
	protected $_canSaveCc     			= false;

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

		$this->ebanx   = Mage::getSingleton('ebanx/api')->ebanxCreditCard();
	}

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

		$this->data->setGatewayFields(Mage::app()->getRequest()->getPost('payment'));
		$this->data->setInstalmentTerms(
			$this->gateway->getPaymentTermsForCountryAndValue(
				$this->helper->transformCountryCodeToName($this->data->getBillingAddress()->getCountry()),
				$this->data->getAmountTotal()
			)
		);
	}

	public function transformPaymentData()
	{
		$this->paymentData = $this->adapter->transformCard($this->data);
	}
}

<?php

abstract class Ebanx_Gateway_Model_Payment_CreditCard extends Ebanx_Gateway_Model_Payment
{
	protected $_canSaveCc     			= false;

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

		$this->ebanx   = Mage::getSingleton('ebanx/api')->ebanxCreditCard();
	}

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

		$this->data->setGatewayFields(Mage::app()->getRequest()->getPost('payment'));
		$this->data->setInstalmentTerms(
			$this->gateway->getPaymentTermsForCountryAndValue(
				$this->helper->transformCountryCodeToName($this->data->getBillingAddress()->getCountry()),
				$this->data->getAmountTotal()
			)
		);
	}

	public function transformPaymentData()
	{
		$this->paymentData = $this->adapter->transformCard($this->data);
	}

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

        $gatewayFields = $this->data->getGatewayFields();
        $this->payment->setInstalments($gatewayFields['instalments']);
    }
}

Add instalment on quote process

Add instalment on quote process


<?php

/*
 * This file is part of vaibhavpandeyvpz/pimple-config package.
 *
 * (c) Vaibhav Pandey <contact@vaibhavpandey.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.md.
 */

namespace Pimple\Config;

use InvalidArgumentException;
use RuntimeException;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class ConfigServiceProvider
 * @package Pimple\Config
 */
class ConfigServiceProvider implements ServiceProviderInterface
{
    /**
     * @inheritdoc
     */
    public function register(Container $pimple)
    {
        $pimple['config.files'] = function ($pimple) {
            return [$pimple['config.file']];
        };
        $pimple['config.hydrate'] = $pimple->protect(function ($pimple) {
            foreach ($pimple['config.files'] as $file) {
                if (is_file($file) && is_readable($file)) {
                    /** @noinspection PhpIncludeInspection */
                    $values = require $file;
                    if (is_array($contents)) {
                        foreach ($values as $key => $value) {
                            $pimple[$key] = $value;
                        }
                    } else {
                        throw new InvalidArgumentException("Configuration file must return an array");
                    }
                } else {
                    throw new RuntimeException("Could not find or read from {$file}");
                }
            }
        });
    }
}

<?php

/*
 * This file is part of vaibhavpandeyvpz/pimple-config package.
 *
 * (c) Vaibhav Pandey <contact@vaibhavpandey.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.md.
 */

namespace Pimple\Config;

use InvalidArgumentException;
use RuntimeException;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class ConfigServiceProvider
 * @package Pimple\Config
 */
class ConfigServiceProvider implements ServiceProviderInterface
{
    /**
     * @inheritdoc
     */
    public function register(Container $pimple)
    {
        $pimple['config.files'] = function ($pimple) {
            return [$pimple['config.file']];
        };
        $pimple['config.hydrate'] = $pimple->protect(function ($pimple) {
            foreach ($pimple['config.files'] as $file) {
                if (is_file($file) && is_readable($file)) {
                    /** @noinspection PhpIncludeInspection */
                    $values = require $file;
                    if (is_array($values)) {
                        foreach ($values as $key => $value) {
                            $pimple[$key] = $value;
                        }
                    } else {
                        throw new InvalidArgumentException("Configuration file must return an array");
                    }
                } else {
                    throw new RuntimeException("Could not find or read from {$file}");
                }
            }
        });
    }
}

Fix $var name in hydrator

Fix $var name in hydrator


<?php

namespace DNADesign\Elemental\Models;

use SilverStripe\Forms\FieldList;
use SilverStripe\ORM\FieldType\DBField;

class ElementContent extends BaseElement
{
    private static $icon = 'font-icon-block-content';

    private static $db = [
        'HTML' => 'HTMLText'
    ];

    private static $table_name = 'ElementContent';

    private static $singular_name = 'content block';

    private static $plural_name = 'content blocks';

    private static $description = 'HTML text block';

    /**
     * Re-title the HTML field to Content
     *
     * {@inheritDoc}
     */
    public function getCMSFields()
    {
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
            $fields
                ->fieldByName('Root.Main.HTML')
                ->setTitle(_t(__CLASS__ . '.ContentLabel', 'Content'))
                ->setSchemaComponent('HtmlEditorField');
        });
        return parent::getCMSFields();
    }

    public function getSummary()
    {
        return DBField::create_field('HTMLText', $this->HTML)->Summary(20);
    }

    protected function provideBlockSchema()
    {
        $blockSchema = parent::provideBlockSchema();
        $blockSchema['content'] = $this->getSummary();
        return $blockSchema;
    }

    public function getType()
    {
        return _t(__CLASS__ . '.BlockType', 'Content');
    }
}

<?php

namespace DNADesign\Elemental\Models;

use SilverStripe\Forms\FieldList;
use SilverStripe\ORM\FieldType\DBField;

class ElementContent extends BaseElement
{
    private static $icon = 'font-icon-block-content';

    private static $db = [
        'HTML' => 'HTMLText'
    ];

    private static $table_name = 'ElementContent';

    private static $singular_name = 'content block';

    private static $plural_name = 'content blocks';

    private static $description = 'HTML text block';

    /**
     * Re-title the HTML field to Content
     *
     * {@inheritDoc}
     */
    public function getCMSFields()
    {
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
            $fields
                ->fieldByName('Root.Main.HTML')
                ->setTitle(_t(__CLASS__ . '.ContentLabel', 'Content'));
        });
        return parent::getCMSFields();
    }

    public function getSummary()
    {
        return DBField::create_field('HTMLText', $this->HTML)->Summary(20);
    }

    protected function provideBlockSchema()
    {
        $blockSchema = parent::provideBlockSchema();
        $blockSchema['content'] = $this->getSummary();
        return $blockSchema;
    }

    public function getType()
    {
        return _t(__CLASS__ . '.BlockType', 'Content');
    }
}

Remove HTMLEditorField schema component definition, done in core now


<?php

/**
 * Created by PhpStorm.
 * User: Boxedsolutions
 * Date: 2016-10-19
 * Time: 12:52
 */
class Billmate_Common_Block_Checkout extends Mage_Core_Block_Template
{
    public function getCheckoutUrl()
    {
        if(Mage::getSingleton('checkout/session')->getBillmateHash()){
            $billmate = Mage::helper('billmatecommon')->getBillmate();
            $checkout = $billmate->getCheckout(array('PaymentData' => array('hash' => Mage::getSingleton('checkout/session')->getBillmateHash())));
            if(!isset($checkout['code'])){
                return $checkout['PaymentData']['url'];
            }

        } else {
            $checkout = Mage::getModel('billmatecommon/checkout')->init();
            Mage::getSingleton('checkout/session')->setBillmateInvoiceId($checkout['number']);
            Mage::log('checkout'.print_r($checkout,true));
            if(!isset($checkout['code'])){
                return $checkout['url'];
            }
        }

    }
}

<?php

/**
 * Created by PhpStorm.
 * User: Boxedsolutions
 * Date: 2016-10-19
 * Time: 12:52
 */
class Billmate_Common_Block_Checkout extends Mage_Core_Block_Template
{
    public function getCheckoutUrl()
    {
        if(Mage::getSingleton('checkout/session')->getBillmateHash()){
            $billmate = Mage::helper('billmatecommon')->getBillmate();
            $checkout = $billmate->getCheckout(array('PaymentData' => array('hash' => Mage::getSingleton('checkout/session')->getBillmateHash())));
            $quote = Mage::getSingleton('checkout/session')->getQuote();
            $total = $quote->getGrandTotal();
            if($checkout['Cart']['Total']['withtax'] != $total){
                $result = Mage::getModel('billmatecommon/checkout')->updateCheckout();
                if(!isset($result['code'])){
                    $checkout = $billmate->getCheckout(array('PaymentData' => array('hash' => Mage::getSingleton('checkout/session')->getBillmateHash())));
                }
            }
            if(!isset($checkout['code'])){
                return $checkout['PaymentData']['url'];
            }

        } else {
            $checkout = Mage::getModel('billmatecommon/checkout')->init();
            Mage::getSingleton('checkout/session')->setBillmateInvoiceId($checkout['number']);
            Mage::log('checkout'.print_r($checkout,true));
            if(!isset($checkout['code'])){
                return $checkout['url'];
            }
        }

    }
}

Fix for if customer leaves checkout, then add products and goes to checkout,


<?php
/**
 * Mondido
 *
 * PHP version 5.6
 *
 * @category Mondido
 * @package  Mondido_Mondido
 * @author   Andreas Karlsson <andreas@kodbruket.se>
 * @license  MIT License https://opensource.org/licenses/MIT
 * @link     https://www.mondido.com
 */

namespace Mondido\Mondido\Controller\Checkout;

/**
 * Error action
 *
 * @category Mondido
 * @package  Mondido_Mondido
 * @author   Andreas Karlsson <andreas@kodbruket.se>
 * @license  MIT License https://opensource.org/licenses/MIT
 * @link     https://www.mondido.com
 */
class Error extends \Magento\Framework\App\Action\Action
{
    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context $context Context object
     *
     * @return void
     */
    public function __construct(\Magento\Framework\App\Action\Context $context)
    {
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return void
     */
    public function execute()
    {
        echo 'Error';
        die();
    }
}

<?php
/**
 * Mondido
 *
 * PHP version 5.6
 *
 * @category Mondido
 * @package  Mondido_Mondido
 * @author   Andreas Karlsson <andreas@kodbruket.se>
 * @license  MIT License https://opensource.org/licenses/MIT
 * @link     https://www.mondido.com
 */

namespace Mondido\Mondido\Controller\Checkout;

/**
 * Error action
 *
 * @category Mondido
 * @package  Mondido_Mondido
 * @author   Andreas Karlsson <andreas@kodbruket.se>
 * @license  MIT License https://opensource.org/licenses/MIT
 * @link     https://www.mondido.com
 */
class Error extends \Mondido\Mondido\Controller\Checkout\Index
{
    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $message = $this->getRequest()->getParam('error_name');
        $this->messageManager->addError(__($message));
        return $this->resultRedirectFactory->create()->setPath('mondido/cart');
    }
}

Add message and redirect to cart if payment fails


<?php

namespace App\Theme\Setup;

/*
|-----------------------------------------------------------
| Theme Custom Services
|-----------------------------------------------------------
|
| This file is for registering your third-parity services
| or custom logic within theme container, so they can
| be easily used for a theme template files later.
|
*/

use function App\Theme\theme;
use Tonik\Gin\Foundation\Theme;

/**
 * Binding handler for book's genres service.
 *
 * @return void
 */
function bind_books_genres_service()
{
    /**
     * Binds service for retrieving genres of the specific book.
     *
     * @param \Tonik\Gin\Foundation\Theme $theme  Instance of the service container
     * @param array $parameters  Parameters passed on service resolving
     *
     * @return \WP_term[]
     */
    theme()->bind('book/genres', function (Theme $theme, $parameters) {
        return wp_get_post_terms($parameters['id'], 'book_grene');
    });
}
add_action('init', 'App\Theme\Setup\bind_books_genres_service');

<?php

namespace App\Theme\Setup;

/*
|-----------------------------------------------------------
| Theme Custom Services
|-----------------------------------------------------------
|
| This file is for registering your third-parity services
| or custom logic within theme container, so they can
| be easily used for a theme template files later.
|
*/

use function App\Theme\theme;
use Tonik\Gin\Foundation\Theme;

/**
 * Service handler for retrieving posts of specific post type.
 *
 * @return void
 */
function bind_books_service()
{
    /**
     * Binds service for retrieving posts of specific post type.
     *
     * @param \Tonik\Gin\Foundation\Theme $theme  Instance of the service container
     * @param array $parameters  Parameters passed on service resolving
     *
     * @return \WP_Post[]
     */
    theme()->bind('books', function (Theme $theme, $parameters) {
        return new WP_Query([
            'post_type' => 'book',
        ]);
    });
}
add_action('init', 'App\Theme\Setup\bind_books_service');

Update example service to follow up with the docs


<?php
/**
 * ownCloud - weather
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @copyright Loic Blot 2015
 */

namespace OCA\Weather\AppInfo;

if (class_exists('\OCP\AppFramework\App')) {
	\OCP\App::addNavigationEntry(array(
	    // the string under which your app will be referenced in owncloud
	    'id' => 'weather',

	    // sorting weight for the navigation. The higher the number, the higher
	    // will it be listed in the navigation
	    'order' => 10,

	    // the route that will be shown on startup
	    'href' => \OCP\Util::linkToRoute('weather.city.index'),

	    // the icon that will be shown in the navigation
	    // this file needs to exist in img/
	    'icon' => \OCP\Util::imagePath('weather', 'app.svg'),

	    // the title of your application. This will be used in the
	    // navigation or on the settings page of your app
	    'name' => \OCP\Util::getL10N('weather')->t('Weather')
	));
} else {
	$msg = 'Can not enable Weather app because the App Framework App is disabled';
	\OCP\Util::writeLog('weather', $msg, \OCP\Util::ERROR);
}

<?php
/**
 * ownCloud - weather
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @copyright Loic Blot 2015
 */

namespace OCA\Weather\AppInfo;

if (class_exists('\OCP\AppFramework\App')) {
	\OC::$server->getNavigationManager()->add(array(
	    // the string under which your app will be referenced in owncloud
	    'id' => 'weather',

	    // sorting weight for the navigation. The higher the number, the higher
	    // will it be listed in the navigation
	    'order' => 10,

	    // the route that will be shown on startup
	    'href' => \OCP\Util::linkToRoute('weather.city.index'),

	    // the icon that will be shown in the navigation
	    // this file needs to exist in img/
	    'icon' => \OCP\Util::imagePath('weather', 'app.svg'),

	    // the title of your application. This will be used in the
	    // navigation or on the settings page of your app
	    'name' => \OCP\Util::getL10N('weather')->t('Weather')
	));
} else {
	$msg = 'Can not enable Weather app because the App Framework App is disabled';
	\OCP\Util::writeLog('weather', $msg, \OCP\Util::ERROR);
}

Use non-deprecated call to add navigation entry

Signed-off-by: Morris Jobke <7f550a9f4c44173a37664d938f1355f0f92a47a7@morrisjobke.de>


<?php

namespace Capgemini\Cache;

/**
 * @class DrupalCacheAdapter
 * @package Capgemini\Cache
 * @codeCoverageIgnore
 */
trait DrupalCacheAdapter {

  public function cache_get($cid, $bin = 'cache') {
    cache_get($cid, $bin);
  }

  public function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
    cache_set($cid, $data, $bin, $expire);
  }

  public function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
    cache_clear_all($cid, $bin, $wildcard);
  }
}

<?php

namespace Capgemini\Cache;

/**
 * @class DrupalCacheAdapter
 * @package Capgemini\Cache
 * @codeCoverageIgnore
 */
trait DrupalCacheAdapter {

  public function cache_get($cid, $bin = 'cache') {
    return cache_get($cid, $bin);
  }

  public function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
    cache_set($cid, $data, $bin, $expire);
  }

  public function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
    cache_clear_all($cid, $bin, $wildcard);
  }
}

Fix not returing cache_get() in bootstrapped mode.


<?php
declare(strict_types = 1);
/**
 * /src/Entity/Traits/Uuid.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
 */

namespace App\Entity\Traits;

use Ramsey\Uuid\Codec\OrderedTimeCodec;
use Ramsey\Uuid\UuidInterface;
use Throwable;

/**
 * Trait Uuid
 *
 * @package App\Entity\Traits
 * @author  TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
 */
trait Uuid
{
    /**
     * @return UuidInterface
     *
     * @throws Throwable
     */
    protected function getUuid(): UuidInterface
    {
        $factory = clone \Ramsey\Uuid\Uuid::getFactory();
        $codec = new OrderedTimeCodec($factory->getUuidBuilder());

        $factory->setCodec($codec);

        return $factory->uuid1();
    }
}

<?php
declare(strict_types = 1);
/**
 * /src/Entity/Traits/Uuid.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
 */

namespace App\Entity\Traits;

use App\Rest\UuidHelper;
use Ramsey\Uuid\UuidInterface;
use Throwable;

/**
 * Trait Uuid
 *
 * @package App\Entity\Traits
 * @author  TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
 */
trait Uuid
{
    /**
     * @return UuidInterface
     *
     * @throws Throwable
     */
    protected function getUuid(): UuidInterface
    {
        return UuidHelper::getFactory()->uuid1();
    }
}

Use the new helper class to do the job.

feat: Use the new helper class to do the job.


<?php

include_once 'header.php';
include_once 'database.php';
include_once 'tohtml.php';

echo userHTML( );

echo '
    <form action="" method="get" accept-charset="utf-8">
    <input type="text" name="query" value="" >
    <button type="submit" name="response" value="Search">Search</button>
    </form>
    ';

if( isset( $_GET[ 'query' ] ) )
{
    $query = $_GET['query' ];
    echo printInfo( "Searching for $query" );

    $awses = queryAWS( $query );
    echo printInfo( "Total matches " .  count( $awses ) );
    foreach( $awses as $aws )
    {
        // Add user info to table.
        $aws['speaker'] .= ',' . loginToText( $aws[ 'speaker' ] );
        echo arrayToVerticalTableHTML( $aws, 'show_aws', ''
            , array( 'id', 'time', 'supervisor_2'
            , 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
        )
    );
        echo '<br>';
    }
}

echo goBackToPageLink( "index.php", "Go back" );

?>

<?php

include_once 'header.php';
include_once 'database.php';
include_once 'tohtml.php';

echo userHTML( );

echo 'Search for a keyword/topic. Currently search is very primitive';
echo '
    <form action="" method="get" accept-charset="utf-8">
    <input type="text" name="query" value="" >
    <button type="submit" name="response" value="Search">Search</button>
    </form>
    ';

if( isset( $_GET[ 'query' ] ) )
{
    $query = $_GET['query' ];
    echo printInfo( "Searching for $query" );

    $awses = queryAWS( $query );
    echo printInfo( "Total matches " .  count( $awses ) );
    foreach( $awses as $aws )
    {
        // Add user info to table.
        $aws['speaker'] .= ',' . loginToText( $aws[ 'speaker' ] );
        echo arrayToVerticalTableHTML( $aws, 'show_aws', ''
            , array( 'id', 'time', 'supervisor_2'
            , 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
        )
    );
        echo '<br>';
    }
}

echo goBackToPageLink( "index.php", "Go back" );

?>

Make sure that admin can add/remove any AWS entry.

Former-commit-id: 78d7e8c51978bb06e96f76c71e685f05692192d2
Former-commit-id: 9c9d2c8abfea2c3e6f1d3c612cb3c4090a7c79fa


<?php get_header(); ?>

<?php wp_title(''); ?>

				<?php get_template_part( 'content', get_post_format() ); ?>

		<?php get_sidebar(); ?>

<?php get_footer(); ?>

<?php get_header(); ?>

			<?php if ( is_active_sidebar('blog_sidebar') ) {
					echo ('
');
				}
				else {
					echo ('
');
				}
			?>

<?php wp_title(''); ?>

				<?php get_template_part( 'content', get_post_format() ); ?>

		<?php get_sidebar(); ?>

<?php get_footer(); ?>

Make blog one column if sidebar isn't active.


Hey {{ $username }}!

Someone (hopefully you!) has signed up to the forum '{{ $forumTitle }}' with this email address.

If this was you, simply visit the following link and your account will be activated:
{{ $url }}

If you did not sign up, just simply ignore this email.

Hey {{ $username }}!

Someone (hopefully you!) has signed up to the forum '{{ $forumTitle }}' with this email address.

If this was you, simply visit the following link and your account will be activated:
{{ $url }}

If you did not sign up, please ignore this email.

Update wording of the confirmation email


<?php
$settings = array(
	'classes'     => array('home'),
	'title'       => 'Titel',
	'description' => 'Beschreibung',
);
include('inc/header.inc.php');
?>

Startseite

Inhalt

<?php include('inc/footer.inc.php'); ?>

<?php
$settings = array(
	'classes'     => array('home'),
	'title'       => 'Titel',
	'description' => 'Beschreibung',
);
include_once('inc/header.inc.php');
?>

Startseite

Inhalt

<?php include_once('inc/footer.inc.php'); ?>

Use include_once() instead of include().


<?php

namespace Scriptotek\Alma\Users;

use Scriptotek\Alma\ResourceList;

class Users extends ResourceList
{
    protected $resourceName = User::class;

    /**
     * Iterates over all users matching the given query.
     * Handles continuation.
     */
    public function search($query, $full = false, $batchSize = 10)
    {
        $offset = 0;
        while (true) {
            $response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);

            foreach ($response->user as $data) {
                $user = User::fromResponse($this->client, $data);
                if ($full) {
                    $user->fetch();
                }
                yield $user;
                $offset++;
            }
            if ($offset >= $response->total_record_count) {
                break;
            }
        }
    }
}

<?php

namespace Scriptotek\Alma\Users;

use Scriptotek\Alma\ResourceList;

class Users extends ResourceList
{
    protected $resourceName = User::class;

    /**
     * Iterates over all users matching the given query.
     * Handles continuation.
     */
    public function search($query, $full = false, $batchSize = 10)
    {
        $offset = 0;
        while (true) {
            $response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);

            if ($response->total_record_count == 0) {
                break;
            }

            foreach ($response->user as $data) {
                $user = User::fromResponse($this->client, $data);
                if ($full) {
                    $user->fetch();
                }
                yield $user;
                $offset++;
            }
            if ($offset >= $response->total_record_count) {
                break;
            }
        }
    }
}

Fix user search with 0 results

Fix user search with 0 results


<?php

session_start();

require_once('include/flight/Flight.php');

require_once('handlers/fb_handlers.php');

Flight::route('/login', 'handle_login');
Flight::route('/fb_callback', 'handle_fb_callback');
Flight::route('/checkin', 'handle_checkin');
Flight::route('/access_code', 'handle_access_code');

require_once('handlers/gw_handlers.php');

Flight::route('/ping', 'handle_ping');
Flight::route('/auth', 'handle_auth');

Flight::start();

?>

<?php

// Configure some security features
// These already have sane defaults in recent PHP versions,
// so consider this as documentation

ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
// This does have a default value listed?
ini_set('session.cookie_httponly', '1');
// HTTPS only!
ini_set('session.cookie_secure', '1');

session_start();

require_once('include/flight/Flight.php');

// Sets up DB
require_once('db.php');

require_once('handlers/fb_handlers.php');

Flight::route('/login', 'handle_login');
Flight::route('/fb_callback', 'handle_fb_callback');
Flight::route('/checkin', 'handle_checkin');
Flight::route('/access_code', 'handle_access_code');

require_once('handlers/gw_handlers.php');

Flight::route('/ping', 'handle_ping');
Flight::route('/auth', 'handle_auth');

Flight::start();

?>

Set up DB, Enable secure sessions

Set up DB, Enable secure sessions


<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli\Question;

use In2pire\Component\Utility\String;

final class Container
{
    public static function create($question, $command)
    {
        static $cache = [];
        $cacheKey = $question;

        if (isset($cache[$cacheKey]))  {
            $class = $cache[$cacheKey]['class'];
            $question = $cache[$cacheKey]['question'];
        } else {
            if (false === strpos($question, '.')) {
                // Not FQCN
                $class = __NAMESPACE__ . '\\' . String::convertToCamelCase($question);
            } else {
                // FQCN
                $class = explode('.', $question);
                $class = array_map(array('In2pire\\Component\\Utility\\String', 'convertToCamelCase'), $class);
                $class = implode('\\', $class);
                $question = substr($question, strrpos($question, '.') + 1);
            }

            $cache[$cacheKey] = [
                'class' => $class,
                'question' => $question
            ];
        }

        $class = __NAMESPACE__ . '\\' . Utility::convertToCamelCase($question);

        if (!class_exists($class)) {
            throw new \RuntimeException('Unknow question ' . $cacheKey);
        }

        return new $class($command);
    }
}

<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli\Question;

use In2pire\Component\Utility\String;

final class Container
{
    public static function create($question, $command)
    {
        static $cache = [];
        $cacheKey = $question;

        if (isset($cache[$cacheKey]))  {
            $class = $cache[$cacheKey]['class'];
            $question = $cache[$cacheKey]['question'];
        } else {
            if (false === strpos($question, '.')) {
                // Not FQCN
                $class = __NAMESPACE__ . '\\' . String::convertToCamelCase($question);
            } else {
                // FQCN
                $class = explode('.', $question);
                $class = array_map(array('In2pire\\Component\\Utility\\String', 'convertToCamelCase'), $class);
                $class = implode('\\', $class);
                $question = substr($question, strrpos($question, '.') + 1);
            }

            $cache[$cacheKey] = [
                'class' => $class,
                'question' => $question
            ];
        }

        if (!class_exists($class)) {
            throw new \RuntimeException('Unknow question ' . $cacheKey);
        }

        return new $class($command);
    }
}

Fix calling to wrong Utility class

Fix calling to wrong Utility class


<?php

class Boom_Controller_Cms_Profile extends Boom_Controller
{
	public function action_view()
	{
		$v = new View('boom/account/profile', array(
			'person' => $this->person,
			'auth' => $this->auth,
			'logs' => $this->person->get_recent_account_activity(),
		));

		$this->response->body($v);
	}

	public function action_save()
	{
		extract($this->request->post());

		$this->person->set('name', $name);

		if ($current_password AND $new_password)
		{
			if ($this->auth->check_password($current_password))
			{
				$this->person->set('password', $this->auth->hash($new_password));
			}
			else
			{
				$this->response
					->status(500)
					->headers('Content-Type', 'application/json')
					->body(json_encode(array('message' => 'Invalid password')));
			}
		}

		$this->person->update();
	}
}

<?php

class Boom_Controller_Cms_Profile extends Boom_Controller
{
	public function action_view()
	{
		$v = new View('boom/account/profile', array(
			'person' => $this->person,
			'auth' => $this->auth,
			'logs' => $this->person->get_recent_account_activity(),
		));

		$this->response->body($v);
	}

	public function action_save()
	{
		extract($this->request->post());

		$this->person->set('name', $name);

		if ($new_password)
		{
			if ( ! $this->person->password OR $this->auth->check_password($current_password))
			{
				$this->person->set('password', $this->auth->hash($new_password));
			}
			else
			{
				$this->response
					->status(500)
					->headers('Content-Type', 'application/json')
					->body(json_encode(array('message' => 'Invalid password')));
			}
		}

		$this->person->update();
	}
}

Allow changing password when no password has been set