<?php
/**
 * PHP version 5.6
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace ComPHPPuebla\DBAL\Fixture\Loader;

use Symfony\Component\Yaml\Parser;

class YamlLoader implements Loader
{
    /** @var string */
    protected $path;

    /** @var Parser */
    protected $reader;

    public function __construct($path, Parser $reader = null)
    {
        $this->path = $path;
        $this->reader = $reader;
    }

    public function load()
    {
        if (!$this->reader) {
            $this->reader = new Parser();
        }

        return $this->reader->parse(file_get_contents($this->path));
    }
}

<?php
/**
 * PHP version 5.6
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace ComPHPPuebla\DBAL\Fixture\Loader;

use Symfony\Component\Yaml\Parser;

class YamlLoader implements Loader
{
    /** @var string */
    protected $path;

    /** @var Parser */
    protected $reader;

    /**
     * @param string $path
     * @param Parser|null $reader
     */
    public function __construct($path, Parser $reader = null)
    {
        $this->path = $path;
        $this->reader = $reader ?: new Parser();
    }

    /**
     * @return array
     */
    public function load()
    {
        return $this->reader->parse(file_get_contents($this->path));
    }
}

Set default parser value in constructor.


@extends('layouts.app')

@section('content')

Add survey report

<form class="form-inline" action="/surveys/storeReport" method="post" enctype="multipart/form-data">

        {{ csrf_field() }}
        {{ method_field('PUT') }}

Survey ID:  <input class="form-control" type="text" id="surveyId" name="surveyId">

Upload survey report:  <input class="form-control" type="file" id="surveyReport" name="surveyReport" >

<button type="submit">Submit survey report</button> / Main

</form>
@endsection

@extends('layouts.app')

@section('content')

Add survey report

<form class="form-inline" action="/surveys/storeReport" method="post" enctype="multipart/form-data">

        {{ csrf_field() }}
        {{ method_field('PUT') }}

Survey ID:  <input class="form-control" type="number" id="surveyId" name="surveyId">

Upload survey report:  <input class="form-control" type="file" id="surveyReport" name="surveyReport" >

<button type="submit">Submit survey report</button> / Main

</form>
@endsection

Make surveyId a number input type field (HTML5)


<?php

namespace Sdz\BlogBundle\Form;

use Sdz\BlogBundle\Form\TagType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class ArticleType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('date')
            ->add('titre')
            ->add('contenu')
            ->add('auteur')
            ->add('tags', 'collection', array('type'      => new TagType,
                                              'prototype' => true,
                                              'allow_add' => true))
        ;
    }

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

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Sdz\BlogBundle\Entity\Article',
        );
    }
}

<?php

namespace Sdz\BlogBundle\Form;

use Sdz\BlogBundle\Form\TagType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class ArticleType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('date')
            ->add('titre')
            ->add('contenu')
            ->add('auteur')
            ->add('tags', 'entity', array(
                                          'class' => 'SdzBlogBundle:Tag',
                                          'property' => 'nom',
                                          'expanded' => true,
                                          'multiple' => true))
        ;

    }

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

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Sdz\BlogBundle\Entity\Article',
        );
    }
}

Tag : case à cocher

Tag : case à cocher


<?php

/*
 * This file is a part of the ChZ-PHP package.
 *
 * (c) François LASSERRE <choiz@me.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Engine;

class Controller
{
    function __construct()
    {
    }

    protected function loadView($file)
    {
        require_once VIEWS_DIR.'/'.$file.'.php';
        return true;
    }

    protected function loadAjax($params = array())
    {
        header('Content-Type: application/json');
        echo json_encode($params, true);
        return true;
    }
}

<?php

/*
 * This file is a part of the ChZ-PHP package.
 *
 * (c) François LASSERRE <choiz@me.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Engine;

class Controller
{
    public function __construct()
    {
    }

    protected function loadView($file, $params = array())
    {
        require_once VIEWS_DIR.'/'.$file.'.php';
        return true;
    }

    protected function loadAjax($params = array())
    {
        header('Content-Type: application/json');
        echo json_encode($params, true);
        return true;
    }
}

Add missing param and add visibility on contruct


<?php
/**
 * Default hero template file.
 *
 * This is the default hero image for page templates, called
 * 'slide'. Strictly air specific.
 *
 * @package air
 */

?>

<div class="slide" style="background-image:url('<?php if ( has_post_thumbnail() ) : ?><?php echo esc_url(wp_get_attachment_url( get_post_thumbnail_id($post->ID) )); ?><?php else : ?><?php echo get_template_directory_uri(); ?>/images/slide.jpg<?php endif; ?>');">

<?php
/**
 * Default hero template file.
 *
 * This is the default hero image for page templates, called
 * 'slide'. Strictly air specific.
 *
 * @package air
 */

?>

<div class="slide" style="background-image:url('<?php if ( has_post_thumbnail() ) : ?><?php echo esc_url(wp_get_attachment_url( get_post_thumbnail_id($post->ID) ) ); ?><?php else : ?><?php echo get_template_directory_uri(); ?>/images/slide.jpg<?php endif; ?>');">

Add space before closing bracket

Add space before closing bracket


<?php

declare(strict_types=1);

namespace Phpcq\Runner\Test\Config\Builder;

use Phpcq\Runner\Config\Builder\AbstractOptionBuilder;
use Phpcq\Runner\Config\Builder\ConfigOptionBuilderInterface;
use Phpcq\PluginApi\Version10\Configuration\Builder\OptionBuilderInterface;
use Phpcq\PluginApi\Version10\Exception\InvalidConfigurationException;

trait OptionBuilderTestTrait
{
    public function testInstantiation(): void
    {
        $builder = $this->createInstance();
        $this->assertInstanceOf(OptionBuilderInterface::class, $builder);
        $this->assertInstanceOf(AbstractOptionBuilder::class, $builder);
    }

    public function testIsRequired(): void
    {
        $builder = $this->createInstance();

        $this->assertSame($builder, $builder->isRequired());
        $this->expectException(InvalidConfigurationException::class);
        $builder->validateValue(null);
    }

    abstract public function testDefaultValue(): void;

    abstract public function testNormalizesValue(): void;

    abstract public function testValidatesValue(): void;

    abstract protected function createInstance(array $validators = []): ConfigOptionBuilderInterface;
}

<?php

declare(strict_types=1);

namespace Phpcq\Runner\Test\Config\Builder;

use Phpcq\Runner\Config\Builder\AbstractOptionBuilder;
use Phpcq\Runner\Config\Builder\ConfigOptionBuilderInterface;
use Phpcq\PluginApi\Version10\Configuration\Builder\OptionBuilderInterface;
use Phpcq\PluginApi\Version10\Exception\InvalidConfigurationException;

trait OptionBuilderTestTrait
{
    public function testInstantiation(): void
    {
        $builder = $this->createInstance();
        $this->assertInstanceOf(OptionBuilderInterface::class, $builder);
        $this->assertInstanceOf(AbstractOptionBuilder::class, $builder);
    }

    public function testIsRequired(): void
    {
        $builder = $this->createInstance();

        $this->assertSame($builder, $builder->isRequired());
        $this->expectException(InvalidConfigurationException::class);
        $builder->validateValue(null);
    }

    abstract public function testDefaultValue(): void;

    abstract public function testNormalizesValue(): void;

    abstract public function testValidatesValue(): void;

    abstract protected function createInstance(): ConfigOptionBuilderInterface;
}

Fix broken unit test under PHP 8

Fix broken unit test under PHP 8


<?php

namespace Symfony\Bundle\ChainRoutingBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ChainRoutingExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('chain_routing.xml');
    }
}

<?php

namespace Symfony\Bundle\ChainRoutingBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class ChainRoutingExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('chain_routing.xml');
    }
}

Fix namespace and class name

Fix namespace and class name


<?php

namespace Encore\Kernel;

class Timezone
{
    public function __construct(Application $app, array $winTimezones)
    {
        $this->app = $app;
        $this->timezones = $winTimezones;
    }

    public function set($timezone)
    {
        return date_default_timezone_set($timezone);
    }

    public function get()
    {
        return date_default_timezone_get();
    }

    public function setToSystem()
    {
        return $this->set($this->getSystemTimezone());
    }

    public function getSystemTimezone()
    {
        if ($this->app->os() === $this->app::OS_WIN) {
            return $this->getWindowsTimezone();
        }

        return $this->getUnitTimezone();
    }

    protected function getUnixTimezone()
    {
        return system('date +%Z');
    }

    protected function getWindowsTimezone()
    {
        $wmiObject = new COM("WinMgmts:\\\\.\\root\\cimv2");
        $wmiObj = $wmiObject->ExecQuery("SELECT Bias FROM Win32_TimeZone");

        foreach ($wmiObj as $objItem) {
            $offset = $objItem->Bias;
            break;
        }

        return array_key_exists($offset/60, $this->timezones) ? $this->timezones[$offset] : "UTC" ;
    }
}

<?php

namespace Encore\Kernel;

class Timezone
{
    public function __construct(Application $app, array $winTimezones)
    {
        $this->app = $app;
        $this->timezones = $winTimezones;
    }

    public function set($timezone)
    {
        return date_default_timezone_set($timezone);
    }

    public function get()
    {
        return date_default_timezone_get();
    }

    public function setToSystem()
    {
        return $this->set($this->getSystemTimezone());
    }

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

        if ($app->os() === $app::OS_WIN) {
            return $this->getWindowsTimezone();
        }

        return $this->getUnitTimezone();
    }

    protected function getUnixTimezone()
    {
        return system('date +%Z');
    }

    protected function getWindowsTimezone()
    {
        $wmiObject = new COM("WinMgmts:\\\\.\\root\\cimv2");
        $wmiObj = $wmiObject->ExecQuery("SELECT Bias FROM Win32_TimeZone");

        foreach ($wmiObj as $objItem) {
            $offset = $objItem->Bias;
            break;
        }

        return array_key_exists($offset/60, $this->timezones) ? $this->timezones[$offset] : "UTC" ;
    }
}

Set $this->app to a variable so we can get the constants out


<?php namespace Modules\Media\Image\Intervention\Manipulations;

use Modules\Media\Image\ImageHandlerInterface;

class Crop implements ImageHandlerInterface
{
    /**
     * Handle the image manipulation request
     * @param \Intervention\Image\Image $image
     * @param array $options
     * @return mixed
     */
    public function handle($image, $options)
    {
        return $image->crop($options['width'], $options['height']);
    }
}

<?php namespace Modules\Media\Image\Intervention\Manipulations;

use InvalidArgumentException;
use Modules\Media\Image\ImageHandlerInterface;

class Crop implements ImageHandlerInterface
{
    /**
     * Handle the image manipulation request
     * @param \Intervention\Image\Image $image
     * @param array $options
     * @return mixed
     */
    public function handle($image, $options)
    {
        if (!isset($options['width']) or !isset($options['height'])) {
            throw new InvalidArgumentException('A width and height parameter are required');
        }

        return $image->crop($options['width'], $options['height']);
    }
}

Add a security mesure for required options


<?php
/**
 * Created by PhpStorm.
 * User: sgueye
 * Date: 12/12/2016
 * Time: 2:42 PM
 */

namespace Mms\Organizations\Tree\NestedSet;

class ModifiedPreOrderTraversal
{
    public function run(NodeInterface $node, $level = 0, $counter = 1)
    {
        $node->setLevel($level)->setLeftValue($counter++);

        foreach ($node->getChildren() as $child) {
            /**
             * @var NodeInterface $child
             */
            $this->run($child, $level+1, $counter++);
        }
        $node->setRightValue($counter+1);
        return $node;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: sgueye
 * Date: 12/12/2016
 * Time: 2:42 PM
 */

namespace Mms\Organizations\Tree\NestedSet;

class ModifiedPreOrderTraversal
{
    /**
     * @var int
     */
    private $counter = 1;

    /**
     * @param NodeInterface $node
     * @param $level
     * @return NodeInterface
     */
    private function doRun(NodeInterface $node, $level)
    {
        $node->setLevel($level)->setLeftValue($this->counter++);

        foreach ($node->getChildren() as $child) {
            /**
             * @var NodeInterface $child
             */
            $this->doRun($child, $level+1);
        }
        $node->setRightValue($this->counter++);
        return $node;
    }

    /**
     * @param NodeInterface $node
     * @return NodeInterface
     */
    public function run(NodeInterface $node)
    {
        $this->counter = 1;
        return $this->doRun($node, 0);
    }
}

Fix the handling of the counter

Fix the handling of the counter


<?php
/* connector for Afrotropical
estimated execution time: 41 mins.
This connector reads an EOL XML and converts PDF files stored in <mediaURL> into text description objects.
*/
//exit;
$timestart = microtime(1);

include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/AfrotropicalAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = AfrotropicalAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "138.xml";

$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

//echo "time: ". Functions::time_elapsed()."\n";
$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec              \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min   \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");

?>

<?php
/* connector for Afrotropical
estimated execution time: 41 mins.
This connector reads an EOL XML and converts PDF files stored in <mediaURL> into text description objects.
*/
exit;
$timestart = microtime(1);

include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/AfrotropicalAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = AfrotropicalAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "138.xml";

$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

//echo "time: ". Functions::time_elapsed()."\n";
$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec              \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min   \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");

?>

Disable Afrotropical connector. Because it doesn't have a regular harvest, just one-time and maybe upon request of content partner.

git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1382 baf6b65b-9124-4dc3-b1c0-01155b4af546


<?php

namespace Northstar\Http\Transformers;

use Northstar\Models\Campaign;
use League\Fractal\TransformerAbstract;

class CampaignTransformer extends TransformerAbstract
{
    /**
     * @param Campaign $campaign
     * @return array
     */
    public function transform(Campaign $campaign)
    {
        return [
            'drupal_id' => $campaign->drupal_id,

            'reportback_id' => $campaign->reportback_id,
            'reportback_source' => $campaign->reportback_source,
            'reportback_data' => $campaign->reportback_data,

            'signup_id' => $campaign->signup_id,
            'signup_source' => $campaign->signup_source,

            'signup_group' => $campaign->signup_group,
        ];
    }
}

<?php

namespace Northstar\Http\Transformers;

use Northstar\Models\Campaign;
use League\Fractal\TransformerAbstract;

class CampaignTransformer extends TransformerAbstract
{
    /**
     * @param Campaign $campaign
     * @return array
     */
    public function transform(Campaign $campaign)
    {
        return [
            'drupal_id' => $campaign->drupal_id,

            'reportback_id' => $campaign->reportback_id,
            'reportback_source' => $campaign->reportback_source,
            'reportback_data' => $campaign->reportback_data,

            'signup_id' => $campaign->signup_id,
            'signup_source' => $campaign->signup_source,

            'signup_group' => $campaign->signup_group,

            // @TODO: Sometimes these aren't set... why?
            'updated_at' => $campaign->updated_at ? $campaign->updated_at->toISO8601String() : null,
            'created_at' => $campaign->created_at ? $campaign->created_at->toISO8601String() : null,
        ];
    }
}

Fix issue with null timestamps on campaign object.

These are sometimes null, causing an issue calling the date formatting
method. Why? :(


<?php

namespace Tests;

use App\Models\User;
use Illuminate\Contracts\Console\Kernel as Artisan;
use Illuminate\Foundation\Application;

trait CreatesApplication
{
    protected $coverPath;
    protected $mediaPath = __DIR__.'/songs';

    /** @var Artisan */
    private $artisan;

    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $this->artisan = $app->make(Artisan::class);
        $this->artisan->bootstrap();

        $this->coverPath = $app->basePath().'/public/img/covers';

        return $app;
    }

    private function prepareForTests()
    {
        $this->artisan->call('migrate');

        if (!User::all()->count()) {
            $this->artisan->call('db:seed');
        }

        if (!file_exists($this->coverPath)) {
            mkdir($this->coverPath, 0777, true);
        }
    }
}

<?php

namespace Tests;

use App\Console\Kernel;
use App\Models\User;
use Illuminate\Contracts\Console\Kernel as Artisan;
use Illuminate\Foundation\Application;

trait CreatesApplication
{
    protected $coverPath;
    protected $mediaPath = __DIR__.'/songs';

    /** @var Kernel */
    private $artisan;

    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $this->artisan = $app->make(Artisan::class);
        $this->artisan->bootstrap();

        $this->coverPath = $app->basePath().'/public/img/covers';

        return $app;
    }

    private function prepareForTests()
    {
        $this->artisan->call('migrate');

        if (!User::all()->count()) {
            $this->artisan->call('db:seed');
        }

        if (!file_exists($this->coverPath)) {
            mkdir($this->coverPath, 0777, true);
        }
    }
}

Fix type hint for Artisan

Fix type hint for Artisan


<?php

namespace BitWasp\Bitcoin\Tests\Script;

use BitWasp\Bitcoin\Script\Opcodes;

class OpcodesTest extends \PHPUnit_Framework_TestCase
{
    public function testGetOpByName()
    {
        $op = new OpCodes;
        $expected = 0;
        $lookupOpName = 'OP_0';
        $val = $op->getOpByName('OP_0');
        $this->assertSame($expected, $val);
        $this->assertTrue(isset($op[Opcodes::OP_0]));
        $this->assertSame($lookupOpName, $op[Opcodes::OP_0]);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Opcode by that name not found
     */
    public function testGetOpByNameFail()
    {
        $op = new Opcodes();
        $op->getOpByName('OP_DEADBEEF');
    }

    public function testGetOp()
    {
        $op = new OpCodes;
        // Check getRegisteredOpCode returns the right operation
        $expected = 'OP_0';
        $val = $op->getOp(0);

        $this->assertSame($expected, $val);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Opcode not found
     */
    public function testGetOpCodeException()
    {
        $op = new OpCodes;
        $op->getOp(3);
    }
}

<?php

namespace BitWasp\Bitcoin\Tests\Script;

use BitWasp\Bitcoin\Script\Opcodes;

class OpcodesTest extends \PHPUnit_Framework_TestCase
{
    public function testGetOpByName()
    {
        $op = new OpCodes;
        $expected = 0;
        $lookupOpName = 'OP_0';
        $val = $op->getOpByName('OP_0');
        $this->assertSame($expected, $val);
        $this->assertTrue(isset($op[Opcodes::OP_0]));
        $this->assertSame($lookupOpName, $op[Opcodes::OP_0]);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Opcode by that name not found
     */
    public function testGetOpByNameFail()
    {
        $op = new Opcodes();
        $op->getOpByName('OP_DEADBEEF');
    }

    public function testGetOp()
    {
        $op = new OpCodes;
        // Check getRegisteredOpCode returns the right operation
        $expected = 'OP_0';
        $val = $op->getOp(0);

        $this->assertSame($expected, $val);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Opcode not found
     */
    public function testGetOpCodeException()
    {
        $op = new OpCodes;
        $op->getOp(3);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testNoWriteSet()
    {
        $op = new Opcodes();
        $op[1] = 2;
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testNoWriteUnSet()
    {
        $op = new Opcodes();
        unset($op[Opcodes::OP_1]);
    }

}

Opcodes: Add tests for final two functions in ArrayAccess (only throw exceptions)


<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;

class User extends Authenticatable
{
	static $rules = [
		'name' => 'required|max:255',
		'email' => 'required|email',
		'password' => 'required|min:8|max:255'
	];
	protected $fillable = ['name', 'email', 'password'];
	protected $hidden = ['password', 'remember_token'];
	public $timestamps = true;
	public $relationships = ['devices', 'templates', 'tokens'];
	public $guardCreate = false;

	static function findByToken ($token)
	{
		$userToken = UserToken::where('token', $token)->first();

		if ( ! $userToken) return;

		return static::findOrFail($userToken->user_id);
	}

	function getDates ()
	{
		return ['last_login', 'created_at', 'updated_at'];
	}

	function devices ()
	{
		return $this->belongsToMany(Device::class, 'user_devices');
	}

	function templates ()
	{
		return $this->hasMany(Template::class);
	}

	function tokens ()
	{
		return $this->hasMany(UserToken::class);
	}

	function setPasswordAttribute ($val)
	{
		$this->attributes['password'] = Hash::make($val);
	}

	function getUserIdsAttribute ()
	{
		return [(int) $this->id];
	}
}

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;

class User extends Authenticatable
{
	static $rules = [
		'name' => 'required|max:255',
		'email' => 'required|email',
		'password' => 'required|confirmed|min:8|max:255'
	];
	protected $fillable = ['name', 'email', 'password'];
	protected $hidden = ['password', 'remember_token'];
	public $timestamps = true;
	public $relationships = ['devices', 'templates', 'tokens'];
	public $guardCreate = false;

	static function findByToken ($token)
	{
		$userToken = UserToken::where('token', $token)->first();

		if ( ! $userToken) return;

		return static::findOrFail($userToken->user_id);
	}

	function getDates ()
	{
		return ['last_login', 'created_at', 'updated_at'];
	}

	function devices ()
	{
		return $this->belongsToMany(Device::class, 'user_devices');
	}

	function templates ()
	{
		return $this->hasMany(Template::class);
	}

	function tokens ()
	{
		return $this->hasMany(UserToken::class);
	}

	function setPasswordAttribute ($val)
	{
		$this->attributes['password'] = Hash::make($val);
	}

	function getUserIdsAttribute ()
	{
		return [(int) $this->id];
	}
}

Add confirmation to user password validation.


<?php
use LinusShops\Prophet\Commands\Scry;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

/**
 *
 *
 * @author Sam Schmidt
 * @date 2015-05-04
 * @company Linus Shops
 */

namespace LinusShops\Prophet;

use LinusShops\Prophet\Commands\Scry;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

class ScryTest extends \PHPUnit_Framework_TestCase
{
    private $path = './magento/prophet.json';

    public function setUp()
    {
        if (file_exists($this->path)) {
            unlink($this->path);
        }

        file_put_contents($this->path, <<<JSON
{
    "modules": [
        {
            "path": "vendor/linusshops/prophet-magento-test-module",
            "name": "test-module"
        }
    ]
}
JSON
        );
    }

    public function tearDown()
    {
        if (file_exists($this->path)) {
            unlink($this->path);
        }
    }

    public function testScryFullExecution()
    {
        $output = shell_exec("./prophet scry -p ./magento");

        $this->assertRegExp('/OK \(1 test, 1 assertion\)/', $output);
    }
}

<?php
use LinusShops\Prophet\Commands\Scry;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

/**
 *
 *
 * @author Sam Schmidt
 * @date 2015-05-04
 * @company Linus Shops
 */

namespace LinusShops\Prophet;

use LinusShops\Prophet\Commands\Scry;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

class ScryTest extends \PHPUnit_Framework_TestCase
{
    private $path = './magento/prophet.json';

    public function getJson()
    {
        return <<<JSON
{
    "modules": [
        {
            "path": "vendor/linusshops/prophet-magento-test-module",
            "name": "test-module"
        }
    ]
}
JSON;
    }

    public function setUp()
    {
        if (file_exists($this->path)) {
            unlink($this->path);
        }

        file_put_contents($this->path, $this->getJson());
    }

    public function tearDown()
    {
        if (file_exists($this->path)) {
            unlink($this->path);
        }
    }

    public function testScryFullExecution()
    {
        $output = shell_exec("./prophet scry -p ./magento");

        $this->assertRegExp('/OK \(1 test, 1 assertion\)/', $output);
    }
}

Move json string into function.

Move json string into function.


<?php

namespace ContentTranslator\Helper;

class Database
{
    protected $db;

    public function __construct()
    {
        global $wpdb;
        $this->db = $wpdb;
    }

    /**
     * Gets all column names of a table
     * @param  string $table Table name
     * @return array
     */
    public static function getTableColumns(string $table) : array
    {
        $columns = array();

        foreach ((array) $this->db->get_col("DESC " . $wpdb->prefix . $table, 0) as $column_name) {
            $columns[] = $column_name;
        }

        return (array) $columns;
    }
}

<?php

namespace ContentTranslator\Helper;

class Database
{
    private static $db;

    public function __construct()
    {
        global $wpdb;
        self::$db = $wpdb;
    }

    /**
     * Gets all column names of a table
     * @param  string $table Table name
     * @return array
     */
    public static function getTableColumns(string $table) : array
    {
        $columns = array();

        foreach ((array) self::$db->get_col("DESC " . self::$db->prefix . $table, 0) as $column_name) {
            $columns[] = $column_name;
        }

        return (array) $columns;
    }

    /**
     * Duplicates a table
     * @param  string $source Name of table to duplicate
     * @param  string $target Table name to create
     * @return boolean
     */
    public static function duplicateTable(string $source, string $target) : bool
    {
        if (!self::tableExist($source)) {
            throw new \Exception("Can't duplicate table since the table '" . $source . "' does not exist.", 1);
        }

        if (self::tableExist($target)) {
            throw new \Exception("Can't duplicate table since the table '" . $target . "' already exist. You will have to manually (with caution) drop the existing table to continue.", 1);
        }

        // Create sql
        $sql = "CREATE TABLE $target LIKE $source;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);

        return true;
    }

    /**
     * Drop a table
     * Note: Can only drop tables created by this plugin for saftey reasons
     * @param  string $table Table name
     * @return bool
     */
    public static function dropTable(string $table) : bool
    {
        /*
        if (!$droppable) {
            throw new \Exception("Ooopsidopsi. Can't do it.", 1);
        }
        */

        self::$db->query("DROP TABLE $table");
        return true;
    }

    /**
     * Checks if a database table exists
     * @param  string $table Table name
     * @return boolean
     */
    public static function tableExist(string $table) : bool
    {
        if (self::$db->get_var("SHOW TABLES LIKE '$table'") !== $table) {
            return false;
        }

        return true;
    }
}

Move database related functions to the database helper


<?php
namespace CrudView\Action;

use CrudView\Dashboard\Dashboard;
use Crud\Action\BaseAction;
use Crud\Traits\ViewTrait;

class DashboardAction extends BaseAction
{
    use ViewTrait;

    protected $_defaultConfig = [
        'enabled' => true,
        'view' => null,
    ];

    /**
     * HTTP GET handler
     *
     * @return void|\Cake\Network\Response
     */
    protected function _get()
    {
        $pageTitle = $this->getConfig('scaffold.page_title', __d('CrudView', 'Dashboard'));
        $this->setConfig('scaffold.page_title', $pageTitle);
        $this->setConfig('scaffold.autoFields', false);
        $this->setConfig('scaffold.fields', ['dashboard']);
        $this->setConfig('scaffold.actions', []);

        $dashboard = $this->getConfig('scaffold.dashboard', new Dashboard($pageTitle));
        $subject = $this->_subject([
            'success' => true,
            'dashboard' => $dashboard,
        ]);

        $this->_trigger('beforeRender', $subject);

        $controller = $this->_controller();
        $controller->set('dashboard', $subject->dashboard);
        $controller->set('viewVar', 'dashboard');
        $controller->set('title', $subject->dashboard->get('title'));
    }
}

<?php
namespace CrudView\Action;

use CrudView\Dashboard\Dashboard;
use Crud\Action\BaseAction;
use Crud\Traits\ViewTrait;

class DashboardAction extends BaseAction
{
    use ViewTrait;

    protected $_defaultConfig = [
        'enabled' => true,
        'view' => null,
    ];

    /**
     * HTTP GET handler
     *
     * @return void|\Cake\Http\Response
     */
    protected function _get()
    {
        $pageTitle = $this->getConfig('scaffold.page_title', __d('CrudView', 'Dashboard'));
        $this->setConfig('scaffold.page_title', $pageTitle);
        $this->setConfig('scaffold.autoFields', false);
        $this->setConfig('scaffold.fields', ['dashboard']);
        $this->setConfig('scaffold.actions', []);

        $dashboard = $this->getConfig('scaffold.dashboard', new Dashboard($pageTitle));
        $subject = $this->_subject([
            'success' => true,
            'dashboard' => $dashboard,
        ]);

        $this->_trigger('beforeRender', $subject);

        $controller = $this->_controller();
        $controller->set('dashboard', $subject->dashboard);
        $controller->set('viewVar', 'dashboard');
        $controller->set('title', $subject->dashboard->get('title'));
    }
}

Update docblock to prevent warning when running phpstan.


<?php

namespace Sven\FlexEnv;

use Illuminate\Support\ServiceProvider;

class FlexEnvServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app['env:set'] = $this->app->share(function () {
            return new Commands\SetEnv();
        });

        $this->app['env:get'] = $this->app->share(function () {
            return new Commands\GetEnv();
        });

        $this->app['env:delete'] = $this->app->share(function () {
            return new Commands\DeleteEnv();
        });

        $this->app['env:list'] = $this->app->share(function () {
            return new Commands\ListEnv();
        });

        $this->commands(
            'env:set',
            'env:get',
            'env:delete',
            'env:list'
        );
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

<?php

namespace Sven\FlexEnv;

use Illuminate\Support\ServiceProvider;

class FlexEnvServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->commands([
            Commands\SetEnv::class,
            Commands\GetEnv::class,
            Commands\DeleteEnv::class,
            Commands\ListEnv::class,
        ]);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            Commands\SetEnv::class,
            Commands\GetEnv::class,
            Commands\DeleteEnv::class,
            Commands\ListEnv::class,
        ];
    }
}

Fix service provider for Laravel 5.4

Fix service provider for Laravel 5.4

Closes #17


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // The table associated with the model
    protected $table = 'posts';

    // columns in table that we are allowed to fill
    protected $fillable = ['category_id', 'title', 'body'];

     // This function allows us to call items sharing the reference
    public function user() {
        return $this->belongsTo('App\User');
    }

    public function replies() {
        return $this->hasMany('App\Models\Reply');
    }

    public function archive_posts() {
        return $this->hasMany('App\Models\Archive_Posts', 'post_id');
    }
}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // The table associated with the model
    protected $table = 'posts';

    // columns in table that we are allowed to fill
    protected $fillable = ['category_id', 'title', 'body'];

     // This function allows us to call items sharing the reference
    public function user() {
        return $this->belongsTo('App\User');
    }

    public function replies() {
        return $this->hasMany('App\Models\Reply', 'post_id', 'id');
    }

    public function archive_posts() {
        return $this->hasMany('App\Models\Archive_Posts', 'post_id');
    }
}

Fix for notification not notifying message creator Also more specific with relation in table


<?php

/**
 * This file is part of the GeocoderLaravel library.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Geocoder\Provider\Chain\Chain;
use Geocoder\Provider\GeoPlugin\GeoPlugin;
use Geocoder\Provider\GoogleMaps\GoogleMaps;
use Http\Client\Curl\Client;

return [
    'cache-duration' => 9999999,
    'providers' => [
        Chain::class => [
            GoogleMaps::class => [
                'en-US',
                env('GOOGLE_MAPS_API_KEY'),
            ],
            GeoPlugin::class  => [],
        ],
    ],
    'adapter'  => Client::class,
];

<?php

use Geocoder\Provider\Chain\Chain;
use Geocoder\Provider\GeoPlugin\GeoPlugin;
use Geocoder\Provider\GoogleMaps\GoogleMaps;
use Http\Client\Curl\Client;

return [

    /*
    |--------------------------------------------------------------------------
    | Cache Duration
    |--------------------------------------------------------------------------
    |
    | Specify the cache duration in seconds. The default approximates a forever
    | cache, but there are certain issues with Laravel's forever caching
    | methods that prevent us from using them in this project.
    |
    | Default: 9999999 (integer)
    |
    */
    'cache-duration' => 9999999,

    /*
    |--------------------------------------------------------------------------
    | Providers
    |--------------------------------------------------------------------------
    |
    | Here you may specify any number of providers that should be used to
    | perform geocaching operations. The `chain` provider is special,
    | in that it can contain multiple providers that will be run in
    | the sequence listed, should the previous provider fail. By
    | default the first provider listed will be used, but you
    | can explicitly call subsequently listed providers by
    | alias: `app('geocoder')->using('google_maps')`.
    |
    | Please consult the official Geocoder documentation for more info.
    | https://github.com/geocoder-php/Geocoder#providers
    |
    */
    'providers' => [
        Chain::class => [
            GoogleMaps::class => [
                env('GOOGLE_MAPS_LOCALE', 'en-US'),
                env('GOOGLE_MAPS_API_KEY'),
            ],
            GeoPlugin::class  => [],
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Adapter
    |--------------------------------------------------------------------------
    |
    | You can specify which PSR-7-compliant HTTP adapter you would like to use.
    | There are multiple options at your disposal: CURL, Guzzle, and others.
    |
    | Please consult the official Geocoder documentation for more info.
    | https://github.com/geocoder-php/Geocoder#usage
    |
    | Default: Client::class (FQCN for CURL adapter)
    |
    */
    'adapter'  => Client::class,

];

Update config to read locale from .env, add descriptions


@extends('layout')

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

@section('body')

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

            @if (count($earnings))
                @foreach ($earnings as $earning)

{{ $earning->description }}

{{ $earning->formatted_happened_on }}

€ {{ $earning->formatted_amount }}

                @endforeach
            @else

You don't have any earnings

            @endif

@endsection

Patch up earnings' index view to align columns properly and add contrast to records


<?php
namespace mxdiModuleTest\Annotation;

use mxdiModule\Annotation\Exception\CannotGetValue;
use mxdiModule\Annotation\Inject;
use mxdiModuleTest\TestCase;
use Zend\ServiceManager\ServiceLocatorInterface;

class InjectTest extends TestCase
{
    public function testIsNotInvokableByDefault()
    {
        $this->assertFalse((new Inject())->invokable);
    }

    public function testGetValueWithServiceLocator()
    {
        $inject = new Inject();
        $inject->value = 'serviceName';
        $inject->invokable = false;

        $service = new \stdClass();

        $sm = $this->getMockBuilder(ServiceLocatorInterface::class)
            ->setMethods(['get'])
            ->getMockForAbstractClass();

        $sm->expects($this->once())
            ->method('get')
            ->with($this->equalTo($inject->value))
            ->will($this->returnValue($service));

        $this->assertSame($service, $inject->getValue($sm));
    }

    public function testGetValueBypassesServiceManagerWithInvokable()
    {
        $inject = new Inject();
        $inject->value = self::class;
        $inject->invokable = true;

        $this->assertInstanceOf(self::class, $inject->getValue());
    }

    public function testGetValueThrowsExceptionOnMissingSMWhenRequired()
    {
        $inject = new Inject();

        $this->setExpectedException(CannotGetValue::class);
        $inject->getValue();
    }
}

<?php
namespace mxdiModuleTest\Annotation;

use mxdiModule\Annotation\Inject;
use mxdiModuleTest\TestCase;
use Zend\ServiceManager\ServiceLocatorInterface;

class InjectTest extends TestCase
{
    public function testIsNotInvokableByDefault()
    {
        $this->assertFalse((new Inject())->invokable);
    }

    public function testGetValueWithServiceLocator()
    {
        $inject = new Inject();
        $inject->value = 'serviceName';
        $inject->invokable = false;

        $service = new \stdClass();

        /** @var ServiceLocatorInterface|\PHPUnit_Framework_MockObject_MockObject $sm */
        $sm = $this->getMockBuilder(ServiceLocatorInterface::class)
            ->setMethods(['get'])
            ->getMockForAbstractClass();

        $sm->expects($this->once())
            ->method('get')
            ->with($this->equalTo($inject->value))
            ->will($this->returnValue($service));

        $this->assertSame($service, $inject->getValue($sm));
    }

    public function testGetValueBypassesServiceManagerWithInvokable()
    {
        $inject = new Inject();
        $inject->value = self::class;
        $inject->invokable = true;

        /** @var ServiceLocatorInterface|\PHPUnit_Framework_MockObject_MockObject $sm */
        $sm = $this->getMockBuilder(ServiceLocatorInterface::class)
            ->setMethods(['get'])
            ->getMockForAbstractClass();

        $sm->expects($this->never())
            ->method('get');

        $this->assertInstanceOf(self::class, $inject->getValue($sm));
    }
}

Test fix due to interface change

Test fix due to interface change


<?php

namespace Omnipay\Moneris\Message;

/**
 * Moneris Complete Purchase Response
 */
class CompletePurchaseResponse extends AbstractResponse
{

    public function isSuccessful()
    {
        return (isset($this->data['message']) && strpos($this->data['message'],'APPROVED') !== false);
    }

    public function getTransactionReference()
    {
        return isset($this->data['bank_transaction_id']) ? $this->data['bank_transaction_id'] : null;
    }

    public function getMessage()
    {
        return isset($this->data['message']) ? $this->data['message'] : null;
    }
}

<?php

namespace Omnipay\Moneris\Message;

/**
 * Moneris Complete Purchase Response
 */
class CompletePurchaseResponse extends AbstractResponse
{

    public function isSuccessful()
    {
        return ((isset($this->data['message']) && strpos($this->data['message'],'APPROVED') !== false) || (isset($this->data['ISSCONF']) && isset($this->data['bank_approval_code']) && $this->data['bank_approval_code'] != '000000'));
    }

    public function getTransactionReference()
    {
        return isset($this->data['bank_transaction_id']) ? $this->data['bank_transaction_id'] : null;
    }

    public function getMessage()
    {
        return isset($this->data['message']) ? $this->data['message'] : null;
    }
}

Update for Interac Online Payment success


<?php

/**
 * Load services definition file.
 */
$settings['container_yamls'][] = __DIR__ . '/services.yml';

/**
 * Include the Pantheon-specific settings file.
 *
 * n.b. The settings.pantheon.php file makes some changes
 *      that affect all envrionments that this site
 *      exists in.  Always include this file, even in
 *      a local development environment, to ensure that
 *      the site settings remain consistent.
 */
include __DIR__ . "/settings.pantheon.php";

/**
 * Place the config directory outside of the Drupal root.
 */
$config_directories = array(
  CONFIG_SYNC_DIRECTORY => dirname(DRUPAL_ROOT) . '/config',
);

/**
 * If there is a local settings file, then include it
 */
$local_settings = __DIR__ . "/settings.local.php";
if (file_exists($local_settings)) {
  include $local_settings;
}

/**
 * Always install the 'standard' profile to stop the installer from
 * modifying settings.php.
 *
 * See: tests/installer-features/installer.feature
 */
$settings['install_profile'] = 'standard';

// Hack to handle containers not supplying $_ENV vars to PHP
if (!isset($settings['hash_salt']) && getenv('DRUPAL_HASH_SALT')) {
  $settings['hash_salt'] = getenv('DRUPAL_HASH_SALT');
}

Stop hacking hash salt, we haz Lando now!


<?php

namespace Kregel\FormModel\Traits;

trait Formable
{
    /**
     * @return mixed
     */
    public function getFormName()
    {
        if (property_exists($this, 'form_model')) {
            return $this->form_name;
        }

        return 'name';
    }

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

<?php

namespace Kregel\FormModel\Traits;

trait Formable
{
    /**
     * @return mixed
     */
    public function getFormName()
    {
        return $this->form_name;
    }

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

Fix form_name in formable trait

Fix form_name in formable trait


<?php

class HTMLPurifier_HTML5Config
{
    /**
     * @param  string|array|HTMLPurifier_Config $config
     * @param  HTMLPurifier_ConfigSchema $schema
     * @return HTMLPurifier_Config
     */
    public static function create($config = null, HTMLPurifier_ConfigSchema $schema = null)
    {
        if (!$schema instanceof HTMLPurifier_ConfigSchema) {
            $schema = HTMLPurifier_ConfigSchema::makeFromSerial();
        }

        if ($config instanceof HTMLPurifier_Config) {
            $configObj = $config;

        } else {
            $configObj = new HTMLPurifier_Config($schema);
            $configObj->set('Core.Encoding', 'UTF-8');
            $configObj->set('HTML.Doctype', 'HTML 4.01 Transitional');

            if (is_string($config)) {
                $configObj->loadIni($config);

            } elseif (is_array($config)) {
                $configObj->loadArray($config);
            }
        }

        $def = $configObj->getHTMLDefinition(true); // this finalizes config
        HTMLPurifier_HTML5Definition::setup($def);

        return $configObj;
    }

    /**
     * Creates a configuration object using the default config schema instance
     *
     * @return HTMLPurifier_Config
     */
    public static function createDefault()
    {
        $schema = HTMLPurifier_ConfigSchema::instance();
        $config = self::create(null, $schema);
        return $config;
    }
}

// vim: et sw=4 sts=4

<?php

class HTMLPurifier_HTML5Config
{
    /**
     * @param  string|array|HTMLPurifier_Config $config
     * @param  HTMLPurifier_ConfigSchema $schema
     * @return HTMLPurifier_Config
     */
    public static function create($config = null, HTMLPurifier_ConfigSchema $schema = null)
    {
        if (!$schema instanceof HTMLPurifier_ConfigSchema) {
            $schema = HTMLPurifier_ConfigSchema::instance();
        }

        if ($config instanceof HTMLPurifier_Config) {
            $configObj = $config;

        } else {
            $configObj = new HTMLPurifier_Config($schema);
            $configObj->set('Core.Encoding', 'UTF-8');
            $configObj->set('HTML.Doctype', 'HTML 4.01 Transitional');

            if (is_string($config)) {
                $configObj->loadIni($config);

            } elseif (is_array($config)) {
                $configObj->loadArray($config);
            }
        }

        $def = $configObj->getHTMLDefinition(true); // this finalizes config
        HTMLPurifier_HTML5Definition::setup($def);

        return $configObj;
    }

    /**
     * Creates a configuration object using the default config schema instance
     *
     * @return HTMLPurifier_Config
     */
    public static function createDefault()
    {
        $schema = HTMLPurifier_ConfigSchema::instance();
        $config = self::create(null, $schema);
        return $config;
    }
}

// vim: et sw=4 sts=4

Use config schema singleton instance if none was provided


<?php

declare(strict_types=1);

namespace App\Traits;

/**
 * Class StringableIdEntity
 */
trait StringableIdEntity
{
    public function __toString(): string
    {
        return (string) $this->id;
    }
}

<?php

declare(strict_types=1);

namespace App\Traits;

trait StringableIdEntity
{
    public function __toString(): string
    {
        return isset($this->id) ? (string) $this->id : '';
    }
}

Handle objects without an ID yet

Handle objects without an ID yet

This is used when we build log data and in some cases the thing being
logged hasn't been created yet when we run this method so we need to
account for the id not yet being set.


<?php

namespace allejo\stakx\Twig;

use allejo\stakx\Object\ContentItem;

class OrderFilter
{
    public function __invoke ($array, $key, $order = "ASC")
    {
        usort($array, function ($a, $b) use ($key, $order) {
            $a = !($a instanceof ContentItem) ?: $a->getFrontMatter();
            $b = !($b instanceof ContentItem) ?: $b->getFrontMatter();

            if ($a[$key] == $b[$key]) return 0;

            if (strtolower($order) === "desc") {
                return ($a[$key] < $b[$key]) ? 1 : -1;
            }

            return ($a[$key] > $b[$key]) ? 1 : -1;
        });

        return $array;
    }

    public static function get ()
    {
        return new \Twig_SimpleFilter('order', new self());
    }
}

<?php

namespace allejo\stakx\Twig;

use allejo\stakx\Object\ContentItem;

class OrderFilter
{
    public function __invoke ($array, $key, $order = "ASC")
    {
        usort($array, function ($a, $b) use ($key, $order) {
            $a = ($a instanceof ContentItem) ? $a->getFrontMatter() : $a;
            $b = ($b instanceof ContentItem) ? $b->getFrontMatter() : $b;

            if ($a[$key] == $b[$key]) return 0;

            if (strtolower($order) === "desc") {
                return ($a[$key] < $b[$key]) ? 1 : -1;
            }

            return ($a[$key] > $b[$key]) ? 1 : -1;
        });

        return $array;
    }

    public static function get ()
    {
        return new \Twig_SimpleFilter('order', new self());
    }
}

Fix Order filter to work with sorting by keys again


<?php
/**
 * @package Airtime
 * @subpackage StorageServer
 * @copyright 2010 Sourcefabric O.P.S.
 * @license http://www.gnu.org/licenses/gpl.txt
 */

/*
 * In the future, most Airtime upgrades will involve just mutating the
 * data that is stored on the system. For example, The only data
 * we need to convert between versions is the database, /etc/airtime, and
 * /srv/airtime. Everything else is just executable files that can be removed/replaced
 * with new versions.
 */

function get_conf_location(){
    $conf = parse_ini_file("/etc/airtime/airtime.conf", TRUE);
    $airtime_dir = $conf['general']['airtime_dir'];
    return $airtime_dir."/"."application/configs/conf.php";
}

$conf_path = get_conf_location();
require_once $conf_path;

require_once 'common/UpgradeCommon.php';
require_once 'ConfFileUpgrade.php';
require_once 'DbUpgrade.php';
require_once 'MiscUpgrade.php';

UpgradeCommon::connectToDatabase();
UpgradeCommon::SetDefaultTimezone();

AirtimeConfigFileUpgrade::start();
AirtimeDatabaseUpgrade::start();
AirtimeMiscUpgrade::start();

<?php
/**
 * @package Airtime
 * @subpackage StorageServer
 * @copyright 2010 Sourcefabric O.P.S.
 * @license http://www.gnu.org/licenses/gpl.txt
 */

/*
 * In the future, most Airtime upgrades will involve just mutating the
 * data that is stored on the system. For example, The only data
 * we need to convert between versions is the database, /etc/airtime, and
 * /srv/airtime. Everything else is just executable files that can be removed/replaced
 * with new versions.
 */

function get_conf_location(){
    $conf = parse_ini_file("/etc/airtime/airtime.conf", TRUE);
    $airtime_dir = $conf['general']['airtime_dir'];
    return $airtime_dir."/"."application/configs/conf.php";
}

$conf_path = get_conf_location();
require_once $conf_path;

set_include_path(__DIR__.'/../../../airtime_mvc/library' . PATH_SEPARATOR . get_include_path());

require_once 'propel/runtime/lib/Propel.php';
require_once 'common/UpgradeCommon.php';
require_once 'ConfFileUpgrade.php';
require_once 'DbUpgrade.php';
require_once 'MiscUpgrade.php';

UpgradeCommon::connectToDatabase();
UpgradeCommon::SetDefaultTimezone();

AirtimeConfigFileUpgrade::start();
AirtimeDatabaseUpgrade::start();
AirtimeMiscUpgrade::start();

CC-3751: Remove db.php requirement in the upgrade script

- added require_once of Propel


<?php

namespace Downsider\Clay\Model;

trait NameConverterTrait
{
    private function toStudlyCaps($string)
    {
        return str_replace( // remove the spaces
            " ",
            "",
            ucwords( // uppercase the 1st letter of each word
                str_replace( // replace underscores with spaces
                    "_",
                    " ",
                    $string
                )
            )
        );
    }

    private function toSplitCase($string, $separator = "_")
    {
        return strtolower(preg_replace('/(?<!^)([A-Z])/', $separator . '$1', $string));
    }
}

<?php

namespace Downsider\Clay\Model;

trait NameConverterTrait
{
    private function toStudlyCaps($string)
    {
        return str_replace( // remove the spaces
            " ",
            "",
            ucwords( // uppercase the 1st letter of each word
                str_replace( // replace underscores with spaces
                    "_",
                    " ",
                    $string
                )
            )
        );
    }

    private function toSplitCase($string, $separator = "_")
    {
        return strtolower(preg_replace('/(?<!^)([A-Z]|\d+)/', $separator . '$1', $string));
    }
}

Fix split case conversion to treat sequences of numbers as words e.g. test123Case => test_123_case


<?php namespace Rafasamp\Sonus;

use Config;

/**
 * Laravel Audio Conversion Package
 *
 * This package is created to handle server-side conversion tasks using FFMPEG (http://www.fmpeg.org)
 *
 * @package    Laravel
 * @category   Bundle
 * @version    0.1
 * @author     Rafael Sampaio <rafaelsampaio@live.com>
 */

class Sonus
{

}

<?php namespace Rafasamp\Sonus;

use Config;

/**
 * Laravel Audio Conversion Package
 *
 * This package is created to handle server-side conversion tasks using FFMPEG (http://www.fmpeg.org)
 *
 * @package    Laravel
 * @category   Bundle
 * @version    0.1
 * @author     Rafael Sampaio <rafaelsampaio@live.com>
 */

class Sonus
{

	protected $FFMPEG;

	public function __construct()
	{
		try
		{
			$this->FFMPEG = Config::get('sonus::ffmpeg');
			if(file_exists($this->FFMPEG) === false)
			{
				throw new FileNotFoundException("Unable to access FFMPEG executable!");
			}

		} catch (Exception $e) {
			return $e;
		}
	}

}

Check if FFMPEG exists using the path provided


<?php

namespace Rvdv\Nntp\Tests\Connection;

use Rvdv\Nntp\Connection\Connection;

/**
 * ConnectionTest
 *
 * @author Robin van der Vleuten <robinvdvleuten@gmail.com>
 */
class ConnectionTest extends \PHPUnit_Framework_TestCase
{
    public function testConnectionCanBeEstablishedThroughSocket()
    {
        $connection = new Connection('localhost', 5000);
        $response = $connection->connect();

        $this->assertInstanceof('Rvdv\Nntp\Response\Response', $response);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('server ready - posting allowed', $response->getMessage());
    }
}

<?php

namespace Rvdv\Nntp\Tests\Connection;

use Rvdv\Nntp\Connection\Connection;

/**
 * ConnectionTest
 *
 * @author Robin van der Vleuten <robinvdvleuten@gmail.com>
 */
class ConnectionTest extends \PHPUnit_Framework_TestCase
{
    public function testConnectionCanBeEstablishedThroughSocket()
    {
        $connection = new Connection('localhost', 5000);
        $response = $connection->connect();

        $this->assertInstanceof('Rvdv\Nntp\Response\Response', $response);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('server ready - posting allowed', $response->getMessage());
    }

    public function testErrorIsThrownWhenConnectionCannotBeEstablished()
    {
        $connection = new Connection('unknownhost', 3000);

        try {
            $connection->connect();
            $this->fail('->connect() throws a Rvdv\Nntp\Exception\RuntimeException because the connection cannot be established');
        } catch (\Exception $e) {
            $this->assertInstanceof('Rvdv\Nntp\Exception\RuntimeException', $e, '->connect() throws a Rvdv\Nntp\Exception\RuntimeException because the connection cannot be established');
        }
    }
}

Test if an error is thrown when connection can't be established.


<?php

namespace Ddeboer\VatinBundle\Validator\Constraints;

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

/**
 * Validate a VAT identification number using the ddeboer/vatin library
 *
 */
class VatinValidator extends ConstraintValidator
{
    /**
     * VATIN validator
     *
     * @var Validator
     */
    protected $validator;

    /**
     * Constructor
     *
     * @param Validator $validator VATIN validator
     */
    public function __construct(Validator $validator)
    {
        $this->validator = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return;
        }

        if ($this->isValidVatin($value, $constraint->checkExistence)) {
            return;
        }

        $this->setMessage($constraint->message);
    }

    /**
     * Is the value a valid VAT identification number?
     *
     * @param string $value Value
     *
     * @return bool
     */
    protected function isValidVatin($value, $checkExistence)
    {
        return $this->validator->isValid($value, $checkExistence);
    }
}

<?php

namespace Ddeboer\VatinBundle\Validator\Constraints;

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

/**
 * Validate a VAT identification number using the ddeboer/vatin library
 *
 */
class VatinValidator extends ConstraintValidator
{
    /**
     * VATIN validator
     *
     * @var Validator
     */
    protected $validator;

    /**
     * Constructor
     *
     * @param Validator $validator VATIN validator
     */
    public function __construct(Validator $validator)
    {
        $this->validator = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return;
        }

        if ($this->isValidVatin($value, $constraint->checkExistence)) {
            return;
        }

        $this->context->addViolation($constraint->message);
    }

    /**
     * Is the value a valid VAT identification number?
     *
     * @param string $value          Value
     * @param bool   $checkExistence Also check whether the VAT number exists
     *
     * @return bool
     */
    protected function isValidVatin($value, $checkExistence)
    {
        return $this->validator->isValid($value, $checkExistence);
    }
}

Replace calls to deprecated Symfony2 functions, fix phpdoc


<?php namespace Orchestra\Control;

use Orchestra\Contracts\Foundation\Foundation;

class ControlMenuHandler
{
    /**
     * ACL instance.
     *
     * @var \Orchestra\Contracts\Authorization\Authorization
     */
    protected $acl;

    /**
     * Menu instance.
     *
     * @var \Orchestra\Widget\Handlers\Menu
     */
    protected $menu;

    /**
     * Construct a new handler.
     *
     * @param  \Orchestra\Contracts\Foundation\Foundation  $foundation
     */
    public function __construct(Foundation $foundation)
    {
        $this->menu = $foundation->menu();
        $this->acl = $foundation->acl();
    }

    /**
     * Create a handler for `orchestra.ready: admin` event.
     *
     * @return void
     */
    public function handle()
    {
        if (! ($this->acl->can('manage roles') || $this->acl->can('manage acl'))) {
            return ;
        }

        $this->menu->add('control', '^:extensions')
            ->title('Control')
            ->link(handles('orchestra::control'));
    }
}

<?php namespace Orchestra\Control;

use Orchestra\Contracts\Foundation\Foundation;

class ControlMenuHandler
{
    /**
     * ACL instance.
     *
     * @var \Orchestra\Contracts\Authorization\Authorization
     */
    protected $acl;

    /**
     * Menu instance.
     *
     * @var \Orchestra\Widget\Handlers\Menu
     */
    protected $menu;

    /**
     * Construct a new handler.
     *
     * @param  \Orchestra\Contracts\Foundation\Foundation  $foundation
     */
    public function __construct(Foundation $foundation)
    {
        $this->menu = $foundation->menu();
        $this->acl = $foundation->acl();
    }

    /**
     * Create a handler for `orchestra.ready: admin` event.
     *
     * @return void
     */
    public function handle()
    {
        if (! ($this->acl->can('manage roles') || $this->acl->can('manage acl'))) {
            return ;
        }

        $parent = $this->menu->has('extensions') ? '^:extensions' : '<:home';

        $this->menu->add('control', $parent)
            ->title('Control')
            ->link(handles('orchestra::control'));
    }
}

Append menu to main menu if extensions doesn't exist.

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


<?php

class UserTableSeeder extends Seeder
{

	public function run()
	{
		DB::table('users')->delete();
		App\Models\User::create(array(
			'email'    => 'chawkinsuf@gmail.com',
			'password' => '123456',
			'nest_password' => ''
		));
	}

}

<?php

class UserTableSeeder extends Seeder
{

	public function run()
	{
		DB::table('users')->delete();
		App\Models\User::create(array(
			'email'    => 'chawkinsuf@gmail.com',
			'password' => '123456',
			'nest_password' => null
		));
	}

}

Change the default nest password to null


<?php

namespace Hubertusanton\SilverStripeSeo;

use SilverStripe\View\Requirements;
use SilverStripe\Forms\FormField;

class GoogleSuggestField extends FormField {

    public function Field($properties = array())
    {
        Requirements::customScript(<<<JS

            (function($) {

                $.entwine('ss', function($){

                    $('.cms-edit-form input#Form_EditForm_{$this->getName()}').entwine({
                        // Constructor: onmatch
                        onmatch : function() {

                            $( "#Form_EditForm_{$this->getName()}" ).autocomplete({
                                source: function( request, response ) {
                                    $.ajax({
                                      url: "//suggestqueries.google.com/complete/search",
                                      dataType: "jsonp",
                                      data: {
                                          client: 'firefox',
                                        q: request.term
                                      },
                                      success: function( data ) {
                                        response( data[1] );
                                      }
                                    });
                                },
                                minLength: 3
                            });

                        },
                    });
                });

            })(jQuery);
JS
);

        $this->addExtraClass('text');

        return parent::Field($properties);

    }
}

<?php

namespace Hubertusanton\SilverStripeSeo;

use SilverStripe\View\Requirements;
use SilverStripe\Forms\FormField;

class GoogleSuggestField extends FormField {

    public function Field($properties = array())
    {
        Requirements::customScript(<<<JS

            (function($) {

                $.entwine('ss', function($){

                    $('.cms-edit-form input[name="{$this->getName()}"]').entwine({
                        // Constructor: onmatch
                        onmatch : function() {

                            $('input[name="{$this->getName()}"]').autocomplete({
                                source: function( request, response ) {
                                    $.ajax({
                                      url: "//suggestqueries.google.com/complete/search",
                                      dataType: "jsonp",
                                      data: {
                                          client: 'firefox',
                                        q: request.term
                                      },
                                      success: function( data ) {
                                        response( data[1] );
                                      }
                                    });
                                },
                                minLength: 3
                            });

                        },
                    });
                });

            })(jQuery);
JS
);

        $this->addExtraClass('text');

        return parent::Field($properties);

    }
}

Change JS field references on suggest field


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\ProductStatusBundle\Entity;

use WellCommerce\Bundle\RoutingBundle\Entity\Route;
use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface;

/**
 * Class ProductStatusRoute
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductStatusRoute extends Route implements RouteInterface
{
    /**
     * @var ProductStatusInterface
     */
    protected $identifier;

    /**
     * @return string
     */
    public function getType()
    {
        return 'product_status';
    }
}

<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\ProductStatusBundle\Entity;

use WellCommerce\Bundle\RoutingBundle\Entity\Route;
use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface;

/**
 * Class ProductStatusRoute
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProductStatusRoute extends Route implements RouteInterface
{
    /**
     * @var ProductStatusInterface
     */
    protected $identifier;

    /**
     * @return string
     */
    public function getType() : string
    {
        return 'product_status';
    }
}

Return types in routing and news bundle

Return types in routing and news bundle


<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

Update redirectTo return type PHPDoc

Update redirectTo return type PHPDoc


<?php namespace Strimoid\Providers;

use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
use Pdp\Parser;
use Pdp\PublicSuffixListManager;
use Strimoid\Helpers\OEmbed;
use Strimoid\Models\UserSettings;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->environment('local')) {
            $this->app->register('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider');
        }

        $rollbarToken = config('services.rollbar.access_token');

        if (! empty($rollbarToken)) {
            $this->app->register('Jenssegers\Rollbar\RollbarServiceProvider');
        }
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('guzzle', function () {
            return new Client([
                'connect_timeout' => 3,
                'timeout'         => 10,
            ]);
        });

        $this->app->bind('settings', function () {
            return new UserSettings();
        });

        $this->app->bind('pdp', function () {
            $pslManager = new PublicSuffixListManager();
            $parser = new Parser($pslManager->getList());

            return $parser;
        });

        $this->app->bind('oembed', function () {
            return new OEmbed();
        });
    }
}

<?php namespace Strimoid\Providers;

use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
use Pdp\Parser;
use Pdp\PublicSuffixListManager;
use Strimoid\Helpers\OEmbed;
use Strimoid\Models\UserSettings;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->environment('local')) {
            $this->app->register('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider');
            $this->app->register('Barryvdh\Debugbar\ServiceProvider');
        }

        $rollbarToken = config('services.rollbar.access_token');

        if (! empty($rollbarToken)) {
            $this->app->register('Jenssegers\Rollbar\RollbarServiceProvider');
        }
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('guzzle', function () {
            return new Client([
                'connect_timeout' => 3,
                'timeout'         => 10,
            ]);
        });

        $this->app->bind('settings', function () {
            return new UserSettings();
        });

        $this->app->bind('pdp', function () {
            $pslManager = new PublicSuffixListManager();
            $parser = new Parser($pslManager->getList());

            return $parser;
        });

        $this->app->bind('oembed', function () {
            return new OEmbed();
        });
    }
}

Enable DebugBar service when using local env


<?
defined('C5_EXECUTE') or die("Access Denied.");
?>

<? foreach($_REQUEST['cvID'] as $cvID) {
	$tabs[] = array('view-version-' . $cvID, t('Version %s', $cvID), $checked);
	$checked = false;
}
print $ih->tabs($tabs);

foreach($_REQUEST['cvID'] as $cvID) { ?>

	<div id="ccm-tab-content-view-version-<?=$cvID?>" style="display: <?=$display?>; height: 100%">
	<iframe border="0" id="v<?=time()?>" frameborder="0" height="100%" width="100%" src="<?=REL_DIR_FILES_TOOLS_REQUIRED?>/pages/preview_version?cvID=<?=$cvID?>&cID=<?=$_REQUEST['cID']?>" />

	<? if ($display == 'block') {
		$display = 'none';
	} ?>

<? } ?>

<?
defined('C5_EXECUTE') or die("Access Denied.");
$val = \Core::make('helper/validation/numbers');

$cID = 0;
if ($val->integer($_REQUEST['cID'])) {
    $cID = $_REQUEST['cID'];
}
if (!is_array($_REQUEST['cvID'])) {
    die(t('Invalid Request.'));
}

?>

<?
$tabs = array();
foreach ($_REQUEST['cvID'] as $key => $cvID) {
    if (!$val->integer($cvID)) {
        unset($_REQUEST['cvID'][$key]);
    } else {
        $tabs[] = array('view-version-' . $cvID, t('Version %s', $cvID), $checked);
        $checked = false;
    }
}
print $ih->tabs($tabs);

foreach ($_REQUEST['cvID'] as $cvID) { ?>

	<div id="ccm-tab-content-view-version-<?=$cvID?>" style="display: <?=$display?>; height: 100%">
	<iframe border="0" id="v<?=time()?>" frameborder="0" height="100%" width="100%" src="<?=REL_DIR_FILES_TOOLS_REQUIRED?>/pages/preview_version?cvID=<?=$cvID?>&cID=<?=$cID?>" />

	<? if ($display == 'block') {
		$display = 'none';
	} ?>

<? } ?>

Add additional validation to request parameters

H1 59701

Former-commit-id: 07d778157b1e49e8177d18733293bc48caf94968
Former-commit-id: 1943dca20dd598f0a882a6b8652985518ab88b8f


<?php

header('Content-Type: text/html; charset=UTF-8');

if ((!$loader = @include __DIR__.'/../../../autoload.php')
        && (!$loader = @include __DIR__.'/../vendor/autoload.php')
) {
    die('You must set up the project dependencies, run the following commands:'.PHP_EOL.
        'curl -s http://getcomposer.org/installer | php'.PHP_EOL.
        'php composer.phar install'.PHP_EOL);
}

<?php

header('Content-Type: text/html; charset=UTF-8');

if (
    (!$loader = @include __DIR__.'/../../../autoload.php')
    && (!$loader = @include __DIR__.'/../vendor/autoload.php')
) {
    die('You must set up the project dependencies, run the following command:'.PHP_EOL.
        'composer install'.PHP_EOL);
}

Stop advising users to pipe a curl download directly into php.


<?php

namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Page\Page;
use Concrete\Core\Updater\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20180328215345 extends AbstractMigration
{

    public function upgradeDatabase()
    {
        $c = Page::getByPath('/page_not_found');
        if ($c && !$c->isError()) {
            $db = $this->connection;
            $db->executeQuery('update Pages set siteTreeID = ? where cID = ?', [
                0, $c->getCollectionID()
            ]);
        }
    }
}

<?php

namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Page\Page;
use Concrete\Core\Updater\Migrations\AbstractMigration;
use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface;

class Version20180328215345 extends AbstractMigration implements RepeatableMigrationInterface
{
    public function upgradeDatabase()
    {
        $c = Page::getByPath('/page_not_found');
        if ($c && !$c->isError()) {
            $db = $this->connection;
            $db->executeQuery('update Pages set siteTreeID = ? where cID = ?', [
                0, $c->getCollectionID(),
            ]);
        }
    }
}

Mark migration 20180328215345 as repeatable


<?php

namespace App\Controllers;

use Psr\Http\Message\ResponseInterface;
use Slim\Container;

class Controller
{
    /**
     * @var Container
     */
    private $container;

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

    /**
     * @param ResponseInterface $response
     * @param string $template
     * @param array $data
     */
    public function render(
        ResponseInterface $response,
        $template,
        array $data = []
    ) {
        $this->container->view->render($response, $template, $data);
    }

    /**
     * @param string $name
     *
     * @return mixed
     */
    public function __get($name)
    {
        return $this->container->get($name);
    }
}

<?php

namespace App\Controllers;

use Psr\Http\Message\ResponseInterface;
use Slim\Container;

class Controller
{
    /**
     * @var Container
     */
    protected $container;

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

    /**
     * @param ResponseInterface $response
     * @param string $template
     * @param array $data
     */
    public function render(
        ResponseInterface $response,
        $template,
        array $data = []
    ) {
        $this->container->view->render($response, $template, $data);
    }

    /**
     * @param string $name
     *
     * @return mixed
     */
    public function __get($name)
    {
        return $this->container->get($name);
    }
}

Change container visibility in controller


<?php

if (version_compare(PHP_VERSION, '5.4.0', '<')) {

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

	}

} else {

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

		/**
		 * Provide iterator for bulk loading from.
		 * Records are expected to be 1 dimensional key-value arrays.
		 * @return Iterator
		 */
		abstract public function getIterator();

	}

}

<?php

	/**
	 * An abstract source to bulk load records from.
	 * Provides an iterator for retrieving records from.
	 *
	 * Useful for holiding source configuration state.
	 */
	abstract class BulkLoaderSource implements IteratorAggregate
	{

	}

Fix issue with php version 5.3.3

Fix issue with php version 5.3.3


<?php
declare(strict_types=1);

namespace Moka\Strategy;

use Moka\Exception\MockNotCreatedException;
use Moka\Stub\StubSet;

/**
 * Interface MockingStrategyInterface
 * @package Moka\Strategy
 */
interface MockingStrategyInterface
{
    /**
     * @param string $fqcn
     * @return object
     *
     * @throws MockNotCreatedException
     */
    public function build(string $fqcn);

    /**
     * @param object $mock
     * @param StubSet $stubs
     * @return mixed
     */
    public function decorate($mock, StubSet $stubs);

    /**
     * @param object $mock
     * @return mixed
     */
    public function get($mock);
}

<?php
declare(strict_types=1);

namespace Moka\Strategy;

use Moka\Exception\MockNotCreatedException;
use Moka\Stub\StubSet;

/**
 * Interface MockingStrategyInterface
 * @package Moka\Strategy
 */
interface MockingStrategyInterface
{
    /**
     * @param string $fqcn
     * @return object
     *
     * @throws MockNotCreatedException
     */
    public function build(string $fqcn);

    /**
     * @param object $mock
     * @param StubSet $stubs
     * @return void
     */
    public function decorate($mock, StubSet $stubs);

    /**
     * @param object $mock
     * @return mixed
     */
    public function get($mock);
}

Document a void return type for decorate()

We need no fluent interface here, and we were already using it in different ways
in the two drivers.


<?php

declare(strict_types=1);

namespace mcordingley\Regression\RegressionAlgorithm;

use InvalidArgumentException;
use mcordingley\LinearAlgebra\Matrix;
use mcordingley\Regression\CoefficientSet;
use mcordingley\Regression\DataBag;
use mcordingley\Regression\RegressionAlgorithm;

final class LinearLeastSquares implements RegressionAlgorithm
{
    public function regress(DataBag $data): CoefficientSet
    {
        $dependentData = $data->getDependents();
        $independentData = $data->getIndependents();

        $design = new Matrix($independentData);
        $observed = (new Matrix([ $dependentData ]))->transpose();

        if ($design->columns >= $design->rows) {
            throw new InvalidArgumentException('Not enough observations to perform regression. You need to have more observations than explanatory variables.');
        }

        $designTranspose = $design->transpose();

        $prediction = $designTranspose
                             ->multiply($design)
                             ->inverse()
                             ->multiply($designTranspose->multiply($observed));

        // Extract the vertical vector as a simple array.
        return new CoefficientSet($prediction->transpose()->toArray()[0]);
    }
}

<?php

declare(strict_types=1);

namespace mcordingley\Regression\RegressionAlgorithm;

use InvalidArgumentException;
use mcordingley\LinearAlgebra\Matrix;
use mcordingley\Regression\CoefficientSet;
use mcordingley\Regression\DataBag;
use mcordingley\Regression\RegressionAlgorithm;

final class LinearLeastSquares implements RegressionAlgorithm
{
    public function regress(DataBag $data): CoefficientSet
    {
        $dependentData = $data->getDependents();
        $independentData = $data->getIndependents();

        // Prepend dummies.
        $independentData = array_map(function ($row) {
            return array_merge([1], $row);
        }, $independentData);

        $design = new Matrix($independentData);
        $observed = (new Matrix([ $dependentData ]))->transpose();

        if ($design->columns >= $design->rows) {
            throw new InvalidArgumentException('Not enough observations to perform regression. You need to have more observations than explanatory variables.');
        }

        $designTranspose = $design->transpose();

        $prediction = $designTranspose
                             ->multiply($design)
                             ->inverse()
                             ->multiply($designTranspose->multiply($observed));

        // Extract the vertical vector as a simple array.
        return new CoefficientSet($prediction->transpose()->toArray()[0]);
    }
}

Insert dummy data for intercepts.

Insert dummy data for intercepts.


<?php
namespace Laranix\Auth\Password\Listeners;

use Laranix\Auth\Password\Events\Settings;
use Laranix\Auth\Password\Events\Updated as UpdatedEvent;
use Laranix\Support\Listeners\Listener;

class Updated extends Listener
{
    /**
     * @var string
     */
    protected $type = 'password';

    /**
     * Handle event
     *
     * @param \Laranix\Auth\Password\Events\Updated $event
     */
    public function handle(UpdatedEvent $event)
    {
        $this->track(Settings::TYPEID_UPDATED, $event->user->id, 50);
    }
}

<?php
namespace Laranix\Auth\Password\Listeners;

use Illuminate\Contracts\Config\Repository;
use Laranix\Auth\Password\Events\Settings;
use Laranix\Auth\Password\Events\Updated as UpdatedEvent;
use Laranix\Session\Session;
use Laranix\Support\Listeners\Listener;
use Laranix\Tracker\TrackWriter;

class Updated extends Listener
{
    /**
     * @var string
     */
    protected $type = 'password';

    /**
     * @var \Illuminate\Contracts\Config\Repository
     */
    protected $config;

    /**
     * Listener constructor.
     *
     * @param \Laranix\Tracker\TrackWriter            $writer
     * @param \Illuminate\Contracts\Config\Repository $config
     */
    public function __construct(TrackWriter $writer, Repository $config)
    {
        parent::__construct($writer);

        $this->config = $config;
    }

    /**
     * Handle event
     *
     * @param \Laranix\Auth\Password\Events\Updated $event
     */
    public function handle(UpdatedEvent $event)
    {
        // Delete sessions for user on password update
        if ($this->config->get('session.driver') === 'laranix') {
            Session::where('user_id', $event->user->id)->delete();
        }

        $this->track(Settings::TYPEID_UPDATED, $event->user->id, 50);
    }
}


<?php

class Default_Model_MovieMapper extends Default_Model_AbstractMapper
{
    public function find($id)
    {

        $result = $this->getDbTable()->find($id);

        return $result->current();
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();

        return $resultSet;
    }

    public function getFilteredQuery($idUser, $status)
    {
		$select = $this->getDbTable()->select()
			->from('movie')
			->joinLeft('status', 'movie.id = status.idMovie' , array())
			->where('status.idUser = ?', $idUser);

		if ($status >= 0 && $status <= 5)
		{
			$select->where('status.rating = ?', $status);
		}
		else
		{
			$select->where('status.rating <> ?', 0);
		}

		if ($status == 0)
		{
			$select->orWhere('status.idUser IS NULL');
			$select->orWhere('status.rating IS NULL');
		}

		echo $select;

    	return $select;
    }
}

?>

<?php

class Default_Model_MovieMapper extends Default_Model_AbstractMapper
{
    public function find($id)
    {

        $result = $this->getDbTable()->find($id);

        return $result->current();
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();

        return $resultSet;
    }

    public function getFilteredQuery($idUser, $status)
    {
		$select = $this->getDbTable()->select()
			->from('movie')
			->joinLeft('status', 'movie.id = status.idMovie' , array())
			->where('status.idUser = ?', $idUser);

		if ($status >= 0 && $status <= 5)
		{
			$select->where('status.rating = ?', $status);
		}
		else
		{
			$select->where('status.rating <> ?', 0);
		}

		if ($status == 0)
		{
			$select->orWhere('status.idUser IS NULL');
			$select->orWhere('status.rating IS NULL');
		}

    	return $select;
    }
}

?>

FIX forgot debug dump (!)

FIX forgot debug dump (!)


<?php

final class HeraldRuleDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getPlaceholderText() {
    return pht('Type a Herald rule name...');
  }

  public function getBrowseTitle() {
    return pht('Browse Herald Rules');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorHeraldApplication';
  }

  public function loadResults() {
    $viewer = $this->getViewer();
    $raw_query = $this->getRawQuery();

    $rules = id(new HeraldRuleQuery())
      ->setViewer($viewer)
      ->withDatasourceQuery($raw_query)
      ->execute();

    $handles = id(new PhabricatorHandleQuery())
      ->setViewer($viewer)
      ->withPHIDs(mpull($rules, 'getPHID'))
      ->execute();

    $results = array();
    foreach ($rules as $rule) {
      $handle = $handles[$rule->getPHID()];

      $result = id(new PhabricatorTypeaheadResult())
        ->setName($handle->getFullName())
        ->setPHID($handle->getPHID());

      if ($rule->getIsDisabled()) {
        $result->setClosed(pht('Archived'));
      }

      $results[] = $result;
    }

    return $results;
  }
}

<?php

final class HeraldRuleDatasource
  extends PhabricatorTypeaheadDatasource {

  public function getPlaceholderText() {
    return pht('Type a Herald rule name...');
  }

  public function getBrowseTitle() {
    return pht('Browse Herald Rules');
  }

  public function getDatasourceApplicationClass() {
    return 'PhabricatorHeraldApplication';
  }

  public function loadResults() {
    $viewer = $this->getViewer();
    $raw_query = $this->getRawQuery();

    $query = id(new HeraldRuleQuery())
      ->setViewer($viewer);

    if (preg_match('/^[hH]\d+\z/', $raw_query)) {
      $id = trim($raw_query, 'hH');
      $id = (int)$id;
      $query->withIDs(array($id));
    } else {
      $query->withDatasourceQuery($raw_query);
    }

    $rules = $query->execute();

    $handles = id(new PhabricatorHandleQuery())
      ->setViewer($viewer)
      ->withPHIDs(mpull($rules, 'getPHID'))
      ->execute();

    $results = array();
    foreach ($rules as $rule) {
      $handle = $handles[$rule->getPHID()];

      $result = id(new PhabricatorTypeaheadResult())
        ->setName($handle->getFullName())
        ->setPHID($handle->getPHID());

      if ($rule->getIsDisabled()) {
        $result->setClosed(pht('Archived'));
      }

      $results[] = $result;
    }

    return $results;
  }
}

Support querying Herald rules by monogram in typeahead datsources

Summary:
Depends on D19556. See PHI765. Ref T13164. Currently, if you type `H1` in this datasource, it isn't smart enough to pull up the right object.

Add support for querying by monogram. This is similar to existing support in Owners packages, etc.

Test Plan: Typed `H1` in the new push log filter, got the right object as a result in the typeahead.

Reviewers: amckinley

Reviewed By: amckinley

Maniphest Tasks: T13164

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


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', 'WelcomeController@index');

Route::get('home', 'HomeController@index');

Route::controllers([
	'auth' => 'Auth\AuthController',
//	'password' => 'Auth\PasswordController',
]);

Route::get('login', '\Meatings\Http\Controllers\Auth\AuthController@login');
Route::resource('users', '\Meatings\Http\Controllers\UserController');
Route::get('user/{user}/calendar', ['as' => 'user.calendar', 'uses' => 'CalendarController@show']);

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/test', function()
{
    $user = Meatings\User::find(1);
    $client = new \Google_Client();
    $client->setApplicationName(env('GOOGLE_APP_NAME'));
    $client->setDeveloperKey($user->token);

    $service = new Google_Service_Calendar($client);

    $calendarList = $service->calendarList->listCalendarList();

    while(true) {
        foreach ($calendarList->getItems() as $calendarListEntry) {
            echo $calendarListEntry->getSummary();
        }
        $pageToken = $calendarList->getNextPageToken();
        if ($pageToken) {
            $optParams = array('pageToken' => $pageToken);
            $calendarList = $service->calendarList->listCalendarList($optParams);
        } else {
            break;
        }
    }
});

Route::get('/', 'WelcomeController@index');

Route::get('home', 'HomeController@index');

Route::controllers([
	'auth' => 'Auth\AuthController',
//	'password' => 'Auth\PasswordController',
]);

Route::get('login', '\Meatings\Http\Controllers\Auth\AuthController@login');
Route::resource('users', '\Meatings\Http\Controllers\UserController');
Route::get('user/{user}/calendar', ['as' => 'user.calendar', 'uses' => 'CalendarController@show']);

Add test route, poking at API stuff

Add test route, poking at API stuff


<?php

class CM_Response_Resource_Layout extends CM_Response_Resource_Abstract {

    protected function _process() {
        $file = null;
        if ($path = $this->getRender()->getLayoutPath('resource/' . $this->getRequest()->getPath(), null, true, false)) {
            $file = new CM_File($path);
        }
        if (!$file) {
            throw new CM_Exception_Nonexistent('Invalid filename: `' . $this->getRequest()->getPath() . '`', null, array('severity' => CM_Exception::WARN));
        }
        $this->enableCache();
        $this->setHeader('Content-Type', $file->getMimeType());
        $this->_setContent($file->read());
    }

    public static function match(CM_Request_Abstract $request) {
        return $request->getPathPart(0) === 'layout';
    }
}

<?php

class CM_Response_Resource_Layout extends CM_Response_Resource_Abstract {

    protected function _process() {
        $content = null;
        $mimeType = null;

        if ($pathRaw = $this->getRender()->getLayoutPath('resource/' . $this->getRequest()->getPath(), null, true, false)) {
            $file = new CM_File($pathRaw);
            $content = $file->read();
            $mimeType = $file->getMimeType();
        } elseif ($pathTpl = $this->getRender()->getLayoutPath('resource/' . $this->getRequest()->getPath() . '.tpl', null, true, false)) {
            $content = $this->getRender()->fetchTemplate($pathTpl);
            $mimeType = CM_File::getMimeTypeByContent($content);
        } else {
            throw new CM_Exception_Nonexistent('Invalid filename: `' . $this->getRequest()->getPath() . '`', null,
                array('severity' => CM_Exception::WARN));
        }
        $this->enableCache();
        $this->setHeader('Content-Type', $mimeType);
        $this->_setContent($content);
    }

    public static function match(CM_Request_Abstract $request) {
        return $request->getPathPart(0) === 'layout';
    }
}

Allow to render layout resources as smarty templates


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.2';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.3';
}

Set release version to 0.8.3

Set release version to 0.8.3


<?php
namespace Concrete\Controller\SinglePage\Members;

use Concrete\Core\Page\Controller\PublicProfilePageController;
use Loader;
use User;
use UserInfo;
use Exception;

class Profile extends PublicProfilePageController
{
    public function view($userID = 0)
    {
        $html = Loader::helper('html');
        $canEdit = false;
        $u = new User();

        if ($userID > 0) {
            $profile = UserInfo::getByID($userID);
            if (!is_object($profile)) {
                throw new Exception('Invalid User ID.');
            }
        } elseif ($u->isRegistered()) {
            $profile = UserInfo::getByID($u->getUserID());
        } else {
            $this->set('intro_msg', t('You must sign in order to access this page!'));
            return $this->replace('/login');
        }
        if (is_object($profile) && $profile->getUserID() == $u->getUserID()) {
            $canEdit = true;
        }

        $this->set('profile', $profile);
        $this->set('badges', $profile->getUserBadges());
        $this->set('av', Loader::helper('concrete/avatar'));
        $this->set('t', Loader::helper('text'));
        $this->set('canEdit', $canEdit);
    }
}

<?php
namespace Concrete\Controller\SinglePage\Members;

use Concrete\Core\Page\Controller\PublicProfilePageController;
use Loader;
use User;
use UserInfo;
use Exception;

class Profile extends PublicProfilePageController
{
    public function view($userID = 0)
    {
        $html = Loader::helper('html');
        $canEdit = false;
        $u = new User();

        if ($userID > 0) {
            $profile = UserInfo::getByID($userID);
            if (!is_object($profile)) {
                return $this->replace('/page_not_found');
            }
        } elseif ($u->isRegistered()) {
            $profile = UserInfo::getByID($u->getUserID());
        } else {
            $this->set('intro_msg', t('You must sign in order to access this page!'));
            return $this->replace('/login');
        }
        if (is_object($profile) && $profile->getUserID() == $u->getUserID()) {
            $canEdit = true;
        }

        $this->set('profile', $profile);
        $this->set('badges', $profile->getUserBadges());
        $this->set('av', Loader::helper('concrete/avatar'));
        $this->set('t', Loader::helper('text'));
        $this->set('canEdit', $canEdit);
    }
}

Fix to show 404 for deleted user

Fix to show 404 for deleted user