<?php
namespace Luracast\Restler\Format;

/**
 * Javascript Object Notation Packaged in a method (JSONP)
 *
 * @category   Framework
 * @package    Restler
 * @subpackage format
 * @author     R.Arul Kumaran <arul@luracast.com>
 * @copyright  2010 Luracast
 * @license    http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link       http://luracast.com/products/restler/
 * @version    3.0.0rc4
 */
class JsFormat extends JsonFormat
{
    const MIME = 'text/javascript';
    const EXTENSION = 'js';

    public static $callbackMethodName = 'parseResponse';
    public static $callbackOverrideQueryString = 'callback';
    public static $includeHeaders = true;

    public function encode($data, $human_readable = false)
    {
        $r = array();
        if (static::$includeHeaders) {
            $r['meta'] = array();
            foreach (headers_list() as $header) {
                list($h, $v) = explode(': ', $header, 2);
                $r['meta'][$h] = $v;
            }
        }
        $r['data'] = $data;
        if ($_GET[static::$callbackOverrideQueryString]) {
            static::$callbackMethodName
                = $_GET[static::$callbackOverrideQueryString];
        }
        return static::$callbackMethodName . '('
            . parent::encode($r, $human_readable) . ');';
    }
}

<?php
namespace Luracast\Restler\Format;

/**
 * Javascript Object Notation Packaged in a method (JSONP)
 *
 * @category   Framework
 * @package    Restler
 * @subpackage format
 * @author     R.Arul Kumaran <arul@luracast.com>
 * @copyright  2010 Luracast
 * @license    http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link       http://luracast.com/products/restler/
 * @version    3.0.0rc4
 */
class JsFormat extends JsonFormat
{
    const MIME = 'text/javascript';
    const EXTENSION = 'js';

    public static $callbackMethodName = 'parseResponse';
    public static $callbackOverrideQueryString = 'callback';
    public static $includeHeaders = true;

    public function encode($data, $human_readable = false)
    {
        $r = array();
        if (static::$includeHeaders) {
            $r['meta'] = array();
            foreach (headers_list() as $header) {
                list($h, $v) = explode(': ', $header, 2);
                $r['meta'][$h] = $v;
            }
        }
        $r['data'] = $data;
        if (isset($_GET[static::$callbackOverrideQueryString])) {
            static::$callbackMethodName
                = (string) $_GET[static::$callbackOverrideQueryString];
        }
        return static::$callbackMethodName . '('
            . parent::encode($r, $human_readable) . ');';
    }
}

Fix for php notice error

Fix for php notice error


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

namespace PH7\Test\Unit\Framework\Video\Api;

use PH7\Framework\Video\Api\Youtube;
use PHPUnit_Framework_TestCase;

class YoutubeTest extends PHPUnit_Framework_TestCase
{
    /** @var Youtube */
    private $oYoutube;

    protected function setUp()
    {
        $this->oYoutube = new Youtube;
    }

    public function testApiKeyIsSet()
    {
        $this->oYoutube->setKey('OIzaSyBu-916IsoKajomJNIgngS6HL_kDIKU0aU');
        $this->assertTrue($this->oYoutube->isApiKeySet());
    }

    public function testWrongApiKeySet()
    {
        $this->oYoutube->setKey('invalid_key');
        $this->assertFalse($this->oYoutube->isApiKeySet());
    }

    public function testApiKeyIsNotSet()
    {
        $this->assertFalse($this->oYoutube->isApiKeySet());
    }
}

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

namespace PH7\Test\Unit\Framework\Video\Api;

use PH7\Framework\Video\Api\Youtube;
use PHPUnit_Framework_TestCase;

class YoutubeTest extends PHPUnit_Framework_TestCase
{
    /** @var Youtube */
    private $oYoutube;

    protected function setUp()
    {
        $this->oYoutube = new Youtube;
    }

    public function testApiKeyIsSet()
    {
        $this->oYoutube->setKey('OIzaSyBu-916IsoKajomJNIgngS6HL_kDIKU0aU');
        $this->assertTrue($this->oYoutube->isApiKeySet());
    }

    public function testWrongApiKeySet()
    {
        $this->oYoutube->setKey('invalid');
        $this->assertFalse($this->oYoutube->isApiKeySet());
    }

    public function testApiKeyIsNotSet()
    {
        $this->assertFalse($this->oYoutube->isApiKeySet());
    }
}

Update Wrong API key test

Update Wrong API key test

Because now, the minimum key length is 10 chars


<?php

/**
 * Interface that collections must implement.
 *
 * PHP Version 5.3
 *
 * @copyright   (c) 2006-2014 brian ridley
 * @author      brian ridley <ptlis@ptlis.net>
 * @license     http://opensource.org/licenses/MIT MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ptlis\ConNeg\Collection;

use Countable;
use IteratorAggregate;
use Traversable;

/**
 * Interface that collections must implement.
 */
interface CollectionInterface extends Countable, IteratorAggregate
{
    /**
     * Set the internal store to the provided values.
     *
     * @param array $typePairList
     *
     * @return CollectionInterface
     */
    public function setList(array $typePairList);

    /**
     * Return count of elements.
     *
     * @link http://php.net/manual/en/countable.count.php
     *
     * @return int
     */
    public function count();

    /**
     * Retrieve an external iterator.
     *
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
     *
     * @return Traversable
     */
    public function getIterator();

    /**
     * Returns a new sorted collection.
     *
     * @return CollectionInterface with elements in ascending order
     */
    public function getAscending();

    /**
     * Returns a new sorted collection.
     *
     * @return CollectionInterface with elements in descending order
     */
    public function getDescending();
}

<?php

/**
 * Interface that collections must implement.
 *
 * PHP Version 5.3
 *
 * @copyright   (c) 2006-2014 brian ridley
 * @author      brian ridley <ptlis@ptlis.net>
 * @license     http://opensource.org/licenses/MIT MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ptlis\ConNeg\Collection;

use Countable;
use IteratorAggregate;
use Traversable;

/**
 * Interface that collections must implement.
 */
interface CollectionInterface extends Countable, IteratorAggregate
{
    /**
     * Set the internal store to the provided values.
     *
     * @param array $list
     *
     * @return CollectionInterface
     */
    public function setList(array $list);

    /**
     * Return count of elements.
     *
     * @link http://php.net/manual/en/countable.count.php
     *
     * @return int
     */
    public function count();

    /**
     * Retrieve an external iterator.
     *
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
     *
     * @return Traversable
     */
    public function getIterator();

    /**
     * Returns a new sorted collection.
     *
     * @return CollectionInterface with elements in ascending order
     */
    public function getAscending();

    /**
     * Returns a new sorted collection.
     *
     * @return CollectionInterface with elements in descending order
     */
    public function getDescending();
}

Rename parameter in interface to be more generic.


<?php

namespace Alegra;

class Item extends Resource
{
    /**
     * Transform attributes when receive the resource
     *
     * @var array
     */
    protected static $casts = [
        'category'  => Category::class,
        'price'     => Item\Price::class . '[]', // this is a collection of Price
        'tax'       => Tax::class . '[]', // this a collection of Tax
        'inventory' => Item\Inventory::class
    ];

    /**
     * Add ability for support metadata
     */
    use Support\Metadata;
}

<?php

namespace Alegra;

class Item extends Resource
{
    /**
     * Transform attributes when receive the resource
     *
     * @var array
     */
    protected $fillable = [
        'name'        => 'string',
        'description' => 'string',
        'reference'   => 'string',
        'status'      => 'string',
        'category'    => Category::class,
        'price'       => Item\Price::class . '[]', // this is a collection of Price
        'tax'         => Tax::class . '[]', // this a collection of Tax
        'inventory'   => Item\Inventory::class
    ];

    /**
     * Add ability for support metadata
     */
    use Support\Metadata;
}

Add fillable property to item resource.

Add fillable property to item resource.


<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

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

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

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

}

<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends \Neonbug\Common\Exceptions\Handler {

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

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

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

}

Fix for PHP 7 exceptions (throwables)

Fix for PHP 7 exceptions (throwables)


<?php

namespace Kibo\Phast\Filters\HTML\Composite;

use Kibo\Phast\Environment\Package;
use Kibo\Phast\ValueObjects\URL;

class Factory {

    public function make(array $config) {
        $composite = new Filter(URL::fromString($config['documents']['baseUrl']), $config['outputServerSideStats']);
        foreach (array_keys($config['documents']['filters']) as $class) {
            $package = Package::fromPackageClass($class);
            if ($package->hasFactory()) {
                $filter = $package->getFactory()->make($config);
            } else {
                $filter = new $class();
            }
            $composite->addHTMLFilter($filter);
        }
        return $composite;
    }

}

<?php

namespace Kibo\Phast\Filters\HTML\Composite;

use Kibo\Phast\Environment\Package;
use Kibo\Phast\Logging\LoggingTrait;
use Kibo\Phast\ValueObjects\URL;

class Factory {

    use LoggingTrait;

    public function make(array $config) {
        $composite = new Filter(URL::fromString($config['documents']['baseUrl']), $config['outputServerSideStats']);
        foreach (array_keys($config['documents']['filters']) as $class) {
            $package = Package::fromPackageClass($class);
            if ($package->hasFactory()) {
                $filter = $package->getFactory()->make($config);
            } elseif (!class_exists($class)) {
                $this->logger(__METHOD__, __LINE__)
                     ->error("Skipping non-existent filter class: $class");
            } else {
                $filter = new $class();
            }
            $composite->addHTMLFilter($filter);
        }
        return $composite;
    }

}

Drop non-existent filter classes and log an error


<?php namespace Qia;

use Flarum\Support\Extension as BaseExtension;
use Illuminate\Events\Dispatcher;
use Flarum\Events\RegisterLocales;

class Extension extends BaseExtension
{
    public function listen(Dispatcher $events)
    {
        $events->listen(RegisterLocales::class, function (RegisterLocales $event) {
            $event->manager->addLocale('fr', 'French');
            $event->addTranslations('fr', __DIR__.'/../locale/core.yml');
            $event->manager->addJsFile('fr', __DIR__.'/../locale/core.js');
            $event->manager->addConfig('fr', __DIR__.'/../locale/core.php');
            $event->addTranslations('fr', __DIR__.'/../locale/likes.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/lock.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/tags.yml');
        });
    }
}

<?php namespace Qia;

use Flarum\Support\Extension as BaseExtension;
use Illuminate\Events\Dispatcher;
use Flarum\Events\RegisterLocales;

class Extension extends BaseExtension
{
    public function listen(Dispatcher $events)
    {
        $events->listen(RegisterLocales::class, function (RegisterLocales $event) {
            $event->manager->addLocale('fr', 'Français');
            $event->manager->addJsFile('fr', __DIR__.'/../locale/core.js');
            $event->manager->addConfig('fr', __DIR__.'/../locale/core.php');
            $event->addTranslations('fr', __DIR__.'/../locale/core.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/likes.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/lock.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml');
            $event->addTranslations('fr', __DIR__.'/../locale/tags.yml');
        });
    }
}

Use "Français" instead of "French".

Use "Français" instead of "French".


<?php

//Indication, Copyright Josh Fradley (http://github.com/joshf/Indication)

if (!file_exists("../../config.php")) {
    header("Location: ../../installer");
    exit;
}

require_once("../../config.php");

session_start();
if (!isset($_SESSION["indication_user"])) {
    header("Location: ../login.php");
    exit;
}

if (!isset($_POST["id"])) {
    header("Location: ../../admin");
    exit;
}

//Connect to database
@$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
    die("Error: Could not connect to database (" . mysqli_connect_error() . "). Check your database settings are correct.");
}

$id = mysqli_real_escape_string($con, $_POST["id"]);

if (isset($_POST["action"])) {
	$action = $_POST["action"];
} else {
	die("Error: No action passed");
}

if ($action == "delete") {
	mysqli_query($con, "DELETE FROM `Data` WHERE `id` = \"$id\"");
}

mysqli_close($con);

?>

<?php

//Indication, Copyright Josh Fradley (http://github.com/joshf/Indication)

if (!file_exists("../../config.php")) {
    header("Location: ../../installer");
    exit;
}

require_once("../../config.php");

session_start();
if (!isset($_SESSION["indication_user"])) {
    header("Location: ../login.php");
    exit;
}

if (!isset($_POST["id"])) {
    header("Location: ../../admin");
    exit;
}

//Connect to database
@$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
    die("Error: Could not connect to database (" . mysqli_connect_error() . "). Check your database settings are correct.");
}

$id = mysqli_real_escape_string($con, $_POST["id"]);

if (isset($_POST["action"])) {
	$action = $_POST["action"];
} else {
	die("Error: No action passed");
}

if ($action == "delete") {
	mysqli_query($con, "DELETE FROM `Data` WHERE `id` = \"$id\"");
} else {
    die("Error: Action not recognised!");
}

mysqli_close($con);

?>

Add die if invalid action is passed

Add die if invalid action is passed


<?php

return [
    [
        'link' => 'https://www.youtube.com/watch?v=-5ZdGUvOqx4',
        'embed_url' => 'https://www.youtube.com/embed/-5ZdGUvOqx4'
    ],
    [
        'link' => 'https://www.youtube.com/watch?v=s6xrnYae1FU',
        'embed_url' => 'https://www.youtube.com/embed/s6xrnYae1FU'
    ],
    [
        'link' => 'https://www.youtube.com/watch?v=MWNcItWuKpI',
        'embed_url' => 'https://www.youtube.com/embed/MWNcItWuKpI'
    ],
];

<?php

return [
    [
        'link' => 'https://www.youtube.com/watch?v=-5ZdGUvOqx4',
        'embed_url' => 'https://www.youtube-nocookie.com/embed/-5ZdGUvOqx4'
    ],
    [
        'link' => 'https://www.youtube.com/watch?v=s6xrnYae1FU',
        'embed_url' => 'https://www.youtube-nocookie.com/embed/s6xrnYae1FU'
    ],
    [
        'link' => 'https://www.youtube.com/watch?v=MWNcItWuKpI',
        'embed_url' => 'https://www.youtube-nocookie.com/embed/MWNcItWuKpI'
    ],
];

Embed youtube videos via youtube-nocookie.com


<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends \App\Http\Controllers\Controller
{

    public function login()
    {
        if (Auth::check() === true)
            return redirect('/');

        return view('login');
    }
    public function logout()
    {
        // TODO: Validation
        Auth::logout();
        return redirect('/login');
    }

    public function signup()
    {
        return view('signup');
    }

    public function authenticate()
    {
        // TODO: Validation
        $credentials = [
            'email' => Request::input('email'),
            'password' => Request::input('password')
        ];

        if( ! Auth::attempt($credentials, true))
            return redirect('login');

        Auth::login(Auth::user());
        return redirect('/');

    }

    public function register()
    {
        // TODO: Validation
        // TODO: get username properly
        $credentials = [
            'username' => str_random(10),
            'email' => Request::input('email'),
            'password' => Request::input('password')
        ];

        try {
            $user = User::create($credentials);
        } catch (QueryException $e) {
            dd($e->errorInfo[2]);
        }

        Auth::login($user);

        return redirect('/');
    }
}

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends \App\Http\Controllers\Controller
{

    public function login()
    {
        if (Auth::check() === true)
            return redirect('/');

        return view('login');
    }
    public function logout()
    {
        // TODO: Validation
        Auth::logout();
        return redirect('/login');
    }

    public function signup()
    {
        return view('signup');
    }

    public function authenticate()
    {
        // TODO: Validation
        $credentials = [
            'email' => Request::input('email'),
            'password' => Request::input('password')
        ];

        if( ! Auth::attempt($credentials, true))
            return redirect('login');

        Auth::login(Auth::user());
        return redirect('/');

    }

    public function register(\Illuminate\Http\Request $request)
    {
        // TODO: Validation
        // TODO: get username properly
        $this->validate($request, [
            'email' => 'required|email|unique:users,email',
            'password' => 'same:repeat-password',
            'repeat-password' => 'required',
        ]);

        $credentials = [
            'username' => str_random(10),
            'email' => Request::input('email'),
            'password' => Request::input('password')
        ];

        try {
            $user = User::create($credentials);
        } catch (QueryException $e) {
            dd($e->errorInfo[2]);
        }

        Auth::login($user);

        return redirect('/');
    }
}

Add simple back-end validation on signup


<?php namespace Nobox\LazyStrings\Commands;

use Nobox\LazyStrings\LazyStrings;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class LazyDeployCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'lazy:deploy';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Deploy LazyStrings.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->info('Deploying...');

        $lazyStrings = new LazyStrings();
        $lazyStrings->generateStrings();

        $this->info('Lazy Strings is now deployed.');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array();
    }

}

<?php namespace Nobox\LazyStrings\Commands;

use Nobox\LazyStrings\LazyStrings;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class LazyDeployCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'lazy:deploy';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Deploy LazyStrings.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->info('Deploying...');

        $lazyStrings = $this->laravel['lazy-strings'];
        $lazyStrings->generateStrings();

        $this->info('Lazy Strings is now deployed.');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array();
    }

}

Use LazyStrings instance in container.

Use LazyStrings instance in container.

The command uses the LazyStrings instance in the container for the deployment command.


<?
include '../scat.php';

$name= $_REQUEST['name'];
$company= $_REQUEST['company'];
$phone= $_REQUEST['phone'];
if (empty($name) && empty($company) && empty($phone))
  die_jsonp("You need to supply at least a name, company, or phone number.");

$list= array();
foreach(array('name', 'company', 'address',
              'email', 'phone', 'tax_id') as $field) {
  $list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', ";
}

if ($list['phone']) {
  $list['loyalty_number']= preg_replace('/[^\d]/', '', $list['phone']);
}

$fields= join('', $list);

$q= "INSERT INTO person
        SET $fields
        active = 1";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('person' => $db->insert_id));

<?
include '../scat.php';

$name= $_REQUEST['name'];
$company= $_REQUEST['company'];
$phone= $_REQUEST['phone'];
if (empty($name) && empty($company) && empty($phone))
  die_jsonp("You need to supply at least a name, company, or phone number.");

$list= array();
foreach(array('name', 'company', 'address',
              'email', 'phone', 'tax_id') as $field) {
  $list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', ";
}

if ($_REQUEST['phone']) {
  $list[]= "loyalty_number = '" .
           preg_replace('/[^\d]/', '', $_REQUEST['phone']) .
           "', ";
}

$fields= join('', $list);

$q= "INSERT INTO person
        SET $fields
        active = 1";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('person' => $db->insert_id));

Fix setting loyalty_number on new customer


<?php

namespace Tests\Feature;

use Tests\TestCase;

class ListingsTest extends TestCase
{
    /**
     * Test that the Listings pages load via HTTP requests.
     *
     * @dataProvider ListingPages
     *
     * @return void
     **/
    public function testListingPagesLoadViaHttp($pageName, $value)
    {
        $this->get($pageName)->assertStatus(200);
    }

    public function listingPages(): array
    {
        return [
            'Machines listing'                 => ['/machines', 'Equipment Inventory - Active'],
            'Test equipment listing'           => ['/testequipment', 'Equipment Inventory - Test Equipment'],
            'Test equipment cal dates listing' => ['/testequipment/caldates', 'Recent Test Equipment Calibration Dates'],
        ];
    }
}

<?php

use function Pest\Laravel\get;

test('Lising page exists', function($url) {
    get($url)->assertStatus(200);
})->with([
    'Machines listing' => '/machines',
    'Test equipment listing' => '/testequipment',
    'Test equipment calibration dates liisting' => '/testequipment/caldates',
]);
// namespace Tests\Feature;

// use Tests\TestCase;

// class ListingsTest extends TestCase
// {
//     /**
//      * Test that the Listings pages load via HTTP requests.
//      *
//      * @dataProvider ListingPages
//      *
//      * @return void
//      **/
//     public function testListingPagesLoadViaHttp($pageName, $value)
//     {
//         $this->get($pageName)->assertStatus(200);
//     }

//     public function listingPages(): array
//     {
//         return [
//             'Machines listing'                 => ['/machines', 'Equipment Inventory - Active'],
//             'Test equipment listing'           => ['/testequipment', 'Equipment Inventory - Test Equipment'],
//             'Test equipment cal dates listing' => ['/testequipment/caldates', 'Recent Test Equipment Calibration Dates'],
//         ];
//     }
//}

Rewrite as a Pest PHP test

Rewrite as a Pest PHP test


<?php

declare(strict_types=1);

namespace Tests\Stub;

use PHPUnit\Framework\TestCase;

class SessionTestStub extends TestCase
{
    private const SESSION_ID = '42';

    protected function setUp(): void
    {
        session_id(self::SESSION_ID);
    }

    public function testOne(): void
    {
        $process = new StubbedParaunitProcess();

        $this->assertTrue($process->isTerminated());
    }

    public function testTwo(): void
    {
        $this->assertEquals(session_id(), self::SESSION_ID);
    }

    public function testThree(): void
    {
        $this->assertTrue(true);
    }
}

<?php

declare(strict_types=1);

namespace Tests\Stub;

use PHPUnit\Framework\TestCase;

class SessionTestStub extends TestCase
{
    private const SESSION_ID = '42';

    protected function setUp(): void
    {
        session_id(self::SESSION_ID);
    }

    public function testOne(): void
    {
        $process = new StubbedParaunitProcess();

        $this->assertTrue($process->isTerminated());
    }

    public function testTwo(): void
    {
        $this->assertEquals(self::SESSION_ID, session_id());
    }

    public function testThree(): void
    {
        $this->assertTrue(true);
    }
}

Fix arguments order in assertion

Fix arguments order in assertion


<?php

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

class CreateFaqsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('polyfaq_faqs', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->string('title')->default('');
            $table->text('content')->default('');

            $table->morphs('faqable');

            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('polyfaq_faqs', function (Blueprint $table) {
            $table->drop();
        });
    }
}

<?php

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

class CreateFaqsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('polyfaq_faqs', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->string('title')->default('');
            $table->text('content')->default('');
            $table->integer('sorting')->default(0);

            $table->morphs('faqable');

            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('polyfaq_faqs', function (Blueprint $table) {
            $table->drop();
        });
    }
}

Add sorting to faqs table

[TASK] Add sorting to faqs table


<?php
namespace spec\rtens\mockster3;

use rtens\mockster3\Mockster;
use watoki\scrut\Specification;

class CheckReturnTypeTest extends Specification {

    /** @var CheckReturnTypeTest_FooClass $mock */
    private $mock;

    /** @var CheckReturnTypeTest_FooClass|Mockster $foo */
    private $foo;

    protected function setUp() {
        parent::setUp();

        $this->foo = new Mockster(CheckReturnTypeTest_FooClass::class);
        $this->mock = $this->foo->mock();
    }

    function testAcceptAllIfNoTypeHintGiven() {
        Mockster::stub($this->foo->noHint())->will()->return_("foo");
        Mockster::stub($this->foo->noHint())->will()->return_(42);
        $this->mock->noHint();
    }

    function testFailIfReturnedValuePrimitiveDoesNotMatch() {
        Mockster::stub($this->foo->returnsString())->will()->return_(42);

        try {
            $this->mock->returnsString();
            $this->fail("Should have thrown an exception");
        } catch (\ReflectionException $e) {
        }
        $this->assertCount(1, Mockster::stub($this->foo->returnsString())->calls());
    }
}

class CheckReturnTypeTest_FooClass {

    public function noHint() {
        return null;
    }

    /**
     * @return string
     */
    public function returnsString() {
        return null;
    }
}

<?php
namespace spec\rtens\mockster3;

use rtens\mockster3\Mockster;
use watoki\scrut\Specification;

class CheckReturnTypeTest extends Specification {

    /** @var CheckReturnTypeTest_FooClass $mock */
    private $mock;

    /** @var CheckReturnTypeTest_FooClass|Mockster $foo */
    private $foo;

    protected function setUp() {
        parent::setUp();

        $this->foo = new Mockster(CheckReturnTypeTest_FooClass::class);
        $this->mock = $this->foo->mock();
    }

    function testAcceptAllIfNoTypeHintGiven() {
        Mockster::stub($this->foo->noHint())->will()->return_("foo");
        Mockster::stub($this->foo->noHint())->will()->return_(42);
        $this->mock->noHint();
    }

    function testFailIfPrimitiveValueDoesNotMatch() {
        Mockster::stub($this->foo->returnsString())->will()->return_(42);

        try {
            $this->mock->returnsString();
            $this->fail("Should have thrown an exception");
        } catch (\ReflectionException $e) {
        }
        $this->assertCount(1, Mockster::stub($this->foo->returnsString())->calls());
    }

    function testFailIfNonStubbedValueDoesNotMatch() {
        Mockster::stub($this->foo->returnsString())->dontStub();

        try {
            $this->mock->returnsString();
            $this->fail("Should have thrown an exception");
        } catch (\ReflectionException $e) {
        }
        $this->assertCount(1, Mockster::stub($this->foo->returnsString())->calls());
    }
}

class CheckReturnTypeTest_FooClass {

    public function noHint() {
        return null;
    }

    /**
     * @return string
     */
    public function returnsString() {
        return null;
    }
}

Check returned value of non-stubbed method call


<?php

namespace AppBundle\Controller;

use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseAdminController;

class AdminController extends BaseAdminController
{

}

<?php

namespace AppBundle\Controller;

use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseAdminController;

class AdminController extends BaseAdminController
{
    public function createNewUserEntity(){
        return $this->get('fos_user.user_manager')->createUser();
    }

    public function prePersistUserEntity($user){
        $this->get('fos_user.user_manager')->updateUser($user, false);
    }
}

Add two functions to amdin controller

Add two functions to amdin controller


<?php

namespace App\Controller\Framework;

use App\Command\CommandDispatcherTrait;
use App\Command\Framework\CloneFrameworkCommand;
use App\Entity\Framework\LsDoc;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;

/**
 * Copy controller.
 *
 * @Route("/clone")
 */
class CloneController extends AbstractController
{
    use CommandDispatcherTrait;

    /**
     * @Route("/framework/{id}", name="clone_framework", methods={"GET"})
     * @Security("is_granted('create', lsDoc)")
     */
    public function frameworkAction(Request $request, LsDoc $lsDoc): Response
    {
        $command = new CloneFrameworkCommand($lsDoc);
        $this->sendCommand($command);

        return $this->redirectToRoute('doc_tree_view', ['slug' => $lsDoc->getId()]);
    }
}

<?php

namespace App\Controller\Framework;

use App\Command\CommandDispatcherTrait;
use App\Command\Framework\CloneFrameworkCommand;
use App\Entity\Framework\LsDoc;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;

/**
 * Copy controller.
 *
 * @Route("/clone")
 */
class CloneController extends AbstractController
{
    use CommandDispatcherTrait;

    /**
     * @Route("/framework/{id}", name="clone_framework", methods={"GET"})
     * @Security("is_granted('edit', lsDoc) and is_granted('create', 'lsdoc')")
     */
    public function frameworkAction(Request $request, LsDoc $lsDoc): Response
    {
        $command = new CloneFrameworkCommand($lsDoc);
        $this->sendCommand($command);

        return $this->redirectToRoute('doc_tree_view', ['slug' => $lsDoc->getId()]);
    }
}

Add both and edit and create security checks.


<?php

return [
    'model_ns' => 'App',
    'sitename' => 'CrudApi',
    'pagination' => [
        'enabled' => true,
        'perPage' => 25
    ]
];

<?php

return [

    'sitename' => 'CrudApi',

    'pagination' => [
        'enabled' => true,
        'perPage' => 25
    ]
];

Remove model NS from config - we can obtain this through code.


<?php
// check if fields passed are empty
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = $_POST['name'];
// $phone = $_POST['phone'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$numOfGuests = $_POST['numOfGuests'];
$checkinDate = $_POST['checkin'];
$checkoutDate = $_POST['checkout'];

// create email body and send it
$to = 'contact@happy-nest.in';
$email_subject = "Accomodation inquiry";
$email_body = "New request\n\n".
                  "Name of the guest: $name \n".
                  "Email: $email_address\n".
                  "Number of guests: $numOfGuests\n".
                  "Checkin Date (mm/dd/yyyy): $checkinDate\n".
                  "Checkout Date (mm/dd/yyyy): $checkoutDate\n".
                  "Message \n $message";
$headers = "From: me@happy-nest.in\n";
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
return true;
?>

<?php
// check if fields passed are empty
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = $_POST['name'];
// $phone = $_POST['phone'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$numOfGuests = $_POST['numOfGuests'];
$checkinDate = $_POST['checkin'];
$checkoutDate = $_POST['checkout'];

// create email body and send it
$to = 'contact@happy-nest.in';
$email_subject = "Happy-nest accomodation inquiry";
$email_body = "New request\n\n".
                  "Name of the guest: $name \n".
                  "Email: $email_address\n".
                  "Number of guests: $numOfGuests\n".
                  "Checkin Date (mm/dd/yyyy): $checkinDate\n".
                  "Checkout Date (mm/dd/yyyy): $checkoutDate\n".
                  "Message \n $message";
$headers = "From: me@happy-nest.in\n";
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
return true;
?>

Add happy-nest in email subject

Add happy-nest in email subject


<?php
/**
* This file is part of the League.url library
*
* @license http://opensource.org/licenses/MIT
* @link https://github.com/thephpleague/url/
* @version 4.0.0
* @package League.url
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\Url;

use InvalidArgumentException;
use League\Url\Interfaces\Component;

/**
* A class to manipulate URL Port component
*
* @package League.url
* @since 1.0.0
*/
class Port extends AbstractComponent implements Component
{
    /**
     * {@inheritdoc}
     */
    protected function validate($data)
    {
        $data = filter_var($data, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        if (! $data) {
            throw new InvalidArgumentException('The submitted port is invalid');
        }

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function getUriComponent()
    {
        $data = $this->__toString();
        if (empty($data)) {
            return $data;
        }
        return ':'.$data;
    }
}

<?php
/**
* This file is part of the League.url library
*
* @license http://opensource.org/licenses/MIT
* @link https://github.com/thephpleague/url/
* @version 4.0.0
* @package League.url
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\Url;

use InvalidArgumentException;
use League\Url\Interfaces\Component;

/**
* A class to manipulate URL Port component
*
* @package League.url
* @since 1.0.0
*/
class Port extends AbstractComponent implements Component
{
    /**
     * {@inheritdoc}
     */
    protected function validate($data)
    {
        if (! ctype_digit($data) || $data < 1) {
            throw new InvalidArgumentException('The submitted port is invalid');
        }

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function getUriComponent()
    {
        $data = $this->__toString();
        if (empty($data)) {
            return $data;
        }
        return ':'.$data;
    }
}

Use ctype_digit to validate port

Use ctype_digit to validate port


@extends('layout')

@section('title')File - {{$file}}@stop

@section('content')

{{SourceController::linkedPath($path)}}

Query

    <?php
	    $source = file_get_contents(base_path() . "/query/" . $file . ".sql");
    	$geshi = new GeSHi($source, 'sql');
    	echo $geshi->parse_code();
    ?>

Output

@stop

@extends('layout')

@section('title')File - {{$file}}@stop

@section('content')

{{SourceController::linkedPath($path)}}

Query

    <?php
	    $source = file_get_contents(base_path() . "/query/" . $file . ".sql");
    	$geshi = new GeSHi($source, 'sql');
    	echo $geshi->parse_code();
    ?>

Output

    <?php
    	$outputs = SourceController::getDir("output/" . $path);
    	$filename = $outputs[sizeof($outputs) - 1];

	    $source = file_get_contents(base_path() . "/output/" . $file . "/" . $filename);
    	$geshi = new GeSHi($source, 'sql');
    	echo $geshi->parse_code();
    ?>

@stop

Make possibe to output the last output of the query


<?php

if (! function_exists('create_hooks_dir')) {
    /**
     * Create hook directory if not exists.
     *
     * @param  string  $dir
     * @param  int  $mode
     * @param  bool  $recursive
     *
     * @return void
     */
    function create_hooks_dir($dir, $mode = 0700, $recursive = true)
    {
        if (! is_dir("{$dir}/hooks")) {
            mkdir("{$dir}/hooks", $mode, $recursive);
        }
    }
}

if (! function_exists('is_windows')) {
    /**
     * Determine whether the current environment is Windows based.
     *
     * @return bool
     */
    function is_windows()
    {
        return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
    }
}

if (! function_exists('global_hook_dir')) {
    /**
     * Gets the global directory set for git hooks
     */
    function global_hook_dir()
    {
        return trim(shell_exec('git config --global core.hooksPath'));
    }
}

if (! function_exists('absolute_git_dir')) {
    /**
     * Resolve absolute git dir which will serve as the default git dir
     * if one is not provided by the user.
     */
    function absolute_git_dir()
    {
        return trim(shell_exec('git rev-parse --absolute-git-dir'));
    }
}

<?php

if (! function_exists('create_hooks_dir')) {
    /**
     * Create hook directory if not exists.
     *
     * @param  string  $dir
     * @param  int  $mode
     * @param  bool  $recursive
     *
     * @return void
     */
    function create_hooks_dir($dir, $mode = 0700, $recursive = true)
    {
        if (! is_dir("{$dir}/hooks")) {
            mkdir("{$dir}/hooks", $mode, $recursive);
        }
    }
}

if (! function_exists('is_windows')) {
    /**
     * Determine whether the current environment is Windows based.
     *
     * @return bool
     */
    function is_windows()
    {
        return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
    }
}

if (! function_exists('global_hook_dir')) {
    /**
     * Gets the global directory set for git hooks
     */
    function global_hook_dir()
    {
        return trim(shell_exec('git config --global core.hooksPath'));
    }
}

if (! function_exists('absolute_git_dir')) {
    /**
     * Resolve absolute git dir which will serve as the default git dir
     * if one is not provided by the user.
     */
    function absolute_git_dir()
    {
        return trim(shell_exec('git rev-parse --git-dir'));
    }
}

Update git command that will support old version of git also


<?php
/**
 * A simple extension to add a sort field to an object.
 *
 * @package silverstripe-orderable
 */
class Orderable extends DataObjectDecorator {

	public function extraStatics() {
		return array('db' => array('Sort' => 'Int'));
	}

	public function augmentSQL($query) {
		if (!$query->orderby) $query->orderby('"Sort"');
	}

	public function onBeforeWrite() {
		if (!$this->owner->Sort) {
			$max = DB::query(sprintf(
				'SELECT MAX("Sort") + 1 FROM "%s"', $this->ownerBaseClass
			));
			$this->owner->Sort = $max->value();
		}
	}

}

<?php
/**
 * A simple extension to add a sort field to an object.
 *
 * @package silverstripe-orderable
 */
class Orderable extends DataObjectDecorator {

	public function extraStatics() {
		return array('db' => array('Sort' => 'Int'));
	}

	public function augmentSQL($query) {
		if (!$query->orderby) $query->orderby('"Sort"');
	}

	public function onBeforeWrite() {
		if (!$this->owner->Sort) {
			$max = DB::query(sprintf(
				'SELECT MAX("Sort") + 1 FROM "%s"', $this->ownerBaseClass
			));
			$this->owner->Sort = $max->value();
		}
	}

	public function updateCMSFields($fields) {
		$fields->removeByName('Sort');
	}

	public function updateFrontEndFields($fields) {
		$fields->removeByName('Sort');
	}

}

Hide the Sort field in forms.

MINOR: Hide the Sort field in forms.


<?php

namespace Algolia\AlgoliaSearchBundle\DependencyInjection;

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

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class AlgoliaAlgoliaSearchExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('algolia.application_id', $config['application_id']);
        $container->setParameter('algolia.api_key', $config['api_key']);
        $container->setParameter('algolia.catch_log_exceptions', $config['catch_log_exceptions']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }

    public function getAlias()
    {
        return 'algolia';
    }
}

<?php

namespace Algolia\AlgoliaSearchBundle\DependencyInjection;

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

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class AlgoliaAlgoliaSearchExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        if (isset($config['application_id']))
            $container->setParameter('algolia.application_id', $config['application_id']);

        if (isset($config['api_key']))
            $container->setParameter('algolia.api_key', $config['api_key']);

        $container->setParameter('algolia.catch_log_exceptions', $config['catch_log_exceptions']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

    }

    public function getAlias()
    {
        return 'algolia';
    }
}

Add condition to avoid notices

Add condition to avoid notices


<?php
function phpme_map( $from_array, $map, $return_type = 'Array' ) {
	$return = array();

	foreach ( $map as $to_key => $from_key ) {
		$return[$to_key] = $from_array[$from_key];
	}

	if ( $return_type == 'Object' )
		$return = (Object) $return;

	return $return;
}
?>

<?php
function phpme_map( $from_array, $map, $return_type = 'Array' ) {
	$return = array();

	foreach ( $map as $to_key => $from_key ) {
		if ( isset( $from_array[$from_key] ) )
		$return[$to_key] = $from_array[$from_key];
	}

	if ( $return_type == 'Object' )
		$return = (Object) $return;

	return $return;
}
?>

Check for existing key before mapping in phpme_map()


<?php
/*
 *	Made by Samerton
 *  https://github.com/NamelessMC/Nameless/
 *  NamelessMC version 2.0.0-dev
 *
 *  License: MIT
 *
 *  EnglishUS Language - Errors
 */

$language = array(
	/*
	 *  Errors
	 */
	'404_title' => 'Promň!',
	'404_content' => 'Ale tuto stránku nemůžeme najít :(',
	'404_back' => 'Vrátit zpět',
	'404_home' => 'Donů',
	'404_error' => 'Pokud se domníváte, že je to chyba, {x}prosím kontaktujte administrátora{y}', // Don't replace {x} or {y}
	'maintenance_title' => 'Maintenance mode.',
    'maintenance_retry' => 'Retry'
);

<?php
/*
 *	Made by Samerton
 *  https://github.com/NamelessMC/Nameless/
 *  NamelessMC version 2.0.0-pr2
 *
 *  License: MIT
 *
 *  Czech Language - Errors
 */

$language = array(
	/*
	 *  Errors
	 */
	'404_title' => 'Promň!',
	'404_content' => 'Ale tuto stránku nemůžeme najít :(',
	'404_back' => 'Vrátit zpět',
	'404_home' => 'Domů',
	'404_error' => 'Pokud se domníváte, že je to chyba, {x}prosím kontaktujte administrátora{y}', // Don't replace {x} or {y}
	'maintenance_title' => 'Maintenance mode.',
	'maintenance_retry' => 'Retry'
);

Fix Czech translation typo, thanks to Renzotom


<?php

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

namespace Moccalotto\Valit\Contracts;

interface CheckManager
{
    /**
     * Get or create the singleton instance.
     *
     * @return CheckManager
     */

    /**
     * Get the default (global) manager instance.
     *
     * If no instance is configured, a new one is created via the create() factory method.
     *
     * @return CheckManager
     *
     * @see create
     */
    public static function instance();

    /**
     * Factory method.
     *
     * Create a Manager with all the default providers loaded
     * as well as the providers defined in $additionalCheckProviders
     *
     * @param string[] $additionalCheckProviders
     *
     * @return @CheckManager
     */
    public static function create($additionalCheckProviders = []);

    /**
     * Check if the manager can perform a given check.
     *
     * @param string $checkName
     *
     * @return bool
     */
    public function hasCheck(string $checkName);

    /**
     * Execute a check.
     *
     * @param string $checkName
     * @param mixed  $value
     * @param array  $args
     *
     * @return \Moccalotto\Valit\Result
     */
    public function executeCheck($checkName, $value, array $args);
}

<?php

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

namespace Moccalotto\Valit\Contracts;

interface CheckManager
{
    /**
     * Get or create the singleton instance.
     *
     * @return CheckManager
     */

    /**
     * Get the default (global) manager instance.
     *
     * If no instance is configured, a new one is created via the create() factory method.
     *
     * @return CheckManager
     *
     * @see create
     */
    public static function instance();

    /**
     * Factory method.
     *
     * Create a Manager with all the default providers loaded
     * as well as the providers defined in $additionalCheckProviders
     *
     * @param string[] $additionalCheckProviders
     *
     * @return @CheckManager
     */
    public static function create($additionalCheckProviders = []);

    /**
     * Check if the manager can perform a given check.
     *
     * @param string $checkName
     *
     * @return bool
     */
    public function hasCheck($checkName);

    /**
     * Execute a check.
     *
     * @param string $checkName
     * @param mixed  $value
     * @param array  $args
     *
     * @return \Moccalotto\Valit\Result
     */
    public function executeCheck($checkName, $value, array $args);
}

Remove scalar type hint for php56 compat


<?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
/*
 * Created on Jan 30, 2009
 *
 * Parent class of all test cases. For some reason PHPUnit doesn't deal
 * well with globals, so $backupGlobals should be set to false.
 * Use this class to set other PHPUnit variables, as needed.
 *
 */

require_once('PHPUnit/Framework.php');

abstract class TikiTestCase extends PHPUnit_Framework_TestCase
{
 	protected $backupGlobals = FALSE;
}

<?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
/*
 * Created on Jan 30, 2009
 *
 * Parent class of all test cases. For some reason PHPUnit doesn't deal
 * well with globals, so $backupGlobals should be set to false.
 * Use this class to set other PHPUnit variables, as needed.
 *
 */

require_once (version_compare(PHPUnit_Runner_Version::id(), '3.5.0', '>=')) ? 'PHPUnit/Autoload.php' : 'PHPUnit/Framework.php';

abstract class TikiTestCase extends PHPUnit_Framework_TestCase
{
 	protected $backupGlobals = FALSE;
}

[FIX] Use the correct include based on the PHPUnit version.

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@36937 b456876b-0849-0410-b77d-98878d47e9d5


<?php
/**
 * User: wangting
 * Date: 12-11-29
 * Time: 上午11:56
 * copyright 2012 tiddr.de
 */
class Base
{

}

<?php
namespace Tiddr\Mapper;
use ZfcBase\Mapper\AbstractDbMapper;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\DbSelect;

/**
 * User: wangting
 * Date: 12-11-29
 * Time: 上午11:56
 * copyright 2012 tiddr.de
 */
class Base extends AbstractDbMapper
{

    public function fetchAll($select = null)
    {
        if (null === $select) {
            $select = $this->getSelect();
        }
        $resultSet = new HydratingResultSet($this->getHydrator(), $this->getEntityPrototype());
        $dbSelect = new DbSelect($select, $this->getDbAdapter(), $resultSet);
        return new Paginator($dbSelect);
    }

    public function findById($id)
    {
        $select = $this->getSelect()->where(array('id' => $id));
        return $this->select($select)->current();
    }

    public function insert($entity, $tableName = null, \Zend\Stdlib\Hydrator\HydratorInterface $hydrator = null)
    {
        $result = parent::insert($entity, $tableName, $hydrator);
        $entity->setId($result->getGeneratedValue());
        return $entity;
    }

    public function update($entity, $where = null, $tableName = null, \Zend\Stdlib\Hydrator\HydratorInterface $hydrator = null)
    {
        if (!$where) {
            $where = 'id = ' . $entity->getId();
        }
        parent::update($entity, $where, $tableName, $hydrator);
    }

    public function deleteById($id, $tableName = null)
    {
        $where = 'id = ' . $id;
        parent::delete($where, $tableName);
    }
}

Move common mapper task into base.

Move common mapper task into base.


<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataLanguagesSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
        'layout' => 'horizontal',
        'fieldConfig' => [
            'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
            'horizontalCssClasses' => [
                'offset' => '',
                'label' => 'col-md-3',
                'wrapper' => 'col-md-5',
                'error' => '',
                'hint' => '',
            ],
        ]
    ]); ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'short_name') ?>

            <?= Html::submitButton(Yii::t('app/frontend', 'Search'), ['class' => 'btn btn-primary']) ?>
            <?php // echo Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>

<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataLanguagesSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
        'layout' => 'horizontal',
        'fieldConfig' => [
            'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
            'horizontalCssClasses' => [
                'offset' => '',
                'label' => 'col-md-3',
                'wrapper' => 'col-md-5',
                'error' => '',
                'hint' => '',
            ],
        ]
    ]); ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'short_name') ?>

            <?= Html::submitButton(Yii::t('app/frontend', 'Search'), ['class' => 'btn btn-primary']) ?>
            <?= Html::a(Yii::t('app/fronted', 'Reset'),
                        Url::to(['index']),
                        ['class' => 'btn btn-danger']) ?>

    <?php ActiveForm::end(); ?>

Add a reset button into the search section.

:)


<?php

namespace SteamRep;

abstract class SteamRepModel {
    protected $body;

    public function __construct(array $body) {
        $this->body = $body;
    }
}

<?php

namespace SteamRep;

abstract class SteamRepModel {
    protected $body;

    public function __construct(array $body) {
        $this->body = $body;
    }

    public function toArray(): array {
        return $this->body;
    }
}

Allow models to be exported to an array

Allow models to be exported to an array


<?php

namespace Interop\Http\Factory;

use Psr\Http\Message\StreamInterface;

interface StreamFactoryInterface
{
    /**
     * Create a new stream from a resource.
     *
     * The resource MUST be readable and SHOULD be seekable. It MAY be writable.
     *
     * @param resource $resource
     *
     * @return StreamInterface
     */
    public function createStream($resource);
}

<?php

namespace Interop\Http\Factory;

use Psr\Http\Message\StreamInterface;

interface StreamFactoryInterface
{
    /**
     * Create a new stream from a resource or a string.
     *
     * If argument is resource, it MUST be readable and SHOULD be seekable. It MAY be writable.
     *
     * @param string|resource $resource
     *
     * @return StreamInterface
     */
    public function createStream($resource);
}

Allow for strings in Stream::createStream


<?php
class C00_Station_ProfileCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function editStationProfile(FunctionalTester $I)
    {
        $I->wantTo('View and edit a station profile.');

        $station_id = $this->test_station->getId();

        $I->amOnPage('/station/'.$station_id);

        $I->see('Functional Test Radio');

        $I->wantTo('Edit a station profile.');
        $I->click('.btn-float'); // Plus sign

        $I->seeCurrentUrlEquals('/station/'.$station_id.'/profile/edit');

        $I->submitForm('.form', [
            'name' => 'Profile Update Test Radio',
            'description' => 'Testing a profile update.',
        ]);

        $I->seeCurrentUrlEquals('/station/'.$station_id);

        $I->see('Profile Update Test Radio');
        $I->see('Testing a profile update.');
    }
}

<?php
class C00_Station_ProfileCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function editStationProfile(FunctionalTester $I)
    {
        $I->wantTo('View and edit a station profile.');

        $station_id = $this->test_station->getId();

        $I->amOnPage('/station/'.$station_id.'/profile');

        $I->see('Functional Test Radio');

        $I->wantTo('Edit a station profile.');
        $I->click('.btn-float'); // Plus sign

        $I->seeCurrentUrlEquals('/station/'.$station_id.'/profile/edit');

        $I->submitForm('.form', [
            'name' => 'Profile Update Test Radio',
            'description' => 'Testing a profile update.',
        ]);

        $I->seeCurrentUrlEquals('/station/'.$station_id.'/profile');

        $I->see('Profile Update Test Radio');
        $I->see('Testing a profile update.');
    }
}

Update unit tests to reflect new routing.


<?php
class User extends AppModel {
	public $name = 'User';
	public $primaryKey = 'id';
	public $displayField = 'name';

	/**
	* @function name:	public function getUser($id)
	* @description:		This function returns data of a user.
	* @related issues:	QH-1
	* @param:			string $id
	* @return:			array $user
	* @author:			Don Hsieh
	* @since:			09/28/2013
	* @last modified: 	09/28/2013
	* @called by:
	*/
	public function getUser($id) {
		$user = null
		return $user;
	}
}
?>

<?php
class User extends AppModel {
	public $name = 'User';
	public $primaryKey = 'id';
	public $displayField = 'name';

	/**
	* @function name:	public function getUser($id)
	* @description:		This function returns data of a user.
	* @related issues:	QH-1
	* @param:			string $id
	* @return:			array $user
	* @author:			Don Hsieh
	* @since:			10/03/2013
	* @last modified: 	10/03/2013
	* @called by:
	*/
	public function getUserByUsername($username) {
		$user = null
		return $user;
	}

	/**
	* @function name:	public function getUser($id)
	* @description:		This function returns data of a user.
	* @related issues:	QH-1
	* @param:			string $id
	* @return:			array $user
	* @author:			Don Hsieh
	* @since:			09/28/2013
	* @last modified: 	09/28/2013
	* @called by:
	*/
	public function getUser($id) {
		$user = null
		return $user;
	}
}
?>

Create users table in database

Create users table in database


<?php
$pdo = new PDO('mysql:host=mysql.hostinger.co.uk;dbname=u897984522_immo', 'u897984522_asdev', 'RevoK2016I');

<?php
$pdo = new PDO('mysql:host=localhost;dbname=annahda', 'root', '');

Fix contrat-status issues - Date : 21/11/2016


<?php

declare(strict_types=1);

namespace SitemapPlugin\Generator;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use SitemapPlugin\Factory\SitemapImageUrlFactoryInterface;
use Sylius\Component\Core\Model\ProductImageInterface;
use Sylius\Component\Core\Model\ProductInterface;

final class ProductToImageSitemapArrayGenerator
{
    /** @var CacheManager */
    private $imagineCacheManager;

    /** @var SitemapImageUrlFactoryInterface */
    private $sitemapImageUrlFactory;

    /** @var string */
    private $imagePreset;

    public function __construct(
        SitemapImageUrlFactoryInterface $sitemapImageUrlFactory,
        CacheManager $imagineCacheManager,
        string $imagePreset = 'sylius_shop_product_original'
    ) {
        $this->sitemapImageUrlFactory = $sitemapImageUrlFactory;
        $this->imagineCacheManager = $imagineCacheManager;
        $this->imagePreset = $imagePreset;
    }

    public function generate(ProductInterface $product): array
    {
        $images = [];

        /** @var ProductImageInterface $image */
        foreach ($product->getImages() as $image) {
            if (!$image->hasFile() || !$image->getPath()) {
                continue;
            }

            $sitemapImage = $this->sitemapImageUrlFactory->createNew();
            $sitemapImage->setLocation($this->imagineCacheManager->getBrowserPath($image->getPath(),
                $this->imagePreset));

            $images[] = $sitemapImage;
        }

        return $images;
    }
}

<?php

declare(strict_types=1);

namespace SitemapPlugin\Generator;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use SitemapPlugin\Factory\SitemapImageUrlFactoryInterface;
use Sylius\Component\Core\Model\ProductImageInterface;
use Sylius\Component\Core\Model\ProductInterface;

final class ProductToImageSitemapArrayGenerator
{
    /** @var CacheManager */
    private $imagineCacheManager;

    /** @var SitemapImageUrlFactoryInterface */
    private $sitemapImageUrlFactory;

    /** @var string */
    private $imagePreset;

    public function __construct(
        SitemapImageUrlFactoryInterface $sitemapImageUrlFactory,
        CacheManager $imagineCacheManager,
        string $imagePreset = 'sylius_shop_product_original'
    ) {
        $this->sitemapImageUrlFactory = $sitemapImageUrlFactory;
        $this->imagineCacheManager = $imagineCacheManager;
        $this->imagePreset = $imagePreset;
    }

    public function generate(ProductInterface $product): array
    {
        $images = [];

        /** @var ProductImageInterface $image */
        foreach ($product->getImages() as $image) {
            if (!$image->getPath()) {
                continue;
            }

            $sitemapImage = $this->sitemapImageUrlFactory->createNew();
            $sitemapImage->setLocation($this->imagineCacheManager->getBrowserPath($image->getPath(),
                $this->imagePreset));

            $images[] = $sitemapImage;
        }

        return $images;
    }
}

Add image when path is set, not only when SplInfo is present


  <link rel="shortcut icon" href="<?php echo get_template_directory_uri() ?>/dist/images/favicon-32.png">

  <?php if(get_field('googlesiteverification_id', 'option')) : ?>
    <meta name="googlesiteverification" content="<?php the_field('googlesiteverification_id', 'option'); ?>">
  <?php endif; ?>

  <link rel="shortcut icon" href="<?php echo get_template_directory_uri() ?>/dist/images/favicon-32.png">

  <?php if(get_field('googlesiteverification_id', 'option')) : ?>
    <meta name="google-site-verification" content="<?php the_field('googlesiteverification_id', 'option'); ?>">
  <?php endif; ?>

Fix google site verification meta tag

Fix google site verification meta tag


<?php

require 'check_setup.php';
require 'vendor/password.php';
require 'vendor/PicoTools/Dependency_Injection.php';
require 'vendor/PicoTools/Translator.php';
require 'vendor/PicoDb/Database.php';
require 'vendor/PicoDb/Table.php';
require 'schema.php';
require 'model.php';

const DB_VERSION    = 8;
const APP_VERSION   = 'master';
const APP_USERAGENT = 'Miniflux - http://miniflux.net';
const HTTP_TIMEOUT  = 5;
const LIMIT_ALL     = -1;

function get_db_filename()
{
    return 'data/db.sqlite';
}

PicoTools\container('db', function() {

    $db = new PicoDb\Database(array(
        'driver' => 'sqlite',
        'filename' => get_db_filename()
    ));

    if ($db->schema()->check(DB_VERSION)) {

        return $db;
    }
    else {

        die('Unable to migrate database schema.');
    }
});

<?php

require 'check_setup.php';
require 'vendor/password.php';
require 'vendor/PicoTools/Dependency_Injection.php';
require 'vendor/PicoTools/Translator.php';
require 'vendor/PicoDb/Database.php';
require 'vendor/PicoDb/Table.php';
require 'schema.php';
require 'model.php';

const DB_VERSION    = 8;
const APP_VERSION   = 'master';
const APP_USERAGENT = 'Miniflux - http://miniflux.net';
const HTTP_TIMEOUT  = 10;
const LIMIT_ALL     = -1;

function get_db_filename()
{
    return 'data/db.sqlite';
}

PicoTools\container('db', function() {

    $db = new PicoDb\Database(array(
        'driver' => 'sqlite',
        'filename' => get_db_filename()
    ));

    if ($db->schema()->check(DB_VERSION)) {

        return $db;
    }
    else {

        die('Unable to migrate database schema.');
    }
});

Change default HTTP timeout to 10 seconds


<?php

namespace Ibuildings\QaTools\Core\Application\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

final class InstallCommand extends Command implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    protected function configure()
    {
        $this
            ->setName('install')
            ->setDescription('Setup for the Ibuildings QA-tools')
            ->setHelp('Setup for the Ibuildings QA-tools');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Implementation
    }
}

<?php

namespace Ibuildings\QaTools\Core\Application\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

final class InstallCommand extends Command implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    protected function configure()
    {
        $this
            ->setName('install')
            ->setDescription('Setup for the Ibuildings QA-tools')
            ->setHelp('Setup for the Ibuildings QA-tools');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $questionHandler = $this->container
            ->get('question_handler_factory')
            ->createWith($input, $output);

        $installer = $this->container
            ->get('installer');

        $installer->install($questionHandler);
    }
}

Add installer to install command execution


<?
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedSearchResult {

	public function __construct($id, $name, $description, $score, $cPath, $content) {
		$this->cID = $id;
		$this->cName = $name;
		$this->cDescription = $description;
		$this->score = $score;
		$this->cPath = $cPath;
		$this->content = $content;
		$this->nh = Loader::helper('navigation');
	}

	public function getID() {return $this->cID;}
	public function getName() {return $this->cName;}
	public function getDescription() {return $this->cDescription;}
	public function getScore() {return $this->score;}
	public function getCollectionPath() {return $this->cPath;}
	public function getCpath() {return $this->cPath;}
	public function getBodyContent() {return $this->content;}
	public function getDate($mask = '') {
		if ($mask == '') {
			$mask = t('Y-m-d H:i:s');
		}
		return date($mask, strtotime($this->cDate));
	}
	public function getPath() {
		$c = Page::getByID($this->cID);
		return $this->nh->getLinkToCollection($c, true);
	}

	public function setDate($date) { $this->cDate = $date;}
}

<?
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedSearchResult {

	public function __construct($id, $name, $description, $score, $cPath, $content, $cDatePublic = false) {
		$this->cID = $id;
		$this->cName = $name;
		$this->cDescription = $description;
		$this->score = $score;
		$this->cPath = $cPath;
		$this->content = $content;
		if ($cDatePublic) {
			$this->setDate($cDatePublic);
		}
		$this->nh = Loader::helper('navigation');
	}

	public function getID() {return $this->cID;}
	public function getName() {return $this->cName;}
	public function getDescription() {return $this->cDescription;}
	public function getScore() {return $this->score;}
	public function getCollectionPath() {return $this->cPath;}
	public function getCpath() {return $this->cPath;}
	public function getBodyContent() {return $this->content;}
	public function getDate($mask = '') {
		if ($mask == '') {
			$mask = t('Y-m-d H:i:s');
		}
		return date($mask, strtotime($this->cDate));
	}
	public function getPath() {
		$c = Page::getByID($this->cID);
		return $this->nh->getLinkToCollection($c, true);
	}

	public function setDate($date) { $this->cDate = $date;}
}

Add cDatePublic to indexed search result constructor


<?php
class Kwc_Box_InheritContent_Cc_Component extends Kwc_Chained_Cc_Component
{
    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $ret = Kwc_Abstract::getTemplateVars($renderer);
        $ret['template'] = self::getTemplateFile($this->getData()->chained->componentClass);
        $ret['child'] = $this->_getContentChild();
        return $ret;
    }

    private function _getContentChild()
    {
        $masterChild = $this->getData()->chained->getComponent()->getContentChild();
        $c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
        $page = $this->getData();
        while($c && !$c->hasContent()) {
            while ($page && !$page->inherits) {
                $page = $page->parent;
                if ($page instanceof Kwf_Component_Data_Root) break;
            }
            if (!isset($page->chained)) {
                $c = null;
                break;
            }
            $masterChild = $page->chained->getChildComponent('-'.$this->getData()->id)
                    ->getChildComponent(array('generator' => 'child'));
            $c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
            if ($page instanceof Kwf_Component_Data_Root) break;
            $page = $page->parent;
        }
        return $c;
    }
}

<?php
class Kwc_Box_InheritContent_Cc_Component extends Kwc_Chained_Cc_Component
{
    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $ret = Kwc_Abstract::getTemplateVars($renderer);
        $ret['template'] = self::getTemplateFile($this->getData()->chained->componentClass);
        $ret['child'] = $this->_getContentChild();
        return $ret;
    }

    private function _getContentChild()
    {
        $masterChild = $this->getData()->chained->getComponent()->getContentChild();
        $c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
        $page = $this->getData();
        while($c && !$c->hasContent()) {
            while ($page && !$page->inherits) {
                $page = $page->parent;
                if ($page instanceof Kwf_Component_Data_Root) break;
            }
            if (!isset($page->chained)) {
                $c = null;
                break;
            }
            $masterBox = $page->chained->getChildComponent('-'.$this->getData()->id);
            if (!$masterBox) {
                $c = null;
                break;
            }
            $masterChild = $masterBox->getChildComponent(array('generator' => 'child'));
            $c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
            if ($page instanceof Kwf_Component_Data_Root) break;
            $page = $page->parent;
        }
        return $c;
    }
}

Stop looking up inherited box when box doesn't exist anymore


<?php

declare (strict_types = 1);

namespace HMLB\DDDBundle\Doctrine\ORM\DBAL\Types;

use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use HMLB\DDD\Entity\Identity;

/**
 * IdentityType.
 *
 * @author Hugues Maignol <hugues@hmlb.fr>
 */
class IdentityType extends Type
{
    const NAME = 'ddd_identity';

    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if (null === $value) {
            return;
        }

        return new Identity($value);
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (empty($value)) {
            return;
        }

        if ($value instanceof Identity) {
            return (string) $value;
        }

        throw ConversionException::conversionFailed($value, self::NAME);
    }

    public function getName()
    {
        return self::NAME;
    }
}

<?php

declare (strict_types = 1);

namespace HMLB\DDDBundle\Doctrine\ORM\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
use HMLB\DDD\Entity\Identity;

/**
 * IdentityType.
 *
 * @author Hugues Maignol <hugues@hmlb.fr>
 */
class IdentityType extends Type
{
    const NAME = 'ddd_identity';

    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if (null === $value) {
            return;
        }

        return new Identity($value);
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (empty($value)) {
            return;
        }

        if ($value instanceof Identity) {
            return (string) $value;
        }

        throw ConversionException::conversionFailed($value, self::NAME);
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }

    public function getName()
    {
        return self::NAME;
    }
}

Add comment for identity reverse engineering


<?php

namespace Lighwand\Validate;

use Lighwand\Validate\Loader\VideoLoader;
use Lighwand\Validate\Video\VideoValidator;
use Zend\ServiceManager\Config;
use Zend\ServiceManager\ServiceManager;

try {
    require_once __DIR__ . '/vendor/autoload.php';

    $config = include __DIR__ . '/validate/config.php';
    $serviceManager = new ServiceManager(new Config($config['services']));

    $return = 0;

    $videoValidator = $serviceManager->get(VideoValidator::class);
    $videoFiles = $serviceManager->get(VideoLoader::class)->getFiles();
    foreach ($videoFiles as $file) {
        if (!$videoValidator->isValid($file)) {
            $return = 1;
            echo join(PHP_EOL, $videoValidator->getMessages()) . PHP_EOL;
        }
    }

    return $return;
} catch (\Exception $e) {
    echo $e->getMessage();
    return 1;
}

<?php

namespace Lighwand\Validate;

use Lighwand\Validate\Loader\VideoLoader;
use Lighwand\Validate\Video\VideoValidator;
use Zend\ServiceManager\Config;
use Zend\ServiceManager\ServiceManager;

try {
    require_once __DIR__ . '/vendor/autoload.php';

    $config = include __DIR__ . '/validate/config.php';
    $serviceManager = new ServiceManager(new Config($config['services']));

    $return = 0;

    $videoValidator = $serviceManager->get(VideoValidator::class);
    $videoFiles = $serviceManager->get(VideoLoader::class)->getFiles();
    foreach ($videoFiles as $file) {
        if (!$videoValidator->isValid($file)) {
            $return = 1;
            echo join(PHP_EOL, $videoValidator->getMessages()) . PHP_EOL;
        }
    }

    if ($return === 0) {
        echo 'Everything is valid!' . PHP_EOL;
    } else {
        echo 'Invalid data found.' . PHP_EOL;
    }

    return $return;
} catch (\Exception $e) {
    echo $e->getMessage();
    return 1;
}

Add message to tell if there were errors or not


<?php

declare(strict_types=1);

namespace App\Service;

use Sentry\Tracing\SamplingContext;

class SentryTraceSampler
{
    private const SKIP_ROUTES = ['app_ics_geticsfeed', 'app_download_downloadmaterials'];

    /**
     * Don't sample ICS or LM transactions as they are very noisy
     * everything else we sample 10% of
     */
    public function getTracesSampler(): callable
    {
        return function (SamplingContext $context): float {
            $tags = $context->getTransactionContext()->getTags();
            if (in_array($tags['route'], self::SKIP_ROUTES)) {
                return 0;
            }
            return 0.1;
        };
    }
}

<?php

declare(strict_types=1);

namespace App\Service;

use Sentry\Tracing\SamplingContext;

class SentryTraceSampler
{
    private const SKIP_ROUTES = ['app_ics_geticsfeed', 'app_download_downloadmaterials'];

    /**
     * Don't sample ICS or LM transactions as they are very noisy
     * everything else we sample 10% of
     */
    public function getTracesSampler(): callable
    {
        return function (SamplingContext $context): float {
            $tags = $context->getTransactionContext()->getTags();
            if (array_key_exists('route', $tags) && in_array($tags['route'], self::SKIP_ROUTES)) {
                return 0;
            }
            return 0.1;
        };
    }
}

Fix TraceSampler for Console Commands

Fix TraceSampler for Console Commands

The array key 'route' doesn't always exist which them emits a PHP
warning, fixed with a check.


<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Filesystem\Filesystem;
use Symfony\Component\Yaml\Yaml;

class DevelopersController extends Controller
{
    public function index()
    {
        return view('developers.index');
    }

    public function contact()
    {
        return view('developers.contact');
    }

    public function redirectToIndex()
    {
        return redirect()->route('developers.index');
    }

    public function endpoints(Filesystem $fs)
    {
        $endpoints = Yaml::parse($fs->get('live/endpoints.yml'));

        return view('developers.endpoints', compact('endpoints'));
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Filesystem\Filesystem;
use Symfony\Component\Yaml\Yaml;

class DevelopersController extends Controller
{
    public function index()
    {
        return view('developers.index');
    }

    public function contact()
    {
        return view('developers.contact');
    }

    public function redirectToIndex()
    {
        return redirect()->route('developers.index');
    }

    public function endpoints(Filesystem $fs)
    {
        $endpoints = collect(Yaml::parse($fs->get('live/endpoints.yml')))->sortBy('name');

        return view('developers.endpoints', compact('endpoints'));
    }
}

Sort endpoint listing by name

Sort endpoint listing by name


   home |
   summary |
   nodes |
   info

<?php
session_start();
$verified = $_SESSION['ver'];

echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">

    <title>MUI</title>
    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
    <meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\" />
    <meta http-equiv=\"cache-control\" content=\"no-cache\" />
    <link rel=\"stylesheet\" type=\"text/css\" href=\"style/styles.css\" />
    <link href=\"style/favicon.ico\" rel=\"icon\" type=\"image/x-icon\" />
    <link href=\"style/favicon.ico\" rel=\"shortcut icon\" />

      MUI - This is unsupported software - use at your own risk.

   home |
   summary |
   nodes |
   info |
   logout

";

// If not logged in, request credentials

if ($verified != "true"){
    echo "
<form action=\"login.php\" method=\"POST\" id=\"form1\">

You need to log in to use this site

    Username: 	<input type=\"text\" name=\"username\">

    Password: 	<input type=\"password\" name=\"secret\">

     	<button type=\"submit\" form=\"form1\" value=\"Submit\">Validate</button>

      </form>
    ";
exit(0);
}

Update to add session verification and better menu bar


Fix update version for 0.9.2 -> 0.9.3

Fix update version for 0.9.2 -> 0.9.3


<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		WP_CLI::log( ' - Installing package' );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString();
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Error: %s", $composer_error ) );
			}
		}

	}

}

<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		WP_CLI::log( ' - Installing package' );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString( $event->getPool() );
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Error: %s", $composer_error ) );
			}
		}

	}

}

Fix fatal error when a dependency needs to be installed

```
PHP Catchable fatal error:  Argument 1 passed to
Composer\DependencyResolver\Rule::getPrettyString() must be an instance
of Composer\DependencyResolver\Pool, none given, called in
/home/vagrant/.wp-cli/php/WP_CLI/PackageManagerEventSubscriber.php on
line 40 and defined in
/home/vagrant/.wp-cli/vendor/composer/composer/src/Composer/DependencyResolver/Rule.php
on line 161
```


<?php

use Mdd\QueryBuilder\Type;
use Mdd\QueryBuilder\Types;
use Mdd\QueryBuilder\Conditions;
use Mdd\QueryBuilder\Tests\Escapers\SimpleEscaper;

class EqualTest extends PHPUnit_Framework_TestCase
{
    protected
        $escaper;

    protected function setUp()
    {
        $this->escaper = new SimpleEscaper();
    }

    /**
     * @dataProvider providerTestEqual
     */
    public function testEqual($expected, $column, Type $type)
    {
        $condition = new Conditions\Equal($column, $type);

        $this->assertSame($expected, $condition->toString($this->escaper));
    }

    public function providerTestEqual()
    {
        return array(
            'simple string' => array("name = 'poney'", 'name', new Types\String('poney')),
            'empty string'  => array("name = ''", 'name', new Types\String('')),
            'simple int'    => array("id = 666", 'id', new Types\Integer(666)),
            'empty int'     => array('id = 0', 'id', new Types\Integer('')),
            'empty column name' => array('', '', new Types\String('poney')),
        );
    }
}

<?php

use Mdd\QueryBuilder\Type;
use Mdd\QueryBuilder\Types;
use Mdd\QueryBuilder\Conditions;
use Mdd\QueryBuilder\Tests\Escapers\SimpleEscaper;
use Mdd\QueryBuilder\Types\Datetime;

class EqualTest extends PHPUnit_Framework_TestCase
{
    protected
        $escaper;

    protected function setUp()
    {
        $this->escaper = new SimpleEscaper();
    }

    /**
     * @dataProvider providerTestEqual
     */
    public function testEqual($expected, $column, Type $type)
    {
        $condition = new Conditions\Equal($column, $type);

        $this->assertSame($expected, $condition->toString($this->escaper));
    }

    public function providerTestEqual()
    {
        return array(
            'simple string' => array("name = 'poney'", 'name', new Types\String('poney')),
            'empty string'  => array("name = ''", 'name', new Types\String('')),

            'simple int'    => array("id = 666", 'id', new Types\Integer(666)),
            'empty int'     => array('id = 0', 'id', new Types\Integer('')),

            'simple datetime'    => array("date = '2014-03-07 14:18:42'", 'date', new Types\Datetime('2014-03-07 14:18:42')),
            'empty datetime'     => array("date = ''", 'date', new Types\Datetime('')),

            'empty column name' => array('', '', new Types\String('poney')),
        );
    }
}

Add test for equal condition with datetime type


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

/**
 * @var Composer\Autoload\ClassLoader $loader
 */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '89.3.160.138', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

/**
 * @var Composer\Autoload\ClassLoader $loader
 */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Add ip restriction on dev env

Add ip restriction on dev env


<?php

require __DIR__ . "/_bootstrap.php";

use Amp\Dns;
use Amp\Loop;
use Amp\Promise;

$customConfigLoader = new class implements Dns\ConfigLoader {
    public function loadConfig(): Promise
    {
        return Amp\call(function () {
            $hosts = yield (new Dns\HostLoader)->loadHosts();

            return new Dns\Config([
                "8.8.8.8:53",
                "[2001:4860:4860::8888]:53",
            ], $hosts, $timeout = 5000, $attempts = 3);
        });
    }
};

Dns\resolver(new Dns\Rfc1035StubResolver(null, $customConfigLoader));

Loop::run(function () {
    $hostname = "amphp.org";

    try {
        pretty_print_records($hostname, yield Dns\resolve($hostname));
    } catch (Dns\DnsException $e) {
        pretty_print_error($hostname, $e);
    }
});

<?php

require __DIR__ . "/_bootstrap.php";

use Amp\Dns;
use Amp\Loop;
use Amp\Promise;

$customConfigLoader = new class implements Dns\ConfigLoader {
    public function loadConfig(): Promise
    {
        return Amp\call(function () {
            $hosts = yield (new Dns\HostLoader)->loadHosts();

            return new Dns\Config([
                "8.8.8.8:53",
                "[2001:4860:4860::8888]:53",
            ], $hosts, $timeout = 5000, $attempts = 3);
        });
    }
};

Dns\resolver(new Dns\Rfc1035StubResolver(null, $customConfigLoader));

Loop::run(function () use ($argv) {
    $hostname = $argv[1] ?? "amphp.org";

    try {
        pretty_print_records($hostname, yield Dns\resolve($hostname));
    } catch (Dns\DnsException $e) {
        pretty_print_error($hostname, $e);
    }
});

Allow custom domain in custom config example


<?php namespace Phphub\Presenters;

use Laracasts\Presenter\Presenter;
use Route;

class UserPresenter extends Presenter
{
    /**
     * Present a link to the user gravatar
     */
    public function gravatar($size = 80)
    {
        return cdn('uploads/avatars/' . $this->avatar) . "?imageView2/1/w/{$size}/h/{$size}";
    }

    public function userinfoNavActive($anchor)
    {
        return Route::currentRouteName() == $anchor ? 'active' : '';
    }
}

<?php namespace Phphub\Presenters;

use Laracasts\Presenter\Presenter;
use Route;
use Config;

class UserPresenter extends Presenter
{
    /**
     * Present a link to the user gravatar.
     */
    public function gravatar($size = 80)
    {
        if (Config::get('app.url_static')) {
            //Using Qiniu image processing service.
            return cdn('uploads/avatars/'.$this->avatar)."?imageView2/1/w/{$size}/h/{$size}";
        }

        $github_id = $this->github_id;
        $domainNumber = rand(0, 3);

        return "https://avatars{$domainNumber}.githubusercontent.com/u/{$github_id}?v=2&s={$size}";
    }

    public function userinfoNavActive($anchor)
    {
        return Route::currentRouteName() == $anchor ? 'active' : '';
    }
}

Fix user avatar show error, In local environment.


<?php

define('FLASH_INFO', 'info');
define('FLASH_SUCCESS', 'success');
define('FLASH_WARNING', 'warning');
define('FLASH_ERROR', 'danger');
define('FLASH_KEY', '_fid');

function getFlashParam() {
	static $param;

	if (!isset($param)) {
		$param = isset($_GET[FLASH_KEY]) ? $_GET[FLASH_KEY] : Nette\Utils\Random::generate(4);
	}
	return $param;
}

function getFlashSession() {
	global $App;

	$param = getFlashParam();
	return $App->getService('session')->getSection('Nette.Application.Flash/' . $param);
}

function flashMessage($message, $type = FLASH_INFO) {
	$session = getFlashSession();

	$messages = $session->flash;
	$messages[] = (object) [
		'message' => $message,
		'type' => $type,
	];
	$session->flash = $messages;

	return getFlashParam();
}

function flashInfo($message) {
	return flashMessage($message, FLASH_INFO);
}

function flashSuccess($message) {
	return flashMessage($message, FLASH_SUCCESS);
}

function flashWarning($message) {
	return flashMessage($message, FLASH_WARNING);
}

function flashError($message) {
	return flashMessage($message, FLASH_ERROR);
}

<?php

define('FLASH_INFO', 'info');
define('FLASH_SUCCESS', 'success');
define('FLASH_WARNING', 'warning');
define('FLASH_ERROR', 'danger');
define('FLASH_KEY', '_fid');

function getFlashParam() {
	static $param;

	if (!isset($param)) {
		$param = isset($_GET[FLASH_KEY]) ? $_GET[FLASH_KEY] : Nette\Utils\Random::generate(4);
	}
	return $param;
}

function getFlashSession() {
	global $App;

	$param = getFlashParam();
	$section = $App->getService('session')->getSection('Nette.Application.Flash/' . $param);
	$section->setExpiration('+5 seconds');
	return $section;
}

function flashMessage($message, $type = FLASH_INFO) {
	$session = getFlashSession();

	$messages = $session->flash;
	$messages[] = (object) [
		'message' => $message,
		'type' => $type,
	];
	$session->flash = $messages;

	return getFlashParam();
}

function flashInfo($message) {
	return flashMessage($message, FLASH_INFO);
}

function flashSuccess($message) {
	return flashMessage($message, FLASH_SUCCESS);
}

function flashWarning($message) {
	return flashMessage($message, FLASH_WARNING);
}

function flashError($message) {
	return flashMessage($message, FLASH_ERROR);
}

Set 5s expiration to the flash session

Set 5s expiration to the flash session


<?php
/**
 * SAML 2.0 remote IdP metadata for SimpleSAMLphp.
 *
 * Remember to remove the IdPs you don't use from this file.
 *
 * See: https://simplesamlphp.org/docs/stable/simplesamlphp-reference-idp-remote
 */

/*
 * Guest IdP. allows users to sign up and register. Great for testing!
 */
$metadata['https://openidp.feide.no'] = array(
	'name' => array(
		'en' => 'Feide OpenIdP - guest users',
		'no' => 'Feide Gjestebrukere',
	),
	'description'          => 'Here you can login with your account on Feide RnD OpenID. If you do not already have an account on this identity provider, you can create a new one by following the create new account link and follow the instructions.',

	'SingleSignOnService'  => 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php',
	'SingleLogoutService'  => 'https://openidp.feide.no/simplesaml/saml2/idp/SingleLogoutService.php',
	'certFingerprint'      => 'c9ed4dfb07caf13fc21e0fec1572047eb8a7a4cb'
);

Remove the OpenIdP from remote IdP metadata template.


<?php
return array (
  'app_version' => 'v6.0.11',
  'full_app_version' => 'v6.0.11 - build 8758-g61fa0bda4',
  'build_version' => '8758',
  'prerelease_version' => '',
  'hash_version' => 'g61fa0bda4',
  'full_hash' => 'v6.0.11-145-g61fa0bda4',
  'branch' => 'master',
);

<?php
return array (
  'app_version' => 'v6.0.11',
  'full_app_version' => 'v6.0.11 - build 8758-g61fa0bda4',
  'build_version' => '8758',
  'prerelease_version' => '',
  'hash_version' => 'g61fa0bda4',
  'full_hash' => 'v6.0.11-145-g61fa0bda4',
  'branch' => 'develop',
);

Set branch back to develop

Set branch back to develop

I hads to switch branches because the automated GH action script always targets masterb

Signed-off-by: snipe <e9c017fc53f27c86a4fb6d4f0de7d332b596a185@snipe.net>