@extends('layouts.main')

@section ('breadcrumb')
    back() }}">
        <button type="button" class="btn round-btn pull-right c-yellow">

        </button>

    {!! Breadcrumbs::render('dynamic', $asset) !!}
@endsection

@section ('content')

                <input type="radio" name="tabs" id="tab1" checked>

                        Asset

Asset

{{ $asset->getHostname() ?? $asset->getName() }}

IP Address: {{ $asset->getIpAddressV4() }}

                @include('partials.vulnerabilities-tab', ['tabNo' => 2])

@endsection

@extends('layouts.main')

@section ('breadcrumb')
    previous() }}">
        <button type="button" class="btn round-btn pull-right c-yellow">

        </button>

    {!! Breadcrumbs::render('dynamic', $asset) !!}
@endsection

@section ('content')

                <input type="radio" name="tabs" id="tab1" checked>

                        Asset

Asset

{{ $asset->getHostname() ?? $asset->getName() }}

IP Address: {{ $asset->getIpAddressV4() }}

                @include('partials.vulnerabilities-tab', ['tabNo' => 2])

@endsection

Fix bug with exit button for single asset view.


<?php
/**
 * ZnZend
 *
 * @author Zion Ng <zion@intzone.com>
 * @link   [Source] http://github.com/zionsg/ZnZend
 * @since  2012-11-23T23:00+08:00
 */
namespace ZnZendTest\View\Helper;

use PHPUnit_Framework_TestCase as TestCase;
use ZnZend\View\Helper\ZnZendFormatBytes;

/**
 * Tests ZnZend\View\Helper\ZnZendFormatBytes
 */
class ZnZendFormatBytesTest extends TestCase
{
    /**
     * Helper instance
     *
     * @var ZnZendFormatBytes
     */
    protected $helper;

    /**
     * Prepares the environment before running a test.
     */
    public function setUp()
    {
        // Constructor has no arguments
        $this->helper = new ZnZendFormatBytes();
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        unset($this->helper);
    }

    public function testInvokeWithOneKilobyte()
    {
        $helper = $this->helper;
        $value = 1024;
        $expected = '1.02 KiB';
        $actual = $helper($value);
        $this->assertEquals($expected, $actual);
    }

}

<?php
/**
 * ZnZend
 *
 * @author Zion Ng <zion@intzone.com>
 * @link   [Source] http://github.com/zionsg/ZnZend
 * @since  2012-11-23T23:00+08:00
 */
namespace ZnZendTest\View\Helper;

use PHPUnit_Framework_TestCase as TestCase;
use ZnZend\View\Helper\ZnZendFormatBytes;

/**
 * Tests ZnZend\View\Helper\ZnZendFormatBytes
 */
class ZnZendFormatBytesTest extends TestCase
{
    /**
     * Helper instance
     *
     * @var ZnZendFormatBytes
     */
    protected $helper;

    /**
     * Prepares the environment before running a test.
     */
    public function setUp()
    {
        // Constructor has no arguments
        $this->helper = new ZnZendFormatBytes();
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        unset($this->helper);
    }

    public function testInvokeWithOneKilobyte()
    {
        $helper = $this->helper;
        $value = 1024;
        $expected = '1.00 KiB';
        $actual = $helper($value);
        $this->assertEquals($expected, $actual);
    }

}

Fix introduced error in test

Fix introduced error in test


<?php

namespace AppBundle\Entity;

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

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

    public function getId()
    {
        return $this->id;
    }
}

<?php

namespace AppBundle\Entity;

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

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

    /**
     * @ORM\Column(type="string")
     */
    private $firstName;

    /**
     * @ORM\Column(type="string")
     */
    private $lastName;

    /**
     * @ORM\Column(type="string")
     */
    private $emailAddress;

    /**
     * @return mixed
     */
    public function getEmailAddress()
    {
        return $this->emailAddress;
    }

    /**
     * @param mixed $emailAddress
     */
    public function setEmailAddress($emailAddress)
    {
        $this->emailAddress = $emailAddress;
    }

    /**
     * @return mixed
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * @param mixed $lastName
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }

    /**
     * @return mixed
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * @param mixed $firstName
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
    }

    public function getId()
    {
        return $this->id;
    }
}

Add several properties to Fennec User

Add several properties to Fennec User


<?php

namespace Watson\Breadcrumbs;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/breadcrumbs.php', 'breadcrumbs');

        $this->app->singleton('breadcrumbs', function ($app) {
            return $app->make(Manager::class);
        });
    }

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            // Can't generate breadcrumbs in the console as there is no route
            // from which we can build the trail from.
            return;
        }

        $this->publishes([
            __DIR__.'/../config/breadcrumbs.php' => config_path('breadcrumbs.php'),
        ], 'config');

        $this->publishes([
            __DIR__.'/../views' => resource_path('views/vendor/breadcrumbs')
        ], 'views');

        $this->loadViewsFrom(__DIR__.'/../views', 'breadcrumbs');

        if (file_exists($file = $this->app['path.base'].'/routes/breadcrumbs.php')) {
            require $file;
        }
    }

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

<?php

namespace Watson\Breadcrumbs;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/breadcrumbs.php', 'breadcrumbs');

        $this->app->singleton('breadcrumbs', function ($app) {
            return $app->make(Manager::class);
        });
    }

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/breadcrumbs.php' => config_path('breadcrumbs.php'),
        ], 'config');

        $this->publishes([
            __DIR__.'/../views' => resource_path('views/vendor/breadcrumbs')
        ], 'views');

        $this->loadViewsFrom(__DIR__.'/../views', 'breadcrumbs');

        if (file_exists($file = $this->app['path.base'].'/routes/breadcrumbs.php')) {
            require $file;
        }
    }

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

Allow service provider to run from console


<?php

/**
 * This file is part of the Hayttp package.
 *
 * @author Kim Ravn Hansen <moccalotto@gmail.com>
 * @copyright 2017
 * @license MIT
 */

namespace Hayttp\Traits;

/**
 * Add __debugInfo support.
 *
 * Returns ALL variables.
 */
trait HasCompleteDebugInfo
{
    /**
     * Public accessor for all instance variables.
     *
     * @return array
     */
    public function instanceVariables()
    {
        return get_object_vars($this);
    }

    /**
     * Return debug info for var_dump, et al.
     *
     * @return array
     */
    public function __debugInfo()
    {
        return array_merge(
            $this->instanceVariables(),
            method_exists($this, 'extraDebugInfo') ? $this->extraDebugInfo() : []
        );
    }
}

<?php

/**
 * This file is part of the Hayttp package.
 *
 * @author Kim Ravn Hansen <moccalotto@gmail.com>
 * @copyright 2017
 * @license MIT
 */

namespace Hayttp\Traits;

/**
 * Add __debugInfo support.
 *
 * Returns ALL variables.
 */
trait HasCompleteDebugInfo
{
    /**
     * Public accessor for all instance variables.
     *
     * @return array
     */
    public function instanceVariables()
    {
        return get_object_vars($this);
    }

    /**
     * Return debug info for var_dump, et al.
     *
     * @return array
     */
    public function __debugInfo()
    {
        $extraDebugFunc = [$this, 'extraDebugInfo'];
        $extraDebugInfo = is_callable($extraDebugFunc)
            ? $extraDebugFunc()
            : [];

        return array_merge(
            $this->instanceVariables(),
            $extraDebugInfo
        );
    }
}

Rewrite for better static code analysis

Rewrite for better static code analysis


<?php setup_postdata($post); ?>

            <a href="<?php the_permalink(); ?>">
                <?php if ( has_post_thumbnail() ) { ?>
                    <?php the_post_thumbnail( 'store-product-custom-thumbnail', array('class' => 'img-responsive') ); ?>
                <?php } ?>

                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
                    <?php the_fik_previous_price(); ?><?php the_fik_price(); ?>

                <?php echo get_the_tag_list( '
', ', ', '
') ?>

<?php setup_postdata($post); ?>

        <?php if ( fik_product_stock_quantity() == 0) { ?>
                Out of stock
        <?php } ?>

-->
            <a href="<?php the_permalink(); ?>">
                <?php if ( has_post_thumbnail() ) { ?>
                    <?php the_post_thumbnail( 'store-product-custom-thumbnail', array('class' => 'img-responsive') ); ?>
                <?php } ?>

                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
                    <?php the_fik_previous_price(); ?><?php the_fik_price(); ?>

                <?php echo get_the_tag_list( '
', ', ', '
') ?>

Add out of stock label

Add out of stock label


<?php

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

namespace Flarum\Notification;

use Flarum\Event\ConfigureNotificationTypes;
use Flarum\Foundation\AbstractServiceProvider;
use Flarum\User\User;
use ReflectionClass;

class NotificationServiceProvider extends AbstractServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        $this->registerNotificationTypes();
    }

    /**
     * Register notification types.
     */
    public function registerNotificationTypes()
    {
        $blueprints = [
            'Flarum\Notification\Notification\DiscussionRenamedBlueprint' => ['alert']
        ];

        $this->app->make('events')->fire(
            new ConfigureNotificationTypes($blueprints)
        );

        foreach ($blueprints as $blueprint => $enabled) {
            Notification::setSubjectModel(
                $type = $blueprint::getType(),
                $blueprint::getSubjectModel()
            );

            User::addPreference(
                User::getNotificationPreferenceKey($type, 'alert'),
                'boolval',
                in_array('alert', $enabled)
            );

            if ((new ReflectionClass($blueprint))->implementsInterface('Flarum\Notification\Notification\MailableInterface')) {
                User::addPreference(
                    User::getNotificationPreferenceKey($type, 'email'),
                    'boolval',
                    in_array('email', $enabled)
                );
            }
        }
    }
}

<?php

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

namespace Flarum\Notification;

use Flarum\Event\ConfigureNotificationTypes;
use Flarum\Foundation\AbstractServiceProvider;
use Flarum\User\User;
use ReflectionClass;

class NotificationServiceProvider extends AbstractServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        $this->registerNotificationTypes();
    }

    /**
     * Register notification types.
     */
    public function registerNotificationTypes()
    {
        $blueprints = [
            'Flarum\Notification\Blueprint\DiscussionRenamedBlueprint' => ['alert']
        ];

        $this->app->make('events')->fire(
            new ConfigureNotificationTypes($blueprints)
        );

        foreach ($blueprints as $blueprint => $enabled) {
            Notification::setSubjectModel(
                $type = $blueprint::getType(),
                $blueprint::getSubjectModel()
            );

            User::addPreference(
                User::getNotificationPreferenceKey($type, 'alert'),
                'boolval',
                in_array('alert', $enabled)
            );

            if ((new ReflectionClass($blueprint))->implementsInterface('Flarum\Notification\MailableInterface')) {
                User::addPreference(
                    User::getNotificationPreferenceKey($type, 'email'),
                    'boolval',
                    in_array('email', $enabled)
                );
            }
        }
    }
}

Fix class names in strings

Fix class names in strings


<?php

namespace Huntie\JsonApi\Exceptions;

use Huntie\JsonApi\Support\JsonApiErrors;
use Illuminate\Http\Response;
use Illuminate\Http\Exception\HttpResponseException;

class HttpException extends HttpResponseException
{
    use JsonApiErrors;

    /**
     * Create a new HttpException instance.
     *
     * @param string            $message  The message for this exception
     * @param Response|int|null $response The response object or HTTP status code send to the client
     */
    public function __construct($message, $response = null)
    {
        if (is_null($response)) {
            $response = $this->error(Response::HTTP_BAD_REQUEST, $message);
        } else if (is_int($response)) {
            $response = $this->error($response, $message);
        }

        parent::__construct($response);
    }
}

<?php

namespace Huntie\JsonApi\Exceptions;

use Huntie\JsonApi\Support\JsonApiErrors;
use Illuminate\Foundation\Application;
use Illuminate\Http\Response;

class_alias(
    version_compare(Application::VERSION, '5.4.0', '>=') ?
        'Illuminate\Http\Exceptions\HttpResponseException' :
        'Illuminate\Http\Exception\HttpResponseException',
    __NAMESPACE__ . '\HttpResponseException'
);

class HttpException extends HttpResponseException
{
    use JsonApiErrors;

    /**
     * Create a new HttpException instance.
     *
     * @param string            $message  The message for this exception
     * @param Response|int|null $response The response object or HTTP status code send to the client
     */
    public function __construct($message, $response = null)
    {
        if (is_null($response)) {
            $response = $this->error(Response::HTTP_BAD_REQUEST, $message);
        } else if (is_int($response)) {
            $response = $this->error($response, $message);
        }

        parent::__construct($response);
    }
}

Fix HttpResponseException namespace reference in Laravel 5.4.x


<?php
function theme_enqueue_custom()
{
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_script( 'custom-scripts', get_template_directory_uri() . '/js/scripts.js', array('jquery') );
}

function wp2vanilla_post_comments()
{
    global $wpdb;
    $id = get_the_ID ();
    if ( empty($id) || !$id )
        return null;

    $vanilla_id = $wpdb->get_var($wpdb->prepare("SELECT vanilla_discussion_id FROM " . WP_TO_VANILLA_PREFIX . "map WHERE wp_post_id = %d", $id));
    if ( empty($vanilla_id) || !$vanilla_id )
        return null;

    return '';
}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_custom' );
?>

<?php
function theme_enqueue_custom()
{
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_script( 'custom-scripts', get_stylesheet_directory_uri() . '/js/scripts.js', array('jquery') );
}

function wp2vanilla_post_comments()
{
    global $wpdb;
    $id = get_the_ID ();
    if ( empty($id) || !$id )
        return null;

    $vanilla_id = $wpdb->get_var($wpdb->prepare("SELECT vanilla_discussion_id FROM " . WP_TO_VANILLA_PREFIX . "map WHERE wp_post_id = %d", $id));
    if ( empty($vanilla_id) || !$vanilla_id )
        return null;

    return '';
}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_custom' );
?>

Fix uri to child theme directory

Fix uri to child theme directory


<?php
namespace Sarcofag\View\Helper;

use Sarcofag\Exception\RuntimeException;
use Sarcofag\View\Renderer\RendererInterface;
use Slim\Http\Response;

class LayoutHelper implements HelperInterface
{
    /**
     * @var RendererInterface
     */
    protected $renderer;

    /**
     * LayoutHelper constructor.
     *
     * @param RendererInterface $renderer
     */
    public function __construct(RendererInterface $renderer)
    {
        $this->renderer = $renderer;
    }

    /**
     * @param array $arguments
     *
     * @return mixed
     */
    public function invoke(array $arguments)
    {
        if (!empty($arguments[0])) {
            switch ($arguments[0]) {
                case 'header':
                    return $this->renderer->render('layout/header.phtml');
                case 'footer':
                    return $this->renderer->render('layout/footer.phtml');
            }
        } else {
            return $this->renderer->render('layout/'.$arguments[0].'.phtml');
        }

        return $this->renderer->render('layout/header.phtml');
    }
}

<?php
namespace Sarcofag\View\Helper;

use Sarcofag\Exception\RuntimeException;
use Sarcofag\View\Renderer\RendererInterface;
use Slim\Http\Response;

class LayoutHelper implements HelperInterface
{
    /**
     * @var RendererInterface
     */
    protected $renderer;

    /**
     * LayoutHelper constructor.
     *
     * @param RendererInterface $renderer
     */
    public function __construct(RendererInterface $renderer)
    {
        $this->renderer = $renderer;
    }

    /**
     * @param array $arguments
     *
     * @return mixed
     */
    public function invoke(array $arguments)
    {
        $script = '';
        $args = [];

        if (!empty($arguments[0])) {
            switch ($arguments[0]) {
                case 'header':
                    $script = 'layout/header.phtml';
                    break;
                case 'footer':
                    $script = 'layout/footer.phtml';
                    break;
                default:
                    $script = 'layout/'.$arguments[0].'.phtml';
                    break;
            }
        } else {
            throw new RuntimeException('First argument must be name of the layout, empty given .');
        }

        if (!empty($arguments[1]) && is_array($arguments[1])) {
            $args = $arguments[1];
        }

        return $this->renderer->render($script, $args);
    }
}

Add support for passing variables to the layout parts.


	<?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:
	<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('language')); ?>:
	<?php echo CHtml::encode($data->language); ?>

Remove id from language indexes

Remove id from language indexes


<?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
    protected function _render($includeMaster)
    {
        header('X-Robots-Tag: noindex');
        $domain = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'];
        $hasDynamicParts = false;
        $ret = parent::_render($includeMaster, $hasDynamicParts);
        $ret = str_replace('href="/', 'href="' . $domain . '/', $ret);
        $ret = str_replace('src="/', 'src="' . $domain . '/', $ret);
        $ret = str_replace("src='/", "src='" . $domain . '/', $ret);
        $ret = str_replace('action="/', 'action="' . $domain . '/', $ret);
        $up = Kwf_Config::getValue('uniquePrefix');
        $up = $up ? $up.'-' : '';
        $class = str_replace('kwfUp-', $up, Kwf_Component_Abstract::formatRootElementClass($this->_data->componentClass, '').'Master');
        $ret = preg_replace('#<body class="([^"]+)"#', '<body class="\\1 '.$class.'" data-'.$up.'base-url="'.$domain.'" ', $ret);
        return $ret;
    }
}

<?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
    protected function _render($includeMaster)
    {
        header('X-Robots-Tag: noindex');
        $domain = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'];
        $hasDynamicParts = false;
        $ret = parent::_render($includeMaster, $hasDynamicParts);
        $ret = str_replace('href="/', 'href="' . $domain . '/', $ret);
        $ret = str_replace('src="/', 'src="' . $domain . '/', $ret);
        $ret = str_replace("src='/", "src='" . $domain . '/', $ret);
        $ret = str_replace('action="/', 'action="' . $domain . '/', $ret);
        $up = Kwf_Config::getValue('uniquePrefix');
        $up = $up ? $up.'-' : '';
        $class = str_replace('kwfUp-', $up, Kwf_Component_Abstract::formatRootElementClass($this->_data->componentClass, '').'Master');
        $ret = preg_replace('#<body class="([^"]+)"#', '<body class="\\1 '.$class.'" data-'.$up.'base-url="'.$domain.'" ', $ret);
        $ret = preg_replace('#<!-- postRenderPlugin.*?-->#s', '', $ret);
        return $ret;
    }
}

Remove postRenderPlugin comments in embed HTML

These can break if -- modifier is used inside commented out html (-- ends a html comment :/)


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Test / Unit / Framework / Date / ValueObject
 */

namespace PH7\Test\Unit\Framework\Date\ValueObject;

use PH7\Framework\Date\ValueObject\DateTime as VODateTime;
use PH7\Framework\Date\ValueObject\InvalidDateFormatException;
use PHPUnit_Framework_TestCase;

class DateTimeTest extends PHPUnit_Framework_TestCase
{
    public function testInvalidDateTime()
    {
        $this->expectException(InvalidDateFormatException::class);

        new VODateTime('31-05-2018 10:00:05');
    }

    public function testGetDateTimeValue()
    {
        $sDateValue = '2018-05-31 10:00:05';

        $oDatetime = new VODateTime($sDateValue);
        $this->assertSame($sDateValue, $oDatetime->asString());
    }
}

<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Test / Unit / Framework / Date / ValueObject
 */

namespace PH7\Test\Unit\Framework\Date\ValueObject;

use PH7\Framework\Date\ValueObject\DateTime as VODateTime;
use PH7\Framework\Date\ValueObject\InvalidDateFormatException;
use PHPUnit_Framework_TestCase;

class DateTimeTest extends PHPUnit_Framework_TestCase
{
    public function testGetDateTimeValue()
    {
        $sDateValue = '2018-05-31 10:00:05';

        $oDatetime = new VODateTime($sDateValue);
        $this->assertSame($sDateValue, $oDatetime->asString());
    }

    public function testInvalidDateTime()
    {
        $this->expectException(InvalidDateFormatException::class);

        new VODateTime('31-05-2018 10:00:05');
    }
}

Move down invalid unit test for better consistency


<?php

namespace SimplyTestable\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use SimplyTestable\ApiBundle\Services\WorkerService;
use SimplyTestable\ApiBundle\Services\WorkerRequestActivationService;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputDefinition;
use SimplyTestable\ApiBundle\Entity\Worker;
use SimplyTestable\ApiBundle\Entity\WorkerActivationRequest;

class StatusController extends ApiController
{

    public function indexAction()
    {
        $responseData = array(
            'status' => $this->getApplicationStateService()->getState(),
            'workers' => $this->getWorkerService()->getEntityRepository()->findAll()
        );

        return $this->sendResponse($responseData);
    }

    /**
     *
     * @return WorkerService
     */
    private function getWorkerService() {
        return $this->container->get('simplytestable.services.workerservice');
    }

}

<?php

namespace SimplyTestable\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use SimplyTestable\ApiBundle\Services\WorkerService;
use SimplyTestable\ApiBundle\Services\WorkerRequestActivationService;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputDefinition;
use SimplyTestable\ApiBundle\Entity\Worker;
use SimplyTestable\ApiBundle\Entity\WorkerActivationRequest;

class StatusController extends ApiController
{

    public function indexAction()
    {
        $workers = $this->getWorkerService()->getEntityRepository()->findAll();

        $workerSummary = array();
        foreach ($workers as $worker) {
            $workerSummary[] = array(
                'hostname' => $worker->getHostname(),
                'state' => $worker->getPublicSerializedState()
            );
        }

        $responseData = array(
            'state' => $this->getApplicationStateService()->getState(),
            'workers' => $workerSummary,
            'version' => $this->getLatestGitHash()
        );

        return $this->sendResponse($responseData);
    }

    private function getLatestGitHash() {
        return trim(shell_exec("git log | head -1 | awk {'print $2;'}"));
    }

    /**
     *
     * @return WorkerService
     */
    private function getWorkerService() {
        return $this->container->get('simplytestable.services.workerservice');
    }

}

Add version to summary; restrict worker details in summary to hostname and state


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

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

[Form] Remove "value" attribute on empty_value option

Today we faced a very strange issue with the newest Blackberry 10 browser, it was not submitting our forms. Finally we found that in a ```select``` element, if you have a disabled option, it can't have a value or the HTML5 validator will crash and not submit the form. Of course, setting the ```novalidate``` option for the whole form also solved the issue.

Although I know this must be an issue with the WebKit version the BB10 has it can easily be solved in symfony with this change. In fact, it does make sense since we already have a disabled option with no value if the ```preferred_choices``` are not empty and a ```separator``` is set


<?php

namespace Pterodactyl\Http\Controllers\Auth;

use Pterodactyl\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

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

<?php

namespace Pterodactyl\Http\Controllers\Auth;

use Pterodactyl\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    public $redirectTo = '/';

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

Fix password reset redirection path

Fix password reset redirection path


<?php
namespace Simox;

class Session extends SimoxServiceBase
{
	public function __construct() {}

    public function start()
    {
		session_start();
    }

    public function destroy()
    {
        $_SESSION = Array();
		session_destroy();
    }

	public function set( $name, $value )
	{
		$_SESSION[$name] = $value;
	}

	public function get( $name )
	{
		if ( isset($_SESSION[$name]) )
		{
			return $_SESSION[$name];
		}
		else
		{
			return false;
		}
	}
}

<?php
namespace Simox;

class Session extends SimoxServiceBase
{
	public function __construct() {}

    /**
     * Starts the session
     */
    public function start()
    {
		session_start();
    }

    /**
     * Destroys the session
     */
    public function destroy()
    {
        $_SESSION = Array();
		session_destroy();
    }

    /**
     * Sets the session
     *
     * @param string $key
     * @param string $value
     */
	public function set( $key, $value )
	{
		$_SESSION[$key] = $value;
	}

    /**
     * Returns the session
     *
     * @param string $key
     */
	public function get( $key )
	{
		if ( isset($_SESSION[$key]) )
		{
			return $_SESSION[$key];
		}
		else
		{
			return false;
		}
	}
}

Add comments and use key => value pair

Add comments and use key => value pair


<?php
/**
 * Interface for the Pages form builder
 * Ensures that JS can stay in sync between global page builder and program page builder
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @package jazzee
 * @subpackage admin
 */
interface PagesInterface{
  public function actionListPages();
  public function actionListPageTypes();
  public function actionSavePage($pageId);
  public function actionDeletePage($pageId);
  public function actionPreviewPage($pageId);
  public function actionListElementTypes();
}

?>

<?php
/**
 * Interface for the Pages form builder
 * Ensures that JS can stay in sync between global page builder and program page builder
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @package jazzee
 * @subpackage admin
 */
interface PagesInterface{
  public function actionListPages();
  public function actionListPageTypes();
  public function actionSavePage($pageId);
  public function actionPreviewPage($pageId);
  public function actionListElementTypes();
}

?>

Remove actionDeletePage from the interface.


<?php
/**
 * SocialConnect project
 * @author: Patsura Dmitry @ovr <talk@dmtry.me>
 */

namespace SocialConnect\Vk\Response;

class Collection
{
    protected $total;

    protected $loadCallback;

    protected $elements = [];

    public function __construct($elements, $total, $loadCallback)
    {
        $this->elements = $elements;
        $this->total = $total;
        $this->loadCallback = $loadCallback;
    }
}

<?php
/**
 * SocialConnect project
 * @author: Patsura Dmitry @ovr <talk@dmtry.me>
 */

namespace SocialConnect\Vk\Response;

class Collection
{
    protected $total;

    protected $loadCallback;

    protected $elements = array();

    public function __construct($elements, $total, $loadCallback)
    {
        $this->elements = $elements;
        $this->total = $total;
        $this->loadCallback = $loadCallback;
    }
}

Fix PHP 5.3 BC Support

Fix PHP 5.3 BC Support


<?php

namespace AppBundle\Twig\Extension;

class GpsDMSExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('gps_dms', array($this, 'dmsFilter')),
        );
    }

    public function dmsFilter($number)
    {

        $vars = explode(".",$number);
        $deg = $vars[0];
        $tempma = "0.".$vars[1];

        $tempma = $tempma * 3600;
        $min = floor($tempma / 60);
        $sec = $tempma - ($min*60);

        $coordinate = $deg.'°'.$min.'\'';

        return $coordinate;
    }
}

<?php

namespace AppBundle\Twig\Extension;

class GpsDMSExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('gps_dms', array($this, 'dmsFilter')),
        );
    }

    public function dmsFilter($number)
    {

        $vars = explode(".",$number);
        $deg = $vars[0];
        $tempma = "0.".$vars[1];

        $tempma = $tempma * 3600;
        $min = floor($tempma / 60);
        // Second is $tempma - ($min*60);

        $coordinate = $deg.'°'.$min.'\'';

        return $coordinate;
    }
}

Fix (*): Remove unused variable

Fix (*): Remove unused variable


<?php

namespace DTR\DTRBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class EventController extends Controller
{
    /**
     * @param $hash
     * @return mixed
     *
     * @Route("/event/{hash}")
     */
    public function dashboardAction($hash)
    {
        $user = $this->getUser();

        if(!$user) {
            return $this->redirectToRoute('fos_user_security_login');
        }

        $doctrine = $this->getDoctrine();

        $event = $doctrine->getRepository('DTRBundle:Event')->findOneByHash($hash);
        $member = $doctrine->getRepository('DTRBundle:Member')->findByEventUser($event, $user);

        if($member == null) {
            return new Response('Not a member yet. Need a join button');
        }

        if($member->isHost()) {
            return new Response('Is a host. Need a moderator view.');
        }

        return new Response('Is a simple member. Need a simple view.');
    }
}

<?php

namespace DTR\DTRBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class EventController extends Controller
{
    /**
     * @param $hash
     * @return mixed
     *
     * @Route("/event/{hash}", name="dashboard")
     */
    public function dashboardAction($hash)
    {
        $user = $this->getUser();

        if(!$user) {
            return $this->redirectToRoute('fos_user_security_login');
        }

        $doctrine = $this->getDoctrine();

        $event = $doctrine->getRepository('DTRBundle:Event')->findOneByHash($hash);
        $member = $doctrine->getRepository('DTRBundle:Member')->findByEventUser($event, $user);

        if($member == null) {
            return new Response('Not a member yet. Need a join button');
        }

        if($member->isHost()) {
            return new Response('Is a host. Need a moderator view.');
        }

        return new Response('Is a simple member. Need a simple view.');
    }
}

Add name to dashboard Route.

Add name to dashboard Route.


<?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'];
    }
}

<?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'];
    }
}

Revert "Add workflow_can and workflow_transitions blade extensions"

This reverts commit 300795a3b1fe2494d1da954531b4f37d1aa88ec9.


<?php
/**
 * Created by PhpStorm.
 * User: sgraupner
 * Date: 04/01/2017
 * Time: 14:39.
 */

namespace OParl\Spec\Commands;

class InitializeCommand extends Command
{
    protected $signature = 'oparl:init';

    public function handle()
    {
        $this->call('oparl:init:schema');

        $this->call('oparl:update:specification');
        $this->call('oparl:update:downloads', ['~1.0']);
        $this->call('oparl:update:downloads', ['master']);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: sgraupner
 * Date: 04/01/2017
 * Time: 14:39.
 */

namespace OParl\Spec\Commands;

class InitializeCommand extends Command
{
    protected $signature = 'oparl:init';

    public function handle()
    {
        $this->call('oparl:init:schema');

        $this->call('oparl:update:specification');

        collect(config('oparl.downloads.specification'))
            ->map(function ($downloadVersionConstraint) {
                $this->call('oparl:update:downloads', [$downloadVersionConstraint]);
            });
    }
}

Update intialize command to use constraints


<?php

declare(strict_types=1);

namespace Tests;

use App\Commands\FakeDefaultCommand;
use App\Commands\FakeFooCommand;
use App\HiddenCommands\FakeHiddenCommand;
use App\OtherCommands\FakeOtherCommand;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

final class LoadConfigurationsTest extends TestCase
{
    public function testThatApplicationConfigurationIsAvailable(): void
    {
        $this->assertSame('Application', Artisan::getName());
        $this->assertSame('Test version', $this->app->version());
        $this->assertEquals($this->app->environment(), 'development');
    }

    public function testAddCommands(): void
    {
        $commands = [
            FakeDefaultCommand::class,
            FakeFooCommand::class,
            FakeOtherCommand::class,
            FakeHiddenCommand::class,
        ];

        $appCommands = collect(Artisan::all())
            ->map(
                function ($command) {
                    return get_class($command);
                }
            )
            ->toArray();

        foreach ($commands as $command) {
            $this->assertContains($command, $appCommands);
        }
    }

    public function testHideCommands(): void
    {
        $this->assertTrue(Artisan::all()['fake:hidden']->isHidden());
    }

    public function testRemoveCommands(): void
    {
        $this->assertArrayNotHasKey('fake:removed', Artisan::all());
    }
}

<?php

declare(strict_types=1);

namespace Tests;

use App\Commands\FakeDefaultCommand;
use App\Commands\FakeFooCommand;
use App\HiddenCommands\FakeHiddenCommand;
use App\OtherCommands\FakeOtherCommand;
use Illuminate\Support\Facades\Artisan;

final class LoadConfigurationsTest extends TestCase
{
    public function testThatApplicationConfigurationIsAvailable(): void
    {
        $this->assertSame('Application', Artisan::getName());
        $this->assertSame('Test version', $this->app->version());
        $this->assertEquals($this->app->environment(), 'development');
    }

    public function testAddCommands(): void
    {
        $commands = [
            FakeDefaultCommand::class,
            FakeFooCommand::class,
            FakeOtherCommand::class,
            FakeHiddenCommand::class,
        ];

        $appCommands = collect(Artisan::all())
            ->map(
                function ($command) {
                    return get_class($command);
                }
            )
            ->toArray();

        foreach ($commands as $command) {
            $this->assertContains($command, $appCommands);
        }
    }

    public function testHideCommands(): void
    {
        $this->assertTrue(Artisan::all()['fake:hidden']->isHidden());
    }

    public function testRemoveCommands(): void
    {
        $this->assertArrayNotHasKey('fake:removed', Artisan::all());
    }
}

Fix Style CI unused import

Fix Style CI unused import


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class AlertsController extends Controller
{
  /**
   *
   */
  public function index()
  {
    $stats = [
      'mbp-user-import: MBP_UserCSVfileTools: gatherIMAP attachment: Niche',
      'mbp-user-import: MBP_UserCSVfileTools: gatherIMAP attachment: AfterSchool'
    ];
    return view('alerts.index')->with('stats', $stats);
  }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class AlertsController extends Controller
{
  /**
   *
   */
  public function index()
  {
    $alerts = DB::table('alerts')->get();
    return view('alerts.index')->with('alerts', $alerts);
  }
}

Move to listing database values

Move to listing database values


<?php

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

class Addresses extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('city_id');
            $table->unsignedInteger('country_id');
            $table->unsignedInteger('district_id');
            $table->string('street');
            $table->string('zip_code');
            $table->string('phone_number');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateAddressesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('city_id');
            $table->unsignedInteger('country_id');
            $table->unsignedInteger('district_id');
            $table->string('street');
            $table->string('zip_code');
            $table->string('phone_number');
            $table->timestamps();
        });
    }

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

Rename Address migration class name

refactor(addresses): Rename Address migration class name

Rename Address migration class name

see #53


<?php
global $post, $MODEL;
$ContentType = $MODEL->getSettings('post_type', ['page_id', $post->ID]);
$args = [ 'post_type' => $ContentType, 'orderby' => 'menu_order', 'posts_per_page' => -1];
$ContentQuery = new WP_Query( $args );
if ($ContentQuery->have_posts( )):
  $index = 0;
  while ( $ContentQuery->have_posts( ) ) : $ContentQuery->the_post( );
    $url =  get_the_post_thumbnail_url( $ContentQuery->post->ID, [300, 300] );
    if (empty( $url ) || $url === ''){
      $url = get_template_directory_uri().'/images/cover.jpg';
    }
?>
    <div class="fw-background-container" id="brand_<?= $index ?>" data-name="" data-container='{"w":225, "h":"auto"}' style="background-image: url(<?= $url ?>); width:225px; height: 225px">
      <div class="uk-label uk-position-bottom-left fw-box-title " id="name_<?= $index ?>">
        <a href="<?= get_permalink( $ContentQuery->post->ID ) ?>">
          <?= strtoupper( $ContentQuery->post->post_title ) ?>

<?php
    $index++;
  endwhile;
endif;

<?php
global $post, $MODEL;
/** Polylang class */
$langIds = PLL()->model->post->get_translations(get_the_ID());
$ContentType = $MODEL->getSettings('post_type', ['page_id', $langIds['en']]);
$args = [ 'post_type' => $ContentType, 'orderby' => 'menu_order', 'posts_per_page' => -1];
$ContentQuery = new WP_Query( $args );
if ($ContentQuery->have_posts( )):
  $index = 0;
  while ( $ContentQuery->have_posts( ) ) : $ContentQuery->the_post( );
    $url =  get_the_post_thumbnail_url( $ContentQuery->post->ID, [300, 300] );
    if (empty( $url ) || $url === ''){
      $url = get_template_directory_uri().'/images/cover.jpg';
    }
?>
    <div class="fw-background-container" id="brand_<?= $index ?>" data-name="" data-container='{"w":225, "h":"auto"}' style="background-image: url(<?= $url ?>); width:225px; height: 225px">
      <div class="uk-label uk-position-bottom-left fw-box-title " id="name_<?= $index ?>">
        <a href="<?= get_permalink( $ContentQuery->post->ID ) ?>">
          <?= strtoupper( $ContentQuery->post->post_title ) ?>

<?php
    $index++;
  endwhile;
endif;

Fix portflofio child template view

Fix portflofio child template view


<?php if (!$content->isNew()) { ?>

<a href="<?= $this->url([
        'entity'    => $info->name,
        'action'    => 'edit',
    ], 'core_content', true) . $this->url->query([
        'url' => 'mailto:',
    ], true) ?>" class="btn btn-focus btn-out icon-add">
        New <?= str_replace('URL', 'Email URL', $info->singular) ?>

<?php } ?>

<?php if (!$content->isNew()) { ?>
    <?php if (!isset($node)) { ?>

<a href="<?= $this->url([
            'entity'    => $info->name,
            'action'    => 'edit',
        ], 'core_content', true) . $this->url->query([
            'url' => 'mailto:',
        ], true) ?>" class="btn btn-focus btn-out icon-add">
            New <?= str_replace('URL', 'Email URL', $info->singular) ?>

    <?php } ?>
<?php } ?>

Fix incorrect add URL button

Fix incorrect add URL button


<?php namespace RainLab\User\Controllers;

use Session;
use BackendMenu;
use BackendAuth;
use Backend\Classes\BackendController;

class Users extends BackendController
{
    public $implement = [
        'Backend.Behaviors.FormController',
        'Backend.Behaviors.ListController'
    ];

    public $formConfig = 'config_form.yaml';
    public $listConfig = 'config_list.yaml';

    public $requiredPermissions = ['october.manage_users'];

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

        BackendMenu::setContext('RainLab.User', 'user', 'users');
    }

    /**
     * Manually activate a user
     */
    public function update_onActivate($recordId = null)
    {
        $model = $this->formFindModelObject($recordId);

        $model->attemptActivation($model->activation_code);

        Session::flash('flash.success', 'User has been activated successfully!');

        if ($redirect = $this->makeRedirect('update', $model))
            return $redirect;
    }
}

<?php namespace RainLab\User\Controllers;

use Flash;
use BackendMenu;
use BackendAuth;
use Backend\Classes\BackendController;

class Users extends BackendController
{
    public $implement = [
        'Backend.Behaviors.FormController',
        'Backend.Behaviors.ListController'
    ];

    public $formConfig = 'config_form.yaml';
    public $listConfig = 'config_list.yaml';

    public $requiredPermissions = ['october.manage_users'];

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

        BackendMenu::setContext('RainLab.User', 'user', 'users');
    }

    /**
     * Manually activate a user
     */
    public function update_onActivate($recordId = null)
    {
        $model = $this->formFindModelObject($recordId);

        $model->attemptActivation($model->activation_code);

        Flash::success('User has been activated successfully!');

        if ($redirect = $this->makeRedirect('update', $model))
            return $redirect;
    }
}

Use custom Flash class instead of Session::flash


<?php

namespace CultuurNet\UDB3\Offer\Events\Moderation;

use CultuurNet\UDB3\Offer\Events\AbstractEvent;
use DateTimeInterface;

abstract class AbstractPublished extends AbstractEvent
{
    /**
     * @var DateTimeInterface
     */
    private $publicationDate;

    final public function __construct(string $itemId, DateTimeInterface $publicationDate)
    {
        parent::__construct($itemId);

        $this->publicationDate = $publicationDate;
    }

    public function getPublicationDate(): DateTimeInterface
    {
        return $this->publicationDate;
    }

    public function serialize(): array
    {
        return parent::serialize() + [
            'publication_date' => $this->publicationDate->format(DateTimeInterface::ATOM),
        ];
    }

    public static function deserialize(array $data): AbstractPublished
    {
        return new static(
            $data['item_id'],
            \DateTime::createFromFormat(DateTimeInterface::ATOM, $data['publication_date'])
        );
    }
}

<?php

namespace CultuurNet\UDB3\Offer\Events\Moderation;

use CultuurNet\UDB3\Offer\Events\AbstractEvent;
use DateTime;
use DateTimeInterface;

abstract class AbstractPublished extends AbstractEvent
{
    /**
     * @var DateTimeInterface
     */
    private $publicationDate;

    final public function __construct(string $itemId, DateTimeInterface $publicationDate)
    {
        parent::__construct($itemId);

        $this->publicationDate = $publicationDate;
    }

    public function getPublicationDate(): DateTimeInterface
    {
        return $this->publicationDate;
    }

    public function serialize(): array
    {
        return parent::serialize() + [
            'publication_date' => $this->publicationDate->format(DateTime::ATOM),
        ];
    }

    public static function deserialize(array $data): AbstractPublished
    {
        return new static(
            $data['item_id'],
            DateTime::createFromFormat(DateTime::ATOM, $data['publication_date'])
        );
    }
}

Fix unknown class constant ATOM

Fix unknown class constant ATOM


<?php

/*
* Possible dates between 14-12-2014 and 12-12-2015
* Possible traintypes: IC, L, P, TGV, THA, TRN and EXT
* Possible languages: Dutch, English, French and German (currently only Dutch has been tested)
* Always leave one language uncommented
*/
return array(
    'start_date' => '01-01-2015',
    'end_date' => '14-12-2015',
    'shortNames' => array("IC", "L", "P", "TGV", "THA", "TRN", "EXT"),
    'language' => 'nn' // Dutch
    // 'language' => 'en' // English
    // 'language' => 'fr' // French
    // 'language' => 'de' // German
);

<?php

/*
* Possible dates between 14-12-2014 and 12-12-2015
* Possible traintypes: IC, L, P, TGV, THA, TRN and EXT
* Possible languages: Dutch, English, French and German (currently only Dutch has been tested)
* Always leave one language uncommented
*/
return array(
    'start_date' => '01-01-2015',
    'end_date' => '14-12-2015',
    'shortNames' => array("IC", "L", "P", "TGV", "THA", "TRN", "EXT"),
    'language' => 'nl' // Dutch
    // 'language' => 'en' // English
    // 'language' => 'fr' // French
    // 'language' => 'de' // German
);

Change Dutch to nl instead of nn. Because it works and is more readable


<?php
$base_plugin = $config->get("base_plugin");
$plugin = $plugins[$base_plugin];

$url = str_replace('{page}','player', $config->get("player-url", 'BlueStats-Url'));
$url = str_replace('{player}', $config->get("useUUID", 'BlueStats-Url')=="true"? '{UUID}' : '{NAME}', $url);

$output['info'] = [
    'url' => $url
];

$page = isset($_GET['page']) ? $_GET['page'] : 0;

$search = "";

if (isset($_GET['search'])) {
    $search = $_GET['search'];
}

$output['data'] = $plugin->getUsers(50 * $page, 50, MYSQLI_NUM, $search);

<?php
$base_plugin = $config->get("base_plugin");
$plugin = $plugins[$base_plugin];

$url = str_replace('{page}','player', $config->get("player-url", 'BlueStats-Url'));
$url = str_replace('{player}', $config->get("useUUID", 'BlueStats-Url')=="true"? '{UUID}' : '{NAME}', $url);

$output['info'] = [
    'url' => $url
];

$page = isset($_GET['page']) ? $_GET['page'] : 0;

$search = "";

if (isset($_GET['search'])) {
    $search = $_GET['search'];
}

$output['data'] = $plugin->getUsers(48 * $page, 48, MYSQLI_NUM, $search);

Make number of players divisible by 4

Make number of players divisible by 4


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

namespace Zend\Text\Table\Exception;

use DomainException;

/**
 * @category Zend
 * @package  Zend_Text
 */
class UnexpectedValueException extends DomainException implements ExceptionInterface
{}

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

namespace Zend\Text\Table\Exception;

use DomainException;

/**
 * @category Zend
 * @package  Zend_Text
 */
class InvalidDecoratorException extends DomainException implements ExceptionInterface
{}

Fix exception name in Zend\Text

Fix exception name in Zend\Text


<?php

namespace GoPague;

class Payment extends Resource
{
    public static function create(array $data)
    {
        return static::request('post', 'payment_collections', $data);
    }

    public function approve($document)
    {
        return static::request(
            'post',
            "payment_collections/{$this->uuid}/approve",
            ['cpf_cnpj' => $document]
        );
    }
}

<?php

namespace GoPague;

class Payment extends Resource
{
    public static function create(array $data)
    {
        return static::request('post', 'payment_collections', $data);
    }

    public static function approve(string $uuid, string $document)
    {
        return static::request(
            'post',
            "payment_collections/{$uuid}/approve",
            ['cpf_cnpj' => $document]
    }

}

Transform approve method to static

Transform approve method to static


<?php

namespace DarthSoup\Rundeck;

use DarthSoup\Rundeck\Adapter\AdapterInterface;
use DarthSoup\Rundeck\Api\System;

class Rundeck
{
    /**
     * @var AdapterInterface
     */
    protected $adapter;

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

    /**
     * @param AdapterInterface $adapter
     * @param string $api
     */
    public function __construct(AdapterInterface $adapter, string $api)
    {
        $this->adapter = $adapter;
        $this->api = $api;
    }

    /**
     * @return System
     */
    public function system()
    {
        return new System($this->adapter, $this->api);
    }
}

<?php

namespace DarthSoup\Rundeck;

use DarthSoup\Rundeck\Adapter\AdapterInterface;
use DarthSoup\Rundeck\Api\Execution;
use DarthSoup\Rundeck\Api\Job;
use DarthSoup\Rundeck\Api\Project;
use DarthSoup\Rundeck\Api\System;

class Rundeck
{
    /**
     * @var AdapterInterface
     */
    protected $adapter;

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

    /**
     * @param AdapterInterface $adapter
     * @param string $api
     */
    public function __construct(AdapterInterface $adapter, string $api)
    {
        $this->adapter = $adapter;
        $this->api = $api;
    }

    /**
     * @return System
     */
    public function system()
    {
        return new System($this->adapter, $this->api);
    }

    /**
     * @return Job
     */
    public function job()
    {
        return new Job($this->adapter, $this->api);
    }

    /**
     * @return Execution
     */
    public function execution()
    {
        return new Execution($this->adapter, $this->api);
    }

    /*
     * @return Project
     */
    public function project()
    {
        return new Project($this->adapter, $this->api);
    }
}

Add api calls to manager

Add api calls to manager


<?php

require 'letterScore.php';

$input = hex2bin("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
$inputLength = strlen($input);
$scores = [];

function sb_xor($encryptedString, $xor_key) {
  $decryptedString = '';

  for ($i = 0; $i < strlen($encryptedString); $i++) {
    $decryptedString .= $encryptedString{$i} ^ chr($xor_key);
  }

  return $decryptedString;
}

for ($kv=0; $kv < 256; $kv++) {
  $charScore = 0;

  $plainText = sb_xor($input, $kv);

  $charScore = englishLetterWeight($plainText, 0.5);

  $scores[chr($kv)] = $charScore;

}

arsort($scores);

$keyCount = 0;
foreach ($scores as $key => $value) {
  if ($keyCount < 5) {
    $decrypt = '';

    for ($i=0; $i < $inputLength; $i++) {
      $decrypt .= $input{$i} ^ $key;
    }

    echo "'$key' (" . ord($key) . ") : " . $decrypt . "\n";
  } else {
    break;
  }

  $keyCount++;

}

?>

<?php

require 'letterScore.php';

$input = hex2bin("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
$inputLength = strlen($input);
$scores = [];

function sb_xor($encryptedString, $xor_key) {
  $decryptedString = '';

  for ($i = 0; $i < strlen($encryptedString); $i++) {
    $decryptedString .= $encryptedString{$i} ^ $xor_key;
  }

  return $decryptedString;
}

for ($kv=0; $kv < 256; $kv++) {
  $charScore = 0;

  $plainText = sb_xor($input, chr($kv));

  $charScore = englishLetterWeight($plainText, 0.5);

  $scores[chr($kv)] = $charScore;

}

arsort($scores);

$keyCount = 0;
foreach ($scores as $key => $value) {
  if ($keyCount < 5) {
    $decrypt = sb_xor($input, $key);

    echo "'$key' (" . ord($key) . ") : " . $decrypt . "\n";
  } else {
    break;
  }

  $keyCount++;

}

?>

Change final decrypt to use function

Change final decrypt to use function

Also changed function to expect key as chr.


<?php
namespace Aws\Test\Route53;

use Aws\Route53\Route53Client;

/**
 * @covers Aws\Route53\Route53Client
 */
class Route53ClientTest extends \PHPUnit_Framework_TestCase
{
    public function testCleansIds()
    {
        $client = new Route53Client([
            'service' => 'route53',
            'region'  => 'us-west-2',
            'version' => 'latest'
        ]);

        $command = $client->getCommand('ChangeResourceRecordSets', [
            'HostedZoneId' => '/hostedzone/foo',
            'ChangeBatch'  => [
                'Changes' => [
                    'bar' => [
                        'Action' => 'foo',
                        'ResourceRecordSet' => [
                            'Name' => 'baz',
                            'Type' => 'abc'
                        ]
                    ]
                ]
            ]
        ]);

        $request = \Aws\serialize($command);

        $this->assertContains(
            '/hostedzone/foo/rrset/',
            (string) $request->getUri()
        );
    }
}

<?php
namespace Aws\Test\Route53;

use Aws\Route53\Route53Client;

/**
 * @covers Aws\Route53\Route53Client
 */
class Route53ClientTest extends \PHPUnit_Framework_TestCase
{
    public function testCleansIds()
    {
        $client = new Route53Client([
            'service' => 'route53',
            'region'  => 'us-west-2',
            'version' => 'latest'
        ]);

        $command = $client->getCommand('ChangeResourceRecordSets', [
            'HostedZoneId' => '/hostedzone/foo',
            'ChangeBatch'  => [
                'Changes' => [
                    'bar' => [
                        'Action' => 'foo',
                        'ResourceRecordSet' => [
                            'Name' => 'baz',
                            'Type' => 'abc'
                        ]
                    ]
                ]
            ]
        ]);

        $request = \Aws\serialize($command);
        $requestUri = (string) $request->getUri();
        $this->assertContains('/hostedzone/foo/rrset/', $requestUri);
        $this->assertNotContains('/hostedzone/hostedzone', $requestUri);

        $command = $client->getCommand('GetReusableDelegationSet', [
            'Id' => '/delegationset/foo',
        ]);

        $request = \Aws\serialize($command);
        $requestUri = (string) $request->getUri();
        $this->assertContains('/delegationset/foo', $requestUri);
        $this->assertNotContains('/delegationset/delegationset', $requestUri);

        $command = $client->getCommand('CreateHostedZone', [
            'Name' => 'foo',
            'CallerReference' => '123',
            'DelegationSetId' => '/delegationset/bar',
        ]);

        $request = \Aws\serialize($command);
        $this->assertContains(
            '<DelegationSetId>bar</DelegationSetId>',
            $request->getBody()->getContents()
        );
    }
}

Add more tests for Route53Client::cleanId


<?php

namespace Spatie\Tail\Tests;

class TailCommandTest extends TestCase
{
    /** @test */
    public function it_will_throw_an_exception_if_the_given_environment_is_not_configured()
    {
        $this->expectExceptionMessageMatches('/^No configuration set/');

        $this->artisan('tail', [
            'environment' => 'non-existing-environment',
        ]);
    }

    /** @test */
    public function the_tail_command_is_correct()
    {
        $this
            ->artisan('tail', [
                '--debug' => true,
            ])
            ->expectsOutput('tail -f -n 0 "`ls -t | head -1`"');
    }

    /** @test */
    public function the_tail_command_with_file_is_correct()
    {
        $this
            ->artisan('tail', [
                '--debug' => true,
                '--file' => 'file.log',
            ])
            ->expectsOutput('tail -f -n 0 "file.log"');
    }

    /** @test */
    public function the_command_when_grepping_is_correct()
    {
        $this
            ->artisan('tail', [
                '--debug' => true,
                '--grep' => 'test',
            ])
            ->expectsOutput('tail -f -n 0 "`ls -t | head -1`" | grep "test"');
    }
}

<?php

namespace Spatie\Tail\Tests;

class TailCommandTest extends TestCase
{
    /** @test */
    public function it_will_throw_an_exception_if_the_given_environment_is_not_configured()
    {
        $this->expectExceptionMessageMatches('/^No configuration set/');

        $this->artisan('tail', [
            'environment' => 'non-existing-environment',
        ]);
    }

    /** @test */
    public function the_tail_command_is_correct()
    {
        $this
            ->artisan('tail', [
                '--debug' => true,
            ])
            ->expectsOutput('\\tail -f -n 0 "`\\ls -t | \\head -1`"');
    }

    /** @test */
    public function the_tail_command_with_file_is_correct()
    {
        $this
            ->artisan('tail', [
                '--debug' => true,
                '--file' => 'file.log',
            ])
            ->expectsOutput('\\tail -f -n 0 "file.log"');
    }

    /** @test */
    public function the_command_when_grepping_is_correct()
    {
        $this
            ->artisan('tail', [
                '--debug' => true,
                '--grep' => 'test',
            ])
            ->expectsOutput('\\tail -f -n 0 "`\\ls -t | \\head -1`" | \\grep "test"');
    }
}

Update tail command tests to check for backslashes


<?php

namespace AlgoWeb\PODataLaravel\Models;

use Illuminate\Foundation\Application;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\ProviderRepository;

class TestApplication extends Application
{
    protected $filesys;
    protected $inConsole = true;

    public function __construct(Filesystem $file)
    {
        parent::__construct();
        $this->filesys = $file;
    }

    /**
     * Register all of the configured providers.
     *
     * @return void
     */
    public function registerConfiguredProviders()
    {
        $this->basePath = dirname(__DIR__);
        $manifestPath = $this->getCachedServicesPath();

        (new ProviderRepository($this, $this->filesys, $manifestPath))
            ->load($this->config['app.providers']);
    }

    public function runningInConsole()
    {
        return $this->inConsole;
    }

    public function setConsole($flag)
    {
        $this->inConsole = true === $flag;
    }
}

<?php

namespace AlgoWeb\PODataLaravel\Models;

use Illuminate\Foundation\Application;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\ProviderRepository;

class TestApplication extends Application
{
    protected $filesys;
    protected $inConsole = true;

    public function __construct(Filesystem $file)
    {
        parent::__construct(dirname(__DIR__));
        $this->filesys = $file;
    }

    /**
     * Register all of the configured providers.
     *
     * @return void
     */
    public function registerConfiguredProviders()
    {
        $this->basePath = dirname(__DIR__);
        $manifestPath = $this->getCachedServicesPath();

        (new ProviderRepository($this, $this->filesys, $manifestPath))
            ->load($this->config['app.providers']);
    }

    public function runningInConsole()
    {
        return $this->inConsole;
    }

    public function setConsole($flag)
    {
        $this->inConsole = true === $flag;
    }
}

Add base path to test application constructor


Fix thumb setting on local, causing thumbs to fail.


<?php

namespace Pagon\Middleware;

use Pagon\Logger;
use Pagon\Middleware;
use Pagon\Utility\Cryptor;

class Booster extends Middleware
{
    public function call()
    {
        $app = $this->app;

        // Set encoding
        iconv_set_encoding("internal_encoding", $app->charset);
        mb_internal_encoding($app->charset);

        // Configure timezone
        date_default_timezone_set($app->timezone);

        // Share the cryptor for the app
        if (!empty($app->crypt)) {
            $app->cryptor = new Cryptor($app->crypt);
        }

        // Share the logger for the app
        if (!empty($app->log)) {
            $app->logger = Logger::dispense();
        }

        // Configure debug
        if ($app->debug) self::graft('PrettyException');
    }
}

<?php

namespace Pagon\Middleware;

use Pagon\Logger;
use Pagon\Middleware;
use Pagon\Utility\Cryptor;

class Booster extends Middleware
{
    /**
     * @var array Default options
     */
    protected $options = array(
        'logger'  => 'log',
        'cryptor' => 'crypt'
    );

    public function call()
    {
        $app = $this->app;

        // Set encoding
        iconv_set_encoding("internal_encoding", $app->charset);
        mb_internal_encoding($app->charset);

        // Configure timezone
        date_default_timezone_set($app->timezone);

        // Share the cryptor for the app
        if (!$_crypt = $app->get($this->options['cryptor'])) {
            $app->cryptor = new Cryptor($_crypt);
        }

        // Share the logger for the app
        if (!$_log = $app->get($this->options['logger'])) {
            $app->logger = new Logger($_log);
        }

        // Configure debug
        if ($app->debug) self::graft('PrettyException');
    }
}

Support setting logger and cryptor config node name


<?php

namespace AppBundle\Controller;

use AppBundle\Model\CastingUser;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class FormController extends AbstractController
{
    public function create(Request $request)
    {
        $user = new CastingUser();
        $form = $this->createFormBuilder($user)
            ->add('name')
            ->add('password')
            ->add('date_of_birth')
            ->add('is_admin')
            ->add('submit', SubmitType::class)
            ->getForm();

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $user->save();

            return new Response('Successfully created user!');
        }

        return $this->render('form/create.twig', ['form' => $form->createView()]);
    }
}

<?php

namespace AppBundle\Controller;

use AppBundle\Model\CastingUser;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

if (class_exists('Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController')) {
    class ParentFormController extends AbstractController {}
} else {
    class ParentFormController extends Controller {}
}

class FormController extends ParentFormController
{
    public function create(Request $request)
    {
        $user = new CastingUser();
        $form = $this->createFormBuilder($user)
            ->add('name')
            ->add('password')
            ->add('date_of_birth')
            ->add('is_admin')
            ->add('submit', SubmitType::class)
            ->getForm();

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $user->save();

            return new Response('Successfully created user!');
        }

        return $this->render('form/create.twig', ['form' => $form->createView()]);
    }
}

Add backwards compatibility for old Symfony versions


<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function echoEvent($datatext) {
    if(!isset($_GET["IE"]))
      echo "data: ".implode("\ndata: ", explode("\n", $datatext))."\n\n";
    else
      echo $datatext;
}

if(isset($_GET["upload"]))
{
	$proc = popen("sudo pihole -d -a", "r");
}
else
{
	$proc = popen("sudo pihole -d", "r");
}
while (!feof($proc)) {
    echoEvent(fread($proc, 4096));
}
?>

<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function echoEvent($datatext) {
    if(!isset($_GET["IE"]))
      echo "data: ".implode("\ndata: ", explode("\n", $datatext))."\n\n";
    else
      echo $datatext;
}

if(isset($_GET["upload"]))
{
	$proc = popen("sudo pihole -d -a -w", "r");
}
else
{
	$proc = popen("sudo pihole -d -w", "r");
}
while (!feof($proc)) {
    echoEvent(fread($proc, 4096));
}
?>

Add undocumented -w flag to alter the countdown behavior.

Signed-off-by: Dan Schaper <e0d147bd42e37db009403956b01c29435870b195@pi-hole.net>


<?php

namespace mcordingley\Regression\Algorithm\GradientDescent\StoppingCriteria;

final class Any implements StoppingCriteria
{
    /** @var array */
    private $criteriaList = [];

    /**
     * @param array $criteriaList Array of StoppingCriteria instances
     */
    public function __construct(array $criteriaList = [])
    {
        foreach ($criteriaList as $criteria) {
            $this->addCriteria($criteria);
        }
    }

    /**
     * @param array $gradient
     * @param array $coefficients
     * @return bool
     */
    public function converged(array $gradient, array $coefficients)
    {
        /** @var StoppingCriteria $criteria */
        foreach ($this->criteriaList as $criteria) {
            if ($criteria->converged($gradient, $coefficients)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param StoppingCriteria $criteria
     */
    public function addCriteria(StoppingCriteria $criteria)
    {
        $this->criteriaList[] = $criteria;
    }
}

<?php

namespace mcordingley\Regression\Algorithm\GradientDescent\StoppingCriteria;

/**
 * Checks for when any of a given list of stopping criteria is met.
 *
 * @package mcordingley\Regression\Algorithm\GradientDescent\StoppingCriteria
 */
final class Any implements StoppingCriteria
{
    /** @var array */
    private $criteriaList = [];

    /**
     * @param array $criteriaList Array of StoppingCriteria instances
     */
    public function __construct(array $criteriaList = [])
    {
        foreach ($criteriaList as $criteria) {
            $this->addCriteria($criteria);
        }
    }

    /**
     * @param array $gradient
     * @param array $coefficients
     * @return bool
     */
    public function converged(array $gradient, array $coefficients)
    {
        /** @var StoppingCriteria $criteria */
        foreach ($this->criteriaList as $criteria) {
            if ($criteria->converged($gradient, $coefficients)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param StoppingCriteria $criteria
     */
    public function addCriteria(StoppingCriteria $criteria)
    {
        $this->criteriaList[] = $criteria;
    }
}

Document the "any" stopping criteria.

Document the "any" stopping criteria.


<?php

namespace BNETDocs\Libraries;

use \BNETDocs\Libraries\Exceptions\TemplateNotFoundException;
use \BNETDocs\Libraries\Logger;
use \SplObjectStorage;

final class Template {

  protected $additional_css;
  protected $context;
  protected $opengraph;
  protected $template;

  public function __construct(&$context, $template) {
    $this->additional_css = [];
    $this->opengraph      = new SplObjectStorage();
    $this->setContext($context);
    $this->setTemplate($template);
  }

  public function getContext() {
    return $this->context;
  }

  public function getTemplate() {
    return $this->template;
  }

  public function render() {
    $cwd = getcwd();
    try {
      chdir($cwd . "/templates");
      if (!file_exists($this->template)) {
        throw new TemplateNotFoundException($this);
      }
      require($this->template);
    } finally {
      chdir($cwd);
    }
  }

  public function setContext(&$context) {
    $this->context = $context;
  }

  public function setTemplate($template) {
    $this->template = "./" . $template . ".phtml";
    Logger::logMetric("template", $template);
  }

}

<?php

namespace BNETDocs\Libraries;

use \BNETDocs\Libraries\Exceptions\TemplateNotFoundException;
use \BNETDocs\Libraries\Logger;
use \SplObjectStorage;

final class Template {

  const TEMPLATE_DIR = "/templates";

  protected $additional_css;
  protected $context;
  protected $opengraph;
  protected $template;

  public function __construct(&$context, $template) {
    $this->additional_css = [];
    $this->opengraph      = new SplObjectStorage();
    $this->setContext($context);
    $this->setTemplate($template);
  }

  public function getContext() {
    return $this->context;
  }

  public function getTemplate() {
    return $this->template;
  }

  public function render() {
    $cwd = getcwd();
    try {
      chdir($cwd . self::TEMPLATE_DIR);
      if (!file_exists($this->template)) {
        throw new TemplateNotFoundException($this);
      }
      require($this->template);
    } finally {
      chdir($cwd);
    }
  }

  public function setContext(&$context) {
    $this->context = $context;
  }

  public function setTemplate($template) {
    $this->template = "./" . $template . ".phtml";
    Logger::logMetric("template", $template);
  }

}

Move template directory string to constant


<?php

namespace Mjarestad\Filtry;

use Illuminate\Support\ServiceProvider;

class FiltryServiceProviderLaravel5 extends ServiceProvider
{
    /**
     * Register the service provider.
     * @return void
     */
    public function register()
    {
        $this->app['filtry'] = $this->app->share(function($app) {
            return new Filtry;
        });
    }
}

<?php

namespace Mjarestad\Filtry;

use Illuminate\Support\ServiceProvider;

class FiltryServiceProviderLaravel5 extends ServiceProvider
{
    /**
     * Register the service provider.
     * @return void
     */
    public function register()
    {
        $this->app->singleton('filtry', function($app) {
            return new Filtry;
        });
    }
}

Use singleton instead of removed share method


<?php
namespace Oro\Bundle\CurrencyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Oro\Bundle\DataAuditBundle\Metadata\Annotation as Oro;

class MultiCurrency
{
    use CurrencyAwareTrait;

    protected $value;
    protected $rate;
    protected $baseCurrencyValue;

    /**
     * @param string $value
     * @param string $currency
     * @param float $rate | null
     * @return MultiCurrency
     */
    public static function create($value, $currency, $rate = null)
    {
        /* @var $multiCurrency self */
        $multiCurrency = new static();
        $multiCurrency->setValue($value)
            ->setCurrency($currency)
            ->setRate($rate);

        return $multiCurrency;
    }

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

    /**
     * @param string $value
     * @return $this
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @return float
     */
    public function getRate()
    {
        return $this->rate;
    }

    /**
     * @param float $rate
     * @return $this
     */
    public function setRate($rate)
    {
        $this->rate = $rate;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getBaseCurrencyValue()
    {
        return $this->baseCurrencyValue;
    }

    /**
     * @param $baseCurrencyValue
     * @return $this
     */
    public function setBaseCurrencyValue($baseCurrencyValue)
    {
        $this->baseCurrencyValue = $baseCurrencyValue;

        return $this;
    }
}

<?php
namespace Oro\Bundle\CurrencyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Oro\Bundle\DataAuditBundle\Metadata\Annotation as Oro;

class MultiCurrency
{
    use CurrencyAwareTrait;

    protected $value;
    protected $baseCurrencyValue = null;

    /**
     * @param string $value
     * @param string $currency
     * @param string | null $baseCurrencyValue
     * @return MultiCurrency
     */
    public static function create($value, $currency, $baseCurrencyValue = null)
    {
        /* @var $multiCurrency self */
        $multiCurrency = new static();
        $multiCurrency->setValue($value)
            ->setCurrency($currency)
            ->setBaseCurrencyValue($baseCurrencyValue);

        return $multiCurrency;
    }

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

    /**
     * @param string $value
     * @return $this
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getBaseCurrencyValue()
    {
        return $this->baseCurrencyValue;
    }

    /**
     * @param $baseCurrencyValue
     * @return $this
     */
    public function setBaseCurrencyValue($baseCurrencyValue)
    {
        $this->baseCurrencyValue = $baseCurrencyValue;

        return $this;
    }
}

OEE-1075: Update rate converter to support fixation logic
- Add freeze case in unit tests
- Rewrite converter for base currency amount usage instead of rate
- Remove unused param from convert method


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

            <?php echo $article->getDate(); ?> / by
            <?php echo $article->getAuthor(); ?>

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

        <?php if ($article->hasCategories()): ?>

            <?php foreach ($article->getCategories() as $category): ?>
                <a href="<?php echo $category['link']; ?>"><?php echo $category['name']; ?>
            <?php endforeach; ?>

        <?php endif; ?>

Add output of artice meta and categories


<?php
class Lexical{
    static $scopes = array();

    public static function init_closure($ns, $id){
        if(isset(self::$scopes[$ns][$id])){
            self::$scopes[$ns][$id][] = array();
        }else{
            self::$scopes[$ns][$id] = array(array());
        }
        return $id;
    }

    public static function get_closure_id($ns, $id){
        if($id === Null){
            return Null;
        }else{
            return count(self::$scopes[$ns][$id])-1;
        }
    }

    public static function bind_lexing($ns, $id, $var, &$val){
        $closure_id = self::get_closure_id($ns, $id);
        self::$scopes[$ns][$id][$closure_id][$var] =& $val;
    }

    public static function get_lexical_binding($ns, $id, $var, $closure_id){
        return self::$scopes[$ns][$id][$closure_id][$var];
    }
}

<?php
namespace Pharen;
class Lexical{
    static $scopes = array();

    public static function init_closure($ns, $id){
        if(isset(self::$scopes[$ns][$id])){
            self::$scopes[$ns][$id][] = array();
        }else{
            self::$scopes[$ns][$id] = array(array());
        }
        return $id;
    }

    public static function get_closure_id($ns, $id){
        if($id === Null){
            return Null;
        }else{
            return count(self::$scopes[$ns][$id])-1;
        }
    }

    public static function bind_lexing($ns, $id, $var, &$val){
        $closure_id = self::get_closure_id($ns, $id);
        self::$scopes[$ns][$id][$closure_id][$var] =& $val;
    }

    public static function get_lexical_binding($ns, $id, $var, $closure_id){
        return self::$scopes[$ns][$id][$closure_id][$var];
    }
}

Put Lexical in its own namespace: Pharen.


<?php

namespace Alpixel\Bundle\UserBundle\Controller;

use FOS\UserBundle\Controller\SecurityController as BaseController;
use Symfony\Component\HttpFoundation\Request;

class SecurityController extends BaseController
{
    public function renderLogin(array $data)
    {
        $request = $this->container->get('request');

        $template = 'AlpixelUserBundle:admin:page/login.html.twig';

        $firewallTemplates = $this->container->getParameter('alpixel_user.firewall_templates');
        foreach ($firewallTemplates as $templateParam) {
            $path = str_replace('/'.$request->getLocale(), '', $request->getPathInfo());
            if ($templateParam['login_path'] === $path) {
                $template = $templateParam['login_template'];
                break;
            }
        }

        return $this->container->get('templating')->renderResponse($template, array_merge($data, [
            'background_image' => $this->container->getParameter('alpixel_user.default_login_background_image'),
            'color'            => $this->container->getParameter('alpixel_user.default_login_background_color'),
        ]));
    }
}

<?php

namespace Alpixel\Bundle\UserBundle\Controller;

use FOS\UserBundle\Controller\SecurityController as BaseController;
use Symfony\Component\HttpFoundation\Request;

class SecurityController extends BaseController
{
    public function renderLogin(array $data)
    {
        $request = $this->container->get('request_stack')->getCurrentRequest();

        $template = 'AlpixelUserBundle:admin:page/login.html.twig';

        $firewallTemplates = $this->container->getParameter('alpixel_user.firewall_templates');
        foreach ($firewallTemplates as $templateParam) {
            $path = str_replace('/'.$request->getLocale(), '', $request->getPathInfo());
            if ($templateParam['login_path'] === $path) {
                $template = $templateParam['login_template'];
                break;
            }
        }

        return $this->container->get('templating')->renderResponse($template, array_merge($data, [
            'background_image' => $this->container->getParameter('alpixel_user.default_login_background_image'),
            'color'            => $this->container->getParameter('alpixel_user.default_login_background_color'),
        ]));
    }
}

Fix missing request service from service, use request_stack instead


<?php

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\ORM\Event\OnClearEventArgs;
use Doctrine\ORM\Events;

require_once __DIR__ . '/../../TestInit.php';

/**
 * ClearEventTest
 *
 * @author Michael Ridgway
 */
class ClearEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp() {
        parent::setUp();
    }

    public function testEventIsCalledOnClear()
    {
        $listener = new OnClearListener;
        $this->_em->getEventManager()->addEventListener(Events::onClear, $listener);

        $this->_em->clear();

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

class OnClearListener
{
    public $called = false;

    public function onClear(OnClearEventArgs $args)
    {
        $this->called = true;
    }
}

<?php

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\ORM\Event\OnClearEventArgs;
use Doctrine\ORM\Events;

require_once __DIR__ . '/../../TestInit.php';

/**
 * ClearEventTest
 *
 * @author Michael Ridgway <mcridgway@gmail.com>
 */
class ClearEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp() {
        parent::setUp();
    }

    public function testEventIsCalledOnClear()
    {
        $listener = new OnClearListener;
        $this->_em->getEventManager()->addEventListener(Events::onClear, $listener);

        $this->_em->clear();

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

class OnClearListener
{
    public $called = false;

    public function onClear(OnClearEventArgs $args)
    {
        $this->called = true;
    }
}

Clean up of test case

Clean up of test case


<?php
namespace Robo\Task\Development;

use Robo\Task\Base\Exec;

/**
 * Runs PHP server and stops it when task finishes.
 *
 * ``` php
 * <?php
 * // run server in /public directory
 * $this->taskServer(8000)
 *  ->dir('public')
 *  ->run();
 *
 * // run with IP 0.0.0.0
 * $this->taskServer(8000)
 *  ->host('0.0.0.0')
 *  ->run();
 *
 * // execute server in background
 * $this->taskServer(8000)
 *  ->background()
 *  ->run();
 * ?>
 * ```
 */
class PhpServer extends Exec
{
    protected $port;
    protected $host = '127.0.0.1';
    protected $command = 'php -S %s:%d ';

    public function __construct($port)
    {
        $this->port = $port;

        if (strtolower(PHP_OS) === 'linux') {
            $this->command = 'exec php -S %s:%d';
        }
    }

    public function host($host)
    {
        $this->host = $host;
        return $this;
    }

    public function dir($path)
    {
        $this->command .= "-t $path";
        return $this;
    }

    public function getCommand()
    {
        return sprintf($this->command . $this->arguments, $this->host, $this->port);
    }

}

<?php
namespace Robo\Task\Development;

use Robo\Task\Base\Exec;

/**
 * Runs PHP server and stops it when task finishes.
 *
 * ``` php
 * <?php
 * // run server in /public directory
 * $this->taskServer(8000)
 *  ->dir('public')
 *  ->run();
 *
 * // run with IP 0.0.0.0
 * $this->taskServer(8000)
 *  ->host('0.0.0.0')
 *  ->run();
 *
 * // execute server in background
 * $this->taskServer(8000)
 *  ->background()
 *  ->run();
 * ?>
 * ```
 */
class PhpServer extends Exec
{
    protected $port;
    protected $host = '127.0.0.1';
    protected $command = 'php -S %s:%d ';

    public function __construct($port)
    {
        $this->port = $port;

        if (strtolower(PHP_OS) === 'linux') {
            $this->command = 'exec php -S %s:%d ';
        }
    }

    public function host($host)
    {
        $this->host = $host;
        return $this;
    }

    public function dir($path)
    {
        $this->command .= "-t $path";
        return $this;
    }

    public function getCommand()
    {
        return sprintf($this->command . $this->arguments, $this->host, $this->port);
    }

}

Add trailing space to command to stay consistent


<?php

/*
 * This file is part of the Subway package.
 *
 * (c) Eymen Gunay <eymen@egunay.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Subway\Command;

use Subway\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Clear command
 */
class ClearCommand extends RedisAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('clear')
            ->setDescription('Clear subway database')
        ;

        parent::configure();
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($input->getOption('no-interaction') === false) {
            $dialog = $this->getHelperSet()->get('dialog');
            if (!$dialog->askConfirmation(
                    $output,
                    '<question>This action will erase entire subway database. Are you sure you want to continue? (Y/n)</question>',
                    true
                )) {
                return;
            }
        }

        $factory = new Factory($this->redis);
        $factory->clear();
        $output->writeln('<info>Database cleared successfully</info>');
    }
}

<?php

/*
 * This file is part of the Subway package.
 *
 * (c) Eymen Gunay <eymen@egunay.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Subway\Command;

use Subway\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Clear command
 */
class ClearCommand extends RedisAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('clear')
            ->setDescription('Clear subway database')
        ;

        parent::configure();
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($input->getOption('no-interaction') === false) {
            $dialog = $this->getHelperSet()->get('dialog');
            if (!$dialog->askConfirmation(
                    $output,
                    '<question>This action will erase entire subway database. Are you sure you want to continue? (y/N)</question>',
                    false
                )) {

                return $output->writeln('<comment>Command aborted by user</comment>');
            }
        }

        $factory = new Factory($this->redis);
        $factory->clear();
        $output->writeln('<info>Database cleared successfully</info>');
    }
}

Clear command default answer changed to no


<?php

function phutil_get_library_root($library = null) {
  if (!$library) {
    $library = phutil_get_current_library_name();
  }
  $bootloader = PhutilBootloader::getInstance();
  return $bootloader->getLibraryRoot($library);
}

function phutil_get_library_root_for_path($path) {
  foreach (Filesystem::walkToRoot($path) as $dir) {
    if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
      return $dir;
    }
  }
  return null;
}

function phutil_get_library_name_for_root($path) {
  $path = rtrim(Filesystem::resolvePath($path), '/');

  $bootloader = PhutilBootloader::getInstance();
  $libraries = $bootloader->getAllLibraries();
  foreach ($libraries as $library) {
    $root = $bootloader->getLibraryRoot($library);
    if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
      return $library;
    }
  }

  return null;
}

function phutil_get_current_library_name() {
  $caller = head(debug_backtrace(false));

  $root = phutil_get_library_root_for_path($caller['file']);
  return phutil_get_library_name_for_root($root);
}

/**
 * Warns about use of deprecated behavior.
 */
function phutil_deprecated($what, $why) {
  PhutilErrorHandler::dispatchErrorMessage(
    PhutilErrorHandler::DEPRECATED,
    $what,
    array(
      'why' => $why,
    ));
}

<?php

function phutil_get_library_root($library) {
  $bootloader = PhutilBootloader::getInstance();
  return $bootloader->getLibraryRoot($library);
}

function phutil_get_library_root_for_path($path) {
  foreach (Filesystem::walkToRoot($path) as $dir) {
    if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
      return $dir;
    }
  }
  return null;
}

function phutil_get_library_name_for_root($path) {
  $path = rtrim(Filesystem::resolvePath($path), '/');

  $bootloader = PhutilBootloader::getInstance();
  $libraries = $bootloader->getAllLibraries();
  foreach ($libraries as $library) {
    $root = $bootloader->getLibraryRoot($library);
    if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
      return $library;
    }
  }

  return null;
}

function phutil_get_current_library_name() {
  $caller = head(debug_backtrace(false));

  $root = phutil_get_library_root_for_path($caller['file']);
  return phutil_get_library_name_for_root($root);
}

/**
 * Warns about use of deprecated behavior.
 */
function phutil_deprecated($what, $why) {
  PhutilErrorHandler::dispatchErrorMessage(
    PhutilErrorHandler::DEPRECATED,
    $what,
    array(
      'why' => $why,
    ));
}

Revert "Simplify the use of `phutil_get_library_root`"

Summary:
This reverts commit 67a17d0efb025665237d0d174d55d1887f9a6064.

This doesn't actually work because the call to `phutil_get_current_library_name()` always occurs within `libphutil`.

Test Plan: N/A

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley, #blessed_reviewers

Subscribers: Korvin, epriestley

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


<?php
if (! class_exists('OmisePluginHelperTransfer')) {
	class OmisePluginHelperTransfer {
		/**
		 * Format the transfer amount into the appropriate format for each currency.
         * Note, no specific format for JPY currency.
		 *
		 * @param  string  $currency
		 * @param  integer $amount
		 *
		 * @return string
		 */
		public static function amount($currency, $amount) {
			switch (strtoupper($currency)) {
				case 'THB':
                case 'IDR':
                case 'SGD':
                    // Convert to a small unit
					$amount = $amount * 100;
					break;
			}

			return $amount;
		}
	}
}

Change a helper file indentation to TAB character

Modify a PHP helper file, transfer.php. Change all indentation from
space to TAB character.

This change makes the PHP source code indentation conformed with
OpenCart coding standard.

Reference:
https://github.com/opencart/opencart/wiki/Coding-standards#indentation