<?php

namespace Egzaminer\Question;

use Egzaminer\Model;
use PDO;

class Answers extends Model
{
    public function getAnswersByQuestions($answers)
    {
        $where = '';
        foreach ($answers as $key => $value) {
            $where .= ' OR question_id = :question_id_'.md5($value['id']);
        }

        $stmt = $this->db->prepare('SELECT * FROM answers WHERE '.trim($where, ' OR '));
        foreach ($answers as $key => $value) {
            $stmt->bindValue(':question_id_'.md5($value['id']), $value['id'], PDO::PARAM_INT);
        }

        $stmt->execute();
        $array = [];

        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $key => $value) {
            $array[$value['question_id']][] = $value;
        }

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

        return $array;
    }

    public function getAnswersByOneQuestionId($id)
    {
        $stmt = $this->db->prepare('SELECT * FROM answers WHERE question_id = :qid');
        $stmt->bindValue(':qid', $id, PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

<?php

namespace Egzaminer\Question;

use Egzaminer\Model;
use PDO;

class Answers extends Model
{
    public function getAnswersByQuestions(array $answers)
    {
        if (empty($answers)) {
            return;
        }

        $where = '';
        foreach ($answers as $key => $value) {
            $where .= ' OR question_id = :question_id_'.md5($value['id']);
        }

        $stmt = $this->db->prepare('SELECT * FROM answers WHERE '.trim($where, ' OR '));
        foreach ($answers as $key => $value) {
            $stmt->bindValue(':question_id_'.md5($value['id']), $value['id'], PDO::PARAM_INT);
        }

        $stmt->execute();

        $array = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $key => $value) {
            $array[$value['question_id']][] = $value;
        }

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

        return $array;
    }

    public function getAnswersByOneQuestionId($id)
    {
        $stmt = $this->db->prepare('SELECT * FROM answers WHERE question_id = :qid');
        $stmt->bindValue(':qid', $id, PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

Fix error when no questions

Fix error when no questions


<?php
namespace RDM\Generics;

class TypedArrayObject extends \ArrayObject
{
    private $type;

    /**
     * {@inheritDoc}
     *
     * @param string $type The type of elements the array can contain.
     *                     Can be any of the primitive types or a class name.
     */
    public function __construct($type, $array = array())
    {
        $this->type = $type;
    }
}

<?php
namespace RDM\Generics;

class TypedArrayObject extends \ArrayObject
{
    private $type;

    /**
     * {@inheritDoc}
     *
     * @param string $type The type of elements the array can contain.
     *                     Can be any of the primitive types or a class name.
     */
    public function __construct($type, $array = array())
    {
        $this->type = $type;
    }

    private function isValid($value)
    {
        switch ($this->type) {
            case 'bool':
                return is_bool($value);
            case 'int':
                return is_int($value);
            case 'float':
                return is_float($value);
            case 'string':
                return is_string($value);
            case 'array':
                return is_array($value);
            case 'resource':
                return is_resource($value);
            case 'callable':
                return is_callable($value);
            default:
                return is_a($value, $this->type);
        }
    }

    /**
     * {@inheritDoc}
     *
     * @throws \InvalidArgumentException If the given value was not of the specified type
     */
    public function offsetSet($offset, $value)
    {
        if ($this->isValid($value)) {
            parent::offsetSet($offset, $value);
        } else {
            throw new \InvalidArgumentException('The given value was not of type ' . $this->type);
        }
    }
}

Add type check when adding items to the array


<!doctype html>

    <meta charset="utf-8" />
    <link href="microcms.css" rel="stylesheet" />
    <title>MicroCMS - Home</title>

MicroCMS

    <?php foreach ($articles as $article): ?>

<?php echo $article['art_title'] ?>

<?php echo $article['art_content'] ?>

    <?php endforeach; ?>

        MicroCMS is a minimalistic CMS built as a showcase for modern PHP development.

Fix GitHub link in footer

Fix GitHub link in footer


<?

/*
  This class strictly deals with HTTP requests.
  It has no awareness of object classes and uses primitive types and arrays.
*/

class HTTP {
  // Retrieves the body of a post request and returns it as an associative array.
  public static function getJsonPost () {
    $raw = file_get_contents("php://input");
    $json = json_decode($raw, true);
    return $json;
  }
}
?>

<?php

/*
  This class strictly deals with HTTP requests.
  It has no awareness of object classes and uses primitive types and arrays.
*/

class HTTP {
  // Retrieves the body of a post request and returns it as an associative array.
  public static function getJsonPost () {
    $raw = file_get_contents("php://input");
    $json = json_decode($raw, true);
    return $json;
  }
}
?>

Fix php template error in HTTP class

Fix php template error in HTTP class


<?php namespace Inkwell\HTML
{
	class esc
	{
		public function __invoke($data)
		{
			return is_string($data)
				? html::out(htmlspecialchars($data, ENT_HTML5), 'esc')
				: $data;
		}
	}
}

<?php namespace Inkwell\HTML
{
	class esc
	{
		public function __invoke($data)
		{
			return is_string($data)
				? html::out(htmlspecialchars($data, ENT_HTML5 | ENT_QUOTES), 'esc')
				: $data;
		}
	}
}

Convert quotes, useful for data- attributes


<?
include_once("include/passwd.php");
pg_connect($pgconnstr);

Header("Content-Type: text/html; charset=utf-8");

if (!isset($_GET["title"])) {
  print "Обязательный параметр title не определён!";
  exit;
}

$title = $_GET["title"];
if (isset($_GET["js"]) && $_GET["js"]) $title = urldecode($title);
$title = preg_replace("@^http://commons\.wikimedia\.org/wiki/@", "", $title);
$title = preg_replace("@\?.+$@", "", $title);
if (!preg_match("@^File:@", $title)) {
  print "Страница $title не является страницей описания картинки";
  exit;
}

$query = "INSERT INTO wpc_req (page, added) VALUES ('".pg_escape_string($title)."', NOW())";
$res = pg_query($query);

print "Страница $title добавлена в очередь на обновление";
?>

<?
include_once("include/passwd.php");
pg_connect($pgconnstr);

Header("Content-Type: text/html; charset=utf-8");

if (!isset($_GET["title"])) {
  print "Обязательный параметр title не определён!";
  exit;
}

$title = $_GET["title"];
if (isset($_GET["js"]) && $_GET["js"]) $title = urldecode($title);
$title = preg_replace("@^http://commons\.wikimedia\.org/wiki/@", "", $title);
$title = preg_replace("@\?.+$@", "", $title);
$title = preg_replace("@#.+$@", "", $title);
if (!preg_match("@^File:@", $title)) {
  print "Страница $title не является страницей описания картинки";
  exit;
}

$query = "INSERT INTO wpc_req (page, added) VALUES ('".pg_escape_string($title)."', NOW())";
$res = pg_query($query);

print "Страница $title добавлена в очередь на обновление";
?>

Fix bug with hash-ref url

Fix bug with hash-ref url


<?php
$sector =& $player->getSector();

$template->assign('PageTopic','Military Payment Center');

require_once(get_file_loc('menu.inc'));
if ($sector->hasHQ())
	create_hq_menu();
else
	create_ug_menu();

if ($player->hasMilitaryPayment()) {
	$PHP_OUTPUT.=('For your military help you have been paid '.number_format($player->getMilitaryPayment()).' credits');

	$player->increaseHOF($player->getMilitaryPayment(),array('Military Payment','Money','Claimed'), HOF_PUBLIC);

	// add to our cash
	$player->increaseCredits($player->getMilitaryPayment());
	$player->setMilitaryPayment(0);
	$player->update();

} else
	$PHP_OUTPUT.=('You have done nothing worthy of military payment');

?>

<?php
$sector =& $player->getSector();

$template->assign('PageTopic','Military Payment Center');

require_once(get_file_loc('menu.inc'));
if ($sector->hasHQ())
	create_hq_menu();
else
	create_ug_menu();

// We can only claim the payment once, so to prevent clobbering the message
// upon AJAX refresh, we store it as a session variable when we first get it.
if(!isset($var['ClaimText'])) {
	if ($player->hasMilitaryPayment()) {
		$payment = $player->getMilitaryPayment();
		$player->increaseHOF($payment, array('Military Payment','Money','Claimed'), HOF_PUBLIC);

		// add to our cash
		$player->increaseCredits($payment);
		$player->setMilitaryPayment(0);
		$player->update();

		$claimText = ('For your military activity you have been paid '.number_format($payment).' credits.');
	} else {
		$claimText = ('You have done nothing worthy of military payment.');
	}

	SmrSession::updateVar('ClaimText', $claimText);
}

$PHP_OUTPUT .= $var['ClaimText'];

?>

Fix AJAX clearing military payment message prematurely

Follow the protocol in bounty_claim.php for storing a message from
a one-time transaction (in this case, claiming military payment)
so that it can correctly remain on the screen when AJAX refreshes.

Without this fix, the message about claimed military payment is
immediately replaced with the message that there is no military
payment to claim.


<?php
/**
 * Return latest API version
 *
 * @author     Knut Kohl <github@knutkohl.de>
 * @copyright  2012-2014 Knut Kohl
 * @license    MIT License (MIT) http://opensource.org/licenses/MIT
 * @version    1.0.0
 */

Header('Content-Type: text/plain');

die(file_get_contents('..'.DIRECTORY_SEPARATOR.'.latest'));

<?php
/**
 * Return latest API version
 *
 * @author     Knut Kohl <github@knutkohl.de>
 * @copyright  2012-2014 Knut Kohl
 * @license    MIT License (MIT) http://opensource.org/licenses/MIT
 * @version    1.0.0
 */

Header('Content-Type: text/plain');

$c = file_get_contents('..'.DIRECTORY_SEPARATOR.'latest'.DIRECTORY_SEPARATOR.'index.php');

preg_match('~latest.*(r\d+)~', $c, $args);

die($args[1]);

Fix readout of latest API version

Fix readout of latest API version


<?php

/*
 * This file is part of Laravel Carriers.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * This file is part of Laravel Carriers.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BrianFaust\Carriers;

use BrianFaust\Carriers\Console\SeedCarriers;
use BrianFaust\ServiceProvider\ServiceProvider;

class CarriersServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot(): void
    {
        $this->publishMigrations();
    }

    /**
     * Register the application services.
     */
    public function register(): void
    {
        parent::register();

        $this->commands(SeedCarriers::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides(): array
    {
        return array_merge(parent::provides(), [
            SeedCarriers::class,
        ]);
    }

    /**
     * Get the default package name.
     *
     * @return string
     */
    public function getPackageName(): string
    {
        return 'carriers';
    }
}

<?php

/*
 * This file is part of Laravel Carriers.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * This file is part of Laravel Carriers.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BrianFaust\Carriers;

use BrianFaust\Carriers\Console\SeedCarriers;
use BrianFaust\ServiceProvider\AbstractServiceProvider;

class CarriersServiceProvider extends AbstractServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot(): void
    {
        $this->publishMigrations();
    }

    /**
     * Register the application services.
     */
    public function register(): void
    {
        parent::register();

        $this->commands(SeedCarriers::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides(): array
    {
        return array_merge(parent::provides(), [
            SeedCarriers::class,
        ]);
    }

    /**
     * Get the default package name.
     *
     * @return string
     */
    public function getPackageName(): string
    {
        return 'carriers';
    }
}

Fix extending service provider name

Fix extending service provider name


<?php
/**
 * definition of class ServiceTestBase
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\test
 */

namespace justso\justapi\test;

use justso\justapi\RequestHelper;

/**
 * Base class for service tests
 *
 * @package    justso\test
 */
class ServiceTestBase extends \PHPUnit_Framework_TestCase
{
    /**
     * Asserts that a JSON header is sent.
     *
     * @param TestEnvironment $environment
     */
    protected function assertJSONHeader(TestEnvironment $environment)
    {
        $header = array(
            'HTTP/1.0 200 Ok',
            'Content-Type: application/json; charset=utf-8',
        );
        $this->assertEquals($header, $environment->getResponseHeader());
    }

    /**
     * Sets up a test environment.
     *
     * @param array $params
     * @param array $header
     * @return TestEnvironment
     */
    protected function createTestEnvironment(array $params = array(), array $header = array())
    {
        $request = new RequestHelper();
        $request->fillWithData($params, array('HTTP_HOST' => 'localhost'));
        return new TestEnvironment($request, $header);
    }

}

<?php
/**
 * definition of class ServiceTestBase
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\test
 */

namespace justso\justapi\test;

use justso\justapi\Bootstrap;
use justso\justapi\RequestHelper;

/**
 * Base class for service tests
 *
 * @package    justso\test
 */
class ServiceTestBase extends \PHPUnit_Framework_TestCase
{
    /**
     * Asserts that a JSON header is sent.
     *
     * @param TestEnvironment $environment
     */
    protected function assertJSONHeader(TestEnvironment $environment)
    {
        $header = array(
            'HTTP/1.0 200 Ok',
            'Content-Type: application/json; charset=utf-8',
        );
        $this->assertEquals($header, $environment->getResponseHeader());
    }

    /**
     * Sets up a test environment.
     *
     * @param array $params
     * @param array $header
     * @return TestEnvironment
     */
    protected function createTestEnvironment(array $params = array(), array $header = array())
    {
        $request = new RequestHelper();
        $request->fillWithData($params, array('HTTP_HOST' => 'localhost'));
        return new TestEnvironment($request, $header);
    }

    /**
     * Reset configuration after tests.
     */
    protected function tearDown()
    {
        parent::tearDown();
        Bootstrap::getInstance()->resetConfiguration();
    }

}

Reset configuration after service tests

Reset configuration after service tests


<?php
namespace Consolidation\OutputFormatters\Formatters;

use Symfony\Component\Yaml\Dumper;
use Consolidation\OutputFormatters\FormatterInterface;
use Symfony\Component\Console\Output\OutputInterface;

class YamlFormatter implements FormatterInterface
{
    /**
     * @inheritdoc
     */
    public function write(OutputInterface $output, $data, $options = [])
    {
        $dumper = new Dumper();
        // Set Yaml\Dumper's default indentation for nested nodes/collections to
        // 2 spaces for consistency with Drupal coding standards.
        $dumper->setIndentation(2);
        // The level where you switch to inline YAML is set to PHP_INT_MAX to
        // ensure this does not occur.
        $output->writeln($dumper->dump($data, PHP_INT_MAX, null, null, true));
    }
}

<?php
namespace Consolidation\OutputFormatters\Formatters;

use Symfony\Component\Yaml\Yaml;
use Consolidation\OutputFormatters\FormatterInterface;
use Symfony\Component\Console\Output\OutputInterface;

class YamlFormatter implements FormatterInterface
{
    /**
     * @inheritdoc
     */
    public function write(OutputInterface $output, $data, $options = [])
    {
        // Set Yaml\Dumper's default indentation for nested nodes/collections to
        // 2 spaces for consistency with Drupal coding standards.
        $indent = 2;
        // The level where you switch to inline YAML is set to PHP_INT_MAX to
        // ensure this does not occur.
        $output->writeln(Yaml::dump($data, PHP_INT_MAX, $indent, false, true));
    }
}

Clean up use of Symfony yaml dumper.

Clean up use of Symfony yaml dumper.


<?php

class CustomMenu extends Extension {

	public function CustomMenu($slug = NULL) {

		if ($slug != NULL) {

			if ($Menu = Menu::get()->filter('Slug', $slug)->First()) {
				return $Menu->MenuItems();
			} else {
				return NULL;
			}

		}

	}

}

<?php

class CustomMenu extends Extension {

	public function CustomMenu($slug = NULL) {

		if ($slug != NULL) {

			if ($menu = $this->getMenu($slug)) {
				return $menu->MenuItems();
			} else {
				return NULL;
			}

		}

	}

	public function CustomMenuTitle($slug = NULL) {

		if ($slug != NULL) {
			if ($menu = $this->getMenu($slug)) {
				return $menu->Name;
			} else {
				return NULL;
			}
		}
	}

	private function getMenu($slug) {
		return Menu::get()->filter('Slug', $slug)->First();
	}

}

Add method to get menu title from CMS.

Add method to get menu title from CMS.


<?php

namespace OpenCFP\Domain\Model;

use OpenCFP\Domain\Services\AirportInformationDatabase;

class Airport extends Eloquent implements AirportInformationDatabase
{
    protected $table = 'airports';
    public $timestamps = false;

    /**
     * @param string $code the IATA Airport Code to get information for
     *
     * @return Airport
     * @throws \Exception
     */
    public function withCode($code): self
    {
        $airport = $this->where('code', $code)->first(['code', 'name', 'country']);

        if (!$airport) {
            throw new \Exception("An airport matching '{$code}' was not found.");
        }
        return $airport;
    }
}

<?php

namespace OpenCFP\Domain\Model;

use OpenCFP\Domain\Services\AirportInformationDatabase;

class Airport extends Eloquent implements AirportInformationDatabase
{
    protected $table = 'airports';
    public $timestamps = false;

    /**
     * @param string $code the IATA Airport Code to get information for
     *
     * @return self
     * @throws \Exception
     */
    public function withCode($code): self
    {
        $airport = $this->where('code', $code)->first(['code', 'name', 'country']);

        if (!$airport) {
            throw new \Exception("An airport matching '{$code}' was not found.");
        }
        return $airport;
    }
}

Update doc blocks in the airport model

Update doc blocks in the airport model


<?php namespace Modules\Menu\Providers;

use Illuminate\Support\ServiceProvider;
use Modules\Menu\Entities\Menu;
use Modules\Menu\Entities\Menuitem;
use Modules\Menu\Repositories\Eloquent\EloquentMenuItemRepository;
use Modules\Menu\Repositories\Eloquent\EloquentMenuRepository;

class MenuServiceProvider extends ServiceProvider
{

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->booted(function () {
            $this->registerBindings();
        });
    }

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

    /**
     * Register class binding
     */
    private function registerBindings()
    {
        $this->app->bind(
            'Modules\Menu\Repositories\MenuRepository',
            function() {
                return new EloquentMenuRepository(new Menu);
            }
        );
        $this->app->bind(
            'Modules\Menu\Repositories\MenuItemRepository',
            function() {
                return new EloquentMenuItemRepository(new Menuitem);
            }
        );
    }

}

<?php namespace Modules\Menu\Providers;

use Illuminate\Support\ServiceProvider;
use Modules\Menu\Entities\Menu;
use Modules\Menu\Repositories\Eloquent\EloquentMenuRepository;

class MenuServiceProvider extends ServiceProvider
{

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->booted(function () {
            $this->registerBindings();
        });
    }

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

    /**
     * Register class binding
     */
    private function registerBindings()
    {
        $this->app->bind(
            'Modules\Menu\Repositories\MenuRepository',
            function() {
                return new EloquentMenuRepository(new Menu);
            }
        );
    }

}

Move the menu item registration to the core provider


<?php

use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\form\ActiveForm;

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

    <?php $form = ActiveForm::begin(); ?>

            <?= $form->field($model, 'mark_disk_color')->dropDownList(frontend\models\Status::dropDown($model->tableName(),'mark_disk_color'),['maxlength' => true]) ?>

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

    <?= $form->field($model, 'variety')->textInput(['maxlength' => true]) ?>

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

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

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

    <?= $form->field($model, 'matting_box_id')->textInput(['maxlength' => true]) ?>

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

        <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>

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

Repair some merge errors before do somethink.


<?php
    class BotController extends ControllerBase {
        public function update( $boturl = '' ) {
            require_once 'models/curl.php';
            require_once 'models/grader/bot.php';
            if ( empty( $boturl ) ) {
                go( 'bot', 'update', [ 'boturl_empty' => true ] );
            }
            if ( isset( $_SESSION[ 'user' ] ) ) {
                $user = $_SESSION[ 'user' ];
            }
            $user->boturl = $boturl;
            $bot = new GraderBot( $user );
            try {
                $bot->sendInitiateRequest();
            }
            catch ( GraderBotException $e ) {
                $error = end( $bot->errors );
                $error = str_replace( "initiate_", "", $error );
                if ( strpos( $error, '_not_set' ) ) {
                    $error = 'invalid_json_dictionary';
                }
                go( 'bot', 'update', [ 'bot_not_success' => true, 'error' => $error ] );
            }
            $user->save();
            go( 'bot', 'update', [ 'bot_success' => true ] );
        }
        public function updateView( $boturl_empty, $boturl_invalid, $bot_success, $bot_not_success, $error ) {
            require_once 'views/bots/update.php';
        }
    }
?>

<?php
    class BotController extends ControllerBase {
        public function update( $boturl = '' ) {
            require_once 'models/curl.php';
            require_once 'models/grader/bot.php';
            if ( empty( $boturl ) ) {
                go( 'bot', 'update', [ 'boturl_empty' => true ] );
            }
            if ( !filter_var( $boturl, FILTER_VALIDATE_URL ) ) {
                go( 'bot', 'update', [ 'boturl_invalid' => true ] );
            }
            if ( isset( $_SESSION[ 'user' ] ) ) {
                $user = $_SESSION[ 'user' ];
            }
            $user->boturl = $boturl;
            $bot = new GraderBot( $user );
            try {
                $bot->sendInitiateRequest();
            }
            catch ( GraderBotException $e ) {
                $error = end( $bot->errors );
                $error = str_replace( "initiate_", "", $error );
                if ( strpos( $error, '_not_set' ) ) {
                    $error = 'invalid_json_dictionary';
                }
                go( 'bot', 'update', [ 'bot_not_success' => true, 'error' => $error ] );
            }
            $user->save();
            go( 'bot', 'update', [ 'bot_success' => true ] );
        }
        public function updateView( $boturl_empty, $boturl_invalid, $bot_success, $bot_not_success, $error ) {
            require_once 'views/bots/update.php';
        }
    }
?>

Add valid http url validation

Add valid http url validation


<!DOCTYPE html>

        <title>Budget</title>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli:300,300i" />
        <link rel="stylesheet" href="/style.css" />

                        Dashboard

                        Settings

            @yield('body')

<!DOCTYPE html>

        <title>Budget</title>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli:300,300i" />
        <link rel="stylesheet" href="/style.css" />

                        Dashboard

                        Settings

                        Log out

            @yield('body')

Add log out to navigation

Add log out to navigation


<?php

namespace App\Http\Controllers;

use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;

class Purchases extends Controller
{

    /**
     * Purchase book and generate invoice.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request) {
        $purchaseService = new Purchase();
        $book = Invoice::find($request->input('book_id'));
        $purchaseResult = $purchaseService->purchaseBook($book,$request->input('qty'));

        return $purchaseResult;
    }
}

<?php

namespace App\Http\Controllers;

use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;

class Purchases extends Controller
{

    /**
     * Purchase book and generate invoice.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request) {
        $invoice = null;
        $purchaseService = new Purchase();
        $purchaseQty = $request->input('qty');
        $book = Invoice::find($request->input('book_id'));
        $purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);

        if($purchasePrice !== null) {
            $invoice = new Invoice();
            $invoice->book_id = $book->id;
            $invoice->amount = $purchasePrice;
            $invoice->qty = $purchaseQty;
            $invoice->created_at = date('Y-m-d H:i:s');
            $invoice->updated_at = date('Y-m-d H:i:s');
            $invoice->save();
        }

        return $invoice;
    }
}

Add purchase functionality in back-end.

Add purchase functionality in back-end.


<?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{
    protected function initialize()
    {
        $this->tag->prependTitle('FoxPaste - ');
        $this->view->setTemplateAfter('main');
    }
}

<?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{
    protected function initialize()
    {
        $this->tag->prependTitle($this->conf->app->name . ' | ');
        $this->view->setTemplateAfter('main');
    }
}

Update title to use app config

Update title to use app config


<?php

namespace App\Model\Repository;

use Nette;
use DateTime;
use Kdyby\Doctrine\EntityManager;

use App\Model\Entity\Role;

class Roles extends BaseRepository {

  public function __construct(EntityManager $em) {
    parent::__construct($em, Role::CLASS);
  }

  public function findLowestLevelRoles() {
    return $this->repository->findBy([ "parentRole" => NULL ]);
  }

}

<?php

namespace App\Model\Repository;

use Nette;
use DateTime;
use Kdyby\Doctrine\EntityManager;

use App\Model\Entity\Role;

class Roles extends BaseRepository {

  public function __construct(EntityManager $em) {
    parent::__construct($em, Role::CLASS);
  }

  public function findLowestLevelRoles() {
    return $this->roles->findBy([ "parentRole" => NULL ]);
  }

}

Revert "Bux in variable name"

Revert "Bux in variable name"

In favour of 3564cc2bfffac78fd7f85f1f2cd9bfbbaa45bf6e.

This reverts commit b57c8258a0932719143c9205b411524e8c4d006d.


<?php
declare(strict_types=1);

namespace Tests\Plugin\Prophecy\Token;

use Moka\Plugin\Prophecy\Token\AbstractPriorityToken;

/**
 * Class UnsaltedPriorityToken
 * @package Tests\Plugin\Prophecy\Token
 */
class UnsaltedPriorityToken extends AbstractPriorityToken
{
    /**
     * UnsaltedPriorityToken constructor.
     */
    public function __construct()
    {
        // No call to parent::__construct().
    }

    /**
     * @return int
     */
    protected function getPriority(): int
    {
        return 0;
    }
}

<?php
declare(strict_types=1);

namespace Tests\Plugin\Prophecy\Token;

use Moka\Plugin\Prophecy\Token\AbstractPriorityToken;

class UnsaltedPriorityToken extends AbstractPriorityToken
{
    public function __construct()
    {
        // No call to parent::__construct().
    }

    protected function getPriority(): int
    {
        return 0;
    }
}

Remove comments from test class

Remove comments from test class


<?php
/**
 * Interface for JiraWebhookData converters.
 *
 * @credits https://github.com/kommuna
 * @author  chewbacca@devadmin.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JiraWebhook;

use JiraWebhook\Models\JiraWebhookData;

interface JiraWebhookDataConverter
{
    /**
     * Convert $data into message
     *
     * @param JiraWebhookData $data parsed data from JIRA webhook
     *
     * @return mixed
     */
    public function convert(JiraWebhookData $data);
}

<?php
/**
 * Interface for JiraWebhookData converters.
 *
 * @credits https://github.com/kommuna
 * @author  chewbacca@devadmin.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JiraWebhook;

use JiraWebhook\Models\JiraWebhookData;
use Maknz\Slack\Message;

interface JiraWebhookDataConverter
{
    /**
     * Convert $data into a Slack Client Instance
     *
     * @param JiraWebhookData $data parsed data from JIRA webhook
     * @param Message $message Slack Client Message instance
     *
     * @return Message
     */
    public function convert(JiraWebhookData $data, Message $message);
}

Update the interface with the Message client parameter


<?php

namespace LeKoala\DebugBar\Proxy;

use SilverStripe\Config\Collections\CachedConfigCollection;

class ConfigManifestProxy extends CachedConfigCollection
{
    /**
     * @var CachedConfigCollection
     */
    protected $parent;

    /**
     * @var array
     */
    protected static $configCalls = [];

    /**
     * @param ConfigCollectionInterface $parent
     */
    public function __construct(CachedConfigCollection $parent)
    {
        $this->parent = $parent;

        $this->collection = $this->parent->getCollection();
        $this->cache = $this->parent->getCache();
        $this->flush = $this->parent->getFlush();
        $this->collectionCreator = $this->parent->getCollectionCreator();
    }

    /**
     * Monitor calls made to get configuration during a request
     *
     * {@inheritDoc}
     */
    public function get($class, $name = null, $excludeMiddleware = 0)
    {
        $result = parent::get($class, $name, $excludeMiddleware);

        if (!isset(self::$configCalls[$class][$name])) {
            self::$configCalls[$class][$name] = [
                'calls' => 0,
                'result' => null
            ];
        }
        self::$configCalls[$class][$name]['calls']++;
        self::$configCalls[$class][$name]['result'] = $result;

        return $result;
    }

    /**
     * Return a list of all config calls made during the request, including how many times they were called
     * and the result
     *
     * @return array
     */
    public static function getConfigCalls()
    {
        return self::$configCalls;
    }
}

<?php

namespace LeKoala\DebugBar\Proxy;

use SilverStripe\Config\Collections\CachedConfigCollection;

class ConfigManifestProxy extends CachedConfigCollection
{
    /**
     * @var CachedConfigCollection
     */
    protected $parent;

    /**
     * @var array
     */
    protected static $configCalls = [];

    /**
     * @param CachedConfigCollection $parent
     */
    public function __construct(CachedConfigCollection $parent)
    {
        $this->parent = $parent;

        $this->collection = $this->parent->getCollection();
        $this->cache = $this->parent->getCache();
        $this->flush = $this->parent->getFlush();
        $this->collectionCreator = $this->parent->getCollectionCreator();
    }

    /**
     * Monitor calls made to get configuration during a request
     *
     * {@inheritDoc}
     */
    public function get($class, $name = null, $excludeMiddleware = 0)
    {
        $result = parent::get($class, $name, $excludeMiddleware);

        if (!isset(self::$configCalls[$class][$name])) {
            self::$configCalls[$class][$name] = [
                'calls' => 0,
                'result' => null
            ];
        }
        self::$configCalls[$class][$name]['calls']++;
        self::$configCalls[$class][$name]['result'] = $result;

        return $result;
    }

    /**
     * Return a list of all config calls made during the request, including how many times they were called
     * and the result
     *
     * @return array
     */
    public static function getConfigCalls()
    {
        return self::$configCalls;
    }
}

Update PHPDoc on config manifest proxy constructor


<?php
use Eris\Generator;

require __DIR__.'/../vendor/autoload.php';

$eris = new Eris\Facade();
$eris
    ->forAll(Generator\int())
    ->then(function ($integer) {
        var_dump($integer);
    });

<?php
use Eris\Generator;

require __DIR__.'/../vendor/autoload.php';

$eris = new Eris\Facade();
$eris
    ->forAll(Generator\int())
    ->then(function ($integer) {
        echo var_export($integer, true) . PHP_EOL;
    });

Update example to output a single line on PHP 7.2

Somewhere in the development leading up to PHP 7.2, var_dump()
started outputting the file and line number as part of it's output.
This causes one of the end-to-end tests to fail as the example script
it uses outputs twice as many lines as expected.

This fixes this by using var_export() and a little wrapping to output
useful debug data if something goes wrong and sensible output
otherwise.


<?php

use Galahad\LaravelAddressing\Country;

/**
 * Class AdministrativeAreaTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class AdministrativeAreaTest extends PHPUnit_Framework_TestCase
{
    public function testMinasGeraisStateInBrazil()
    {
        $country = new Country;
        $brazil = $country->getByCode('BR');
        $minasGerais = $brazil->getAdministrativeAreas()->getByCode('MG');

        $this->assertEquals($minasGerais->getName(), 'Minas Gerais');
    }

    public function testAlabamaCodeByName()
    {
        $country = new Country;
        $us = $country->getByCode('US');
        $alabama = $us->getAdministrativeAreas()->getByName('Alabama');
        $alabama2 = $us->states()->name('Alabama');

        $this->assertEquals($alabama->getCode(), 'AL');
        $this->assertEquals($alabama2->getCode(), 'AL');
    }
}

<?php

use Galahad\LaravelAddressing\Country;
use Galahad\LaravelAddressing\LaravelAddressing;

/**
 * Class AdministrativeAreaTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class AdministrativeAreaTest extends PHPUnit_Framework_TestCase
{
    public function testMinasGeraisStateInBrazil()
    {
        $country = new Country;
        $brazil = $country->getByCode('BR');
        $minasGerais = $brazil->getAdministrativeAreas()->getByCode('MG');

        $this->assertEquals($minasGerais->getName(), 'Minas Gerais');
    }

    public function testAlabamaCodeByName()
    {
        $country = new Country;
        $us = $country->getByCode('US');
        $alabama = $us->getAdministrativeAreas()->getByName('Alabama');
        $alabama2 = $us->states()->name('Alabama');

        $this->assertEquals($alabama->getCode(), 'AL');
        $this->assertEquals($alabama2->getCode(), 'AL');
    }

    public function testGetMagicMethod()
    {
        $maker = new LaravelAddressing();
        $firstState = $maker->country('US')->states()->getByKey(0);

        $this->assertEquals($firstState->name, 'Alabama');
    }
}

Add test for __get magic method in AdministrativeArea class


<?php

/**
 * Autoloaded file to handle deprecation such as class aliases.
 *
 * NOTE:
 * If for any reason arrays are required in this file, only ever use array()
 * syntax to prevent breakage on PHP < 5.4 and allow the legacy warnings.
 */

// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');

<?php

/**
 * Autoloaded file to handle deprecation such as class aliases.
 *
 * NOTE:
 * If for any reason arrays are required in this file, only ever use array()
 * syntax to prevent breakage on PHP < 5.4 and allow the legacy warnings.
 */

// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Legacy\Content', '\Bolt\Content');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');

Add deprecation class alias for Bolt\Content


<?php

return [
    'itemsPerPage'   => 100,
    'rootURL'        => 'api/oparl/v1/',
    'modelNamespace' => 'OParl\\Server\\Model\\',

    'transformers' => [
        'serializer' => OParl\Server\API\Serializer::class,

        'namespace'    => 'OParl\\Server\\API\\Transformers',
        'classPattern' => '[:modelName]Transformer',

        'formatHelpers' => [
            'email'    => 'EFrane\Transfugio\Transformers\Formatter\EMailURI',
            'date'     => 'EFrane\Transfugio\Transformers\Formatter\DateISO8601',
            'datetime' => 'EFrane\Transfugio\Transformers\Formatter\DateTimeISO8601',
            'url'      => 'EFrane\Transfugio\Transformers\Formatter\HttpURI',
        ],

        'recursionLimit' => 2,
    ],

    'http' => [
        'format'     => 'json_accept',
        'enableCORS' => true,
    ],

    'web' => [
        'documentationEnabled' => true, // Toggle the auto-documentation feature

        'documentationType' => 'JSONSchema',
        'documentationRoot' => '/storage/app/hub_sync/oparl_spec/schema/',
    ],
];

<?php

return [
    'itemsPerPage'   => 100,
    'rootURL'        => 'api/oparl/v1/',
    'modelNamespace' => 'OParl\\Server\\Model\\',

    'transformers' => [
        'serializer' => OParl\Server\API\Serializer::class,

        'namespace'    => 'OParl\\Server\\API\\Transformers',
        'classPattern' => '[:modelName]Transformer',

        'formatHelpers' => [
            'email'    => 'EFrane\Transfugio\Transformers\Formatter\EMailURI',
            'date'     => 'EFrane\Transfugio\Transformers\Formatter\DateISO8601',
            'datetime' => 'EFrane\Transfugio\Transformers\Formatter\DateTimeISO8601',
            'url'      => 'EFrane\Transfugio\Transformers\Formatter\HttpURI',
        ],

        'recursionLimit' => 2,
    ],

    'http' => [
        'format'     => 'json_accept',
        'enableCORS' => true,
    ],

    'web' => [
        'documentationEnabled' => true, // Toggle the auto-documentation feature

        'documentationType' => 'JSONSchema',
        'documentationRoot' => '/storage/app/schema/1.0',
    ],
];

Fix schema version for api demo

Fix schema version for api demo


<?php

namespace Rudolf\Alerts;

class AlertsCollection {

	/**
	 * @var array
	 */
	private $collection;

	/**
	 * Add alert to collection
	 *
	 * @param Alert $alert Alert object
	 *
	 * @return void
	 */
	public function add(Rudolf\Alerts\Alert $alert) {
		$this->collection[] = $alert;
	}

	/**
	 * Get alerts by type
	 *
	 * @param string $type Alert type
	 *
	 * @return Alert array
	 */
	public function getByType($type) {
		$collection = $this->collection;

		foreach ($this->collection as $key => $value) {
			if($type === $value->getType()) {
				$newCollection[] = $value;
			}
		}

		return $newCollection;
	}

	/**
	 * Get all alerts
	 *
	 * @return Alert array
	 */
	public function getAll() {
		return $this->collection;
	}
}

<?php

namespace Rudolf\Alerts;

class AlertsCollection {

	/**
	 * @var array
	 */
	private static $collection;

	/**
	 * Add alert to collection
	 *
	 * @param Alert $alert Alert object
	 *
	 * @return void
	 */
	public static function add(\Rudolf\Alerts\Alert $alert) {
		self::$collection[] = $alert;
	}

	/**
	 * Get alerts by type
	 *
	 * @param string $type Alert type
	 *
	 * @return Alert array
	 */
	public static function getByType($type) {
		$collection = self::$collection;

		foreach (self::$collection as $key => $value) {
			if($type === $value->getType()) {
				$newCollection[] = $value;
			}
		}

		return $newCollection;
	}

	/**
	 * Get all alerts
	 *
	 * @return Alert array
	 */
	public static function getAll() {
		return self::$collection;
	}
}

Change function and vars to static

Change function and vars to static


<?php

namespace allejo\DaPulse\Objects;

/**
 * Class PulseColumnTextValue
 *
 * @internal
 * @package allejo\DaPulse\Objects
 */
class PulseColumnDateValue extends PulseColumnValue
{
    public function getValue ()
    {
        if (!isset($this->column_value))
        {
            $this->column_value = new DateTime($this->jsonResponse["value"]);
        }

        return $this->column_value;
    }

    /**
     * @param \DateTime $dateTime
     */
    public function updateValue ($dateTime)
    {
        $url = sprintf("%s/%d/columns/%s/text.json", parent::apiEndpoint(), $this->board_id, $this->column_id);
        $postParams = array(
            "pulse_id" => $this->pulse_id,
            "date_str" => date_format($dateTime, "Y-m-d")
        );

        self::sendPut($url, $postParams);

        $this->column_value = $dateTime;
    }
}

<?php

namespace allejo\DaPulse\Objects;

/**
 * Class PulseColumnTextValue
 *
 * @internal
 * @package allejo\DaPulse\Objects
 */
class PulseColumnDateValue extends PulseColumnValue
{
    public function getValue ()
    {
        if (!isset($this->column_value))
        {
            $this->column_value = new DateTime($this->jsonResponse["value"]);
        }

        return $this->column_value;
    }

    /**
     * @param \DateTime $dateTime
     */
    public function updateValue ($dateTime)
    {
        $url = sprintf("%s/%d/columns/%s/date.json", parent::apiEndpoint(), $this->board_id, $this->column_id);
        $postParams = array(
            "pulse_id" => $this->pulse_id,
            "date_str" => date_format($dateTime, "Y-m-d")
        );

        self::sendPut($url, $postParams);

        $this->column_value = $dateTime;
    }
}

Fix "400: text is missing" when updating a date


<?php

namespace App\Service;

use App\Model\SongRecord;

class SoundcloudApiService extends AbstractApiService
{

    public function getSongRecords(array $filters): array
    {
        $data = [];
        foreach($this->licenses as $license) {
            $uri = '?client_id=' . $this->apiKey .
                '&limit=' . $this->limit .
                '&license=cc-' . $license .
                '&tags=' . $filters['tag'];
            $results = array_values((array)$this->apiClient->performRequest($this->baseUri, $uri));
            $data = array_merge($data, $results);
        }

        $songRecords = [];
        foreach($data as $song) {
            $songRecords[] = new SongRecord(
                $song['user']['username'],
                $song['title'],
                date('i.s', $song['duration']/1000),
                new \DateTime($song['created_at']),
                $song['permalink_url'],
                $song['license'],
                'soundcloud'
            );
        }

        return $songRecords;
    }
}

<?php

namespace App\Service;

use App\Model\SongRecord;

class SoundcloudApiService extends AbstractApiService
{

    public function getSongRecords(array $filters): array
    {
        $data = [];
        foreach($this->licenses as $license) {

            // because of this:
            // https://stackoverflow.com/questions/34978178/soundcloud-tracks-api-with-license-cc-by-nc-returning-400-bad-request
            if ($license === 'by-nc') break;

            $uri = '?client_id=' . $this->apiKey .
                '&limit=' . $this->limit .
                '&license=cc-' . $license .
                '&tags=' . $filters['tag'];
            $results = array_values((array)$this->apiClient->performRequest($this->baseUri, $uri));
            $data = array_merge($data, $results);
        }

        $songRecords = [];
        foreach($data as $song) {
            $songRecords[] = new SongRecord(
                $song['user']['username'],
                $song['title'],
                date('i.s', $song['duration']/1000),
                new \DateTime($song['created_at']),
                $song['permalink_url'],
                $song['license'],
                'soundcloud'
            );
        }

        return $songRecords;
    }
}

Fix problem with Soundcloud API bug

Fix problem with Soundcloud API bug


<?php

/**
 * @mixin PHPUnit_Framework_TestCase
 */
class DatabaseCheckTest extends SapphireTest {
	public function testCheckReportsValidConnection() {
		$check = new DatabaseCheck();

		$expected = array(
			EnvironmentCheck::OK,
			'',
		);

		$this->assertEquals($expected, $check->check());
	}
}

<?php

/**
 * @mixin PHPUnit_Framework_TestCase
 */
class DatabaseCheckTest extends SapphireTest {
    protected $usesDatabase = true;

	public function testCheckReportsValidConnection() {
		$check = new DatabaseCheck();

		$expected = array(
			EnvironmentCheck::OK,
			'',
		);

		$this->assertEquals($expected, $check->check());
	}
}

Use test database in database check test


<?php

// This file needs to parse without error in PHP < 5.3

if ( 'cli' !== PHP_SAPI ) {
	echo "Only CLI access.\n";
	die( -1 );
}

if ( version_compare( PHP_VERSION, '5.3.0', '<' ) ) {
	printf( "Error: WP-CLI requires PHP %s or newer. You are running version %s.\n", '5.3.0', PHP_VERSION );
	die( -1 );
}

define( 'WP_CLI_ROOT', dirname( __DIR__ ) );

require_once WP_CLI_ROOT . '/php/wp-cli.php';

<?php

// This file needs to parse without error in PHP < 5.3

if ( 'cli' !== PHP_SAPI ) {
	echo "Only CLI access.\n";
	die( -1 );
}

if ( version_compare( PHP_VERSION, '5.4.0', '<' ) ) {
	printf( "Error: WP-CLI requires PHP %s or newer. You are running version %s.\n", '5.4.0', PHP_VERSION );
	die( -1 );
}

define( 'WP_CLI_ROOT', dirname( __DIR__ ) );

require_once WP_CLI_ROOT . '/php/wp-cli.php';

Bump PHP version check in bootstrap code to v5.4+

fixes https://github.com/wp-cli/wp-cli/issues/5037


<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;

$versions = GitVersionCollection::create(dirname(__FILE__) . '/src')
	->addFromTags('0.*')
	->add('master', 'master branch')
;

return new Sami(dirname(__FILE__) . '/src', array(	'title' => 'Notificare API',
													'build_dir' => dirname(__FILE__) . '/../notificare-api-docs/%version%',
													'cache_dir' => sys_get_temp_dir() . '/sami-notificare-cache/%version%',
													'versions' => $versions));

<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;

$versions = GitVersionCollection::create(dirname(__FILE__) . '/src')
	->addFromTags('0.*')
	->add('master', 'master branch')
;

return new Sami(dirname(__FILE__) . '/src', array(	'title' => 'Notificare API',
													'build_dir' => dirname(__FILE__) . '/../notificare-apidoc/%version%',
													'cache_dir' => dirname(__FILE__) . '/../notificare-apidoc/cache/%version%',
													'versions' => $versions));

Fix in sami output path

Fix in sami output path


<?php

namespace PHPPHP\Engine;

abstract class OpLine {
    public $op1;
    public $op2;
    public $result;
    public $attributes;

    public function __construct(\PHPParser_Node $node, $op1 = null, $op2 = null, $result = null) {
        $this->op1    = $op1;
        $this->op2    = $op2;
        $this->result = $result;
        $this->attributes   = $node->getAttributes();
    }

    abstract public function execute(\PHPPHP\Engine\ExecuteData $data);
}

<?php

namespace PHPPHP\Engine;

abstract class OpLine {
    public $op1;
    public $op2;
    public $result;
    public $attributes = array();

    public function __construct(\PHPParser_Node $node, $op1 = null, $op2 = null, $result = null) {
        $this->op1    = $op1;
        $this->op2    = $op2;
        $this->result = $result;
        $this->attributes['startLine']   = $node->getLine();
    }

    abstract public function execute(\PHPPHP\Engine\ExecuteData $data);
}

Clean up copying of attributes at @nikic's request


<?php

if (isset($_REQUEST['retryURL'])) {
	$retryURL = (string)$_REQUEST['retryURL'];
	$retryURL = \SimpleSAML\Utils\HTTP::normalizeURL($retryURL);
} else {
	$retryURL = NULL;
}

$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'core:no_cookie.tpl.php');
$t->data['retryURL'] = $retryURL;
$t->show();

<?php

if (isset($_REQUEST['retryURL'])) {
	$retryURL = (string)$_REQUEST['retryURL'];
	$retryURL = \SimpleSAML\Utils\HTTP::checkURLAllowed($retryURL);
} else {
	$retryURL = NULL;
}

$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'core:no_cookie.tpl.php');
$t->data['retryURL'] = $retryURL;
$t->show();

Verify that the URL passed as a parameter in the no cookie error page is allowed. Reported by John Page (hyp3rlinx).


<?php

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

class First extends Application
{

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

	/**
	 * The default page for the current first quote.
	 */
	public function index()
	{
		// build the list of author we want to pass on to our view
		$firstAuthor = $this->quotes->get(1);
		$this->data['who'] = $firstAuthor['who'];
		$this->data['mug'] = $firstAuthor['mug'];
		$this->data['what'] = $firstAuthor['what'];

		// this is the view we want shown
		$this->data['pagebody'] = 'justone';
		$this->render();
	}

}

<?php

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

class First extends Application
{

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

	/**
	 * The default page for the current first quote.
	 */
	public function index()
	{
		// build the author we want to pass on to our view
		$firstAuthor = $this->quotes->get(1);
		$this->data['who'] = $firstAuthor['who'];
		$this->data['mug'] = $firstAuthor['mug'];
		$this->data['what'] = $firstAuthor['what'];

		// this is the view we want shown
		$this->data['pagebody'] = 'justone';
		$this->render();
    }

    /*
     * Function displays the Bob Monkouse quote.
     */
    public function zzz() {
		// build the author we want to pass on to our view
		$bob = $this->quotes->get(1);
		$this->data['who'] = $bob['who'];
		$this->data['mug'] = $bob['mug'];
		$this->data['what'] = $bob['what'];

		// this is the view we want shown
		$this->data['pagebody'] = 'justone';
		$this->render();
    }
}

Fix comments and add the zzz() function to display Bob's quote.


<?php
    if (!defined('UPGRADING') or !UPGRADING)
        exit;

    /**
     * Function: read_more_add_config
     * Adds config settings into an array.
     *
     * Versions: 2022.01 => 2022.02
     */
    function read_more_add_config(): void {
        $set = Config::current()->set("module_read_more",
                                      array("apply_to_feeds" => false, "default_text" => ""),
                                      true);

        if ($set === false)
            error(__("Error"), __("Could not write the configuration file."));
    }

    read_more_add_config();

<?php
    if (!defined('UPGRADING') or !UPGRADING)
        exit;

    /**
     * Function: read_more_add_config
     * Adds config settings into an array.
     *
     * Versions: 2022.02 => 2022.03
     */
    function read_more_add_config(): void {
        $set = Config::current()->set("module_read_more",
                                      array("apply_to_feeds" => false, "default_text" => ""),
                                      true);

        if ($set === false)
            error(__("Error"), __("Could not write the configuration file."));
    }

    read_more_add_config();

Read More module: fixed upgrader versioning


<?php

namespace GeniusTS\Preferences\Models;

use Illuminate\Contracts\View\View;

/**
 * Class Element
 *
 * @package GeniusTS\Preferences
 * @property string $name
 * @property string $namespace
 * @property string $rules
 * @property View   $view
 */
class Element
{

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

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

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

    /**
     * Element constructor.
     *
     * @param string $name
     * @param string $rules
     */
    public function __construct($name, $rules = '')
    {
        $this->name = $name;

        if (is_array($rules))
        {
            $this->rules = $rules;
        }
        else
        {
            $this->rules = [$name => $rules];
        }
    }

    /**
     * Set the name space of element
     *
     * @param string $namespace
     *
     * @return $this
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;

        return $this;
    }

    /**
     * @param string $property
     *
     * @return null
     */
    public function __get($property)
    {
        if (property_exists($this, $property))
        {
            return $this->{$property};
        }

        return null;
    }
}

<?php

namespace GeniusTS\Preferences\Models;

use Illuminate\Support\Collection;
use Illuminate\Contracts\View\View;

/**
 * Class Element
 *
 * @package GeniusTS\Preferences
 * @property string $name
 * @property string $namespace
 * @property string $rules
 * @property View   $view
 */
class Element
{

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

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

    /**
     * @var \Illuminate\Support\Collection
     */
    protected $rules;

    /**
     * Element constructor.
     *
     * @param string       $name
     * @param array|string $rules
     */
    public function __construct($name, $rules = '')
    {
        $this->name = $name;
        $this->rules = new Collection(is_array($rules) ? $rules : [$name => $rules]);
    }

    /**
     * Set the name space of element
     *
     * @param string $namespace
     *
     * @return $this
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;

        return $this;
    }

    /**
     * @param string $property
     *
     * @return null
     */
    public function __get($property)
    {
        if (property_exists($this, $property))
        {
            return $this->{$property};
        }

        return null;
    }
}

Update rules property to ba a collection instead of array


<?php

class AddMailTest extends PHPUnit_Extensions_Selenium2TestCase
{
    protected function setUp()
    {
        $this->setHost('127.0.0.1');
        $this->setBrowser('firefox');
        $this->setBrowserUrl('http://mail-sender.dev');
    }

    public function setUpPage()
    {
        $this->url('/mail_sender.php?page=add_mail');

        $passwordField = $this->byId('pass');
        $passwordField->value('admin');

        $this->byId('OK')->click();
    }

    /**
     * @test
     */
    public function addMail()
    {
        $this->url('/mail_sender.php?page=add_mail');

        $button = $this->byName('add_mail');

        $button->click();

        $this->assertContains('Niepoprawne mail!', $this->source());
    }
}

<?php

class AddMailTest extends PHPUnit_Extensions_Selenium2TestCase
{
    protected function setUp()
    {
        $this->setHost('127.0.0.1');
        $this->setBrowser('firefox');
        $this->setBrowserUrl('http://mail-sender.dev');
    }

    public function setUpPage()
    {
        $this->url('/mail_sender.php?page=add_mail');

        $passwordField = $this->byId('pass');
        $passwordField->value('admin');

        $this->byId('OK')->click();
    }

    /**
     * @dataProvider emailProvider
     */
    public function testAddMail($mail, $expectedMessage)
    {
        $this->url('/mail_sender.php?page=add_mail');

        $emailField = $this->byName('n_mail');
        $emailField->value($mail);

        $button = $this->byName('add_mail');

        $button->click();

        $this->assertContains($expectedMessage, $this->source());
    }

    public function emailProvider()
    {
        return array(
            array('', 'Niepoprawne mail!'),
            array('some@', 'Niepoprawne mail!'),
            array('some@email', 'Niepoprawne mail!'),
            array('some@email.com', 'Maila dodano do bazy!'),
            array('some@email.com', 'Zapytanie ofertowe wysłano ponownie!'),
        );
    }
}

Add test for add single email function

Add test for add single email function


<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

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

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string
     */
    protected $someString;
}

<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

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

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string|null
     */
    protected $someString;
}

BUGFIX: Handle nullable property annotations correctly


<?php
namespace Spark;

use Spark\Adr\PayloadInterface;

class Payload implements PayloadInterface
{
    /**
     * @var integer
     */
    private $status;

    /**
     * @var array
     */
    private $output;

    /**
     * @var array
     */
    private $messages;

    public function withStatus($code)
    {
        $new = clone $this;
        $new->status = $code;
        return $new;
    }

    public function getStatus()
    {
        return $this->status;
    }

    public function withOutput(array $output)
    {
        $new = clone $this;
        $new->output = $output;
        return $new;
    }

    public function getOutput()
    {
        return $this->output;
    }

    public function withMessages(array $messages)
    {
        $new = clone $this;
        $new->messages = $messages;
        return $new;
    }

    public function getMessages()
    {
        return $this->messages;
    }
}

<?php
namespace Spark;

use Spark\Adr\PayloadInterface;

class Payload implements PayloadInterface
{
    /**
     * @var integer
     */
    private $status;

    /**
     * @var array
     */
    private $input;

    /**
     * @var array
     */
    private $output;

    /**
     * @var array
     */
    private $messages;

    public function withStatus($code)
    {
        $new = clone $this;
        $new->status = $code;
        return $new;
    }

    public function getStatus()
    {
        return $this->status;
    }

    public function withInput(array $input)
    {
        $new = clone $this;
        $new->input = $input;
        return $new;
    }

    public function getInput()
    {
        return $this->input;
    }

    public function withOutput(array $output)
    {
        $new = clone $this;
        $new->output = $output;
        return $new;
    }

    public function getOutput()
    {
        return $this->output;
    }

    public function withMessages(array $messages)
    {
        $new = clone $this;
        $new->messages = $messages;
        return $new;
    }

    public function getMessages()
    {
        return $this->messages;
    }
}

Add input controls to payload

Add input controls to payload

It is very helpful for invalid state to notify the user of the input that was not correct.


<?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */

?>

Links Index

<?= ListView::widget([
    'dataProvider' => $data,
    'itemView' => '_linkItem',
    'options' => ['class' => 'striped'],
]); ?>

<?php if (!Yii::$app->user->isGuest) : ?>
<?= Html::a('Add New', ['new'], ['class' => 'btn btn-default btn-success']); ?>
<?php endif; ?>

<?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */

?>

Shared Links:

<?php if (!Yii::$app->user->isGuest) : ?>
    <?= Html::a('Add New', ['new'], ['class' => 'btn btn-default btn-success']); ?>
<?php endif; ?>
<?= ListView::widget([
    'dataProvider' => $data,
    'itemView' => '_linkItem',
    'options' => ['class' => 'striped'],
]); ?>

Move "Add Link" button to top of page

Move "Add Link" button to top of page

It will be annoying at the bottom when there are a lot of links.
This closes #10


<?php

use Phinx\Migration\AbstractMigration;

class AddSpriteHashToAppearances extends AbstractMigration {
	public function up() {
		$this->table('appearances')
			->addColumn('sprite_hash', 'string', ['length' => 32, 'null' => true])
			->update();

		foreach (new DirectoryIterator(SPRITE_PATH) as $file_info){
			echo "$file_info\n";
			if ($file_info->isDot()) continue;

			$filename = $file_info->getFilename();
			$appearance_id = explode('.', $filename)[0];
			$hash = md5_file($file_info->getPathname());
			echo "$appearance_id:$hash\n";
			if ($hash !== false) {
				$this->query("UPDATE appearances SET sprite_hash = '$hash' WHERE id = $appearance_id");
			}
		}
	}

	public function down() {
		$this->table('appearances')
			->removeColumn('sprite_hash')
			->update();
	}
}

<?php

use Phinx\Migration\AbstractMigration;

class AddSpriteHashToAppearances extends AbstractMigration {
	public function up() {
		$this->table('appearances')
			->addColumn('sprite_hash', 'string', ['length' => 32, 'null' => true])
			->update();

		foreach (new DirectoryIterator(SPRITE_PATH) as $file_info){
			if ($file_info->isDot()) continue;

			$filename = $file_info->getFilename();
			$appearance_id = explode('.', $filename)[0];
			$hash = md5_file($file_info->getPathname());
			if ($hash !== false) {
				$this->query("UPDATE appearances SET sprite_hash = '$hash' WHERE id = $appearance_id");
			}
		}
	}

	public function down() {
		$this->table('appearances')
			->removeColumn('sprite_hash')
			->update();
	}
}

Remove debug code from migration

Remove debug code from migration


<?php
/**
 * Will hold data from the Kaltura Player components to be passed on to the live analytics system
 * @package api
 * @subpackage objects
 */
class KalturaLiveStatsEvent extends KalturaObject
{

	/**
	 * @var int
	 */
	public $partnerId;

	/**
	 * @var string
	 */
	public $entryId;

    /**
     * an integer representing the type of event being sent from the player
     * @var KalturaLiveStatsEventType
     */
    public $eventType;

	/**
	 * a unique string generated by the client that will represent the client-side session: the primary component will pass it on to other components that sprout from it
	 * @var string
	 */
	public $sessionId;

	/**
	 * incremental sequence of the event
	 * @var int
	 */
	public $eventIndex;

	/**
	 * buffer time in seconds from the last 10 seconds
	 * @var int
	 */
	public $bufferTime;

	/**
	 * bitrate used in the last 10 seconds
	 * @var int
	 */
	public $bitrate;

	/**
	 * the referrer of the client
	 * @var string
	 */
	public $referrer;

	/**
	 * @var bool
	 */
	public $isLive;

	/**
	 * delivery type used for this stream
	 * @var KalturaPlaybackProtocol
	 */
	public $deliveryType;

}

Fix indenation to project's default

Fix indenation to project's default


<?php include "../com/panel.php"; ?>

    برنامه هفتگی
    خروج

Fix schedule link in nav

Fix schedule link in nav


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

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->boolean('is_sticky')->default(0);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->dropColumn('is_sticky');
        });
    }
];

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

use Flarum\Database\Migration;

return Migration::addColumns('discussions', [
    'is_sticky' => ['boolean', 'default' => 0]
]);

Use new shortcuts for migrations

Use new shortcuts for migrations


<?php
require __DIR__ . "/../vendor/autoload.php";

error_reporting(~E_ALL);

$manager = new PhpProbe\Manager();
$manager->importConfig('config.yml');
$manager->checkAll();

if (php_sapi_name() == 'cli') {
    $manager
        ->outputText(true)
        ->end();
} else {
    $manager
        ->outputHtml(true)
        ->end();
}

<?php
require __DIR__ . "/../vendor/autoload.php";

error_reporting(~E_ALL);

$manager = new PhpProbe\Manager();
$manager->importConfig(__DIR__ . '/config.yml');
$manager->checkAll();

if (php_sapi_name() == 'cli') {
    $manager
        ->outputText(true)
        ->end();
} else {
    $manager
        ->outputHtml(true)
        ->end();
}

Load config file from examples directory


@extends('layout')

@section('title', $category->name)

@section('content')

  @forelse($category->candidates as $candidate)
    @include('candidates.tile', ['candidate' => $candidate, 'drawer' => true])
  @empty

No candidates in this category... yet!

  @endforelse

@stop

@section('actions')

{{ link_to_route('categories.edit', 'Edit Category', [$category->slug], ['class' => 'btn secondary']) }}

@stop

@extends('layout')

@section('title', $category->name)

@section('content')

  @if($category->candidates)
    @foreach($category->candidates as $candidate)
      @include('candidates.tile', ['candidate' => $candidate, 'drawer' => true])
    @endforeach
  @else

No candidates in this category... yet!

  @endif

@stop

@section('actions')

{{ link_to_route('categories.edit', 'Edit Category', [$category->slug], ['class' => 'btn secondary']) }}

@stop

Fix forelse's candidate variable being pushed into template.


<?php

/**
 * This script fetch data from IMDb for all movies currently in our database and save it.
 * It will overwrite existing data (update).
 */

require_once('../public/index.php');

$movies = Default_Model_MovieMapper::fetchAll();
foreach ($movies as $movie)
{
	echo $movie->getImdbUrl(). "\t";
	$movie->title = null;
	$title = $movie->getTitle();
	echo $title . "\n";
}

echo count($movies) . " movies updated in database\n";

<?php

/**
 * This script fetch data from IMDb for all movies currently in our database and save it.
 * It will overwrite existing data (update).
 */

require_once(dirname(__FILE__) . '/../public/index.php');

$movies = Default_Model_MovieMapper::fetchAll();
$count = 0;
$total = $movies->count();
foreach ($movies as $movie)
{

	echo '[' . str_pad(++$count, 5, ' ', STR_PAD_LEFT) . '/' . str_pad($total, 5, ' ', STR_PAD_LEFT) . "]\t" . $movie->getImdbUrl(). "\t";
	$movie->title = null;
	$title = $movie->getTitle();
	echo $title . "\n";
}

echo count($movies) . " movies updated in database\n";

ADD counting movies during update

ADD counting movies during update


<?php

return [
    'providers' => [
        #\App\Http\Terranet\Administrator\Navigation\Providers\PagesProvider::class,
        \App\Http\Terranet\Administrator\Navigation\Providers\RoutesProvider::class,
        \App\Http\Terranet\Administrator\Navigation\Providers\LinksProvider::class,
    ],

    'paths' => [
        'provider' => "Http/Terranet/Administrator/Navigation/Providers"
    ]
];

<?php

return [
    'providers' => [
        #\App\Http\Terranet\Administrator\Navigation\Providers\PagesProvider::class,
        \App\Http\Terranet\Administrator\Navigation\Providers\RoutesProvider::class,
        \App\Http\Terranet\Administrator\Navigation\Providers\LinksProvider::class,
    ],

    'paths' => [
        'provider' => "Http/Terranet/Administrator/Navigation/Providers"
    ],

    # Routes under these prefixes will be skipped from navigation module.
    'skip' => [
        'cms', 'horizon', 'api', 'auth'
    ],
];

Add a set of prefixes for routes skipping


<?php

/*
 * This file is part of the Foxy package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Foxy\Util;

use Foxy\Exception\RuntimeException;

/**
 * Helper for Composer.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class ComposerUtil
{
    /**
     * Validate the composer version.
     *
     * @param string $requiredVersion The composer required version
     * @param string $composerVersion The composer version
     */
    public static function validateVersion($requiredVersion, $composerVersion)
    {
        if (false === strpos($composerVersion, '@') && !version_compare($composerVersion, $requiredVersion, '>=')) {
            $msg = 'Foxy requires the Composer\'s minimum version "%s", current version is "%s"';

            throw new RuntimeException(sprintf($msg, $composerVersion, $requiredVersion));
        }
    }
}

<?php

/*
 * This file is part of the Foxy package.
 *
 * (c) François Pluchino <francois.pluchino@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Foxy\Util;

use Foxy\Exception\RuntimeException;

/**
 * Helper for Composer.
 *
 * @author François Pluchino <francois.pluchino@gmail.com>
 */
class ComposerUtil
{
    /**
     * Validate the composer version.
     *
     * @param string $requiredVersion The composer required version
     * @param string $composerVersion The composer version
     */
    public static function validateVersion($requiredVersion, $composerVersion)
    {
        if (false === strpos($composerVersion, '@') && !version_compare($composerVersion, $requiredVersion, '>=')) {
            $msg = 'Foxy requires the Composer\'s minimum version "%s", current version is "%s"';

            throw new RuntimeException(sprintf($msg, $requiredVersion, $composerVersion));
        }
    }
}

Fix error message of composer version

Fix error message of composer version


<?php

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

namespace Symfony\Component\Filesystem\Exception;

/**
 * Exception class thrown when a filesystem operation failure happens.
 *
 * @author Romain Neutron <imprec@gmail.com>
 * @author Christian Gärtner <christiangaertner.film@googlemail.com>
 * @author Fabien Potencier <fabien@symfony.com>
 */
class IOException extends \RuntimeException implements IOExceptionInterface
{
    private $path;

    public function __construct(string $message, int $code = 0, \Throwable $previous = null, string $path = null)
    {
        $this->path = $path;

        parent::__construct($message, $code, $previous);
    }

    /**
     * {@inheritdoc}
     */
    public function getPath()
    {
        return $this->path;
    }
}

<?php

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

namespace Symfony\Component\Filesystem\Exception;

/**
 * Exception class thrown when a filesystem operation failure happens.
 *
 * @author Romain Neutron <imprec@gmail.com>
 * @author Christian Gärtner <christiangaertner.film@googlemail.com>
 * @author Fabien Potencier <fabien@symfony.com>
 */
class IOException extends \RuntimeException implements IOExceptionInterface
{
    private ?string $path;

    public function __construct(string $message, int $code = 0, \Throwable $previous = null, string $path = null)
    {
        $this->path = $path;

        parent::__construct($message, $code, $previous);
    }

    /**
     * {@inheritdoc}
     */
    public function getPath()
    {
        return $this->path;
    }
}

Add types to private properties

[Filesystem] Add types to private properties

Signed-off-by: Alexander M. Turek <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@derrabus.de>


<?php

if (file_exists(__DIR__ . '../vendor/autoload.php')) {
    require_once __DIR__ . '../vendor/autoload.php';
}

if (isset($_GET['flush']) && $_GET['flush']) {
    define('CACHEINCLUDE_FORCE_EXPIRE', true);
}

<?php

if (isset($_GET['flush']) && $_GET['flush']) {
    define('CACHEINCLUDE_FORCE_EXPIRE', true);
}

MINOR: Remove inclusion of autoloader because silverstripe already includes it


<?php

namespace ModuleGenerator\Domain\Entity;

use ModuleGenerator\CLI\Service\Generate\GeneratableClass;
use ModuleGenerator\PhpGenerator\ClassName\ClassName;

final class Entity extends GeneratableClass
{
    /** @var ClassName */
    private $className;

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

    public function getClassName(): ClassName
    {
        return $this->className;
    }

    public function getTableName(): string
    {
        return $this->tableName;
    }

    public static function fromDataTransferObject(EntityDataTransferObject $entityDataTransferObject): self
    {
        return new self(
            ClassName::fromDataTransferObject($entityDataTransferObject->className),
            $entityDataTransferObject->tableName
        );
    }
}

<?php

namespace ModuleGenerator\Domain\Entity;

use ModuleGenerator\CLI\Service\Generate\GeneratableClass;
use ModuleGenerator\PhpGenerator\ClassName\ClassName;

final class Entity extends GeneratableClass
{
    /** @var ClassName */
    private $className;

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

    /**
     * @param ClassName $className
     * @param string $tableName
     */
    public function __construct(ClassName $className, string $tableName)
    {
        $this->className = $className;
        $this->tableName = $tableName;
    }

    public function getClassName(): ClassName
    {
        return $this->className;
    }

    public function getTableName(): string
    {
        return $this->tableName;
    }

    public static function fromDataTransferObject(EntityDataTransferObject $entityDataTransferObject): self
    {
        return new self(
            ClassName::fromDataTransferObject($entityDataTransferObject->className),
            $entityDataTransferObject->tableName
        );
    }
}

Add missing constructor for the entity class


<?php
/**
 *Class for processing framework with HTML standards.
 *
 *@package Html
 *@author  Vinicius Pinheiro <viny-pinheiro@hotmail.com>
 *@license MIT License
 *@link    http://eletronjun.com.br/class/html/communityMenu.php
 */
namespace html{

    include_once __DIR__ . "/../autoload.php";

    use \utilities\Session as Session;
    use \html\Page as Page;
    use \html\Menu as Menu;
    use \configuration\Globals as Globals;
    use \dao\CategoryDao as CategoryDao;

    class CommunityMenu extends Menu
    {

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

        public function construct()
        {
            parent::addItem(PROJECT_ROOT ."/enterprise.php", "A Empresa");
            parent::addItem(PROJECT_ROOT ."/projects.php", "Projetos");
            parent::addItem(PROJECT_ROOT ."/events.php", "Eventos");
            parent::addItem(PROJECT_ROOT ."/selective_process.php", "Processos Seletivos");
            $this->publicationOptions();
            parent::endMenu();
        }

        private function publicationOptions()
        {
            parent::startDropdown("Publicações");
            foreach (CategoryDao::returnActiveCategories() as $code => $name) {
                parent::addItem(PROJECT_ROOT . "categories.php?code={$code}", $name);
            }
            parent::endDropdown();
        }
    }
}

<?php
/**
 *Class for processing framework with HTML standards.
 *
 *@package Html
 *@author  Vinicius Pinheiro <viny-pinheiro@hotmail.com>
 *@license MIT License
 *@link    http://eletronjun.com.br/class/html/communityMenu.php
 */
namespace html{

    include_once __DIR__ . "/../autoload.php";

    use \utilities\Session as Session;
    use \html\Page as Page;
    use \html\Menu as Menu;
    use \configuration\Globals as Globals;
    use \dao\CategoryDao as CategoryDao;

    class CommunityMenu extends Menu
    {

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

        public function construct()
        {
            parent::addItem(PROJECT_ROOT ."/enterprise.php", "A Empresa");
            parent::addItem(PROJECT_ROOT ."/projects.php", "Projetos");
            parent::addItem(PROJECT_ROOT ."/events.php", "Eventos");
            $this->selectiveProcessOptions();
            $this->publicationOptions();
            parent::endMenu();
        }

        private function publicationOptions()
        {
            parent::startDropdown("Publicações");
            foreach (CategoryDao::returnActiveCategories() as $code => $name) {
                parent::addItem(PROJECT_ROOT . "categories.php?code={$code}", $name);
            }
            parent::endDropdown();
        }

        private function selectiveProcessOptions()
        {
            parent::startDropdown("Processos Seletivos");
              parent::addItem(PROJECT_ROOT . "selective_process2015.php", "Processo Seletivo 2015");
              parent::addItem(PROJECT_ROOT . "selective_process2016.php", "Processo Seletivo 2016");
            parent::endDropdown();
        }
    }
}

Change option 'Processos Seletivos' to dropdown item


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

namespace WellCommerce\Bundle\NewsBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;

/**
 * Class NewsManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class NewsManagerTest extends AbstractManagerTestCase
{
    protected function get()
    {
        return $this->container->get('news.manager');
    }
}

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

namespace WellCommerce\Bundle\NewsBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;
use WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface;

/**
 * Class NewsManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class NewsManagerTest extends AbstractManagerTestCase
{
    protected function get() : ManagerInterface
    {
        return $this->container->get('news.manager');
    }
}

Return types in manager tests

Return types in manager tests


<?php

namespace Kibo\Phast\Cache\File;

use Kibo\Phast\Common\ObjectifiedFunctions;

class DiskCleanup extends ProbabilisticExecutor {

    /**
     * @var integer
     */
    private $maxSize;

    /**
     * @var float
     */
    private $portionToFree;

    public function __construct(array $config, ObjectifiedFunctions $functions = null) {
        $this->maxSize = $config['diskCleanup']['maxSize'];
        $this->probability = $config['diskCleanup']['probability'];
        $this->portionToFree = $config['diskCleanup']['portionToFree'];
        parent::__construct($config, $functions);
    }

    protected function execute() {
        list ($usedSpace, $files) = $this->calculateUsedSpace();
        $neededSpace = round($this->portionToFree * $this->maxSize);
        $bytesToDelete = $usedSpace - $this->maxSize + $neededSpace;
        $deletedBytes = 0;
        /** @var \SplFileInfo $file */
        foreach ($files as $file) {
            if ($deletedBytes >= $bytesToDelete) {
                break;
            }
            $deletedBytes += $file->getSize();
            @unlink($file->getRealPath());
        }
    }

    private function calculateUsedSpace() {
        $size = 0;
        $files = [];
        /** @var \SplFileInfo $file */
        foreach ($this->getCacheFiles($this->cacheRoot) as $file) {
            $size += $file->getSize();
            $files[] = $file;
        }
        return [$size, $files];
    }

}

<?php

namespace Kibo\Phast\Cache\File;

use Kibo\Phast\Common\ObjectifiedFunctions;

class DiskCleanup extends ProbabilisticExecutor {

    /**
     * @var integer
     */
    private $maxSize;

    /**
     * @var float
     */
    private $portionToFree;

    public function __construct(array $config, ObjectifiedFunctions $functions = null) {
        $this->maxSize = $config['diskCleanup']['maxSize'];
        $this->probability = $config['diskCleanup']['probability'];
        $this->portionToFree = $config['diskCleanup']['portionToFree'];
        parent::__construct($config, $functions);
    }

    protected function execute() {
        $usedSpace= $this->calculateUsedSpace();
        $neededSpace = round($this->portionToFree * $this->maxSize);
        $bytesToDelete = $usedSpace - $this->maxSize + $neededSpace;
        $deletedBytes = 0;
        /** @var \SplFileInfo $file */
        foreach ($this->getCacheFiles($this->cacheRoot) as $file) {
            if ($deletedBytes >= $bytesToDelete) {
                break;
            }
            $deletedBytes += $file->getSize();
            @unlink($file->getRealPath());
        }
    }

    private function calculateUsedSpace() {
        $size = 0;
        $files = [];
        /** @var \SplFileInfo $file */
        foreach ($this->getCacheFiles($this->cacheRoot) as $file) {
            $size += $file->getSize();
            $files[] = $file;
        }
        return $size;
    }

}

Read the files again upon deletion

Read the files again upon deletion


<?php namespace Modules\Block\Composers;

use Illuminate\Contracts\View\View;
use Maatwebsite\Sidebar\SidebarGroup;
use Maatwebsite\Sidebar\SidebarItem;
use Modules\Core\Composers\BaseSidebarViewComposer;

class SidebarViewComposer extends BaseSidebarViewComposer
{
    public function compose(View $view)
    {
        $view->sidebar->group(trans('core::sidebar.content'), function (SidebarGroup $group) {
            $group->addItem(trans('block::blocks.title.blocks'), function (SidebarItem $item) {
                $item->authorize(
                    $this->auth->hasAccess('block.blocks.index')
                );
                $item->icon = 'fa fa-cube';
                $item->weight = 0;
                $item->append('admin.block.block.create');
                $item->route('admin.block.block.index');
                $item->authorize(
                    $this->auth->hasAccess('block.blocks.index')
                );
            });
        });
    }
}

<?php namespace Modules\Block\Composers;

use Illuminate\Contracts\View\View;
use Maatwebsite\Sidebar\SidebarGroup;
use Maatwebsite\Sidebar\SidebarItem;
use Maatwebsite\Sidebar\SidebarManager;
use Modules\Core\Composers\BaseSidebarViewComposer;

class SidebarViewComposer extends BaseSidebarViewComposer
{
    public function compose(View $view)
    {
        if (! $view->sidebar instanceof SidebarManager) {
            return;
        }

        $view->sidebar->group(trans('core::sidebar.content'), function (SidebarGroup $group) {
            $group->addItem(trans('block::blocks.title.blocks'), function (SidebarItem $item) {
                $item->authorize(
                    $this->auth->hasAccess('block.blocks.index')
                );
                $item->icon = 'fa fa-cube';
                $item->weight = 0;
                $item->append('admin.block.block.create');
                $item->route('admin.block.block.index');
                $item->authorize(
                    $this->auth->hasAccess('block.blocks.index')
                );
            });
        });
    }
}

Add an instance of check

Add an instance of check


<?php

namespace PhpWatson\Sdk;

use GuzzleHttp\Client as GuzzleClient;
use PhpWatson\Sdk\Interfaces\ClientInterface;

class Client implements ClientInterface{
    /**
     * @var \GuzzleHttp\Client
     */
    private $guzzle;

    public function __construct()
    {
        $this->guzzle = new GuzzleClient();
    }

    /**
     * {@inheritdoc}
     */
    public function request($method, $uri, $options = [])
    {
        return $this->guzzle->request($method, $uri, $options);
    }

    /**
     * {@inheritdoc}
     */
    public function setGuzzleInstance(GuzzleClient $guzzle)
    {
        $this->guzzle = $guzzle;
    }
}

<?php

namespace PhpWatson\Sdk;

use GuzzleHttp\Client as GuzzleClient;
use PhpWatson\Sdk\Interfaces\ClientInterface;

class Client implements ClientInterface
{
    /**
     * The client request options
     *
     * @var array
     */
    private $options = [
        'exceptions' => false,
        'headers' => [
            'Accept' => 'application/json'
        ]
    ];

    /**
     * The Guzzle instance
     *
     * @var \GuzzleHttp\Client
     */
    private $guzzle;

    public function __construct($username, $password)
    {
        $this->setOptions(['auth' => [$username, $password]]);
        $this->setGuzzleInstance(new GuzzleClient());
    }

    /**
     * {@inheritdoc}
     */
    public function request($method, $uri, $options = [])
    {
        return $this->guzzle->request($method, $uri, array_merge($this->getOptions(), $options));
    }

    /**
     * {@inheritdoc}
     */
    public function setGuzzleInstance(GuzzleClient $guzzle)
    {
        $this->guzzle = $guzzle;
    }

    /**
     * {@inheritdoc}
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * {@inheritdoc}
     */
    public function setOptions(array $options)
    {
        $this->options = array_merge($this->getOptions(), $options);
    }
}

Add options property for request Receive credentials on constructor Push credentials as auth basic


<?php
namespace Gothick\AkismetClient;

class ClientResult
{
    const PRO_TIP_HEADER = 'X-akismet-pro-tip';
    private $raw_result;
    private $pro_tip;

    public function __construct(\GuzzleHttp\Psr7\Response $response)
    {
        if ($response->getStatusCode() != 200)
        {
            // Our clients are meant to check first
            throw new Exception('Response with invalid status code in ' . __METHOD__);
        }
        $this->raw_result = (string) $response->getBody();
        if ($response->hasHeader(self::PRO_TIP_HEADER))
        {
            $this->pro_tip = $response->getHeader(self::PRO_TIP_HEADER);
        }
    }

    public function isSpam() {
        return $this->raw_result == 'true';
    }
    public function isBlatantSpam() {
        return (isSpam() && $this->pro_tip == 'disacrd');
    }
}

<?php
namespace Gothick\AkismetClient;

class ClientResult
{

	const PRO_TIP_HEADER = 'X-akismet-pro-tip';

	/**
	 * Raw string we got back from the Akismet API as an answer
	 * @var string
	 */
	protected $raw_result;

	/**
	 * Akismet's X-akismet-pro-tip header, which sometimes has
	 * useful extra information.
	 * @var unknown
	 */
	protected $pro_tip;

	public function __construct (\GuzzleHttp\Psr7\Response $response)
	{
		if ($response->getStatusCode() != 200)
		{
			// Our clients are meant to check first
			throw new Exception(
					'Response with invalid status code in ' . __METHOD__);
		}
		$this->raw_result = (string) $response->getBody();
		if ($response->hasHeader(self::PRO_TIP_HEADER))
		{
			$this->pro_tip = $response->getHeader(self::PRO_TIP_HEADER);
		}
	}

	public function hasProTip()
	{
		return (!empty($this->pro_tip));
	}
	public function getProTip()
	{
		return $this->pro_tip;
	}
}

Reformat & move comment checking stuff to subclass.


<?php
    require "scripts/pi-hole/php/header.php";
?>

Generate debug log

<button class="btn btn-lg btn-primary btn-block" id="debugBtn">Generate debug log</button>

<?php
    require "scripts/pi-hole/php/footer.php";
?>

<?php
    require "scripts/pi-hole/php/header.php";
?>

Generate debug log

Once you click this button a debug log will be generated and automatically uploaded if we detect a working internet connection

<button class="btn btn-lg btn-primary btn-block" id="debugBtn">Generate debug log</button>

<?php
    require "scripts/pi-hole/php/footer.php";
?>

Add notice that we are going to automatically upload the log once the user clicks on the big button


<?php

Route::post('laralytics', function (Bsharp\Laralytics\Laralytics $laralytics,
                                    Illuminate\Http\Request $request,
                                    Illuminate\Contracts\Cookie\Factory $cookie) {

    $trackerCookie = null;

    // Define payload
    $payload = $request->only('info', 'click', 'custom');

    // Check for tracking cookie if we have info in the payload
    if (!empty($payload['info'])) {
        $trackerCookie = $laralytics->checkCookie($request, $cookie);
    }

    // Insert payload
    $laralytics->payload($request, $payload, !is_null($trackerCookie));

    if (is_null($trackerCookie)) {
        return response()->json($_POST);
    } else {
        return response()->json($_POST)->withCookie($trackerCookie);
    }
});

<?php

Route::post('laralytics', function (Bsharp\Laralytics\Laralytics $laralytics,
                                    Illuminate\Http\Request $request,
                                    Illuminate\Contracts\Cookie\Factory $cookie) {

    $trackerCookie = null;

    // Define payload
    $payload = $request->only('info', 'click', 'custom');

    // Check for tracking cookie if we have info in the payload
    if (!empty($payload['info'])) {
        $trackerCookie = $laralytics->checkCookie($request, $cookie);
    }

    // Insert payload
    $laralytics->payload($request, $payload, !is_null($trackerCookie));

    if (!is_null($trackerCookie)) {
        return response()->json()->withCookie($trackerCookie);
    }
});

Remove json return (for testing purpose)


<?php

namespace Borfast\Socializr;

class Profile
{
    public $provider;
    public $id;
    public $email;
    public $name;
    public $first_name;
    public $middle_name;
    public $last_name;
    public $username;
    public $link;
    public $raw_response;
    public $avatar;

    /**
     * Create a new Profile object based on an array of attributes and a mapping
     * from those attributes to the Profile object's attributes.
     * The $mapping array should have this format:
     * $mapping = [
     *       'id' => 'id',
     *       'email' => 'email',
     *       'name' => 'name',
     *       'first_name' => 'firs_name',
     *       'middle_name' => 'middle_name',
     *       'last_name' => 'last_name',
     *       'username' => 'username',
     *       'link' => 'link'
     *   ];
     * The keys are the name of the Profile object attributes, while the values
     * are the key of that attribute in the $attributes array. Like so:
     * ['profile_object_attribute' => 'key_in_attributes_array']
     *
     * @author Raúl Santos
     */
    public static function create(array $mapping, array $attributes)
    {
        $profile = new Profile;

        foreach ($mapping as $key => $name) {
            $profile->$key = (isset($attributes[$name])) ? $attributes[$name] : null;
        }

        return $profile;
    }
}

<?php

namespace Borfast\Socializr;

class Profile
{
    public $provider;
    public $id;
    public $email;
    public $name;
    public $first_name;
    public $middle_name;
    public $last_name;
    public $username;
    public $link;
    public $raw_response;
    public $avatar;

    /**
     * Create a new Profile object based on an array of attributes and a mapping
     * from those attributes to the Profile object's attributes.
     * The $mapping array should have this format (example for Facebook):
     * $mapping = [
     *       'id' => 'id',
     *       'email' => 'email',
     *       'name' => 'name',
     *       'first_name' => 'first_name',
     *       'middle_name' => 'middle_name',
     *       'last_name' => 'last_name',
     *       'username' => 'username',
     *       'link' => 'link'
     *   ];
     * The keys are the name of the Profile object attributes, while the values
     * are the key of that attribute in the $attributes array. Like so:
     * ['profile_object_attribute' => 'key_in_attributes_array']
     *
     * @author Raúl Santos
     */
    public static function create(array $mapping, array $attributes)
    {
        $profile = new Profile;

        foreach ($mapping as $key => $name) {
            $profile->$key = (isset($attributes[$name])) ? $attributes[$name] : null;
        }

        return $profile;
    }
}

Fix typo in mapping array key.

Fix typo in mapping array key.


<?php

namespace CultuurNet\UDB3\Event\Events;

use CultuurNet\UDB3\Event\EventEvent;
use CultuurNet\UDB3\Offer\ImageRemoveTrait;

/**
 * Provides an ImageDeleted event.
 */
class ImageRemoved extends EventEvent
{
    use ImageRemoveTrait;
}

<?php

namespace CultuurNet\UDB3\Event\Events;

use CultuurNet\UDB3\Event\EventEvent;
use CultuurNet\UDB3\Offer\ImageRemoveTrait;

/**
 * Provides an ImageRemoved event.
 */
class ImageRemoved extends EventEvent
{
    use ImageRemoveTrait;
}

Correct class name in comment

III-611: Correct class name in comment


<form name="loginform" action="<?php echo wp_login_url($_SERVER['REQUEST_URI']);?>" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="E-postadress eller nick"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

</form>

<form name="loginform" action="<?php echo wp_login_url($_SERVER['REQUEST_URI']);?>" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="CID eller e-postadress"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

</form>

Change placeholder text in sign in form

Change placeholder text in sign in form