<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Project;
use App\ProjectLabel;

class LabelsController extends Controller
{

    /**
     * Dsiplay a listing of the project labels
     *
     * @param Project $project
     * @return Response
     */
    public function index(Project $project)
    {
        $project->load('labels');

        return response()->json($project);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @param Project $project
     * @return Response
     */
    public function store(Request $request, Project $project)
    {
        $label = new ProjectLabel($request->all());

        $project->labels()->save($label);

        return response()->json($label);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Project $project
     * @param ProjectLabel $label
     * @return Response
     */
    public function update(Request $request, Project $project, ProjectLabel $label)
    {
        $label->update($request->all());

        return response()->json($label);http://localhost:8000

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Project $project
     * @param ProjectLabel $label
     * @return Response
     */
    public function destroy(Project $project, ProjectLabel $label)
    {
        $label->delete();
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Project;
use App\ProjectLabel;

class LabelsController extends Controller
{

    /**
     * Dsiplay a listing of the project labels
     *
     * @param Project $project
     * @return Response
     */
    public function index(Project $project)
    {
        $project->load('labels');

        return response()->json($project);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @param Project $project
     * @return Response
     */
    public function store(Request $request, Project $project)
    {
        $label = new ProjectLabel($request->all());

        $project->labels()->save($label);

        return response()->json($label);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Project $project
     * @param ProjectLabel $label
     * @return Response
     */
    public function update(Request $request, Project $project, ProjectLabel $label)
    {
        $label->update($request->all());

        return response()->json($label);

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Project $project
     * @param ProjectLabel $label
     * @return Response
     */
    public function destroy(Project $project, ProjectLabel $label)
    {
        $label->delete();

        return $label;
    }
}

Fix delete action should return a json object


<?php

namespace App\Http\Livewire;

use App\Models\TestDate;
use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;

class PendingSurveysTable extends DataTableComponent
{
    public string $defaultSortColumn = 'test_date';
    public string $defaultSortDirection = 'asc';
    public bool $singleColumnSorting = false;
    public bool $paginationEnabled = false;
    public bool $showSearch = false;

    public function columns(): array
    {
        return [
            Column::make('Survey ID', 'id')
                ->sortable(),
            Column::make('Description', 'machine.description'),
            Column::make('Date scheduled', 'test_date')
                ->sortable(),
            Column::make('Test Type', 'type.test_type'),
            Column::make('Accession'),
            Column::make('Survey Note'),
        ];
    }

    public function rowView(): string
    {
        return 'livewire-tables.pending-surveys-row';
    }

    public function query(): Builder
    {
        return TestDate::with('machine', 'type')
            ->pending();
    }
}

<?php

namespace App\Http\Livewire;

use App\Models\TestDate;
use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;

class PendingSurveysTable extends DataTableComponent
{
    public string $defaultSortColumn = 'test_date';
    public string $defaultSortDirection = 'asc';
    public bool $singleColumnSorting = false;
    public bool $paginationEnabled = false;
    public bool $showSearch = false;

    public function columns(): array
    {
        return [
            Column::make('Survey ID', 'id')
                ->sortable(),
            Column::make('Description', 'machine.description'),
            Column::make('Date scheduled', 'test_date')
                ->sortable(),
            Column::make('Test Type', 'type.test_type'),
            Column::make('Accession'),
            Column::make('Survey Note'),
        ];
    }

    public function rowView(): string
    {
        return 'livewire-tables.pending-surveys-row';
    }

    public function query(): Builder
    {
        return TestDate::query()
            ->with('machine', 'type')
            ->pending();
    }
}

Adjust pending survey table query

Adjust pending survey table query


<?php

// directory paths
$baseDirectory = realpath(__DIR__.'/..');
$buildDirectory = $baseDirectory . '/build';
$artifactsDirectory = $buildDirectory . '/artifacts';
$stagingDirectory = $artifactsDirectory . '/staging';

// create all needed directories.
if( !file_exists( $artifactsDirectory )) {
    mkdir($artifactsDirectory);
}

// setup packager
require $baseDirectory . '/vendor/mtdowling/burgomaster/src/Burgomaster.php';
$packager = new \Burgomaster( $stagingDirectory, $baseDirectory );

// include readme and license files
foreach(['README.md', 'LICENSE'] as $file) {
    $packager->deepCopy( $file, $file );
}

// include source
$packager->recursiveCopy( 'src', 'GW2Treasures/GW2Api', ['php'] );

// create the autoloader
$packager->createAutoloader();

// build phar and zip archives
$packager->createPhar( $buildDirectory . '/artifacts/gw2api.phar');
$packager->createZip( $buildDirectory . '/artifacts/gw2api.zip');

<?php

// directory paths
$baseDirectory = realpath(__DIR__.'/..');
$buildDirectory = $baseDirectory . '/build';
$artifactsDirectory = $buildDirectory . '/artifacts';
$stagingDirectory = $artifactsDirectory . '/staging';

// create all needed directories.
if( !file_exists( $artifactsDirectory )) {
    mkdir($artifactsDirectory);
}

// setup packager
require $baseDirectory . '/vendor/mtdowling/burgomaster/src/Burgomaster.php';
$packager = new \Burgomaster( $stagingDirectory, $baseDirectory );

// include readme and license files
foreach(['README.md', 'LICENSE'] as $file) {
    $packager->deepCopy( $file, $file );
}

// include source
$packager->recursiveCopy( 'src', 'GW2Treasures/GW2Api', ['php'] );

// include cacert.pem
$packager->deepCopy('src/cacert.pem', 'GW2Treasures/GW2Api/cacert.pem');

// create the autoloader
$packager->createAutoloader();

// build phar and zip archives
$packager->createPhar( $buildDirectory . '/artifacts/gw2api.phar');
$packager->createZip( $buildDirectory . '/artifacts/gw2api.zip');

Add missing cacert.pem to phar archives

Add missing cacert.pem to phar archives


<?php

namespace Common\BlockEditor\Blocks;

final class QuoteBlock extends AbstractBlock
{
    public function getConfig(): array
    {
        return [
            'class' => 'BlockEditor.blocks.Quote',
        ];
    }

    public function getValidation(): array
    {
        return [
            'text' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'caption' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'alignment' => [
                'type' => 'string',
            ],
        ];
    }

    public function parse(array $data): string
    {
        return $this->parseWithTwig('Core/Layout/Templates/EditorBlocks/QuoteBlock.html.twig', $data);
    }

    public function getJavaScriptUrl(): ?string
    {
        return null;
    }
}

<?php

namespace Common\BlockEditor\Blocks;

final class QuoteBlock extends AbstractBlock
{
    public function getConfig(): array
    {
        return [
            'class' => 'BlockEditor.blocks.Quote',
        ];
    }

    public function getValidation(): array
    {
        return [
            'text' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'caption' => [
                'type' => 'string',
                'required' => true,
                'allowedTags' => 'b,i,a[href]',
            ],
            'alignment' => [
                'canBeOnly' => '["left", "center"]',
            ],
        ];
    }

    public function parse(array $data): string
    {
        return $this->parseWithTwig('Core/Layout/Templates/EditorBlocks/QuoteBlock.html.twig', $data);
    }

    public function getJavaScriptUrl(): ?string
    {
        return null;
    }
}

Make alignment a canOnlyBe type

Make alignment a canOnlyBe type


<?php
namespace Freischutz\Application;

use Phalcon\Mvc\User\Component;

/**
 * Freischutz\Application\Data
 */
class Data extends Component
{
    private $data;

    /**
     * Constructor.
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Get raw data.
     *
     * @return string|binary
     */
    public function getRaw()
    {
        return $this->data;
    }

    /**
     * Handle JSON data.
     *
     * @param bool $assoc (optional) Return associative array instead of object.
     * @return object|array|false
     */
    public function getJson($assoc = false)
    {
        $json = json_decode($this->data, $assoc);
        $json = $json !== null ? $json : false;
        return $json;
    }

    /**
     * Handle XML data.
     *
     * @return \SimpleXMLElement|false
     */
    public function getXml()
    {
        return simplexml_load_string($this->data);
    }
}

<?php
namespace Freischutz\Application;

use Phalcon\Mvc\User\Component;

/**
 * Freischutz\Application\Data
 */
class Data extends Component
{
    private $data;

    /**
     * Constructor.
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Get data handled according to content-type.
     *
     * @return mixed
     */
    public function get()
    {
        switch ($this->request->getHeader('CONTENT_TYPE')) {
            case 'application/json':
                $data = $this->getJson();
                break;
            case 'application/xml':
            case 'text/xml':
                $data = $this->getXml();
                break;
            default:
                $data = $this->getRaw();
                break;
        }
        return $data;
    }

    /**
     * Get raw data.
     *
     * @return string|binary
     */
    public function getRaw()
    {
        return $this->data;
    }

    /**
     * Handle JSON data.
     *
     * @param bool $assoc (optional) Return associative array instead of object.
     * @return object|array|false
     */
    public function getJson($assoc = false)
    {
        $json = json_decode($this->data, $assoc);
        $json = $json !== null ? $json : false;
        return $json;
    }

    /**
     * Handle XML data.
     *
     * @return \SimpleXMLElement|false
     */
    public function getXml()
    {
        return simplexml_load_string($this->data);
    }
}

Add generic get() method for data

Add generic get() method for data

Data::get() will check content-type and use the appropriate type-specific
get method to handle the data.


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;

/**
 * AuthenticationProviderInterface is the interface for all authentication
 * providers.
 *
 * Concrete implementations processes specific Token instances.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface AuthenticationProviderInterface extends AuthenticationManagerInterface
{
    /**
     * Checks whether this provider supports the given token.
     *
     * @param TokenInterface $token A TokenInterface instance
     *
     * @return Boolean true if the implementation supports the Token, false otherwise
     */
     function supports(TokenInterface $token);
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;

/**
 * AuthenticationProviderInterface is the interface for all authentication
 * providers.
 *
 * Concrete implementations processes specific Token instances.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface AuthenticationProviderInterface extends AuthenticationManagerInterface
{
    /**
     * Checks whether this provider supports the given token.
     *
     * @param TokenInterface $token A TokenInterface instance
     *
     * @return Boolean true if the implementation supports the Token, false otherwise
     */
     public function supports(TokenInterface $token);
}

Add a public modifier to an interface method


<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014-2015 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Plugin\PinterestBundle;

use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\PinterestBundle\DependencyInjection\ElcodiPinterestExtension;

/**
 * Class ElcodiPinterestBundle
 */
class ElcodiPinterestBundle extends Bundle implements PluginInterface
{
    /**
     * Returns the bundle's container extension.
     *
     * @return ExtensionInterface The container extension
     */
    public function getContainerExtension()
    {
        return new ElcodiPinterestExtension();
    }

    /**
     * Register Commands.
     *
     * Disabled as commands are registered as services.
     *
     * @param Application $application An Application instance
     */
    public function registerCommands(Application $application)
    {
        return null;
    }
}

<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014-2015 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Plugin\PinterestBundle;

use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\PinterestBundle\DependencyInjection\ElcodiPinterestExtension;

/**
 * Class ElcodiPinterestBundle
 */
class ElcodiPinterestBundle extends Bundle implements PluginInterface
{
    /**
     * Returns the bundle's container extension.
     *
     * @return ExtensionInterface The container extension
     */
    public function getContainerExtension()
    {
        return new ElcodiPinterestExtension();
    }

    /**
     * Register Commands.
     *
     * Disabled as commands are registered as services.
     *
     * @param Application $application An Application instance
     *
     * @return null
     */
    public function registerCommands(Application $application)
    {
        return null;
    }
}

Store + Shipping + Menus

Store + Shipping + Menus

* Using new Store feature from Elcodi
* Added Store management in Admin
* Changed all definitions that was depending on such implementation
* Removed under construction logic and tests

* Removed menu fixtures
* Defined them as dynamic content. Some of them are generated dinamically, and
  some of them statically.
* Added neede menu builders in every Admin bundle
* Changed the way menu is loaded in Admin

* Removed dependency with Configuration and Configuration annotation, in order to use
  new implementation.
* Removed configuration elements
* Removed all `elcodi_config` twig extension usage

* Moved custom shipping logic from elcodi/elcodi to elcodi-plugins/*
* Added full repo inside Plugin folder
* Using new Shipping engine

* Updated some code in order to be compatible with Sf2.7 deprecations

Ready for Elcodi Beta! Auu! Auu!


<?php

function pole_display_price($label, $price) {
  if (!function_exists('socket_create')) return;
  if (!defined('POLE_SERVER')) return;

  $sock= socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  /* Set 1 sec timeout to avoid getting stuck, should be plenty long enough */
  socket_set_option($sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1,
                                                          'usec' => 0));
  if (@socket_connect($sock,  POLE_SERVER, 1888)) {
    socket_write($sock,
                 sprintf("\x0a\x0d%-19.19s\x0a\x0d$%18.2f ",
                         $label, $price));
  }
}

<?php

function pole_display_price($label, $price) {
  if (!defined('POLE_SERVER')) {
    error_log("POLE_SERVER not configured");
    return;
  }

  $sock= fsockopen(POLE_SERVER, 1888, $errno, $errstr, 1);
  if ($sock) {
    fwrite($sock, sprintf("\x0a\x0d%-19.19s\x0a\x0d$%18.2f ", $label, $price));
  }
}

Use fsockopen() instead of socket functions


<?
include '../scat.php';
include '../lib/txn.php';
include '../lib/item.php';

$txn_id= (int)$_REQUEST['txn'];

if ($txn_id) {
  $txn= txn_load($db, $txn_id);
  if ($txn['paid']) {
    die_jsonp("This order is already paid!");
  }
}

foreach ($_REQUEST['items'] as $item => $qty) {
  $q= "INSERT INTO txn_line (txn, item, ordered, retail_price, taxfree)
       SELECT $txn_id AS txn, $item AS item, $qty AS ordered,
              (SELECT net_price
                 FROM vendor_item
                WHERE item = $item AND vendor = {$txn['person']}), taxfree
         FROM item WHERE id = $item";
  $r= $db->query($q);
  if (!$r) die_query($db, $q);
}

$txn= txn_load($db, $txn_id);
$items= txn_load_items($db, $txn_id);

echo jsonp(array('txn' => $txn, 'items' => $items));

<?
include '../scat.php';
include '../lib/txn.php';
include '../lib/item.php';

$txn_id= (int)$_REQUEST['txn'];

if ($txn_id) {
  $txn= txn_load($db, $txn_id);
  if ($txn['paid']) {
    die_jsonp("This order is already paid!");
  }
}

foreach ($_REQUEST['items'] as $item => $qty) {
  $q= "INSERT INTO txn_line (txn, item, ordered, retail_price, taxfree)
       SELECT $txn_id AS txn, $item AS item, $qty AS ordered,
              (SELECT net_price
                 FROM vendor_item
                WHERE item = $item AND vendor = {$txn['person']}
                ORDER BY id DESC LIMIT 1), taxfree
         FROM item WHERE id = $item";
  $r= $db->query($q);
  if (!$r) die_query($db, $q);
}

$txn= txn_load($db, $txn_id);
$items= txn_load_items($db, $txn_id);

echo jsonp(array('txn' => $txn, 'items' => $items));

Deal with multiple listings in vendor items


<?php

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

class CreateBlogpostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    private $table_name = 'blogposts';

    public function up()
    {
        if (Schema::hasTable($this->table_name)) { return; }

        Schema::create($this->table_name, function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug');
            $table->string('summary');
            $table->text('text');
            $table->integer('category_id');
            $table->integer('comments_enabled');
            $table->integer('author_id');
            $table->string('image')->nullable();
            $table->timestamps();
            $table->boolean('active')->default(true);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop($this->table_name);
    }
}

<?php

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

class CreateBlogpostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    private $table_name = 'blogposts';

    public function up()
    {
        if (Schema::hasTable($this->table_name)) { return; }

        Schema::create($this->table_name, function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug');
            $table->string('summary')->nullable();
            $table->text('text')->nullable();
            $table->integer('category_id');
            $table->integer('comments_enabled');
            $table->integer('author_id');
            $table->string('image')->nullable();
            $table->timestamps();
            $table->boolean('active')->default(true);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop($this->table_name);
    }
}

Make blogpost summary and content nullable


<?php

declare(strict_types=1);

namespace JMS\Serializer;

/**
 * Serializer Interface.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
interface SerializerInterface
{
    /**
     * Serializes the given data to the specified output format.
     *
     * @param mixed $data
     */
    public function serialize($data, string $format, ?SerializationContext $context = null, ?string $type = null): string;

    /**
     * Deserializes the given data to the specified type.
     *
     * @return mixed
     */
    public function deserialize(string $data, string $type, string $format, ?DeserializationContext $context = null);
}

<?php

declare(strict_types=1);

namespace JMS\Serializer;

/**
 * Serializer Interface.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
interface SerializerInterface
{
    /**
     * Serializes the given data to the specified output format.
     *
     * @param mixed $data
     */
    public function serialize($data, string $format, ?SerializationContext $context = null, ?string $type = null): string;

    /**
     * Deserializes the given data to the specified type.
     *
     * @return mixed
     *
     * @psalm-template T
     * @psalm-param class-string<T> $type
     * @psalm-return T
     */
    public function deserialize(string $data, string $type, string $format, ?DeserializationContext $context = null);
}

Add psalm specific generic return type for deserialize

See https://psalm.dev/ and
https://medium.com/vimeo-engineering-blog/uncovering-php-bugs-with-template-a4ca46eb9aeb


<?php

namespace React\Dns;

use React\Socket\Connection;

class Resolver
{
    public function resolve($domain, $callback)
    {
        $nameserver = '8.8.8.8';
        $query = new Query($domain, 'A', 'IN');

        $this->query($nameserver, $query, function (Message $response) use ($callback) {
            $answer = $response->answer[array_rand($response->answer)]->data->address;
            $callback($address);
        });
    }

    public function query($nameserver, Query $query, $callback)
    {
        $dumper = new BinaryDumper();
        $parser = new Parser();

        $message = new Message();
        $message->header = array(
            $query...
        );
        $message->question = array(
            $query...
        );

        $response = new Message();

        $conn = new Connection(fopen("udp://$nameserver:53"), $this->loop);
        $conn->on('data', function ($data) use ($conn, $response, $callback) {
            if ($parser->parseChunk($data, $response)) {
                $conn->end();
                $callback($response);
            }
        });
        $conn->write($dumper->toBinary($message));
    }
}

<?php

namespace React\Dns;

use React\Socket\Connection;

class Resolver
{
    public function resolve($domain, $callback)
    {
        $nameserver = '8.8.8.8';
        $query = new Query($domain, 'A', 'IN');

        $this->query($nameserver, $query, function (Message $response) use ($callback) {
            $answer = $response->answer[array_rand($response->answer)]->data->address;
            $callback($address);
        });
    }

    public function query($nameserver, Query $query, $callback)
    {
        $dumper = new BinaryDumper();
        $parser = new Parser();

        $message = new Message();
        $message->header = array(
            // $query...
        );
        $message->question = array(
            // $query...
        );

        $response = new Message();

        $conn = new Connection(fopen("udp://$nameserver:53"), $this->loop);
        $conn->on('data', function ($data) use ($conn, $response, $callback) {
            if ($parser->parseChunk($data, $response)) {
                $conn->end();
                $callback($response);
            }
        });
        $conn->write($dumper->toBinary($message));
    }
}

Fix parse errors in resolver stub

[Dns] Fix parse errors in resolver stub


<?php

namespace Stripe\ApiOperations;

/**
 * Trait for retrievable resources. Adds a `retrieve()` static method to the
 * class.
 *
 * This trait should only be applied to classes that derive from StripeObject.
 */
trait Retrieve
{
    /**
     * @param array|string $id The ID of the API resource to retrieve,
     *     or an options array containing an `id` key.
     * @param array|string|null $opts
     *
     * @return \Stripe\StripeObject
     */
    public static function retrieve($id, $opts = null)
    {
        $opts = \Stripe\Util\RequestOptions::parse($opts);
        $instance = new static($id, $opts);
        $instance->refresh();
        return $instance;
    }
}

<?php

namespace Stripe\ApiOperations;

/**
 * Trait for retrievable resources. Adds a `retrieve()` static method to the
 * class.
 *
 * This trait should only be applied to classes that derive from StripeObject.
 */
trait Retrieve
{
    /**
     * @param array|string $id The ID of the API resource to retrieve,
     *     or an options array containing an `id` key.
     * @param array|string|null $opts
     *
     * @return static
     */
    public static function retrieve($id, $opts = null)
    {
        $opts = \Stripe\Util\RequestOptions::parse($opts);
        $instance = new static($id, $opts);
        $instance->refresh();
        return $instance;
    }
}

Update return type to `static` to improve static analysis


<?php
/**
 * Configuration file for the OpenID provider.
 */

$config = array(

	/* The authentication source that should be used. */
	'auth' => 'default-sp',

	/* The name of the attribute which contains the username of the user. */
	'username_attribute' => 'uid',

	/* The directory where OpenID data is stored. */
	'filestore' => '/tmp/ssp-openid-provider',

);

<?php
/**
 * Configuration file for the OpenID provider.
 */

$config = array(

	/* The authentication source that should be used. */
	'auth' => 'default-sp',

	/* The name of the attribute which contains the username of the user. */
	'username_attribute' => 'uid',

	/* The directory where OpenID data is stored. */
	'filestore' => '/var/lib/simplesamlphp-openid-provider',

);

openidProvider: Change the default directory for the data store.

The default configuration uses a directory in /tmp, which may allow
an user to create this directory before simpleSAMLphp attempts to
create it. This can allow the user to overwrite files the webserver has
access to.

This patch changes the default directory.

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@2084 44740490-163a-0410-bde0-09ae8108e29a


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    protected $table = 'threads';

    public function posts() {
        return $this->hasMany('App\Post');
    }
}

Fix code to comply with coding standards


<?php

/**
 * @loadSharedFixture
 */
class SPM_ShopyMind_Test_Lib_ShopymindClient_Callback_Get_Products extends EcomDev_PHPUnit_Test_Case
{

    public function testCanGetRandomProducts()
    {
        Mage::app()->setCurrentStore(1);
        $products = ShopymindClient_Callback::getProducts('store-1', false, false, true, 1);

        $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_url']);

        Mage::app()->setCurrentStore(0);
    }

    public function testIfAStoreHasNoProductsNothingIsReturned()
    {
        $products = ShopymindClient_Callback::getProducts('store-2', false, false, true, 1);

        $this->assertEmpty($products);
    }

}

<?php

/**
 * @loadSharedFixture
 */
class SPM_ShopyMind_Test_Lib_ShopymindClient_Callback_Get_Products extends EcomDev_PHPUnit_Test_Case
{

    public function testCanGetRandomProducts()
    {
        Mage::app()->setCurrentStore(1);
        $products = ShopymindClient_Callback::getProducts('store-1', false, false, true, 1);

        $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_url']);

        Mage::app()->setCurrentStore(0);
    }

    public function testIfAStoreHasNoProductsNothingIsReturned()
    {
        $products = ShopymindClient_Callback::getProducts('store-2', false, false, true, 1);

        $this->assertEmpty($products);
    }

    public function testCanGetRandomProductsIfNoStoreIsDefined()
    {
        $products = ShopymindClient_Callback::getProducts(null, false, false, true, 1);

        $this->assertRegExp('#catalog/product/view/id/[1-2]/#', $products[0]['product_url']);
    }
}

Add test for get products when no store is specified


<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Sporz</title>
        <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
	</head>
	<body>
	<?php $this->yields(); ?>
	</body>
</html>

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Sporz</title>
        <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
	</head>
	<body>
	<?php $this->yields(); ?>
	</body>
</html>

Use absolute include web path

Use absolute include web path


<div class="post" id="post-<?php echo post['id'];?>">

<?php echo h($post['title'])?>

Modified at: <?php echo strftime('%c', strtotime($post['modified_at']))?>

    <?php echo h($post['body'])?>

    <a href="<?php echo  url_for('posts', $post['id']); ?>">show |
    <a href="<?php echo url_for('posts', $post['id'], 'edit'); ?>">edit |
    <a href="<?php echo  url_for('posts', $post['id']);?>" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'DELETE'); f.appendChild(m); f.submit(); };return false;">delete

<div class="post" id="post-<?php echo $post['id'];?>">

<?php echo h($post['title'])?>

Modified at: <?php echo strftime('%c', strtotime($post['modified_at']))?>

    <?php echo h($post['body'])?>

    <a href="<?php echo  url_for('posts', $post['id']); ?>">show |
    <a href="<?php echo url_for('posts', $post['id'], 'edit'); ?>">edit |
    <a href="<?php echo  url_for('posts', $post['id']);?>" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'DELETE'); f.appendChild(m); f.submit(); };return false;">delete

Fix post id in _post view

Fix post id in _post view


<?php
/*
 * This file is part of the PayBreak\ApiClient package.
 *
 * (c) PayBreak <dev@paybreak.com>
 *
 * For the full copyright and license information, please view the LICENSE.md
 * file that was distributed with this source code.
 */

namespace Tests\ApiClient;

use PayBreak\ApiClient\CsvApiClient;
use GuzzleHttp\Exception\ClientException;

/**
 * Csv Api Client Test
 *
 * @author JH
 * @package Tests\ApiClient
 */
class CsvApiClientTest extends \PHPUnit_Framework_TestCase
{
    private $sampleCsvPath = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv';

    public function testMake()
    {
        $client = CsvApiClient::make('http://httpbin.org/');
        $this->assertInstanceOf('PayBreak\ApiClient\ApiClient', $client);
        $this->assertInstanceOf('PayBreak\ApiClient\CsvApiClient', $client);
    }

    public function testExceptionIsThrownWhenResponseIsNotCsv()
    {
        $client = CsvApiClient::make('http://httpbin.org/');

        $this->setExpectedException(ClientException::class);
        $client->get('get');
    }

    public function testGetCsv()
    {
        $client = new CsvApiClient();
        $response = $client->get($this->sampleCsvPath);
        $this->assertArrayHasKey('csv', $response);
    }
}

<?php
/*
 * This file is part of the PayBreak\ApiClient package.
 *
 * (c) PayBreak <dev@paybreak.com>
 *
 * For the full copyright and license information, please view the LICENSE.md
 * file that was distributed with this source code.
 */

namespace Tests\ApiClient;

use PayBreak\ApiClient\CsvApiClient;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

/**
 * Csv Api Client Test
 *
 * @author JH
 * @package Tests\ApiClient
 */
class CsvApiClientTest extends \PHPUnit_Framework_TestCase
{
    public function testMake()
    {
        $client = CsvApiClient::make('http://httpbin.org/');
        $this->assertInstanceOf('PayBreak\ApiClient\ApiClient', $client);
        $this->assertInstanceOf('PayBreak\ApiClient\CsvApiClient', $client);
    }

    public function testExceptionIsThrownWhenResponseIsNotCsv()
    {
        $client = CsvApiClient::make('http://httpbin.org/');

        $this->setExpectedException(ClientException::class);
        $client->get('get');
    }

    public function testGetCsv()
    {
        $mock = new MockHandler([
            new Response(200, ['Content-Type' => 'text/csv']),
        ]);

        $client = new CsvApiClient(['handler' => HandlerStack::create($mock)]);
        $response = $client->get('http://example.com/test.csv');
        $this->assertArrayHasKey('csv', $response);
    }
}

Use Guzzle/MockHandler instead of external url to test csv download


<?php
namespace Kuartet\BI\ExchangeRate;

use \Carbon\Carbon;
use \PHPUnit_Framework_TestCase;

class ExchangeRateTest extends PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $code = 'IDR';
        $name = 'Indonesian Rupiah';
        $sell = 10000;
        $buy = 11000;
        $middle = 10500;
        $updatedAt = Carbon::now();

        $exchangeRate = new ExchangeRate($code, $name, $sell, $buy, $middle, $updatedAt);
        $this->assertInstanceOf('Kuartet\BI\ExchangeRate\ExchangeRateInterface', $exchangeRate);
        $this->assertEquals($code, $exchangeRate->getCode());
        $this->assertEquals($name, $exchangeRate->getName());
        $this->assertEquals($sell, $exchangeRate->getSell());
        $this->assertEquals($but, $exchangeRate->getBuy());
        $this->assertEquals($middle, $exchangeRate->getMiddle());
        $this->assertEquals($updatedAt, $exchangeRate->getUpdatedAt());
    }
}

<?php
namespace Kuartet\BI\ExchangeRate;

use \Carbon\Carbon;
use \PHPUnit_Framework_TestCase;

class ExchangeRateTest extends PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $code = 'IDR';
        $name = 'Indonesian Rupiah';
        $sell = 10000;
        $buy = 11000;
        $middle = 10500;
        $updatedAt = Carbon::now();

        $exchangeRate = new ExchangeRate($code, $name, $sell, $buy, $updatedAt);
        $this->assertInstanceOf('Kuartet\BI\ExchangeRate\ExchangeRateInterface', $exchangeRate);
        $this->assertEquals($code, $exchangeRate->getCode());
        $this->assertEquals($name, $exchangeRate->getName());
        $this->assertEquals($sell, $exchangeRate->getSell());
        $this->assertEquals($buy, $exchangeRate->getBuy());
        $this->assertEquals($middle, $exchangeRate->getMiddle());
        $this->assertEquals($updatedAt, $exchangeRate->getUpdatedAt());
    }
}

Remove $middle from constructor and fix some typo


<?php

namespace MusicBrainz\Value\Property;

use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\TextRepresentation;

/**
 * Provides a getter for the text representation.
 */
trait TextRepresentationTrait
{
    /**
     * A text representation
     *
     * @var TextRepresentation
     */
    private $textRepresentation;

    /**
     * Returns the text representation.
     *
     * @return TextRepresentation
     */
    public function getText(): TextRepresentation
    {
        return $this->textRepresentation;
    }

    /**
     * Sets the text representation by extracting it from a given input array.
     *
     * @param array $input An array returned by the webservice
     *
     * @return void
     */
    private function setTextRepresentationFromArray(array $input): void
    {
        $this->textRepresentation = is_null($textRepresentation = ArrayAccess::getArray($input, 'text-representation'))
            ? new TextRepresentation
            : new TextRepresentation($textRepresentation);
    }
}

<?php

namespace MusicBrainz\Value\Property;

use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\TextRepresentation;

/**
 * Provides a getter for the text representation.
 */
trait TextRepresentationTrait
{
    /**
     * A text representation
     *
     * @var TextRepresentation
     */
    private $textRepresentation;

    /**
     * Returns the text representation.
     *
     * @return TextRepresentation
     */
    public function getTextRepresentation(): TextRepresentation
    {
        return $this->textRepresentation;
    }

    /**
     * Sets the text representation by extracting it from a given input array.
     *
     * @param array $input An array returned by the webservice
     *
     * @return void
     */
    private function setTextRepresentationFromArray(array $input): void
    {
        $this->textRepresentation = is_null($textRepresentation = ArrayAccess::getArray($input, 'text-representation'))
            ? new TextRepresentation
            : new TextRepresentation($textRepresentation);
    }
}

Fix getter for text representation

Fix getter for text representation


<?php
namespace Polidog\Todo\Resource\Page;

namespace Polidog\Todo\Form;

use Ray\WebFormModule\FormFactory;

class TodoFormTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var TodoForm
     */
    private $form;

    protected function setUp()
    {
        parent::setUp();
        $this->form = (new FormFactory())->newInstance(TodoForm::class);
    }

    public function testFailedEmpty()
    {
        $submit = [];
        $isValid = $this->form->apply($submit);
        $this->assertFalse($isValid);
    }

    public function testFailedEmptyVale()
    {
        $submit = ['title' => ''];
        $isValid = $this->form->apply($submit);
        $this->assertFalse($isValid);
        $msg = $this->form->getFailureMessages();
        $expected = ['title' => ['必ず入力してください']];
        $this->assertSame($expected, $msg);
    }

    public function testOk()
    {
        $submit = ['title' => 'test'];
        $isValid = $this->form->apply($submit);
        $this->assertTrue($isValid);
    }

    public function testFormView()
    {
        $formHtml = (string) $this->form;
        $expected = '<form method="post" action="/" enctype="multipart/form-data"><div class="form-group"><input id="todo[title]" type="text" name="todo[title]" class="form-control" size="20" />
</div>
<input type="submit" name="submit" value="登録" class="btn btn-primary" />
</form>';
        $this->assertSame($expected, $formHtml);
    }
}

<?php
namespace Polidog\Todo\Form;

use Ray\WebFormModule\FormFactory;

class TodoFormTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var TodoForm
     */
    private $form;

    protected function setUp()
    {
        parent::setUp();
        $this->form = (new FormFactory())->newInstance(TodoForm::class);
    }

    public function testFailedEmpty()
    {
        $submit = [];
        $isValid = $this->form->apply($submit);
        $this->assertFalse($isValid);
    }

    public function testFailedEmptyVale()
    {
        $submit = ['title' => ''];
        $isValid = $this->form->apply($submit);
        $this->assertFalse($isValid);
        $msg = $this->form->getFailureMessages();
        $expected = ['title' => ['必ず入力してください']];
        $this->assertSame($expected, $msg);
    }

    public function testOk()
    {
        $submit = ['title' => 'test'];
        $isValid = $this->form->apply($submit);
        $this->assertTrue($isValid);
    }

    public function testFormView()
    {
        $formHtml = (string) $this->form;
        $expected = '<form method="post" action="/" enctype="multipart/form-data"><div class="form-group"><input id="todo[title]" type="text" name="todo[title]" class="form-control" size="20" />
</div>
<input type="submit" name="submit" value="登録" class="btn btn-primary" />
</form>';
        $this->assertSame($expected, $formHtml);
    }
}

Fix phpmd error: USE declarations must go after the first namespace declaration


<?php

/**
 * Skeleton subclass for representing a row from the 'profile' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.lib.model
 */
class Profile extends BaseProfile {

  const DEFAULT_AVATAR_URL = "mm";

  public function __toString()
  {
    return ($this->getNickname() != '') ? $this->getNickname() : $this->getsfGuardUser()->getUsername();
  }

  public function getAvatarUrl($size = 24)
  {
    return sprintf("http://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($this->getEmail()))), urlencode(self::DEFAULT_AVATAR_URL), $size);
  }

  /**
   * @static
   * @param string $email
   * @param int $size
   * @return string
   */
  public static function getAvatarUrlFromEmail($email, $size = 24)
  {
    if (null === $email)
    {
      $email = 0;
    }

    return sprintf("http://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($email))), urlencode(self::DEFAULT_AVATAR_URL), $size);
  }
} // Profile

<?php

/**
 * Skeleton subclass for representing a row from the 'profile' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.lib.model
 */
class Profile extends BaseProfile {

  const DEFAULT_AVATAR_URL = "mm";

  public function __toString()
  {
    return ($this->getNickname() != '') ? $this->getNickname() : $this->getsfGuardUser()->getUsername();
  }

  public function getAvatarUrl($size = 24)
  {
    return sprintf("https://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($this->getEmail()))), urlencode(self::DEFAULT_AVATAR_URL), $size);
  }

  /**
   * @static
   * @param string $email
   * @param int $size
   * @return string
   */
  public static function getAvatarUrlFromEmail($email, $size = 24)
  {
    if (null === $email)
    {
      $email = 0;
    }

    return sprintf("https://www.gravatar.com/avatar/%s?d=%s&s=%s", md5(strtolower(trim($email))), urlencode(self::DEFAULT_AVATAR_URL), $size);
  }
} // Profile

Use https for gravatar images

Use https for gravatar images


<?php
$RUNTIME_NOSETUPFS = true;
$RUNTIME_NOAPPS = TRUE;
require_once('lib/base.php');
if (array_key_exists('PATH_INFO', $_SERVER)){
	$path_info = $_SERVER['PATH_INFO'];
}else{
	$path_info = substr($_SERVER['PHP_SELF'], strpos($_SERVER['PHP_SELF'], basename(__FILE__)) + strlen(basename(__FILE__)));
}
if (!$pos = strpos($path_info, '/', 1)) {
	$pos = strlen($path_info);
}
$service=substr($path_info, 1, $pos-1);
$file = OC_AppConfig::getValue('core', 'remote_' . $service);
if(is_null($file)){
	header('HTTP/1.0 404 Not Found');
	exit;
}

$parts=explode('/',$file);
$app=$parts[2];
OC_App::loadApp($app);

$baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
require_once(OC::$APPSROOT . $file);

<?php
$RUNTIME_NOSETUPFS = true;
$RUNTIME_NOAPPS = TRUE;
require_once('lib/base.php');
if (array_key_exists('PATH_INFO', $_SERVER)){
	$path_info = $_SERVER['PATH_INFO'];
}else{
	$path_info = substr($_SERVER['PHP_SELF'], strpos($_SERVER['PHP_SELF'], basename(__FILE__)) + strlen(basename(__FILE__)));
}
if ($path_info === false) {
	OC_Response::setStatus(OC_Response::STATUS_NOT_FOUND);
	exit;
}
if (!$pos = strpos($path_info, '/', 1)) {
	$pos = strlen($path_info);
}
$service=substr($path_info, 1, $pos-1);
$file = OC_AppConfig::getValue('core', 'remote_' . $service);
if(is_null($file)){
	OC_Response::setStatus(OC_Response::STATUS_NOT_FOUND);
	exit;
}

$parts=explode('/',$file);
$app=$parts[2];
OC_App::loadApp($app);

$baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
require_once(OC::$APPSROOT . $file);

Check for missing path_info, also use OC_Response for 404 error


<?php
namespace ThinkSayDo\EnvTenant\Events;

use ThinkSayDo\EnvTenant\Resolver;

class TenantNotResolvedEvent extends TenantEvent
{
    public $resolver;

    public function __construct(Resolver $resolver)
    {
        $this->resolver = $resolver;
    }
}

<?php
namespace ThinkSayDo\EnvTenant\Events;

use ThinkSayDo\EnvTenant\TenantResolver;

class TenantNotResolvedEvent extends TenantEvent
{
    public $resolver;

    public function __construct(TenantResolver $resolver)
    {
        $this->resolver = $resolver;
    }
}

Fix bug with TenantResolver injection.

Fix bug with TenantResolver injection.


<?php
/**
 * PSR-4 Compliant Autoloader
 *
 * This will dynamically load classes by resolving the prefix and class name. This is the method that frameworks
 * such as Laravel and Composer automatically resolve class names and load them. To use it, simply set the
 * configurable parameters inside the closure. This example is taken from PHP-FIG, referenced below.
 *
 * @param string $class fully qualified class name to load
 * @see http://www.php-fig.org/psr/psr-4/examples/ PSR-4 Example Autoloader
 **/
spl_autoload_register(function($class) {
	/**
	 * CONFIGURABLE PARAMETERS
	 * prefix: the prefix for all the classes (i.e., the namespace)
	 * baseDir: the base directory for all classes (default = current directory)
	 **/
	$prefix = "PetRescueAbq\\Http\\Petfoster";
	$baseDir = __DIR__;

	// does the class use the namespace prefix?
	$len = strlen($prefix);
	if (strncmp($prefix, $class, $len) !== 0) {
		// no, move to the next registered autoloader
		return;
	}

	// get the relative class name
	$className = substr($class, $len);

	// replace the namespace prefix with the base directory, replace namespace
	// separators with directory separators in the relative class name, append
	// with .php
	$file = $baseDir . str_replace("\\", "/", $className) . ".php";

	// if the file exists, require it
	if(file_exists($file)) {
		require_once($file);
	}
});

<?php
/**
 * PSR-4 Compliant Autoloader
 *
 * This will dynamically load classes by resolving the prefix and class name. This is the method that
 * frameworks such as Laravel and Composer automatically resolve class names and load them. To use it,
 * simply set the configurable parameters inside the closure. This example is taken from PHP-FIG,
 * referenced below.
 *
 * @param string $class fully qualified class name to load
 * @see http://www.php-fig.org/psr/psr-4/examples/ PSR-4 Example Autoloader
 **/
spl_autoload_register(function($class) {
	/**
	 * CONFIGURABLE PARAMETERS
	 * prefix: the prefix for all the classes (i.e., the namespace)
	 * baseDir: the base directory for all classes (default = current directory)
	 **/
	$prefix = "PetRescueAbq\\Http\\Petfoster";
	$baseDir = __DIR__;

	// does the class use the namespace prefix?
	$len = strlen($prefix);
	if (strncmp($prefix, $class, $len) !== 0) {
		// no, move to the next registered autoloader
		return;
	}

	// get the relative class name
	$className = substr($class, $len);

	// replace the namespace prefix with the base directory, replace namespace
	// separators with directory separators in the relative class name, append
	// with .php
	$file = $baseDir . str_replace("\\", "/", $className) . ".php";

	// if the file exists, require it
	if(file_exists($file)) {
		require_once($file);
	}
});

Test Driven Development Unit Test code CONTD

https://app.asana.com/0/334403035277160/335518406456410


<?php

return [

    //what authentication method to use 'direct', 'oauth2'. Currently only support 'direct'
    'auth_type' => 'direct',

    'direct' => [
        'username'  => env('GOTO_DIRECT_USER', 'user.account@test.com'),
        'password'  => env('GOTO_CONSUMER_SECRET', 'someSecret'),
        'client_id' => env('GOTO_CONSUMER_KEY', 'someConsumerKey'),
    ],

];

<?php

return [

    //what authentication method to use 'direct', 'oauth2'. Currently only support 'direct'
    'auth_type' => 'direct',

    'direct' => [
        'username'  => env('GOTO_DIRECT_USER', 'user.account@test.com'),
        'password'  => env('GOTO_CONSUMER_SECRET', 'someSecret'),
        'client_id' => env('GOTO_CONSUMER_KEY', 'someConsumerKey'),
        'client_secret' => env('GOTO_CLIENT_SECRET', 'someConsumerSecret')
    ],
];

Add new client secret option for config for oAuth2


<?php

namespace Auth0\Login\Repository;

use Auth0\Login\Auth0User;
use Auth0\Login\Auth0JWTUser;
use Auth0\Login\Contract\Auth0UserRepository as Auth0UserRepositoryContract;
use Illuminate\Contracts\Auth\Authenticatable;

class Auth0UserRepository implements Auth0UserRepositoryContract
{
    /**
     * @param array $decodedJwt
     *
     * @return Auth0JWTUser
     */
    public function getUserByDecodedJWT(array $decodedJwt) : Authenticatable
    {
        return new Auth0JWTUser($decodedJwt);
    }

    /**
     * @param array $userInfo
     *
     * @return Auth0User
     */
    public function getUserByUserInfo(array $userInfo) : Authenticatable
    {
        return new Auth0User($userInfo['profile'], $userInfo['accessToken']);
    }

    /**
     * @param string|int|null $identifier
     *
     * @return Authenticatable|null
     */
    public function getUserByIdentifier($identifier) : ?Authenticatable
    {
        // Get the user info of the user logged in (probably in session)
        $user = \App::make('auth0')->getUser();

        if ($user === null) {
            return null;
        }

        // Build the user
        $auth0User = $this->getUserByUserInfo($user);

        // It is not the same user as logged in, it is not valid
        if ($auth0User && $auth0User->getAuthIdentifier() == $identifier) {
            return $auth0User;
        }
    }
}

<?php

namespace Auth0\Login\Repository;

use Auth0\Login\Auth0User;
use Auth0\Login\Auth0JWTUser;
use Auth0\Login\Contract\Auth0UserRepository as Auth0UserRepositoryContract;
use Illuminate\Contracts\Auth\Authenticatable;

class Auth0UserRepository implements Auth0UserRepositoryContract
{
    /**
     * @param array $decodedJwt
     *
     * @return Auth0JWTUser
     */
    public function getUserByDecodedJWT(array $decodedJwt) : Authenticatable
    {
        return new Auth0JWTUser($decodedJwt);
    }

    /**
     * @param array $userInfo
     *
     * @return Auth0User
     */
    public function getUserByUserInfo(array $userInfo) : Authenticatable
    {
        return new Auth0User($userInfo['profile'], $userInfo['accessToken']);
    }

    /**
     * @param string|int|null $identifier
     *
     * @return Authenticatable|null
     */
    public function getUserByIdentifier($identifier) : ?Authenticatable
    {
        // Get the user info of the user logged in (probably in session)
        $user = \App::make('auth0')->getUser();

        if ($user === null) {
            return null;
        }

        // Build the user
        $auth0User = $this->getUserByUserInfo($user);

        // It is not the same user as logged in, it is not valid
        if ($auth0User && $auth0User->getAuthIdentifier() == $identifier) {
            return $auth0User;
        }

        return null;
    }
}

Fix missing return statement in getUserByIdentifier


<?php

namespace ScottRobertson\Scrutiny;

class Client
{
    private $services = array();
    private $reporters = array();

    public function addService($service)
    {
        $this->services[] = $service;
    }

    public function addReporter($reporter)
    {
        $this->reporters[] = $reporter;
    }

    public function getServices()
    {
        return $this->services;
    }

    public function getReporters()
    {
        return $this->reporters;
    }

    public function watch($global_interval = 20)
    {
        while (true) {
            foreach ($this->services as $service) {
                if ($service->checkable()) {
                    $this->report($service->getStatus());
                }
            }

            sleep($global_interval);
        }
    }

    public function report(\ScottRobertson\Scrutiny\Service\Base $service)
    {
        foreach ($this->reporters as $report) {
            if ($report->subscribed($service->getEvent())) {
                $report->report($service, $this->hostname);
            }
        }
    }
}

<?php

namespace ScottRobertson\Scrutiny;

class Client
{
    private $services = array();
    private $reporters = array();

    public function addService($service)
    {
        if (! method_exists($service, 'getStatus')) {
            throw new \Exception('Method: getStatus() does not exist');
        }

        $this->services[] = $service;
    }

    public function addReporter($reporter)
    {
        if (! method_exists($reporter, 'report')) {
            throw new \Exception('Method: report() does not exist');
        }

        $this->reporters[] = $reporter;
    }

    public function getServices()
    {
        return $this->services;
    }

    public function getReporters()
    {
        return $this->reporters;
    }

    public function watch($global_interval = 20)
    {
        while (true) {
            foreach ($this->services as $service) {
                if ($service->checkable()) {
                    $this->report($service->getStatus());
                }
            }

            sleep($global_interval);
        }
    }

    public function report(\ScottRobertson\Scrutiny\Service\Base $service)
    {
        foreach ($this->reporters as $report) {
            if ($report->subscribed($service->getEvent())) {
                $report->report($service, $this->hostname);
            }
        }
    }
}

Add checks to make sure services and reporters are valid


<?php

/*
 * This file is part of Laravel Vimeo.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vinkla\Tests\Vimeo;

use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test case class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return 'Vinkla\Vimeo\VimeoServiceProvider';
    }
}

<?php

/*
 * This file is part of Laravel Vimeo.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Vinkla\Tests\Vimeo;

use GrahamCampbell\TestBench\AbstractPackageTestCase;

/**
 * This is the abstract test case class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
abstract class AbstractTestCase extends AbstractPackageTestCase
{
    /**
     * Get the service provider class.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return string
     */
    protected function getServiceProviderClass($app)
    {
        return 'Vinkla\Vimeo\VimeoServiceProvider';
    }
}

Make abstract test case class abstract

Make abstract test case class abstract


<?php
/**
 * Cleans up old entries in tblActivation
 */

define('MAX_LIFETIME', 30);	//delete entries older than 30 days

require_once('/home/ml/dev/pc/config.php');	//FIXME: no hardcoded path

$q = 'DELETE FROM tblActivation WHERE timeCreated <= DATE_SUB(NOW(),INTERVAL '.MAX_LIFETIME.' DAY)';
$db->delete($q);

?>

<?php
/**
 * Cleans up old entries in tblActivation
 */

define('MAX_LIFETIME', 30);	//delete entries older than 30 days

require_once('find_config.php');

$q = 'DELETE FROM tblActivation WHERE timeCreated <= DATE_SUB(NOW(),INTERVAL '.MAX_LIFETIME.' DAY)';
$db->delete($q);

?>

Fix the other script in the cron dir

Fix the other script in the cron dir


<?php

require_once('../_include.php');

try {

	$config = SimpleSAML_Configuration::getInstance();
	$session = SimpleSAML_Session::getInstance();

	/* Make sure that the user has admin access rights. */
	if (!isset($session) || !$session->isValid('login-admin') ) {
		SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
		                               array('RelayState' => SimpleSAML_Utilities::selfURL())
		                               );
	}

	$stats = SimpleSAML_MemcacheStore::getStats();

	$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
	$template->data['title'] = 'Memcache stats';
	$template->data['table'] = $stats;
	$template->show();

} catch(Exception $e) {
	SimpleSAML_Utilities::fatalError('na', NULL, $e);
}

?>

<?php

require_once('../_include.php');

try {

	$config = SimpleSAML_Configuration::getInstance();
	$session = SimpleSAML_Session::getInstance();

	/* Make sure that the user has admin access rights. */
	if (!isset($session) || !$session->isValid('login-admin') ) {
		SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
		                               array('RelayState' => SimpleSAML_Utilities::selfURL())
		                               );
	}

	$stats = SimpleSAML_Memcache::getStats();

	$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
	$template->data['title'] = 'Memcache stats';
	$template->data['table'] = $stats;
	$template->show();

} catch(Exception $e) {
	SimpleSAML_Utilities::fatalError('na', NULL, $e);
}

?>

Fix Memcachestat. Using wrong classname

Fix Memcachestat. Using wrong classname


<?php

namespace WP_CLI\Fetchers;

/**
 * Fetch a WordPress plugin based on one of its attributes.
 */
class Plugin extends Base {

	/**
	 * @var string $msg Error message to use when invalid data is provided
	 */
	protected $msg = "The '%s' plugin could not be found.";

	/**
	 * Get a plugin object by name
	 *
	 * @param string $name
	 * @return object|false
	 */
	public function get( $name ) {
		foreach ( get_plugins() as $file => $_ ) {
			if ( $file === "$name.php" ||
				( dirname( $file ) === $name && $name !== '.' ) ) {
				return (object) compact( 'name', 'file' );
			}
		}

		return false;
	}
}

<?php

namespace WP_CLI\Fetchers;

/**
 * Fetch a WordPress plugin based on one of its attributes.
 */
class Plugin extends Base {

	/**
	 * @var string $msg Error message to use when invalid data is provided
	 */
	protected $msg = "The '%s' plugin could not be found.";

	/**
	 * Get a plugin object by name
	 *
	 * @param string $name
	 * @return object|false
	 */
	public function get( $name ) {
		foreach ( get_plugins() as $file => $_ ) {
			if ( $file === "$name.php" ||
				( $name && $file === $name ) ||
				( dirname( $file ) === $name && $name !== '.' ) ) {
				return (object) compact( 'name', 'file' );
			}
		}

		return false;
	}
}

Update plugin fetcher to match on full path

WordPress stores dirname/filename.php in the database, so this is a
valid name to use


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Core\Plugin;

/**
 * Additional bootstrapping and configuration for CLI environments should
 * be put here.
 */

// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');

try {
    Plugin::load('Bake');
} catch (MissingPluginException $e) {
    // Do not halt if the plugin is missing
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Core\Plugin;

/**
 * Additional bootstrapping and configuration for CLI environments should
 * be put here.
 */

// Set the fullBaseUrl to some doubtful/useful default as it cannot be known
// from e.g. $_SERVER['HOST_NAME'] with no webserver involved (cli-sapi).
// This is especially very usefull when sending email from the shell.
//Configure::write('App.fullBaseUrl', php_uname('n'));

// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');

try {
    Plugin::load('Bake');
} catch (MissingPluginException $e) {
    // Do not halt if the plugin is missing
}

Add hint for fullBaseUrl in CLI environments

Whenever a URL is generated from within a shell context, the fullBaseUrl cannot be known (automatically), like from the $_SERVER['HOST_NAME'],
which leads to problems when e.g. sending emails...
The information and documentation on how to "fix" this is hard to find and hinting in the configuration file for this specific case seems reasonable.


<?php

final class PhabricatorRemarkupBlockInterpreterGraphviz
  extends PhutilRemarkupBlockInterpreter {

  public function getInterpreterName() {
    return 'dot';
  }

  public function markupContent($content, array $argv) {
    if (!Filesystem::binaryExists('dot')) {
      return $this->markupError(
        pht('Unable to locate the `dot` binary. Install Graphviz.'));
    }

    $future = id(new ExecFuture('dot -T%s', 'png'))
      ->setTimeout(15)
      ->write(trim($content));

    list($err, $stdout, $stderr) = $future->resolve();

    if ($err) {
      return $this->markupError(
        pht(
          'Execution of `dot` failed (#%d), check your syntax: %s',
          $err,
          $stderr));
    }

    $file = PhabricatorFile::buildFromFileDataOrHash(
      $stdout,
      array(
        'name' => 'graphviz.png',
      ));

    if ($this->getEngine()->isTextMode()) {
      return '<'.$file->getBestURI().'>';
    }

    return phutil_tag(
      'img',
      array(
        'src' => $file->getBestURI(),
      ));
  }

}

<?php

final class PhabricatorRemarkupBlockInterpreterGraphviz
  extends PhutilRemarkupBlockInterpreter {

  public function getInterpreterName() {
    return 'dot';
  }

  public function markupContent($content, array $argv) {
    if (!Filesystem::binaryExists('dot')) {
      return $this->markupError(
        pht('Unable to locate the `dot` binary. Install Graphviz.'));
    }

    $width = $this->parseDimension(idx($argv, 'width'));

    $future = id(new ExecFuture('dot -T%s', 'png'))
      ->setTimeout(15)
      ->write(trim($content));

    list($err, $stdout, $stderr) = $future->resolve();

    if ($err) {
      return $this->markupError(
        pht(
          'Execution of `dot` failed (#%d), check your syntax: %s',
          $err,
          $stderr));
    }

    $file = PhabricatorFile::buildFromFileDataOrHash(
      $stdout,
      array(
        'name' => 'graphviz.png',
      ));

    if ($this->getEngine()->isTextMode()) {
      return '<'.$file->getBestURI().'>';
    }

    return phutil_tag(
      'img',
      array(
        'src' => $file->getBestURI(),
        'width' => nonempty($width, null),
      ));
  }

  // TODO: This is duplicated from PhabricatorRemarkupRuleEmbedFile since they
  // do not share a base class.
  private function parseDimension($string) {
    $string = trim($string);

    if (preg_match('/^(?:\d*\\.)?\d+%?$/', $string)) {
      return $string;
    }

    return null;
  }
}

Add ability to pass `width` arg to dot remarkup interpeter

Summary:
Allows to keep really wide graphs inside the div:

  dot (width=100%) {{{ }}}

Test Plan:
Created a graph that is wider than a phriction page.
Added `(width=100%)` and now the images stays within the div.

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley

CC: Korvin, epriestley, aran

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


<?php
$GLOBALS['email'] = array(
    'email' => 'no-reply@tadhg.sh',
    'username' => 'theepicgamers28@gmail.com',
    'password' => 'ettettett',
    'name' => 'NamelessMC',
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'secure' => 'tls',
    'smtp_auth' => true
);

<?php
$GLOBALS['email'] = [
    'email' => '',
    'username' => '',
    'password' => '',
    'name' => '',
    'host' => '',
    'port' => 587,
    'secure' => 'tls',
    'smtp_auth' => true,
];

Remove API key from URL in StaffCP

Remove API key from URL in StaffCP


Recent Activity

	<fb:activity site="felixonline.co.uk" app_id="200482590030408" action="like" width="300" height="300" header="false" border_color="#BEBEBE" font="arial" recommendations="false"></fb:activity>

Correct facebook social feed box

Correct facebook social feed box


            Time
            Event Title

        <?php
        foreach ($context as $eventinstance) {
            //Start building an array of row classes
            $row_classes = array('vevent');

            if ($eventinstance->isAllDay()) {
                $row_classes[] = 'all-day';
            }

            if ($eventinstance->isInProgress()) {
                $row_classes[] = 'in-progress';
            }

            if ($eventinstance->isOnGoing()) {
                $row_classes[] = 'ongoing';
            }

            ?>
            <tr class="<?php echo implode(' ', $row_classes) ?>">

                    <?php echo $savvy->render($eventinstance, 'EventInstance/Date.tpl.php') ?>

                    <?php echo $savvy->render($eventinstance, 'EventInstance/Summary.tpl.php') ?>
                    <?php echo $savvy->render($eventinstance, 'EventInstance/Location.tpl.php') ?>
                    <?php echo $savvy->render($eventinstance, 'EventInstance/Description.tpl.php') ?>

            <?php
        }
        ?>

        <?php
        foreach ($context as $eventinstance) {
            //Start building an array of row classes
            $row_classes = array('vevent');

            if ($eventinstance->isAllDay()) {
                $row_classes[] = 'all-day';
            }

            if ($eventinstance->isInProgress()) {
                $row_classes[] = 'in-progress';
            }

            if ($eventinstance->isOnGoing()) {
                $row_classes[] = 'ongoing';
            }

            ?>
            <div class="<?php echo implode(' ', $row_classes) ?>">
                    <?php echo $savvy->render($eventinstance, 'EventInstance/Summary.tpl.php') ?>
                    <?php echo $savvy->render($eventinstance, 'EventInstance/Date.tpl.php') ?>
                    <?php echo $savvy->render($eventinstance, 'EventInstance/Location.tpl.php') ?>
                    <?php echo $savvy->render($eventinstance, 'EventInstance/Description.tpl.php') ?>

            <?php
        }
        ?>

Remove table markup for lists of events

Remove table markup for lists of events


<?php
namespace Neos\MarketPlace\TypoScriptObjects;

/*
 * This file is part of the Neos.MarketPlace package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Packagist\Api\Client;
use Packagist\Api\Result\Package;
use TYPO3\TypoScript\TypoScriptObjects\AbstractArrayTypoScriptObject;

/**
 * Package TypoScript Implementation
 *
 * @api
 */
class PackageImplementation extends AbstractArrayTypoScriptObject
{

    /**
     * @return string
     */
    public function getName()
    {
        return $this->tsValue('name');
    }

    /**
     * Evaluate this TypoScript object and return the result
     *
     * @return mixed
     */
    public function evaluate()
    {
        $client = new Client();
        return $client->get($this->getName());
    }
}

<?php
namespace Neos\MarketPlace\TypoScriptObjects;

/*
 * This file is part of the Neos.MarketPlace package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use TYPO3\Flow\Annotations as Flow;
use Packagist\Api\Client;
use Packagist\Api\Result\Package;
use TYPO3\Flow\Log\SystemLoggerInterface;
use TYPO3\TypoScript\TypoScriptObjects\AbstractArrayTypoScriptObject;

/**
 * Package TypoScript Implementation
 *
 * @api
 */
class PackageImplementation extends AbstractArrayTypoScriptObject
{
    /**
     * @var SystemLoggerInterface
     * @Flow\Inject
     */
    protected $systemLogger;

    /**
     * @return string
     */
    public function getName()
    {
        return $this->tsValue('name');
    }

    /**
     * Evaluate this TypoScript object and return the result
     *
     * @return Package|null
     */
    public function evaluate()
    {
        try {
            $client = new Client();
            return $client->get($this->getName());
        } catch (\Exception $exception) {
            $this->systemLogger->logException($exception);
            return null;
        }
    }
}

TASK: Package TS implement must return null on exception


<?php

if (!function_exists('array_except_value')) {
    function array_except_value(array $array, $value)
    {
        if (!is_array($value)) {
            $value = [$value];
        }

        foreach ($value as $item) {
            while (($key = array_search($item, $array, true)) !== false) {
                unset($array[$key]);
            }
        }

        return $array;
    }
}

if (!function_exists('multiarray_set')) {
    function multiarray_set(array &$multiarray, $key, $value)
    {
        foreach ($multiarray as &$array) {
            array_set($array, $key, $value);
        }

        return $multiarray;
    }
}

if (!function_exists('multiarray_sort_by')) {
    function multiarray_sort_by(array $multiarray, $field1 = null, $sort1 = null, $_ = null)
    {
        $arguments = func_get_args();

        $multiarray = array_shift($arguments);
        foreach ($arguments as $key => $value) {
            if (is_string($value)) {
                $arguments[$key] = array_pluck($multiarray, $value);
            }
        }
        $arguments[] = &$multiarray;
        call_user_func_array('array_multisort', $arguments);

        return array_pop($arguments);
    }
}

<?php

use Illuminate\Support\Arr;

if (!function_exists('array_except_value')) {
    function array_except_value(array $array, $value)
    {
        if (!is_array($value)) {
            $value = [$value];
        }

        foreach ($value as $item) {
            while (($key = array_search($item, $array, true)) !== false) {
                unset($array[$key]);
            }
        }

        return $array;
    }
}

if (!function_exists('multiarray_set')) {
    function multiarray_set(array &$multiarray, $key, $value)
    {
        foreach ($multiarray as &$array) {
            Arr::set($array, $key, $value);
        }

        return $multiarray;
    }
}

if (!function_exists('multiarray_sort_by')) {
    function multiarray_sort_by(array $multiarray, $field1 = null, $sort1 = null, $_ = null)
    {
        $arguments = func_get_args();

        $multiarray = array_shift($arguments);
        foreach ($arguments as $key => $value) {
            if (is_string($value)) {
                $arguments[$key] = Arr::pluck($multiarray, $value);
            }
        }
        $arguments[] = &$multiarray;
        call_user_func_array('array_multisort', $arguments);

        return array_pop($arguments);
    }
}

Remove usages of the deprecated helpers

Remove usages of the deprecated helpers


<?php

namespace Rx\Notification;

use Rx\ObserverInterface;
use Rx\Notification;

class OnNextNotification extends Notification
{
    private $value;

    public function __construct($value)
    {
        parent::__construct('N', true);

        $this->value = $value;
    }

    protected function doAcceptObservable(ObserverInterface $observer)
    {
        $observer->onNext($this->value);
    }

    protected function doAccept($onNext, $onError, $onCompleted)
    {
        $onNext($this->value);
    }

    public function __toString()
    {
        return 'OnNext(' . json_encode($this->value) . ')';
    }
}

<?php

namespace Rx\Notification;

use Rx\ObserverInterface;
use Rx\Notification;

class OnNextNotification extends Notification
{
    private $value;

    public function __construct($value)
    {
        parent::__construct('N', true);

        $this->value = $value;
    }

    protected function doAcceptObservable(ObserverInterface $observer)
    {
        $observer->onNext($this->value);
    }

    protected function doAccept($onNext, $onError, $onCompleted)
    {
        $onNext($this->value);
    }

    public function __toString()
    {
        return 'OnNext(' . json_encode($this->value) . ')';
    }

    public function getValue() {
        return $this->value;
    }
}

Allow getting value from OnNextNorification


<?php

namespace App\Form\Field;

class File extends \AzuraForms\Field\File
{
    public function configure(array $config = []): void
    {
        parent::configure($config);

        $this->options['button_text'] = $this->attributes['button_text'] ?? __('Select File');
        $this->options['button_icon'] = $this->attributes['button_icon'] ?? null;
    }

    public function getField($form_name): ?string
    {
        list($attribute_string, $class) = $this->_attributeString();

        $button_text = $this->options['button_text'];

        if ($this->options['button_icon'] !== null) {
            $button_text .= sprintf(' %1$s', $this->options['button_icon']);
        }

        $output = '<button name="%1$s_button" id="%2$s_%1$s_button" class="file-upload btn btn-primary btn-block text-center %3$s" type="button">';
        $output .= '%4$s';
        $output .= '</button>';
        $output .= '';
        $output .= '<input type="file" name="%1$s" id="%2$s_%1$s" style="visibility: hidden; position: absolute;">';

        return sprintf($output,
            $this->getFullName(),
            $form_name,
            $class,
            $button_text
        );
    }
}

<?php

namespace App\Form\Field;

class File extends \AzuraForms\Field\File
{
    public function configure(array $config = []): void
    {
        parent::configure($config);

        $this->options['button_text'] = $this->attributes['button_text'] ?? __('Select File');
        $this->options['button_icon'] = $this->attributes['button_icon'] ?? null;
    }

    public function getField($form_name): ?string
    {
        list($attribute_string, $class) = $this->_attributeString();

        $button_text = $this->options['button_text'];

        if ($this->options['button_icon'] !== null) {
            $button_text .= sprintf(' %1$s', $this->options['button_icon']);
        }

        $output = '<button name="%1$s_button" id="%2$s_%1$s_button" class="file-upload btn btn-primary btn-block text-center %3$s" type="button">';
        $output .= '%4$s';
        $output .= '</button>';
        $output .= '';
        $output .= '<input type="file" name="%1$s" id="%2$s_%1$s" style="visibility: hidden; position: absolute; left: -9999px;">';

        return sprintf($output,
            $this->getFullName(),
            $form_name,
            $class,
            $button_text
        );
    }
}

Add negative positioning to hidden file input


<?php

global $amp_conf;
$location = $amp_conf['AMPWEBROOT'].'/ucp';
if(!file_exists($location)) {
	symlink(dirname(__FILE__).'/htdocs',$location);
}

$links = array('js','css','fonts','images');
foreach($links as $link) {
	if(!file_exists(dirname(__FILE__).'/htdocs/global/assets/'.$link)) {
		symlink($amp_conf['AMPWEBROOT'].'/admin/assets/'.$link,dirname(__FILE__).'/htdocs/global/assets/'.$link);
	}
}

<?php

global $amp_conf;
$location = $amp_conf['AMPWEBROOT'].'/ucp';
if(!file_exists($location)) {
	symlink(dirname(__FILE__).'/htdocs',$location);
}

if(!file_exists(dirname(__FILE__).'/htdocs/global/assets')) {
	mkdir(dirname(__FILE__).'/htdocs/global/assets');
}

$links = array('js','css','fonts','images');
foreach($links as $link) {
	if(!file_exists(dirname(__FILE__).'/htdocs/global/assets/'.$link)) {
		symlink($amp_conf['AMPWEBROOT'].'/admin/assets/'.$link,dirname(__FILE__).'/htdocs/global/assets/'.$link);
	}
}

Create the assets folder though

Create the assets folder though


<?php
/**
 * A SessionInterface
 *
 * @link        https://github.com/pavlakis/session
 * @copyright   Copyright © 2016 Antonis Pavlakis
 * @author      Antonis Pavlakis (@pavlakis)
 * @license     https://github.com/pavlakis/session/blob/master/LICENSE (MIT License)
 */
namespace Pavlakis\Http\SessionInterface;

interface SessionInterface
{

    /**
     * @return SessionInterface
     */
    public function start();

    /**
     * @return void
     */
    public function destroy();

    /**
     * @param bool $deleteOldSession
     * @return bool
     */
    public function regenerate($deleteOldSession = false);

    /**
     * @return bool
     */
    public static function isStarted();

    /**
     * @param string $name
     * @param $value
     * @return mixed
     */
    public function set($name, $value);

    /**
     * @param $name
     * @param mixed $default
     * @return mixed
     */
    public function get($name, $default = null);

    /**
     * @param $name
     * @return bool
     */
    public function has($name);

    /**
     * @return array
     */
    public function getSessionArray();
}

<?php
/**
 * A SessionInterface
 *
 * @link        https://github.com/pavlakis/session
 * @copyright   Copyright © 2016 Antonis Pavlakis
 * @author      Antonis Pavlakis (@pavlakis)
 * @license     https://github.com/pavlakis/session/blob/master/LICENSE (MIT License)
 */
namespace Pavlakis\Http\SessionInterface;

interface SessionInterface
{

    /**
     * @return SessionInterface
     */
    public function start();

    /**
     * @return void
     */
    public function destroy();

    /**
     * @param bool $deleteOldSession
     * @return bool
     */
    public function regenerate($deleteOldSession = false);

    /**
     * @return bool
     */
    public static function isStarted();

    /**
     * @param string $name
     * @param $value
     * @return mixed
     */
    public function set($name, $value);

    /**
     * @param $name
     * @param mixed $default
     * @return mixed
     */
    public function get($name, $default = null);

    /**
     * @param $name
     * @return void
     */
    public function remove($name);

    /**
     * @param $name
     * @return bool
     */
    public function has($name);

    /**
     * @return array
     */
    public function getSessionArray();
}

Add remove method to remove attribute from session


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Authentication Model
	|--------------------------------------------------------------------------
	|
	| This model will be used by the Auth class when retrieving the users of
	| your application. Feel free to change it to the name of your user model.
	|
	| Note: The authentication model must be an Eloquent model.
	|
	*/

	'model' => 'User',

	/*
	|--------------------------------------------------------------------------
	| Authentication Username
	|--------------------------------------------------------------------------
	|
	| The authentication username is the column on your users table that
	| is considered the username of the user. Typically, this is either "email"
	| or "username". However, you are free to make it whatever you wish.
	|
	*/

	'username' => 'email',

);

<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Retrieve Users By ID
	|--------------------------------------------------------------------------
	|
	| This method is called by the Auth::user() method when attempting to load
	| a user by their user ID.
	|
	| You are free to change this method for your application however you wish.
	|
	*/

	'by_id' => function($id)
	{
		return User::find($id);
	},

	/*
	|--------------------------------------------------------------------------
	| Retrieve Users By Username
	|--------------------------------------------------------------------------
	|
	| This method is called by the Auth::check() method when attempting to load
	| a user by their username.
	|
	| You are free to change this method for your application however you wish,
	| as long as you return an object that has "id" and "password" properties.
	|
	*/

	'by_username' => function($username)
	{
		return User::where('email', '=', $username)->first();
	},

);

Refactor Auth config to use closures.

Refactor Auth config to use closures.


<?php

namespace Kunstmaan\VotingBundle\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Kunstmaan\VotingBundle\Entity\AbstractVote;
use Kunstmaan\VotingBundle\Event\EventInterface;

abstract class AbstractVoteListener
{
    /**
     * @var EntityManagerInterface
     */
    protected $em;

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

    /**
     * @param EntityManagerInterface $em
     * @param array                  $actions
     */
    public function __construct(EntityManagerInterface $em, array $actions = array())
    {
        $this->em = $em;
        $this->actions = $actions;
    }

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

    /**
     * @param AbstractVote   $vote
     * @param EventInterface $event
     * @param null|int       $defaultValue
     */
    protected function createVote(AbstractVote $vote, EventInterface $event, $defaultValue = null)
    {
        $vote->setReference($event->getReference());
        if ($event->getRequest() !== null) {
            $vote->setIp($event->getRequest()->getClientIp());
        }
        if ($event->getValue() !== null) {
            $vote->setValue($event->getValue());
        } elseif ($defaultValue !== null) {
            $vote->setValue($defaultValue);
        }

        $this->em->persist($vote);
        $this->em->flush();
    }
}

<?php

namespace Kunstmaan\VotingBundle\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Kunstmaan\VotingBundle\Entity\AbstractVote;
use Kunstmaan\VotingBundle\Event\EventInterface;

abstract class AbstractVoteListener
{
    /**
     * @var EntityManagerInterface
     */
    protected $em;

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

    /**
     * @param EntityManagerInterface $em
     * @param array                  $actions
     */
    public function __construct(EntityManagerInterface $em, array $actions = array())
    {
        $this->em = $em;
        $this->actions = $actions;
    }

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

    /**
     * @param AbstractVote   $vote
     * @param EventInterface $event
     * @param int|null       $defaultValue
     */
    protected function createVote(AbstractVote $vote, EventInterface $event, $defaultValue = null)
    {
        $vote->setReference($event->getReference());
        if ($event->getRequest() !== null) {
            $vote->setIp($event->getRequest()->getClientIp());
        }
        if ($event->getValue() !== null) {
            $vote->setValue($event->getValue());
        } elseif ($defaultValue !== null) {
            $vote->setValue($defaultValue);
        }

        $this->em->persist($vote);
        $this->em->flush();
    }
}

Apply new symfony preset fixer "phpdoc_types_null_last"


<?php

/*
 * This file is part of the ICanBoogie package.
 *
 * (c) Olivier Laviale <olivier.laviale@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ICanBoogie;

/*
 * URL rewriting functionality for the built-in PHP web server.
 */
if (PHP_SAPI === 'cli-server')
{
	$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

	if ($uri !== '/' && file_exists(__DIR__ . $uri))
	{
		return false;
	}

	unset($uri);
}

/*
 * Obtain the booted application and run it.
 */
$app = require __DIR__ . '/../app/bootstrap.php';
$app();

<?php

/*
 * This file is part of the ICanBoogie package.
 *
 * (c) Olivier Laviale <olivier.laviale@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ICanBoogie;

chdir(dirname(__DIR__));

/*
 * URL rewriting functionality for the built-in PHP web server.
 */
if (PHP_SAPI === 'cli-server')
{
	$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

	if ($uri !== '/' && file_exists(__DIR__ . $uri))
	{
		return false;
	}

	unset($uri);
}

/*
 * Obtain the booted application and run it.
 */
$app = require __DIR__ . '/../app/bootstrap.php';
$app();

Change working directory to app directory


<?php

namespace Gregoriohc\Preview;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

class PreviewServiceProvider extends LaravelServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->handleConfigs();

        if (!$this->app->routesAreCached() && $this->isEnabled()) {
            Route::get('_preview/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    }

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

    private function handleConfigs()
    {
        $configPath = __DIR__.'/../config/preview.php';

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

        $this->mergeConfigFrom($configPath, 'preview');
    }

    public static function isEnabled()
    {
        return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
    }
}

<?php

namespace Gregoriohc\Preview;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

class PreviewServiceProvider extends LaravelServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->handleConfigs();

        if (!$this->app->routesAreCached() && $this->isEnabled()) {
            Route::group(['middleware' => ['web']], function () {
                Route::get('_preview/{view}', '\Gregoriohc\Preview\Controller@show')->name('_preview.show');
            });
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    }

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

    private function handleConfigs()
    {
        $configPath = __DIR__.'/../config/preview.php';

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

        $this->mergeConfigFrom($configPath, 'preview');
    }

    public static function isEnabled()
    {
        return (config('app.debug') && 'local' === config('app.env')) || config('preview.force_enable');
    }
}

Add web middleware to route

Add web middleware to route


<?php

namespace ShootProof\Cli\Utility;

class ShootproofFile
{
    public $id = '';
    public $name = '';
    public $url = [];

    public function arrayFactory(array $data)
    {
        extract($data);
        return new self($name, $id, $url);
    }

    public function stringFactory($name)
    {
        return new self($name);
    }

    public function __construct($name = '', $id = '', $url = [])
    {
        $this->name = $name;
        $this->id = $id;
        $this->url = $url;
    }

    public function __toString()
    {
        return (string) $this->name;
    }
}

<?php

namespace ShootProof\Cli\Utility;

class ShootproofFile
{
    public $id = '';
    public $name = '';
    public $url = [];

    public function __construct($name = '', $id = '', $url = [])
    {
        $this->name = $name;
        $this->id = $id;
        $this->url = $url;
    }

    public function __toString()
    {
        return (string) $this->name;
    }

    public function arrayFactory(array $data)
    {
        extract($data);
        return new self($name, $id, $url);
    }

    public function stringFactory($name)
    {
        return new self($name);
    }
}

Move constructor and magic method to top of methods


<?php

namespace Customizer;

abstract class Core {

	public function add_section( Section $section ) {

	}

	public function remove_section( Section $section ) {

	}

}

<?php

namespace Customizer;

abstract class Core {

	private $sections;

	public function add_section( Section $section ) {

	}

	public function remove_section( Section $section ) {

	}

}

Add sections instance variable to customizer core


Spencer and Jennifer recently purchased a townhouse in the Great Bridge area of Chesapeake.  The townhouse is an end unit with two bedrooms, two & half baths, brand new kitchen appliances, a deck, and a see-though fireplace!  Spencer will be moving into the new house on the 25th of January and Jennifer will join him in August after the wedding.  Since they became homeowners, they have been working on furnishing the house and they are well on their way to calling it a home.

Make it a paragraph so it gets justified.


<?php
/**
 * Graph extension Hooks
 *
 * @file
 * @ingroup Extensions
 */

namespace Graph;

use ResourceLoader;

class Hooks {
	/**
	 * Conditionally register the unit testing module for the ext.graph.visualEditor module
	 * only if that module is loaded
	 *
	 * @param array $testModules The array of registered test modules
	 * @param ResourceLoader $resourceLoader The reference to the resource loader
	 * @return bool
	 */
	public static function onResourceLoaderTestModules( array &$testModules, ResourceLoader &$resourceLoader ) {
		$resourceModules = $resourceLoader->getConfig()->get( 'ResourceModules' );

		if ( isset( $resourceModules[ 'ext.graph.visualEditor' ] ) || $resourceLoader->isModuleRegistered( 'ext.graph.visualEditor' ) ) {
			$testModules['qunit']['ext.graph.visualEditor.test'] = array(
				'scripts' => array(
					'modules/ve-graph/tests/ext.graph.visualEditor.test.js'
				),
				'dependencies' => array(
					'ext.graph.visualEditor',
					'ext.graph.vega1',
					'ext.visualEditor.test'
				),
				'localBasePath' => dirname( __DIR__ ),
				'remoteExtPath' => 'Graph'
			);
		}

		return true;
	}
}

<?php
/**
 * Graph extension Hooks
 *
 * @file
 * @ingroup Extensions
 */

namespace Graph;

use ResourceLoader;

class Hooks {
	/**
	 * Conditionally register the unit testing module for the ext.graph.visualEditor module
	 * only if that module is loaded
	 *
	 * @param array $testModules The array of registered test modules
	 * @param ResourceLoader $resourceLoader The reference to the resource loader
	 * @return bool
	 */
	public static function onResourceLoaderTestModules( array &$testModules, ResourceLoader &$resourceLoader ) {
		$resourceModules = $resourceLoader->getConfig()->get( 'ResourceModules' );

		if (
			isset( $resourceModules[ 'ext.visualEditor.mediawiki' ] ) ||
			$resourceLoader->isModuleRegistered( 'ext.visualEditor.mediawiki' )
		) {
			$testModules['qunit']['ext.graph.visualEditor.test'] = array(
				'scripts' => array(
					'modules/ve-graph/tests/ext.graph.visualEditor.test.js'
				),
				'dependencies' => array(
					'ext.graph.visualEditor',
					'ext.graph.vega1',
					'ext.visualEditor.test'
				),
				'localBasePath' => dirname( __DIR__ ),
				'remoteExtPath' => 'Graph'
			);
		}

		return true;
	}
}

Check VE is available before running unit tests

Bug: T127763
Change-Id: Ic5eef55c3327f95362e2f69fbebc86be306790f7


<?
class _ArrayObject implements ArrayAccess {

  function offsetExists ($key){ return isset($this->$key); }
  function offsetGet($key){ return $this->$key;}
  function offsetSet($key, $value){$this->$key = $value;}
  function offsetUnset($key){unset($this->$key); }

  public static function expose($obj){
    if(is_scalar($obj) || is_null($obj))
      return $obj;

    if(is_array($obj)) {
      $out = new self();
      foreach($obj as $k=>$v)
        $out->$k = call_user_func(__METHOD__, $v);
      return $out;
    }

    if(is_object($obj)) {
      $out = new self();
      $fx = new ReflectionObject($obj);
      foreach($fx->getProperties() as $property) {
          $property_name = $property->getName();
          $property->setAccessible(true);
          $out->$property_name = call_user_func(__METHOD__, $property->getValue($obj));
      }
      return $out ;
    }

    return null;

  }
}

<?
class _ArrayObject implements ArrayAccess {

  function offsetExists ($key){ return isset($this->$key); }
  function offsetGet($key){ return $this->$key;}
  function offsetSet($key, $value){$this->$key = $value;}
  function offsetUnset($key){unset($this->$key); }

  protected function __get($key){
    if(method_exists($this, $getter = "get_$key"))
        return $this->$getter();
  }

  public static function expose($obj){
    if(is_scalar($obj) || is_null($obj))
      return $obj;

    if(is_array($obj)) {
      $out = new self();
      foreach($obj as $k=>$v)
        $out->$k = call_user_func(__METHOD__, $v);
      return $out;
    }

    if(is_object($obj)) {
      $out = new self();
      $fx = new ReflectionObject($obj);
      foreach($fx->getProperties() as $property) {
          $property_name = $property->getName();
          $property->setAccessible(true);
          $out->$property_name = call_user_func(__METHOD__, $property->getValue($obj));
      }
      return $out ;
    }

    return null;

  }
}

Allow _get access in ArrayObject

Allow _get access in ArrayObject

git-svn-id: 4cd2d1688610a87757c9f4de95975a674329c79f@1807 b8ca103b-dd03-488c-9448-c80b36131af2